Hướng Dẫn Sử Dụng Bot CNPS51 - VWAP MEAN REVERSION V4 cho VN30F1M
TradingviewHướng dẫn sử dụng Bot CNPS51 VWAP Mean Reversion V4 cho VN30F1M trên TradingView: cơ chế Arm & Reclaim theo VWAP Sigma Bands, 4 Profile, bộ lọc Directional Guard và full source code Pine Script v6.

Mục lục
Trong giao dịch chứng khoán phái sinh VN30F1M trong ngày, giá thường có xu hướng bị kéo giãn quá mức khỏi vùng giá trị hợp lý rồi mới quay đầu hồi quy về mức trung bình (Mean Reversion). Tuy nhiên, nếu bắt đáy hoặc bắt đỉnh ngay khi giá vừa chạm biên ngoài, nhà đầu tư rất dễ bị “bắt dao rơi” khi thị trường đang có xu hướng mạnh. Ngược lại, nếu đặt bộ lọc quá chặt, chiến lược sẽ có rất ít lệnh để kiểm chứng.
CNPS51 VWAP MEAN REVERSION V4 được xây dựng bằng Pine Script v6 trên TradingView nhằm giải quyết bài toán cân bằng giữa tần suất giao dịch và độ an toàn:
- Đo độ lệch theo khối lượng (Session VWAP + Sigma Bands): Xác định vùng giá quá giãn dựa trên VWAP nội phiên Việt Nam.
- Cơ chế vào lệnh 2 bước (Arm & Reclaim): Chỉ ghi nhận Setup khi giá chạm dải ngoài (Outer Band), sau đó kiên nhẫn chờ giá hồi lại vào trong dải trong (Inner Band) kèm nến xác nhận mới vào lệnh hướng về VWAP.
- Bộ lọc Regime thông minh (Directional Guard): Chỉ chặn lệnh ngược xu hướng mạnh, giúp tăng tần suất giao dịch mà vẫn tránh được các phiên chạy một chiều.
- 4 Profile cài đặt sẵn: Cho phép chuyển đổi nhanh giữa
Strict,Balanced,ActivevàManual.
Bài viết dưới đây sẽ hướng dẫn chi tiết nguyên lý hoạt động, bộ thông số, mã nguồn đầy đủ và cách thiết lập cảnh báo (Alert) cho Bot CNPS51 V4 trên VN30F1M.
1. CNPS51 VWAP Mean Reversion V4 là gì?
CNPS51 V4 là chiến lược giao dịch đảo chiều về giá trị trung bình (Mean Reversion) thiết kế riêng cho khung giờ giao dịch của hợp đồng tương lai VN30F1M. Chiến lược gồm 4 thành phần chính:
- VN Session VWAP & Volume-Weighted Sigma: Tự động reset đầu ngày, chỉ tích lũy dữ liệu trong phiên sáng (
09:00–11:30) và phiên chiều (13:00–14:45). - Hệ thống Profile 4 chế độ: Tùy biến độ nhạy tín hiệu (
Strict,Balanced,Active,Manual) chỉ với một lựa chọn. - Market Regime Filter: Kết hợp
ADX(14),EMA(20/50)và độ dốc VWAP để bảo vệ tài khoản trước các nhịp sóng trend mạnh. - Quản trị lệnh khép kín: Đặt Stop Loss theo cực trị kéo giãn (
stretchLow/stretchHigh), chốt lời tại VWAP, tự đóng lệnh nếu dính Gap bất lợi, giới hạn thời gian giữ lệnh (60 nến) và đóng toàn bộ cuối phiên lúc14:45.
Bảng thông số mặc định (Profile Balanced)
| Nhóm | Thông số | Giá trị mặc định (Balanced) |
|---|---|---|
| Profile | Chế độ mặc định | Balanced |
| VWAP Bands | Outer Sigma / Inner Sigma | 1.60 / 0.90 |
| VWAP Setup | Warmup / Setup Lifetime | 10 nến / 10 nến |
| Nến xác nhận | Min Body Ratio | 0.15 |
| Regime Filter | Chế độ / ADX Threshold / Slope Lookback | Directional guard / 30 / 5 nến |
| Quản trị lệnh | Khối lượng mặc định / Tối đa lệnh ngày / Cooldown | 1 HĐ / 5 lệnh / 3 nến |
| Rủi ro (Risk) | Min–Max Risk / Stop Buffer | 1.5–12.0 điểm / 1 tick |
| Mục tiêu (TP) | Target Mode / Min Reward / Min R:R | VWAP / 1.5 điểm / 0.35 |
| Thoát lệnh | Time Exit (Max Hold) / Force Close | 60 nến / 14:45 |
Source Code CNPS51 VWAP Mean Reversion V4
Bạn có thể sao chép toàn bộ mã nguồn Pine Script v6 dưới đây để dán trực tiếp vào Pine Editor trên TradingView:
//@version=6
strategy(
title="CNPS51 VWAP MEAN REVERSION V4 - VN30F1M",
shorttitle="CNPS51 VWAP MR V4",
overlay=true,
initial_capital=100000000,
currency=currency.VND,
default_qty_type=strategy.fixed,
default_qty_value=1,
pyramiding=0,
margin_long=0,
margin_short=0,
commission_type=strategy.commission.cash_per_contract,
commission_value=0,
slippage=0,
fill_orders_on_standard_ohlc=true,
process_orders_on_close=false,
calc_on_order_fills=false,
calc_on_every_tick=false,
max_bars_back=5000
)
// ============================================================================
// CNPS51 V4 - VN30F1M | Controlled increase in trade frequency
// STRYK source idea: reach outer VWAP sigma -> reclaim inner sigma -> VWAP TP.
// V4 adds three test presets, optional regime guard, and signal diagnostics.
// V4 is a modified research strategy, NOT the exact STRYK implementation.
// ============================================================================
// 1. PRESET ENGINE
string G1 = "01 - STRATEGY PROFILE"
profile = input.string("Balanced", "Profile", options=["Strict", "Balanced", "Active", "Manual"], group=G1)
manualOuter = input.float(1.60, "Manual: Outer sigma", minval=1.0, maxval=4.0, step=0.05, group=G1)
manualInner = input.float(0.90, "Manual: Inner sigma", minval=0.2, maxval=2.0, step=0.05, group=G1)
manualWarmup = input.int(10, "Manual: VWAP warmup bars", minval=3, maxval=100, group=G1)
manualLifetime = input.int(10, "Manual: Setup lifetime bars", minval=1, maxval=100, group=G1)
manualBody = input.float(0.15, "Manual: Min candle body ratio", minval=0, maxval=1, step=0.05, group=G1)
manualRiskMin = input.float(1.5, "Manual: Min risk (points)", minval=0.1, step=0.5, group=G1)
manualRiskMax = input.float(12.0, "Manual: Max risk (points)", minval=0.5, step=0.5, group=G1)
manualReward = input.float(1.5, "Manual: Min VWAP reward (points)", minval=0.1, step=0.5, group=G1)
manualRR = input.float(0.35, "Manual: Min reward / risk", minval=0.1, step=0.05, group=G1)
manualTrades = input.int(5, "Manual: Max entries/day", minval=1, maxval=20, group=G1)
manualCooldown = input.int(3, "Manual: Cooldown after exit", minval=0, maxval=100, group=G1)
float outerMult = profile == "Strict" ? 2.0 : profile == "Balanced" ? 1.6 : profile == "Active" ? 1.4 : manualOuter
float innerMult = profile == "Strict" ? 1.0 : profile == "Balanced" ? 0.9 : profile == "Active" ? 0.75 : manualInner
int warmup = profile == "Strict" ? 20 : profile == "Balanced" ? 10 : profile == "Active" ? 6 : manualWarmup
int lifetime = profile == "Strict" ? 6 : profile == "Balanced" ? 10 : profile == "Active" ? 12 : manualLifetime
float bodyMin = profile == "Strict" ? 0.30 : profile == "Balanced" ? 0.15 : profile == "Active" ? 0.05 : manualBody
float riskMin = profile == "Strict" ? 2.0 : profile == "Balanced\" ? 1.5 : profile == \"Active\" ? 1.0 : manualRiskMin
float riskMax = profile == "Strict" ? 8.0 : profile == "Balanced" ? 12.0 : profile == "Active" ? 16.0 : manualRiskMax
float rewardMin = profile == "Strict" ? 3.0 : profile == "Balanced" ? 1.5 : profile == "Active" ? 1.0 : manualReward
float rrMin = profile == "Strict" ? 0.70 : profile == "Balanced" ? 0.35 : profile == "Active" ? 0.20 : manualRR
int maxTrades = profile == "Strict" ? 2 : profile == "Balanced" ? 5 : profile == "Active" ? 8 : manualTrades
int cooldown = profile == "Strict" ? 8 : profile == "Balanced" ? 3 : profile == "Active" ? 1 : manualCooldown
bool requireCross = profile == "Strict"
int minWait = profile == "Strict" ? 1 : 0
// 2. VWAP SOURCE, REGIME, TRADE SETTINGS
string G2 = "02 - VWAP / MARKET REGIME"
priceSource = input.source(hlc3, "VWAP price source", group=G2)
regimeMode = input.string("Directional guard", "Regime filter", options=["Directional guard", "Strict range", "Off"], group=G2)
adxLen = input.int(14, "ADX length", minval=2, group=G2)
maxADX = input.float(30.0, "Guard ADX threshold", minval=5, maxval=60, step=1, group=G2)
slopeLookback = input.int(5, "VWAP slope lookback", minval=1, maxval=30, group=G2)
strictSlopeATR = input.float(0.65, "Strict: Max VWAP slope / ATR", minval=0.05, step=0.05, group=G2)
strictEMAGapATR = input.float(1.00, "Strict: Max EMA20/50 gap / ATR", minval=0.05, step=0.05, group=G2)
string G3 = "03 - TRADING / EXITS"
tradeDirection = input.string("Both", "Trade Direction", options=["Both", "Long", "Short"], group=G3)
contracts = input.int(3, "Contracts", minval=1, maxval=20, group=G3)
stopTicks = input.int(1, "Stop buffer (ticks)", minval=0, maxval=30, group=G3)
targetMode = input.string("VWAP", "Take Profit", options=["VWAP", "Opposite inner band", "Fixed R"], group=G3)
fixedR = input.float(1.50, "Fixed R TP (if selected)", minval=0.25, maxval=10, step=0.25, group=G3)
useTimeout = input.bool(true, "Time exit", group=G3)
maxHold = input.int(60, "Maximum bars held", minval=1, maxval=500, group=G3)
// 3. VIETNAM SESSION
string G4 = "04 - VN30F1M SESSION"
string TZ = "Asia/Ho_Chi_Minh"
morningEntry = input.session("0905-1125", "Morning Entry", group=G4)
afternoonEntry = input.session("1305-1425", "Afternoon Entry", group=G4)
morningVWAP = input.session("0900-1130", "Morning VWAP", group=G4)
afternoonVWAP = input.session("1300-1445", "Afternoon VWAP", group=G4)
forceCloseHour = input.int(14, "Force Close Hour", minval=0, maxval=23, group=G4)
forceCloseMinute = input.int(45, "Force Close Minute", minval=0, maxval=59, group=G4)
string G5 = "05 - VISUALS / DEBUG"
showBands = input.bool(true, "Show VWAP bands", group=G5)
showSignals = input.bool(true, "Show entry markers", group=G5)
showLevels = input.bool(true, "Show active SL/TP", group=G5)
showDiagnostics = input.bool(true, "Show signal funnel", group=G5)
// 4. SESSION VWAP + VOLUME WEIGHTED SIGMA
bool inAM = not na(time(timeframe.period, morningVWAP + ":23456", TZ))
bool inPM = not na(time(timeframe.period, afternoonVWAP + ":23456", TZ))
bool inVWAP = inAM or inPM
bool inEntry = not na(time(timeframe.period, morningEntry + ":23456", TZ)) or not na(time(timeframe.period, afternoonEntry + ":23456", TZ))
int vnDay = year(time, TZ) * 10000 + month(time, TZ) * 100 + dayofmonth(time, TZ)
var int anchorDay = na
var float volumeSum = 0.0
var float pvSum = 0.0
var float p2vSum = 0.0
var int barsAccumulated = 0
bool firstTradingBar = inVWAP and (na(anchorDay) or anchorDay != vnDay)
if firstTradingBar
anchorDay := vnDay
if inVWAP
float v = math.max(nz(volume), 0.0)
volumeSum := (firstTradingBar ? 0.0 : nz(volumeSum[1], 0.0)) + v
pvSum := (firstTradingBar ? 0.0 : nz(pvSum[1], 0.0)) + priceSource * v
p2vSum := (firstTradingBar ? 0.0 : nz(p2vSum[1], 0.0)) + priceSource * priceSource * v
barsAccumulated := (firstTradingBar ? 0 : nz(barsAccumulated[1], 0)) + (v > 0 ? 1 : 0)
else
volumeSum := nz(volumeSum[1], 0.0)
pvSum := nz(pvSum[1], 0.0)
p2vSum := nz(p2vSum[1], 0.0)
barsAccumulated := nz(barsAccumulated[1], 0)
float sessionVWAP = volumeSum > 0 ? pvSum / volumeSum : na
float stdev = volumeSum > 0 ? math.sqrt(math.max(0.0, p2vSum / volumeSum - sessionVWAP * sessionVWAP)) : na
float upperInner = sessionVWAP + stdev * innerMult
float lowerInner = sessionVWAP - stdev * innerMult
float upperOuter = sessionVWAP + stdev * outerMult
float lowerOuter = sessionVWAP - stdev * outerMult
bool ready = inVWAP and barsAccumulated >= warmup and not na(stdev) and stdev > syminfo.mintick and innerMult < outerMult
plot(inVWAP ? sessionVWAP : na, "VN Session VWAP", color=color.orange, linewidth=2, style=plot.style_linebr)
plot(showBands and ready ? upperInner : na, "+Inner", color=color.new(color.gray, 30), style=plot.style_linebr)
plot(showBands and ready ? lowerInner : na, "-Inner", color=color.new(color.gray, 30), style=plot.style_linebr)
plot(showBands and ready ? upperOuter : na, "+Outer", color=color.new(color.red, 65), style=plot.style_linebr)
plot(showBands and ready ? lowerOuter : na, "-Outer", color=color.new(color.teal, 65), style=plot.style_linebr)
// 5. TREND GUARD: ONLY BLOCK STRONG TREND AGAINST ENTRY DIRECTION
[diPlus, diMinus, adx] = ta.dmi(adxLen, adxLen)
float ema20 = ta.ema(close, 20)
float ema50 = ta.ema(close, 50)
float atr = ta.atr(14)
float slope = not na(sessionVWAP[slopeLookback]) ? (sessionVWAP - sessionVWAP[slopeLookback]) / math.max(atr, syminfo.mintick) : na
float emaGap = math.abs(ema20 - ema50) / math.max(atr, syminfo.mintick)
bool strictRangeOK = not na(adx) and not na(slope) and adx <= maxADX and math.abs(slope) <= strictSlopeATR and emaGap <= strictEMAGapATR
bool dangerousLong = not na(adx) and not na(slope) and adx > maxADX and ema20 < ema50 and slope < 0
bool dangerousShort = not na(adx) and not na(slope) and adx > maxADX and ema20 > ema50 and slope > 0
bool longRegimeOK = regimeMode == "Off" ? true : regimeMode == "Strict range" ? strictRangeOK : not dangerousLong
bool shortRegimeOK = regimeMode == "Off" ? true : regimeMode == "Strict range" ? strictRangeOK : not dangerousShort
// 6. STATE & DEBUG COUNTERS
var bool armedLong = false
var bool armedShort = false
var int longTouchBar = na
var int shortTouchBar = na
var float stretchLow = na
var float stretchHigh = na
var int tradesToday = 0
var int closedSeen = 0
var int lastExitBar = na
var int lastSubmittedBar = na
var int totalTouches = 0
var int totalRaw = 0
var int rejectedQuality = 0
var int rejectedRegime = 0
var int rejectedRisk = 0
var int rejectedReward = 0
var int rejectedOther = 0
var int totalOrders = 0
var float activeStop = na
var float activeTarget = na
bool pmOpening = inPM and not inPM[1]
if firstTradingBar
tradesToday := 0
lastExitBar := na
if firstTradingBar or pmOpening
armedLong := false
armedShort := false
longTouchBar := na
shortTouchBar := na
stretchLow := na
stretchHigh := na
if strategy.closedtrades > closedSeen
closedSeen := strategy.closedtrades
lastExitBar := bar_index
// 7. ARM AT OUTER BAND; HOLD SETUP UNTIL RECLAIM / EXPIRY
if ready and barstate.isconfirmed
if armedLong
stretchLow := math.min(nz(stretchLow, low), low)
if bar_index - longTouchBar > lifetime or close >= sessionVWAP
armedLong := false
stretchLow := na
longTouchBar := na
if armedShort
stretchHigh := math.max(nz(stretchHigh, high), high)
if bar_index - shortTouchBar > lifetime or close <= sessionVWAP
armedShort := false
stretchHigh := na
shortTouchBar := na
bool touchLong = low <= lowerOuter and close < sessionVWAP
bool touchShort = high >= upperOuter and close > sessionVWAP
if touchLong and not touchShort
stretchLow := armedLong and not na(stretchLow) ? math.min(stretchLow, low) : low
armedLong := true
longTouchBar := bar_index
armedShort := false
shortTouchBar := na
stretchHigh := na
totalTouches += 1
else if touchShort and not touchLong
stretchHigh := armedShort and not na(stretchHigh) ? math.max(stretchHigh, high) : high
armedShort := true
shortTouchBar := bar_index
armedLong := false
longTouchBar := na
stretchLow := na
totalTouches += 1
// 8. RECLAIM TRIGGER, STRUCTURAL STOP, VWAP-BASED TARGET
float bodyRatio = math.abs(close - open) / math.max(high - low, syminfo.mintick)
bool bullCandle = close > open and bodyRatio >= bodyMin
bool bearCandle = close < open and bodyRatio >= bodyMin
bool priorBelow = not na(lowerInner[1]) and close[1] <= lowerInner[1]
bool priorAbove = not na(upperInner[1]) and close[1] >= upperInner[1]
bool longReclaim = ready and armedLong and bar_index - longTouchBar >= minWait and close > lowerInner and close < sessionVWAP and (not requireCross or priorBelow)
bool shortReclaim = ready and armedShort and bar_index - shortTouchBar >= minWait and close < upperInner and close > sessionVWAP and (not requireCross or priorAbove)
float longStop = not na(stretchLow) ? stretchLow - stopTicks * syminfo.mintick : na
float shortStop = not na(stretchHigh) ? stretchHigh + stopTicks * syminfo.mintick : na
float longRisk = close - longStop
float shortRisk = shortStop - close
float longTarget = targetMode == "VWAP" ? sessionVWAP : targetMode == "Opposite inner band" ? upperInner : close + longRisk * fixedR
float shortTarget = targetMode == "VWAP" ? sessionVWAP : targetMode == "Opposite inner band" ? lowerInner : close - shortRisk * fixedR
float longReward = longTarget - close
float shortReward = close - shortTarget
bool longRiskOK = not na(longRisk) and longRisk >= riskMin and longRisk <= riskMax
bool shortRiskOK = not na(shortRisk) and shortRisk >= riskMin and shortRisk <= riskMax
bool longRewardOK = not na(longReward) and longReward >= rewardMin and longReward / math.max(longRisk, syminfo.mintick) >= rrMin
bool shortRewardOK = not na(shortReward) and shortReward >= rewardMin and shortReward / math.max(shortRisk, syminfo.mintick) >= rrMin
bool cooldownOK = na(lastExitBar) or bar_index - lastExitBar > cooldown
bool capacityOK = tradesToday < maxTrades
bool commonOK = barstate.isconfirmed and strategy.position_size == 0 and inEntry and cooldownOK and capacityOK and (na(lastSubmittedBar) or lastSubmittedBar != bar_index)
bool allowLong = tradeDirection != "Short"
bool allowShort = tradeDirection != "Long"
bool rawLong = barstate.isconfirmed and longReclaim and allowLong
bool rawShort = barstate.isconfirmed and shortReclaim and allowShort
if rawLong or rawShort
totalRaw += 1
if (rawLong and not bullCandle) or (rawShort and not bearCandle)
rejectedQuality += 1
else if (rawLong and not longRegimeOK) or (rawShort and not shortRegimeOK)
rejectedRegime += 1
else if (rawLong and not longRiskOK) or (rawShort and not shortRiskOK)
rejectedRisk += 1
else if (rawLong and not longRewardOK) or (rawShort and not shortRewardOK)
rejectedReward += 1
else if not commonOK
rejectedOther += 1
bool goLong = commonOK and rawLong and bullCandle and longRegimeOK and longRiskOK and longRewardOK
bool goShort = commonOK and rawShort and bearCandle and shortRegimeOK and shortRiskOK and shortRewardOK and not goLong
// 9. ORDERS: PROTECTIVE BRACKET SUBMITTED WITH MARKET ENTRY
if goLong
lastSubmittedBar := bar_index
activeStop := longStop
activeTarget := longTarget
strategy.entry("CNPS51-L", strategy.long, comment="VWAP LONG V4", alert_message="🟢 VÀO VỊ THẾ LONG (CNPS51)\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\n🛑 Cắt lỗ (SL): " + str.tostring(activeStop, format.mintick) + "\n🎯 Chốt lời (TP): " + str.tostring(activeTarget, format.mintick))
strategy.exit("CNPS51-L-X", from_entry="CNPS51-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 lời: " + str.tostring(activeTarget, format.mintick), alert_loss="🛑 CẮT LỖ LONG (SL HIT)\nGiá cắt lỗ: " + str.tostring(activeStop, format.mintick))
tradesToday += 1
totalOrders += 1
armedLong := false
armedShort := false
else if goShort
lastSubmittedBar := bar_index
activeStop := shortStop
activeTarget := shortTarget
strategy.entry("CNPS51-S", strategy.short, comment="VWAP SHORT V4", alert_message="🔴 VÀO VỊ THẾ SHORT (CNPS51)\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\n🛑 Cắt lỗ (SL): " + str.tostring(activeStop, format.mintick) + "\n🎯 Chốt lời (TP): " + str.tostring(activeTarget, format.mintick))
strategy.exit("CNPS51-S-X", from_entry="CNPS51-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 lời: " + str.tostring(activeTarget, format.mintick), alert_loss="🛑 CẮT LỖ SHORT (SL HIT)\nGiá cắt lỗ: " + str.tostring(activeStop, format.mintick))
tradesToday += 1
totalOrders += 1
armedLong := false
armedShort := false
// 10. GAP VALIDITY, MAX HOLD, END OF DAY
if strategy.position_size > 0 and (na(activeStop) or na(activeTarget) or activeStop >= strategy.position_avg_price or activeTarget <= strategy.position_avg_price)
strategy.close("CNPS51-L", immediately=true, comment="INVALID GAP", alert_message="⚠️ ĐÓNG VỊ THẾ LONG DO GAP KHÔNG HỢP LỆ (Invalid Gap)")
if strategy.position_size < 0 and (na(activeStop) or na(activeTarget) or activeStop <= strategy.position_avg_price or activeTarget >= strategy.position_avg_price)
strategy.close("CNPS51-S", immediately=true, comment="INVALID GAP", alert_message="⚠️ ĐÓNG VỊ THẾ SHORT DO GAP KHÔNG HỢP LỆ (Invalid Gap)")
if useTimeout and strategy.position_size != 0 and strategy.opentrades > 0 and barstate.isconfirmed
int fillBar = strategy.opentrades.entry_bar_index(0)
if bar_index - fillBar >= maxHold
if strategy.position_size > 0
strategy.close("CNPS51-L", comment="TIMEOUT", alert_message="⏱️ ĐÓNG VỊ THẾ LONG HẾT THỜI GIAN GIỮ LỆNH (Time Exit)")
else
strategy.close("CNPS51-S", comment="TIMEOUT", alert_message="⏱️ ĐÓNG VỊ THẾ SHORT HẾT THỜI GIAN GIỮ LỆNH (Time Exit)")
int forceMinute = forceCloseHour * 60 + forceCloseMinute
int candleStart = hour(time, TZ) * 60 + minute(time, TZ)
int candleEnd = hour(time_close, TZ) * 60 + minute(time_close, TZ)
bool forceClose = barstate.isconfirmed and not na(time_close) and candleStart < forceMinute and candleEnd >= forceMinute
if forceClose and strategy.position_size != 0
strategy.close_all(immediately=true, comment="SESSION END", alert_message="⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End)")
if strategy.position_size == 0 and not goLong and not goShort
activeStop := na
activeTarget := na
// 11. DISPLAY + FUNNEL DIAGNOSTICS
plot(showLevels and strategy.position_size != 0 ? activeStop : na, "Active Stop", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showLevels and strategy.position_size != 0 ? activeTarget : na, "Active TP", color=color.green, linewidth=2, style=plot.style_linebr)
plotshape(showSignals and goLong, title="Long", text="L", style=shape.triangleup, location=location.belowbar, color=color.teal, textcolor=color.white, size=size.tiny)
plotshape(showSignals and goShort, title="Short", text="S", style=shape.triangledown, location=location.abovebar, color=color.red, textcolor=color.white, size=size.tiny)
var table diag = table.new(position.top_right, 2, 14, border_width=1)
if barstate.islast
if showDiagnostics
table.cell(diag, 0, 0, "CNPS51 V4")
table.cell(diag, 1, 0, profile)
table.cell(diag, 0, 1, "VWAP bars")
table.cell(diag, 1, 1, str.tostring(barsAccumulated))
table.cell(diag, 0, 2, "Outer / Inner")
table.cell(diag, 1, 2, str.tostring(outerMult, "#.00") + " / " + str.tostring(innerMult, "#.00"))
table.cell(diag, 0, 3, "ADX")
table.cell(diag, 1, 3, str.tostring(adx, "#.0"))
table.cell(diag, 0, 4, "Outer touches")
table.cell(diag, 1, 4, str.tostring(totalTouches))
table.cell(diag, 0, 5, "Raw reclaims")
table.cell(diag, 1, 5, str.tostring(totalRaw))
table.cell(diag, 0, 6, "Reject: candle")
table.cell(diag, 1, 6, str.tostring(rejectedQuality))
table.cell(diag, 0, 7, "Reject: regime")
table.cell(diag, 1, 7, str.tostring(rejectedRegime))
table.cell(diag, 0, 8, "Reject: risk")
table.cell(diag, 1, 8, str.tostring(rejectedRisk))
table.cell(diag, 0, 9, "Reject: reward")
table.cell(diag, 1, 9, str.tostring(rejectedReward))
table.cell(diag, 0, 10, "Reject: session/flat")
table.cell(diag, 1, 10, str.tostring(rejectedOther))
table.cell(diag, 0, 11, "Entries sent")
table.cell(diag, 1, 11, str.tostring(totalOrders))
table.cell(diag, 0, 12, "Today")
table.cell(diag, 1, 12, str.tostring(tradesToday) + "/" + str.tostring(maxTrades))
table.cell(diag, 0, 13, "Position")
table.cell(diag, 1, 13, strategy.position_size > 0 ? "LONG" : strategy.position_size < 0 ? "SHORT" : "FLAT")
else
table.clear(diag, 0, 0, 1, 13)
2. Những khái niệm kỹ thuật cốt lõi trong CNPS51 V4
2.1. Session VWAP và Volume-Weighted Sigma Bands
Khác với đường trung bình động SMA/EMA chỉ tính theo giá, Session VWAP tính giá trung bình có trọng số khối lượng kể từ đầu phiên sáng (09:00):
- Outer Band (
VWAP ± Outer × Stdev): Biên độ kéo giãn cực đại — nơi giá bắt đầu rơi vào vùng quá mua/quá bán ngắn hạn. - Inner Band (
VWAP ± Inner × Stdev): Biên độ xác nhận hồi quy — nơi giá cho thấy dấu hiệu quay đầu trở lại vùng cân bằng.
Bot chỉ hoạt động khi đã tích lũy đủ số nến khởi động (warmup) và độ lệch chuẩn stdev lớn hơn 1 tick tối thiểu của hợp đồng.
2.2. Hệ thống 4 Profile (Strict / Balanced / Active / Manual)
Để người dùng không phải chỉnh tay hàng chục thông số, CNPS51 V4 gom sẵn 3 bộ cấu hình chuẩn và 1 chế độ tự chỉnh:
| Thông số | Strict (Chặt chẽ) | Balanced (Mặc định) | Active (Tần suất cao) |
|---|---|---|---|
| Outer / Inner Sigma | 2.0 / 1.0 | 1.6 / 0.9 | 1.4 / 0.75 |
| Warmup / Setup Lifetime | 20 / 6 nến | 10 / 10 nến | 6 / 12 nến |
| Min Body Ratio | 0.30 | 0.15 | 0.05 |
| Khoảng Risk cho phép | 2.0–8.0 điểm | 1.5–12.0 điểm | 1.0–16.0 điểm |
| Min Reward / Min R:R | 3.0 điểm / 0.70 | 1.5 điểm / 0.35 | 1.0 điểm / 0.20 |
| Lệnh tối đa / Cooldown | 2 lệnh / 8 nến | 5 lệnh / 3 nến | 8 lệnh / 1 nến |
| Yêu cầu cắt qua Inner & chờ 1 nến | Có | Không | Không |
2.3. Bộ lọc Market Regime (Directional Guard vs Strict Range)
Mean Reversion rất sợ thị trường có xu hướng mạnh một chiều. CNPS51 V4 giải quyết bằng 3 chế độ lọc dựa trên ADX(14) (ngưỡng 30), EMA(20/50) và độ dốc VWAP trong 5 nến:
Directional guard(Mặc định): Chỉ chặn lệnh Long khi thị trường đang giảm mạnh (ADX > 30,EMA20 < EMA50, độ dốc VWAP âm), và chỉ chặn lệnh Short khi thị trường đang tăng mạnh (ADX > 30,EMA20 > EMA50, độ dốc VWAP dương).Strict range: Chỉ cho phép giao dịch khi thị trường thực sự đi ngang (ADX ≤ 30, độ dốc VWAP≤ 0.65 ATR, khoảng cách EMA20/50≤ 1.0 ATR).Off: Tắt bộ lọc xu hướng để test tín hiệu thuần VWAP.
3. Nguyên lý hoạt động của CNPS51 V4
Quy trình xử lý của bot đi qua 4 bước rõ ràng:
- Khởi tạo phiên & Reset Setup: Đầu phiên sáng (
09:00) bot reset dữ liệu VWAP; đầu phiên chiều (13:00) bot xóa trạng thái Setup đang chờ từ buổi sáng để tránh nhiễu qua giờ nghỉ trưa. - Chạm Outer Band (Arm Setup): Khi giá chạm
±Outer Bandvà vẫn nằm đúng phía so với VWAP, bot bật trạng thái chờ (armedLonghoặcarmedShort) và liên tục cập nhật mức giá giãn sâu nhất (stretchLowhoặcstretchHigh). - Hồi về Inner Band (Reclaim) & Lọc chất lượng: Trong vòng
lifetimenến, nếu giá đóng cửa quay lại vào trongInner Band(nhưng chưa chạm VWAP) với cây nến xác nhận đạtbodyRatio, bot kiểm tra tiếp bộ lọc Regime, Risk và Reward/R:R. - Gửi lệnh Bracket & Bảo vệ vị thế: Nếu hợp lệ, bot vào lệnh Market kèm ngay lệnh Stop Loss và Take Profit bảo vệ, đồng thời theo dõi Gap, thời gian giữ lệnh tối đa (
60 nến) và Force Close lúc14:45.
4. Điều kiện vào lệnh Long và Short của CNPS51 V4
4.1. Điều kiện vào lệnh Long (Mua hồi quy từ biên dưới)
- Giá trước đó đã chạm hoặc xuyên xuống dưới
-Outer Band(low <= lowerOuter) khiclose < sessionVWAP. - Setup vẫn còn hiệu lực (chưa quá
lifetimenến và giá chưa chạm lênsessionVWAP). - Nến hiện tại đóng cửa quay lại trên
-Inner Bandnhưng vẫn dướisessionVWAP(lowerInner < close < sessionVWAP). (Nếu dùngStrict, cần thêm nến trước đó đóng dưới-Inner Bandvà cách nến chạm tối thiểu 1 nến). - Nến xác nhận là nến tăng (
close > open) với tỷ lệ thân nếnbodyRatio ≥ bodyMin. - Bộ lọc
longRegimeOKhợp lệ (không rơi vào pha giảm mạnh). - Khoảng Risk và Reward đạt ngưỡng của Profile đang chọn.
4.2. Điều kiện vào lệnh Short (Bán hồi quy từ biên trên)
- Giá trước đó đã chạm hoặc xuyên lên trên
+Outer Band(high >= upperOuter) khiclose > sessionVWAP. - Setup còn hiệu lực (chưa quá
lifetimenến và giá chưa chạm xuốngsessionVWAP). - Nến hiện tại đóng cửa quay lại dưới
+Inner Bandnhưng vẫn trênsessionVWAP(sessionVWAP < close < upperInner). - Nến xác nhận là nến giảm (
close < open) với tỷ lệ thân nếnbodyRatio ≥ bodyMin. - Bộ lọc
shortRegimeOKhợp lệ (không rơi vào pha tăng mạnh). - Khoảng Risk, Reward và các điều kiện chung (đang Flat, trong giờ
09:05–11:25hoặc13:05–14:25, hết Cooldown, chưa vượt số lệnh ngày) đều thỏa mãn.
5. Quản trị Stop Loss, Gap Risk và Thoát lệnh
5.1. Structural Stop Loss và bộ lọc Risk / Reward
Bot đặt Stop Loss dựa trên chính cực trị kéo giãn của nhịp sóng hiện tại:
- Long Stop:
stretchLow − 1 tick(mặc địnhstopTicks = 1) - Short Stop:
stretchHigh + 1 tick
Trước khi gửi lệnh, bot kiểm tra hai lớp bảo vệ:
- Lọc Risk: Khoảng dừng lỗ phải nằm trong
riskMin – riskMax(vớiBalancedlà1.5 – 12.0 điểm). - Lọc Reward: Khoảng cách từ giá đóng cửa đến mục tiêu (mặc định là
sessionVWAP) phải đạt tối thiểu1.5 điểmvà tỷ lệReward / Risk ≥ 0.35.
5.2. Ba cơ chế chọn Take Profit
Trong nhóm 03 - TRADING / EXITS, bạn có thể chọn 1 trong 3 cách chốt lời:
VWAP(Mặc định): Chốt lời tại chính đườngsessionVWAP(đúng bản chất Mean Reversion).Opposite inner band: Kỳ vọng giá đi xuyên qua VWAP tới dải Inner phía đối diện.Fixed R: Chốt lời theo tỷ lệ R:R cố định (mặc định1.50R).
5.3. Bảo vệ sau khớp lệnh: Invalid Gap, Timeout và Force Close
| Cơ chế | Mặc định | Vai trò bảo vệ |
|---|---|---|
| Bracket Order | Bật | Gửi Stop Loss và Take Profit ngay cùng lúc với lệnh Market Entry |
| Invalid Gap Exit | Bật | Nếu giá khớp nến sau bị nhảy Gap xuyên qua Stop hoặc Target làm lệch vị thế, đóng lệnh ngay (INVALID GAP) |
| Time Exit (Timeout) | 60 nến | Nếu giữ lệnh quá 60 nến mà giá đi ngang không chạm SL hay TP, chủ động đóng lệnh (TIMEOUT) |
| Force Close | 14:45 | Đóng toàn bộ vị thế đang mở trước giờ ATC (SESSION END) |
6. Hướng dẫn cài đặt và đọc bảng Signal Funnel trên TradingView
Các bước cài đặt
- Mở biểu đồ VN30F1M trên TradingView (khung thời gian M1 hoặc M5).
- Mở Pine Editor → tạo Strategy mới → sao chép toàn bộ mã nguồn ở Mục 1 dán vào → bấm Save và Add to chart.
- Mở Strategy Tester để xem kết quả kiểm thử và điều chỉnh
Profile(Strict,Balanced,Active) theo khẩu vị rủi ro.
Cách đọc bảng chẩn đoán phễu tín hiệu (Signal Funnel)
Điểm rất hay của CNPS51 V4 là bảng Diagnostics ở góc trên bên phải hiển thị rõ từng bước lọc lệnh để bạn biết vì sao bot vào ít hay nhiều lệnh:
- Outer touches: Tổng số lần giá chạm dải Outer Band.
- Raw reclaims: Số lần giá quay đầu vào lại Inner Band.
- Reject: candle / regime / risk / reward / session: Đếm chính xác số tín hiệu bị loại ở từng bộ lọc (do nến yếu, ngược trend, Stop quá xa/gần, Reward tới VWAP quá mỏng, hoặc ngoài giờ).
- Entries sent: Tổng số lệnh thực tế đã gửi đi.
Lưu ý kiểm thử: Thông số mặc định (100 triệu VNĐ, 1 hợp đồng, margin=0) chỉ phục vụ mô phỏng trên TradingView, không thay thế yêu cầu ký quỹ và điều kiện khớp lệnh thực tế tại công ty chứng khoán.
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 chi tiết (kèm giá vào, SL, TP) về Telegram hoặc kết nối Webhook:
- Trên biểu đồ đã gắn
CNPS51 VWAP MR V4, bấm Create Alert. - Ở mục Condition, chọn Strategy
CNPS51 VWAP MEAN REVERSION V4 - VN30F1Mvà chế độ Order fills only. - Ở ô Message, nhập:
{{strategy.order.alert_message}}.
Bảng thông điệp Alert của CNPS51 V4
| Nhóm sự kiện | Nội dung Alert Message xuất ra |
|---|---|
| Mở vị thế Long / Short | 🟢 VÀO VỊ THẾ LONG (CNPS51) hoặc 🔴 VÀO VỊ THẾ SHORT (CNPS51) kèm Giá vào, Cắt lỗ (SL) và Chốt lời (TP) |
| Chốt lời (TP) | 💰 CHỐT LỜI LONG (TP HIT) / 💰 CHỐT LỜI SHORT (TP HIT) kèm giá chốt lời |
| Cắt lỗ (SL) | 🛑 CẮT LỖ LONG (SL HIT) / 🛑 CẮT LỖ SHORT (SL HIT) kèm giá cắt lỗ |
| Thoát do Gap | ⚠️ ĐÓNG VỊ THẾ LONG/SHORT DO GAP KHÔNG HỢP LỆ (Invalid Gap) |
| Hết giờ giữ lệnh | ⏱️ ĐÓNG VỊ THẾ LONG/SHORT HẾT THỜI GIAN GIỮ LỆNH (Time Exit) |
| Đóng cuối phiên | ⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End) |
Kết luận
CNPS51 VWAP MEAN REVERSION V4 là một chiến lược giao dịch đảo chiều về trung bình gọn gàng, thực tế và dễ tùy biến cho VN30F1M. Nhờ kết hợp cơ chế chờ Reclaim tại Inner Band, bộ lọc xu hướng Directional Guard, các lớp bảo vệ Invalid Gap / Timeout / Force Close cùng bảng Signal Funnel Diagnostics, người dùng có thể kiểm soát chặt tần suất lệnh và rủi ro trên từng nhịp biến động trong phiên.
Bạn có thể tham khảo thêm các hệ thống giao dịch khác trên Phái Sinh Online như Bot CNPS50 - Trend Analysis V2 hoặc Bot CNPS49 - Daily Open để kết hợp đa dạng hóa chiến lược theo từng trạng thái thị trường.
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.








