Overnight MNQ Synapse Confluence Scalper Pro

uprisingchristian · strategy · 826 行 · 点赞 46 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

//@version=6
 
strategy("Synapse Confluence Scalper Pro v6.3 | Exclusion Window", overlay=true, pyramiding=0, initial_capital=50000, currency=currency.USD, default_qty_type=strategy.fixed, default_qty_value=1, commission_type=strategy.commission.cash_per_contract, commission_value=1.25, slippage=2, process_orders_on_close=true, calc_on_order_fills=false, calc_on_every_tick=false, max_labels_count=500)
 
 
 
// === CONTROLS ===
 
gCore = "01 | Core & Schedule"
 
qty = input.int(1, "Contracts", minval=1, group=gCore)
 
side = input.string("Both", "Trade Direction", options=["Both", "Long Only", "Short Only"], group=gCore)
 
tz = input.string("America/New_York", "Session Time Zone", options=["America/New_York", "America/Chicago", "Etc/UTC"], group=gCore)
 
tradeWindow = input.session("1800-1700", "Allowed Time Window", group=gCore)
 
sun = input.bool(true, "Sunday 18:00 → Monday 17:00", group=gCore)
 
mon = input.bool(true, "Monday 18:00 → Tuesday 17:00", group=gCore)
 
tue = input.bool(true, "Tuesday 18:00 → Wednesday 17:00", group=gCore)
 
wed = input.bool(true, "Wednesday 18:00 → Thursday 17:00", group=gCore)
 
thu = input.bool(true, "Thursday 18:00 → Friday 17:00", group=gCore)
 
flattenAtClose = input.bool(true, "Flatten at 17:00 ET", group=gCore)
 
useMaxTrades = input.bool(true, "Enable Max Entries Limit", group=gCore)
 
maxTrades = input.int(12, "Max Entries per Overnight Session", minval=1, group=gCore)
 
useCooldown = input.bool(true, "Enable Entry Cooldown", group=gCore)
 
cooldown = input.int(3, "Bars Between Entries", minval=0, group=gCore)
 
requireFresh = input.bool(true, "Require Fresh Confluence Trigger", group=gCore)
 
// === OPTIONAL NO-TRADE WINDOW ===
gExclude = "01B | Exclusion Window"
useExclusion = input.bool(false, "Enable Exclusion Window", group=gExclude)
excludeStartHour = input.int(9, "Start Hour (0-23)", minval=0, maxval=23, group=gExclude)
excludeStartMinute = input.int(0, "Start Minute", minval=0, maxval=59, group=gExclude)
excludeEndHour = input.int(10, "End Hour (0-23)", minval=0, maxval=23, group=gExclude)
excludeEndMinute = input.int(0, "End Minute", minval=0, maxval=59, group=gExclude)
excludePositionMode = input.string("Keep Open", "Position at Exclusion Start", options=["Keep Open", "Flatten"], group=gExclude)
// Optional safety delay: applies after any completed exit, not only Synapse exits.
useExitDelay = input.bool(false, "Wait After Any Exit Before Re-entry", group=gExclude)
exitDelayBars = input.int(1, "Minimum Full Bars After Exit", minval=1, maxval=20, group=gExclude)
 
 
 
 
// === SESSION RISK ===
 
gRisk = "02 | Overnight Risk Limits"
 
useDailyTP = input.bool(true, "Enable Overnight Profit Lock", group=gRisk)
 
dailyTP = input.float(250, "Overnight Profit Target ($)", minval=1, group=gRisk)
 
useDailyLoss = input.bool(true, "Enable Overnight Loss Lock", group=gRisk)
 
dailyLoss = input.float(630, "Overnight Loss Limit ($)", minval=1, group=gRisk)
 
includeOpenPnL = input.bool(true, "Include Open P&L in Session Limits", group=gRisk)
 
 
 
// === EXITS ===
 
gExit = "03 | Stops, Targets & Trailing"
 
useStop = input.bool(true, "Enable Initial Stop Loss", group=gExit)
 
stopMode = input.string("ATR", "Stop Distance Type", options=["Ticks", "Points", "ATR", "Dollars / Contract", "Entry Price %"], group=gExit)
 
