本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
strategy("Synapse Quantum v1.4 | Martingale & Contract Cap", overlay=true, initial_capital=50000, currency=currency.USD, pyramiding=0, commission_type=strategy.commission.cash_per_contract, commission_value=0.75, slippage=2, process_orders_on_close=false, calc_on_order_fills=false, calc_on_every_tick=false, use_bar_magnifier=true, default_qty_type=strategy.fixed, default_qty_value=1)
// ─── 01: Market geometry ───
gGeo = "01 | Market Geometry"
eqLen = input.int(34, "Equilibrium EMA length", minval=5, group=gGeo)
atrLen = input.int(14, "ATR length", minval=2, group=gGeo)
effLen = input.int(20, "Efficiency length", minval=3, group=gGeo)
trendCut = input.float(0.38, "Trend efficiency minimum", minval=0.01, maxval=1, group=gGeo)
rangeCut = input.float(0.25, "Range efficiency maximum", minval=0.01, maxval=1, group=gGeo)
compLen = input.int(30, "ATR baseline length", minval=5, group=gGeo)
compCut = input.float(0.82, "Compression threshold", minval=0.1, group=gGeo)
regimeMode = input.string("Engine-specific", "Regime requirement", options=["Engine-specific","Off"], group=gGeo)
// ─── 02: Entry engines ───
gEnt = "02 | Independent Entry Engines"
useTrend = input.bool(true, "1. Memory / equilibrium reclaim", group=gEnt)
useSnap = input.bool(true, "2. Elastic snapback", group=gEnt)
useBreak = input.bool(true, "3. Compression breakout", group=gEnt)
useEmaCross = input.bool(false, "4. EMA crossover", group=gEnt)
useEmaPull = input.bool(false, "5. EMA pullback continuation", group=gEnt)
useBbRevert = input.bool(false, "6. Bollinger band reversion", group=gEnt)
useBbBreak = input.bool(false, "7. Bollinger squeeze breakout", group=gEnt)
trendPull = input.float(0.35, "Memory pullback proximity (ATR)", minval=0, step=0.05, group=gEnt)
stretch = input.float(1.5, "Snapback stretch (ATR)", minval=0.1, step=0.1, group=gEnt)
breakLen = input.int(12, "Channel breakout lookback", minval=2, group=gEnt)
emaFastLen = input.int(9, "Fast EMA", minval=1, group=gEnt)
emaSlowLen = input.int(21, "Slow EMA", minval=2, group=gEnt)
emaPullATR = input.float(0.25, "EMA pullback proximity (ATR)", minval=0, step=0.05, group=gEnt)
bbLen = input.int(20, "Bollinger length", minval=5, group=gEnt)
bbDev = input.float(2.0, "Bollinger deviation", minval=0.1, step=0.1, group=gEnt)
bbSqueezeLen = input.int(50, "BB squeeze baseline length", minval=5, group=gEnt)
bbSqueezeRatio = input.float(0.75, "BB squeeze width / average", minval=0.1, step=0.05, group=gEnt)
entryConflict = input.string("Skip", "Opposite signals same bar", options=["Skip","Prefer trend","Prefer reversion"], group=gEnt)
// ─── 03: Optional confirmation filters ───
gFilt = "03 | Optional Entry Filters"
useEmaAlign = input.bool(false, "Require fast/slow EMA alignment", group=gFilt)
useEmaSlope = input.bool(false, "Require slow EMA slope alignment", group=gFilt)
usePriceEma = input.bool(false, "Require price above/below slow EMA", group=gFilt)
useAtrMin = input.bool(false, "Require minimum ATR", group=gFilt)
minAtr = input.float(8, "Minimum ATR (points)", minval=0, group=gFilt)
useAtrExpand = input.bool(false, "Require ATR expansion", group=gFilt)
atrExpandMult = input.float(1.05, "ATR / ATR baseline minimum", minval=0.1, step=0.05, group=gFilt)
useRsi = input.bool(false, "Require RSI directional confirmation", group=gFilt)
rsiLen = input.int(14, "RSI length", minval=2, group=gFilt)
rsiLong = input.float(52, "RSI minimum for longs", minval=0, maxval=100, group=gFilt)
rsiShort = input.float(48, "RSI maximum for shorts", minval=0, maxval=100, group=gFilt)
usePressure = input.bool(false, "Require candle pressure confirmation", group=gFilt)
pressureLen = input.int(8, "Pressure EMA smoothing", minval=1, group=gFilt)
useVolume = input.bool(false, "Require relative volume", group=gFilt)
volLen = input.int(20, "Volume average length", minval=2, group=gFilt)
rvolMin = input.float(1.15, "Relative volume minimum", minval=0.1, group=gFilt)
useHtf = input.bool(false, "Require completed HTF EMA bias", group=gFilt)
htf = input.timeframe("60", "Higher timeframe", group=gFilt)
useSyn = input.bool(false, "Require Supertrend direction", group=gFilt)
synFactor = input.float(2.0, "Supertrend ATR multiplier", minval=0.1, group=gFilt)
synLen = input.int(10, "Supertrend ATR length", minval=1, group=gFilt)
allowLong = input.bool(true, "Allow longs", group=gFilt)
allowShort = input.bool(true, "Allow shorts", group=gFilt)
// ─── 04: Risk / exits ───
gExit = "04 | Stops, Targets & Exits"
stopMode = input.string("ATR", "Initial stop units", options=["ATR","Points","Dollars","Percent","Ticks"], group=gExit)
stopValue = input.float(1.8, "Initial stop distance", minval=0.01, group=gExit)
targetMode = input.string("R multiple", "Target units", options=["R multiple","ATR","Points","Dollars","Percent","Ticks"], group=gExit)
targetValue = input.float(1.6, "Target distance", minval=0.01, group=gExit)
exitMode = input.string("Static bracket", "Exit management", options=["Static bracket","ATR trailing + target","Chandelier + target","Breakeven + target","Trailing only","Equilibrium target","Bollinger midline target"], group=gExit)
trailArmR = input.float(0.8, "Trail arms after favorable R", minval=0, step=0.1, group=gExit)
trailAtr = input.float(1.5, "ATR trailing distance", minval=0.1, step=0.1, group=gExit)
chandAtr = input.float(2.0, "Chandelier distance (entry ATR)", minval=0.1, step=0.1, group=gExit)
useBE = input.bool(false, "Additional breakeven (all modes)", group=gExit)
beTriggerR = input.float(1.0, "Breakeven activation (R)", minval=0, step=0.1, group=gExit)
beOffsetTicks = input.int(1, "Breakeven offset (ticks)", minval=0, group=gExit)
exitOpposite = input.bool(false, "Exit on opposing qualified setup", group=gExit)
exitRegime = input.bool(false, "Exit trend trades when efficiency fails", group=gExit)
maxBars = input.int(0, "Max bars in trade (0=off)", minval=0, group=gExit)
useMinRR = input.bool(false, "Require minimum configured reward/risk", group=gExit)
minRR = input.float(1.0, "Minimum R:R", minval=0.1, step=0.1, group=gExit)
// ─── 04B: Optional Martingale / contract sizing ───
gSize = "04B | Martingale & Position Sizing"
useMartingale = input.bool(false, "Enable loss-based Martingale sizing", group=gSize)
baseQty = input.int(1, "Starting contracts", minval=1, group=gSize)
martingaleMult = input.float(2.0, "Multiplier after each loss", minval=1.0, maxval=5.0, step=0.25, group=gSize)
maxContracts = input.int(2, "Maximum contracts (hard cap)", minval=1, group=gSize)
maxMartingaleSteps = input.int(1, "Maximum consecutive sizing steps", minval=0, maxval=10, group=gSize)
resetOnWin = input.bool(true, "Reset to starting size after winning trade", group=gSize)
resetStreakDaily = input.bool(false, "Reset losing streak at new overnight session", group=gSize)
showSizing = input.bool(false, "Show next order size in data window", group=gSize)
// ─── 05: Sessions and protection ───
gDay = "05 | Overnight Session & Daily Guardrails"
tz = input.string("America/New_York", "Timezone", group=gDay)
tradeSession = input.session("1800-1640", "Entry window", group=gDay)
useSession = input.bool(true, "Restrict entries to session", group=gDay)
useSun = input.bool(true, "Sunday overnight", group=gDay)
useMon = input.bool(true, "Monday overnight", group=gDay)
useTue = input.bool(true, "Tuesday overnight", group=gDay)
useWed = input.bool(true, "Wednesday overnight", group=gDay)
useThu = input.bool(true, "Thursday overnight", group=gDay)
maxTrades = input.int(6, "Maximum entries per session (0=unlimited)", minval=0, group=gDay)
cooldown = input.int(3, "Bars between entries", minval=0, group=gDay)
useDailyPT = input.bool(true, "Enable daily profit lockout", group=gDay)
dailyPT = input.float(250, "Daily profit target ($)", minval=1, group=gDay)
useDailyLoss = input.bool(true, "Enable daily loss lockout", group=gDay)
dailyLoss = input.float(700, "Daily loss limit ($)", minval=1, group=gDay)
flattenLimits = input.bool(true, "Flatten on daily threshold", group=gDay)
useStandingGuards = input.bool(true, "Standing daily stop/target price guards", group=gDay)
avoidNearPT = input.bool(true, "Avoid new entries near daily PT", group=gDay)
minRemaining = input.float(30, "Minimum $ remaining for entry", minval=0, step=5, group=gDay)
flattenEnd = input.bool(true, "Flatten at entry window end", group=gDay)
// ─── 06: Visuals ───
gVis = "06 | Visuals & Diagnostics"
showEMA = input.bool(true, "Show EMAs", group=gVis)
showBB = input.bool(false, "Show Bollinger bands", group=gVis)
showEq = input.bool(true, "Show equilibrium", group=gVis)
showSignals = input.bool(true, "Show engine signals", group=gVis)
showDebug = input.bool(false, "Show diagnostics in data window", group=gVis)
// ─── Geometry ───
atr = ta.atr(atrLen)
eq = ta.ema(hlc3, eqLen)
fast = ta.ema(close, emaFastLen)
slow = ta.ema(close, emaSlowLen)
effTravel = math.sum(math.abs(ta.change(close)), effLen)
eff = effTravel > 0 ? math.abs(close - close[effLen]) / effTravel : 0.0
slope = eq - eq[3]
trendRegime = regimeMode == "Off" or eff >= trendCut
rangeRegime = regimeMode == "Off" or eff <= rangeCut
atrBase = ta.sma(atr, compLen)
volRatio = atrBase > 0 ? atr / atrBase : 1.0
compressedRecently = ta.lowest(volRatio[1], breakLen) < compCut
expanding = atr > atr[1] and volRatio > compCut
z = atr > 0 ? (close - eq) / atr : 0.0
bbBasis = ta.sma(close, bbLen)
bbStd = ta.stdev(close, bbLen)
bbUpper = bbBasis + bbDev * bbStd
bbLower = bbBasis - bbDev * bbStd
bbWidth = bbBasis != 0 ? (bbUpper - bbLower) / math.abs(bbBasis) : 0.0
bbWidthAvg = ta.sma(bbWidth, bbSqueezeLen)
bbWasTight = bbWidthAvg[1] > 0 and bbWidth[1] < bbWidthAvg[1] * bbSqueezeRatio
barRange = math.max(high - low, syminfo.mintick)
pressure = ta.ema((2 * close - high - low) / barRange, pressureLen)
rsi = ta.rsi(close, rsiLen)
volAvg = ta.sma(volume, volLen)
rvol = volAvg > 0 ? nz(volume) / volAvg : 0.0
[stLine, stDir] = ta.supertrend(synFactor, synLen)
// Completed HTF values with lookahead OFF. No future higher-timeframe data is exposed.
// Use an HTF strictly higher than the chart timeframe when enabling this filter.
[htfClose, htfEq] = request.security(syminfo.tickerid, htf, [close[1], ta.ema(hlc3, eqLen)[1]], lookahead=barmerge.lookahead_off)
longFilter = allowLong and (not useEmaAlign or fast > slow) and (not useEmaSlope or slow > slow[1]) and (not usePriceEma or close > slow) and (not useAtrMin or atr >= minAtr) and (not useAtrExpand or volRatio >= atrExpandMult) and (not useRsi or rsi >= rsiLong) and (not usePressure or pressure > 0) and (not useVolume or (not na(volume) and rvol >= rvolMin)) and (not useHtf or htfClose > htfEq) and (not useSyn or stDir < 0)
shortFilter = allowShort and (not useEmaAlign or fast < slow) and (not useEmaSlope or slow < slow[1]) and (not usePriceEma or close < slow) and (not useAtrMin or atr >= minAtr) and (not useAtrExpand or volRatio >= atrExpandMult) and (not useRsi or rsi <= rsiShort) and (not usePressure or pressure < 0) and (not useVolume or (not na(volume) and rvol >= rvolMin)) and (not useHtf or htfClose < htfEq) and (not useSyn or stDir > 0)
// ─── Independent signals; no future bars used ───
trendL = useTrend and trendRegime and slope > 0 and low <= eq + trendPull * atr and ta.crossover(close, eq)
trendS = useTrend and trendRegime and slope < 0 and high >= eq - trendPull * atr and ta.crossunder(close, eq)
snapL = useSnap and rangeRegime and z[1] < -stretch and ta.crossover(z, -stretch)
snapS = useSnap and rangeRegime and z[1] > stretch and ta.crossunder(z, stretch)
breakL = useBreak and compressedRecently and expanding and close > ta.highest(high[1], breakLen)
breakS = useBreak and compressedRecently and expanding and close < ta.lowest(low[1], breakLen)
crossL = useEmaCross and ta.crossover(fast, slow)
crossS = useEmaCross and ta.crossunder(fast, slow)
pullL = useEmaPull and fast > slow and low <= fast + emaPullATR * atr and ta.crossover(close, fast)
pullS = useEmaPull and fast < slow and high >= fast - emaPullATR * atr and ta.crossunder(close, fast)
bbRevL = useBbRevert and rangeRegime and low[1] < bbLower[1] and ta.crossover(close, bbLower)
bbRevS = useBbRevert and rangeRegime and high[1] > bbUpper[1] and ta.crossunder(close, bbUpper)
bbBreakL = useBbBreak and bbWasTight and close > bbUpper and close > open
bbBreakS = useBbBreak and bbWasTight and close < bbLower and close < open
trendCandidateL = trendL or breakL or crossL or pullL or bbBreakL
trendCandidateS = trendS or breakS or crossS or pullS or bbBreakS
revertCandidateL = snapL or bbRevL
revertCandidateS = snapS or bbRevS
rawL = trendCandidateL or revertCandidateL
rawS = trendCandidateS or revertCandidateS
chooseLong = rawL and (not rawS or (entryConflict == "Prefer trend" and trendCandidateL and not trendCandidateS) or (entryConflict == "Prefer reversion" and revertCandidateL and not revertCandidateS))
chooseShort = rawS and (not rawL or (entryConflict == "Prefer trend" and trendCandidateS and not trendCandidateL) or (entryConflict == "Prefer reversion" and revertCandidateS and not revertCandidateL))
signalL = chooseLong and not chooseShort and longFilter
signalS = chooseShort and not chooseLong and shortFilter
string longEngine = breakL ? "Compression" : bbBreakL ? "BB Break" : trendL ? "Memory" : crossL ? "EMA Cross" : pullL ? "EMA Pull" : snapL ? "Snapback" : "BB Revert"
string shortEngine = breakS ? "Compression" : bbBreakS ? "BB Break" : trendS ? "Memory" : crossS ? "EMA Cross" : pullS ? "EMA Pull" : snapS ? "Snapback" : "BB Revert"
// ─── Session accounting ───
// Reset at 18:00 in selected timezone. Flat-at-session-end is optional.
sessionKey = time("D", "1800-1800", tz)
newDay = ta.change(sessionKey) != 0
var float sessionBase = na
var int entriesToday = 0
var int lastEntry = na
var bool locked = false
if barstate.isfirst or newDay
sessionBase := strategy.netprofit + strategy.openprofit
entriesToday := 0
locked := false
sessionPnL = strategy.netprofit + strategy.openprofit - nz(sessionBase, strategy.netprofit + strategy.openprofit)
hitPT = useDailyPT and sessionPnL >= dailyPT
hitDLL = useDailyLoss and sessionPnL <= -dailyLoss
if hitPT or hitDLL
locked := true
if locked and flattenLimits and strategy.position_size != 0
strategy.cancel_all()
strategy.close_all(comment="Daily P/L lockout", immediately=true)
inSession = not na(time(timeframe.period, tradeSession, tz))
sessionEnd = useSession and not inSession and inSession[1]
if flattenEnd and sessionEnd and strategy.position_size != 0
strategy.cancel_all()
strategy.close_all(comment="Session end", immediately=true)
localHour = hour(time, tz)
localDay = dayofweek(time, tz)
anchorDay = localHour >= 18 ? localDay : localDay == dayofweek.sunday ? dayofweek.saturday : localDay - 1
dayOK = (anchorDay == dayofweek.sunday and useSun) or (anchorDay == dayofweek.monday and useMon) or (anchorDay == dayofweek.tuesday and useTue) or (anchorDay == dayofweek.wednesday and useWed) or (anchorDay == dayofweek.thursday and useThu)
nearPT = avoidNearPT and useDailyPT and sessionPnL > 0 and dailyPT - sessionPnL < minRemaining
canEnter = barstate.isconfirmed and (not useSession or inSession) and dayOK and not locked and not nearPT and not (flattenEnd and sessionEnd) and strategy.position_size == 0 and (maxTrades == 0 or entriesToday < maxTrades) and (na(lastEntry) or bar_index - lastEntry > cooldown)
// Update the loss streak from *closed* trades, not signals.
// Only the most recently closed trade matters with pyramiding=0.
// Subtract commissions so small nominal wins are not misclassified.
var int losingStreak = 0
var int processedClosedTrades = 0
if strategy.closedtrades > processedClosedTrades
for tradeIndex = processedClosedTrades to strategy.closedtrades - 1
float tradeNet = strategy.closedtrades.profit(tradeIndex) - strategy.closedtrades.commission(tradeIndex)
if tradeNet < 0
losingStreak += 1
else if tradeNet > 0 and resetOnWin
losingStreak := 0
processedClosedTrades := strategy.closedtrades
if newDay and resetStreakDaily
losingStreak := 0
int sizingStep = useMartingale ? math.min(losingStreak, maxMartingaleSteps) : 0
float requestedSize = baseQty * math.pow(useMartingale ? martingaleMult : 1.0, sizingStep)
int nextQty = math.min(maxContracts, math.max(1, int(math.round(requestedSize))))
// ─── Entry-snapshot risk distances ───
f_dist(string mode, float value, float price, float frozenATR, float units, float initialRisk) =>
switch mode
"Points" => value
"Dollars" => value / math.max(units * syminfo.pointvalue, 0.0000001)
"Percent" => price * value / 100.0
"Ticks" => value * syminfo.mintick
"R multiple" => initialRisk * value
=> frozenATR * value
var float riskDist = na
var float rewardDist = na
var float frozenAtr = na
var float peak = na
var float trough = na
var float ratchetL = na
var float ratchetS = na
var int tradeBar = na
var string engine = ""
if canEnter and (signalL != signalS)
float proposedRisk = math.max(syminfo.mintick, f_dist(stopMode, stopValue, close, atr, nextQty, atr))
float proposedReward = math.max(syminfo.mintick, f_dist(targetMode, targetValue, close, atr, nextQty, proposedRisk))
if not useMinRR or proposedReward / proposedRisk >= minRR
riskDist := proposedRisk
rewardDist := proposedReward
frozenAtr := atr
peak := na
trough := na
ratchetL := na
ratchetS := na
engine := signalL ? longEngine : shortEngine
tradeBar := bar_index
// Submit an initial protective bracket on the signal bar, before the
// next-tick entry fill. No historical fill-triggered recalculation.
int riskTicks = math.max(1, int(math.ceil(proposedRisk / syminfo.mintick)))
int rewardTicks = math.max(1, int(math.ceil(proposedReward / syminfo.mintick)))
if signalL
strategy.entry("L", strategy.long, qty=nextQty, comment=engine)
strategy.exit("L exit", from_entry="L", loss=riskTicks, profit=rewardTicks)
else
strategy.entry("S", strategy.short, qty=nextQty, comment=engine)
strategy.exit("S exit", from_entry="S", loss=riskTicks, profit=rewardTicks)
entriesToday += 1
lastEntry := bar_index
// Initial stop/target are attached on the entry signal bar using ticks.
// Subsequent updates happen only on confirmed bar closes; they use the actual
// average fill and can never benefit from historical fill-triggered recalc.
if strategy.position_size != 0 and not na(riskDist)
float avg = strategy.position_avg_price
bool isLong = strategy.position_size > 0
// Only include completed bars AFTER the entry-signal bar. The entry
// candle's full high/low may have occurred before the actual fill.
if barstate.isconfirmed and bar_index > nz(tradeBar, bar_index)
if isLong
peak := math.max(nz(peak, avg), high)
else
trough := math.min(nz(trough, avg), low)
float baseStop = isLong ? avg - riskDist : avg + riskDist
float stopPrice = baseStop
float favorable = isLong ? nz(peak, avg) - avg : avg - nz(trough, avg)
bool trailing = exitMode == "ATR trailing + target" or exitMode == "Trailing only"
bool chandelier = exitMode == "Chandelier + target"
bool beEnabled = useBE or exitMode == "Breakeven + target"
if beEnabled and favorable >= riskDist * beTriggerR
stopPrice := isLong ? math.max(stopPrice, avg + beOffsetTicks * syminfo.mintick) : math.min(stopPrice, avg - beOffsetTicks * syminfo.mintick)
if trailing and favorable >= riskDist * trailArmR
if isLong
ratchetL := math.max(nz(ratchetL, peak - atr * trailAtr), peak - atr * trailAtr)
stopPrice := math.max(stopPrice, ratchetL)
else
ratchetS := math.min(nz(ratchetS, trough + atr * trailAtr), trough + atr * trailAtr)
stopPrice := math.min(stopPrice, ratchetS)
if chandelier and favorable >= riskDist * trailArmR
if isLong
ratchetL := math.max(nz(ratchetL, peak - frozenAtr * chandAtr), peak - frozenAtr * chandAtr)
stopPrice := math.max(stopPrice, ratchetL)
else
ratchetS := math.min(nz(ratchetS, trough + frozenAtr * chandAtr), trough + frozenAtr * chandAtr)
stopPrice := math.min(stopPrice, ratchetS)
float targetPrice = isLong ? avg + rewardDist : avg - rewardDist
if exitMode == "Equilibrium target"
float eqTarget = eq
if isLong and eqTarget > avg
targetPrice := math.min(targetPrice, eqTarget)
if not isLong and eqTarget < avg
targetPrice := math.max(targetPrice, eqTarget)
if exitMode == "Bollinger midline target"
float bbTarget = bbBasis
if isLong and bbTarget > avg
targetPrice := math.min(targetPrice, bbTarget)
if not isLong and bbTarget < avg
targetPrice := math.max(targetPrice, bbTarget)
if exitMode == "Trailing only"
targetPrice := na
// Daily guards are standing price orders, not just bar-close tests.
// Only tighten the trade bracket; never widen its existing stop/target.
// Daily threshold accounting assumes no change in quantity during a trade.
if useStandingGuards and flattenLimits
float units = math.abs(strategy.position_size)
float usdPerPoint = units * syminfo.pointvalue
// Session P/L less current open P/L gives realized session P/L.
float closedSessionPnL = sessionPnL - strategy.openprofit
if usdPerPoint > 0
if useDailyLoss
float remainingLossBudget = dailyLoss + closedSessionPnL
float guardStop = avg + (isLong ? -remainingLossBudget : remainingLossBudget) / usdPerPoint
stopPrice := isLong ? math.max(stopPrice, guardStop) : math.min(stopPrice, guardStop)
if useDailyPT
float remainingProfitBudget = dailyPT - closedSessionPnL
float guardTarget = avg + (isLong ? remainingProfitBudget : -remainingProfitBudget) / usdPerPoint
targetPrice := na(targetPrice) ? guardTarget : isLong ? math.min(targetPrice, guardTarget) : math.max(targetPrice, guardTarget)
// Avoid invalid brackets when a session guard threshold has already been crossed.
// Do not revise orders on unconfirmed realtime ticks.
if barstate.isconfirmed
if isLong
strategy.exit("L exit", from_entry="L", stop=stopPrice, limit=targetPrice)
else
strategy.exit("S exit", from_entry="S", stop=stopPrice, limit=targetPrice)
bool maxAge = maxBars > 0 and bar_index - nz(tradeBar, bar_index) >= maxBars
bool opposing = exitOpposite and (isLong ? signalS : signalL)
bool regimeFailed = exitRegime and (engine == "Memory" or engine == "Compression" or engine == "EMA Cross" or engine == "EMA Pull" or engine == "BB Break") and not trendRegime
if barstate.isconfirmed and (maxAge or opposing or regimeFailed)
if isLong
strategy.close("L", comment=maxAge ? "Time exit" : opposing ? "Opposite setup" : "Regime exit")
else
strategy.close("S", comment=maxAge ? "Time exit" : opposing ? "Opposite setup" : "Regime exit")
plot(showEq ? eq : na, "Equilibrium", color=color.orange, linewidth=2)
plot(showEMA ? fast : na, "Fast EMA", color=color.aqua)
plot(showEMA ? slow : na, "Slow EMA", color=color.purple)
plot(showBB ? bbUpper : na, "BB upper", color=color.new(color.blue, 35))
plot(showBB ? bbBasis : na, "BB middle", color=color.new(color.blue, 55))
plot(showBB ? bbLower : na, "BB lower", color=color.new(color.blue, 35))
plot(useSyn ? stLine : na, "Supertrend filter", color=stDir < 0 ? color.teal : color.red)
plotshape(showSignals and canEnter and signalL and not signalS, title="Long setup", style=shape.triangleup, location=location.belowbar, color=color.teal, size=size.tiny)
plotshape(showSignals and canEnter and signalS and not signalL, title="Short setup", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.tiny)
plot(showDebug ? sessionPnL : na, "Session P&L", display=display.data_window)
plot(showDebug ? eff : na, "Efficiency", display=display.data_window)
plot(showDebug ? volRatio : na, "ATR ratio", display=display.data_window)
bgcolor(locked ? color.new(color.red, 90) : na, title="Daily lockout")
plot(showSizing ? nextQty : na, "Next entry contracts", display=display.data_window)
plot(showSizing ? losingStreak : na, "Consecutive losing trades", display=display.data_window)