New to mql

 

Hi all.

I am veteran C programer but new to mql.

I order to learn the languagh I started to learn the order commands API.

I understand the basics of these command, but I don`t understand several basic issues:

1.

How/when do I know that a pending order has been executed.

For example price is 1, I send sell order with limit=2, how can I check that the order has been executed?

2.

Can anyone explain about the code "flow".

I mean - in c, java, etc - the code flow starts from the "main()" function and finish at the end of that function.

In mql there is start() function - is it like main() in C or some kind of loop.

I assume that in expert advisor there should never be end to the execution as long as the advisor is activated.

3.

About orders handling : lets say that I buy tow lots and then sell tow lots -

I would like the sell order to close the open "long" position.

According to the API if I will simply send "sell" I will be in neutral long+short position.

That case is unwanted because I will have to pay extra commisions to close and swap this position.

Is there easier way to solve this problem rather than "remembering" all my commands?

4.

And finally : one qustion that summeris all the above :

I am trying to write a program that open order for every order that has been executed.

If the price is X - the program will place buy order with limit X-1 and sell order with limit X+1.

When one of the orders (buy or sell) has been executed - the program will cancel the other order and agin will send buy and sell orders with Y-1, Y+1.

It should be very simple program and will help me understand how mql worls

Thanks all

 

1. There are no events. You can't know exactly when a pending order has been executed. The OrderSend() returns you the ticket of the order that is launched. You can know if the order has been executed if you check it again with OrderSelect(). If the order has been selected, check its type. If it is BUY, and you launched it as BUYLIMIT or BUYSTOP, then it was executed.

2. Code flow in MQL4 is simple. Every time you turn on the station, attach the EA to a chart, change symbol or periodicity of the chart, connection comes back after an outage, the init is executed. Every time a tick comes on the contract you attached the EA on, the start is run. And finally, if you remove the EA, the deinit is called. Scripts have only one block to run, straight top to bottom.

My advice is that you write routines that understand your current state ("recognize" your own orders already launched) and routines that recognize market signals. Call from init the routines that recognize your current state - perhaps the station was stopped, some orders reached SL/TP, so it is necessary a recognition on init. Call from start the routines that recognize market signals - calculate indicators and take decisions, and pass these decisions to execution routines. Actually in my EAs everything happens in routines that are just called from start...

3. Don't quite understand the "remembering" stuff. 

4. I don't see where you close orders... It seems the program will continue opening orders all the time.

Basic thing is to learn how to recognize market situation.

//THIS IS NOT A FULL EA!

#define  HIGH_ORDER  0
#define  LOW_ORDER  1


int hi_ticket=-1;
int hi_type=-1;
int lo_ticket=-1;
int lo_type=-1;

void RecognizeTrades()
   {    
    int ntrades=OrdersTotal();
    if (ntrades!=0)
      {
       for (int i=ntrades-1;i>=0;i--)  //always do this loop like this, downwards
          {
           if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==True) // if current order iterated has been selected
             {
              if (OrderSymbol()==Symbol()) //if current selected order symbol is the one of the ea on chart
                {
                 if (OrderMagicNumber()==HIGH_ORDER)
                   {
                    hi_ticket=OrderTicket();
                    hi_type=OrderType();
                   }
                 if (OrderMagicNumber()==LOW_ORDER)
                   {
                    lo_ticket=OrderTicket();
                    lo_type=OrderType();
                   }
                }    
             }
          }
      }
   return;
   }

int init()
   {
    // no need to write anything here, action is repetitive within start();
   }

int start()
   {    
    RecognizeTrades();
    if (hi_type!=-1) //we have an order placed there
      {
       if (hi_type==OP_SELL)
         { 
          ...do whatever...(perhaps close something...)
         }
      }
    else
      {
       OrderSend(.... make sure magic number is HIGH_ORDER ... );
      }
    if (lo_type!=-1) //we have an order placed there
      {
       if (hi_type==OP_BUY)
         { 
          ...do whatever...(perhaps close something...)
         }
      }
    else
      {
       OrderSend(.... make sure magic number is LOW_ORDER ... );
      }
    return(0)
   }

Also don't forget to check this post here

 
nirshats:

3.

About orders handling : lets say that I buy tow lots and then sell tow lots -

I would like the sell order to close the open "long" position.

According to the API if I will simply send "sell" I will be in neutral long+short position.

That case is unwanted because I will have to pay extra commisions to close and swap this position.

Is there easier way to solve this problem rather than "remembering" all my commands?

It depends whether you know that you want the sell to close the buy before you place it, or it's a decision you reach after you have orders in opposite directions. In either case, you can query MT4's order history rather than having to maintain your list of trades.


In MT4, if you have a position and you want to close it, you do OrderClose() rather than doing an OrderSend() in the opposite direction.


If you have two existing positions in opposite directions and you want to pair them off, you may be able to use OrderCloseBy(). Only some brokers support this; the call simply fails on other brokers. There are certain types of trading system which benefit enormously from running on brokers who do support OrderCloseBy()...

 
TheEconomist wrote >>

1. There are no events. You can't know exactly when a pending order has been executed. The OrderSend() returns you the ticket of the order that is launched. You can know if the order has been executed if you check it again with OrderSelect(). If the order has been selected, check its type. If it is BUY, and you launched it as BUYLIMIT or BUYSTOP, then it was executed.

2. Code flow in MQL4 is simple. Every time you turn on the station, attach the EA to a chart, change symbol or periodicity of the chart, connection comes back after an outage, the init is executed. Every time a tick comes on the contract you attached the EA on, the start is run. And finally, if you remove the EA, the deinit is called. Scripts have only one block to run, straight top to bottom.

My advice is that you write routines that understand your current state ("recognize" your own orders already launched) and routines that recognize market signals. Call from init the routines that recognize your current state - perhaps the station was stopped, some orders reached SL/TP, so it is necessary a recognition on init. Call from start the routines that recognize market signals - calculate indicators and take decisions, and pass these decisions to execution routines. Actually in my EAs everything happens in routines that are just called from start...

3. Don't quite understand the "remembering" stuff.

4. I don't see where you close orders... It seems the program will continue opening orders all the time.

Basic thing is to learn how to recognize market situation.

Also don't forget to check this post here

Thanks you very much.

You helped alot

 
nirshats wrote >>

Thanks you very much.

You helped alot

Correct me if I`m wrong:

I do need to "remember" my orders and balance the position (take profit) by closing existing order and NOT by sending another order.

I don`t understand what the reason to think about position in meaning of "open orders" I always think about position as a long/short and quantity.

If there is open (executed) buy and sell orders at the same time you are not "long and short at the same time" because the long balances the short position, so in the end of the day you can be only long short or neutral.

The only reason I can think of that you are required to close specific open orders (take profit or stop loss ) is to take triple commisions.

Therefore I assumed the MQL should do this automatically (I mean close existing open long position instead of sending sell order).

About the code I mention - the position will be close if the rate will go back to opposite direction.

For example : The rate is 2 - place but with limit 1 and sell with limit 3.

When sell order has been executed (position of 1 lot short) place buy with limit 2 and sell with limit 4.

If the buy order has been executed (rate is back to 2) - your position is neutral (of course I expect closing the short position rather than being "long and short")

 
nirshats:

I do need to "remember" my orders and balance the position (take profit) by closing existing order and NOT by sending another order.

Yes, unless your broker allows orders to be offset against each other using OrderCloseBy(). In terms of "remembering", most EAs rely on MT4's order history rather than maintaining their own "memory" of the orders they have placed.


I don`t understand what the reason to think about position in meaning of "open orders" I always think about position as a long/short and quantity.

If there is open (executed) buy and sell orders at the same time you are not "long and short at the same time" because the long balances the short position, so in the end of the day you can be only long short or neutral.

For better or worse, MT4 isn't like e.g. trading futures on the CME. Placing matching buy and sell orders leads to separate and matching long and short positions, and this isn't the same as having no position (unless you are using a US broker regulated by the NFA). The broker will pay/charge you swap on each of the pair of positions, which will be a small net loss each day that the pair remains open. And if the spread changes, the unrealized PnL on the pair of positions changes. And if there were to be a catastrophic failure of market liquidity, you might only be able to close one of the positions.


The only reason I can think of that you are required to close specific open orders (take profit or stop loss ) is to take triple commisions.

You're right but, as I've said before, some brokers support MT4's OrderCloseBy() command. In effect, this allows pairs of orders to be offset against each other without incurring double commissions/spreads.


There are at least two other reasons why MT4 behaves the way it does:


  • It makes programming simpler. The position-based system means that stop losses and profit targets can be specified as attributes of a position, rather than having to have separate orders on an OCO basis.
  • Losing trades can be left unrealized while winning trades are banked. Unscrupulous and/or self-deluding EA writers use this in order to boost the apparent risk profile of their EAs. The problem is exacerbated by the fact that MT4 shows reports and results based on trade closure, not based on time. It's fairly easy to generate a strategy which appears in MT4's backtesting as steadily increasing account balance and equity, with no apparent dips - unless or until the account is completely bankrupted.


All this is expected to change in MT5.

Reason: