0

In below Short position strategy tester, the tester opens the short position which is fine. If position makes a profit, "Take profit trailing stop" works just fine. But somehow if position makes a loss, STOP LOSS does not work. Can someone tell me what am I missing? I wrote the same code for LONG position and it works with no issue. but the same stop loss code does not work on short position. Many many thanks in advance for your support

strategy("WILLIAMS-R + ZERO LAG MACD SHORT POSITION TRAILING TAKE PROFIT STRATEGY", shorttitle="WILLIAMS-R + ZERO LAG MACD SHORT POSITION TRAILING TAKE PROFIT STRATEGY", overlay=true, initial_capital=1000, default_qty_value=1000, currency=currency.USD, pyramiding=1)
source = close
fastLength = input(12, title="Fast MM period", minval=1)
slowLength = input(26,title="Slow MM period",  minval=1)
signalLength =input(9,title="Signal MM period",  minval=1)
MacdEmaLength =input(9, title="MACD EMA period", minval=1)
useEma = input(true, title="Use EMA (otherwise SMA)")
useOldAlgo = input(false, title="Use Glaz algo (otherwise 'real' original zero lag)")
length = input(title="Length", type=input.integer, defval=10)
src = input(close, "Source", type = input.source)
longupperline = input(title="Long Signal Upper Threshold:", type=input.integer, defval=-70)
longlowerline = input(title="Long Signal Lower Threshold:", type=input.integer, defval=-90)
shortupperline = input(title="Short Signal Upper Threshold:", type=input.integer, defval=-10)
shortlowerline = input(title="Short Signal Lower Threshold:", type=input.integer, defval=-30)
ma1= useEma ? ema(source, fastLength) : sma(source, fastLength) 
ma2 = useEma ?  ema(ma1,fastLength) :  sma(ma1,fastLength) 
zerolagEMA = ((2 * ma1) - ma2)
mas1=  useEma ? ema(source , slowLength) :  sma(source , slowLength)
mas2 =  useEma ? ema(mas1 , slowLength): sma(mas1 , slowLength)
zerolagslowMA = ((2 * mas1) - mas2)
ZeroLagMACD = zerolagEMA - zerolagslowMA 
emasig1 = ema(ZeroLagMACD, signalLength)
emasig2 = ema(emasig1, signalLength)
signal = useOldAlgo ? sma(ZeroLagMACD, signalLength) : (2 * emasig1) - emasig2

hist = ZeroLagMACD - signal

_pr(length) =>
    max = highest(length)
    min = lowest(length)
    100 * (src - max) / (max - min)
percentR = _pr(length)


ShortTakeProfitPerc = input(defval = 5.0, title = 'Take Profit %', type = input.float, minval = 0.1, step = 0.1, tooltip = "The percentage of the price increase to set the take profit price target.", group = "Strategy") / 100

enableTrailing = input(defval = true, title = "Enable Trailing", type = input.bool, tooltip = "Enable or disable the trailing for take profit.", group = "Strategy")
trailingTakeProfitDeviationPerc = input(defval = 1.0, title = "Trailing Take Profit Deviation %", type = input.float, minval = 0.05, maxval = 100, step = 0.05, tooltip = "The step to follow the price when the take profit limit is reached.", group = "Strategy") / 100


// Set stop loss level with input options (optional)
shortLossPerc = input(title="Short Stop Loss (%)",
     type=input.float, minval=0.0, step=0.1, defval=1) * 0.01


ShortStopPrice = strategy.position_avg_price * (1 + shortLossPerc)


// BACKTEST PERIOD INPUT ============================================================================================
fromDate = input(defval = timestamp("01 Jan 2021 00:00 UTC"), title = "From Date", type = input.time, minval = timestamp("01 Jan 1970 00:00 UTC"), group = "Backtest Period") // backtest start date
toDate   = input(defval = timestamp("31 Dec 2121 23:59 UTC"), title = "To Date",   type = input.time, minval = timestamp("01 Jan 1970 00:00 UTC"), group = "Backtest Period") // backtest finish date

isWithinBacktestPeriod() =>
    time >= fromDate and time <= toDate ? true : false // create function "within window of time"

// SHOW PLOT INPUT ==================================================================================================
showDate = input(defval = true, title = "Show Backtest Range", type = input.bool, group = "Plot", tooltip = "Gray out the backround of the backtest period.")


// STRATEGY =========================================================================================================

startShortDeal = percentR<-10 and percentR>-30 and crossunder(hist, 0)

bool ShortIsActive = startShortDeal or strategy.position_size > 0

float ShortTakeProfitPrice = na
ShortTakeProfitPrice := if (isWithinBacktestPeriod() and ShortIsActive)
    nz(ShortTakeProfitPrice[1], close * (1 - ShortTakeProfitPerc))
else
    na

ShortTrailingTakeProfitStepTicks = ShortTakeProfitPrice * trailingTakeProfitDeviationPerc / syminfo.mintick


// STRATEGY EXECUTION ===============================================================================================

if (isWithinBacktestPeriod())
    // getting into SHORT position
    strategy.entry("Short Entry", strategy.short, when=startShortDeal, alert_message = "short("  + syminfo.ticker + "): Started")
    // submit exit orders for trailing take profit price
    strategy.exit(id ="Short exit", stop=ShortStopPrice, limit = enableTrailing ? na : ShortTakeProfitPrice, trail_price = enableTrailing ? ShortTakeProfitPrice : na, trail_offset = enableTrailing ? ShortTrailingTakeProfitStepTicks : na, when = ShortIsActive, alert_message = "Short(" + syminfo.ticker + "): Take Profit activated")```



Michael Butscher
  • 10,028
  • 4
  • 24
  • 25
Ovgu Sayan
  • 11
  • 1

1 Answers1

1

Try replacing your short is active variable with this:

bool ShortIsActive = startShortDeal or strategy.position_size < 0

I noticed your > sign was backwards, which wasn't allowing your stop to recognize when the strategy was short.

Best of luck with your trading and coding my friend!

Bjorgum
  • 2,054
  • 2
  • 4
  • 11