stopValue = input.float(1.5, "Stop Distance Value", minval=0.01, step=0.05, group=gExit)
 
useTarget = input.bool(true, "Enable Take Profit", group=gExit)
 
targetMode = input.string("ATR", "Target Distance Type", options=["Ticks", "Points", "ATR", "Dollars / Contract", "Entry Price %", "Risk / Reward"], group=gExit)
 
targetValue = input.float(2.0, "Target Distance Value", minval=0.01, step=0.05, group=gExit)
 
// Risk / Reward target is a multiple of the calculated initial stop distance,
 
// even when the initial stop order is switched off.
 
exitMode = input.string("Static", "Exit Style", options=["Static", "ATR Trail", "EMA Trail", "ATR + EMA Trail"], group=gExit)
 
atrLen = input.int(14, "ATR Length", minval=1, group=gExit)
 
trailATR = input.float(1.5, "ATR Trailing Multiplier", minval=0.1, group=gExit)
 
trailEMALen = input.int(21, "Trailing EMA Length", minval=1, group=gExit)
 
trailBuffer = input.float(0.25, "EMA Trail ATR Buffer", minval=0, group=gExit)
 
trailActivate = input.float(0.5, "Trail Activation (ATR in Profit)", minval=0, group=gExit)
 
useBreakEven = input.bool(false, "Enable Break Even", group=gExit)
 
breakEvenATR = input.float(1.0, "Break Even Activation (ATR)", minval=0, group=gExit)
 
breakEvenTicks = input.int(1, "Break Even Offset (Ticks)", minval=0, group=gExit)
 
useOppositeExit = input.bool(false, "Close on Opposite Synapse Trend", group=gExit)
 
 
 
// === CONFLUENCES ===
 
gConf = "04 | Optional Confluences"
 
useConfluence = input.bool(true, "Enable Confluence Score Gate", group=gConf)
 
minimum = input.int(3, "Minimum Enabled Confirmations", minval=1, maxval=12, group=gConf)
 
useEMA = input.bool(true, "01 EMA Fast / Slow Alignment", group=gConf)
 
useRSI = input.bool(true, "02 RSI Momentum", group=gConf)
 
useMACD = input.bool(false, "03 MACD Histogram", group=gConf)
 
useADX = input.bool(true, "04 ADX Trend Strength", group=gConf)
 
useVWAP = input.bool(false, "05 VWAP Position", group=gConf)
 
useBB = input.bool(false, "06 Bollinger Basis Position", group=gConf)
 
useST = input.bool(false, "07 Supertrend Direction", group=gConf)
 
useVolume = input.bool(false, "08 Relative Volume", group=gConf)
 
useBreakout = input.bool(false, "09 Donchian Breakout", group=gConf)
 
useCandle = input.bool(false, "10 Candle Body / ATR", group=gConf)
 
useHTF = input.bool(false, "11 Higher Timeframe EMA Trend", group=gConf)
 
useSlope = input.bool(false, "12 EMA Slope", group=gConf)
 
 
 
// === INDICATOR PARAMETERS ===
 
gParam = "05 | Indicator Parameters"
 
fastLen = input.int(9, "Fast EMA", minval=1, group=gParam)
 
slowLen = input.int(34, "Slow EMA", minval=2, group=gParam)
 
rsiLen = input.int(14, "RSI Length", minval=2, group=gParam)
 
rsiLong = input.float(52, "Long RSI Threshold", minval=1, maxval=99, group=gParam)
 
rsiShort = input.float(48, "Short RSI Threshold", minval=1, maxval=99, group=gParam)
 
macdFast = input.int(12, "MACD Fast", minval=1, group=gParam)
 
macdSlow = input.int(26, "MACD Slow", minval=2, group=gParam)
 
macdSignal = input.int(9, "MACD Signal", minval=1, group=gParam)
 
adxLen = input.int(14, "DMI / ADX Length", minval=2, group=gParam)
 
adxMin = input.float(18, "Minimum ADX", minval=1, group=gParam)
 
bbLen = input.int(20, "Bollinger Basis Length", minval=2, group=gParam)
 
