Trying to close EA as soon as the stop loss has been triggered

 

Can someone help please? I've written the attached code but it looks back at the total trade history rather than the history since the EA was loaded. I need the EA to allow a trade but then close if the stop loss was triggered. Any help appreciated.

for(int i = OrdersHistoryTotal()-1; i >= 0 ; i--)
            {
               if (OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==true
               && OrderSymbol() == Symbol()
               && StringFind(OrderComment(), "[sl]", 0)!=-1)
                        {
                           Alert(Symbol()," closed at stop loss");
                           ExpertRemove();
                        }
            }

 

Forum on trading, automated trading systems and testing trading strategies

When you post code please use the CODE button (Alt-S)!

Use the CODE button


 

You can also analyze 

OrderOpenTime()

Find the latest order, grab the OrderTicket() and use that ticket number to scan the ordercomment ( of the latest order)

 
Marco vd Heijden:

You can also analyze 

Find the latest order, grab the OrderTicket() and use that ticket number to scan the ordercomment ( of the latest order)

Thanks Marco, just not sure how that'd help. Can you elaborate please?

 
tmpascoe:

but it looks back at the total trade history rather than the history since the EA was loaded.

That's by design. You'll have to check the OrderOpen() time to see if it's after when the EA was loaded. Here's one way to go about it:

When the EA is loaded, in the OnInit() function, you can create a terminal Global Variable (see the link below).

You'll probably want to use a unique name for the Global Variable to tie it to the chart that it's loaded on, so you can use something like "MyEA" + ChartID().

Check to see if the variable exists. If it doesn't, once it's created, assign TimeCurrent() to that variable (you'll have to typecast when setting and getting the variable because all global variables are of type double).

Then, check if OrderOpen() >= <the global variable>.

Since there's two ways to create a global variable, depending on which one you choose, you'll want to either delete the global variable or set it to something like -1 if you won't have a use for it again for some time (<- this method can be used to check if the variable is currently in use).


tmpascoe:

I need the EA to allow a trade but then close if the stop loss was triggered.

for(int i = OrdersHistoryTotal()-1; i >= 0 ; i--)
            {
               if (OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==true
               && OrderSymbol() == Symbol()
               && StringFind(OrderComment(), "[sl]", 0)!=-1)
                        {
                           Alert(Symbol()," closed at stop loss");
                           ExpertRemove();
                        }
            }

ExpertRemove() is the correct way to go about it, but you didn't specify if the Expert is being removed or not. If not, then the likely culprit is the OrderComment() check is preventing the if statement condition from being met.

If that's the case: some brokers don't store the Order Comment.

To check, first, separate the OrderSelect() function call from the other conditions. Then, if OrderSelect() returns true, create a string variable and assign OrderComment() to it, then check (either through the debugger or Print()) if the comment is present.

If not, then you'll have to work around it.

One solution would be to create a terminal Global Variable, assign a unique Magic number to both the variable and the order, then check if OrderMagic() == <the global variable>. If so, set the Global Variable to -1 (or delete the global variable) then call ExpertRemove().


https://docs.mql4.com/globals

Global Variables of the Terminal - MQL4 Reference
Global Variables of the Terminal - MQL4 Reference
  • docs.mql4.com
Global variables are kept in the client terminal for 4 weeks since the last access, then they will be deleted automatically. An access to a global variable is not only setting of a new value, but reading of the global variable value, as well. When testing and optimizing the Expert Advisors that use global variables, keep in mind...
 
Compare OrderClosePrice() to OrderStopLoss() for a that selected closed order
 
Mladen Rakic:
Compare OrderClosePrice() to OrderStopLoss() for a that selected closed order

Some testing will need to be done if he decides to use this method. This is because price gaps and, if I recall correctly, stoploss / takeprofit orders are converted to market orders once price crosses the SL / TP level.

I tried it out and here are the results:

SL & TP Price vs Exit Price

As you can see, only 1 of out 3 trades exited at the SL / TP price.

 

That is due to slippage and that is why you don't check only for equal(s). A quote from one of the posts dealing with that issue :

  • if the order was an OP_BUY and the OrderClosePrice <= OrderStopLoss, the order was closed because the Bid price hit the order's stoploss price.
  • if the order was an OP_SELL and the OrderClosePrice >= OrderStopLoss, the order was closed because the Ask price hit the order's stoploss price.
 
Mladen Rakic:

That is due to slippage and that is why you don't check only for equal(s). A quote from one of the posts dealing with that issue :

Thanks for clearing that up.
Reason: