Thứ Ba, 01/12/202601/12/2026

Hướng Dẫn Sử Dụng Bot CNPS66 - VWAP Elastic Reversion V1 cho VN30F1M

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

Trong giao dịch phái sinh VN30F1M trong ngày, giá thường xuyên có những nhịp kéo giãn quá mức khỏi vùng giá trị hợp lý (Session VWAP) do lực đẩy tâm lý hoặc quét thanh khoản ngắn hạn, rồi nhanh chóng bị từ chối và hồi quy trở lại. Tuy nhiên, nếu bắt đáy/đỉnh mù quáng khi giá đang đi mạnh, nhà đầu tư dễ gặp rủi ro “bắt dao rơi” khi xu hướng quá khỏe hoặc bị kẹt lệnh qua giờ nghỉ trưa và phiên ATC.

CNPS66 VWAP ELASTIC REVERSION V1 - VN30F1M (shorttitle: "CNPS66 VER V1") được viết bằng Pine Script v6 trên TradingView để giải quyết bài toán trên theo mô hình đảo chiều về giá trị trung bình (mean-reversion): phát hiện độ lệch VWAP theo biên độ biến động ATR, ghi nhận trạng thái quá độ (exhaustion) và chỉ kích hoạt lệnh khi có xác nhận từ chối ngay tại nến cực trị hoặc tái chiếm dải hồi quy ở các nến kế tiếp.

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

  • Hai lộ trình vào lệnh linh hoạt (Active Hybrid): Kết hợp cả Extreme Rejection (từ chối ngay tại nến chạm cực trị) và Later Band Reclaim (chờ nến sau đóng cửa vượt lại qua dải Reclaim).
  • Chốt chặn chống ngược xu hướng mạnh (Strong Trend Guard): Sử dụng ADX(14) và +DI / -DI để tự động chặn lệnh Long khi xu hướng giảm quá mạnh hoặc chặn lệnh Short khi xu hướng tăng quá mạnh.
  • Bảo vệ vị thế đa lớp: Ngoài Stop Loss và Take Profit cố định theo R hoặc theo Session VWAP, bot còn tích hợp thoát lệnh khi hồi quy thất bại (VWAP Reversion Failed), giới hạn thời gian giữ lệnh (Maximum Hold Minutes) và tự động đóng toàn bộ vị thế trước giờ nghỉ trưa (11:25) cũng như trước ATC (14:25).
  • Giới hạn lỗ ngày (Daily Loss Guard): Tự động khóa mở vị thế mới nếu mức lỗ đã thực hiện trong ngày chạm ngưỡng 2.400.000 VND.

1. CNPS66 VWAP Elastic Reversion V1 là gì?

CNPS66 là hệ thống giao dịch tự động theo trường phái intraday mean-reversion dành cho hợp đồng tương lai VN30F1M (khuyến nghị khung thời gian chuẩn trong ngày như 1m, 3m, 5m). Chiến lược vận hành dựa trên 4 trụ cột kỹ thuật chính:

  1. Session-Anchored VWAP & Dải ATR Co Giãn (Elastic Bands): Tính toán VWAP neo theo từng phiên giao dịch trong ngày (reset mỗi ngày mới, chỉ tích lũy trong phiên khớp lệnh liên tục sáng 09:00–11:30 và chiều 13:00–14:30), kết hợp với ATR(14) để tạo ra dải cực trị (±1.35 ATR) và dải tái chiếm (±0.95 ATR).
  2. Máy trạng thái 3 bước (State Machine): Theo dõi chặt chẽ quá trình chuyển pha từ trạng thái chờ (0) sang trạng thái ghi nhận cực trị dưới (-1) hoặc cực trị trên (1), lưu giữ đỉnh/đáy cực trị thực tế (recordedLow / recordedHigh) trong tối đa 7 nến chờ tái chiếm.
  3. Bộ lọc chất lượng nến & Regime thị trường: Đo lường tỷ lệ thân nến (bodyRatio), vị trí đóng cửa (closeLocation), độ dài râu nến từ chối (lowerWickShare / upperWickShare), cùng bộ lọc xu hướng ADX (bật mặc định) và tùy chọn RSI / RVOL.
  4. Hệ thống quản trị rủi ro & Đồng hồ phiên VN30F1M: Kiểm tra Min–Max Stop, Minimum Gross Target, Minimum Reward/Risk ngay trước khi gửi lệnh; đồng thời kiểm soát khung giờ vào lệnh (09:15–11:20 và 13:05–14:15), số lệnh tối đa trong ngày, cooldown sau thoát lệnh và đóng lệnh bắt buộc trước nghỉ trưa/ATC.

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

Nhóm thông sốTên biến trong codeGiá trị mặc địnhMô tả chức năng
01 - Trade ControltradeDirection"Both"Hướng giao dịch cho phép (Both, Long, Short)
contracts3Số hợp đồng cấu hình ở Input (strategy() mặc định default_qty_value=1)
maximumTradesPerDay6Số lệnh tối đa mỗi ngày
cooldownBars2Số nến nghỉ tối thiểu sau khi đóng lệnh
minimumEntrySpacing3Khoảng cách nến tối thiểu giữa 2 lần vào lệnh
oneTradePerDirectionfalseGiới hạn tối đa 1 lệnh mỗi chiều/ngày
02 - VWAP DeviationatrPeriod14Chu kỳ tính chỉ báo ATR
extremeBandATR1.35Biên độ dải cực trị tính từ VWAP (theo ATR)
reclaimBandATR0.95Biên độ dải tái chiếm tính từ VWAP (theo ATR)
minimumEntryDistanceATR0.35Khoảng cách tối thiểu từ giá vào tới VWAP (theo ATR)
minimumSessionBars5Số nến tối thiểu sau 09:00 để kích hoạt tín hiệu
03 - Reversal EntryentryMode"Active Hybrid"Chế độ vào lệnh (Active Hybrid, Extreme Rejection, Later Band Reclaim)
maximumReclaimBars7Số nến tối đa chờ tín hiệu tái chiếm sau khi tạo cực trị
minimumRejectionWick0.25Tỷ lệ râu nến từ chối tối thiểu trên biên độ nến
minimumCandleBody0.15Tỷ lệ thân nến tối thiểu trên biên độ nến
minimumCloseLocation0.55Vị trí giá đóng cửa tối thiểu theo chiều đảo chiều
minimumRecoveryPoints0.20Khoảng đệm vượt dải Reclaim khi tái chiếm (điểm)
allowSameBarRejectiontrueCho phép vào lệnh ngay tại nến tạo cực trị
04 - Market RegimeuseStrongTrendGuardtrueBật bộ lọc chặn bắt đỉnh/đáy khi ADX quá cao
strongTrendADX42.0Ngưỡng ADX xác định xu hướng rất mạnh
useRSIFilterfalseBật bộ lọc RSI ngắn hạn
rsiPeriod / longRSIMaximum / shortRSIMinimum7 / 52.0 / 48.0Chu kỳ và ngưỡng RSI cho Long/Short
useRVOLFilter / volumeBaseline / minimumRVOLfalse / 25 / 0.70Bộ lọc khối lượng tương đối so với SMA(25)
05 - RiskstopMode"ATR Fixed"Phương pháp đặt SL (ATR Fixed, Extreme Structure, Recent Structure)
fixedStopATR1.35Khoảng SL cố định theo ATR
stopLookback / stopBufferATR4 / 0.15Số nến cấu trúc gần nhất và khoảng đệm ATR
minimumStopPoints / maximumStopPoints1.50 / 15.0Giới hạn rủi ro SL tối thiểu và tối đa (điểm)
targetMode / takeProfitR"Fixed R" / 1.45Phương pháp đặt TP (Fixed R, VWAP Snapshot, VWAP With Minimum R)
minimumVWAPTargetR / minimumGrossTarget0.90 / 2.50Tỷ lệ R:R tối thiểu và mục tiêu điểm gộp tối thiểu
06 - ExitsuseBreakEven / breakEvenAtR / breakEvenOffsetfalse / 1.00 / 0.20Cơ chế dời SL về hòa vốn + offset
useFailedReversionExit / failureBandATR / failureClosestrue / 2.00 / 2Thoát lệnh nếu giá đóng cửa bất lợi vượt 2.00 ATR liên tiếp 2 nến
useTimeExit / maximumHoldMinutestrue / 40Thoát lệnh nếu giữ quá 40 phút
07 - ProtectionuseDailyLossGuard / maximumDailyLossVNDtrue / 2400000Khóa vào lệnh mới khi lỗ đã chốt trong ngày >= 2.400.000 VND
08 - Trading SessionmorningEntry / afternoonEntry"0915-1120" / "1305-1415"Khung giờ cho phép tìm điểm vào lệnh
closeBeforeLunch / lunchFlatMinutetrue / 25Đóng toàn bộ vị thế trước giờ nghỉ trưa lúc 11:25
finalFlatHour / finalFlatMinute14 / 25Đóng toàn bộ vị thế cuối ngày lúc 14:25

Source Code CNPS66 VWAP Elastic Reversion V1

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
// CNPS66 - Session VWAP Elastic Reversion V1 - VN30F1M.
// Distinct mean-reversion model: intraday VWAP displacement -> exhaustion
// -> same-bar rejection or later band reclaim. No diagnostic table.
strategy(title="CNPS66 VWAP ELASTIC REVERSION V1 - VN30F1M", shorttitle="CNPS66 VER V1", overlay=true, initial_capital=100000000, currency=currency.VND, default_qty_type=strategy.fixed, default_qty_value=1, pyramiding=0, margin_long=10, margin_short=10, slippage=0, commission_type=strategy.commission.cash_per_contract, commission_value=0, process_orders_on_close=false, calc_on_order_fills=false, calc_on_every_tick=false, fill_orders_on_standard_ohlc=true, max_bars_back=5000, max_labels_count=100)

// ============================================================================
// SECTION 1: EXECUTION AND FREQUENCY
// ============================================================================
tradeDirection = input.string("Both", "Trade Direction", options=["Both", "Long", "Short"], group="01 - Trade Control")
contracts = input.int(3, "Contracts Per Entry", minval=1, maxval=20, group="01 - Trade Control")
maximumTradesPerDay = input.int(6, "Maximum Trades Per Day", minval=1, maxval=20, group="01 - Trade Control")
cooldownBars = input.int(2, "Cooldown Bars After Exit", minval=0, maxval=60, group="01 - Trade Control")
minimumEntrySpacing = input.int(3, "Minimum Bars Between Entries", minval=0, maxval=60, group="01 - Trade Control")
oneTradePerDirection = input.bool(false, "Only One Trade Per Direction Per Day?", group="01 - Trade Control")

// ============================================================================
// SECTION 2: ELASTIC VWAP BANDS
// ============================================================================
atrPeriod = input.int(14, "ATR Lookback", minval=5, maxval=100, group="02 - VWAP Deviation")
extremeBandATR = input.float(1.35, "Extreme Distance From VWAP (ATR)", minval=0.40, maxval=5.00, step=0.05, group="02 - VWAP Deviation")
reclaimBandATR = input.float(0.95, "Reclaim Band Distance From VWAP (ATR)", minval=0.10, maxval=4.00, step=0.05, group="02 - VWAP Deviation")
minimumEntryDistanceATR = input.float(0.35, "Minimum Entry Distance From VWAP (ATR)", minval=0.0, maxval=3.0, step=0.05, group="02 - VWAP Deviation")
minimumSessionBars = input.int(5, "Minimum Bars After 09:00 Open", minval=1, maxval=60, group="02 - VWAP Deviation")

// ============================================================================
// SECTION 3: ENTRY TRIGGERS - DISTINCT REVERSAL ROUTES
// ============================================================================
entryMode = input.string("Active Hybrid", title="Entry Method", options=["Active Hybrid", "Extreme Rejection", "Later Band Reclaim"], group="03 - Reversal Entry")
maximumReclaimBars = input.int(7, "Maximum Bars Waiting For Reclaim", minval=1, maxval=30, group="03 - Reversal Entry")
minimumRejectionWick = input.float(0.25, "Minimum Rejection Wick / Candle Range", minval=0, maxval=0.90, step=0.05, group="03 - Reversal Entry")
minimumCandleBody = input.float(0.15, "Minimum Directional Candle Body / Range", minval=0, maxval=1.0, step=0.05, group="03 - Reversal Entry")
minimumCloseLocation = input.float(0.55, "Minimum Directional Close Location", minval=0.50, maxval=0.95, step=0.05, group="03 - Reversal Entry")
minimumRecoveryPoints = input.float(0.20, "Minimum Reclaim Close Buffer (points)", minval=0, step=0.10, group="03 - Reversal Entry")
allowSameBarRejection = input.bool(true, "Allow Direct Extreme Rejection?", group="03 - Reversal Entry")

// ============================================================================
// SECTION 4: OPTIONAL ANTI-TREND FILTERS
// ============================================================================
useStrongTrendGuard = input.bool(true, "Avoid Fading Very Strong ADX Trend?", group="04 - Market Regime")
strongTrendADX = input.float(42.0, "Strong Trend ADX Threshold", minval=15, maxval=65, step=1, group="04 - Market Regime")
useRSIFilter = input.bool(false, "Require Short-Term RSI Exhaustion?", group="04 - Market Regime")
rsiPeriod = input.int(7, "RSI Length", minval=2, maxval=30, group="04 - Market Regime")
longRSIMaximum = input.float(52.0, "Long Maximum RSI", minval=10, maxval=70, step=1, group="04 - Market Regime")
shortRSIMinimum = input.float(48.0, "Short Minimum RSI", minval=30, maxval=90, step=1, group="04 - Market Regime")
useRVOLFilter = input.bool(false, "Require Minimum Volume At Entry?", group="04 - Market Regime")
volumeBaseline = input.int(25, "Volume Baseline Bars", minval=5, maxval=150, group="04 - Market Regime")
minimumRVOL = input.float(0.70, "Minimum Entry Relative Volume", minval=0.10, maxval=5.0, step=0.05, group="04 - Market Regime")

// ============================================================================
// SECTION 5: STOP AND TARGET
// ============================================================================
stopMode = input.string("ATR Fixed", "Initial Stop Method", options=["ATR Fixed", "Extreme Structure", "Recent Structure"], group="05 - Risk")
fixedStopATR = input.float(1.35, "Fixed Stop Distance (ATR)", minval=0.25, maxval=5.0, step=0.05, group="05 - Risk")
stopLookback = input.int(4, "Recent Structure Lookback", minval=2, maxval=30, group="05 - Risk")
stopBufferATR = input.float(0.15, "Structure Stop Buffer (ATR)", minval=0, maxval=2, step=0.05, group="05 - Risk")
minimumStopPoints = input.float(1.50, "Minimum Initial Stop (points)", minval=0.10, step=0.50, group="05 - Risk")
maximumStopPoints = input.float(15.0, "Maximum Initial Stop (points)", minval=1, step=0.50, group="05 - Risk")
targetMode = input.string("Fixed R", "Profit Target Method", options=["Fixed R", "VWAP Snapshot", "VWAP With Minimum R"], group="05 - Risk")
takeProfitR = input.float(1.45, "Fixed-R Profit Target", minval=0.25, maxval=6.0, step=0.05, group="05 - Risk")
minimumVWAPTargetR = input.float(0.90, "Minimum Reward/Risk For VWAP Target", minval=0.25, maxval=5.0, step=0.05, group="05 - Risk")
minimumGrossTarget = input.float(2.50, "Minimum Gross Target (points)", minval=0, step=0.50, group="05 - Risk")

