I wrote a strategy that includes trailing profit by following examples of another coders. However, when the entry conditions are still valid and the strategy entry executed second time, it still takes the previous position's trailing profit price. it causes multiple entries and exits without any profit (in fact trailing offset works, so profit is random when the prices are still going up).
I tried many things such as barssince or strategy position commands to distinguish from previous entry. But I failed.
Sorry about my code seems like a mass. My problem is specificly starts the startLongDeal and longIsActive variables after line 112. You can see that desired exit prices are plotted in the code.
Thank you in advance!
[btc example][1]
//@version=5
// SETUP ============================================================================================================
strategy(title = 'internet', shorttitle = 'internet', overlay = true, pyramiding = 0, calc_on_every_tick = true, calc_on_order_fills=true, currency=currency.USD, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, initial_capital = 100)
// INPUTS ===========================================================================================================
//SEYDA - COMBO BÖLÜMÜ
fastperiod = input.int(7, title='fastperiod', minval=1, maxval=500)
slowperiod = input.int(21, title='slowperiod', minval=1, maxval=500)
signalperiod = input.int(9, title='signalperiod', minval=1, maxval=500)
fastMA = ta.ema(close, fastperiod)
slowMA = ta.ema(close, slowperiod)
macd = fastMA - slowMA
signal = ta.ema(macd, signalperiod)
macdAS = macd - signal
//type = float
signalAS = ta.ema(macdAS, signalperiod)
STO = input(false, title='Show INVERSE FISHER TRANSFORM on STOCHASTIC Line?')
RSI = input(false, title='Show INVERSE FISHER TRANSFORM on RSI Line?')
CCI = input(false, title='Show INVERSE FISHER TRANSFORM on CCI Line?')
MFI = input(false, title='Show INVERSE FISHER TRANSFORM on MFI Line?')
//Average means: average value of all 4 inverse fisher trasformed indicators
AVERAGE = input(true, title='Show INVERSE FISHER TRANSFORM AVERAGE Line?')
ccilength = input(5, 'CCI Length')
wmalength = input(9, title='Smoothing Length')
v11 = 0.1 * (ta.cci(close, ccilength) / 4)
v21 = ta.wma(v11, wmalength)
INV1 = (math.exp(2 * v21) - 1) / (math.exp(2 * v21) + 1)
rsilength = input(5, 'RSI Length')
v12 = 0.1 * (ta.rsi(close, rsilength) - 50)
v22 = ta.wma(v12, wmalength)
INV2 = (math.exp(2 * v22) - 1) / (math.exp(2 * v22) + 1)
stochlength = input(5, 'STOCH Length')
v1 = 0.1 * (ta.stoch(close, high, low, stochlength) - 50)
v2 = ta.wma(v1, wmalength)
INVLine = (math.exp(2 * v2) - 1) / (math.exp(2 * v2) + 1)
//MFI
mfilength = input(5, 'MFI Length')
source = hlc3
up = math.sum(volume * (ta.change(source) <= 0 ? 0 : source), mfilength)
lo = math.sum(volume * (ta.change(source) >= 0 ? 0 : source), mfilength)
mfi = 100.0 - 100.0 / (1.0 + up / lo)
v13 = 0.1 * (mfi - 50)
v23 = ta.wma(v13, wmalength)
INV3 = (math.exp(2 * v23) - 1) / (math.exp(2 * v23) + 1)
AVINV = (INV1 + INV2 + INVLine + INV3) / 4
//SEYDA -VFI bölümü
vfilength = input(130, title='VFI length')
coef = input(0.2)
vcoef = input(2.5, title='Max. vol. cutoff')
vfisignalLength = input(5)
smoothVFI = input(false)
ma(x, y) =>
smoothVFI ? ta.sma(x, y) : x
typical = hlc3
inter = math.log(typical) - math.log(typical[2])
vinter = ta.stdev(inter, 30)
cutoff = coef * vinter * close
vave = ta.sma(volume, vfilength)[2]
vmax = vave * vcoef
vc = volume < vmax ? volume : vmax //min( volume, vmax )
mf = typical - typical[2]
iff_1 = mf < -cutoff ? -vc : 0
vcp = mf > cutoff ? vc : iff_1
vfi = ma(math.sum(vcp, vfilength) / vave, 3)
vfima = ta.ema(vfi, vfisignalLength)
d = vfi - vfima
// ===================================================================================================
strategy.risk.allow_entry_in(strategy.direction.long) // There will be no short entries, only exits from long.
// STRATEGY INPUT ===================================================================================================
longTradesEnabled = input.bool(defval = true, title = 'Long Trades', inline = 'Trades', group = 'Strategy')
// ===================================================================================================
enableTakeProfitTrailing = input.bool(defval = true, title = 'Enable Trailing', tooltip = 'Enable or disable the trailing for take profit.', group = 'Take Profit')
trailingTakeProfitDeviationPerc = input.float(defval = 0.1, title = 'Trailing Deviation %', minval = 0.1, maxval = 100, step = 0.1, tooltip = 'The step to follow the price when the take profit limit is reached.', group = 'Take Profit') / 100
longTakeProfitPerc = input.float(defval = 1.1, title = 'Long/Short Take Profit %', minval = 0.05, step = 0.05, inline = 'Take Profit Perc', group = 'Take Profit') / 100
enableStopLossTrailing = input.string(defval = 'TP', title = 'Enable Trailing', options = ['TP', 'ON', 'OFF'], tooltip = 'Enable the trailing for stop loss when Take Profit order is executed (TP) or from the start of the entry order (ON) or not at all (OFF).', group = 'Stop Loss')
breakEvenEnabled = input.bool(defval = false, title = 'Break Even', group = 'Stop Loss', tooltip = 'When take profit price target is hit, move the stop loss to the entry price (or to a more strict price defined by the Stop Loss %)')
longTrailingStopLossPerc = input.float(defval = 6, title = 'Long/Short Stop Loss %', minval = 0.1, maxval = 100, step = 0.1, inline = 'Trailing Stop Loss Perc', group = 'Stop Loss') / 100
// BACKTEST PERIOD INPUT ============================================================================================
fromDate = input.time(defval = timestamp('21 Nov 2021 00:00 UTC'), title = 'From Date', group = 'Backtest Period') // backtest start date
toDate = input.time(defval = timestamp('31 Dec 2121 23:59 UTC'), title = 'To Date', group = 'Backtest Period') // backtest finish date
isWithinBacktestPeriod() =>
time >= fromDate and time <= toDate ? true : false // create function "within window of time"
// SHOW PLOT INPUT ==================================================================================================
showDate = input.bool(defval = true, title = 'Show Backtest Range', tooltip = 'Gray out the backround of the backtest period.', group = 'Plot')
highlighting = input.bool(defval = false, title = 'Show Highlighter', tooltip = 'Highlight long and short deals.', group = 'Plot')
//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
//ATTEMPTS TO DEFINE WHETHER STRATEGY OPEN OR CLOSE
straEntry = strategy.position_size != strategy.position_size[2] and strategy.position_size > 0
strategyjustExited = strategy.position_size != strategy.position_size[2] and strategy.position_size[2]>0
strategyactive=ta.barssince(straEntry)>=0 and strategy.position_size > 0
//CONDITION FOR TRAIL AND ENTRY
bool startLongDeal = AVINV > 0.4 and (AVINV[2]<=AVINV[2] or AVINV[2]<=AVINV)
bool longIsActive = strategy.position_size > 0 or startLongDeal
//TRAILING PARTS
var longTrailingTakeProfitExecuted = false
float longTakeProfitPrice = na
longTakeProfitPrice := if longTradesEnabled and isWithinBacktestPeriod() and not longTrailingTakeProfitExecuted and longIsActive //long buradan kalktı mı %20 kayıp
nz(longTakeProfitPrice[2], close * (1 + longTakeProfitPerc))
else
na
longTrailingTakeProfitExecuted := strategy.position_size > 0 and (longTrailingTakeProfitExecuted[2] or strategy.position_size < strategy.position_size[2] or strategy.position_size[2] == 0 and high >= longTakeProfitPrice)
longTrailingTakeProfitStepTicks = longTakeProfitPrice * trailingTakeProfitDeviationPerc / syminfo.mintick
// determine trailing stop loss price. Trailing starts when the take profit price is reached
bool enableLongTakeProfitTrailing = enableStopLossTrailing == 'ON' or enableStopLossTrailing == 'TP' and longTrailingTakeProfitExecuted
float longTrailingStopLossPrice = na
longTrailingStopLossPrice := if longTradesEnabled and isWithinBacktestPeriod() and longIsActive // ama bir kayıp yok
if startLongDeal and strategy.position_size == 0 // and XX
close * (1 - longTrailingStopLossPerc)
else
stopValue = (enableLongTakeProfitTrailing ? high : strategy.position_avg_price) * (1 - longTrailingStopLossPerc)
stopValue := breakEvenEnabled and longTrailingTakeProfitExecuted ? math.max(stopValue, strategy.position_avg_price) : stopValue
math.max(stopValue, nz(longTrailingStopLossPrice[2]))
else
na
// STRATEGY EXECUTION ===============================================================================================
if strategy.position_size[2]==0 and AVINV>0.4 and longTradesEnabled and isWithinBacktestPeriod() and longIsActive and startLongDeal
strategy.entry(id = 'Long Entry', direction = strategy.long, alert_message = 'Long(' + syminfo.ticker + '): Started', comment='ENTRY')
strategy.exit(id = 'Long Entry',from_entry='Long Entry', limit = enableTakeProfitTrailing ? na : longTakeProfitPrice, stop = longTrailingStopLossPrice, trail_price = enableTakeProfitTrailing ? longTakeProfitPrice : na, trail_offset = enableTakeProfitTrailing ? longTrailingTakeProfitStepTicks : na, alert_message = 'Long(' + syminfo.ticker + '): Take Profit or Stop Loss activated', comment='EXIT')
//PLOTS
bgcolor(color = showDate and isWithinBacktestPeriod() ? color.new(color.gray, 98) : na)
lowHighPrice = high > strategy.position_avg_price and low < strategy.position_avg_price ? longIsActive ? high : na : na//shortIsActive ? low : na
: high > strategy.position_avg_price ? high
: low < strategy.position_avg_price ? low
: na
// PLOT İÇİN İPTAL DENEMELERİ
pricePlot = plot(series = lowHighPrice, title = 'Price', color = na, linewidth = 1, style = plot.style_linebr)
posPlot = plot(series = strategy.position_avg_price, title = 'Position', color = color.new(color.blue, 0), linewidth = 1, style = plot.style_linebr)
var takeProfitColor = color.new(color.yellow, 0) // #419388
ltpPlot = plot(series = longTakeProfitPrice, title = 'Long Take Profit', color = takeProfitColor, linewidth = 1, style = plot.style_linebr, offset = 1)
var stopLossColor = color.fuchsia // #e25141
lslPlot = plot(series = longTrailingStopLossPrice, title = 'Long Trail Stop', color = stopLossColor, linewidth = 1, style = plot.style_linebr, offset = 1)
highlightColor = lowHighPrice > strategy.position_avg_price and longIsActive ? color.green : na//or lowHighPrice < strategy.position_avg_price and shortIsActive ? color.green
: lowHighPrice < strategy.position_avg_price and longIsActive ? color.red : na//or lowHighPrice > strategy.position_avg_price and shortIsActive ? color.red
: na
// ==================================================================================================================
[1]: https://i.stack.imgur.com/n6wyq.jpg
[2]: https://i.stack.imgur.com/djdj2.jpg