CNPS24_BASIS MEAN REVERSION

PhaisinhOnline · strategy · 1508 行 · 点赞 10 · TradingView 原页

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

Pine Script

//@version=6
strategy(
     title="CNPS24 BASIS MEAN REVERSION V3",
     shorttitle="CNPS24 BASIS V3",
     overlay=true,
     initial_capital=100000000,
     default_qty_type=strategy.fixed,
     default_qty_value=3,
     pyramiding=0,
     margin_long=0,
     margin_short=0,
     slippage=3,
     commission_type=strategy.commission.cash_per_contract,
     commission_value=10000,
     fill_orders_on_standard_ohlc=true,
     process_orders_on_close=true,
     calc_on_order_fills=true,
     max_labels_count=300,
     max_lines_count=300,
     max_bars_back=5000
)
 
 
// ============================================================================
// CNPS24 BASIS MEAN REVERSION V3
//
// VN30F1M RELATIVE-VALUE MODEL
//
// FUTURES PRICE
//       -
// VN30 SPOT INDEX
//       =
// INTRADAY BASIS
//
// ENTRY:
//
// Extreme discount
// -> Basis Z <= -Entry Z
// -> Arm LONG
// -> Basis hooks back upward
// -> Price confirmation
// -> LONG
//
// Extreme premium
// -> Basis Z >= +Entry Z
// -> Arm SHORT
// -> Basis hooks back downward
// -> Price confirmation
// -> SHORT
//
// COST-AWARE:
// - Max 2 trades / day
// - Cooldown 10 bars
// - No break-even
// - SL = 6 points
// - TP = 12 points
// - Statistical exit only if gross profit >= 2 points
//
// CURRENT CHART TIMEFRAME
// POSITION = 3 CONTRACTS
// ============================================================================
 
 
// ============================================================================
// SECTION 1: TRADE CONTROL
// ============================================================================
 
tradeDirection = input.string(
     "Both",
     title="Trade Direction",
     options=["Long", "Short", "Both"],
     group="Trade Control"
)
 
bool allowLong = tradeDirection == "Long" or tradeDirection == "Both"
bool allowShort = tradeDirection == "Short" or tradeDirection == "Both"
 
maximumTradesPerDay = input.int(
     2,
     title="Maximum Trades Per Day",
     minval=1,
     maxval=10,
     group="Trade Control"
)
 
cooldownBars = input.int(
     10,
     title="Cooldown Bars After Exit",
     minval=0,
     maxval=100,
     group="Trade Control"
)
 
 
// ============================================================================
// SECTION 2: VN30 SPOT REFERENCE
// ============================================================================
 
referenceSymbol = input.symbol(
     "HOSE:VN30",
     title="VN30 Spot Reference",
     group="Basis Model"
)
 
basisLookback = input.int(
     60,
     title="Basis Mean / Z Window",
     minval=20,
     maxval=500,
     group="Basis Model"
)
 
longBasisVolLookback = input.int(
     180,
     title="Long Basis Volatility Window",
     minval=60,
     maxval=1000,
     group="Basis Model"
)
 
 
// ============================================================================
// SECTION 3: ENTRY EXTREME
// ============================================================================
 
entryZScore = input.float(
     1.50,
     title="Entry Absolute Basis Z",
     minval=0.50,
     maxval=5.0,
     step=0.10,
     group="Entry Logic"
)
 
exitZScore = input.float(
     0.25,
     title="Mean-Reversion Exit Z",
     minval=0.0,
     maxval=2.0,
     step=0.05,
     group="Entry Logic"
)
 
maximumExtremeZ = input.float(
     3.50,
     title="Maximum Acceptable Entry Extreme",
     minval=1.0,
     maxval=10.0,
     step=0.25,
     group="Entry Logic"
)
 
 
// ============================================================================
// SECTION 4: SETUP LIFETIME
// ============================================================================
 
extremeSetupLifetime = input.int(
     20,
     title="Extreme Setup Lifetime Bars",
     minval=2,
     maxval=100,
     group="Entry Logic"
)
 
confirmationWindowBars = input.int(
     3,
     title="Confirmation Window After Hook",
     minval=0,
     maxval=20,
     group="Entry Logic"
)
 
 
// ============================================================================
// SECTION 5: PRICE CONFIRMATION
// ============================================================================
 
confirmationEMALength = input.int(
     9,
     title="Confirmation EMA",
     minval=2,
     maxval=100,
     group="Price Confirmation"
)
 
minimumBodyRatio = input.float(
     0.40,
     title="Minimum Confirmation Body / Range",
     minval=0.0,
     maxval=1.0,
     step=0.05,
     group="Price Confirmation"
)
 
requirePreviousHighLowBreak = input.bool(
     true,
     title="Require Previous High / Low Break?",
     group="Price Confirmation"
)
 
requireEMAConfirmation = input.bool(
     true,
     title="Require EMA Confirmation?",
     group="Price Confirmation"
)
 
 
// ============================================================================
// SECTION 6: VOLATILITY REGIME
// ============================================================================
 
useBasisVolatilityFilter = input.bool(
     true,
     title="Use Basis Volatility Filter?",
     group="Regime Filter"
)
 
maximumBasisVolatilityRatio = input.float(
     1.80,
     title="Maximum Short / Long Basis Volatility",
     minval=0.5,
     maxval=10.0,
     step=0.1,
     group="Regime Filter"
)
 
 
// ============================================================================
// SECTION 7: HARD RISK
// ============================================================================
 
stopLossPoints = input.float(
     6.0,
     title="Hard Stop Loss Points",
     minval=1.0,
     step=0.5,
     group="Risk Management"
)
 
takeProfitPoints = input.float(
     12.0,
     title="Hard Take Profit Points",
     minval=1.0,
     step=0.5,
     group="Risk Management"
)
 
 
// ============================================================================
// SECTION 8: STATISTICAL EXIT
// ============================================================================
 
useStatisticalExit = input.bool(
     true,
     title="Use Basis Mean Exit?",
     group="Statistical Exit"
)
 
minimumStatExitProfitPoints = input.float(
     2.0,
     title="Minimum Profit Before Statistical Exit",
     minval=0.0,
     step=0.5,
     group="Statistical Exit"
)
 
 
// ============================================================================
// SECTION 9: OPTIONAL BASIS STOP
// ============================================================================
 
useBasisEmergencyStop = input.bool(
     false,
     title="Use Emergency Z-Score Stop?",
     group="Statistical Exit"
)
 
emergencyZScore = input.float(
     3.50,
     title="Emergency Absolute Basis Z",
     minval=1.5,
     maxval=10.0,
     step=0.25,
     group="Statistical Exit"
)
 
 
// ============================================================================
// SECTION 10: OPTIONAL TIME STOP
// ============================================================================
 
useTimeStop = input.bool(
     false,
     title="Use Time Stop?",
     group="Time Stop"
)
 
maximumBarsInTrade = input.int(
     45,
     title="Maximum Bars In Trade",
     minval=5,
     maxval=500,
     group="Time Stop"
)
 
timeStopOnlyIfNotProfitable = input.bool(
     true,
     title="Time Stop Only If Trade <= 0?",
     group="Time Stop"
)
 
 
// ============================================================================
// SECTION 11: SESSION
// ============================================================================
 
strategyTimezone = input.string(
     "Asia/Ho_Chi_Minh",
     title="Strategy Timezone",
     group="Session"
)
 
morningStartHour = input.int(
     9,
     title="Morning Entry Start Hour",
     minval=0,
     maxval=23,
     group="Session"
)
 
morningStartMinute = input.int(
     5,
     title="Morning Entry Start Minute",
     minval=0,
     maxval=59,
     group="Session"
)
 
morningEndHour = input.int(
     11,
     title="Morning Entry End Hour",
     minval=0,
     maxval=23,
     group="Session"
)
 
morningEndMinute = input.int(
     20,
     title="Morning Entry End Minute",
     minval=0,
     maxval=59,
     group="Session"
)
 
afternoonStartHour = input.int(
     13,
     title="Afternoon Entry Start Hour",
     minval=0,
     maxval=23,
     group="Session"
)
 
afternoonStartMinute = input.int(
     5,
     title="Afternoon Entry Start Minute",
     minval=0,
     maxval=59,
     group="Session"
)
 
