Post Tagged with: "mql"

MetaTrader Magic Number

MetaTrader Magic Number

A magic number is used to identify a trade.

When a trade is opened by an Expert Advisor, a magic number can be associated with the trade.

The MQL function used to open a trade is called OrderSend.  (The OrderSend function can be difficult to configure)

OrderSend has many parameters, one of them is named magic.  When your Expert Advisor uses the OrderSend function to open an order, you set the magic parameter to a unique number that you can use later to identify the trade.

Here is the actual definition of OrderSend directly from the MetaEditor help file:

OrderSend( string symbol, int cmd, double volume, double price, int slippage, double stoploss, double takeprofit, string comment=NULL, int magic=0, datetime expiration=0, color arrow_color=CLR_NONE)

Parameters:

symbol   – Symbol for trading.
cmd   – Operation type. It can be any of the Trade operation enumeration.
volume   – Number of lots.
price   – Preferred price of the trade.
slippage   – Maximum price slippage for buy or sell orders.
stoploss   – Stop loss level.
takeprofit   – Take profit level.
comment   – Order comment text. Last part of the comment may be changed by server.
magic   – Order magic number. May be used as user defined identifier.
expiration   – Order expiration time (for pending orders only).
arrow_color   – Color of the opening arrow on the chart. If parameter is missing or has CLR_NONE value opening arrow is not drawn on the chart.

 

Note: See the “magic=0” in the function definition? This means the magic parameter is optional: it does not need to be defined.  Furthermore, when it is not defined, it will get the value of 0.  By the way, trades opened manually (not by an EA) always have a magic number value of 0.  This is good to know hen you write your Expert Advisor.

What’s the Purpose of Identifying a Trade with a Magic Number?

The main purpose of tagging your trade with a Magic number is so you can manage the trade based upon the circumstances under which it was opened.  For example, suppose you have this situation:

  • You are running 2 Expert Advisors:  one on a  EURUSD 1-hour chart and the other on a EURUSD 15-minute chart.
  • One EA is a scalping EA and the other is a trend-following EA.
  • Each of these EAs has 1 open trade.

You’ll probably want to manage the exit of these trades differently.  Aside from the standard stoploss and takeprofit exit, you may want to run a trailing-stop on one trade and a channel-stop on the other.

In this case, it’s not sufficient to identify the trade by its currency pair, since both trades are EURUSD trades.  This is where the magic number comes in.  If a unique magic number was used when these trades were opened, it can now be used to identify what EA opened the trade.  For example, the scalping EA could use a magic number of 100, and the trend-following EA can use a magic number of 200.

How to Get the Magic Number of an Open Trade

There is an MQL function named OrderMagicNumber that will get the magic number of a trade.  But don’t get too excited, it’s not quite that easy.

The function  OrderMagicNumber must be run in an order selection loop.  The MQL function OrderSelect is used to select a trade.  After a trade has been selected, the OrderMagicNumber  function is used to get the magic number.  Typically the MQL function OrdersTotal is used to cycle through all of the open trades for the account. Here is an MQL code sample:

int total=OrdersTotal();
int mymagic;

for(int pos=0;pos<total;pos++)
{
     if(OrderSelect(pos,SELECT_BY_POS)==false) continue;
     mymagic = OrderMagicNumber();
}

