简体   繁体   中英

Trimming position is not working in pine script

I've created a strategy that buys and sells based on an indicator. After buying it will follow te SAR for stop-loss. the strategy is set to execute every tick.

This parts works fine.

I have however one more condition and that is that I close half the position when certain conditions are met. However, the strategy keeps closing half the remaining position every tick, until the complete position is closed.

I've tried to use the position_size variable to check the remaining position against the initial position and also introduced a bool variable to indicate that trimming has been taken place, but it is not working.

What can I do to stop the strategy from completely closing the position?

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

Should be something more like this. You are currently redeclaring a new, local trim var within local if block. Need to use := when you want to change an existing variable's value after it has already been declared.

//@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM