TradingView Pine 脚本突破策略 - 问题相同柱收盘

问题描述 投票:0回答:1

我在 Pine Script 中构建了突破策略:

  • 如果当前柱的收盘价高于最后 100 根柱的最高点,则做多
  • 如果当前柱的收盘价低于最后 50 根柱的最低价,则做空
  • 我添加了 25 个基点的止盈
  • 同一方向不能连续进行两笔交易

因此,如果触及多头头寸的止盈位,则会平仓并等待空头信号。如果没有达到止盈位,则在出现空头信号时交易会反转。对于空头交易反之亦然。它运作良好,除非该策略由于止盈而在同一柱进入并平仓。如果多头/空头条件有效,则它会在相同方向上打开新交易(见下面的屏幕截图)。

我不知道如何避免这种情况。我已经尝试了与strategy.opentrades.*、*profit、bar_index变量等的几种组合。试图检查最后一个柱是否是止盈或者最后一个止盈和新条目之间有多少个柱,但我无法计算得出正确的组合。或者也许有更简单的方法。

这是代码:

//@version=5

strategy(title="Breakout", overlay = true, process_orders_on_close = false)
periodhh = input(100)
periodll = input(50)
reverse = input(false, title="Trade reverse")
hh = ta.highest(periodhh)
ll = ta.lowest(periodll)

pos=0
pos :=  close > hh[1] ? 1 : close < ll[1] ? -1 : nz(pos[1], 0)

if (pos==1 and pos[2]!=1)
    strategy.entry("Long", strategy.long)
    strategy.exit("Take Profit", profit=25)
    
if (pos==-1 and pos[2]!=-1)
    strategy.entry("Short", strategy.short)   
    strategy.exit("Take Profit", profit=25)

enter image description here

pine-script pine-script-v5 tradingview-api trading algorithmic-trading
1个回答
0
投票

回到pos的柱数,应该是1

if (pos==1 and pos[1]!=1)

尝试:

//@version=5

strategy(title="Breakout", overlay = true, process_orders_on_close = false)
periodhh = input(100)
periodll = input(50)
reverse = input(false, title="Trade reverse")
hh = ta.highest(periodhh)
ll = ta.lowest(periodll)

pos=0
pos :=  close > hh[1] ? 1 : close < ll[1] ? -1 : nz(pos[1], 0)

if (pos==1 and pos[1]!=1)
    strategy.entry("Long", strategy.long)
    strategy.exit("Take Profit", profit=25)
    
if (pos==-1 and pos[1]!=-1)
    strategy.entry("Short", strategy.short)   
    strategy.exit("Take Profit", profit=25)

plot (
   hh,
  'hh',
  linewidth      = 2,
  color          = color.new(color.gray, 0),
  style          = plot.style_line)
plot (
   ll,
  'll',
  linewidth      = 2,
  color          = color.new(color.silver, 0),
  style          = plot.style_line)
plot(
   pos,
  "pos",
  editable = false, display = display.data_window)

test

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.