(Don’t worry, this code get’s easier to work with after you’ve done it about thousands times 🙂

Incidentally, this same technique is used to get just about any information about a trade: stoploss, takeprofit, open time, open price, etc.   (Also, the trade history of an account can be queried in the same way. You can get all of the same information about closed trades).

So now that you can get a trade’s magic number, you can execute a specific trade exit based upon the magic number.  You can do this using basic if-then logic:

  • if mymagic is equal to 100
    • run a trailing stop
  • if mymagic is equal to 200
    • run a channel stop

Using Magic Numbers in VTS

In VTS, an input variable named MagicNumber is created with every system.

  • The MagicNumber variable is defined and configured in the VTS Input Manager .
  • The MagicNumber variable appears on the input tab when you start the EA, so it can be set each time the EA is run.
  • The default value of the magic parameter for all OrderSend functions in VTS is the variable MagicNumber
  • Note that the OrderSend function in VTS is called by the user-friendly VTS function fnOpenOrder.

So, when you create a simple EA in VTS that uses the fnOpenOrder function, and you use the default values, you’ll have an EA that opens trades using the magic number that is shown on input window when you start the EA.  See this link for an example of the EA input window and the VTS Input Manager window.

Here is an image of the magic parameter on the VTS fnOpenOrder function configuration. Note, it is on the advanced tab:

Magic Number Parameter on fnOpenOrder (OrderSened)

Magic Number Parameter on fnOpenOrder (OrderSened) 

 

 

Since you can set the magic parameter on the VTS fnOpenOrder function to any value, not just the MagicNumber variable, the capability to utilize a magic number within VTS is very flexible.

You may have noticed the comment parameter.  The comment parameter of OrderSend is used to add a text comment to a trade.  (Note: you have to be careful if you want to use the comment value to identify a trade because the value can be change by the broker. Actually, it is changed anytime the trade is modified).

Anyway, it can be extremely handy to see the magic number of a trade in the MetaTrader platform. So by default, VTS sets the name of the EA and the magic number into the comment parameter.  This way, you can visually see how your trades were opened in the MT platform.  Here is an image of an open trade in the Trade tab:

The name of the EA that opened this EURUSD trade is “system3”, and the magic number is  123456.

Here is an image of a closed trade in the Account History tab:

Note that the comment field has been changed by the broker: they added the text “[tp]”.

By the way, if you don’t see the Comment field in your MetaTrader platform, you can right mouse-click on the columns and add it.

How to get the Magic Number of a Trade using VTS

The VTS function fnGetOrderInfo is used to get the magic number, or many other values, from an open trade.  See this link on how to use fnGetOrderInfo and the different values you can get from the function.

The fnGetOrderInfo generates all of the MQL code for the order selection loop and returns the requested value.

Special MetaTrader Functions: init, deinit and start

Special MetaTrader Functions: init, deinit and start

If you have ever used the MetaEditor to build an Expert Advisor, you may have noticed that the editor automatically builds 3 functions for you: init, deinit and start. This is what they mean:

  • init: This function is called when the Expert Advisor is first attached to a chart, or whenever the EA is reset and the input variables were changed.
  • deinit: This function is called when the Expert Advisor is removed from a chart.
  • start: This function is called on every incoming tick.

In VTS, the main system drawing represents the start function.  The main system drawing is the drawing tab with the same name as the VTS system, for example ‘system1″.

On each new incoming tick of price data your MT platform receives from your brokers server, execution begins at the Start Element of  the main system drawing.

How to Use the init and deinit Functions in Visual Traders Studio

VTS supports a drag, drop and connect approach to building an EA. You connect the Elements on the Drawing Pad in the way that you expect them to execute.  The drag, drop and connect approach does not support the concept of the init and deinit functions cleanly because those functions are not executed on each tick. The init and deinit functions are only executed when the EA is started and stopped.

An Elegant Solution for supporting init and deinit

Don’t worry, we have an elegant solution. If you need to use either the init or deinit functions in a VTS system, simply create a drawing named init or deinit , add the drawing Element to the main system drawing and don’t connect it.

Here are the steps:

  • From the New Elements tab in the Toolbox, drag a Drawing Element Icon onto the Drawing Pad
  • Name the Drawing init (leave the return value as integer and you probably don’t want to add a logic element, so un-check that box)
  • Drag, drop and connect any Elements needed on the init drawing
  • Save the init drawing (click the Save button in the top left corner of VTS)
  • Locate the init drawing in the Toolbox under:  Functions->System Functions->Name of your system->init
  • On the main system drawing, drag and drop the init function Element anywhere. Do not connect it to any other Elements!
  • Done.

If you connect the init Element, it will be executed on each tick, like any Element connected on a drawing. That’s not what you want.

(deinit is handled the same way.)

Normally, any Element not connected on a VTS drawing will not be included in the generated MQL code.  (This feature is a handy way to temporarily remove some functionality from a system).

But the init and deinit functions are handled differently. If they exist on the main system drawing, they will be included in the generated MQL.  Also, VTS often makes use of the init function (especially the plug-ins), but you don’t have to worry about any conflicts. VTS will combine your drawing Elements with its own internal MQL code into a single complete init (or deinit) function.

What are init and deinit used for?

If you don’t have a compelling reason to use these functions then you probably don’t need to be concerned with them.

The init function is good for resetting values and clearing of objects. For example, the VTS TrendLine plug-in may draw trendlines on the chart. There are functions in the TrendLine library to delete all of the trendlines and their labels. You can add those functions to your init or deinit drawing to clear the chart whenever you start or end the EA.

Also, I have found when I am testing an EA, it’s handy to add the fnCloseAll function onto the deinit drawing so that all trades are closed when I finish testing the EA.  This is on a demo account only of course!

Here is a drawing showing how it looks to use  init and deinit on the main system drawing:

MetaTrader init and deinit functions on main system drawing of VTS