修剪位置在pine脚本中不起作用

时间:2019-09-16 09:50:40

标签: pine-script

我创建了一个基于指标进行买卖的策略。购买后,它将按照SAR进行止损。该策略将设置为每隔一个执行一次。

这部分工作正常。

但是我还有一个条件,那就是当满足某些条件时我平仓一半。但是,该策略会在每个报价周期都平仓剩余仓位的一半,直到平仓为止。

我尝试使用position_size变量对照初始位置检查剩余位置,并引入了一个bool变量来指示已经进行了修剪,但是它不起作用。

我该怎么做才能阻止策略完全平仓?

strategy("MyStrategy", overlay=true, calc_on_every_tick=true, 
          commission_type=strategy.commission.percent, commission_value=0.075, slippage=2)
...
bool trim = na
if TDUp == 9 and not trim and high > strategy.position_avg_price and strategy.opentrades >= 
        strategy.opentrades[max(0, barssince(Buy)-1)]
    // this shall execute only once, but it is executed every tick
    strategy.order("triml", false, qty=abs(strategy.position_size / 2))
    trim = true

if TDDn == 9 and not trim and low < strategy.position_avg_price and strategy.opentrades <= 
        strategy.opentrades[max(0, barssince(Sell)-1)]
    // this shall execute only once, but it is executed every tick
    strategy.order("trims", true, qty=abs(strategy.position_size / 2))
    trim = true

1 个答案:

答案 0 :(得分:0)

应该更像这样。您目前正在本地trim块中重新声明一个新的本地if变量。要在声明现有变量后更改其值,需要使用:=

//@version=4
study("My Script")
bool trim = false
if TDUp == 9 and not trim and high > strategy.position_avg_price and strategy.opentrades >= 
        strategy.opentrades[max(0, barssince(Buy)-1)]
    // this shall execute only once, but it is executed every tick
    strategy.order("triml", false, qty=abs(strategy.position_size / 2))
    trim := true

if TDDn == 9 and not trim and low < strategy.position_avg_price and strategy.opentrades <= 
        strategy.opentrades[max(0, barssince(Sell)-1)]
    // this shall execute only once, but it is executed every tick
    strategy.order("trims", true, qty=abs(strategy.position_size / 2))
    trim := true