// ============================================================================
// SECTION 6: POSITION MANAGEMENT
// ============================================================================
useBreakEven = input.bool(false, "Activate Break Even?", group="06 - Exits")
breakEvenAtR = input.float(1.00, "Break Even After (R)", minval=0.25, maxval=5.0, step=0.25, group="06 - Exits")
breakEvenOffset = input.float(0.20, "Break Even Offset (points)", minval=0, step=0.10, group="06 - Exits")
useFailedReversionExit = input.bool(true, "Exit If Price Extends Against Reversion?", group="06 - Exits")
failureBandATR = input.float(2.00, "Adverse Close Distance From VWAP (ATR)", minval=0.50, maxval=8.0, step=0.10, group="06 - Exits")
failureCloses = input.int(2, "Consecutive Adverse Closes", minval=1, maxval=5, group="06 - Exits")
useTimeExit = input.bool(true, "Limit Holding Time?", group="06 - Exits")
maximumHoldMinutes = input.int(40, "Maximum Holding Minutes", minval=5, maxval=240, group="06 - Exits")

// ============================================================================
// SECTION 7: DAILY LOSS GUARD
// ============================================================================
useDailyLossGuard = input.bool(true, "Block New Entries After Daily Realized Loss?", group="07 - Protection")
maximumDailyLossVND = input.float(2400000, "Daily Realized Loss Threshold (VND)", minval=100000, step=100000, group="07 - Protection")

// ============================================================================
// SECTION 8: VN30F1M INTRADAY SESSIONS
// ============================================================================
string timezoneVN = "Asia/Ho_Chi_Minh"
morningEntry = input.session("0915-1120", "Morning Entry Window", group="08 - Trading Session")
afternoonEntry = input.session("1305-1415", "Afternoon Entry Window", group="08 - Trading Session")
closeBeforeLunch = input.bool(true, "Force Flat Before Lunch?", group="08 - Trading Session")
lunchFlatMinute = input.int(25, "Lunch Flat Minute (11:xx)", minval=15, maxval=30, group="08 - Trading Session")
finalFlatHour = input.int(14, "Final Flat Hour", minval=0, maxval=23, group="08 - Trading Session")
finalFlatMinute = input.int(25, "Final Flat Minute", minval=0, maxval=59, group="08 - Trading Session")

// ============================================================================
// SECTION 9: DISPLAY - NO FLOATING TABLE
// ============================================================================
showVWAP = input.bool(true, "Show Continuous-Session VWAP?", group="09 - Display")
showBands = input.bool(false, "Show Extreme VWAP Bands?", group="09 - Display")
showArmedMarkers = input.bool(false, "Show Recorded Extremes?", group="09 - Display")
showEntryMarkers = input.bool(true, "Show Trade Signals?", group="09 - Display")
showTradeLevels = input.bool(true, "Show Active SL / TP?", group="09 - Display")

// ============================================================================
// SECTION 10: CLOCK AND SESSION ENGINE
// ============================================================================
int minuteOpen = hour(time, timezoneVN) * 60 + minute(time, timezoneVN)
int minuteClose = hour(time_close, timezoneVN) * 60 + minute(time_close, timezoneVN)
int lunchCutoff = 660 + lunchFlatMinute
int finalCutoff = finalFlatHour * 60 + finalFlatMinute
bool continuousMorning = minuteOpen >= 540 and minuteOpen < 690
bool continuousAfternoon = minuteOpen >= 780 and minuteOpen < 870
bool continuousSession = continuousMorning or continuousAfternoon
bool morningStarts = continuousMorning and not continuousMorning[1]
bool afternoonStarts = continuousAfternoon and not continuousAfternoon[1]
bool inMorningEntry = not na(time(timeframe.period, morningEntry + ":23456", timezoneVN))
bool inAfternoonEntry = not na(time(timeframe.period, afternoonEntry + ":23456", timezoneVN))
bool entrySession = continuousSession and (inMorningEntry or inAfternoonEntry)
int dayKey = year(time, timezoneVN) * 10000 + month(time, timezoneVN) * 100 + dayofmonth(time, timezoneVN)
bool newTradingDay = bar_index == 0 or dayKey != nz(dayKey[1], dayKey)
bool beforeCutoff = (not na(time_close) and minuteClose < finalCutoff and (not closeBeforeLunch or not continuousMorning or minuteClose < lunchCutoff))
bool lunchFlatBar = (closeBeforeLunch and barstate.isconfirmed and continuousMorning and minuteOpen < lunchCutoff and minuteClose >= lunchCutoff)
bool finalFlatBar = (barstate.isconfirmed and continuousAfternoon and minuteOpen < finalCutoff and minuteClose >= finalCutoff)

// ============================================================================
// SECTION 11: SESSION-ANCHORED VWAP AND ELASTIC BANDS
// ============================================================================
var float cumulativePriceVolume = 0.0
var float cumulativeVolume = 0.0
var int sessionBarsToday = 0
if newTradingDay
    cumulativePriceVolume := 0.0
    cumulativeVolume := 0.0
    sessionBarsToday := 0
if continuousSession and barstate.isconfirmed
    float barVolume = na(volume) or volume <= 0 ? 1.0 : volume
    cumulativePriceVolume += hlc3 * barVolume
    cumulativeVolume += barVolume
    sessionBarsToday += 1
float sessionVWAP = cumulativeVolume > 0 ? cumulativePriceVolume / cumulativeVolume : na
float atr = ta.atr(atrPeriod)
float upperExtreme = sessionVWAP + extremeBandATR * atr
float lowerExtreme = sessionVWAP - extremeBandATR * atr
float upperReclaim = sessionVWAP + reclaimBandATR * atr
float lowerReclaim = sessionVWAP - reclaimBandATR * atr
bool valueReady = (continuousSession and sessionBarsToday >= minimumSessionBars and not na(sessionVWAP) and not na(atr) and atr > 0)

// ============================================================================
// SECTION 12: CANDLE EXHAUSTION / OPTIONAL REGIME GUARDS
// ============================================================================
float candleRange = math.max(high - low, syminfo.mintick)
float bodyRatio = math.abs(close - open) / candleRange
float closeLocation = (close - low) / candleRange
float lowerWickShare = (math.min(open, close) - low) / candleRange
float upperWickShare = (high - math.max(open, close)) / candleRange
bool bullishRejection = (close > open and bodyRatio >= minimumCandleBody and closeLocation >= minimumCloseLocation and lowerWickShare >= minimumRejectionWick)
bool bearishRejection = (close < open and bodyRatio >= minimumCandleBody and closeLocation <= 1.0 - minimumCloseLocation and upperWickShare >= minimumRejectionWick)
bool bullishConfirmation = close > open and bodyRatio >= minimumCandleBody and closeLocation >= minimumCloseLocation
bool bearishConfirmation = close < open and bodyRatio >= minimumCandleBody and closeLocation <= 1.0 - minimumCloseLocation
[pDI, mDI, adx] = ta.dmi(14, 14)
float rsi = ta.rsi(close, rsiPeriod)
float priorVolumeSMA = ta.sma(volume, volumeBaseline)[1]
float entryRVOL = not na(priorVolumeSMA) and priorVolumeSMA > 0 ? volume / priorVolumeSMA : na
bool avoidLong = useStrongTrendGuard and not na(adx) and adx > strongTrendADX and mDI > pDI
bool avoidShort = useStrongTrendGuard and not na(adx) and adx > strongTrendADX and pDI > mDI
bool volumeOK = not useRVOLFilter or (not na(entryRVOL) and entryRVOL >= minimumRVOL)
bool rsiLongOK = not useRSIFilter or (not na(rsi) and rsi <= longRSIMaximum)
bool rsiShortOK = not useRSIFilter or (not na(rsi) and rsi >= shortRSIMinimum)

// ============================================================================
// SECTION 13: DAILY COUNTERS AND ENTRY PERMISSION
// ============================================================================
var int tradesToday = 0
var int previouslyClosedTrades = 0
var int lastExitBar = na
var int lastEntryBar = na
var float dayStartingNetProfit = na
var bool longTradedToday = false
var bool shortTradedToday = false
if newTradingDay
    tradesToday := 0
    dayStartingNetProfit := strategy.netprofit
    longTradedToday := false
    shortTradedToday := false
if strategy.closedtrades > previouslyClosedTrades
    previouslyClosedTrades := strategy.closedtrades
    lastExitBar := bar_index
bool flat = strategy.position_size == 0
bool inLong = strategy.position_size > 0
bool inShort = strategy.position_size < 0
bool longAllowed = tradeDirection != "Short" and (not oneTradePerDirection or not longTradedToday)
bool shortAllowed = tradeDirection != "Long" and (not oneTradePerDirection or not shortTradedToday)
float realizedDailyPnL = strategy.netprofit - nz(dayStartingNetProfit, strategy.netprofit)
bool dailyLossOK = not useDailyLossGuard or realizedDailyPnL > -maximumDailyLossVND
bool cooldownOK = na(lastExitBar) or bar_index - lastExitBar > cooldownBars
bool spacingOK = na(lastEntryBar) or bar_index - lastEntryBar >= minimumEntrySpacing
bool canEnter = (flat and entrySession and beforeCutoff and valueReady and tradesToday < maximumTradesPerDay and dailyLossOK and cooldownOK and spacingOK and barstate.isconfirmed)

// ============================================================================
// SECTION 14: ELASTIC STRETCH / RECLAIM STATE MACHINE
// ============================================================================
// State  0: Waiting for a large VWAP deviation.
// State -1: Lower extreme printed; await upward reversal or band reclaim.
// State  1: Upper extreme printed; await downward reversal or band reclaim.
// ============================================================================
var int setupState = 0
var int extremeBar = na
var float recordedLow = na
var float recordedHigh = na
bool lowerExtremeMarker = false
bool upperExtremeMarker = false
bool rawLong = false
bool rawShort = false
float signalExtreme = na
if newTradingDay or morningStarts or afternoonStarts or lunchFlatBar or finalFlatBar
    setupState := 0
    extremeBar := na
    recordedLow := na
    recordedHigh := na

// ============================================================================
// SECTION 15: PREVIOUS LOWER EXTREME -> LONG REVERSION
// ============================================================================
if setupState == -1 and barstate.isconfirmed and bar_index > extremeBar
    bool expired = bar_index - extremeBar > maximumReclaimBars
    bool invalid = not entrySession or not beforeCutoff or not valueReady
    bool noLongTrade = not longAllowed or not dailyLossOK
    if expired or invalid or noLongTrade
        setupState := 0
    else
        recordedLow := math.min(recordedLow, low)
        bool reclaimedBand = (close > lowerReclaim + minimumRecoveryPoints and close > close[1] and bullishConfirmation)
        bool anotherRejection = (low <= lowerExtreme and bullishRejection and close > close[1])
        bool triggerLong = ((entryMode != "Extreme Rejection" and reclaimedBand) or (entryMode != "Later Band Reclaim" and anotherRejection))
        if triggerLong and not avoidLong and volumeOK and rsiLongOK
            rawLong := true
            signalExtreme := recordedLow
            setupState := 0
        else if close >= sessionVWAP
            setupState := 0

// ============================================================================
// SECTION 16: PREVIOUS UPPER EXTREME -> SHORT REVERSION
// ============================================================================
if setupState == 1 and barstate.isconfirmed and bar_index > extremeBar
    bool expired = bar_index - extremeBar > maximumReclaimBars
    bool invalid = not entrySession or not beforeCutoff or not valueReady
    bool noShortTrade = not shortAllowed or not dailyLossOK
    if expired or invalid or noShortTrade
        setupState := 0
    else
        recordedHigh := math.max(recordedHigh, high)
        bool reclaimedBand = (close < upperReclaim - minimumRecoveryPoints and close < close[1] and bearishConfirmation)
        bool anotherRejection = (high >= upperExtreme and bearishRejection and close < close[1])
        bool triggerShort = ((entryMode != "Extreme Rejection" and reclaimedBand) or (entryMode != "Later Band Reclaim" and anotherRejection))
        if triggerShort and not avoidShort and volumeOK and rsiShortOK
            rawShort := true
            signalExtreme := recordedHigh
            setupState := 0
        else if close <= sessionVWAP
            setupState := 0

// ============================================================================
// SECTION 17: DETECT NEW EXTREMES / SAME-BAR REJECTION
// ============================================================================
bool newLowerExtreme = valueReady and low <= lowerExtreme and close < sessionVWAP
bool newUpperExtreme = valueReady and high >= upperExtreme and close > sessionVWAP
if setupState == 0 and canEnter and not rawLong and not rawShort
    if newLowerExtreme and longAllowed
        lowerExtremeMarker := true
        extremeBar := bar_index
        recordedLow := low
        setupState := -1
        bool directLong = (allowSameBarRejection and entryMode != "Later Band Reclaim" and bullishRejection and close > close[1] and not avoidLong and volumeOK and rsiLongOK)
        if directLong
            rawLong := true
            signalExtreme := recordedLow
            setupState := 0
    else if newUpperExtreme and shortAllowed
        upperExtremeMarker := true
        extremeBar := bar_index
        recordedHigh := high
        setupState := 1
        bool directShort = (allowSameBarRejection and entryMode != "Later Band Reclaim" and bearishRejection and close < close[1] and not avoidShort and volumeOK and rsiShortOK)
        if directShort
            rawShort := true
            signalExtreme := recordedHigh
            setupState := 0

// ============================================================================
// SECTION 18: INITIAL STOP AND SNAPSHOT TARGET
// ============================================================================
float recentStructureLow = ta.lowest(low, stopLookback)
float recentStructureHigh = ta.highest(high, stopLookback)
float longStopReference = stopMode == "Extreme Structure" ? signalExtreme : recentStructureLow
float shortStopReference = stopMode == "Extreme Structure" ? signalExtreme : recentStructureHigh
float candidateLongStop = (valueReady ? math.round_to_mintick(stopMode == "ATR Fixed" ? close - fixedStopATR * atr : longStopReference - stopBufferATR * atr) : na)
float candidateShortStop = (valueReady ? math.round_to_mintick(stopMode == "ATR Fixed" ? close + fixedStopATR * atr : shortStopReference + stopBufferATR * atr) : na)
float longRisk = close - candidateLongStop
float shortRisk = candidateShortStop - close
float fixedLongTarget = close + longRisk * takeProfitR
float fixedShortTarget = close - shortRisk * takeProfitR
float targetFloorLong = close + longRisk * minimumVWAPTargetR
float targetFloorShort = close - shortRisk * minimumVWAPTargetR
float candidateLongTarget = (targetMode == "Fixed R" ? fixedLongTarget : targetMode == "VWAP Snapshot" ? sessionVWAP : math.max(sessionVWAP, targetFloorLong))
float candidateShortTarget = (targetMode == "Fixed R" ? fixedShortTarget : targetMode == "VWAP Snapshot" ? sessionVWAP : math.min(sessionVWAP, targetFloorShort))
candidateLongTarget := not na(candidateLongTarget) ? math.round_to_mintick(candidateLongTarget) : na
candidateShortTarget := not na(candidateShortTarget) ? math.round_to_mintick(candidateShortTarget) : na
float longReward = candidateLongTarget - close
float shortReward = close - candidateShortTarget
bool longRiskOK = (not na(longRisk) and longRisk >= minimumStopPoints and longRisk <= maximumStopPoints and not na(longReward) and longReward >= minimumGrossTarget and longReward / longRisk >= minimumVWAPTargetR)
bool shortRiskOK = (not na(shortRisk) and shortRisk >= minimumStopPoints and shortRisk <= maximumStopPoints and not na(shortReward) and shortReward >= minimumGrossTarget and shortReward / shortRisk >= minimumVWAPTargetR)
bool longDistanceOK = close <= sessionVWAP - atr * minimumEntryDistanceATR
bool shortDistanceOK = close >= sessionVWAP + atr * minimumEntryDistanceATR
bool finalLong = rawLong and canEnter and longAllowed and not avoidLong and longDistanceOK and longRiskOK
bool finalShort = rawShort and canEnter and shortAllowed and not avoidShort and shortDistanceOK and shortRiskOK and not finalLong

// ============================================================================
// SECTION 19: ACTIVE POSITION STATE
// ============================================================================
var float activeStop = na
var float activeTarget = na
var float actualFillPrice = na
var float initialFillRisk = na
var int actualFillBar = na
var int adverseCloseCount = 0
var bool breakEvenActive = false

// ============================================================================
// SECTION 20: ENTER LONG WITH INITIAL BRACKET
// ============================================================================
if finalLong
    activeStop := candidateLongStop
    activeTarget := candidateLongTarget
    actualFillPrice := na
    initialFillRisk := na
    actualFillBar := na
    adverseCloseCount := 0
    breakEvenActive := false
    strategy.entry("CNPS66-L", strategy.long, comment="VWAP ELASTIC LONG", alert_message="🟢 VÀO VỊ THẾ LONG (VWAP Elastic Reversion)\\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\\n🛑 SL dự kiến: " + str.tostring(activeStop, format.mintick) + "\\n🎯 TP dự kiến: " + str.tostring(activeTarget, format.mintick))
    strategy.exit("CNPS66-L-X", from_entry="CNPS66-L", stop=activeStop, limit=activeTarget, comment_profit="TP Long", comment_loss="SL Long", alert_profit="💰 CHỐT LỜI LONG (TP HIT)\\n🎯 Giá chốt: " + str.tostring(activeTarget, format.mintick), alert_loss="🛑 CẮT LỖ LONG (SL HIT)\\n🎯 Giá cắt: " + str.tostring(activeStop, format.mintick))
    tradesToday += 1
    longTradedToday := true
    lastEntryBar := bar_index
    setupState := 0

// ============================================================================
// SECTION 21: ENTER SHORT WITH INITIAL BRACKET
// ============================================================================
else if finalShort
    activeStop := candidateShortStop
    activeTarget := candidateShortTarget
    actualFillPrice := na
    initialFillRisk := na
    actualFillBar := na
    adverseCloseCount := 0
    breakEvenActive := false
    strategy.entry("CNPS66-S", strategy.short, comment="VWAP ELASTIC SHORT", alert_message="🔴 VÀO VỊ THẾ SHORT (VWAP Elastic Reversion)\\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\\n🛑 SL dự kiến: " + str.tostring(activeStop, format.mintick) + "\\n🎯 TP dự kiến: " + str.tostring(activeTarget, format.mintick))
    strategy.exit("CNPS66-S-X", from_entry="CNPS66-S", stop=activeStop, limit=activeTarget, comment_profit="TP Short", comment_loss="SL Short", alert_profit="💰 CHỐT LỜI SHORT (TP HIT)\\n🎯 Giá chốt: " + str.tostring(activeTarget, format.mintick), alert_loss="🛑 CẮT LỖ SHORT (SL HIT)\\n🎯 Giá cắt: " + str.tostring(activeStop, format.mintick))
    tradesToday += 1
    shortTradedToday := true
    lastEntryBar := bar_index
    setupState := 0

// ============================================================================
// SECTION 22: ACTUAL NEXT-BAR FILL AND OPTIONAL BREAK EVEN
// ============================================================================
if strategy.position_size != 0 and strategy.opentrades > 0 and barstate.isconfirmed
    int fillBar = strategy.opentrades.entry_bar_index(0)
    float fillPrice = strategy.position_avg_price
    if na(actualFillBar) or fillBar != actualFillBar
        actualFillBar := fillBar
        actualFillPrice := fillPrice
        initialFillRisk := inLong ? fillPrice - activeStop : activeStop - fillPrice
    bool validFill = (not na(initialFillRisk) and initialFillRisk > syminfo.mintick and (inLong ? activeTarget > fillPrice : activeTarget < fillPrice))
    if not validFill
        strategy.close(inLong ? "CNPS66-L" : "CNPS66-S", immediately=true, comment="INVALID NEXT-BAR FILL", alert_message="🔄 ĐÓNG VỊ THẾ (Khớp lệnh không hợp lệ)\\n🎯 Giá đóng: " + str.tostring(close, format.mintick))
    else
        float currentR = (inLong ? close - fillPrice : fillPrice - close) / initialFillRisk
        if useBreakEven and currentR >= breakEvenAtR
            float breakEvenStop = math.round_to_mintick(inLong ? fillPrice + breakEvenOffset : fillPrice - breakEvenOffset)
            activeStop := inLong ? math.max(activeStop, breakEvenStop) : math.min(activeStop, breakEvenStop)
            breakEvenActive := true
        if inLong
            strategy.exit("CNPS66-L-X", from_entry="CNPS66-L", stop=activeStop, limit=activeTarget, comment_profit="TP Long", comment_loss=breakEvenActive ? "BE Long" : "SL Long", alert_profit="💰 CHỐT LỜI LONG (TP HIT)\\n🎯 Giá chốt: " + str.tostring(activeTarget, format.mintick), alert_loss=breakEvenActive ? ("🛡️ HÒA VỐN LONG (BE HIT)\\n🎯 Giá thoát: " + str.tostring(activeStop, format.mintick)) : ("🛑 CẮT LỖ LONG (SL HIT)\\n🎯 Giá cắt: " + str.tostring(activeStop, format.mintick)))
        else
            strategy.exit("CNPS66-S-X", from_entry="CNPS66-S", stop=activeStop, limit=activeTarget, comment_profit="TP Short", comment_loss=breakEvenActive ? "BE Short" : "SL Short", alert_profit="💰 CHỐT LỜI SHORT (TP HIT)\\n🎯 Giá chốt: " + str.tostring(activeTarget, format.mintick), alert_loss=breakEvenActive ? ("🛡️ HÒA VỐN SHORT (BE HIT)\\n🎯 Giá thoát: " + str.tostring(activeStop, format.mintick)) : ("🛑 CẮT LỖ SHORT (SL HIT)\\n🎯 Giá cắt: " + str.tostring(activeStop, format.mintick)))

// ============================================================================
// SECTION 23: REVERSION FAILURE / TIME EXIT
// ============================================================================
if strategy.position_size != 0 and strategy.opentrades > 0 and barstate.isconfirmed
    bool adverseExtension = (inLong ? close < sessionVWAP - atr * failureBandATR : close > sessionVWAP + atr * failureBandATR)
    adverseCloseCount := adverseExtension ? adverseCloseCount + 1 : 0
    if useFailedReversionExit and adverseCloseCount >= failureCloses
        strategy.close(inLong ? "CNPS66-L" : "CNPS66-S", comment="VWAP REVERSION FAILED", alert_message="⚡ ĐÓNG VỊ THẾ (Hồi quy VWAP thất bại)\\n🎯 Giá đóng: " + str.tostring(close, format.mintick))
    int entryTimestamp = strategy.opentrades.entry_time(0)
    if useTimeExit and not na(time_close) and time_close >= entryTimestamp + maximumHoldMinutes * 60000
        strategy.close(inLong ? "CNPS66-L" : "CNPS66-S", comment="MAXIMUM HOLD EXIT", alert_message="⏱️ ĐÓNG VỊ THẾ (Hết thời gian giữ lệnh tối đa)\\n🎯 Giá đóng: " + str.tostring(close, format.mintick))

// ============================================================================
// SECTION 24: FLAT BEFORE LUNCH AND ATC
// ============================================================================
if (lunchFlatBar or finalFlatBar) and strategy.position_size != 0
    strategy.close_all(immediately=true, comment="VN30F1M SESSION FLAT", alert_message="⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End)\\n🎯 Giá đóng: " + str.tostring(close, format.mintick))

// ============================================================================
// SECTION 25: CLEAN UP AFTER EXIT
// ============================================================================
if flat and not finalLong and not finalShort
    activeStop := na
    activeTarget := na
    actualFillPrice := na
    initialFillRisk := na
    actualFillBar := na
    adverseCloseCount := 0
    breakEvenActive := false

// ============================================================================
// SECTION 26: CLEAN PLOTS - NO DASHBOARD
// ============================================================================
plot(showVWAP ? sessionVWAP : na, title="Continuous-Session VWAP", color=color.orange, linewidth=2, style=plot.style_linebr)
plot(showBands ? upperExtreme : na, title="Upper Elastic Extreme", color=color.new(color.red, 40), style=plot.style_linebr)
plot(showBands ? lowerExtreme : na, title="Lower Elastic Extreme", color=color.new(color.teal, 40), style=plot.style_linebr)
plot(showTradeLevels and strategy.position_size != 0 ? activeStop : na, title="Active Stop Loss", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showTradeLevels and strategy.position_size != 0 ? activeTarget : na, title="Active Take Profit", color=color.green, linewidth=2, style=plot.style_linebr)
plotshape(showArmedMarkers and lowerExtremeMarker, title="Lower Extreme Recorded", style=shape.circle, location=location.belowbar, color=color.new(color.teal, 50), size=size.tiny)
plotshape(showArmedMarkers and upperExtremeMarker, title="Upper Extreme Recorded", style=shape.circle, location=location.abovebar, color=color.new(color.red, 50), size=size.tiny)
plotshape(showEntryMarkers and finalLong, title="CNPS66 LONG", text="L", style=shape.triangleup, location=location.belowbar, color=color.teal, textcolor=color.white, size=size.small)
plotshape(showEntryMarkers and finalShort, title="CNPS66 SHORT", text="S", style=shape.triangledown, location=location.abovebar, color=color.red, textcolor=color.white, size=size.small)

// ============================================================================
// CNPS66 V1 - EXECUTION NOTES
// ============================================================================
// 1. Distinct from CNPS64: this is VWAP-based mean reversion, not migration.
// 2. Dynamic deviation is normalized by ATR, with a frozen extreme reference.
// 3. Signals use closed bars and current/past session data, never future bars.
// 4. Default Active Hybrid accepts extreme rejection or later band reclaim.
// 5. Market entries normally fill on the chart bar after the signal.
// 6. Stop and profit target are determined from the confirmed signal candle.
// 7. Daily realized-loss protection blocks further entries only.
// 8. 10% simulated margin is not actual broker margin or margin guidance.
// 9. Use standard intraday bars, preferably VN30F1M 1m / 3m / 5m.
// 10. Profitability has not been established; verify in Strategy Tester.
// ============================================================================

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

2.1. Session-Anchored VWAP và Dải ATR Co Giãn (Elastic Bands)

Khác với VWAP thông thường chạy liên tục qua các phiên không khớp lệnh, CNPS66 chỉ tích lũy giá trị giao dịch khi continuousSession là đúng (phiên sáng 09:00–11:30, tức minuteOpen >= 540 and minuteOpen < 690; phiên chiều 13:00–14:30, tức minuteOpen >= 780 and minuteOpen < 870) và reset về 0 khi sang ngày mới (newTradingDay):

  • Nếu nến có volume <= 0 hoặc na, code tự thay bằng 1.0 để tránh chia cho 0 (barVolume = na(volume) or volume <= 0 ? 1.0 : volume).
  • Công thức: sessionVWAP = cumulativePriceVolume / cumulativeVolume, trong đó mỗi nến đóng cửa cộng dồn hlc3 * barVolume.
  • Từ sessionVWAP và atr = ta.atr(14), bot dựng 2 cặp dải co giãn:
    • Dải cực trị (Extreme Bands): upperExtreme = sessionVWAP + 1.35 * atr và lowerExtreme = sessionVWAP - 1.35 * atr.
    • Dải tái chiếm (Reclaim Bands): upperReclaim = sessionVWAP + 0.95 * atr và lowerReclaim = sessionVWAP - 0.95 * atr.
  • Dữ liệu chỉ hợp lệ (valueReady) khi đang trong phiên liên tục, đã qua ít nhất minimumSessionBars = 5 nến sau 09:00, sessionVWAP và atr > 0 đều hợp lệ.

2.2. Cấu trúc nến từ chối (Candle Exhaustion) và Xác nhận (Confirmation)

Bot định lượng lực đảo chiều trực tiếp trên từng cây nến đã đóng cửa bằng 4 đại lượng (với candleRange = math.max(high - low, syminfo.mintick)):

  • bodyRatio = math.abs(close - open) / candleRange (mặc định >= 0.15).
  • closeLocation = (close - low) / candleRange (Long cần >= 0.55, Short cần <= 0.45).
  • lowerWickShare = (math.min(open, close) - low) / candleRange và upperWickShare = (high - math.max(open, close)) / candleRange (mặc định cần râu từ chối >= 0.25).
  • Từ đó hình thành bullishRejection / bearishRejection (yêu cầu đủ thân nến, vị trí đóng cửa và râu nến từ chối) dùng cho lộ trình từ chối cực trị, và bullishConfirmation / bearishConfirmation (yêu cầu thân nến và vị trí đóng cửa, không bắt buộc râu dài) dùng cho lộ trình tái chiếm dải.

2.3. Bộ lọc Regime chống bắt dao rơi (Strong Trend Guard, RSI, RVOL)

Để tránh giao dịch ngược chiều khi thị trường đang vào sóng xu hướng cực mạnh:

  • Strong Trend Guard (bật mặc định): Tính ta.dmi(14, 14). Nếu adx > 42.0 và mDI > pDI, avoidLong = true (cấm Long khi xu hướng giảm quá mạnh). Ngược lại, nếu adx > 42.0 và pDI > mDI, avoidShort = true (cấm Short khi xu hướng tăng quá mạnh).
  • RSI Filter (tắt mặc định): Với rsiPeriod = 7, yêu cầu rsi <= 52.0 cho Long và rsi >= 48.0 cho Short nếu được bật.
  • RVOL Filter (tắt mặc định): So sánh volume nến tín hiệu với ta.sma(volume, 25)[1], yêu cầu entryRVOL >= 0.70 nếu được bật.

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

Quy trình vận hành của CNPS66 diễn ra tuần tự theo 5 bước trên mỗi nến đóng cửa (barstate.isconfirmed):

  1. Khởi tạo phiên và đếm ngưỡng an toàn: Khi sang ngày mới (newTradingDay), bot reset VWAP, bộ đếm tradesToday, longTradedToday, shortTradedToday, và ghi nhận dayStartingNetProfit. Nếu chuyển giao phiên (morningStarts, afternoonStarts, lunchFlatBar, finalFlatBar), máy trạng thái setupState cũng được reset về 0.
  2. Phát hiện độ lệch cực trị (setupState = -1 hoặc 1): Khi setupState == 0 và canEnter thỏa mãn, nếu giá chọc thủng lowerExtreme nhưng đóng cửa vẫn dưới sessionVWAP, bot chuyển sang setupState := -1 và lưu recordedLow := low. Tương tự với upperExtreme để chuyển sang setupState := 1 và lưu recordedHigh := high.
  3. Kích hoạt tín hiệu theo 1 trong 2 lộ trình:
    • Nếu allowSameBarRejection = true và entryMode != "Later Band Reclaim", bot kiểm tra ngay tại nến cực trị xem có nến từ chối (bullishRejection / bearishRejection) và giá đóng cửa cải thiện so với nến trước (close > close[1] hoặc close < close[1]) hay không.
    • Nếu chưa vào ngay, ở các nến kế tiếp (tối đa maximumReclaimBars = 7 nến), bot tiếp tục cập nhật recordedLow / recordedHigh và chờ giá đóng cửa vượt lại qua dải Reclaim (Later Band Reclaim) hoặc tạo thêm một nhịp từ chối mới tại dải Extreme. Nếu giá quay về chạm sessionVWAP trước khi có tín hiệu, setup bị hủy (setupState := 0).
  4. Kiểm tra khoảng cách, Risk/Reward và gửi lệnh: Khi có rawLong hoặc rawShort, bot tính candidateStop, candidateTarget, kiểm tra khoảng cách tối thiểu tới VWAP (0.35 ATR), giới hạn min/max stop, min gross target, min R:R rồi mới gửi lệnh strategy.entry kèm strategy.exit.
  5. Quản trị vị thế sau khi khớp lệnh: Ở nến tiếp theo sau khi khớp lệnh (strategy.position_avg_price), bot kiểm tra validFill (nếu khớp lệnh bị lệch làm SL/TP không hợp lệ sẽ đóng ngay bằng INVALID NEXT-BAR FILL), theo dõi tùy chọn Break Even, đếm số nến đóng cửa bất lợi vượt 2.00 ATR (VWAP REVERSION FAILED), kiểm tra thời gian giữ lệnh tối đa 40 phút (MAXIMUM HOLD EXIT) và đóng toàn bộ vị thế trước giờ nghỉ trưa/ATC (VN30F1M SESSION FLAT).

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

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

Lệnh Long (CNPS66-L) chỉ được gửi khi finalLong = true, tức đồng thời thỏa mãn toàn bộ các điều kiện sau:

  • Điều kiện chung: canEnter == true và longAllowed == true (tradeDirection != "Short" và chưa giao dịch Long trong ngày nếu bật oneTradePerDirection).
  • Tín hiệu rawLong: Xuất phát từ một trong hai trường hợp:
    1. Từ chối ngay tại nến cực trị mới (setupState == 0): newLowerExtreme (valueReady và low <= lowerExtreme và close < sessionVWAP), allowSameBarRejection == true, entryMode != "Later Band Reclaim", bullishRejection == true (close > open, bodyRatio >= 0.15, closeLocation >= 0.55, lowerWickShare >= 0.25) và close > close[1].
    2. Tín hiệu từ setupState == -1 (trong vòng <= 7 nến sau nến cực trị): Thỏa mãn reclaimedBand (close > lowerReclaim + 0.20, close > close[1], bullishConfirmation) khi entryMode != "Extreme Rejection", HOẶC anotherRejection (low <= lowerExtreme, bullishRejection, close > close[1]) khi entryMode != "Later Band Reclaim".
  • Bộ lọc Regime: not avoidLong (không có adx > 42.0 kèm mDI > pDI), volumeOK và rsiLongOK.
  • Khoảng cách tới VWAP: close <= sessionVWAP - 0.35 * atr (longDistanceOK).
  • Bộ lọc Rủi ro (longRiskOK): 1.50 <= longRisk <= 15.0, longReward >= 2.50 và longReward / longRisk >= 0.90.

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

Lệnh Short (CNPS66-S) chỉ được gửi khi finalShort = true (và not finalLong), đồng thời thỏa mãn:

  • Điều kiện chung: canEnter == true và shortAllowed == true (tradeDirection != "Long" và chưa giao dịch Short trong ngày nếu bật oneTradePerDirection).
  • Tín hiệu rawShort: Xuất phát từ một trong hai trường hợp:
    1. Từ chối ngay tại nến cực trị mới (setupState == 0): newUpperExtreme (valueReady và high >= upperExtreme và close > sessionVWAP), allowSameBarRejection == true, entryMode != "Later Band Reclaim", bearishRejection == true (close < open, bodyRatio >= 0.15, closeLocation <= 0.45, upperWickShare >= 0.25) và close < close[1].
    2. Tín hiệu từ setupState == 1 (trong vòng <= 7 nến sau nến cực trị): Thỏa mãn reclaimedBand (close < upperReclaim - 0.20, close < close[1], bearishConfirmation) khi entryMode != "Extreme Rejection", HOẶC anotherRejection (high >= upperExtreme, bearishRejection, close < close[1]) khi entryMode != "Later Band Reclaim".
  • Bộ lọc Regime: not avoidShort (không có adx > 42.0 kèm pDI > mDI), volumeOK và rsiShortOK.
  • Khoảng cách tới VWAP: close >= sessionVWAP + 0.35 * atr (shortDistanceOK).
  • Bộ lọc Rủi ro (shortRiskOK): 1.50 <= shortRisk <= 15.0, shortReward >= 2.50 và shortReward / shortRisk >= 0.90.

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

Biến canEnter kiểm soát toàn bộ quyền mở lệnh mới trên nến đóng cửa (barstate.isconfirmed):

  • Trạng thái phẳng: strategy.position_size == 0 (flat, pyramiding=0).
  • Khung giờ phiên VN30F1M: Nằm trong entrySession (09:15–11:20 phiên sáng hoặc 13:05–14:15 phiên chiều theo giờ Asia/Ho_Chi_Minh) và beforeCutoff (nến đóng trước 11:25 ở phiên sáng và trước 14:25 ở phiên chiều).
  • Giới hạn tần suất: tradesToday < 6, bar_index - lastExitBar > 2 (cooldown sau thoát lệnh) và bar_index - lastEntryBar >= 3 (khoảng cách giữa 2 lần vào lệnh).
  • Bảo vệ lỗ ngày (Daily Loss Guard): realizedDailyPnL > -2,400,000 VND.
  • Đóng vị thế cưỡng bức (Flat): Tự động strategy.close_all ở nến chạm mốc 11:25 (lunchFlatBar, nếu closeBeforeLunch = true) và nến chạm mốc 14:25 (finalFlatBar).

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

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

Bot hỗ trợ 3 chế độ tính Stop Loss ban đầu qua stopMode (làm tròn theo syminfo.mintick):

  1. ATR Fixed (mặc định): close - 1.35 * atr (Long) hoặc close + 1.35 * atr (Short).
  2. Extreme Structure: Dùng cực trị đã ghi nhận trong setup (signalExtreme, tức recordedLow / recordedHigh) cộng/trừ khoảng đệm 0.15 * atr.
  3. Recent Structure: Dùng ta.lowest(low, 4) (Long) hoặc ta.highest(high, 4) (Short) cộng/trừ khoảng đệm 0.15 * atr.

Trước khi vào lệnh, hệ thống kiểm tra chặt chẽ longRiskOK / shortRiskOK: khoảng dừng lỗ bắt buộc nằm trong [1.50, 15.0] điểm, mục tiêu lợi nhuận gộp tối thiểu 2.50 điểm, và tỷ lệ Reward/Risk tối thiểu 0.90.

5.2. Cơ chế Take Profit, Break Even và Thoát lệnh sớm

  • Take Profit (targetMode):
    • Fixed R (mặc định): close ± risk * 1.45.
    • VWAP Snapshot: Chốt lời tại mức sessionVWAP ngay thời điểm nến tín hiệu đóng cửa.
    • VWAP With Minimum R: Lấy giá trị xa hơn (có lợi hơn) giữa sessionVWAP và mức close ± risk * 0.90.
  • Break Even (useBreakEven, mặc định false): Khi bật, nếu lợi nhuận tính theo initialFillRisk đạt >= 1.00R, bot dời SL về fillPrice + 0.20 (Long) hoặc fillPrice - 0.20 (Short) và chỉ cập nhật theo hướng có lợi hơn (math.max / math.min).
  • Thoát lệnh khi hồi quy thất bại (useFailedReversionExit = true): Nếu giá đóng cửa đi ngược tiếp vượt quá sessionVWAP ∓ 2.00 * atr trong 2 nến liên tiếp (failureCloses = 2), bot chủ động đóng lệnh (VWAP REVERSION FAILED).
  • Giới hạn thời gian giữ lệnh (useTimeExit = true): Nếu thời gian đóng nến hiện tại time_close >= entryTimestamp + 40 * 60000 (40 phút), bot đóng lệnh (MAXIMUM HOLD EXIT).
  • Kiểm tra khớp lệnh nến kế tiếp (INVALID NEXT-BAR FILL): Nếu giá khớp thực tế ở nến sau làm initialFillRisk <= syminfo.mintick hoặc làm activeTarget không còn nằm đúng phía có lãi so với fillPrice, bot đóng ngay lập tức.

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

Cơ chế bảo vệTham số mặc địnhĐiều kiện kích hoạtNhãn / Comment thoát lệnh
Stop Loss cố định / cấu trúcATR Fixed (1.35 ATR)Giá chạm mức activeStopSL Long / SL Short
Take ProfitFixed R (1.45R)Giá chạm mức activeTargetTP Long / TP Short
Break Even (tùy chọn)false (1.00R, offset 0.20)Đạt 1.00R, giá quay lại chạm mức hòa vốnBE Long / BE Short
Hồi quy thất bạitrue (2.00 ATR, 2 nến)2 nến liên tiếp đóng vượt VWAP ∓ 2.00 ATRVWAP REVERSION FAILED
Giới hạn thời gian giữ lệnhtrue (40 phút)Giữ vị thế quá 40 phútMAXIMUM HOLD EXIT
Khớp lệnh bất hợp lệLuôn bậtinitialFillRisk hoặc activeTarget sai phía khi khớpINVALID NEXT-BAR FILL
Đóng lệnh cuối phiên11:25 & 14:25Chạm giờ nghỉ trưa hoặc trước phiên ATCVN30F1M SESSION FLAT

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 (khuyến nghị khung 1m, 3m hoặc 5m chuẩn, không dùng Heikin Ashi).
  2. Mở tab Pine Editor ở phía dưới màn hình, xóa code mẫu mặc định và dán toàn bộ mã nguồn Pine Script v6 từ Mục 1 vào.
  3. Nhấn Save (Lưu), đặt tên tùy chọn (ví dụ: CNPS66 VWAP Elastic Reversion V1), sau đó nhấn Add to chart (Thêm vào biểu đồ).
  4. Vào biểu tượng bánh răng (Settings) của chiến lược để điều chỉnh các thông số theo nhu cầu (lưu ý mục Properties hoặc default_qty_value nếu muốn thay đổi khối lượng hợp đồng thực thi).

Cách đọc tín hiệu hiển thị trên biểu đồ (Lưu ý về Diagnostics Table)

Theo thiết kế nguyên bản trong mã nguồn (No diagnostic table / CLEAN PLOTS - NO DASHBOARD), Bot CNPS66 không vẽ bảng table.new nổi trên góc màn hình nhằm giữ biểu đồ VN30F1M thông thoáng tối đa. Thay vào đó, toàn bộ thông tin trực quan được hiển thị qua các đường plot và nhãn sau (tùy chỉnh trong nhóm 09 - Display):

  • Đường cam (Continuous-Session VWAP): Đường giá trị trung bình neo theo phiên liên tục, reset mỗi ngày.
  • Dải đỏ / xanh ngọc (Upper / Lower Elastic Extreme): Hai biên cực trị ±1.35 ATR tính từ VWAP (mặc định ẩn showBands = false, có thể bật để quan sát vùng quá độ).
  • Chấm tròn nhỏ (Lower / Upper Extreme Recorded): Đánh dấu cây nến kích hoạt trạng thái chờ đảo chiều (setupState = -1 hoặc 1), mặc định ẩn (showArmedMarkers = false).
  • Tam giác L (xanh ngọc) / S (đỏ): Tín hiệu vào lệnh Long / Short chính thức đã vượt qua toàn bộ bộ lọc.
  • Đường đỏ & xanh lá (Active Stop Loss / Active Take Profit): Mức SL và TP đang hiệu lực khi có vị thế mở. Để xem các chỉ số thống kê hiệu suất chi tiết (Net Profit, Win Rate, Profit Factor, Max Drawdown), bạn theo dõi trực tiếp tại tab Strategy Tester bên dưới biểu đồ.

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 TradingView App, Email hoặc Webhook khi Bot CNPS66 phát sinh tín hiệu:

  1. Nhấn vào nút Alert (biểu tượng đồng hồ báo thức) trên thanh công cụ TradingView.
  2. Tại mục Condition, chọn chiến lược CNPS66 VWAP ELASTIC REVERSION V1 - VN30F1M.
  3. Tại ô Message, xóa nội dung mặc định và điền chính xác cú pháp sau để TradingView truyền nguyên văn thông điệp động từ code: {{strategy.order.alert_message}}
  4. Đặt tên Alert và nhấn Create.

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

Sự kiệnĐiều kiện / Hàm kích hoạtNội dung thông điệp (alert_message / alert_profit / alert_loss)
Vào lệnh Longstrategy.entry("CNPS66-L", ...)🟢 VÀO VỊ THẾ LONG (VWAP Elastic Reversion) kèm Giá vào, SL dự kiến, TP dự kiến
Vào lệnh Shortstrategy.entry("CNPS66-S", ...)🔴 VÀO VỊ THẾ SHORT (VWAP Elastic Reversion) kèm Giá vào, SL dự kiến, TP dự kiến
Chốt lời Long / Shortalert_profit trên CNPS66-L-X / CNPS66-S-X💰 CHỐT LỜI LONG (TP HIT) / 💰 CHỐT LỜI SHORT (TP HIT) kèm Giá chốt
Cắt lỗ Long / Shortalert_loss (khi breakEvenActive == false)🛑 CẮT LỖ LONG (SL HIT) / 🛑 CẮT LỖ SHORT (SL HIT) kèm Giá cắt
Hòa vốn Long / Shortalert_loss (khi breakEvenActive == true)🛡️ HÒA VỐN LONG (BE HIT) / 🛡️ HÒA VỐN SHORT (BE HIT) kèm Giá thoát
Hồi quy thất bạistrategy.close(..., "VWAP REVERSION FAILED")⚡ ĐÓNG VỊ THẾ (Hồi quy VWAP thất bại) kèm Giá đóng
Hết thời gian giữ lệnhstrategy.close(..., "MAXIMUM HOLD EXIT")⏱️ ĐÓNG VỊ THẾ (Hết thời gian giữ lệnh tối đa) kèm Giá đóng
Khớp lệnh bất hợp lệstrategy.close(..., "INVALID NEXT-BAR FILL")🔄 ĐÓNG VỊ THẾ (Khớp lệnh không hợp lệ) kèm Giá đóng
Đóng hết phiênstrategy.close_all(..., "VN30F1M SESSION FLAT")⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End) kèm Giá đóng

Kết luận

Bot CNPS66 (VWAP Elastic Reversion V1) là một công cụ giao dịch đảo chiều trong ngày được thiết kế kỷ luật cho VN30F1M, kết hợp giữa định giá theo Session VWAP, biên độ co giãn ATR, hai lộ trình xác nhận nến từ chối/tái chiếm và hàng rào bảo vệ đa lớp (Strong Trend Guard, Failed Reversion Exit, Time Exit, Daily Loss Guard, Session Flat). Chiến lược phát huy hiệu quả tốt nhất trong các phiên thị trường dao động hai chiều hoặc có các nhịp rũ bỏ/kéo rướn quá đà quanh vùng giá trị trung bình, đồng thời biết tự đứng ngoài khi xu hướng một chiều quá mạnh (ADX > 42).

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

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