Thứ Tư, 02/12/202602/12/2026

Hướng Dẫn Sử Dụng Bot CNPS76 - VWAP Z-Score Reversion cho VN30F1M

Bot CNPS76 VWAP Z-Score Reversion giao dịch đảo chiều hồi quy về VWAP trên VN30F1M dựa trên độ lệch chuẩn Z-Score, kết hợp cửa sổ xác nhận N nến và quản trị rủi ro cố định.

Hướng dẫn sử dụng Bot CNPS76 cho VN30F1M
Hướng dẫn sử dụng Bot CNPS76 cho VN30F1M
Mục lục
Mục lục

Trong giao dịch hợp đồng tương lai VN30F1M, giá thường xuyên có những nhịp biến động quá mức (overextension) tách rời khỏi giá trị trung bình theo khối lượng trong phiên (Session VWAP) trước khi quay đầu điều chỉnh về vùng cân bằng. Nếu nhà đầu tư bắt đỉnh/đáy quá sớm khi giá vẫn đang mở rộng độ lệch, rủi ro bị quét dừng lỗ là rất lớn; ngược lại, nếu chờ đợi quá lâu thì sẽ đánh mất tỷ lệ R:R tối ưu.

CNPS76 VWAP Z-SCORE REVERSION (tên đầy đủ trong mã nguồn: strategy(title="CNPS76 VWAP Z-SCORE REVERSION")) là chiến lược giao dịch định lượng viết bằng Pine Script v6 trên TradingView, được thiết kế để giải quyết bài toán này theo quy trình chặt chẽ: Độ lệch cực hạn (Extreme Deviation) → Tái gia nhập Z-Score (Z-Score Re-entry) → Đảo chiều (Reversal).

Những điểm nổi bật cốt lõi của Bot CNPS76 gồm:

  • Đo lường độ lệch chuẩn hóa quanh VWAP: Tính Z-Score của khoảng cách close - vwap trên chu kỳ 50 nến, giúp nhận diện chính xác trạng thái giá bị kéo giãn quá mức so với ngưỡng ±1.80.
  • Cơ chế chờ xác nhận (Pending Setup Window): Sau khi Z-Score cắt ngược lại ngưỡng cực hạn (bullishZReentry / bearishZReentry), bot giữ trạng thái chờ tối đa 3 nến (confirmationBars) và tự hủy nếu giá quay lại vùng cực hạn, tránh vào lệnh vội vàng.
  • Hệ thống bộ lọc đa tầng tùy chọn: Tích hợp sẵn các bộ lọc khoảng cách VWAP theo ATR, RSI, ADX, Volume Spike và xu hướng H1 EMA50 để tinh chỉnh theo từng giai đoạn thị trường.
  • Quản trị rủi ro kỷ luật: Thiết lập mặc định Stop Loss 5.0 điểm và Take Profit 15.0 điểm (tỷ lệ 1:3), giới hạn tối đa 2 lệnh/ngày và tự động đóng toàn bộ vị thế trước khi kết thúc phiên lúc 14:45.

1. CNPS76 VWAP Z-Score Reversion là gì?

CNPS76 VWAP Z-Score Reversion là hệ thống giao dịch đảo chiều về giá trị trung bình (Mean Reversion) hoạt động trên khung thời gian biểu đồ hiện tại, cấu thành từ 4 trụ cột kỹ thuật chính:

  1. Động cơ VWAP & Độ lệch chuẩn (VWAP & Price Deviation Engine): Sử dụng ta.vwap(hlc3) làm trục giá trị cân bằng trong phiên và đo độ lệch chuẩn ta.stdev(close - vwap, 50) để chuẩn hóa biên độ dao động thành chỉ số Z-Score.
  2. Bộ máy trạng thái chờ (Pending Setup State): Khi Z-Score cắt trở lại vào trong vùng ±1.80, tín hiệu chưa kích hoạt ngay nếu người dùng bật các điều kiện xác nhận giá/động lượng, mà được lưu vào trạng thái pendingLong hoặc pendingShort trong cửa sổ tối đa confirmationBars nến.
  3. Hệ thống bộ lọc ngữ cảnh (Context & Confirmation Filters): Cho phép kích hoạt độc lập các bộ lọc hướng nến, phá vỡ giá đóng cửa trước, động lượng Z-Score, khoảng cách tối thiểu tính theo ATR, RSI, ADX (tránh thị trường có xu hướng quá mạnh), Volume Spike và thiên hướng EMA khung H1.
  4. Khung kiểm soát lệnh & Rủi ro (Risk & Trade Control): Quản lý số lượng lệnh tối đa trong ngày (maximumTradesPerDay), thời gian nghỉ sau thoát lệnh (cooldownBars), khung giờ giao dịch theo múi giờ Asia/Ho_Chi_Minh, cố định mức SL/TP theo điểm và tất toán cuối phiên.

Bảng thông số mặc định

Nhóm thông sốTên tham số trong codeGiá trị mặc địnhÝ nghĩa
VWAP Z-ScorezScoreLength50Chu kỳ tính độ lệch chuẩn của close - vwap
VWAP Z-ScoreextremeThreshold1.80Ngưỡng Z-Score cực hạn (+1.80 / -1.80)
VWAP Z-ScoreusePreviousDayResettrueXóa các setup đang chờ khi sang ngày mới
ConfirmationconfirmationBars3Số nến tối đa chờ xác nhận sau khi Z-Score tái gia nhập
ConfirmationrequireCandleDirectionfalseYêu cầu nến tăng (Long) hoặc nến giảm (Short)
ConfirmationrequirePreviousCloseBreakfalseYêu cầu close > close[1] (Long) / close < close[1] (Short)
ConfirmationrequireZMomentumfalseYêu cầu biến động Z-Score tối thiểu
ConfirmationminimumZChange0.10Mức thay đổi Z-Score tối thiểu giữa 2 nến
VWAP DistancerequireMinimumDistancefalseBật bộ lọc khoảng cách tối thiểu tới VWAP
VWAP DistanceminimumDistanceATR0.20Khoảng cách tối thiểu tính theo hệ số nhân ATR
RSIuseRSIFilterfalseBật bộ lọc RSI
RSIrsiLength / longRSIMax / shortRSIMin14 / 50.0 / 50.0Chu kỳ RSI; ngưỡng tối đa cho Long / tối thiểu cho Short
ADXuseADXFilterfalseBật bộ lọc sức mạnh xu hướng ADX
ADXdiLength / adxSmoothing / maximumADX14 / 14 / 30.0Thông số DMI và ngưỡng ADX tối đa cho phép vào lệnh
VolumerequireVolumeSpikefalseBật bộ lọc đột biến khối lượng
VolumevolumeAverageLength / volumeSpikeFactor20 / 1.20Trung bình khối lượng 20 nến và hệ số nhân 1.20
H1 TrenduseH1EMABias / h1EMALengthfalse / 50Bật lọc xu hướng theo EMA 50 nến H1 đã đóng
ATRatrLength14Chu kỳ tính chỉ báo ATR
Risk ManagementstopLossPoints / takeProfitPoints5.0 / 15.0Cắt lỗ 5.0 điểm, Chốt lời 15.0 điểm
Trade ControlmaximumTradesPerDay2Số lệnh tối đa mỗi ngày
Trade ControltradeDirection"Long"Hướng giao dịch mặc định ("Long", "Short", "Both")
Trade ControlcooldownBars0Số nến nghỉ sau khi đóng vị thế
SessionuseSessionFilter / strategyTimezonefalse / "Asia/Ho_Chi_Minh"Bật lọc phiên giao dịch và múi giờ Việt Nam
SessionsessionStart / lastEntry / sessionEnd09:00 / 14:30 / 14:45Giờ bắt đầu, giờ nhận lệnh cuối, giờ đóng lệnh bắt buộc
AlertsdisableSLTPAlertsfalseTắt cảnh báo SL/TP nếu đặt true

Source Code CNPS76 VWAP Z-Score Reversion

Bạn có thể sao chép toàn bộ mã nguồn Pine Script v6 dưới đây để dán trực tiếp vào Pine Editor trên TradingView:

//@version=6
strategy(title="CNPS76 VWAP Z-SCORE REVERSION", shorttitle="CNPS76 VWAP Z", overlay=true, initial_capital=100000000, default_qty_type=strategy.fixed, default_qty_value=1, pyramiding=0, margin_long=0, margin_short=0, slippage=0, commission_type=strategy.commission.cash_per_contract, commission_value=0, 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)

// ============================================================================
// CNPS76 VWAP Z-SCORE REVERSION
// EXTREME DEVIATION -> Z-SCORE RE-ENTRY -> REVERSAL
//
// LONG:
// Z-Score moves below negative threshold
// -> Crosses back above negative threshold
// -> Optional price / momentum confirmation
// -> LONG
//
// SHORT:
// Z-Score moves above positive threshold
// -> Crosses back below positive threshold
// -> Optional price / momentum confirmation
// -> SHORT
//
// DEFAULT SL = 5 POINTS
// DEFAULT TP = 15 POINTS
//
// CURRENT CHART TIMEFRAME
// ============================================================================
// ============================================================================
// SECTION 1: VWAP Z-SCORE SETTINGS
// ============================================================================
zScoreLength = input.int(50, "Z-Score Lookback", minval=5, maxval=500, group="VWAP Z-Score")
extremeThreshold = input.float(1.80, "Extreme Z-Score Threshold", minval=0.1, step=0.1, group="VWAP Z-Score")
usePreviousDayReset = input.bool(true, "Reset Pending Setups Each Day?", group="VWAP Z-Score")

// ============================================================================
// SECTION 2: SIGNAL CONFIRMATION
// ============================================================================
confirmationBars = input.int(3, "Maximum Confirmation Bars", minval=0, maxval=30, group="Confirmation")
requireCandleDirection = input.bool(false, "Require Bullish / Bearish Candle?", group="Confirmation")
requirePreviousCloseBreak = input.bool(false, "Require Previous Close Break?", group="Confirmation")
requireZMomentum = input.bool(false, "Require Z-Score Momentum?", group="Confirmation")
minimumZChange = input.float(0.10, "Minimum Z-Score Change", minval=0.0, step=0.05, group="Confirmation")

// ============================================================================
// SECTION 3: VWAP DISTANCE FILTER
// ============================================================================
requireMinimumDistance = input.bool(false, "Require Minimum VWAP Distance?", group="VWAP Distance")
minimumDistanceATR = input.float(0.20, "Minimum Distance From VWAP / ATR", minval=0.0, step=0.05, group="VWAP Distance")

// ============================================================================
// SECTION 4: RSI FILTER
// ============================================================================
useRSIFilter = input.bool(false, "Use RSI Filter?", group="RSI")
rsiLength = input.int(14, "RSI Length", minval=2, group="RSI")
longRSIMax = input.float(50.0, "Maximum RSI For Long", minval=1, maxval=100, group="RSI")
shortRSIMin = input.float(50.0, "Minimum RSI For Short", minval=1, maxval=100, group="RSI")

// ============================================================================
// SECTION 5: ADX FILTER
// ============================================================================
useADXFilter = input.bool(false, "Use ADX Filter?", group="ADX")
diLength = input.int(14, "DI Length", minval=2, group="ADX")
adxSmoothing = input.int(14, "ADX Smoothing", minval=2, group="ADX")
maximumADX = input.float(30.0, "Maximum ADX", minval=1, step=1, group="ADX")

// ============================================================================
// SECTION 6: VOLUME FILTER
// ============================================================================
requireVolumeSpike = input.bool(false, "Require Volume Spike?", group="Volume")
volumeAverageLength = input.int(20, "Volume Average Length", minval=2, group="Volume")
volumeSpikeFactor = input.float(1.20, "Volume Spike Factor", minval=0.1, step=0.1, group="Volume")

// ============================================================================
// SECTION 7: H1 TREND FILTER
// ============================================================================
useH1EMABias = input.bool(false, "Use Confirmed H1 EMA Bias?", group="H1 Trend")
h1EMALength = input.int(50, "H1 EMA Length", minval=1, group="H1 Trend")

// ============================================================================
// SECTION 8: ATR
// ============================================================================
atrLength = input.int(14, "ATR Length", minval=1, group="ATR")

// ============================================================================
// SECTION 9: RISK MANAGEMENT
// ============================================================================
stopLossPoints = input.float(5.0, "Stop Loss (Points)", minval=0.1, step=0.5, group="Risk Management")
takeProfitPoints = input.float(15.0, "Take Profit (Points)", minval=0.1, step=0.5, group="Risk Management")

// ============================================================================
// SECTION 10: TRADE CONTROL
// ============================================================================
maximumTradesPerDay = input.int(2, "Maximum Trades Per Day", minval=1, maxval=20, group="Trade Control")
tradeDirection = input.string("Long", "Trade Direction", options=["Long", "Short", "Both"], group="Trade Control")
cooldownBars = input.int(0, "Cooldown Bars After Exit", minval=0, maxval=100, group="Trade Control")
bool allowLong = (tradeDirection == "Long" or tradeDirection == "Both")
bool allowShort = (tradeDirection == "Short" or tradeDirection == "Both")

// ============================================================================
// SECTION 11: SESSION
// ============================================================================
useSessionFilter = input.bool(false, "Use Entry Session Filter?", group="Session")
strategyTimezone = input.string("Asia/Ho_Chi_Minh", "Strategy Timezone", group="Session")
sessionStartHour = input.int(9, "Session Start Hour", minval=0, maxval=23, group="Session")
sessionStartMinute = input.int(0, "Session Start Minute", minval=0, maxval=59, group="Session")
lastEntryHour = input.int(14, "Last Entry Hour", minval=0, maxval=23, group="Session")
lastEntryMinute = input.int(30, "Last Entry Minute", minval=0, maxval=59, group="Session")
sessionEndHour = input.int(14, "Force Close Hour", minval=0, maxval=23, group="Session")
sessionEndMinute = input.int(45, "Force Close Minute", minval=0, maxval=59, group="Session")

// ============================================================================
// SECTION 12: ALERT CONTROL
// ============================================================================
disableSLTPAlerts = input.bool(false, "Disable SL / TP Alerts?", group="Alerts")

// ============================================================================
// SECTION 13: DISPLAY
// ============================================================================
showVWAP = input.bool(true, "Show VWAP?", group="Display")
showZBands = input.bool(false, "Show VWAP Z-Score Bands?", group="Display")
showH1EMA = input.bool(false, "Show H1 EMA?", group="Display")
showExtremeMarkers = input.bool(false, "Show Z-Score Re-entry Markers?", group="Display")
showSignalMarkers = input.bool(false, "Show Setup Markers?", group="Display")
showActiveSLTP = input.bool(true, "Show Active SL / TP?", group="Display")
showDiagnostics = input.bool(false, "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 sessionStartTotal = (sessionStartHour * 60 + sessionStartMinute)
int lastEntryTotal = (lastEntryHour * 60 + lastEntryMinute)
int sessionEndTotal = (sessionEndHour * 60 + sessionEndMinute)
bool entrySession = (currentMinute >= sessionStartTotal and currentCloseMinute <= lastEntryTotal)
bool sessionOK = (not useSessionFilter or entrySession)

// ============================================================================
// SECTION 15: TRADING DAY
// ============================================================================
int tradingDayKey = (year(time, strategyTimezone) * 10000 + month(time, strategyTimezone) * 100 + dayofmonth(time, strategyTimezone))
var int lastResetDay = na
var int tradesToday = 0
bool newTradingDay = (na(lastResetDay) or tradingDayKey != lastResetDay)
if newTradingDay
    tradesToday := 0
    lastResetDay := tradingDayKey

// ============================================================================
// SECTION 16: VWAP ENGINE
// ============================================================================
float vwap = ta.vwap(hlc3)
bool vwapReady = (not na(vwap))

// ============================================================================
// SECTION 17: PRICE DEVIATION
// ============================================================================
float priceDeviation = (close - vwap)
float deviationStdev = ta.stdev(priceDeviation, zScoreLength)
bool deviationReady = (vwapReady and not na(deviationStdev) and deviationStdev > 0)

// ============================================================================
// SECTION 18: Z-SCORE ENGINE
// ============================================================================
float zScore = (deviationReady ? priceDeviation / deviationStdev : na)
float zScoreChange = (zScore - zScore[1])
bool extremeLow = (not na(zScore) and zScore < -extremeThreshold)
bool extremeHigh = (not na(zScore) and zScore > extremeThreshold)

// ============================================================================
// SECTION 19: Z-SCORE RE-ENTRY
// ============================================================================
//
// LONG:
// Previous Z-Score below negative threshold.
// Current Z-Score crosses back above threshold.
//
// SHORT:
// Previous Z-Score above positive threshold.
// Current Z-Score crosses back below threshold.
//
// ============================================================================
bool bullishZReentry = ta.crossover(zScore, -extremeThreshold)
bool bearishZReentry = ta.crossunder(zScore, extremeThreshold)

// ============================================================================
// SECTION 20: ATR ENGINE
// ============================================================================
float atr = ta.atr(atrLength)
float distanceFromVWAP = math.abs(close - vwap)
bool distanceOK = (not requireMinimumDistance or (not na(atr) and atr > 0 and distanceFromVWAP >= minimumDistanceATR * atr))

// ============================================================================
// SECTION 21: PRICE CONFIRMATION
// ============================================================================
bool bullishCandle = (close > open)
bool bearishCandle = (close < open)
bool longCandleOK = (not requireCandleDirection or bullishCandle)
bool shortCandleOK = (not requireCandleDirection or bearishCandle)
bool longPriceOK = (not requirePreviousCloseBreak or close > close[1])
bool shortPriceOK = (not requirePreviousCloseBreak or close < close[1])
bool longZMomentumOK = (not requireZMomentum or (not na(zScoreChange) and zScoreChange >= minimumZChange))
bool shortZMomentumOK = (not requireZMomentum or (not na(zScoreChange) and zScoreChange <= -minimumZChange))
bool longConfirmation = (longCandleOK and longPriceOK and longZMomentumOK)
bool shortConfirmation = (shortCandleOK and shortPriceOK and shortZMomentumOK)

// ============================================================================
// SECTION 22: RSI FILTER
// ============================================================================
float rsi = ta.rsi(close, rsiLength)
bool longRSIOK = (not useRSIFilter or (not na(rsi) and rsi <= longRSIMax))
bool shortRSIOK = (not useRSIFilter or (not na(rsi) and rsi >= shortRSIMin))

// ============================================================================
// SECTION 23: ADX FILTER
// ============================================================================
[diPlus, diMinus, adx] = ta.dmi(diLength, adxSmoothing)
bool adxOK = (not useADXFilter or (not na(adx) and adx <= maximumADX))

// ============================================================================
// SECTION 24: VOLUME FILTER
// ============================================================================
float averageVolume = ta.sma(volume, volumeAverageLength)
bool volumeSpike = (not na(averageVolume) and volume >= averageVolume * volumeSpikeFactor)
bool volumeOK = (not requireVolumeSpike or volumeSpike)

// ============================================================================
// SECTION 25: CONFIRMED H1 EMA
// ============================================================================
//
// Uses the previous confirmed H1 candle.
//
// Intended for chart timeframes below 60 minutes.
//
// ============================================================================
float h1EMA = request.security(syminfo.tickerid, "60", ta.ema(close, h1EMALength)[1], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
float h1Close = request.security(syminfo.tickerid, "60", close[1], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
bool longBiasOK = (not useH1EMABias or (not na(h1EMA) and not na(h1Close) and h1Close > h1EMA))
bool shortBiasOK = (not useH1EMABias or (not na(h1EMA) and not na(h1Close) and h1Close < h1EMA))

// ============================================================================
// SECTION 26: PENDING SETUP STATE
// ============================================================================
//
// Register a Z-Score re-entry event.
//
// Wait for confirmation during N bars.
//
// Repeated evaluation of the same candle
// must not generate multiple setups.
//
// ============================================================================
var bool pendingLong = false
var bool pendingShort = false
var int pendingLongBar = na
var int pendingShortBar = na
var int extremeLowCount = 0
var int extremeHighCount = 0
var int bullReentryCount = 0
var int bearReentryCount = 0
var int expiredLongCount = 0
var int expiredShortCount = 0
var int lastProcessedBar = na
bool processState = (barstate.isconfirmed and (na(lastProcessedBar) or lastProcessedBar != bar_index))
if processState
    lastProcessedBar := bar_index
    if newTradingDay and usePreviousDayReset
        pendingLong := false
        pendingShort := false
        pendingLongBar := na
        pendingShortBar := na
    if extremeLow and not extremeLow[1]
        extremeLowCount += 1
    if extremeHigh and not extremeHigh[1]
        extremeHighCount += 1

    // Expire pending LONG.
    if pendingLong and not na(pendingLongBar)
        if bar_index - pendingLongBar > confirmationBars
            pendingLong := false
            pendingLongBar := na
            expiredLongCount += 1

    // Expire pending SHORT.
    if pendingShort and not na(pendingShortBar)
        if bar_index - pendingShortBar > confirmationBars
            pendingShort := false
            pendingShortBar := na
            expiredShortCount += 1

    // Cancel setups when price moves back
    // into the original extreme condition.
    if pendingLong and extremeLow
        pendingLong := false
        pendingLongBar := na
    if pendingShort and extremeHigh
        pendingShort := false
        pendingShortBar := na

    // Register fresh re-entry events.
    if bullishZReentry
        pendingLong := true
        pendingLongBar := bar_index
        pendingShort := false
        pendingShortBar := na
        bullReentryCount += 1
    if bearishZReentry
        pendingShort := true
        pendingShortBar := bar_index
        pendingLong := false
        pendingLongBar := na
        bearReentryCount += 1

// ============================================================================
// SECTION 27: VALID SETUP WINDOW
// ============================================================================
bool validLongSetup = (pendingLong and not na(pendingLongBar) and bar_index - pendingLongBar <= confirmationBars)
bool validShortSetup = (pendingShort and not na(pendingShortBar) and bar_index - pendingShortBar <= confirmationBars)

// ============================================================================
// SECTION 28: BASE SIGNALS
// ============================================================================
bool longBase = (validLongSetup and longConfirmation)
bool shortBase = (validShortSetup and shortConfirmation)

// ============================================================================
// SECTION 29: RAW SIGNALS
// ============================================================================
bool rawLongSignal = (longBase and distanceOK and longRSIOK and adxOK and volumeOK and longBiasOK)
bool rawShortSignal = (shortBase and distanceOK and shortRSIOK and adxOK and volumeOK and shortBiasOK)

// ============================================================================
// SECTION 30: POSITION STATE
// ============================================================================
bool positionFlat = (strategy.position_size == 0)
bool positionLong = (strategy.position_size > 0)
bool positionShort = (strategy.position_size < 0)
bool positionJustClosed = (positionFlat and strategy.position_size[1] != 0)

// ============================================================================
// SECTION 31: COOLDOWN
// ============================================================================
var int lastExitBar = na
if strategy.closedtrades > nz(strategy.closedtrades[1])
    lastExitBar := bar_index
bool cooldownOK = (na(lastExitBar) or bar_index - lastExitBar > cooldownBars)

// ============================================================================
// SECTION 32: CAN TRADE
// ============================================================================
bool dailyTradeLimitOK = (tradesToday < maximumTradesPerDay)
bool canTrade = (positionFlat and dailyTradeLimitOK and cooldownOK and sessionOK and currentCloseMinute < sessionEndTotal and barstate.isconfirmed)

// ============================================================================
// SECTION 33: SIGNAL PROTECTION
// ============================================================================
bool ambiguousSignal = (rawLongSignal and rawShortSignal)
var int lastEntryBar = na
bool notEnteredThisBar = (na(lastEntryBar) or bar_index != lastEntryBar)
bool finalLongSignal = (canTrade and notEnteredThisBar and allowLong and rawLongSignal and not ambiguousSignal)
bool finalShortSignal = (canTrade and notEnteredThisBar and allowShort and rawShortSignal and not ambiguousSignal)

// ============================================================================
// SECTION 34: DIAGNOSTIC COUNTERS
// ============================================================================
var int longBaseCount = 0
var int shortBaseCount = 0
var int longSignalCount = 0
var int shortSignalCount = 0
var int longEntryCount = 0
var int shortEntryCount = 0
if processState
    if longBase
        longBaseCount += 1
    if shortBase
        shortBaseCount += 1
    if rawLongSignal
        longSignalCount += 1
    if rawShortSignal
        shortSignalCount += 1

// ============================================================================
// SECTION 35: LONG ENTRY
// ============================================================================
if finalLongSignal
    strategy.entry("Long", strategy.long, comment="VWAP Z-Score Long", alert_message="🟢 VÀO VỊ THẾ LONG (CNPS76 VWAP Z-Score)\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\n🛑 Cắt lỗ (SL): " + str.tostring(close - stopLossPoints, format.mintick) + "\n💰 Chốt lời (TP): " + str.tostring(close + takeProfitPoints, format.mintick))
    tradesToday += 1
    longEntryCount += 1
    lastEntryBar := bar_index
    pendingLong := false
    pendingLongBar := na

// ============================================================================
// SECTION 36: SHORT ENTRY
// ============================================================================
if finalShortSignal
    strategy.entry("Short", strategy.short, comment="VWAP Z-Score Short", alert_message="🔴 VÀO VỊ THẾ SHORT (CNPS76 VWAP Z-Score)\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\n🛑 Cắt lỗ (SL): " + str.tostring(close + stopLossPoints, format.mintick) + "\n💰 Chốt lời (TP): " + str.tostring(close - takeProfitPoints, format.mintick))
    tradesToday += 1
    shortEntryCount += 1
    lastEntryBar := bar_index
    pendingShort := false
    pendingShortBar := na

// ============================================================================
// SECTION 37: ACTIVE RISK LEVELS
// ============================================================================
var float activeLongSL = na
var float activeLongTP = na
var float activeShortSL = na
var float activeShortTP = na

// ============================================================================
// SECTION 38: LONG SL / TP
// ============================================================================
if positionLong
    float entryPrice = (strategy.position_avg_price)
    activeLongSL := (entryPrice - stopLossPoints)
    activeLongTP := (entryPrice + takeProfitPoints)
    strategy.exit("Long Exit", from_entry="Long", stop=activeLongSL, limit=activeLongTP, comment_profit="TP Long", comment_loss="SL Long", alert_profit="💰 CHỐT LỜI LONG (TP HIT)\n🎯 Giá chốt: " + str.tostring(activeLongTP, format.mintick), alert_loss="🛑 CẮT LỖ LONG (SL HIT)\n🎯 Giá cắt: " + str.tostring(activeLongSL, format.mintick), disable_alert=disableSLTPAlerts)

// ============================================================================
// SECTION 39: SHORT SL / TP
// ============================================================================
if positionShort
    float entryPrice = (strategy.position_avg_price)
    activeShortSL := (entryPrice + stopLossPoints)
    activeShortTP := (entryPrice - takeProfitPoints)
    strategy.exit("Short Exit", from_entry="Short", stop=activeShortSL, limit=activeShortTP, comment_profit="TP Short", comment_loss="SL Short", alert_profit="💰 CHỐT LỜI SHORT (TP HIT)\n🎯 Giá chốt: " + str.tostring(activeShortTP, format.mintick), alert_loss="🛑 CẮT LỖ SHORT (SL HIT)\n🎯 Giá cắt: " + str.tostring(activeShortSL, format.mintick), disable_alert=disableSLTPAlerts)

// ============================================================================
// SECTION 40: POSITION CLEANUP
// ============================================================================
if positionJustClosed
    activeLongSL := na
    activeLongTP := na
    activeShortSL := na
    activeShortTP := na

// ============================================================================
// SECTION 41: SESSION END
// ============================================================================
bool finalSessionBar = (currentMinute < sessionEndTotal and currentCloseMinute >= sessionEndTotal)
if finalSessionBar and strategy.position_size != 0
    strategy.close_all(immediately=true, comment="Session End", alert_message="⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End)\n🎯 Giá đóng: " + str.tostring(close, format.mintick))

// ============================================================================
// SECTION 42: VWAP DISPLAY
// ============================================================================
plot(showVWAP ? vwap : na, title="Session VWAP", color=color.orange, linewidth=2)

// ============================================================================
// SECTION 43: Z-SCORE PRICE BANDS
// ============================================================================
//
// Display corresponding price levels
// for positive and negative Z thresholds.
//
// ============================================================================
float upperZBand = (deviationReady ? vwap + extremeThreshold * deviationStdev : na)
float lowerZBand = (deviationReady ? vwap - extremeThreshold * deviationStdev : na)
plot(showZBands ? upperZBand : na, title="Upper Z-Score Band", color=color.red, linewidth=1)
plot(showZBands ? lowerZBand : na, title="Lower Z-Score Band", color=color.green, linewidth=1)

// ============================================================================
// SECTION 44: H1 EMA DISPLAY
// ============================================================================
plot(showH1EMA and useH1EMABias ? h1EMA : na, title="Confirmed H1 EMA", color=color.blue, linewidth=1)

// ============================================================================
// SECTION 45: ACTIVE SL / TP DISPLAY
// ============================================================================
plot(showActiveSLTP and positionLong ? activeLongSL : na, title="Long SL", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showActiveSLTP and positionLong ? activeLongTP : na, title="Long TP", color=color.green, linewidth=2, style=plot.style_linebr)
plot(showActiveSLTP and positionShort ? activeShortSL : na, title="Short SL", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showActiveSLTP and positionShort ? activeShortTP : na, title="Short TP", color=color.green, linewidth=2, style=plot.style_linebr)

// ============================================================================
// SECTION 46: EXTREME RE-ENTRY MARKERS
// ============================================================================
plotshape(showExtremeMarkers and bullishZReentry, title="Bullish Z Re-entry", style=shape.circle, location=location.belowbar, color=color.aqua, size=size.tiny, text="Z")
plotshape(showExtremeMarkers and bearishZReentry, title="Bearish Z Re-entry", style=shape.circle, location=location.abovebar, color=color.orange, size=size.tiny, text="Z")

// ============================================================================
// SECTION 47: SIGNAL MARKERS
// ============================================================================
plotshape(showSignalMarkers and rawLongSignal, title="VWAP Z-Score Long Setup", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.tiny, text="L", textcolor=color.white)
plotshape(showSignalMarkers and rawShortSignal, title="VWAP Z-Score Short Setup", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.tiny, text="S", textcolor=color.white)

// ============================================================================
// SECTION 48: DATA WINDOW
// ============================================================================
plot(zScore, title="VWAP Z-Score", color=color.purple, display=display.data_window)
plot(deviationStdev, title="Deviation Standard Deviation", color=color.gray, display=display.data_window)
plot(rsi, title="RSI Value", color=color.blue, display=display.data_window)

// ============================================================================
// SECTION 49: DIAGNOSTICS
// ============================================================================
var table diagnostics = table.new(position.top_right, 2, 21, border_width=1)
if showDiagnostics and barstate.islast
    string positionText = (positionLong ? "LONG" : positionShort ? "SHORT" : "FLAT")
    table.cell(diagnostics, 0, 0, "CNPS76")
    table.cell(diagnostics, 1, 0, timeframe.period)
    table.cell(diagnostics, 0, 1, "VWAP")
    table.cell(diagnostics, 1, 1, str.tostring(vwap, format.mintick))
    table.cell(diagnostics, 0, 2, "Z-Score")
    table.cell(diagnostics, 1, 2, str.tostring(zScore, "#.###"))
    table.cell(diagnostics, 0, 3, "Z Change")
    table.cell(diagnostics, 1, 3, str.tostring(zScoreChange, "#.###"))
    table.cell(diagnostics, 0, 4, "Deviation")
    table.cell(diagnostics, 1, 4, str.tostring(priceDeviation, "#.##"))
    table.cell(diagnostics, 0, 5, "Deviation StDev")
    table.cell(diagnostics, 1, 5, str.tostring(deviationStdev, "#.##"))
    table.cell(diagnostics, 0, 6, "RSI")
    table.cell(diagnostics, 1, 6, str.tostring(rsi, "#.##"))
    table.cell(diagnostics, 0, 7, "ADX")
    table.cell(diagnostics, 1, 7, str.tostring(adx, "#.##"))
    table.cell(diagnostics, 0, 8, "Low Extremes")
    table.cell(diagnostics, 1, 8, str.tostring(extremeLowCount))
    table.cell(diagnostics, 0, 9, "High Extremes")
    table.cell(diagnostics, 1, 9, str.tostring(extremeHighCount))
    table.cell(diagnostics, 0, 10, "Bull Re-entries")
    table.cell(diagnostics, 1, 10, str.tostring(bullReentryCount))
    table.cell(diagnostics, 0, 11, "Bear Re-entries")
    table.cell(diagnostics, 1, 11, str.tostring(bearReentryCount))
    table.cell(diagnostics, 0, 12, "Long Bases")
    table.cell(diagnostics, 1, 12, str.tostring(longBaseCount))
    table.cell(diagnostics, 0, 13, "Short Bases")
    table.cell(diagnostics, 1, 13, str.tostring(shortBaseCount))
    table.cell(diagnostics, 0, 14, "Long Signals")
    table.cell(diagnostics, 1, 14, str.tostring(longSignalCount))
    table.cell(diagnostics, 0, 15, "Short Signals")
    table.cell(diagnostics, 1, 15, str.tostring(shortSignalCount))
    table.cell(diagnostics, 0, 16, "Pending Long")
    table.cell(diagnostics, 1, 16, pendingLong ? "YES" : "NO")
    table.cell(diagnostics, 0, 17, "Pending Short")
    table.cell(diagnostics, 1, 17, pendingShort ? "YES" : "NO")
    table.cell(diagnostics, 0, 18, "Long Entries")
    table.cell(diagnostics, 1, 18, str.tostring(longEntryCount))
    table.cell(diagnostics, 0, 19, "Short Entries")
    table.cell(diagnostics, 1, 19, str.tostring(shortEntryCount))
    table.cell(diagnostics, 0, 20, "Trades Today")
    table.cell(diagnostics, 1, 20, str.tostring(tradesToday) + " / " + str.tostring(maximumTradesPerDay))

2. Những khái niệm kỹ thuật cốt lõi trong CNPS76

2.1. Công thức VWAP Z-Score và dải Z-Score Bands

Thay vì dùng dải Bollinger dựa trên đường trung bình giản đơn (SMA), CNPS76 lấy Session VWAP (ta.vwap(hlc3)) làm tâm quy chiếu dòng tiền trong phiên:

  • Độ lệch giá (Price Deviation): priceDeviation = close - vwap
  • Độ lệch chuẩn của độ lệch (Deviation StDev): deviationStdev = ta.stdev(priceDeviation, zScoreLength) với zScoreLength = 50.
  • Chỉ số Z-Score: zScore = priceDeviation / deviationStdev (chỉ tính khi vwap hợp lệ và deviationStdev > 0).
  • Tốc độ thay đổi Z-Score: zScoreChange = zScore - zScore[1].

Trên biểu đồ, khi bật showZBands, bot vẽ hai dải giá tương ứng với ngưỡng cực hạn:

  • Upper Z-Score Band: vwap + extremeThreshold * deviationStdev
  • Lower Z-Score Band: vwap - extremeThreshold * deviationStdev

2.2. Cơ chế Tái gia nhập (Z-Score Re-entry) và Cửa sổ xác nhận N nến

Bot không bắt dao rơi ngay khi giá vừa chạm vùng cực hạn (zScore < -1.80 hoặc zScore > 1.80), mà chờ tín hiệu quay đầu:

  • Bullish Z Re-entry: ta.crossover(zScore, -extremeThreshold) — Z-Score từ dưới -1.80 cắt ngược lên trên -1.80.
  • Bearish Z Re-entry: ta.crossunder(zScore, extremeThreshold) — Z-Score từ trên +1.80 cắt ngược xuống dưới +1.80.

Sự kiện tái gia nhập sẽ kích hoạt trạng thái pendingLong hoặc pendingShort tại cây nến đóng cửa (barstate.isconfirmed). Trạng thái chờ này chỉ có hiệu lực trong vòng confirmationBars nến (mặc định 3 nến) và sẽ tự động bị hủy nếu:

  • Hết hạn cửa sổ xác nhận (bar_index - pendingLongBar > confirmationBars).
  • Giá quay trở lại vùng cực hạn ban đầu (pendingLong and extremeLow hoặc pendingShort and extremeHigh).
  • Sang ngày giao dịch mới khi usePreviousDayReset = true.

2.3. Hệ thống bộ lọc xác nhận và ngữ cảnh thị trường

Để thích ứng với nhiều trạng thái thị trường VN30F1M, CNPS76 trang bị 2 tầng lọc tùy chọn (mặc định đều false để giữ nguyên tín hiệu gốc):

  • Tầng xác nhận giá & động lượng (longConfirmation / shortConfirmation): Kiểm tra màu nến (close > open cho Long, close < open cho Short), phá vỡ giá đóng cửa trước (close > close[1] / close < close[1]) và động lượng Z-Score (zScoreChange >= 0.10 / <= -0.10).
  • Tầng lọc ngữ cảnh (rawLongSignal / rawShortSignal):
    • Khoảng cách VWAP (distanceOK): math.abs(close - vwap) >= 0.20 * ta.atr(14), đảm bảo giá còn đủ dư địa hồi về VWAP.
    • RSI (longRSIOK / shortRSIOK): RSI(14) <= 50.0 cho Long và >= 50.0 cho Short.
    • ADX (adxOK): ADX(14, 14) <= 30.0, tránh giao dịch ngược xu hướng khi thị trường đang có trend quá mạnh.
    • Volume Spike (volumeOK): Khối lượng nến hiện tại >= 1.20 * SMA(volume, 20).
    • H1 EMA Bias (longBiasOK / shortBiasOK): Dùng request.security(..., "60", ...[1]) lấy giá đóng cửa và EMA 50 của nến H1 đã xác nhận gần nhất (h1Close > h1EMA cho Long, h1Close < h1EMA cho Short).

3. Nguyên lý hoạt động của CNPS76

Quy trình vận hành của CNPS76 VWAP Z-Score Reversion diễn ra tuần tự qua 5 bước trên mỗi cây nến đóng (barstate.isconfirmed):

  1. Khởi tạo phiên và bộ đếm ngày: Theo dõi tradingDayKey theo múi giờ Asia/Ho_Chi_Minh. Khi sang ngày mới, bot reset tradesToday = 0 và xóa các trạng thái pendingLong / pendingShort còn tồn đọng từ phiên trước (nếu usePreviousDayReset = true).
  2. Tính toán VWAP Z-Score và các chỉ báo phụ trợ: Cập nhật vwap, priceDeviation, deviationStdev, zScore, cùng với atr, rsi, adx, averageVolume và dữ liệu H1 EMA.
  3. Cập nhật trạng thái Setup (processState): Ghi nhận sự kiện bullishZReentry hoặc bearishZReentry, quản lý thời hạn confirmationBars (tối đa 3 nến), hủy setup nếu giá tái lập cực hạn và cập nhật các biến đếm chẩn đoán.
  4. Đánh giá điều kiện vào lệnh (canTrade & finalLongSignal / finalShortSignal): Kiểm tra đồng thời tín hiệu cơ sở (longBase/shortBase), toàn bộ bộ lọc ngữ cảnh, trạng thái không có vị thế (strategy.position_size == 0), giới hạn lệnh ngày, cooldown, khung giờ và chống tín hiệu mâu thuẫn (ambiguousSignal).
  5. Thực thi lệnh và quản trị vị thế: Gửi lệnh vào thị trường kèm thông báo Alert, gắn ngay cặp lệnh chốt lời/cắt lỗ cố định qua strategy.exit và kích hoạt đóng toàn bộ vị thế cuối phiên lúc 14:45.

4. Điều kiện vào lệnh Long và Short của CNPS76

4.1. Điều kiện vào lệnh Long

Lệnh Long (finalLongSignal) được kích hoạt khi tất cả các điều kiện sau cùng thỏa mãn:

  • Hướng giao dịch cho phép Long (tradeDirection là "Long" hoặc "Both" — mặc định là "Long").
  • Có validLongSetup: Sự kiện ta.crossover(zScore, -1.80) đã xảy ra trong vòng confirmationBars (≤ 3 nến) và chưa bị hủy do zScore rơi lại dưới -1.80.
  • Thỏa mãn longConfirmation: Đạt các điều kiện bật thêm về nến tăng (close > open), vượt giá đóng cửa trước (close > close[1]) và động lượng Z-Score (zScoreChange >= 0.10).
  • Thỏa mãn toàn bộ bộ lọc ngữ cảnh đang bật: distanceOK, longRSIOK (rsi <= 50.0), adxOK (adx <= 30.0), volumeOK (volume >= 1.20 * avgVol), và longBiasOK (h1Close > h1EMA).
  • Không đồng thời xuất hiện tín hiệu Short (not ambiguousSignal) và thỏa mãn điều kiện kiểm soát giao dịch chung canTrade.

4.2. Điều kiện vào lệnh Short

Lệnh Short (finalShortSignal) được kích hoạt khi tất cả các điều kiện sau cùng thỏa mãn:

  • Hướng giao dịch cho phép Short (tradeDirection là "Short" hoặc "Both" — lưu ý mặc định code đang để "Long", cần đổi sang "Short" hoặc "Both" nếu muốn đánh Short).
  • Có validShortSetup: Sự kiện ta.crossunder(zScore, 1.80) đã xảy ra trong vòng confirmationBars (≤ 3 nến) và chưa bị hủy do zScore vượt lại lên trên +1.80.
  • Thỏa mãn shortConfirmation: Đạt các điều kiện bật thêm về nến giảm (close < open), thủng giá đóng cửa trước (close < close[1]) và động lượng Z-Score (zScoreChange <= -0.10).
  • Thỏa mãn toàn bộ bộ lọc ngữ cảnh đang bật: distanceOK, shortRSIOK (rsi >= 50.0), adxOK, volumeOK, và shortBiasOK (h1Close < h1EMA).
  • Không đồng thời xuất hiện tín hiệu Long (not ambiguousSignal) và thỏa mãn điều kiện kiểm soát giao dịch chung canTrade.

4.3. Điều kiện kiểm soát giao dịch chung

Cả hai chiều Long và Short đều phải vượt qua lớp kiểm soát canTrade và notEnteredThisBar:

  • Vị thế phẳng (positionFlat): strategy.position_size == 0 (không nhồi lệnh, pyramiding = 0).
  • Giới hạn lệnh trong ngày (dailyTradeLimitOK): tradesToday < maximumTradesPerDay (mặc định tối đa 2 lệnh/ngày).
  • Thời gian nghỉ (cooldownOK): bar_index - lastExitBar > cooldownBars (mặc định 0).
  • Khung giờ giao dịch (sessionOK & currentCloseMinute < sessionEndTotal): Nếu bật useSessionFilter, nến phải mở từ 09:00 trở đi và đóng trước hoặc bằng 14:30; đồng thời trong mọi trường hợp nến phải đóng trước giờ Force Close 14:45 (Asia/Ho_Chi_Minh).
  • Xác nhận đóng nến & chống trùng lặp: barstate.isconfirmed phải là true và chưa vào lệnh nào trên bar_index hiện tại (notEnteredThisBar).

5. Quản trị Stop Loss, Take Profit và Thoát lệnh

5.1. Cơ chế Stop Loss và bộ lọc Risk

CNPS76 áp dụng cơ chế cắt lỗ cố định theo điểm số tính từ giá khớp lệnh trung bình (strategy.position_avg_price):

  • Với vị thế Long: activeLongSL = entryPrice - stopLossPoints (mặc định entryPrice - 5.0 điểm).
  • Với vị thế Short: activeShortSL = entryPrice + stopLossPoints (mặc định entryPrice + 5.0 điểm).

Bot không sử dụng khoảng đệm ATR hay giới hạn Min–Max Risk cho SL; tuy nhiên, bộ lọc requireMinimumDistance (nếu bật) đóng vai trò kiểm soát chất lượng điểm vào bằng cách đảm bảo giá cách VWAP tối thiểu 0.20 * ATR(14) trước khi mở vị thế.

5.2. Cơ chế Take Profit, Break Even và Trailing

Chốt lời cũng được thiết lập cố định theo điểm số với tỷ lệ Risk:Reward mặc định là 1:3:

  • Với vị thế Long: activeLongTP = entryPrice + takeProfitPoints (mặc định entryPrice + 15.0 điểm).
  • Với vị thế Short: activeShortTP = entryPrice - takeProfitPoints (mặc định entryPrice - 15.0 điểm).

Mã nguồn CNPS76 không sử dụng cơ chế dời hòa vốn (Break Even) hay Trailing Stop. Thay vào đó, bot trang bị cơ chế tất toán cuối phiên (Session End): tại cây nến chuyển giao qua mốc 14:45 (currentMinute < sessionEndTotal and currentCloseMinute >= sessionEndTotal), nếu vẫn còn vị thế mở, bot sẽ gọi strategy.close_all(immediately=true, comment="Session End") để đóng lệnh ngay lập tức, tránh rủi ro qua đêm.

5.3. Bảng tổng hợp cơ chế bảo vệ vị thế

Cơ chế bảo vệTham số liên quanCông thức / Điều kiện thực tế trong codeGhi chú
Stop Loss cố địnhstopLossPoints (5.0)Long: entryPrice - 5.0 / Short: entryPrice + 5.0Khớp qua strategy.exit
Take Profit cố địnhtakeProfitPoints (15.0)Long: entryPrice + 15.0 / Short: entryPrice - 15.0Tỷ lệ R:R mặc định 1:3
Đóng lệnh cuối phiênsessionEndHour (14), sessionEndMinute (45)finalSessionBar and strategy.position_size != 0Gọi strategy.close_all(immediately=true)
Chống trùng lệnhpyramiding=0, notEnteredThisBarChỉ vào khi positionFlat và 1 lệnh/nếnNgăn nhồi lệnh hoặc vào đúp
Giới hạn tần suấtmaximumTradesPerDay (2), cooldownBars (0)tradesToday < 2 và bar_index - lastExitBar > 0Kiểm soát giao dịch quá mức

6. Hướng dẫn cài đặt và đọc bảng Diagnostics trên TradingView

Các bước cài đặt

  1. Mở biểu đồ hợp đồng tương lai VN30F1M trên TradingView (chọn khung thời gian giao dịch mong muốn, ví dụ M5 hoặc M15; nếu bật useH1EMABias thì nên dùng khung dưới 60 phút).
  2. Mở tab Pine Editor ở thanh công cụ phía dưới biểu đồ.
  3. Xóa mã mặc định, sao chép toàn bộ 100% mã nguồn Pine Script v6 ở Mục 1 và dán vào Pine Editor.
  4. Nhấn Save (Lưu), đặt tên chiến lược, sau đó nhấn Add to chart (Thêm vào biểu đồ).
  5. Mở phần Settings (Cài đặt) của chiến lược: nếu muốn giao dịch cả 2 chiều, chuyển Trade Direction từ "Long" sang "Both", và bật Show Diagnostics? nếu muốn theo dõi bảng thống kê trực tiếp.

Cách đọc bảng chẩn đoán (Diagnostics Table)

Khi bật tùy chọn Show Diagnostics? (showDiagnostics = true), bot hiển thị bảng table.new(position.top_right, 2, 21) ở góc trên bên phải biểu đồ tại cây nến cuối cùng (barstate.islast) với 21 dòng thông tin:

  • Dòng 0 – 7 (Thông số thị trường & Chỉ báo): Hiển thị tên bot CNPS76 cùng khung thời gian (timeframe.period), giá trị VWAP, Z-Score, Z Change, Deviation (close - vwap), Deviation StDev, RSI và ADX.
  • Dòng 8 – 11 (Thống kê cực hạn & Tái gia nhập): Đếm số lần Z-Score đi vào vùng cực hạn (Low Extremes, High Extremes) và số lần cắt ngược lại ngưỡng (Bull Re-entries, Bear Re-entries).
  • Dòng 12 – 15 (Thống kê tín hiệu): Đếm số lần đạt tín hiệu cơ sở (Long Bases, Short Bases) và tín hiệu thô qua hết bộ lọc (Long Signals, Short Signals).
  • Dòng 16 – 17 (Trạng thái chờ): Pending Long và Pending Short hiển thị YES hoặc NO, cho biết bot có đang nằm trong cửa sổ chờ xác nhận confirmationBars hay không.
  • Dòng 18 – 20 (Thống kê thực thi): Tổng số lệnh đã khớp (Long Entries, Short Entries) và tiến độ giới hạn ngày Trades Today (tradesToday / maximumTradesPerDay).

7. Cách thiết lập cảnh báo tín hiệu giao dịch (Alert)

Để nhận thông báo tự động qua ứng dụng TradingView, Email hoặc Webhook khi Bot CNPS76 phát sinh lệnh, bạn thực hiện theo các bước sau:

  1. Nhấn vào biểu tượng Alert (Đồng hồ báo thức) trên thanh công cụ TradingView.
  2. Ở mục Condition, chọn đúng tên chiến lược CNPS76 VWAP Z-SCORE REVERSION.
  3. Ở mục Message, xóa nội dung mặc định và điền chính xác cú pháp: {{strategy.order.alert_message}}
  4. Cấu hình kênh nhận thông báo (Notify in app, Webhook URL…) và nhấn Create. Lưu ý: nếu không muốn nhận thông báo khi chạm SL/TP, bạn có thể tích chọn Disable SL / TP Alerts? trong phần cài đặt bot.

Bảng thông điệp Alert của CNPS76

Loại sự kiệnTham số trong codeNội dung thông điệp thực tế được gửi
Vào lệnh Longalert_message (Section 35)🟢 VÀO VỊ THẾ LONG (CNPS76 VWAP Z-Score) kèm 🎯 Giá vào, 🛑 Cắt lỗ (SL), 💰 Chốt lời (TP)
Vào lệnh Shortalert_message (Section 36)🔴 VÀO VỊ THẾ SHORT (CNPS76 VWAP Z-Score) kèm 🎯 Giá vào, 🛑 Cắt lỗ (SL), 💰 Chốt lời (TP)
Chốt lời Longalert_profit (Section 38)💰 CHỐT LỜI LONG (TP HIT) kèm 🎯 Giá chốt (activeLongTP)
Cắt lỗ Longalert_loss (Section 38)🛑 CẮT LỖ LONG (SL HIT) kèm 🎯 Giá cắt (activeLongSL)
Chốt lời Shortalert_profit (Section 39)💰 CHỐT LỜI SHORT (TP HIT) kèm 🎯 Giá chốt (activeShortTP)
Cắt lỗ Shortalert_loss (Section 39)🛑 CẮT LỖ SHORT (SL HIT) kèm 🎯 Giá cắt (activeShortSL)
Đóng lệnh cuối phiênalert_message (Section 41)⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End) kèm 🎯 Giá đóng (close)

Kết luận

CNPS76 VWAP Z-Score Reversion là một hệ thống giao dịch hồi quy về trung bình bài bản, giải quyết hiệu quả bài toán bắt điểm đảo chiều quanh Session VWAP nhờ kết hợp chuẩn hóa Z-Score, cửa sổ chờ xác nhận confirmationBars và cơ chế tự hủy setup khi giá quay lại vùng cực hạn. Chiến lược phát huy hiệu quả tốt nhất trong các phiên thị trường đi ngang (sideway) hoặc dao động trong biên độ quanh VWAP (khi ADX ở mức vừa phải), với tỷ lệ R:R mặc định 1:3 (5.0 điểm SL / 15.0 điểm TP) và quy tắc tất toán hết phiên lúc 14:45.

Bạn có thể tham khảo thêm các hệ thống giao dịch tự động khác trên VN30F1M như Bot CNPS50 - Trend Analysis V2 và Bot CNPS49 - Daily Open để đa dạng hóa danh mục chiến lược.

Thông tin chỉ mang tính tham khảo, không phải khuyến nghị đầu tư. Kết quả kiểm thử quá khứ không đảm bảo lợi nhuận trong tương lai.

Thông tin trong bài chỉ mang tính tham khảo, không phải khuyến nghị mua bán. Giao dịch phái sinh có rủi ro cao do sử dụng đòn bẩy; nhà đầu tư tự chịu trách nhiệm với quyết định của mình.

Đinh Mạnh Đạt

Nhà nghiên cứu định lượng, chuyên sâu về dữ liệu Open Interest và quản trị vị thế.

Bản tin phái sinh mỗi phiên
Nhận bản tin mỗi phiên + Dự báo Nhịp đập phái sinh

Giao dịch & cuộc sống

Xem tất cả →
Cộng đồng