I'm struggling to figure out how to partially close open trades in pinescript in tradingview based on different conditions. I am trying to partially close trades with size pos_size2
using strategy.order
conditional upon the following: -sell 50% conditional upon long_stop2
-sell remaining 50% conditional upon long_stop1
Any help would be appreciated.
// LONG
//my_margin = strategy.equity * margin_pct
//pos_size = (my_margin * leverage) / price
//pos_size2 = (my_margin * leverage2) / price
//symbol = security(syminfo.tickerid, resolution, close)
//percent = input(defval=50.0, title='Percentage of position to take profit.')
//size_trim = (pos_size2 / 2)
//Open Order
entry = 0
if trendhi_ema > trendlo_ema
entry:=2
strategy.entry(id='Long Signal', long=true, qty=pos_size2, when= window() and long_signal, comment = "2.5x Long")
else
entry:=1
strategy.entry(id='Long Signal', long=true, qty=pos_size, when= window() and long_signal, comment = "1.5x Long")
//Close Order
if trendhi_ema > trendlo_ema
if entry == 2
strategy.order(id='Long Signal', long=false, qty=size_trim, when= window() and long_stop2 and strategy.position_size > 0, comment = "close first 50% long")
strategy.order(id='Long Signal', long=false, qty=size_trim, when= window() and long_stop1 and strategy.position_size > 0, comment = "close second 50% long")
if entry == 1
strategy.order(id='Long Signal', long=false, qty=pos_size, when= window() and long_stop2 and strategy.position_size > 0, comment = "close long")
else
strategy.order(id='Long Signal', long=false, qty=pos_size, when= window() and long_stop2 and strategy.position_size > 0, comment = "close")
The id
parameter is important. Use same id
when you want to MODIFY a strategy.***
command parameters. Use different id
if you want to specify different commands.
//Close Order
if trendhi_ema > trendlo_ema
if entry == 2
strategy.order(id='Long Signal 1', long=false, qty=size_trim, when= window() and long_stop2 and strategy.position_size > 0, comment = "close first 50% long")
strategy.order(id='Long Signal 2', long=false, qty=size_trim, when= window() and long_stop1 and strategy.position_size > 0, comment = "close second 50% long")
if entry == 1
strategy.order(id='Long Signal 3', long=false, qty=pos_size, when= window() and long_stop2 and strategy.position_size > 0, comment = "close long")
else
strategy.order(id='Long Signal 4', long=false, qty=pos_size, when= window() and long_stop2 and strategy.position_size > 0, comment = "close")
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.