Therein, we proposed a solution to creating trading strategies in ZeroMQ supported programming languages outside the MetaTrader environment, with the latter simply acting as the intermediary to the market.

Leveraging ZeroMQ’s convenient communication patterns such as Request (REQ) / Reply (REP) and PUSH/PULL, we demonstrated how to plan and develop a simple yet powerful, distributed trading architecture that opens doors to more sophisticated trading strategy development otherwise not possible within the confines of the MetaTrader terminal.

—

In this post we’ll describe how to execute new orders and manage existing ones via ZeroMQ, through any supported programming language such as Python or R.

Our route to market will continue to be MetaTrader 4, all trading decisions being made outside it the entire time.

In technical terms – as before, any trading strategy will behave as a Client and MetaTrader as the Server.

We will also develop a simple message topology for performing these execution and reporting functions, such that the same topology is understood by both Clients (trading strategies) and Servers (MetaTrader).

In particular, we’re interested in:

The Message Topology

Opening, Modifying & Closing Trades

‎Getting Account/Market Information

‎Getting Trade Reports

This post will cover the Message Topology and Opening/Modifying/Closing Trades sections. The next post in this series will describe the latter two.

—

1) Message Topology

ZeroMQ – Distributed Messaging

Before moving forward, we first need to define some discrete messaging rules that both our trading strategies and MetaTrader can understand.

In the MQL source code provided in the previous post, these rules will need to be implemented in the InterpretZmqMessage function, the definition for which is:

voidInterpretZmqMessage(Socket &pSocket, string& compArray[])

These rules will in essence map particular messages to actions, for example:

“TRADE” -> Open a Market Order on the EUR/USD for 0.01 lots, Stop Loss of x and Take Profit of y.

“RATES” -> What is the current Bid/Ask for EUR/USD?

“ACCOUNT” -> What is account’s currenty Equity?

“HISTORY” -> How many trades are currently open?

.. and so on.

For this post’s implementation, let’s define the following message formats:

Opening, Modifying & Closing Trades:

TRADE|ACTION|TYPE|SYMBOL|PRICE|SL|TP|COMMENT|TICKET

Market Information:

RATES|SYMBOL

DATA|SYMBOL|TIMEFRAME|START_DATETIME|END_DATETIME

Account Information:

ACCOUNT|ACTION

Trade Reporting:

HISTORY|ACTION

With the message topology in place, we can now construct messages containing trading/reporting instructions.

The ZeroMQ enabled MetaTrader server will receive and execute the instructions via the REQ/REP socket as defined in the first post, and send information back to requesting clients using either the REQ/REP or PUSH/PULL socket depending on the instruction.

One implementation for example, could use REQ/REP for “critical” messages, e.g. Open/Modify/Close trading instructions and their corresponding results, while “non-critical” instructions such as displaying account equity for reporting purposes could use the PUSH/PULL socket.

At the end of the day, there are a number of ways this logic could be implemented.

Your choice of communication pattern (REQ/REP or PUSH/PULL) will depend entirely on how critical you consider one instruction set vs. another.

Generally, it pays dividends to plan this in advance of any development, as different control flows will have different performance results and come with their own considerations (good or bad problems if you will).

In the next 3 sections, we’ll run through some examples of how each message format above can be used in practice.

The ZMQ EA Template for MetaTrader 4 shared in the last post, is already setup with the appropriate code placeholders in the InterpretZmqMessage() function so readers can implement these easily.

—

2) Opening, Modifying & Closing Trades

As above, we’ll use the following format for trade instructions:

TRADE|ACTION|TYPE|SYMBOL|PRICE|SL|TP|COMMENT|TICKET

Let’s break this down further, into what each component of this message could contain:

Note: The numeric values (1,2,3,4,5) are chosen arbitrarily of course. You may choose any values you consider meaningful, as long as you implement their corresponding logic exactly in MetaTrader as you do in your external trading strategy (in e.g. Python or R).

