Search code examples
pine-scripttrading

Sometimes the take profit is reached but the strategy could open another trade and take another take profit


I have a problem with my script, to optimize the gains, I would like to put a take profit and a stop loss (which I have already done in the script)

The problem is that sometimes, the take profit is reached but the strategy could open another trade and take another take profit ( see the screens )

I would like to know how to tell him that.

If the take profit is reached, but the conditions (long or short) are still good open another trade.

Thanks in advance to those who will help me.

I put the strategy below, if you want to enjoy it. I am currently testing it on SOLUSDT in 30m

Screen

//@version=5
strategy("VortexStrategyEMA", overlay=true,  initial_capital = 1000, default_qty_type=strategy.percent_of_equity, default_qty_value=100)


AlerteBuy = input("Alerte BUY")
AlerteSell = input("Alerte SELL")
AlerteCloseBuy = input("Alerte CLOSE BUY")
AlerteCloseSell = input("Alerte CLOSE SELL")

//EMA

longer = (ta.ema(close, 100))
longest = (ta.ema(close, 200))
plot(longer, title="EMA100", color=#2962FF)
plot(longest,title="EMA200", color=#E91E63)
emahigh = (ta.ema(high,14))
emalow = (ta.ema(low,14))

//Vortex 

period_ = input.int(200, title="Length", minval=2)
VMP = math.sum( math.abs( emahigh - emalow[1]), period_ )
VMM = math.sum( math.abs( emalow - emahigh[1]), period_ )
STR = math.sum( ta.atr(1), period_ )
VIP = VMP / STR
VIM = VMM / STR
emaVIP = (ta.ema(VIP, 14))
emaVIM = (ta.ema(VIM, 14))
plot(VIP, title="VI +", color=#2962FF)
plot(VIM, title="VI -", color=#E91E63)

//ConditionsLONG

EMALONG = longer > longest
VortexLONG = ta.crossover(VIP,VIM)
LONG = VortexLONG and EMALONG

//ConditionsSHORT
 
EMASHORT = longer < longest
VortexSHORT = ta.crossunder(VIP,VIM)
SHORT = VortexSHORT and EMASHORT

//Strategy

strategy.entry("Long", strategy.long, when=LONG, comment="Long" ,  alert_message = AlerteBuy)
strategy.entry("Short", strategy.short, when=SHORT, comment="Short" ,   alert_message = AlerteSell)


stopPer = input(5, title='Stop Loss %') / 100
takePer = input(10, title='Take Profit %') / 100


// Determine where you've entered and in what direction
shortStop = strategy.position_avg_price * (1 + stopPer)
shortTake = strategy.position_avg_price * (1 - takePer)

longStop = strategy.position_avg_price * (1 - stopPer)
longTake = strategy.position_avg_price * (1 + takePer)


if strategy.position_size < 0
    strategy.exit(id='Close Short', stop=shortStop, limit=shortTake,   alert_message = AlerteCloseSell)
    

if strategy.position_size > 0
    strategy.exit(id='Close Long', stop=longStop, limit=longTake, alert_message = AlerteCloseBuy)

Solution

  • You can change the conditions of vortex long and short from crossover and cross under to direct comparison like below

    VortexLONG = (VIP>VIM)
    

    and

    VortexSHORT = VIP<VIM
    

    Then it will reenter the trade after exit