Trades won't close at set stop and profit level

15 Views Asked by At

I am creating a simple long/short pinescript.

I want my long trades to close with +6% profit and close when -4% in loss. For my shorts I want it to close with +3% profit and when -2% in loss.

Current code does not work, for example the current open long position has 9% profit while it should have been closed at +6%. I have no idea why this is the case. Can some one look at the exit code?

//@version=4
strategy("Long/Short", shorttitle="LS 10 DMA", overlay=true)

// Configure backtest start date with inputs
startDate = input(title="Start Date", type=input.integer,
     defval=1, minval=1, maxval=31)
startMonth = input(title="Start Month", type=input.integer,
     defval=1, minval=1, maxval=12)
startYear = input(title="Start Year", type=input.integer,
     defval=2022, minval=1800, maxval=2100)

     // See if this bar's time happened on/after start date
afterStartDate = (time >= timestamp(syminfo.timezone,
     startYear, startMonth, startDate, 0, 0))

length = input(10, minval=1, title="DMA Length")
price = close
dma = ema(price, length)

////////////////////////////// ###################### RSI 
// Invoerparameters voor de RSI berekening
lengthrsi = input(14, title="Lengte")
src = input(close, title="Bron")

// RSI berekening
rsiValue = rsi(src, lengthrsi)

// Variabele toewijzing
var float myRsiValue = na
myRsiValue := rsiValue


////////////////////////////// ###################### CCI 
// Invoerparameters voor de CCI berekening
lengthcci = input(20, title="Lengte cci")
srccci = input(close, title="Bron cci")

// CCI berekening
typicalPrice = (high + low + close) / 3
meanDeviation = sma(abs(typicalPrice - sma(typicalPrice, lengthcci)), lengthcci)
cciValue = (typicalPrice - sma(typicalPrice, lengthcci)) / (0.015 * meanDeviation)


////////////////////////////// ###################### Conditions 
openLong = strategy.position_size > 0
longconditions = (crossover(close, dma) and cciValue > 1)
shortconditions = (crossunder(close, dma) and cciValue < -1)

if ( longconditions and afterStartDate )
    strategy.entry("Long", strategy.long)


if ( shortconditions and afterStartDate )
    strategy.entry("Short", strategy.short)
    


limitLong = price * 1.06
stopLong = price * 0.96
stopLossTrigger = (limitLong >= close) or (close <= stopLong)
//strategy.close("Long", when=stopLossTrigger)


limitShort = price * 0.97 
stopShort = price * 1.02
stopLossTriggerShort = (limitShort <= close) or (close >= stopShort)
//strategy.close("Short", when=stopLossTriggerShort)



strategy.exit("Exit Long", from_entry="Long", limit=limitLong, stop=stopLong)
strategy.exit("Exit Short", from_entry="Short", limit=limitShort, stop=stopShort)
0

There are 0 best solutions below