Hướng Dẫn Sử Dụng Bot CNPS66 - VWAP Elastic Reversion V1 cho VN30F1M
Tradingview
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ụngADX(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
Rhoặc theoSession 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ưỡng2.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:
- 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:30và chiều13:00–14:30), kết hợp vớiATR(14)để tạo ra dải cực trị (±1.35 ATR) và dải tái chiếm (±0.95 ATR). - 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 đa7nến chờ tái chiếm. - 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ướngADX(bật mặc định) và tùy chọnRSI/RVOL. - 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/Riskngay trước khi gửi lệnh; đồng thời kiểm soát khung giờ vào lệnh (09:15–11:20và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 code | Giá trị mặc định | Mô tả chức năng |
|---|---|---|---|
| 01 - Trade Control | tradeDirection | "Both" | Hướng giao dịch cho phép (Both, Long, Short) |
contracts | 3 | Số hợp đồng cấu hình ở Input (strategy() mặc định default_qty_value=1) | |
maximumTradesPerDay | 6 | Số lệnh tối đa mỗi ngày | |
cooldownBars | 2 | Số nến nghỉ tối thiểu sau khi đóng lệnh | |
minimumEntrySpacing | 3 | Khoảng cách nến tối thiểu giữa 2 lần vào lệnh | |
oneTradePerDirection | false | Giới hạn tối đa 1 lệnh mỗi chiều/ngày | |
| 02 - VWAP Deviation | atrPeriod | 14 | Chu kỳ tính chỉ báo ATR |
extremeBandATR | 1.35 | Biên độ dải cực trị tính từ VWAP (theo ATR) | |
reclaimBandATR | 0.95 | Biên độ dải tái chiếm tính từ VWAP (theo ATR) | |
minimumEntryDistanceATR | 0.35 | Khoảng cách tối thiểu từ giá vào tới VWAP (theo ATR) | |
minimumSessionBars | 5 | Số nến tối thiểu sau 09:00 để kích hoạt tín hiệu | |
| 03 - Reversal Entry | entryMode | "Active Hybrid" | Chế độ vào lệnh (Active Hybrid, Extreme Rejection, Later Band Reclaim) |
maximumReclaimBars | 7 | Số nến tối đa chờ tín hiệu tái chiếm sau khi tạo cực trị | |
minimumRejectionWick | 0.25 | Tỷ lệ râu nến từ chối tối thiểu trên biên độ nến | |
minimumCandleBody | 0.15 | Tỷ lệ thân nến tối thiểu trên biên độ nến | |
minimumCloseLocation | 0.55 | Vị trí giá đóng cửa tối thiểu theo chiều đảo chiều | |
minimumRecoveryPoints | 0.20 | Khoảng đệm vượt dải Reclaim khi tái chiếm (điểm) | |
allowSameBarRejection | true | Cho phép vào lệnh ngay tại nến tạo cực trị | |
| 04 - Market Regime | useStrongTrendGuard | true | Bật bộ lọc chặn bắt đỉnh/đáy khi ADX quá cao |
strongTrendADX | 42.0 | Ngưỡng ADX xác định xu hướng rất mạnh | |
useRSIFilter | false | Bật bộ lọc RSI ngắn hạn | |
rsiPeriod / longRSIMaximum / shortRSIMinimum | 7 / 52.0 / 48.0 | Chu kỳ và ngưỡng RSI cho Long/Short | |
useRVOLFilter / volumeBaseline / minimumRVOL | false / 25 / 0.70 | Bộ lọc khối lượng tương đối so với SMA(25) | |
| 05 - Risk | stopMode | "ATR Fixed" | Phương pháp đặt SL (ATR Fixed, Extreme Structure, Recent Structure) |
fixedStopATR | 1.35 | Khoảng SL cố định theo ATR | |
stopLookback / stopBufferATR | 4 / 0.15 | Số nến cấu trúc gần nhất và khoảng đệm ATR | |
minimumStopPoints / maximumStopPoints | 1.50 / 15.0 | Giới hạn rủi ro SL tối thiểu và tối đa (điểm) | |
targetMode / takeProfitR | "Fixed R" / 1.45 | Phương pháp đặt TP (Fixed R, VWAP Snapshot, VWAP With Minimum R) | |
minimumVWAPTargetR / minimumGrossTarget | 0.90 / 2.50 | Tỷ lệ R:R tối thiểu và mục tiêu điểm gộp tối thiểu | |
| 06 - Exits | useBreakEven / breakEvenAtR / breakEvenOffset | false / 1.00 / 0.20 | Cơ chế dời SL về hòa vốn + offset |
useFailedReversionExit / failureBandATR / failureCloses | true / 2.00 / 2 | Thoá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 / maximumHoldMinutes | true / 40 | Thoát lệnh nếu giữ quá 40 phút | |
| 07 - Protection | useDailyLossGuard / maximumDailyLossVND | true / 2400000 | Khóa vào lệnh mới khi lỗ đã chốt trong ngày >= 2.400.000 VND |
| 08 - Trading Session | morningEntry / afternoonEntry | "0915-1120" / "1305-1415" | Khung giờ cho phép tìm điểm vào lệnh |
closeBeforeLunch / lunchFlatMinute | true / 25 | Đóng toàn bộ vị thế trước giờ nghỉ trưa lúc 11:25 | |
finalFlatHour / finalFlatMinute | 14 / 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 <= 0hoặcna, code tự thay bằng1.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ồnhlc3 * barVolume. - Từ
sessionVWAPvà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 * atrvàlowerExtreme = sessionVWAP - 1.35 * atr. - Dải tái chiếm (Reclaim Bands):
upperReclaim = sessionVWAP + 0.95 * atrvàlowerReclaim = sessionVWAP - 0.95 * atr.
- Dải cực trị (Extreme Bands):
- Dữ liệu chỉ hợp lệ (
valueReady) khi đang trong phiên liên tục, đã qua ít nhấtminimumSessionBars = 5nến sau09:00,sessionVWAPvà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) / candleRangevà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ếuadx > 42.0vàmDI > pDI,avoidLong = true(cấm Long khi xu hướng giảm quá mạnh). Ngược lại, nếuadx > 42.0và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ầursi <= 52.0cho Long vàrsi >= 48.0cho Short nếu được bật. - RVOL Filter (tắt mặc định): So sánh
volumenến tín hiệu vớita.sma(volume, 25)[1], yêu cầuentryRVOL >= 0.70nế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):
- Khởi tạo phiên và đếm ngưỡng an toàn: Khi sang ngày mới (
newTradingDay), bot reset VWAP, bộ đếmtradesToday,longTradedToday,shortTradedToday, và ghi nhậndayStartingNetProfit. Nếu chuyển giao phiên (morningStarts,afternoonStarts,lunchFlatBar,finalFlatBar), máy trạng tháisetupStatecũng được reset về0. - Phát hiện độ lệch cực trị (
setupState = -1hoặc1): KhisetupState == 0vàcanEnterthỏa mãn, nếu giá chọc thủnglowerExtremenhưng đóng cửa vẫn dướisessionVWAP, bot chuyển sangsetupState := -1và lưurecordedLow := low. Tương tự vớiupperExtremeđể chuyển sangsetupState := 1và lưurecordedHigh := high. - Kích hoạt tín hiệu theo 1 trong 2 lộ trình:
- Nếu
allowSameBarRejection = truevà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ặcclose < close[1]) hay không. - Nếu chưa vào ngay, ở các nến kế tiếp (tối đa
maximumReclaimBars = 7nến), bot tiếp tục cập nhậtrecordedLow/recordedHighvà 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ạmsessionVWAPtrước khi có tín hiệu, setup bị hủy (setupState := 0).
- Nếu
- Kiểm tra khoảng cách, Risk/Reward và gửi lệnh: Khi có
rawLonghoặcrawShort, bot tínhcandidateStop,candidateTarget, kiểm tra khoảng cách tối thiểu tới VWAP (0.35 ATR), giới hạnmin/max stop,min gross target,min R:Rrồi mới gửi lệnhstrategy.entrykèmstrategy.exit. - 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 travalidFill(nếu khớp lệnh bị lệch làm SL/TP không hợp lệ sẽ đóng ngay bằngINVALID NEXT-BAR FILL), theo dõi tùy chọn Break Even, đếm số nến đóng cửa bất lợi vượt2.00 ATR(VWAP REVERSION FAILED), kiểm tra thời gian giữ lệnh tối đa40phú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 == truevàlongAllowed == true(tradeDirection != "Short"và chưa giao dịch Long trong ngày nếu bậtoneTradePerDirection). - Tín hiệu
rawLong: Xuất phát từ một trong hai trường hợp:- Từ chối ngay tại nến cực trị mới (
setupState == 0):newLowerExtreme(valueReadyvàlow <= lowerExtremevà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]. - Tín hiệu từ
setupState == -1(trong vòng<= 7nến sau nến cực trị): Thỏa mãnreclaimedBand(close > lowerReclaim + 0.20,close > close[1],bullishConfirmation) khientryMode != "Extreme Rejection", HOẶCanotherRejection(low <= lowerExtreme,bullishRejection,close > close[1]) khientryMode != "Later Band Reclaim".
- Từ chối ngay tại nến cực trị mới (
- Bộ lọc Regime:
not avoidLong(không cóadx > 42.0kèmmDI > pDI),volumeOKvà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.50và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 == truevàshortAllowed == true(tradeDirection != "Long"và chưa giao dịch Short trong ngày nếu bậtoneTradePerDirection). - Tín hiệu
rawShort: Xuất phát từ một trong hai trường hợp:- Từ chối ngay tại nến cực trị mới (
setupState == 0):newUpperExtreme(valueReadyvàhigh >= upperExtremevà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]. - Tín hiệu từ
setupState == 1(trong vòng<= 7nến sau nến cực trị): Thỏa mãnreclaimedBand(close < upperReclaim - 0.20,close < close[1],bearishConfirmation) khientryMode != "Extreme Rejection", HOẶCanotherRejection(high >= upperExtreme,bearishRejection,close < close[1]) khientryMode != "Later Band Reclaim".
- Từ chối ngay tại nến cực trị mới (
- Bộ lọc Regime:
not avoidShort(không cóadx > 42.0kèmpDI > mDI),volumeOKvà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.50và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:20phiên sáng hoặc13:05–14:15phiên chiều theo giờAsia/Ho_Chi_Minh) vàbeforeCutoff(nến đóng trước11:25ở phiên sáng và trước14: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ự độngstrategy.close_allở nến chạm mốc11:25(lunchFlatBar, nếucloseBeforeLunch = true) và nến chạm mốc14: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):
ATR Fixed(mặc định):close - 1.35 * atr(Long) hoặcclose + 1.35 * atr(Short).Extreme Structure: Dùng cực trị đã ghi nhận trong setup (signalExtreme, tứcrecordedLow/recordedHigh) cộng/trừ khoảng đệm0.15 * atr.Recent Structure: Dùngta.lowest(low, 4)(Long) hoặcta.highest(high, 4)(Short) cộng/trừ khoảng đệm0.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ứcsessionVWAPngay 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ữasessionVWAPvà mứcclose ± risk * 0.90.
- Break Even (
useBreakEven, mặc địnhfalse): Khi bật, nếu lợi nhuận tính theoinitialFillRiskđạt>= 1.00R, bot dời SL vềfillPrice + 0.20(Long) hoặcfillPrice - 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 * atrtrong2nế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ạitime_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àminitialFillRisk <= syminfo.mintickhoặc làmactiveTargetkhông còn nằm đúng phía có lãi so vớifillPrice, 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ạt | Nhãn / Comment thoát lệnh |
|---|---|---|---|
| Stop Loss cố định / cấu trúc | ATR Fixed (1.35 ATR) | Giá chạm mức activeStop | SL Long / SL Short |
| Take Profit | Fixed R (1.45R) | Giá chạm mức activeTarget | TP 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ốn | BE Long / BE Short |
| Hồi quy thất bại | true (2.00 ATR, 2 nến) | 2 nến liên tiếp đóng vượt VWAP ∓ 2.00 ATR | VWAP REVERSION FAILED |
| Giới hạn thời gian giữ lệnh | true (40 phút) | Giữ vị thế quá 40 phút | MAXIMUM HOLD EXIT |
| Khớp lệnh bất hợp lệ | Luôn bật | initialFillRisk hoặc activeTarget sai phía khi khớp | INVALID NEXT-BAR FILL |
| Đóng lệnh cuối phiên | 11:25 & 14:25 | Chạm giờ nghỉ trưa hoặc trước phiên ATC | VN30F1M 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
- Mở biểu đồ hợp đồng tương lai VN30F1M trên TradingView (khuyến nghị khung
1m,3mhoặc5mchuẩn, không dùng Heikin Ashi). - 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.
- 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 đồ). - 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
Propertieshoặcdefault_qty_valuenế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 ATRtính từ VWAP (mặc định ẩnshowBands = 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 = -1hoặc1), 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:
- Nhấn vào nút Alert (biểu tượng đồng hồ báo thức) trên thanh công cụ TradingView.
- Tại mục Condition, chọn chiến lược
CNPS66 VWAP ELASTIC REVERSION V1 - VN30F1M. - 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}} - Đặ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ạt | Nội dung thông điệp (alert_message / alert_profit / alert_loss) |
|---|---|---|
| Vào lệnh Long | strategy.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 Short | strategy.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 / Short | alert_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 / Short | alert_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 / Short | alert_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ại | strategy.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ệnh | strategy.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ên | strategy.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.