lastEntryHour = input.int(
     14,
     title="Last Entry Hour",
     minval=0,
     maxval=23,
     group="Session"
)
 
lastEntryMinute = input.int(
     15,
     title="Last Entry Minute",
     minval=0,
     maxval=59,
     group="Session"
)
 
sessionEndHour = input.int(
     14,
     title="Force Close Hour",
     minval=0,
     maxval=23,
     group="Session"
)
 
sessionEndMinute = input.int(
     45,
     title="Force Close Minute",
     minval=0,
     maxval=59,
     group="Session"
)
 
 
// ============================================================================
// SECTION 12: ALERTS
// ============================================================================
 
disableSLTPAlerts = input.bool(
     false,
     title="Disable SL / TP Alerts?",
     group="Alerts"
)
 
 
// ============================================================================
// SECTION 13: DISPLAY
// ============================================================================
 
showEMA = input.bool(
     false,
     title="Show Confirmation EMA?",
     group="Display"
)
 
showSignals = input.bool(
     false,
     title="Show Setup / Entry Markers?",
     group="Display"
)
 
showActiveSLTP = input.bool(
     true,
     title="Show Active SL / TP?",
     group="Display"
)
 
showDiagnostics = input.bool(
     false,
     title="Show Diagnostics?",
     group="Display"
)
 
 
// ============================================================================
// SECTION 14: TIME ENGINE
// ============================================================================
 
int currentMinute = hour(time, strategyTimezone) * 60 + minute(time, strategyTimezone)
 
int currentCloseMinute = hour(time_close, strategyTimezone) * 60 + minute(time_close, strategyTimezone)
 
int morningStartTotal = morningStartHour * 60 + morningStartMinute
 
int morningEndTotal = morningEndHour * 60 + morningEndMinute
 
int afternoonStartTotal = afternoonStartHour * 60 + afternoonStartMinute
 
int lastEntryTotal = lastEntryHour * 60 + lastEntryMinute
 
int sessionEndTotal = sessionEndHour * 60 + sessionEndMinute
 
bool morningSession = currentMinute >= morningStartTotal and currentMinute <= morningEndTotal
 
bool afternoonSession = currentMinute >= afternoonStartTotal and currentMinute <= lastEntryTotal
 
bool entrySession = morningSession or afternoonSession
 
 
// ============================================================================
// SECTION 15: DAILY COUNTER
// ============================================================================
 
int dayKey = year(time, strategyTimezone) * 10000 + month(time, strategyTimezone) * 100 + dayofmonth(time, strategyTimezone)
 
bool newTradingDay = bar_index == 0 or dayKey != nz(dayKey[1], dayKey)
 
var int tradesToday = 0
 
if newTradingDay
    tradesToday := 0
 
 
// ============================================================================
// SECTION 16: VN30 SPOT DATA
// ============================================================================
 
float spotClose = request.security(
     referenceSymbol,
     timeframe.period,
     close,
     gaps=barmerge.gaps_off,
     lookahead=barmerge.lookahead_off,
     ignore_invalid_symbol=true
)
 
 
// ============================================================================
// SECTION 17: BASIS
// ============================================================================
//
// Basis = Futures - VN30 Spot
//
// Positive:
// Futures premium.
//
// Negative:
// Futures discount.
//
// ============================================================================
 
float basis = na
 
if not na(spotClose)
    basis := close - spotClose
 
 
float basisMean = ta.sma(
     basis,
     basisLookback
)
 
float basisStdev = ta.stdev(
     basis,
     basisLookback
)
 
float basisZ = na
 
if not na(basisStdev) and basisStdev > syminfo.mintick
    basisZ := (basis - basisMean) / basisStdev
 
 
// ============================================================================
// SECTION 18: BASIS VOLATILITY REGIME
// ============================================================================
 
float longBasisStdev = ta.stdev(
     basis,
     longBasisVolLookback
)
 
float basisVolatilityRatio = na
 
if not na(longBasisStdev) and longBasisStdev > syminfo.mintick
    basisVolatilityRatio := basisStdev / longBasisStdev
 
 
bool basisVolatilityOK = (
     not useBasisVolatilityFilter or
     (
         not na(basisVolatilityRatio) and
         basisVolatilityRatio <= maximumBasisVolatilityRatio
     )
)
 
 
// ============================================================================
// SECTION 19: MODEL READY
// ============================================================================
 
