首页 > 解决方案 > 自条件 x 以来仅使用条形数据计算函数

问题描述

是否可以让函数在条件后开始计算,仅使用条件后的条形数据?比方说| sma1= sma(close,20)| 我想仅使用自策略输入以来过去的柱线来计算 sma1。因此,在这种情况下sma1,我们甚至在距离策略输入栏 20 个柱之前都不会绘图。然后情节将在策略退出位置后消失,并在下一个策略进入后重新开始重新计算。我想用它来绘制和触发位置变化。

这不起作用,我有点理解为什么,但想知道是否有办法解决它。它只是进入和退出条件来测试这个想法直到降低

open_long  = strategy.position_size > 0
open_short = strategy.position_size < 0

//Entry MA's
fast_ma = sma(close,10)
slow_ma = sma(close,20)

ma_long = crossover(fast_ma ,slow_ma)
ma_short =  crossover(slow_ma ,fast_ma)

//EntryRSI
rsi = rsi(close,14)

rsi_long  = rsi[1] > 50
rsi_short = rsi[1] < 50

//Exit RSI
exit_long  = crossunder(rsi,50)
exit_short = crossover(rsi,50)

//strategy
if ma_long and rsi_long
    strategy.entry("Long", strategy.long)
if ma_short and rsi_short
    strategy.entry("Short", strategy.short)

if open_long and exit_long
    strategy.close("Long")
if open_short and exit_short
    strategy.close("Short")



//This is where my issue is 

x = input(10,"Variable Length")
y = 0

// if not in a position and bars since position is equal to length of MA
if strategy.position_size != 0 and barssince(strategy.position_size == 0) == x
    y := x

var_ma = sma(close,y)

plot(var_ma)

标签: pine-script

解决方案


我的朋友这个怎么样?如果系列为 na,我们可以有条件地设置绘图并使用 plot.style_linebr 停止绘图。我也将条形更改为 >= 长度。

//@version=4
strategy("My Strategy", overlay=true, margin_long=100, margin_short=100)

open_long  = strategy.position_size > 0
open_short = strategy.position_size < 0

//Entry MA's
fast_ma = sma(close,10)
slow_ma = sma(close,20)

ma_long = crossover(fast_ma ,slow_ma)
ma_short =  crossover(slow_ma ,fast_ma)

//EntryRSI
rsi = rsi(close,14)

rsi_long  = rsi[1] > 50
rsi_short = rsi[1] < 50

//Exit RSI
exit_long  = crossunder(rsi,50)
exit_short = crossover(rsi,50)

//strategy
if ma_long and rsi_long
    strategy.entry("Long", strategy.long)
if ma_short and rsi_short
    strategy.entry("Short", strategy.short)

if open_long and exit_long
    strategy.close("Long")
if open_short and exit_short
    strategy.close("Short")



//This is where my issue is 

x = input(10,"Variable Length")

// if not in a position and bars since position is equal to length of MA
cond = strategy.position_size != 0 and barssince(strategy.position_size == 0) >= x

var_ma = sma(close,x)

plot(cond ? var_ma : na, style=plot.style_linebr)

推荐阅读