stFactor = input.float(2.0, "Supertrend Factor", minval=0.1, group=gParam)
 
stLen = input.int(10, "Supertrend ATR Length", minval=1, group=gParam)
 
volLen = input.int(20, "Volume Average Length", minval=1, group=gParam)
 
volMult = input.float(1.0, "Relative Volume Minimum", minval=0.1, group=gParam)
 
breakLen = input.int(20, "Donchian Lookback", minval=2, group=gParam)
 
bodyMin = input.float(0.25, "Minimum Candle Body / ATR", minval=0.01, group=gParam)
 
htf = input.timeframe("60", "Higher Timeframe", group=gParam)
 
htfLen = input.int(50, "Higher Timeframe EMA", minval=2, group=gParam)
 
slopeBars = input.int(3, "EMA Slope Lookback", minval=1, group=gParam)
 
 
 
// === SYNAPSE-STYLE FILTER ===
 
gSyn = "06 | Synapse-Style ATR / EMA Trend"
 
useSyn = input.bool(true, "Require Synapse Direction", group=gSyn)
 
synEMALen = input.int(8, "Synapse EMA Length", minval=1, group=gSyn)
 
synATRLen = input.int(8, "Synapse ATR Length", minval=1, group=gSyn)
 
synFactor = input.float(1.618, "Synapse ATR Multiplier", minval=0.1, group=gSyn)
 
showSyn = input.bool(true, "Plot Synapse Trend Line", group=gSyn)
 
 
 
// === SELECTABLE ENTRY ENGINES ===
 
gEngine = "07 | Optional Entry Engines"
 
entryEngine = input.string("Confluence Transition", "Entry Engine", options=["Confluence Transition", "Trend Continuation", "EMA Pullback", "Breakout", "Breakout Retest", "RSI Reversal", "Synapse Flip", "Any Enabled Engine"], group=gEngine)
 
useEngineGate = input.bool(true, "Enable Entry Engine Gate (OFF = Score-Only)", group=gEngine)
 
useTrendEngine = input.bool(true, "Any Mode: Trend Continuation", group=gEngine)
 
usePullbackEngine = input.bool(true, "Any Mode: EMA Pullback", group=gEngine)
 
useBreakEngine = input.bool(true, "Any Mode: Donchian Breakout", group=gEngine)
 
useRetestEngine = input.bool(false, "Any Mode: Breakout Retest", group=gEngine)
 
useReversalEngine = input.bool(false, "Any Mode: RSI Reversal", group=gEngine)
 
useFlipEngine = input.bool(false, "Any Mode: Synapse Flip", group=gEngine)
 
retestBars = input.int(5, "Retest Maximum Bars After Breakout", minval=1, maxval=50, group=gEngine)
 
retestATR = input.float(0.35, "Retest Tolerance (ATR)", minval=0.01, group=gEngine)
 
reversalLow = input.float(30, "RSI Oversold Cross", minval=1, maxval=49, group=gEngine)
 
reversalHigh = input.float(70, "RSI Overbought Cross", minval=51, maxval=99, group=gEngine)
 
 
 
// === OPTIONAL MARTINGALE: SIZE ONLY AFTER CLOSED LOSSES ===
 
gMG = "08 | Optional Martingale"
 
useMartingale = input.bool(false, "Enable Martingale (OFF by default)", group=gMG)
 
mgMultiplier = input.float(2.0, "Size Multiplier After Loss", minval=1.0, step=0.25, group=gMG)
 
mgMaxContracts = input.int(8, "Absolute Maximum Contracts", minval=1, group=gMG)
 
mgMaxSteps = input.int(3, "Maximum Consecutive Size Increases", minval=0, maxval=12, group=gMG)
 
mgResetSession = input.bool(false, "Reset Martingale at New 18:00 Session", group=gMG)
 
mgResetBreakeven = input.bool(true, "Reset on Breakeven Trade", group=gMG)
 
mgIncludeFees = input.bool(true, "Count Net Trade Profit After Fees", group=gMG)
 
 
 
// === CALCULATIONS ===
 
atr = ta.atr(atrLen)
 
