'PineScript Strategy not opening and closing positions

My position doesnt open and close positions sometimes.

It should open long positions when three conditions are valid:

  • the 50 EMA is above the 200 EMA (Seen with the green cloud inbetween them)
  • the blue line (%k or in the strategy just k) of the stoch indicator crosses above the orange one (%d or in the strategy just d)
  • the k and d of the stochastic indicator both have been under 20 the candle before

it should exit the position at a take profit which is the entry price plus 0.25% profit or at a stop loss which is the entry price minus 0.2% loss

I think the strategy doesnt open positions because there is already a position open but i dont understand why the old position doesnt close

here is an image of when the strategy should open positions but doesnt: https://i.stack.imgur.com/Xttlf.png

i havent found anything regarding this problem anywhere so help here would be great as i am still a beginner in pinescript and programming in general

this is the code of my strategy:

// © justFred_

//@version=5
strategy("2x EMA + Stochastic", overlay=true, margin_long=100, margin_short=100)





//EMA

len1 = input(defval=50, title="Length", group="EMA 1")
src1 = input(close, title="Source", group="EMA 1")
ema1 = ta.ema(src1, len1)

len2 = input(defval=200, title="Length", group="EMA 2")
src2 = input(defval=close, title="Source", group="EMA 2")
ema2 = ta.ema(src2, len2)



//Stochastic

periodK = input.int(5, title="%K Length", minval=1, group="Stochastic")
smoothK = input.int(3, title="%K Smoothing", minval=1, group="Stochastic")
periodD = input.int(3, title="%D Smoothing", minval=1, group="Stochastic")
k = ta.sma(ta.stoch(close, high, low, periodK), smoothK)
d = ta.sma(k, periodD)



//Conditions

longEMA = ema1 > ema2
shortEMA = ema1 < ema2

longstochcross = ta.crossover(k,d)
shortstochcross = ta.crossunder(k,d)

longstochvalue = k[1] < 20 and d[1] < 20
shortstochvalue = k[1] > 80 and d[1] > 80



//Entry

longCondition = longEMA and longstochcross and longstochvalue
if (longCondition)
    strategy.entry("long", strategy.long)

shortCondition = shortEMA and shortstochcross and shortstochvalue
if (shortCondition)
    strategy.entry("short", strategy.short)



//Exit

if longCondition = true
    takeprofitlong = strategy.position_avg_price * 1.0025
if longCondition = true
    stoplosslong = strategy.position_avg_price * 0.998

if shortCondition = true
    takeprofitshort = strategy.position_avg_price * 0.9975
if shortCondition = true
    stoplossshort = strategy.position_avg_price * 1.002

strategy.cancel("long", when = close > takeprofitlong)
strategy.cancel("long", when = close < stoplosslong)

strategy.cancel("short", when = close < takeprofitshort)
strategy.cancel("short", when = close > stoplossshort)```


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source