我正在尝试为我的策略创建多个止损/获利者。但是,一旦添加了第二个头寸(例如 2 个多头(但可以是无限多头或空头)),设置为入场蜡烛低点的止损参数将移动到第二个多头头寸入场蜡烛的低点,导致我同时被阻止出两个位置。目标是为每个交易信号设置独立的止损和利润目标。我对 java 的了解很少,建议使用带有数组的计数器之类的东西来存储值,但我不清楚它是如何完成的,过去几个小时的试验并没有让我走得太远。任何帮助或方向都会很棒,如果您需要更多详细信息,请告诉我。这是我当前的代码,只有一个止损/获利单:
strategy("My Script"), overlay=true
//filters
timezone = input(title="Timezone", type=input.session, defval="0950-1500")
days = input(title="Days To Trade", defval="23456")
inSession(sess) => na(time(timeframe.period, sess + ":" + days)) == false
//identify engulfing candle
bullishEC = close >= high[1] and close[1] < open[1]
bearishEC = close <= low[1] and close[1] > open[1]
//get ema user input
emaLength1 = input(title="EMA 1 Length", type=input.integer, defval=110)
//get ema
ema1 = ema(close, emaLength1)
//plot ema
plot(ema1, color=close > ema1 ? color.green : color.red, linewidth=2)
//macd parameter
[macdline, signalline, macdhist] = macd(close, 12,26,9) //built in function
bearishM = macdline < signalline
bullishM = macdline > signalline
tradeSignal = ((close >= ema1) and bullishEC) or ((close < ema1) and bearishEC)
plotshape(tradeSignal and bearishEC and bearishM and barstate.isconfirmed and
inSession(timezone), title="bearish", location=location.abovebar, color=color.red,
style=shape.triangledown, text="Sell")
plotshape(tradeSignal and bullishEC and bullishM and barstate.isconfirmed and
inSession(timezone), title="bullish", location=location.belowbar, color=color.green,
style=shape.triangleup, text="Buy")
alertcondition(tradeSignal and bullishEC and bullishM, title="BUY SIGNAL", message="GO LONG
on {{ticker}}")
alertcondition(tradeSignal and bearishEC and bearishM, title="SHORT SIGNAL", message="GO SHORT
on {{ticker}}")
//setting stop & targets for current trade
var shortStopPrice = 0.0
var shortTargetPrice = 0.0
var shortStopDistance = 0.0
var longStopPrice = 0.0
var longTargetPrice = 0.0
var longStopDistance = 0.0
if (tradeSignal and bullishEC and bullishM and barstate.isconfirmed and inSession(timezone))
longStopPrice := low
longStopDistance := close - longStopPrice
longTargetPrice := close + (longStopDistance * 2)
strategy.entry(id="long", long=strategy.long)
if (tradeSignal and bearishEC and bearishM and barstate.isconfirmed and inSession(timezone))
shortStopPrice := high
shortStopDistance := shortStopPrice - close
shortTargetPrice := close - (shortStopDistance * 2)
strategy.entry(id="short", long=strategy.short)
//exit trade when stop or target is hit
strategy.exit("id=exit", from_entry="short", limit=shortTargetPrice, stop=shortStopPrice)
strategy.exit("id=exit", from_entry="long", limit=longTargetPrice, stop=longStopPrice)
//@version=4