emaFast = ta.ema(close, fastLen)
 
emaSlow = ta.ema(close, slowLen)
 
rsi = ta.rsi(close, rsiLen)
 
[macdLine, macdSig, macdHist] = ta.macd(close, macdFast, macdSlow, macdSignal)
 
[diPlus, diMinus, adx] = ta.dmi(adxLen, adxLen)
 
vwapLine = ta.vwap(hlc3)
 
bbBasis = ta.sma(close, bbLen)
 
[stLine, stDirection] = ta.supertrend(stFactor, stLen)
 
volAvg = ta.sma(volume, volLen)
 
prevHigh = ta.highest(high, breakLen)[1]
 
prevLow = ta.lowest(low, breakLen)[1]
 
trailEMA = ta.ema(close, trailEMALen)
 
// Previous completed HTF bar avoids lookahead/repainting.
 
htfClose = request.security(syminfo.tickerid, htf, close[1], lookahead=barmerge.lookahead_on)
 
htfEMA = request.security(syminfo.tickerid, htf, ta.ema(close, htfLen)[1], lookahead=barmerge.lookahead_on)
 
synBasis = ta.ema(hlc3, synEMALen)
 
synBand = ta.atr(synATRLen) * synFactor
 
var float synLine = na
 
var int synDirection = 1
 
priorLine = nz(synLine[1], synBasis)
 
priorDirection = nz(synDirection[1], 1)
 
synDirection := close > priorLine ? 1 : close < priorLine ? -1 : priorDirection
 
synLine := synDirection == 1 ? math.max(synBasis - synBand, priorDirection == 1 ? priorLine : synBasis - synBand) : math.min(synBasis + synBand, priorDirection == -1 ? priorLine : synBasis + synBand)
 
plot(showSyn ? synLine : na, "Synapse-Style Trend", color=synDirection == 1 ? color.teal : color.orange, linewidth=2)
 
plot(emaFast, "Fast EMA", color=color.new(color.aqua, 50))
 
plot(emaSlow, "Slow EMA", color=color.new(color.yellow, 50))
 
 
 
// === SCORING: each enabled condition counts once ===
 
int enabled = 0
 
int longScore = 0
 
int shortScore = 0
 
if useEMA
 
    enabled += 1
 
    longScore += emaFast > emaSlow ? 1 : 0
 
    shortScore += emaFast < emaSlow ? 1 : 0
 
if useRSI
 
    enabled += 1
 
    longScore += rsi >= rsiLong ? 1 : 0
 
    shortScore += rsi <= rsiShort ? 1 : 0
 
if useMACD
 
    enabled += 1
 
    longScore += macdHist > 0 ? 1 : 0
 
    shortScore += macdHist < 0 ? 1 : 0
 
if useADX
 
    enabled += 1
 
    longScore += adx >= adxMin and diPlus > diMinus ? 1 : 0
 
    shortScore += adx >= adxMin and diMinus > diPlus ? 1 : 0
 
if useVWAP
 
    enabled += 1
 
    longScore += close > vwapLine ? 1 : 0
 
    shortScore += close < vwapLine ? 1 : 0
 
if useBB
 
    enabled += 1
 
    longScore += close > bbBasis ? 1 : 0
 
    shortScore += close < bbBasis ? 1 : 0
 
if useST
 
    enabled += 1
 
    longScore += stDirection < 0 ? 1 : 0
 
    shortScore += stDirection > 0 ? 1 : 0
 
if useVolume
 
    enabled += 1
 
    longScore += volume >= volAvg * volMult ? 1 : 0
 
    shortScore += volume >= volAvg * volMult ? 1 : 0
 
if useBreakout
 
    enabled += 1
 
    longScore += close > prevHigh ? 1 : 0
 
    shortScore += close < prevLow ? 1 : 0
 
if useCandle
 
    enabled += 1
 
    longScore += close > open and (close - open) >= atr * bodyMin ? 1 : 0
 
    shortScore += close < open and (open - close) >= atr * bodyMin ? 1 : 0
 
if useHTF
 
    enabled += 1
 
    longScore += htfClose > htfEMA ? 1 : 0
 
    shortScore += htfClose < htfEMA ? 1 : 0
 
