I am getting an unexpected result when ApplyStop( stopTypeTrailing, stopModeRisk ) is used with Buy and Short entries and do not know where might be the problem.
The code below is a modified version of "How does risk-mode trailing stop work?" found here
I add a short entry , used symbol AAPL from database Data and set periodicity to weekly.
If I enable only the short entry, the stop is triggered on 2016-03-04
**When I enable the Long entry (buy) the Short stop change to 2015-05-08. Why ? **
Code used with symbol AAPL from database Data and set periodicity to weekly.
/*
Using symbol AAPL from database Data , periodicity set to weekly
copied code found at http://www.amibroker.com/kb/index.php?s=applystop
add short entry
*/
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
EnableBuy = ParamToggle("Enable Buy", "No|Yes", 1);
EnableShort = ParamToggle("Enable Short", "No|Yes", 1);
Buy = EnableBuy && DateNum() == 1130419; // custom entry on a fixed date
Sell = 0;
BuyPrice = SellPrice = close;
Short = EnableShort && DateNum() == 1150501; // custom entry on a fixed date
Cover = 0;
ShortPrice = CoverPrice = close;
riskSize = Param("riskSize", 35, 1, 100, 1);
daysDelay = Param("daysDelay", 41, 1, 100, 1);
ApplyStop( stopTypeTrailing, stopModeRisk, riskSize, 1, False, 0, daysDelay );
Equity( 1, 0 );
Plot( Close, "", colorDefault, styleBar );
barBuy = BarsSince( Buy );
barShort = BarsSince( Short );
if( EnableBuy ) {
priceAtBuy = ValueWhen( Buy, BuyPrice );
highsinceBuy = HighestSince( Buy, High );
stoplevel = priceAtBuy + ( highsinceBuy - priceAtBuy ) * ( 100 - riskSize ) / 100;
priceAtBuy = IIf(IsEmpty(barShort), priceAtBuy, Null);
highsinceBuy = IIf(IsEmpty(barShort), highsinceBuy, Null);
stoplevel = IIf(IsEmpty(barShort), stoplevel, Null);
Plot( stoplevel, "\n\nBuy - stop", colorRed, styleDashed );
Plot( highsinceBuy, "highsinceBuy", colorBlue, styleDashed );
Plot( priceAtBuy, "priceAtBuy", colorBlue, styleDashed );
Plot( barBuy, "BuyBars", colorDefault, styleNoline | styleNolabel | styleOwnScale);
}
if( EnableShort ) {
priceAtShort = ValueWhen( Short, ShortPrice );
LowestSinceShort = LowestSince( Short, Low );
stoplevel = priceAtShort - ( priceAtShort - LowestSinceShort) * ( 100 - riskSize ) / 100;
Plot( stoplevel, "\n\nShort - stop", colorRed, styleDashed );
Plot( LowestSinceShort, "LowestSinceShort", colorBlue, styleDashed );
Plot( priceAtShort, "priceAtShort", colorBlue, styleDashed );
Plot( barShort, "ShortBars", colorDefault, styleNoline | styleNolabel | styleOwnScale);
}
PlotShapes( Buy*shapeUpArrow, colorGreen, 0, Low );
PlotShapes( IIf( Sell, shapeDownArrow, shapeNone ), colorRed, 0, High );
PlotShapes( Short*shapeDownArrow, colorBlue, 0, High );
PlotShapes( IIf( Cover, shapeUpArrow, shapeNone ), colorLightBlue, 0, Low );