Example message:

“TRADE|MODIFY|1|EURUSD|0|70|90|R-to-MetaTrader4|12345678”

Modifying Orders

In this case, your logic in the InterpretZmqMessage() function will need to ignore Open/Close price once again, and instead populate a call to MetaTrader’s OrderModify() function with its “stoploss” and “takeprofit” parameters set to those received in the ZeroMQ message.

Order Type can be ignored as an existing order is being modified.

You will also need to read the Ticket ID field and specify it in OrderModify()’s “ticket” parameter, so MetaTrader knows which trade to modify, in this case “12345678”.

Closing / Deleting Orders

The procedure for closing orders in MetaTrader 4 is fairly straightforward.

All you would need is to pass the Ticket ID received via ZeroMQ to an OrderClose() call, along with parameter values for “lots” specifying lot size to close, the “price” you wish to close at (e.g. Bid or Ask) and the maximum “slippage” you’re willing to tolerate on the transaction.

Let’s continue where we left off in our last post on tick data collection. If you missed it, it’s important that you familiarise yourself with its contents first. Here’s the link again: https://blog.darwinex.com/download-tick-data-metatrader/ Therein, we promised a follow-up post that would discuss an approach for retail traders to automate tick data collection with the R […]

This is the second post in the MetaTrader Expert Advisor [EAS] series we’ve begun recently. In case you missed it, here’s a link to the first post: Commercial Expert Advisors: everything that glitters is not gold. If you’re wondering what “set & forget” means, it’s a common catch phrase used widely by many commercial MetaTrader […]

In this third installment of our ZeroMQ series, we describe how to use ZeroMQ in non-MQL trading strategies to get the following information: Account Information (e.g. equity, margin, balance, etc) Trades at market (live or pending) Historical Trades If you haven’t already, please consider reading the following posts before proceeding further in this article: ZMQ-I: […]

This post describes how to construct a currency portfolio composed of any number of currency pairs (from those available on the Darwinex platform) and allocations, in MetaTrader. A few common use-cases for constructing currency portfolios include: Studying the correlation of a trading strategy’s returns to market volatility. Trading currency strength instead of single pairs themselves. […]

Your email address will not be published. Required fields are marked *

Name *

Email *

Website

Jobe Soffa

10 April 2018

Hey! This might sound like a dumb question because I still lack a basic understanding of how zeromq works. I'm mostly interested in the trading template and how I can send trades live to an MT4 account through my python program. I see in the example template the use of "tcp://localhost:5555", which I would assume is a local connection to your MT4 account. If so, how can I create a local connection to *MY* mt4 account?
If not, how exactly do I edit your template and what other steps do I need to do to connect my program to my mt4 account? Does it have to do with getting the desktop version of mt4 or something? Any help would be great!
p.s. as a side note for the trade example on the template, how do i specify units/lotsize of the trade? what is a trade ticket/id?

Subscribe to our newsletter to stay up to date with Darwinex news, we promise we won’t spam you!

Email

The Darwinex® trademark and the www.darwinex.com domain are owned by
Tradeslide Trading Tech Limited, a company duly authorised and regulated by the Financial Conduct Authority
(FCA) in the United Kingdom with FRN 586466. Our Company number is 08061368 and our registered office is Acre
House, 11-15 William Road, London NW1 3ER, UK.

This website stores cookies on your computer. These cookies are used to collect information about how you interact with our website and allow us to remember you. We use this information in order to improve and customize your browsing experience and for analytics and metrics about our visitors both on this website and other media. To find out more about the cookies we use, see our
Privacy Policy.

If you decline, your information won't be tracked when you visit this website. A single cookie will be used in your browser to remember your preference not to be tracked

CFDs are complex instruments and come with a high risk of losing money rapidly due to leverage.
77 % of retail investor accounts lose money when trading CFDs with this provider. You should consider whether
you understand how CFDs work and whether you can afford to take the high risk of losing your money.