if useSlope
 
    enabled += 1
 
    longScore += emaFast > emaFast[slopeBars] ? 1 : 0
 
    shortScore += emaFast < emaFast[slopeBars] ? 1 : 0
 
 
 
// === OVERNIGHT SESSION ACCOUNTING ===
 
// Trading day is identified by the calendar date at the 18:00 ET session start.
 
// At 00:00-17:00, the prior calendar day owns the overnight session.
 
localHour = hour(time, tz)
 
localMinute = minute(time, tz)
 
localDOW = dayofweek(time, tz)
 
startDOW = localHour >= 18 ? localDOW : localDOW == dayofweek.sunday ? dayofweek.saturday : localDOW - 1
 
selectedDay = (startDOW == dayofweek.sunday and sun) or (startDOW == dayofweek.monday and mon) or (startDOW == dayofweek.tuesday and tue) or (startDOW == dayofweek.wednesday and wed) or (startDOW == dayofweek.thursday and thu)
 
inMarketHours = localHour >= 18 or localHour < 17
 
inWindow = not na(time(timeframe.period, tradeWindow, tz))
// Use bar CLOSE time because orders in this strategy are placed on close.
// This prevents a new order at 09:00 on the 08:50-09:00 bar.
closeClock = hour(time_close, tz) * 60 + minute(time_close, tz)
excludeStart = excludeStartHour * 60 + excludeStartMinute
excludeEnd = excludeEndHour * 60 + excludeEndMinute
// Identical start/end times mean a full-day exclusion when enabled.
clockExcluded = excludeStart == excludeEnd ? true : excludeStart < excludeEnd ? (closeClock >= excludeStart and closeClock < excludeEnd) : (closeClock >= excludeStart or closeClock < excludeEnd)
isExcluded = useExclusion and clockExcluded
// Detect first bar whose CLOSE falls in the excluded period.
exclusionBegins = isExcluded and not isExcluded[1]
if exclusionBegins and excludePositionMode == "Flatten" and strategy.position_size != 0
    strategy.cancel_all()
    strategy.close_all(comment="Exclusion Window Flatten", immediately=true)
 
// Track flat transitions to optionally delay new entries after an exit.
var int lastExitBar = na
if strategy.position_size == 0 and strategy.position_size[1] != 0
    lastExitBar := bar_index
exitDelayOK = not useExitDelay or na(lastExitBar) or bar_index - lastExitBar > exitDelayBars
 
 
// The 18:00 session reset is independent of the chart's selected trade window.
 
newSession = inMarketHours and (not inMarketHours[1] or (localHour >= 18 and localHour[1] < 18))
 
var float sessionBaseNet = na
 
var int entriesToday = 0
 
var int lastEntryBar = na
 
var bool locked = false
 
if barstate.isfirst or newSession
 
    sessionBaseNet := strategy.netprofit
 
    entriesToday := 0
 
    locked := false
 
sessionClosedPnL = strategy.netprofit - nz(sessionBaseNet, strategy.netprofit)
 
sessionPnL = sessionClosedPnL + (includeOpenPnL ? strategy.openprofit : 0.0)
 
if (useDailyTP and sessionPnL >= dailyTP) or (useDailyLoss and sessionPnL <= -dailyLoss)
 
    locked := true
 
    strategy.cancel_all()
 
    strategy.close_all(comment="Overnight P&L Lock", immediately=true)
 
if flattenAtClose and not inMarketHours and strategy.position_size != 0
 
    strategy.close_all(comment="17:00 Session Flatten", immediately=true)
 
 
 
// === CLOSED-TRADE MARTINGALE TRACKING ===
 
var int mgLossStreak = 0
 
var int lastClosedCount = 0
 
if strategy.closedtrades > lastClosedCount
 
    for tradeNo = lastClosedCount to strategy.closedtrades - 1
 
        float tradeResult = strategy.closedtrades.profit(tradeNo)
 
        if mgIncludeFees
 
            tradeResult -= strategy.closedtrades.commission(tradeNo)
 
        if tradeResult < 0
 
            mgLossStreak += 1
 
        else if tradeResult > 0 or mgResetBreakeven
 
            mgLossStreak := 0
 
    lastClosedCount := strategy.closedtrades
 
if newSession and mgResetSession
 
    mgLossStreak := 0
 
int mgSteps = useMartingale ? math.min(mgLossStreak, mgMaxSteps) : 0
 
int orderQty = useMartingale ? math.min(mgMaxContracts, math.max(1, int(math.round(qty * math.pow(mgMultiplier, mgSteps))))) : qty
 
 
 
// === ENTRY ENGINE SIGNALS (all based on completed chart bars) ===
 
bool trendLong = emaFast > emaSlow and close > emaFast and close[1] <= emaFast[1] and close > open
 
bool trendShort = emaFast < emaSlow and close < emaFast and close[1] >= emaFast[1] and close < open
 
bool pullLong = emaFast > emaSlow and low <= emaFast and close > emaFast and close > open
 
bool pullShort = emaFast < emaSlow and high >= emaFast and close < emaFast and close < open
 
bool breakLong = close > prevHigh and close[1] <= prevHigh[1]
 
bool breakShort = close < prevLow and close[1] >= prevLow[1]
 
int sinceBreakLong = ta.barssince(breakLong)
 
int sinceBreakShort = ta.barssince(breakShort)
 
float brokenHigh = ta.valuewhen(breakLong, prevHigh, 0)
 
float brokenLow = ta.valuewhen(breakShort, prevLow, 0)
 
bool retestLong = not na(sinceBreakLong) and sinceBreakLong > 0 and sinceBreakLong <= retestBars and low <= brokenHigh + atr * retestATR and close > brokenHigh and close > open
 
bool retestShort = not na(sinceBreakShort) and sinceBreakShort > 0 and sinceBreakShort <= retestBars and high >= brokenLow - atr * retestATR and close < brokenLow and close < open
 
bool reversalLong = ta.crossover(rsi, reversalLow)
 
bool reversalShort = ta.crossunder(rsi, reversalHigh)
 
bool flipLong = synDirection == 1 and synDirection[1] == -1
 
bool flipShort = synDirection == -1 and synDirection[1] == 1
 
bool anyLong = (useTrendEngine and trendLong) or (usePullbackEngine and pullLong) or (useBreakEngine and breakLong) or (useRetestEngine and retestLong) or (useReversalEngine and reversalLong) or (useFlipEngine and flipLong)
 
bool anyShort = (useTrendEngine and trendShort) or (usePullbackEngine and pullShort) or (useBreakEngine and breakShort) or (useRetestEngine and retestShort) or (useReversalEngine and reversalShort) or (useFlipEngine and flipShort)
 
 
 
// === ENTRY SIGNALS ===
 
validScore = not useConfluence or (enabled > 0 and minimum <= enabled)
 
longReady = validScore and (not useConfluence or longScore >= minimum) and (not useSyn or (synDirection == 1 and close > synLine))
 
shortReady = validScore and (not useConfluence or shortScore >= minimum) and (not useSyn or (synDirection == -1 and close < synLine))
 
// In score-only mode, requireFresh controls repeated signals. Engine mode requires a new event.
 
longScoreTrigger = longReady and (not requireFresh or not longReady[1])
 
shortScoreTrigger = shortReady and (not requireFresh or not shortReady[1])
 
longEngine = switch entryEngine
 
    "Confluence Transition" => longScoreTrigger
 
    "Trend Continuation" => trendLong
 
    "EMA Pullback" => pullLong
 
    "Breakout" => breakLong
 
    "Breakout Retest" => retestLong
 
    "RSI Reversal" => reversalLong
 
    "Synapse Flip" => flipLong
 
    => anyLong
 
shortEngine = switch entryEngine
 
    "Confluence Transition" => shortScoreTrigger
 
    "Trend Continuation" => trendShort
 
    "EMA Pullback" => pullShort
 
    "Breakout" => breakShort
 
    "Breakout Retest" => retestShort
 
    "RSI Reversal" => reversalShort
 
    "Synapse Flip" => flipShort
 
    => anyShort
 