bool modelReady = (
     not na(spotClose) and
     not na(basis) and
     not na(basisMean) and
     not na(basisStdev) and
     basisStdev > syminfo.mintick and
     not na(basisZ) and
     basisVolatilityOK
)
 
 
// ============================================================================
// SECTION 20: PRICE CONFIRMATION INDICATORS
// ============================================================================
 
float confirmationEMA = ta.ema(
     close,
     confirmationEMALength
)
 
float candleRange = high - low
 
float candleBody = math.abs(close - open)
 
float bodyRatio = 0.0
 
if candleRange > 0
    bodyRatio := candleBody / candleRange
 
 
bool bullishCandle = close > open
 
bool bearishCandle = close < open
 
bool bodyQualityOK = bodyRatio >= minimumBodyRatio
 
 
// ============================================================================
// SECTION 21: EXTREME SETUP STATE
// ============================================================================
 
var bool longExtremeArmed = false
 
var bool shortExtremeArmed = false
 
var int longExtremeBar = na
 
var int shortExtremeBar = na
 
var bool longHookActive = false
 
var bool shortHookActive = false
 
var int longHookBar = na
 
var int shortHookBar = na
 
 
// ============================================================================
// SECTION 22: RESET AT NEW DAY
// ============================================================================
 
if newTradingDay
 
    longExtremeArmed := false
    shortExtremeArmed := false
 
    longHookActive := false
    shortHookActive := false
 
    longExtremeBar := na
    shortExtremeBar := na
 
    longHookBar := na
    shortHookBar := na
 
 
// ============================================================================
// SECTION 23: ARM LONG EXTREME
// ============================================================================
 
if (
     strategy.position_size == 0 and
     entrySession and
     modelReady and
     basisZ <= -entryZScore and
     basisZ > -maximumExtremeZ
)
 
    longExtremeArmed := true
 
    longExtremeBar := bar_index
 
    longHookActive := false
 
    longHookBar := na
 
    shortExtremeArmed := false
 
    shortHookActive := false
 
 
// ============================================================================
// SECTION 24: ARM SHORT EXTREME
// ============================================================================
 
if (
     strategy.position_size == 0 and
     entrySession and
     modelReady and
     basisZ >= entryZScore and
     basisZ < maximumExtremeZ
)
 
    shortExtremeArmed := true
 
    shortExtremeBar := bar_index
 
    shortHookActive := false
 
    shortHookBar := na
 
    longExtremeArmed := false
 
    longHookActive := false
 
 
// ============================================================================
// SECTION 25: EXTREME EXPIRATION
// ============================================================================
 
bool longExtremeExpired = (
     longExtremeArmed and
     not na(longExtremeBar) and
     bar_index - longExtremeBar > extremeSetupLifetime
)
 
bool shortExtremeExpired = (
     shortExtremeArmed and
     not na(shortExtremeBar) and
     bar_index - shortExtremeBar > extremeSetupLifetime
)
 
 
if longExtremeExpired
 
    longExtremeArmed := false
 
    longHookActive := false
 
 
if shortExtremeExpired
 
    shortExtremeArmed := false
 
    shortHookActive := false
 
 
// ============================================================================
// SECTION 26: LONG REVERSAL HOOK
// ============================================================================
 
bool longHookEvent = (
     longExtremeArmed and
     modelReady and
     ta.crossover(
         basisZ,
         -entryZScore
     )
)
 
 
if longHookEvent
 
    longHookActive := true
 
    longHookBar := bar_index
 
    longExtremeArmed := false
 
 
// ============================================================================
// SECTION 27: SHORT REVERSAL HOOK
// ============================================================================
 
bool shortHookEvent = (
     shortExtremeArmed and
     modelReady and
     ta.crossunder(
         basisZ,
         entryZScore
     )
)
 
 
if shortHookEvent
 
    shortHookActive := true
 
    shortHookBar := bar_index
 
    shortExtremeArmed := false
 
 
// ============================================================================
// SECTION 28: HOOK EXPIRATION
// ============================================================================
 
bool longHookExpired = (
     longHookActive and
     not na(longHookBar) and
     bar_index - longHookBar > confirmationWindowBars
)
 
bool shortHookExpired = (
     shortHookActive and
     not na(shortHookBar) and
     bar_index - shortHookBar > confirmationWindowBars
)
 
 
if longHookExpired
    longHookActive := false
 
 
if shortHookExpired
    shortHookActive := false
 
 
// ============================================================================
// SECTION 29: PRICE CONFIRMATION
// ============================================================================
 
bool longEMAOK = (
     not requireEMAConfirmation or
     close > confirmationEMA
)
 
bool shortEMAOK = (
     not requireEMAConfirmation or
     close < confirmationEMA
)
 
 
bool longPreviousBreakOK = (
     not requirePreviousHighLowBreak or
     close > high[1]
)
 
bool shortPreviousBreakOK = (
     not requirePreviousHighLowBreak or
     close < low[1]
)
 
 
// ============================================================================
// SECTION 30: LONG CONFIRMATION
// ============================================================================
 
bool longConfirmation = (
     longHookActive and
     bullishCandle and
     bodyQualityOK and
     close > close[1] and
     longEMAOK and
     longPreviousBreakOK and
     modelReady and
     basisZ < 0.50 and
     barstate.isconfirmed
)
 
 
// ============================================================================
// SECTION 31: SHORT CONFIRMATION
// ============================================================================
 
bool shortConfirmation = (
     shortHookActive and
     bearishCandle and
     bodyQualityOK and
     close < close[1] and
     shortEMAOK and
     shortPreviousBreakOK and
     modelReady and
     basisZ > -0.50 and
     barstate.isconfirmed
)
 
 
// ============================================================================
// SECTION 32: POSITION STATE
// ============================================================================
 
bool flat = strategy.position_size == 0
 
bool inLong = strategy.position_size > 0
 
bool inShort = strategy.position_size < 0
 
bool newLongPosition = inLong and strategy.position_size[1] <= 0
 
bool newShortPosition = inShort and strategy.position_size[1] >= 0
 
bool positionJustClosed = flat and strategy.position_size[1] != 0
 
 
// ============================================================================
// SECTION 33: COOLDOWN
// ============================================================================
 
var int lastExitBar = na
 
if positionJustClosed
    lastExitBar := bar_index
 
bool cooldownOK = na(lastExitBar) or bar_index - lastExitBar > cooldownBars
 
 
// ============================================================================
// SECTION 34: DAILY LIMIT
// ============================================================================
 
bool tradeLimitOK = tradesToday < maximumTradesPerDay
 
 
// ============================================================================
// SECTION 35: COMMON ENTRY APPROVAL
// ============================================================================
 
bool commonEntryApproval = (
     flat and
     entrySession and
     currentCloseMinute < sessionEndTotal and
     cooldownOK and
     tradeLimitOK and
     modelReady and
     barstate.isconfirmed
)
 
 
// ============================================================================
// SECTION 36: FINAL ENTRY SIGNALS
// ============================================================================
 
bool finalLongSignal = (
     commonEntryApproval and
     allowLong and
     longConfirmation
)
 
bool finalShortSignal = (
     commonEntryApproval and
     allowShort and
     shortConfirmation
)
 
 
// ============================================================================
// SECTION 37: LONG ENTRY
// ============================================================================
 
if finalLongSignal
 
    strategy.entry(
         "Long",
         strategy.long,
         qty=3,
         comment="Basis MR Long",
         alert_message="ENTRY_LONG_CNPS24_V3"
    )
 
    tradesToday += 1
 
    longHookActive := false
 
    shortHookActive := false
 
 
// ============================================================================
// SECTION 38: SHORT ENTRY
// ============================================================================
 
if finalShortSignal
 
    strategy.entry(
         "Short",
         strategy.short,
         qty=3,
         comment="Basis MR Short",
         alert_message="ENTRY_SHORT_CNPS24_V3"
    )
 
    tradesToday += 1
 
    shortHookActive := false
 
    longHookActive := false
 
 
// ============================================================================
// SECTION 39: ACTIVE TRADE STATE
// ============================================================================
 
var float activeEntryPrice = na
 
var float activeLongSL = na
 
var float activeLongTP = na
 
var float activeShortSL = na
 
var float activeShortTP = na
 
var int activeEntryBar = na
 
 
// ============================================================================
// SECTION 40: INITIALIZE LONG
// ============================================================================
 
if newLongPosition
 
    activeEntryPrice := strategy.position_avg_price
 
    activeLongSL := activeEntryPrice - stopLossPoints
 
    activeLongTP := activeEntryPrice + takeProfitPoints
 
    activeShortSL := na
 
    activeShortTP := na
 
    activeEntryBar := bar_index
 
 
// ============================================================================
// SECTION 41: INITIALIZE SHORT
// ============================================================================
 
if newShortPosition
 
    activeEntryPrice := strategy.position_avg_price
 
    activeShortSL := activeEntryPrice + stopLossPoints
 
    activeShortTP := activeEntryPrice - takeProfitPoints
 
    activeLongSL := na
 
    activeLongTP := na
 
    activeEntryBar := bar_index
 
 
// ============================================================================
// SECTION 42: HARD LONG EXIT
// ============================================================================
 
if (
     inLong and
     not na(activeLongSL) and
     not na(activeLongTP)
)
 
    strategy.exit(
         "Long Exit",
         from_entry="Long",
         stop=activeLongSL,
         limit=activeLongTP,
         alert_profit="EXIT_LONG_TP_CNPS24_V3",
         alert_loss="EXIT_LONG_SL_CNPS24_V3",
         disable_alert=disableSLTPAlerts
    )
 
 
// ============================================================================
// SECTION 43: HARD SHORT EXIT
// ============================================================================
 
if (
     inShort and
     not na(activeShortSL) and
     not na(activeShortTP)
)
 
    strategy.exit(
         "Short Exit",
         from_entry="Short",
         stop=activeShortSL,
         limit=activeShortTP,
         alert_profit="EXIT_SHORT_TP_CNPS24_V3",
         alert_loss="EXIT_SHORT_SL_CNPS24_V3",
         disable_alert=disableSLTPAlerts
    )
 
 
// ============================================================================
// SECTION 44: OPEN TRADE PROFIT IN POINTS
// ============================================================================
 
float openTradePoints = 0.0
 
if inLong and not na(activeEntryPrice)
    openTradePoints := close - activeEntryPrice
 
if inShort and not na(activeEntryPrice)
    openTradePoints := activeEntryPrice - close
 
 
// ============================================================================
// SECTION 45: STATISTICAL MEAN EXIT
// ============================================================================
 
bool basisNearMean = (
     modelReady and
     math.abs(basisZ) <= exitZScore
)
 
bool profitableEnoughForStatExit = (
     openTradePoints >= minimumStatExitProfitPoints
)
 
 
bool longStatisticalExit = (
     inLong and
     useStatisticalExit and
     basisNearMean and
     profitableEnoughForStatExit
)
 
bool shortStatisticalExit = (
     inShort and
     useStatisticalExit and
     basisNearMean and
     profitableEnoughForStatExit
)
 
 
if longStatisticalExit
 
    strategy.close(
         "Long",
         comment="Basis Mean Exit",
         alert_message="STAT_EXIT_LONG_CNPS24_V3"
    )
 
 
if shortStatisticalExit
 
    strategy.close(
         "Short",
         comment="Basis Mean Exit",
         alert_message="STAT_EXIT_SHORT_CNPS24_V3"
    )
 
 
// ============================================================================
// SECTION 46: OPTIONAL EMERGENCY BASIS STOP
// ============================================================================
 
bool longEmergencyBasisStop = (
     inLong and
     useBasisEmergencyStop and
     modelReady and
     basisZ <= -emergencyZScore
)
 
bool shortEmergencyBasisStop = (
     inShort and
     useBasisEmergencyStop and
     modelReady and
     basisZ >= emergencyZScore
)
 
 
if longEmergencyBasisStop
 
    strategy.close(
         "Long",
         comment="Basis Emergency Stop",
         alert_message="BASIS_STOP_LONG_CNPS24_V3"
    )
 
 
if shortEmergencyBasisStop
 
    strategy.close(
         "Short",
         comment="Basis Emergency Stop",
         alert_message="BASIS_STOP_SHORT_CNPS24_V3"
    )
 
 
// ============================================================================
// SECTION 47: OPTIONAL TIME STOP
// ============================================================================
 
int barsInTrade = 0
 
if not flat and not na(activeEntryBar)
    barsInTrade := bar_index - activeEntryBar
 
 
bool timeCondition = (
     useTimeStop and
     barsInTrade >= maximumBarsInTrade
)
 
 
bool longTimeStop = (
     inLong and
     timeCondition and
     (
         not timeStopOnlyIfNotProfitable or
         openTradePoints <= 0
     )
)
 
bool shortTimeStop = (
     inShort and
     timeCondition and
     (
         not timeStopOnlyIfNotProfitable or
         openTradePoints <= 0
     )
)
 
 
if longTimeStop
 
    strategy.close(
         "Long",
         comment="Time Stop",
         alert_message="TIME_EXIT_LONG_CNPS24_V3"
    )
 
 
if shortTimeStop
 
    strategy.close(
         "Short",
         comment="Time Stop",
         alert_message="TIME_EXIT_SHORT_CNPS24_V3"
    )
 
 
// ============================================================================
// SECTION 48: CLEANUP
// ============================================================================
 
if positionJustClosed
 
    activeEntryPrice := na
 
    activeLongSL := na
 
    activeLongTP := na
 
    activeShortSL := na
 
    activeShortTP := na
 
    activeEntryBar := na
 
 
// ============================================================================
// SECTION 49: SESSION END
// ============================================================================
 
bool finalSessionBar = currentMinute < sessionEndTotal and currentCloseMinute >= sessionEndTotal
 
 
if finalSessionBar
 
    longExtremeArmed := false
 
    shortExtremeArmed := false
 
    longHookActive := false
 
    shortHookActive := false
 
 
    if strategy.position_size != 0
 
        strategy.close_all(
             immediately=true,
             comment="Session End",
             alert_message="SESSION_END_CNPS24_V3"
        )
 
 
// ============================================================================
// SECTION 50: EMA DISPLAY
// ============================================================================
 
plot(
     showEMA ? confirmationEMA : na,
     title="Confirmation EMA",
     color=color.orange,
     linewidth=1
)
 
 
// ============================================================================
// SECTION 51: HARD SL / TP DISPLAY
// ============================================================================
 
plot(
     showActiveSLTP and inLong ? activeLongSL : na,
     title="Long SL",
     color=color.red,
     linewidth=2,
     style=plot.style_linebr
)
 
plot(
     showActiveSLTP and inLong ? activeLongTP : na,
     title="Long TP",
     color=color.green,
     linewidth=2,
     style=plot.style_linebr
)
 
plot(
     showActiveSLTP and inShort ? activeShortSL : na,
     title="Short SL",
     color=color.red,
     linewidth=2,
     style=plot.style_linebr
)
 
plot(
     showActiveSLTP and inShort ? activeShortTP : na,
     title="Short TP",
     color=color.green,
     linewidth=2,
     style=plot.style_linebr
)
 
 
// ============================================================================
// SECTION 52: SETUP / SIGNAL MARKERS
// ============================================================================
 
plotshape(
     showSignals and longHookEvent,
     title="Long Basis Hook",
     style=shape.circle,
     location=location.belowbar,
     color=color.orange,
     size=size.tiny,
     text="H"
)
 
plotshape(
     showSignals and shortHookEvent,
     title="Short Basis Hook",
     style=shape.circle,
     location=location.abovebar,
     color=color.orange,
     size=size.tiny,
     text="H"
)
 
plotshape(
     showSignals and finalLongSignal,
     title="Long Entry",
     style=shape.triangleup,
     location=location.belowbar,
     color=color.green,
     size=size.small,
     text="L",
     textcolor=color.white
)
 
plotshape(
     showSignals and finalShortSignal,
     title="Short Entry",
     style=shape.triangledown,
     location=location.abovebar,
     color=color.red,
     size=size.small,
     text="S",
     textcolor=color.white
)
 
 
// ============================================================================
// SECTION 53: DIAGNOSTIC COUNTERS
// ============================================================================
 
var int longExtremeCount = 0
 
var int shortExtremeCount = 0
 
var int longHookCount = 0
 
var int shortHookCount = 0
 
var int longEntryCount = 0
 
var int shortEntryCount = 0
 
 
if (
     modelReady and
     basisZ <= -entryZScore and
     basisZ > -maximumExtremeZ
)
 
    longExtremeCount += 1
 
 
if (
     modelReady and
     basisZ >= entryZScore and
     basisZ < maximumExtremeZ
)
 
    shortExtremeCount += 1
 
 
if longHookEvent
    longHookCount += 1
 
 
if shortHookEvent
    shortHookCount += 1
 
 
if finalLongSignal
    longEntryCount += 1
 
 
if finalShortSignal
    shortEntryCount += 1
 
 
// ============================================================================
// SECTION 54: DIAGNOSTICS
// ============================================================================
 
var table diagnostics = table.new(
     position.top_right,
     2,
     18,
     border_width=1
)
 
 
if showDiagnostics and barstate.islast
 
    string positionText = "FLAT"
 
    if inLong
        positionText := "LONG"
 
    else if inShort
        positionText := "SHORT"
 
 
    string setupText = "NONE"
 
    if longExtremeArmed
        setupText := "LONG EXTREME"
 
    else if shortExtremeArmed
        setupText := "SHORT EXTREME"
 
    else if longHookActive
        setupText := "LONG HOOK"
 
    else if shortHookActive
        setupText := "SHORT HOOK"
 
 
    table.cell(diagnostics, 0, 0, "CNPS24 V3")
    table.cell(diagnostics, 1, 0, timeframe.period)
 
 
    table.cell(diagnostics, 0, 1, "VN30 Spot")
    table.cell(diagnostics, 1, 1, str.tostring(spotClose, format.mintick))
 
 
    table.cell(diagnostics, 0, 2, "Futures")
    table.cell(diagnostics, 1, 2, str.tostring(close, format.mintick))
 
 
    table.cell(diagnostics, 0, 3, "Basis")
    table.cell(diagnostics, 1, 3, str.tostring(basis, "0.00"))
 
 
    table.cell(diagnostics, 0, 4, "Basis Mean")
    table.cell(diagnostics, 1, 4, str.tostring(basisMean, "0.00"))
 
 
    table.cell(diagnostics, 0, 5, "Basis Z")
    table.cell(diagnostics, 1, 5, str.tostring(basisZ, "0.00"))
 
 
    table.cell(diagnostics, 0, 6, "Basis Vol Ratio")
    table.cell(diagnostics, 1, 6, str.tostring(basisVolatilityRatio, "0.00"))
 
 
    table.cell(diagnostics, 0, 7, "Model Ready")
    table.cell(diagnostics, 1, 7, modelReady ? "YES" : "NO")
 
 
    table.cell(diagnostics, 0, 8, "Setup")
    table.cell(diagnostics, 1, 8, setupText)
 
 
    table.cell(diagnostics, 0, 9, "Extreme L")
    table.cell(diagnostics, 1, 9, str.tostring(longExtremeCount))
 
 
    table.cell(diagnostics, 0, 10, "Extreme S")
    table.cell(diagnostics, 1, 10, str.tostring(shortExtremeCount))
 
 
    table.cell(diagnostics, 0, 11, "Hook L")
    table.cell(diagnostics, 1, 11, str.tostring(longHookCount))
 
 
    table.cell(diagnostics, 0, 12, "Hook S")
    table.cell(diagnostics, 1, 12, str.tostring(shortHookCount))
 
 
    table.cell(diagnostics, 0, 13, "Entry L")
    table.cell(diagnostics, 1, 13, str.tostring(longEntryCount))
 
 
    table.cell(diagnostics, 0, 14, "Entry S")
    table.cell(diagnostics, 1, 14, str.tostring(shortEntryCount))
 
 
    table.cell(diagnostics, 0, 15, "Trades Today")
    table.cell(diagnostics, 1, 15, str.tostring(tradesToday) + " / " + str.tostring(maximumTradesPerDay))
 
 
    table.cell(diagnostics, 0, 16, "Open Pts")
    table.cell(diagnostics, 1, 16, str.tostring(openTradePoints, "0.00"))
 
 
    table.cell(diagnostics, 0, 17, "Position")
    table.cell(diagnostics, 1, 17, positionText)

← 返回列表