Auto Close Script (Close small lots 1st)

Hello,

I am writing a code to close trades when Account Equity is greater that Account Balance.
My target is to reduce risk for another martingale EA. so I exit at neutral point (No Loss / Profit) after the EA open 5 trades or more.
My question is: is there is any way to close orders based on the open time or lot size? … I want to close the smaller lots or older trade first then go to the next and then to the next …
This is basically to avoid interacting with the main Martingale EA, where the EA will automatically open another trade if the account is in loss.

Example:

Martingale EA open 5 Buy trades on EURUSD

  • 0.01 @ 1.2150 @ 10:15

  • 0.02 @ 1.2140 @ 11:20

  • 0.03 @ 1.2130 @ 11:55

  • 0.04 @ 1.2120 @ 13:50

  • 0.05 @ 1.2110 @ 15:10

if the Auto close EA I implemented close 0.05 1st then the Martingale EA will Open another trade, so I do like to close 0.01 > 0.02 > 0.03 > 0.04 > 0.05 to avoid such interaction.

if (OrdersTotal() > 4 && (AccountEquity() > AccountBalance()))
{

SendNotification(“Auto Close”);
Print (“Auto Close”);
CloseOrdersAll();
}

}

//±-----------------------------------------------------------------+

void CloseOrdersAll()
{
for(int i=OrdersTotal()-1;i>=0;i–)
{
OrderSelect(i, SELECT_BY_POS);
bool result = false;
if ( OrderType() == OP_BUY ) result = OrderClose( OrderTicket(), OrderLots(), NormalizeDouble(Bid,Digits), 30 );
if ( OrderType() == OP_SELL ) result = OrderClose( OrderTicket(), OrderLots(), NormalizeDouble(Ask,Digits), 30 );

}
return;
}

Please note that this does not work in the United States because of fifo rules, just FYI.

I think what you’re looking for in your closing function you need to say the following to only close trades that have an order profit of greater than zero.

if(OrderProfit()>0) …then close this ticket…

As I see it it really doesn’t matter if the order is a buy or sell but instead it only matters if the order profit of that ticket is greater than zero and should be greater than 0 by a few pips okay thank you

I tell you what you can do you can take this to another level let’s say for example that you have 12 trades that you’re going to close and they are all in profit or some are in profit and some are not in profit always close the most profitable trade first going on down to the least profitable that you intend to close do you know what this will make in your equity curve it will make a hump… This will cause your equity curve to not be jagged up down up down up down up down but instead it will make upward bound humps if you are profitable and it will make downward bound humps if you are negative overall