longTrigger = longReady and (not useEngineGate ? longScoreTrigger : longEngine)
 
shortTrigger = shortReady and (not useEngineGate ? shortScoreTrigger : shortEngine)
 
canEnter = barstate.isconfirmed and inMarketHours and inWindow and not isExcluded and exitDelayOK and selectedDay and not locked and (not useMaxTrades or entriesToday < maxTrades) and strategy.position_size == 0 and (not useCooldown or na(lastEntryBar) or bar_index - lastEntryBar >= cooldown) and not na(atr)
 
// Store ATR-based distances at signal time so initial stops do not widen with future volatility.
 
var float entryStopDistance = na
 
var float entryTargetDistance = na
 
var float entryATR = na
 
var float highestSinceEntry = na
 
var float lowestSinceEntry = na
 
var float activeStop = na
 
f_distance(string unit, float value, float currentATR, float entryPrice, float riskDistance) =>
 
    float distance = switch unit
 
        "Ticks" => value * syminfo.mintick
 
        "Points" => value
 
        "ATR" => value * currentATR
 
        "Dollars / Contract" => value / syminfo.pointvalue
 
        "Entry Price %" => entryPrice * value / 100.0
 
        "Risk / Reward" => value * riskDistance
 
        => value * currentATR
 
    math.max(syminfo.mintick, math.ceil(distance / syminfo.mintick) * syminfo.mintick)
 
if canEnter and longTrigger and side != "Short Only"
 
    entryATR := atr
 
    entryStopDistance := f_distance(stopMode, stopValue, atr, close, na)
 
    entryTargetDistance := f_distance(targetMode, targetValue, atr, close, entryStopDistance)
 
    highestSinceEntry := na
 
    lowestSinceEntry := na
 
    activeStop := na
 
    strategy.entry("Long", strategy.long, qty=orderQty)
 
    entriesToday += 1
 
    lastEntryBar := bar_index
 
else if canEnter and shortTrigger and side != "Long Only"
 
    entryATR := atr
 
    entryStopDistance := f_distance(stopMode, stopValue, atr, close, na)
 
    entryTargetDistance := f_distance(targetMode, targetValue, atr, close, entryStopDistance)
 
    highestSinceEntry := na
 
    lowestSinceEntry := na
 
    activeStop := na
 
    strategy.entry("Short", strategy.short, qty=orderQty)
 
    entriesToday += 1
 
    lastEntryBar := bar_index
 
 
 
// === EXIT ENGINE ===
 
if strategy.position_size > 0
 
    highestSinceEntry := math.max(nz(highestSinceEntry, strategy.position_avg_price), high)
 
    float baseStop = strategy.position_avg_price - nz(entryStopDistance, atr * stopValue)
 
    float candidate = useStop ? baseStop : na
 
    bool trailOn = highestSinceEntry - strategy.position_avg_price >= nz(entryATR, atr) * trailActivate
 
    if trailOn and (exitMode == "ATR Trail" or exitMode == "ATR + EMA Trail")
 
        candidate := math.max(nz(candidate, baseStop), highestSinceEntry - atr * trailATR)
 
    if trailOn and (exitMode == "EMA Trail" or exitMode == "ATR + EMA Trail")
 
        candidate := math.max(nz(candidate, baseStop), trailEMA - atr * trailBuffer)
 
    if useBreakEven and highestSinceEntry - strategy.position_avg_price >= nz(entryATR, atr) * breakEvenATR
 
        candidate := math.max(nz(candidate, baseStop), strategy.position_avg_price + breakEvenTicks * syminfo.mintick)
 
    activeStop := na(candidate) ? na : math.max(nz(activeStop, candidate), candidate)
 
    if not na(activeStop) or useTarget
 
        strategy.exit("Long Exit", "Long", stop=activeStop, limit=useTarget ? strategy.position_avg_price + entryTargetDistance : na)
 
    if useOppositeExit and synDirection == -1
 
        strategy.close("Long", comment="Synapse Reversal")
 
