【问题标题】:Stop Loss function does not work in my Strategy Tester止损功能在我的策略测试器中不起作用
【发布时间】:2021-11-11 18:00:51
【问题描述】:

在下面的空头策略测试器中,测试器可以打开空头头寸。如果头寸获利,“止盈止损”就可以了。但不知何故,如果头寸亏损,止损不起作用。有人能告诉我我错过了什么吗?我为 LONG 头寸编写了相同的代码,它没有问题。但相同的止损代码不适用于空头头寸。非常感谢您的支持

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")```



【问题讨论】:

  • 这与 Python 有什么关系?
  • 对不起,我的错 :(

标签: pine-script trailing


【解决方案1】:

尝试用这个替换你的 short is active 变量:

bool ShortIsActive = startShortDeal 或 strategy.position_size

我注意到您的 > 符号是向后的,这使您的止损无法识别策略何时做空。

祝你交易和编码我的朋友好运!

【讨论】:

  • 你是英雄 :) 非常感谢
  • 不客气!接受答案即可关闭工单
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
  • 2022-08-23
  • 1970-01-01
  • 2013-05-29
相关资源
最近更新 更多