Code Library / Order Management

MQL5 Close All Positions

Close all positions with optional filtering.

Language: MQL5 · Category: Order Management · Tags: close all, positions, MQL5, filter, portfolio

Source code

#include <Trade/Trade.mqh>
CTrade trade;
void CloseAll() {
   for(int i=PositionsTotal()-1;i>=0;i--)
      trade.PositionClose(PositionGetTicket(i));
}
void CloseLosers() {
   for(int i=PositionsTotal()-1;i>=0;i--) {
      ulong t=PositionGetTicket(i);
      if(PositionSelectByTicket(t)&&PositionGetDouble(POSITION_PROFIT)<0)
         trade.PositionClose(t);
   }
}

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