All,
How to close all opened positions in MQL5. Need your sample please
See https://www.mql5.com/en/forum/902
Thank Phampton,
It looks that it is for single position only. How to close all positions from the last position to the first position. Sorry for this dummy question. I just learn this MQL5 language
Thank Phampton,
It looks that it is for single position only. How to close all positions from the last position to the first position. Sorry for this dummy question. I just learn this MQL5 language
Try it - it should close every position until PositionsTotal()==0.
Sorry, I've just tested it, and found that the loop is a fraction too quick for PositionsTotal() to pick up the change. It works with a Sleep(1000) added, but it seems safer to re-write to be a conventional loop
#include <trade/trade.mqh> void OnStart() { CTrade trade; int i=PositionsTotal()-1; while (i>=0) { if (trade.PositionClose(PositionGetSymbol(i))) i--; } }
Sorry, I've just tested it, and found that the loop is a fraction too quick for PositionsTotal() to pick up the change. It works with a Sleep(1000) added, but it seems safer to re-write to be a conventional loop
Does the code above works?
Where to add the Sleep(1000)?
How to rewrite it to a conventional loop?
Mql5 not Mql4
void CloseAll() { for (int i=PositionsTotal()-1;i>=0; i--) { { if(!trade.PositionClose(PositionGetSymbol(i))) { //--- failure message Print(PositionGetSymbol(i), "PositionClose() method failed. Return code=",trade.ResultRetcode(), ". Code description: ",trade.ResultRetcodeDescription()); } else { Print(PositionGetSymbol(i), "PositionClose() method executed successfully. Return code=",trade.ResultRetcode(), " (",trade.ResultRetcodeDescription(),")"); } } } }
while(PositionsTotal() != 0);
This would work.
- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
You agree to website policy and terms of use
All,
How to close all opened positions in MQL5. Need your sample please