How to Keep two long and short opposed positions open in tradingview pinescript?

Viewed 1810

this is a simple code to show you what I mean, there are stop losses for both long and short positions but the problem is that I want to be able to open short positions without closing the already opened long position. as you've probably guessed, I want to test this strategy when the market is tight and you could make profit on, either way, it just needs two accounts.

strategy("bothways", overlay=true)

leverage=input(5,"leverage",step=.25)
partoftrade=input(1,"partoftrade",step=.01)
StoplosssS=input(0.025,"StopLOSS SHORT",step=0.001)
StoplosssL=input(0.025,"StopLOSS LONG",step=0.001)
pertpS = input(0.02,"TP Short",step=0.01)
pertpL = input(0.02,"TP Long",step=0.01)
narrow=bbw(open,20,2)<0.005
red=open>close
green=open<close
longCondition = narrow and green
if (longCondition and strategy.opentrades<2)
    strategy.entry("L", strategy.long,qty=(strategy.equity/1)*partoftrade*leverage/open,oca_name="ocg",oca_type=strategy.oca.cancel)
strategy.exit("LE",from_entry="L",profit=close*pertpL/syminfo.mintick,loss=open*StoplosssL/syminfo.mintick,oca_name="ocg")

shortCondition = narrow and red
if (shortCondition and strategy.opentrades<2)
    strategy.entry("S", strategy.short,qty=(strategy.equity/1)*partoftrade*leverage/open,oca_name="ocg",oca_type=strategy.oca.reduce)
strategy.exit("SE",from_entry="S",profit=close*pertpS/syminfo.mintick,loss=open*StoplosssS/syminfo.mintick,oca_name="ocg")    

thanks for help

2 Answers

You can seperate them into two different command files of course. I know this answer will not satisfy you, I tried my best to beat it.. but just think about one thing... profitability.

[ Although, imho... I would suggest checking out the 'contracts held' row in the strategy summary for each positions and choosing the most lucrative one. Imagine you enter these orders to your exchange. Your 2 longs will buy the contract. And when you want to short it, it will go for what you have in your pocket first, and give you an option to borrow that contract or go margin selling only when you don't have it in your portfolio. So they cancel each other out if they are not consequential but interwoven (when you have blue longs and red shorts in the same place before each one close) ]

Have you tried strategy.order command? and you can provide a condition for the strategy.order command to run till a specific position size is achieved for the multiple longs.

if BuyCallSignal and strategy.position_size == 1
    strategy.order("ABCall",  strategy.long ,  when = long, qty = 1)
Related