Code Library / Order Management

MQL5 OCO Orders

One-Cancels-Other: when one fills, cancel the other.

Language: MQL5 · Category: Order Management · Tags: OCO, one cancels other, MQL5, pending orders, bracket

Source code

#include <Trade/Trade.mqh>
CTrade trade;
ulong buyT=0, sellT=0;
void PlaceOCO(double bp,double sp,double lots) {
   if(trade.BuyStop(lots,bp,_Symbol)) buyT=trade.ResultOrder();
   if(trade.SellStop(lots,sp,_Symbol)) sellT=trade.ResultOrder();
}
void CheckOCO() {
   bool be=false,se=false;
   for(int i=0;i<OrdersTotal();i++) {
      ulong t=OrderGetTicket(i);
      if(t==buyT) be=true; if(t==sellT) se=true;
   }
   if(!be&&se){trade.OrderDelete(sellT);sellT=0;}
   if(!se&&be){trade.OrderDelete(buyT);buyT=0;}
}

How to use this snippet

This is a building block, not a finished trading system. Paste it into your own MQL5 project, compile it, and test it on a demo account with your broker's real spreads before relying on it. If MetaEditor reports errors, the compilation error fixer can help.

Related snippets