else if strategy.position_size < 0
 
    lowestSinceEntry := math.min(nz(lowestSinceEntry, strategy.position_avg_price), low)
 
    float baseStop = strategy.position_avg_price + nz(entryStopDistance, atr * stopValue)
 
    float candidate = useStop ? baseStop : na
 
    bool trailOn = strategy.position_avg_price - lowestSinceEntry >= nz(entryATR, atr) * trailActivate
 
    if trailOn and (exitMode == "ATR Trail" or exitMode == "ATR + EMA Trail")
 
        candidate := math.min(nz(candidate, baseStop), lowestSinceEntry + atr * trailATR)
 
    if trailOn and (exitMode == "EMA Trail" or exitMode == "ATR + EMA Trail")
 
        candidate := math.min(nz(candidate, baseStop), trailEMA + atr * trailBuffer)
 
    if useBreakEven and strategy.position_avg_price - lowestSinceEntry >= nz(entryATR, atr) * breakEvenATR
 
        candidate := math.min(nz(candidate, baseStop), strategy.position_avg_price - breakEvenTicks * syminfo.mintick)
 
    activeStop := na(candidate) ? na : math.min(nz(activeStop, candidate), candidate)
 
    if not na(activeStop) or useTarget
 
        strategy.exit("Short Exit", "Short", stop=activeStop, limit=useTarget ? strategy.position_avg_price - entryTargetDistance : na)
 
    if useOppositeExit and synDirection == 1
 
        strategy.close("Short", comment="Synapse Reversal")
 
else
 
    highestSinceEntry := na
 
    lowestSinceEntry := na
 
    activeStop := na
 
plot(activeStop, "Active Protective Stop", color=color.red, style=plot.style_linebr, linewidth=2)
 
plotshape(canEnter and longTrigger and side != "Short Only", title="Long Signal", style=shape.triangleup, location=location.belowbar, color=color.lime, size=size.tiny)
 
plotshape(canEnter and shortTrigger and side != "Long Only", title="Short Signal", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.tiny)
 
 
 
// === STATUS DASHBOARD ===
 
var table dash = table.new(position.top_right, 2, 7, border_width=1)
 
if barstate.islast
 
    table.cell(dash, 0, 0, "Session P&L", text_color=color.white, bgcolor=color.gray)
 
    table.cell(dash, 1, 0, str.tostring(sessionPnL, "#.##") + " USD", text_color=sessionPnL >= 0 ? color.lime : color.red, bgcolor=color.black)
 
    table.cell(dash, 0, 1, "Entries", text_color=color.white, bgcolor=color.gray)
 
    table.cell(dash, 1, 1, str.tostring(entriesToday) + "/" + str.tostring(maxTrades), text_color=color.white, bgcolor=color.black)
 
    table.cell(dash, 0, 2, "Confluences L/S", text_color=color.white, bgcolor=color.gray)
 
    table.cell(dash, 1, 2, str.tostring(longScore) + "/" + str.tostring(shortScore) + " of " + str.tostring(enabled), text_color=color.white, bgcolor=color.black)
 
    table.cell(dash, 0, 3, "Trading", text_color=color.white, bgcolor=color.gray)
 
    table.cell(dash, 1, 3, locked ? "LOCKED" : selectedDay and inWindow and inMarketHours and not isExcluded ? "ENABLED" : "OFF", text_color=locked ? color.red : color.white, bgcolor=color.black)
 
    table.cell(dash, 0, 4, "Synapse", text_color=color.white, bgcolor=color.gray)
 
    table.cell(dash, 1, 4, synDirection == 1 ? "BULLISH" : "BEARISH", text_color=synDirection == 1 ? color.lime : color.orange, bgcolor=color.black)
 
 
 
    table.cell(dash, 0, 5, "Entry Engine", text_color=color.white, bgcolor=color.gray)
 
    table.cell(dash, 1, 5, useEngineGate ? entryEngine : "Score Only", text_color=color.white, bgcolor=color.black)
 
    table.cell(dash, 0, 6, "Next Qty / Losses", text_color=color.white, bgcolor=color.gray)
 
    table.cell(dash, 1, 6, str.tostring(orderQty) + " / " + str.tostring(mgLossStreak), text_color=color.white, bgcolor=color.black)

← 返回列表