Hola a todos,
After spending some time with the ApplyStop() function I have now got it to result in the exiting of positions. For reasons that escape me, the position is exited a bar late and at a lower price. I'm not sure where the price it exits at is coming from because its not an O, H, L or C value and I can't pull it from any other calculations. All other aspects of the strategy operate as expected (entry, entry price, pos sizing, exit, exit price).
Scenario
- Post-session on signal bar, limit order is placed 1% below this bar's low. Risk per share is x * ATR( x) below order price.
- Post-session on entry bar, trailing stop is set to x * ATR( x) below this bar's low.
- Intraday on exit/stop bar, stop level is hit and position is exited.
Code below with Buys/Sells substituted for generic rules.
_SECTION_BEGIN("stop_test_gen");
/* Set Options */
SetOption("EveryBarNullCheck", True);
SetOption("InitialEquity", 10000);
SetOption("AllowSameBarExit", False);
SetOption("MaxOpenPositions", 10);
SetOption("CommissionMode", 2);
SetOption("CommissionAmount", 5);
SetOption("UsePrevBarEquityForPosSizing", True);
SetTradeDelays(0, 0, 0, 0);
SetBacktestMode(backtestRegular);
SetOption("ActivateStopsImmediately", True);
RoundLotSize = 1;
/* Position Sizing */
riskPerShare = ATR(10);
pctSize = (1 * BuyPrice / riskPerShare);
SetPositionSize(pctSize, spsPercentOfEquity);
/* Buy Conditions */
enterLong = Cross(C, MA(C, 20));
/* Buy */
BuyPrice = (1.00 - (1 / 100)) * Ref(Low, -1);
Buy = (Ref(enterLong, -1)) AND (Low < (1.00 - (1 / 100)) * Ref(Low, -1));
/* Sell */
exitLong = Cross( MA(C, 20), C);
SellPrice = Open;
Sell = Ref(exitLong, -1);
/* Stoploss */
stopLength = (High - Low) + Ref(ATR(10), -1);
ApplyStop(stopTypeTrailing, stopModePoint, stopLength, 1, True, 1);
/* Plots */
Equity(1, 0);
inTrade = Flip(Buy, Sell);
stopLine = IIf(inTrade, HighestSince(Buy, High - stopLength), Null);
Plot(stopLine, "Stop Level", colorRed, styleLine);
Plot( Close, "Price", colorBlack, styleCandle);
PlotShapes(Buy * shapeUpArrow, colorGreen, 0, Low);
PlotShapes(Sell * shapeDownArrow, colorRed, 0, High);
_SECTION_END();
/* Exploration */
Filter = Buy OR Sell;
AddColumn(BuyPrice, "Entry Price");
AddColumn(Open, "Open");
AddColumn(High, "High");
AddColumn(Low, "Low");
AddColumn(Close, "Close");
AddColumn(stopLength, "Stop Length");
AddColumn(HighestSince(Buy, High - stopLength), "Stop Price");
Below is the backtest and exploration results. Trade exited at 48.76 instead of the stop level of 49.14.