简体   繁体   中英

coding a take profit on pinescript

I am having trouble coding a take profit for my strategy.

I have a trailing stop loss.

I want my take profit to be twice as large as the difference between my entry point and my stop loss at time of entry to have a risk reward of. so once I enter a trade I want my take profit to be fixed and my stop loss to be trailing.

problem: the way I coded the script, my take profit is also moves in tandem with my stop loss which I want to avoid.

//SL_TP
ss_low = math.min(senkouA[ss_offset - 1], senkouB[ss_offset - 1])
stoploss_long = ss_low
profit_long = (strategy.position_avg_price - ss_low) * 2 + strategy.position_avg_price

ss_low will change with each bar, therefore your take profit level will also change. Create a var variable and store your SL level when you enter the trade. Then use it in your TP calculations.

Something like this should work:

var float sl_at_entry = na
is_new_position = (strategy.position_size[1] != strategy.position_size)    // This will only be true on the bar of the entry
sl_at_entry := is_new_position ? math.min(senkouA[ss_offset - 1], senkouB[ss_offset - 1]) : sl_at_entry // Only update the value if it is a new position. Keep the old value otherwise
profit_long = (strategy.position_avg_price - sl_at_entry) * 2 + strategy.position_avg_price

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