EMA crossover with Nicolas' Break even stop loss
Forums › ProRealTime English forum › ProOrder support › EMA crossover with Nicolas' Break even stop loss
- This topic has 19 replies, 3 voices, and was last updated 4 years ago by
crolakstrading.
-
-
08/07/2019 at 12:16 PM #104345
Hi All,
Ive been working on a simple EMA crossover strategy that utilises Nicolas’ code for moving a stop loss to breakeven after the trade has moved in our direction by a specified number of points.
I have backtested the system and it gives good results. I am also in the midst of testing it in realtime with demo. Again, it is doing pretty well. However a couple of things have come up that Im struggling to resolve.
When profitable positions close due to an EMA crossover, the remaining stop loss also seems to trigger as soon as another position is entered in the opposite direction. See attached screen shot of 4 executions on the NASDAQ. A long of 10 per point at 7500.4 is opened at 08:42 this is then exited at 11:53 at 7548.7. Because the EMA strategy is always in the market a new position is trigger on the short side but then a buy stop is also trigger just above the original 08:42 entry price at 7500.7. Does anyone have any idea what is going on here?
The full code is posted below.
Thanks for any help.
Roj
EMA cross with BE stop12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485// Definition of code parametersDEFPARAM CumulateOrders = False // Cumulating positions deactivatedEMAfast = 23EMAslow = 47//Risk ManagementCapital = 20000Risk = 0.005StopLossL = abs(close - LOWEST[10](Low)) + 1.5 * pointsizeStopLossS = abs(close - HIGHEST[10](High)) + 1.5 * pointsizeequity = Capital + StrategyProfitmaxrisk = round(equity*Risk)PositionSizeL = abs(round((maxrisk/StopLossL)/PointValue)*pipsize)PositionSizeS = abs(round((maxrisk/StopLossS)/PointValue)*pipsize)// Conditions to enter long positionsindicator1 = ExponentialAverage[EMAfast](close)indicator2 = ExponentialAverage[EMAslow](close)c1 = (indicator1 CROSSES OVER indicator2)IF c1 THENBUY PositionSizeL PERPOINT AT MARKETset stop loss StopLossLENDIF// Conditions to exit long positionsindicator3 = ExponentialAverage[EMAfast](close)indicator4 = ExponentialAverage[EMAslow](close)c2 = (indicator3 CROSSES UNDER indicator4)IF c2 THENSELL AT MARKETENDIF// Conditions to enter short positionsindicator5 = ExponentialAverage[EMAfast](close)indicator6 = ExponentialAverage[EMAslow](close)c3 = (indicator5 CROSSES UNDER indicator6)IF c3 THENSELLSHORT PositionSizeS PERPOINT AT MARKETset stop loss StopLossSENDIF// Conditions to exit short positionsindicator7 = ExponentialAverage[EMAfast](close)indicator8 = ExponentialAverage[EMAslow](close)c4 = (indicator7 CROSSES OVER indicator8)IF c4 THENEXITSHORT AT MARKETENDIF//trailing stop functionTrailingStart = 10 * pipsize //trailing will start @trailinstart points profitTrailingStep = 5 * pipsize//reset the stoploss valueIF NOT ONMARKET THENnewSL = 0ENDIF//manage long positionsIF LONGONMARKET THEN//first move (breakeven)IF newSL = 0 AND CLOSE - TRADEPRICE(1) >= TrailingStart THENnewSL = TRADEPRICE(1) + TrailingStepENDIFENDIF//manage short positionsIF SHORTONMARKET THEN//first move (breakeven)IF newSL = 0 AND TRADEPRICE(1) - CLOSE[1] >= TrailingStart THENnewSL = TRADEPRICE(1) - TrailingStepENDIFENDIF//stop order to exit the positionsIF newSL > 0 THENSELL AT newSL STOPEXITSHORT AT newSL STOPENDIF08/07/2019 at 1:34 PM #104353At lines 23 and 33 add the condition
1AND Not OnMarketThen move line 10 between lines 23 and 24 and move line 11 between lines 42 and 43.
08/07/2019 at 2:03 PM #104356Thanks.
Are you sure I should add a AND NOT ONMARKET to line 33? That is the condition to sell a long position for profit when the fast EMA crosses below the slow. Don’t we need to be on the market for that condition to be implemented?
Shouldnt AND NOT ONMARKET go to line 42 (i.e. where we enter short)?
Sorry if Ive misunderstood and thanks for your help.
08/07/2019 at 2:13 PM #104357Sorry, you’re right, it’s 23 and 42.
08/07/2019 at 9:05 PM #104372Thanks Roberto.
Ive now trialed the updated code and whilst it does prevent new orders from being immediately closed I think the ‘AND NOT ONMARKET’ command is preventing new orders from being initiated. Because this is an EMA cross over strategy it should be on the market pretty much all of the time (unless the breakeven stop has been triggered at which point we wait for the next crossover). For example we should exit longs when the fast EMA crosses below the the slow EMA and simultaneously flip short. I think the ‘AND NOT ONMARKET’ command when we specify conditions to enter is preventing the strategy from simultaneously flipping sides. Is that correct? Can you explain a bit of your rationale for using the ‘AND NOT ONMARKET’ statement? Any ideas how to resolve this? The update code is pasted below.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384// Definition of code parametersDEFPARAM CumulateOrders = False // Cumulating positions deactivatedEMAfast = 6EMAslow = 27//Risk ManagementCapital = 20000Risk = 0.005equity = Capital + StrategyProfitmaxrisk = round(equity*Risk)PositionSizeL = abs(round((maxrisk/StopLossL)/PointValue)*pipsize)PositionSizeS = abs(round((maxrisk/StopLossS)/PointValue)*pipsize)// Conditions to enter long positionsindicator1 = ExponentialAverage[EMAfast](close)indicator2 = ExponentialAverage[EMAslow](close)c1 = (indicator1 CROSSES OVER indicator2)IF c1 AND NOT ONMARKET THENBUY PositionSizeL PERPOINT AT MARKETStopLossL = abs(close - LOWEST[10](Low)) + 1.5 * pointsizeset stop loss StopLossLENDIF// Conditions to exit long positionsindicator3 = ExponentialAverage[EMAfast](close)indicator4 = ExponentialAverage[EMAslow](close)c2 = (indicator3 CROSSES UNDER indicator4)IF c2 THENSELL AT MARKETENDIF// Conditions to enter short positionsindicator5 = ExponentialAverage[EMAfast](close)indicator6 = ExponentialAverage[EMAslow](close)c3 = (indicator5 CROSSES UNDER indicator6)IF c3 AND NOT ONMARKET THENSELLSHORT PositionSizeS PERPOINT AT MARKETStopLossS = abs(close - HIGHEST[10](High)) + 1.5 * pointsizeset stop loss StopLossSENDIF// Conditions to exit short positionsindicator7 = ExponentialAverage[EMAfast](close)indicator8 = ExponentialAverage[EMAslow](close)c4 = (indicator7 CROSSES OVER indicator8)IF c4 THENEXITSHORT AT MARKETENDIF//trailing stop functionTrailingStart = 5 * pipsize //trailing will start @trailinstart points profitTrailingStep = 1 * pipsize//reset the stoploss valueIF NOT ONMARKET THENnewSL = 0ENDIF//manage long positionsIF LONGONMARKET THEN//first move (breakeven)IF newSL = 0 AND CLOSE - TRADEPRICE(1) >= TrailingStart THENnewSL = TRADEPRICE(1) + TrailingStepENDIFENDIF//manage short positionsIF SHORTONMARKET THEN//first move (breakeven)IF newSL = 0 AND TRADEPRICE(1) - CLOSE[1] >= TrailingStart THENnewSL = TRADEPRICE(1) - TrailingStepENDIFENDIF//stop order to exit the positionsIF newSL > 0 THENSELL AT newSL STOPEXITSHORT AT newSL STOPENDIF08/07/2019 at 9:47 PM #104373Yes, On Market prevents reversing positions, but it allows to keep your StopLoss at the point it was calculated on entry, otherwise it will change every candle.
But, the issue you were complaining about was probably be due to the very narrow value for your trailing stop settings (5 and 1).
IG requires a minimun stop distance when placing pending orders (the ones you use to trail stop loss).
You’d better use GRAPH to monitor your variables, StopLossL, StopLossS, close and NewSL. so that you can figure out what value they do retain each candlestick.
08/07/2019 at 10:16 PM #104375Thanks Roberto. I will graph and try to figure it out. Im not sure its the SL distance though as I’ve been watching the strategy automatically take trades in realtime on demo mode and it works perfectly, just fails to flip from long to short or vice versa with this new code. It was doing that fine in the previous version without a breakeven stop.
I have one more question if you don’t mind me troubling you…
How would I specify that I don’t want any new positions to be taken between 21:15 and 23:00 (i.e. between the close of the NY session and the open of Sydney)?
08/07/2019 at 10:31 PM #10437608/08/2019 at 9:03 AM #104385It’s very difficult your strategy can run as expected, too narrow SL’s that don’t always abide to the required minimum distance.
I rewrote your initial code using only 2 indicators and 2 conditions (the other ones were just duplicate instances), adding GRAPH and GRAPHONPRICE and you can see the value of the GRAPHed variable in the variable windows (c1 & c2) and on the price chart (both SL’s + NewSL):
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566DEFPARAM CumulateOrders = False // Cumulating positions deactivatedEMAfast = 23EMAslow = 47//Risk ManagementCapital = 20000Risk = 0.005StopLossL = abs(close - LOWEST[10](Low)) + 1.5 * pointsizeStopLossS = abs(close - HIGHEST[10](High)) + 1.5 * pointsizeequity = Capital + StrategyProfitmaxrisk = round(equity*Risk)PositionSizeL = abs(round((maxrisk/StopLossL)/PointValue)*pipsize)PositionSizeS = abs(round((maxrisk/StopLossS)/PointValue)*pipsize)// Conditions to enter long positionsindicator1 = ExponentialAverage[EMAfast](close)indicator2 = ExponentialAverage[EMAslow](close)c1 = (indicator1 CROSSES OVER indicator2)IF c1 THENBUY PositionSizeL PERPOINT AT MARKETset stop loss StopLossLENDIF// Conditions to exit long positionsc2 = (indicator1 CROSSES UNDER indicator2)IF c2 THENSELL AT MARKETENDIF// Conditions to enter short positionsIF c2 THENSELLSHORT PositionSizeS PERPOINT AT MARKETset stop loss StopLossSENDIF// Conditions to exit short positionsIF c1 THENEXITSHORT AT MARKETENDIF//trailing stop functionTrailingStart = 10 * pipsize //trailing will start @trailinstart points profitTrailingStep = 5 * pipsize//reset the stoploss valueIF NOT ONMARKET THENnewSL = 0ENDIF//manage long positionsIF LONGONMARKET THEN//first move (breakeven)IF newSL = 0 AND CLOSE - TRADEPRICE(1) >= TrailingStart THENnewSL = TRADEPRICE(1) + TrailingStepENDIFENDIF//manage short positionsIF SHORTONMARKET THEN//first move (breakeven)IF newSL = 0 AND TRADEPRICE(1) - CLOSE[1] >= TrailingStart THENnewSL = TRADEPRICE(1) - TrailingStepENDIFENDIF//stop order to exit the positionsIF newSL > 0 THENSELL AT newSL STOPEXITSHORT AT newSL STOPENDIF//graphOnPrice StopLossL coloured(255,0,0,255) AS "slL"graphOnPrice StopLossS coloured(0,128,0,255) AS "slS"graphOnPrice NewSL coloured(0,0,255,255) AS "NewSL"graph c1graph c2You will see the price as a single flat line identified only by the downward orange arrow of the short trade entered, since I had to shkring the scale 1,000 times to be able to see small values compared to a price of over 7,000.
08/08/2019 at 9:26 AM #104389Thanks Roberto. Im pretty much certain that its not down to the size of the stop loss distance. I ran the strategy over night last night in realtime. It is nicely profitable but is still not behaving as expected. I removed the ‘AND NOT ONMARKET’ command as I didn’t think this makes sense for a strategy that should flip from one side to another. However the issue still remains that when a winning position closes due to an EMA cross the leftover trailing stop the instantly closes the new position that is opened. The periodicity of this is evident from the attached chart which shows the performance over last night. Notice how there’s a gap between each position – i.e. every time it flips the trade is closed, so it essentially skips every other signal due to the leftover breakeven stop.
I feel like the reason this is happening is because there are 2 orders to exit positions; 1 being the EMA crossover and the 2nd being the order from the breakeven stop. Is there something that I can add to the condition for the breakeven stop that will pull it from the market when the current position closes (i.e. the one that it is linked to)? Here’s the code that deals with the command for executing the stop:
12345//stop order to exit the positionsIF newSL > 0 THENSELL AT newSL STOPEXITSHORT AT newSL STOPENDIF08/08/2019 at 9:34 AM #104392The issue is at line 39, since NewSL requires the status NOT ON MARKET to be detected and it only will the next bar after a trade closes. If you open a new trade after closing another one and there is not at least ONE bar with no trades open, NewSL will retain the same previous value.
Try adding a line with
1NewSL = 0betewwen line 25 and 26, then again between lines 44 and 45.
08/08/2019 at 6:56 PM #10443808/08/2019 at 7:04 PM #104439Lines in your first post.
08/08/2019 at 8:41 PM #104442I think that might have solved the problem, seems to be doing what its supposed to. I will run it over night and post the full code for the strategy with backtesting results etc if it works. Thanks for your help and patience Roberto.
08/09/2019 at 7:10 PM #104498Hi Roberto,
Sadly the addition of ‘NewSL=0’ at the end of the buy and sell conditions does does not seem to have solved the problem and I still get new orders immediately closed out. This pattern is consistent in the backtest and realtime trading over the course of the day.
Its super frustrating as the addition of the breakeven stop to this strategy really increases its profitability and reduces drawdown – see attached screenshot of walk forward analysis on NQ on m1 timeframe. Ive also added some conditions that use the ATR to determine when to move to breakeven, which works nicely. Just massively frustrating that I cent get it to flip sides when the EMAs cross and we take profits on winning trades.
For reference the most up to date cost is pasted below along with the attached screen shot of the walk forward analysis
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990// Intraday trend following strategy. Entries and Exits defined by EMA crossovers. Position size determiend by distance to stop loss and percent of equity at risk. Initial stop loss set at recent swing low or high. Profits are protected by a stoploss that moves to breakeven after a defined number of points// Issues: new flipped positions are immediately closed due to the BE stop which remains on the market after the positon is exited due to EMA crossover// Definition of code parametersDEFPARAM CumulateOrders = False // Cumulating positions deactivatedDEFPARAM FlatBefore = 230000DEFPARAM FlatAfter = 211500EMAfast = 11EMAslow = 38//Risk ManagementCapital = 36000Risk = 0.01equity = Capital + StrategyProfitmaxrisk = round(equity*Risk)PositionSizeL = abs(round((maxrisk/StopLossL)/PointValue)*pipsize)PositionSizeS = abs(round((maxrisk/StopLossS)/PointValue)*pipsize)// Conditions to enter long positionsindicator1 = ExponentialAverage[EMAfast](close)indicator2 = ExponentialAverage[EMAslow](close)c1 = (indicator1 CROSSES OVER indicator2)IF c1 THENBUY PositionSizeL PERPOINT AT MARKETStopLossL = abs(close - LOWEST[10](Low)) + 1.5 * pointsizeset stop loss StopLossLENDIF// Conditions to exit long positionsindicator3 = ExponentialAverage[EMAfast](close)indicator4 = ExponentialAverage[EMAslow](close)c2 = (indicator3 CROSSES UNDER indicator4)IF c2 THENSELL AT MARKETENDIF// Conditions to enter short positionsindicator5 = ExponentialAverage[EMAfast](close)indicator6 = ExponentialAverage[EMAslow](close)c3 = (indicator5 CROSSES UNDER indicator6)IF c3 THENSELLSHORT PositionSizeS PERPOINT AT MARKETStopLossS = abs(close - HIGHEST[10](High)) + 1.5 * pointsizeset stop loss StopLossSENDIF// Conditions to exit short positionsindicator7 = ExponentialAverage[EMAfast](close)indicator8 = ExponentialAverage[EMAslow](close)c4 = (indicator7 CROSSES OVER indicator8)IF c4 THENEXITSHORT AT MARKETENDIF//trailing stop functionTrailingStart = AverageTrueRange[10] * pipsize //trailing will start @trailinstart points profitTrailingStep = 0 * pipsize//reset the stoploss valueIF NOT ONMARKET THENnewSL = 0ENDIF//manage long positionsIF LONGONMARKET THEN//first move (breakeven)IF newSL = 0 AND CLOSE - TRADEPRICE(1) >= TrailingStart THENnewSL = TRADEPRICE(1) + TrailingStepENDIFENDIF//manage short positionsIF SHORTONMARKET THEN//first move (breakeven)IF newSL = 0 AND TRADEPRICE(1) - CLOSE[1] >= TrailingStart THENnewSL = TRADEPRICE(1) - TrailingStepENDIFENDIF//stop order to exit the positionsIF newSL > 0 THENSELL AT newSL STOPEXITSHORT AT newSL STOPENDIF -
AuthorPosts
Find exclusive trading pro-tools on