Click here to Skip to main content
Click here to Skip to main content

Creating a Mechanical Trading System Part 3: Get real time quotes using DDE

By , 10 Mar 2008
 

Sample Image - Realtime_Quotes.jpg

Introduction

This is the third article in the series:
Creating a Mechanical Trading System Part 1: Technical Indicators
Creating a Mechanical Trading System Part 2: Four Percent Trading System
Creating a Mechanical Trading System Part 3: Get real time quotes using DDE

The first article in this series introduced a project to code mechanical trading system robots for the .NET platform using the C# language. The second article introduced how to code a trading system that will watch price action and make buying or selling decisions. This article shows how to obtain real time forex quotes for several currency pairs using the DDE protocol and the Metatrader 4 trading terminal.

It is the aim of this project to write a program that does not depend on any underlying platform to execute, but rather receives price data directly from a broker and places orders via an API.

The code provided here is part of a larger project to create a backtesting platform and an automated FOREX trading robot. Source code for this project is available at http://www.4xlab.net/

Background

DDE (Dynamic Data Exchange) is an interprocess communication system that enables two applications to share the same data. This mechanism is deprecated in favor of other alternatives such as OLE or COM. In financial applications, it is popular and DDE enabled applications are still being built. The interaction between a quote provider and a client is typically limited to receiving real time quotes. DDE is not used to get historical data or enter trades.

For a DDE dialog to occur, two applications must be running, the server, or provider of data, and the client, or consumer. If the server application is not running, the client connection attempts will fail. In this example, the server will be Metatrader Terminal 4.0, and the clients will be Microsoft Excel and the 4X DDE Client.

Connecting to Metatrader 4 using Excel:

The default installation of Metatrader does not enable the DDE server. It must be manually enabled once. To do so, click on Tools -> Options on the Server tab (selected by default), ensure the 'Enable DDE server' option is checked, click OK to save your options.

Once Metatrader is running, connected to a server, and its DDE server has been enabled, launch Excel. To test the connection, type in a cell =MT4|ASK!EURUSD , this command obtains the ASK quote for the EUR USD pair using the MT4 DDE server. The cell content should display the last ask price for the pair and automatically update this value in real time if everything is working properly. If Metatrader is not running, or the DDE server is not enabled, Excel will try to start it using the non existing MT4.exe filename, which will fail and #VALUE! or #REF! will be displayed in cells using live data.

Excel implements a DDE client with a syntax that is extremely easy to use and helps in debugging. To communicate, the client needs to know the DDE Application name, the DDE Topic, and the DDE Item. To make a request, the syntax is as follows: =DDEAppName|DDETopic!DDEItem

To communicate with Metatrader 4, the DDEAppName is MT4, the DDETopic is one of the commands listed below and the DDEItem is the currency pair you are interested in.

MT4 DDE Topics

  • BID

    Item: Currency Pair   Example: =MT4|BID!USDCHF   Sample Output: 1.2472
    Returns the BID or selling price for the pair

  • ASK

    Item: Currency Pair   Example: =MT4|ASK!GBPUSD   Sample Output: 1.8656
    Returns the ASK or buying price for the pair

  • HIGH

    Item: Currency Pair   Example: =MT4|HIGH!EURUSD   Sample Output: 1.2873
    Returns the High price for the pair

  • LOW

    Item: Currency Pair   Example: =MT4|LOW!USDJPY   Sample Output: 115.95
    Returns the Low price for the pair

  • QUOTE

    Item: Currency Pair   Example: =MT4|QUOTE!AUDUSD   Sample Output: 2006/09/08 19:58 0.7540 0.7546
    Returns the Time, BID and ASK prices for the pair

  • TIME

    Item: Does not take an Item   Example: =MT4|TIME   Sample Output: 2006/09/08 19:58
    Returns the server time

The DDE Topic STATUS and DDE Items ACCOUNT, BALANCE and CONNECT have been deprecated and obsoleted in version 4.0 of the client. The queries =MT|STATUS!ACCOUNT =MT|STATUS!BALANCE and =MT|STATUS!CONNECT only work in previous versions of the trading terminal.

Other DDE Enabled Financial Applications

Other financial applications share some of the previous DDE topics. Some of those applications and their App Names are: eSignal (WINROS): Stock Quotes, Thinkorswim (TOS): Stocks and futures broker.

Using the code

The code below shows the minimum number of steps required to setup the NDDE library to receive real time quotes from Metatrader 4. Metatrader responds to the initial request for a value using client.Request(Item, 60000); with N\A and instead only sends the quotes as updates via the Advise mechanism.

This code connects to the MT4 DDE server and the QUOTE topic. It then sets up item update notifications using StartAdvise for the desired currency pairs. The OnAdvise event handler prints the tick received using the Item (pair) and Text (quote) attributes of the DdeAdviseEventArgs object it receives as a parameter.

If an exception is thrown during this process, it means that Metatrader is not started or its DDE server is not enabled. The user is informed to launch Metatrader, or to follow the procedure to enable the DDE server.

File: Form1.cs
//
// 4XDDEClient, a part of the www.4xlab.net Forex Lab Project
//

using NDde.Client;

namespace _4XDDEClient
{

  public partial class Form1 : Form
  {

    ...

    private void StartQuotes()
    {
      try
      {
        if (TheContainer.TheDdeClient == null)
        {
          DdeClient client = new DdeClient("MT4", "QUOTE");
          TheContainer.TheDdeClient = client;

          // Subscribe to the Disconnected event.  
          // This event will notify the application when 
          // a conversation has been terminated.
          client.Disconnected += OnDisconnected;

          // Connect to the server.  
          // It must be running or an exception will be thrown.
          client.Connect();

          // Advise Loop
          client.StartAdvise("USDCHF", 1, true, 60000);
          client.StartAdvise("USDJPY", 1, true, 60000);
          client.StartAdvise("EURUSD", 1, true, 60000);
          client.StartAdvise("GBPUSD", 1, true, 60000);
          client.StartAdvise("EURJPY", 1, true, 60000);
          client.StartAdvise("EURCHF", 1, true, 60000);
          client.StartAdvise("EURGBP", 1, true, 60000);
          client.StartAdvise("USDCAD", 1, true, 60000);
          client.StartAdvise("AUDUSD", 1, true, 60000);
          client.StartAdvise("GBPCHF", 1, true, 60000);
          client.StartAdvise("GBPJPY", 1, true, 60000);
          client.StartAdvise("CHFJPY", 1, true, 60000);
          client.StartAdvise("NZDUSD", 1, true, 60000);
          client.StartAdvise("EURCAD", 1, true, 60000);
          client.StartAdvise("AUDJPY", 1, true, 60000);
          client.StartAdvise("EURAUD", 1, true, 60000);
          client.StartAdvise("AUDCAD", 1, true, 60000);
          client.StartAdvise("AUDNZD", 1, true, 60000);
          client.StartAdvise("NZDJPY", 1, true, 60000);

          // subscribe to the Advise event
          // this method will be called when a quote
          // is received.
          client.Advise += OnAdvise;

          Log("DDE Client Started");
        }
        else
        {
          Log("DDE Client Already Started");
        }
      }
      catch (Exception)
      {
        TheContainer.TheDdeClient = null;
        Log("An exception was thrown during DDE connection");
        Log("Ensure Metatrader 4 is running and DDE is enabled");
        Log("To activate the DDE Server go to Tools -> Options");
        Log("On the Server tab, ensure \"Enable DDE server\" is checked");
      }
    }

    private void OnAdvise(object sender, DdeAdviseEventArgs args)
    {
      Log(args.Item+": " + args.Text);
    }

  }

