Bucharest + Romania
Posts: 2 since Jul 2013
Thanks Given: 0
Thanks Received: 0
|
Hi guys,
I'm having an issue with a strategy here. I'm using a volatility based trailing stop similar to the chandelier stop. While backtesting i saw that the strategy records entering and exiting at the calculated stop price instead of the closed candle price.
In other words although the strategy waits for the candle to close before exiting and reversing, it records doing so at the stop price and not the actual closed candle price.
Where am i going wrong with the code here?
Thanks guys.
# Input Declarations:
#
input mult = 3.0; #Multiple of Average True Range to use
input length = 10; #Average True Range period
#
# Input to select Close or High/Low for switching:
#
input Style = {default Close, HighLow};
def type;
switch (Style){
case Close:
type = 1;
case HighLow:
type = 0;
}
#
# Set parameters based on switch selection:
#
def uu = if type then close else high;
def ll = if type then close else low;
def na = Double.NaN;
#
# Calculate average range for volatility:
#
def atr = ExpAverage(high - low, length);
#
# Calculate initial short and long volatility stop values:
#
def svs = low + Ceil(mult * atr / TickSize()) * TickSize();
def lvs = high - Ceil(mult * atr / TickSize()) * TickSize();
#
# Set up the trailing stop logic:
#
rec shortvs = if IsNaN(shortvs[1]) then svs else if uu > shortvs[1] then svs else Min(svs, shortvs[1]);
rec longvs = if IsNaN(longvs[1]) then lvs else if ll < longvs[1] then lvs else Max(lvs, longvs[1]);
#
# Detect if we breached the trailing stop (close or high/low):
#
def longswitch = if uu >= shortvs[1] and uu[1] < shortvs[1] then 1 else 0;
def shortswitch = if ll <= longvs[1] and ll[1] > longvs[1] then 1 else 0;
#
# This logic remembers the direction and changes when needed:
#
rec direction = CompoundValue(1, if IsNaN(direction[1]) then 0 else
if direction[1] <= 0 and longswitch then 1
else if direction[1] >= 0 and shortswitch then -1
else direction[1], 0);
#
# Set up the two plots. "na" makes the current value disappear
# if we're trading in the opposite direction:
#
def short = if direction > 0 then na else shortvs;
def long = if direction < 0 then na else longvs;
def stopout = if direction[1] < 0 and direction > 0 then 1 else 0;
def stopprice = shortvs[1];
AddOrder(OrderType.BUY_TO_CLOSE, stopout, stopprice);
I also have another separate script for the opposite side running them both at the same time.
def stopout = if direction[1] > 0 and direction < 0 then 1 else 0;
def stopprice = longvs[1];
AddOrder(OrderType.SELL_TO_CLOSE, stopout, stopprice);
|