Pine Script: Short position automatically closed when next long position triggered even though the TP/SL is not met yet

Viewed 41

Good day everyone, I need some help with the pine script below. From the strategy result, the majority of the trades look correct, eg: long associated with close long or short associated with close short, but there're some trades having such conditions: entry with short position but automatically closed when next long position triggered (TP and SL haven't been met yet). Does anyone know what's the issue here? Thank you.

pc=input.int(title="tpsl percent",defval=6)/100
adx_val=input.int(title="adx_val",defval=50)
k_val=input.int(title="k_val",defval=20)
d_val=input.int(title="d_val",defval=20)
longTP_pc  = strategy.position_avg_price*(1+pc)
longSL_pc  = strategy.position_avg_price*(1-pc)
ordersize=1000/close
 
longCondition = k<=k_val and d<=d_val and ta.crossover(k,d)

if (longCondition)
    strategy.entry("Long", strategy.long, ordersize)

if strategy.position_size > 0                                               
    strategy.exit(id="close long",limit=longTP_pc, stop=longSL_pc)

shortCondition = k>=(100-k_val) and d>=(100-d_val) and ta.crossunder(k,d)

if (shortCondition)
    strategy.entry("Short", strategy.short,ordersize)

if strategy.position_size < 0 
    strategy.exit(id="close short",limit=longSL_pc, stop=longTP_pc)
1 Answers

In comparison to the function strategy.order, the function strategy.entry is affected by pyramiding and it can reverse market position correctly.

Reference
This means that if you use eg.: strategy.entry('Long entry', strategy.long) you don't need to take care about the exact position size if you want to close all of those and open a counter entry with strategy.entry('Short entry', strategy.short). The short entry automatically closes all your long entries and opens the short.

The definition also offers you the solution:
You need strategy.order() instead of "entry".

if longCondition
    strategy.order("Long", strategy.long, ordersize)
                                           
strategy.exit(id="close long", "Long", limit=longTP_pc, stop=longSL_pc) // closes from "Long"
...
if shortCondition
    strategy.order("Short", strategy.short, ordersize) // does not close "Long"

strategy.exit("close short", "Short", limit=longSL_pc, stop=longTP_pc) // closes from "Short"

Related