Important coding advice

This topic contains 0 replies, has 1 voice, and was last updated by  Kiaria Yoshida 3 weeks ago.

Viewing 1 post (of 1 total)
  • Author
    Posts
  • #2400

    Kiaria Yoshida
    Keymaster

    I was just reading through the code of one of the commercial expert advisers and found a very common error. I would like to highlight the authors’ mistake in this post, so that you can take it into account and not make the same mistake in your own systems.

    Here we go…

    I am not naming the EA or the Author and this is intentional – so that no copyrights are breached. However, here is an extract [modified] from the code:

    for (int i = 0; i < OrdersTotal(); i++)
    {
    if (OrderSelect(pos_52, SELECT_BY_POS, MODE_TRADES) == TRUE)
    {
    if(OrderType() == OP_BUY)
    {
    if (Bid >= PriceRangeCloseBUY_1 || Bid <= PriceRangeCloseBUY_2)
    OrderClose(OrderTicket(), OrderLots(), Bid, slippage, Red);
    }

    if(OrderType() == OP_SELL)
    {
    if (Ask >= PriceRangeCloseSELL_1 || Ask <= PriceRangeCloseSELL_2)
    OrderClose(OrderTicket(), OrderLots(), Ask, slippage, Red);
    }
    }
    }

    Can you spot the error?

    The mistake the author made is that you in the case when you close orders you cannot go cycle through the list of orders from lowest to highest, because you risk missing some orders. This happens due to the fact that OrdersTotal() is checked on every iteration of the cycle and when you delete (close) orders WITHIN the cycle itself, the value of OrdersTotal() constantly decreases. Additionally, the list of orders itself changes too. When you delete order #4, order #5 becomes order #4, and therefore when your index changes to i=5, you are not looking at the original #5 anymore. Instead, you are looking at what used to be #6.

    Please be careful in your code. The correct way of arranging the logic of this cycle is from top to bottom. Here, have a look at this code:

    for (int i = OrdersTotal()-1; i >= 0; i–)
    {
    if (OrderSelect(pos_52, SELECT_BY_POS, MODE_TRADES) == TRUE)
    {
    if(OrderType() == OP_BUY)
    {
    if (Bid >= PriceRangeCloseBUY_1 || Bid <= PriceRangeCloseBUY_2)
    OrderClose(OrderTicket(), OrderLots(), Bid, slippage, Red);
    }

    if(OrderType() == OP_SELL)
    {
    if (Ask >= PriceRangeCloseSELL_1 || Ask <= PriceRangeCloseSELL_2)
    OrderClose(OrderTicket(), OrderLots(), Ask, slippage, Red);
    }
    }
    }

    Do you see the difference?

    This code is safe, because its logic is concrete. I hope this helps you avoid errors in your own code, and save money on technical mistakes of your expert advisers.

Viewing 1 post (of 1 total)

You must be logged in to reply to this topic.

Related Posts