Automatic setting of stop losses

Some time ago I was writing about an interesting offer of MB Trading. Because it is an ECN broker, it manages order sending in a specific way – you can’t send market order with the specified SL and TP levels – you have to enter the market and then modify the SL and TP levels.

This situation (as well as numerous questions) inspired me to write this entry. Below I present you sample code, which can be used for automatic setting of stop losses for all orders that don’t have them set. Of course, this code can be used not only with ECN brokers.

void stoploss(int sl,int magic=0) {

 for(int i=0;i<OrdersTotal();i++) {
  if(OrderSelect(i,SELECT_BY_POS)) {
   if(OrderMagicNumber()==magic && OrderSymbol()==Symbol()) {

    if(OrderStopLoss()==0) {
     if(OrderType()==OP_BUY || OrderType()==OP_BUYLIMIT || OrderType()==OP_BUYSTOP) {
      OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()-sl*Point,
                  OrderTakeProfit(),OrderExpiration(),CLR_NONE);
     } else {
      OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+sl*Point,
                  OrderTakeProfit(),OrderExpiration(),CLR_NONE);
     }
    }
   }
  }
 }
}

As function parameters we pass the stop loss size to be set and an optional magic number (if we don’t set it, it will use zero as magic number, which means it will set SL for all orders entered manually).

Share with your friends:

Send us your comments

Name (required)

Email (required)

Message

  • Facebook