  public class TheContainer
  {
    public static Form1 TheForm;
    public static DdeClient TheDdeClient;
  }

Credits

This article uses the capable NDDE library which implements a DDE client, server and monitor in C# 2.0
This library is available at: http://www.codeplex.com/ndde

This project and the NDDE library require the .NET Framework 2.0 installed with Visual Studio 2005, or available at
http://www.microsoft.com/downloads/details.aspx?FamilyID=0856EACB-4362-4B0D-8EDD-AAB15C5E04F5

Read More About It

user's guide for Metatrader
http://www.metaquotes.net/userguides

AmiBroker DDE guide
http://www.amibroker.com/dde.html

The DDE client page in the 4XLab.NET site
http://www.4xlab.net/cs/forums/136/ShowPost.aspx

The next article in the series will put everything together and show how to receive realtime email trading alerts. This article will be posted first in the Articles section of the 4xlab.net website.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Alejandro Simon
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionRetrieve Topics List and Items List from DDE Server ApplicationmemberUmesh Sharma Kota9 Oct '12 - 8:44 
Is there any way, that we can Retrieve Topics List and Items List from DDE Server Application, so that we write "Advice requests" for all the items/topics
 
What if these changes time to time on source ??
How can we prevent our vb.net application to become "Hard Coded" bcoz DDEitems on DDEServer may change any time when new contracts arrive ?
 
Please guide me
Thanks
QuestionHow to program in C# for MetaTrader?memberbrick22218 Sep '12 - 1:36 
recently saw another free way to program C# for MetaTrader
http://tradeplatform.codeplex.com
QuestionDDE Application Parametermemberadam_mor13 Apr '12 - 1:52 
Hi,
To connect to the application you use
public DdeClient(
   String service,
   String topic
);
 
1. How do I locate the service name?
2. What if you have more than one instance of the same application running?
(i.e. you are using in your example "MT4", how do you know this is the application name? where do you find it?)
 
Thank you!
Questionbubble in troublememberDan_crucifi3r7 Mar '12 - 7:00 
how do i get this part into the code
=MRegionalDdeServer|'BOKSE~NBK`R'!'3'
 
DdeClient client = new DdeClient("MRegionalDdeServer", "BOKSE~NBK`R");
 
now the problem is here...
 
client.StartAdvise("3", 1, true, 60000);
or
cient.Request("3",10000);
Questiongreat work! but memory leaks?memberjesuscheung15 Jan '09 - 5:29 
i ran the demo for a few hour. The memory usage steadily ate up the memory. I don't see a problem in your code. Could the leak be NDde.dll?
AnswerRe: great work! but memory leaks?membermbaocha25 Aug '09 - 20:35 
Yea. u r right. there are obviously problems with memory. were u able to resolve it?
 
___________________________________________
forex robot review | forex trading signal system
GeneralCross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on.memberMagick937 May '08 - 10:49 
Hi
 
I keep getting this error . Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on. - when running from the source files.
 
However the binary download works fine.
 
Any idea how I can fix this?
 
Thanks
GeneralRe: Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on.memberUmesh Sharma Kota9 Oct '12 - 9:04 
Put this line into form load...
 
Control.CheckForIllegalCrossThreadCalls = False
QuestionThe Link to the DDE Library is no longer validmemberdbambirck9 Mar '08 - 14:33 
The link to the DDE library is no longer valid.
 
Do you have a copy of the library files, or know where I can find one?
 
Thanks, any help would be appreciated.
GeneralRe: The Link to the DDE Library is no longer validmemberAlejandro Simon10 Mar '08 - 12:05 
In this ever-shifting, quicksand web, google is useful for locating information
the new homepage for NDDE is http://www.codeplex.com/ndde
GeneralChecked Enable DDE Server but an exception was thrown during DDE connectionmemberlytjuan200613 Dec '07 - 19:49 
Hi,
 
I have installed MetaTrader 4 and checked the Enable DDE Server checkbox but I still get error: An exception was thrown during DDE connection...
 
When I try to compile the source code, it ask me for the 4XLab.NET.pfx key file password, can I ask for the password? I need to try one QUOTE first.
 
Thanks.
GeneralRe: Checked Enable DDE Server but an exception was thrown during DDE connectionmemberChetan Sheladiya4 Apr '12 - 2:14 
1. remove 4XLab.NET.pfx from solution
2. go to prject properties > signing tab > uncheck the sigining texy box, compile it.
 
it will works.
 
Thanks
Chetan Sheladiya
chetan

GeneralAn exception was thrown during DDE connectionmemberlytjuan200613 Dec '07 - 19:43 
Hi,
I have installed MetaTrader 4 and checked the Enable DDE Server checkbox, but I still get the error: An exception was thrown during DDE connection .... when running the demo application.
 
When I try to compile the source code, it ask me for 4XLab.NET.pfx key file password, can I ask for the password? I need to test only one QUOTE first.
 
Thanks.
 
Best Regards,
Ly Tjuan.
GeneralRe: An exception was thrown during DDE connectionmemberDamoner27 Mar '10 - 9:59 
Hi all,
 
I have the same problem. I get the ecception and ask me the password for 4XLab.NET.pfx
 
How can I solve?
 
Thanks
GeneralHelp mememberEEmadzadeh4 Nov '07 - 16:32 
Hi,
Thanks for useful article,
the http://www.4xlab.net/[^] is not accessibleFrown | :(
 
anyway when i tried to open source VS2005 says the dll 4xlab need password to compile,what is password?
 
Thanks
QuestionRe: Help mememberlytjuan200613 Dec '07 - 19:52 
Hi,
 
I have installed MetaTrader 4 and checked the Enable DDE Server checkbox but I still get error: An exception was thrown during DDE connection...
 
When I try to compile the source code, it ask me for the 4XLab.NET.pfx key file password, can I ask for the password? I need to try one QUOTE first.
 
Thanks.
QuestionMT3 APImemberDmitri Nesteruk5 Mar '07 - 20:16 
Don't you think it's better to use the MT3 API (which is available in a .NET version)?
QuestionException thrown during DDE connectionmemberJames S. Taylor23 Oct '06 - 8:05 
I have downloaded MetaTrader 4 and have enabled DDE from the options. I tried running excel and referencing the DDE server (=MT4|ASK!EURUSD) and it works great. But when I run the code example it keeps telling me that the DDE connection has thrown an exception and that it may not be enabled. Here is the stack trace:
 
at NDde.Client.DdeClient.StartAdvise(String item, Int32 format, Boolean hot, Boolean acknowledge, Int32 timeout, Object adviseState)
at NDde.Client.DdeClient.StartAdvise(String item, Int32 format, Boolean hot, Int32 timeout)
at _4XDDEClient.Form1.StartQuotes() in C:\Documents and Settings\jtaylor\Desktop\Downloads\Projects\Trading\MetaTrader\Source\4XDDEClient\4XDDEClient\Form1.cs:line 70
 
Any suggestions?
 
Thanks,
 
JT
AnswerRe: Exception thrown during DDE connectionmemberShay Ben-Sasson20 Oct '07 - 5:22 
try opening other symbols that your metatrader has them opened. it throws the exception because you mt4 is not listening to these symbols (i think ...)
it worked for me Smile | :)
hope this helps

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 10 Mar 2008
Article Copyright 2006 by Alejandro Simon
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid