Hướng Dẫn Sử Dụng Bot CNPS64 - Active Value Migration V2 cho VN30F1M
TradingviewBot CNPS64 Value Migration V2 giao dịch VN30F1M trên nến xác nhận với 4 nhánh vào lệnh độc lập quanh vùng giá trị VWMA, kết hợp quản trị rủi ro theo cấu trúc và giới hạn lỗ ngày.

Mục lục
Khi giao dịch hợp đồng tương lai VN30F1M, giá thường xuyên dịch chuyển qua lại quanh các vùng giá trị hợp lý theo khối lượng (Volume-Weighted Fair Value) trước khi bứt phá hoặc đảo chiều. Nếu chỉ bám theo một mẫu hình vào lệnh duy nhất, trader rất dễ bỏ lỡ các nhịp hồi kiểm định (retest), nhịp lấy lại vùng giá trị (reclaim) hoặc nhịp tiếp diễn ngắn hạn trong phiên.
Để giải quyết bài toán này, CNPS64 VALUE MIGRATION V2 ACTIVE HYBRID - VN30F1M (CNPS64 VALUE V2) được xây dựng bằng Pine Script v6 trên TradingView, sử dụng hoàn toàn dữ liệu OHLCV trên biểu đồ (không cần dữ liệu Basis) và chỉ xử lý tín hiệu trên nến đã xác nhận (barstate.isconfirmed).
Những điểm nổi bật cốt lõi của Bot CNPS64:
- 4 nhánh vào lệnh độc lập (Four Entry Routes): Kết hợp Value Tap (chạm bật vùng giá trị nhanh), Fast Reclaim (lấy lại Fast VWMA), Slow Reclaim (đảo chiều qua Slow VWMA) và Micro Continuation (phá vỡ vi mô tiếp diễn) để gia tăng tần suất cơ hội hợp lệ.
- Mô hình vùng giá trị theo khối lượng (VWMA): Dùng cặp
Fast VWMA (8)vàSlow VWMA (21)tính trênhlc3kết hợp độ dốc và độ giãn cách chuẩn hóa theoATR(14). - Quản trị rủi ro theo cấu trúc: Hỗ trợ 3 chế độ đặt Stop Loss (
Micro Structure,Slow Fair Value,ATR Fixed), kiểm tra chặt biên độ rủi ro (1.5 – 12.0điểm) và mục tiêu tối thiểu (2.5điểm) trước khi gửi lệnh. - Bảo vệ đa tầng: Tích hợp giới hạn thời gian giữ lệnh tối đa (
40 phút), giới hạn lỗ đã chốt trong ngày (2.400.000 VND), tùy chọn Break Even, tùy chọn thoát khi mất vùng giá trị và tự động đóng vị thế trước giờ nghỉ trưa (11:25) cũng như trước phiên ATC (14:25).
1. CNPS64 Value Migration V2 là gì?
CNPS64 VALUE MIGRATION V2 ACTIVE HYBRID - VN30F1M là hệ thống giao dịch theo vùng giá trị dịch chuyển (Active Value Migration) trên khung thời gian nội ngày, vận hành dựa trên 4 trụ cột kỹ thuật chính:
- Hệ thống vùng giá trị kép (Volume-Weighted Value Model): Kết hợp
Fast VWMA (8)vàSlow VWMA (21)trên giá trung bìnhhlc3để đo lường sự dịch chuyển dòng tiền và xu hướng cân bằng cung cầu. - 4 nhánh kích hoạt tín hiệu (Four Independent Entry Routes): Bao quát cả các pha hồi chạm hỗ trợ/kháng cự động (
Value Tap), pha lấy lại vùng giá trị (Fast Reclaim,Slow Reclaim) và pha tiếp diễn ngắn hạn (Micro Continuation). - Bộ lọc chất lượng nến và bối cảnh: Yêu cầu nến tín hiệu đạt tỷ lệ thân/biên độ tối thiểu (
0.20), vị trí giá đóng cửa thuận hướng (0.55với Long,0.45với Short), kèm các bộ lọc tùy chọn nhưSession VWAP,ADX(14)vàRVOL. - Kiểm soát rủi ro và phiên VN30F1M: Khung giờ vào lệnh riêng cho phiên sáng/chiều, cơ chế chống khớp lệnh lỗi ở nến kế tiếp (
INVALID NEXT-BAR FILL), giới hạn thời gian giữ lệnh, khóa lỗ ngày và tự động đưa vị thế vềFlatcuối mỗi buổi.
Bảng thông số mặc định
| Nhóm thông số | Tham số (input) | Giá trị mặc định | Ý nghĩa thực tế |
|---|---|---|---|
| 01 - Trade Control | tradeDirection | "Both" | Chiều giao dịch (Both / Long / Short) |
contracts | 3 | Tham số số hợp đồng hiển thị cấu hình (lệnh strategy.entry dùng default_qty_value = 1) | |
maximumTradesPerDay | 6 | Số lệnh tối đa trong một ngày | |
cooldownBars | 2 | Số nến nghỉ tối thiểu sau khi đóng lệnh | |
minimumBarsBetweenEntries | 3 | Khoảng cách nến tối thiểu giữa các lần vào lệnh | |
oneTradePerDirection | false | Giới hạn mỗi chiều tối đa 1 lệnh/ngày | |
| 02 - Fair Value | fastValueBars / slowValueBars | 8 / 21 | Chu kỳ Fast VWMA và Slow VWMA trên hlc3 |
slopeLookback | 3 | Số nến tính độ dốc Fast VWMA | |
maximumAdverseFastSlopeATR | 0.15 | Độ dốc nghịch tối đa cho phép của Fast VWMA theo ATR | |
maximumValueSeparationATR | 0.60 | Độ đảo nghịch tối đa giữa Fast VWMA và Slow VWMA theo ATR | |
useAcceptanceFilter | false | Bật/tắt bộ lọc tỷ lệ nến chấp nhận Slow VWMA (5 nến, tối thiểu 0.40) | |
| 03 - Entry Routes | enableValueTap / enableFastReclaim / enableSlowReclaim / enableContinuation | true (cả 4) | Bật/tắt từng nhánh vào lệnh A, B, C, D |
valueTouchATR / slowPierceATR | 0.40 / 0.80 | Bán kính chạm Fast VWMA và độ xuyên tối đa qua Slow VWMA theo ATR | |
reclaimBuffer / microBreakBuffer | 0.10 / 0.10 | Khoảng đệm xác nhận vượt vùng giá trị và phá vỡ vi mô (điểm) | |
continuationBreakBars / continuationTouchBars / continuationProximityATR | 3 / 3 / 0.75 | Chu kỳ đỉnh/đáy vi mô và vùng tiệm cận Fast VWMA cho Route D | |
| 04 - Quality | minimumBodyRatio / minimumCloseLocation | 0.20 / 0.55 | Tỷ lệ thân nến tối thiểu và vị trí đóng cửa thuận hướng |
useVWAPFilter / useADXFilter (17) / useRelativeVolume (25, 0.80) | false | Các bộ lọc tùy chọn theo Session VWAP, ADX(14) và RVOL | |
| 05 - Risk | stopMode | "Micro Structure" | Chế độ đặt SL (Micro Structure, Slow Fair Value, ATR Fixed) |
stopLookback / stopBufferATR / fixedStopATR | 4 / 0.15 / 1.40 | Số nến cấu trúc, khoảng đệm ATR và hệ số ATR Fixed | |
minimumStopPoints / maximumStopPoints | 1.50 / 12.0 | Biên độ rủi ro SL hợp lệ (điểm) | |
takeProfitR / minimumGrossTarget | 1.55 / 2.50 | Tỷ lệ chốt lời 1.55R và khoảng cách TP tối thiểu 2.50 điểm | |
| 06 - Exits | useMigrationFailureExit / failureCloses | false / 2 | Đóng lệnh khi đóng cửa mất Slow VWMA liên tiếp |
useBreakEven / breakEvenAtR / breakEvenOffset | false / 1.0 / 0.20 | Dời SL về hòa vốn cộng đệm khi đạt 1.0R | |
useTimeExit / maximumHoldMinutes | true / 40 | Tự động đóng vị thế sau 40 phút giữ lệnh | |
| 07 - Protection | useDailyLossGuard / maximumDailyLossVND | true / 2400000 | Chặn vào lệnh mới nếu lỗ đã chốt trong ngày vượt 2.400.000 VND |
| 08 - Session | morningEntry / afternoonEntry | "0905-1120" / "1305-1415" | Khung giờ cho phép vào lệnh sáng và chiều |
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 phiên lúc 14:25 |
Source Code CNPS64 Value Migration V2
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
// CNPS64 V2 - Active Value Migration - VN30F1M
// Four entry routes: Value Tap, Fast Reclaim, Slow Reclaim, Micro Continuation.
// Confirmed-bar strategy. No dashboard.
strategy(title="CNPS64 VALUE MIGRATION V2 ACTIVE HYBRID - VN30F1M", shorttitle="CNPS64 VALUE V2", 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, 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: POSITION / TRADE FREQUENCY
// ============================================================================
tradeDirection = input.string("Both", "Trade Direction", options=["Both", "Long", "Short"], group="01 - Trade Control")
contracts = input.int(3, "Contracts Per Trade", 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=100, group="01 - Trade Control")
minimumBarsBetweenEntries = input.int(3, "Minimum Bars Between Signals", minval=0, maxval=100, group="01 - Trade Control")
oneTradePerDirection = input.bool(false, "One Trade Per Direction Per Day?", group="01 - Trade Control")
// ============================================================================
// SECTION 2: VOLUME-WEIGHTED VALUE MODEL
// ============================================================================
fastValueBars = input.int(8, "Fast VWMA Length", minval=2, maxval=100, group="02 - Fair Value")
slowValueBars = input.int(21, "Slow VWMA Length", minval=5, maxval=200, group="02 - Fair Value")
slopeLookback = input.int(3, "Fair-Value Slope Bars", minval=1, maxval=30, group="02 - Fair Value")
maximumAdverseFastSlopeATR = input.float(0.15, "Maximum Adverse Fast Slope / ATR", minval=0, maxval=2, step=0.05, group="02 - Fair Value")
maximumValueSeparationATR = input.float(0.60, "Maximum Fast/Slow Inversion x ATR", minval=0, maxval=3, step=0.05, group="02 - Fair Value")
useAcceptanceFilter = input.bool(false, "Require Recent Closes To Accept Slow Value?", group="02 - Fair Value")
acceptanceBars = input.int(5, "Acceptance Observation Bars", minval=2, maxval=30, group="02 - Fair Value")
minimumAcceptanceShare = input.float(0.40, "Minimum Acceptance Share", minval=0, maxval=1, step=0.05, group="02 - Fair Value")
// ============================================================================
// SECTION 3: ENTRY ROUTES
// ============================================================================
enableValueTap = input.bool(true, "Route A: Fast Value Tap / Rejection", group="03 - Entry Routes")
enableFastReclaim = input.bool(true, "Route B: Fast Value Reclaim", group="03 - Entry Routes")
enableSlowReclaim = input.bool(true, "Route C: Slow Value Reclaim", group="03 - Entry Routes")
enableContinuation = input.bool(true, "Route D: Micro Continuation", group="03 - Entry Routes")
valueTouchATR = input.float(0.40, "Tap Radius Beyond Fast Value x ATR", minval=0.05, maxval=3, step=0.05, group="03 - Entry Routes")
slowPierceATR = input.float(0.80, "Maximum Wick Beyond Slow Value x ATR", minval=0.05, maxval=3, step=0.05, group="03 - Entry Routes")
reclaimBuffer = input.float(0.10, "Reclaim Close Buffer (points)", minval=0, step=0.1, group="03 - Entry Routes")
continuationBreakBars = input.int(3, "Micro Break Lookback", minval=2, maxval=20, group="03 - Entry Routes")
continuationTouchBars = input.int(3, "Recent Value Proximity Lookback", minval=2, maxval=10, group="03 - Entry Routes")
continuationProximityATR = input.float(0.75, "Recent Value Proximity x ATR", minval=0.1, maxval=3, step=0.05, group="03 - Entry Routes")
microBreakBuffer = input.float(0.10, "Micro Break Buffer (points)", minval=0, step=0.1, group="03 - Entry Routes")
// ============================================================================
// SECTION 4: SIGNAL QUALITY
// ============================================================================
minimumBodyRatio = input.float(0.20, "Minimum Signal Body / Range", minval=0, maxval=1, step=0.05, group="04 - Quality")
minimumCloseLocation = input.float(0.55, "Minimum Directional Close Location", minval=0.5, maxval=0.95, step=0.05, group="04 - Quality")
useVWAPFilter = input.bool(false, "Require Session VWAP Alignment?", group="04 - Quality")
useADXFilter = input.bool(false, "Require ADX Strength?", group="04 - Quality")
minimumADX = input.float(17, "Minimum ADX14", minval=5, maxval=60, step=1, group="04 - Quality")
useRelativeVolume = input.bool(false, "Require Relative Entry Volume?", group="04 - Quality")
volumeBaselineBars = input.int(25, "Volume SMA Lookback", minval=5, maxval=150, group="04 - Quality")
minimumEntryRVOL = input.float(0.80, "Minimum Entry RVOL", minval=0.1, maxval=5, step=0.05, group="04 - Quality")
// ============================================================================
// SECTION 5: STRUCTURAL RISK / TARGET
// ============================================================================
stopMode = input.string("Micro Structure", "Stop Location", options=["Micro Structure", "Slow Fair Value", "ATR Fixed"], group="05 - Risk")
stopLookback = input.int(4, "Micro Stop Structure Bars", minval=2, maxval=30, group="05 - Risk")
stopBufferATR = input.float(0.15, "Structural Stop Buffer x ATR", minval=0, maxval=2, step=0.05, group="05 - Risk")
fixedStopATR = input.float(1.40, "ATR Fixed Stop x ATR", minval=0.25, maxval=5, step=0.05, group="05 - Risk")
minimumStopPoints = input.float(1.50, "Minimum Stop Distance (points)", minval=0.1, step=0.5, group="05 - Risk")
maximumStopPoints = input.float(12.0, "Maximum Stop Distance (points)", minval=0.5, step=0.5, group="05 - Risk")
takeProfitR = input.float(1.55, "Take Profit Multiple (R)", minval=0.25, maxval=8, step=0.05, group="05 - Risk")
minimumGrossTarget = input.float(2.50, "Minimum Target Distance (points)", minval=0, step=0.5, group="05 - Risk")
// ============================================================================
// SECTION 6: EXITS
// ============================================================================
useMigrationFailureExit = input.bool(false, "Close On Failed Slow-Value Acceptance?", group="06 - Exits")
failureCloses = input.int(2, "Consecutive Failure Closes", minval=1, maxval=5, group="06 - Exits")
useBreakEven = input.bool(false, "Enable Break Even?", group="06 - Exits")
breakEvenAtR = input.float(1.0, "Break Even Trigger (R)", minval=0.25, maxval=5, step=0.25, group="06 - Exits")
breakEvenOffset = input.float(0.20, "Break Even Offset (points)", minval=0, step=0.1, group="06 - Exits")
useTimeExit = input.bool(true, "Use Maximum Hold Time?", group="06 - Exits")
maximumHoldMinutes = input.int(40, "Maximum Hold Minutes", minval=5, maxval=240, group="06 - Exits")
// ============================================================================
// SECTION 7: DAILY PROTECTION
// ============================================================================
useDailyLossGuard = input.bool(true, "Block New Entries After Daily Closed Loss?", group="07 - Protection")
maximumDailyLossVND = input.float(2400000, "Daily Closed Loss Threshold (VND)", minval=100000, step=100000, group="07 - Protection")
// ============================================================================
// SECTION 8: VN30F1M SESSION
// ============================================================================
string timezoneVN = "Asia/Ho_Chi_Minh"
morningEntry = input.session("0905-1120", "Morning Entry Window", group="08 - Session")
afternoonEntry = input.session("1305-1415", "Afternoon Entry Window", group="08 - Session")
closeBeforeLunch = input.bool(true, "Force Flat Before Lunch?", group="08 - Session")
lunchFlatMinute = input.int(25, "Lunch Flat Minute (11:xx)", minval=15, maxval=30, group="08 - Session")
finalFlatHour = input.int(14, "Final Flat Hour", minval=0, maxval=23, group="08 - Session")
finalFlatMinute = input.int(25, "Final Flat Minute", minval=0, maxval=59, group="08 - Session")
// ============================================================================
// SECTION 9: CLEAN DISPLAY - NO DASHBOARD
// ============================================================================
showFairValue = input.bool(true, "Show Fast / Slow Value?", group="09 - Display")
showVWAP = input.bool(false, "Show Session VWAP?", group="09 - Display")
showEntrySignals = input.bool(true, "Show Entry Signals?", group="09 - Display")
showTradeLevels = input.bool(true, "Show Active SL / TP?", group="09 - Display")
// ============================================================================
// SECTION 10: CLOCK / SESSION CUT-OFFS
// ============================================================================
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 morningContinuous = minuteOpen >= 540 and minuteOpen < 690
bool afternoonContinuous = minuteOpen >= 780 and minuteOpen < 870
bool continuousSession = morningContinuous or afternoonContinuous
bool morningEntryBar = not na(time(timeframe.period, morningEntry + ":23456", timezoneVN))
bool afternoonEntryBar = not na(time(timeframe.period, afternoonEntry + ":23456", timezoneVN))
bool entrySession = continuousSession and (morningEntryBar or afternoonEntryBar)
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 morningContinuous or minuteClose < lunchCutoff))
bool lunchFlatBar = closeBeforeLunch and barstate.isconfirmed and morningContinuous and minuteOpen < lunchCutoff and minuteClose >= lunchCutoff
bool finalFlatBar = barstate.isconfirmed and afternoonContinuous and minuteOpen < finalCutoff and minuteClose >= finalCutoff
// ============================================================================
// SECTION 11: VALUE MIGRATION METRICS
// ============================================================================
float atr = ta.atr(14)
float fastValue = ta.vwma(hlc3, fastValueBars)
float slowValue = ta.vwma(hlc3, slowValueBars)
float fastSlopeATR = not na(atr) and atr > 0 ? (fastValue - fastValue[slopeLookback]) / atr : na
float valueSpreadATR = not na(atr) and atr > 0 ? (fastValue - slowValue) / atr : na
float longAcceptanceShare = ta.sma(close > slowValue ? 1.0 : 0.0, acceptanceBars)
float shortAcceptanceShare = ta.sma(close < slowValue ? 1.0 : 0.0, acceptanceBars)
bool longValueContext = (not na(fastValue) and not na(slowValue) and not na(fastSlopeATR) and not na(valueSpreadATR) and fastSlopeATR >= -maximumAdverseFastSlopeATR and valueSpreadATR >= -maximumValueSeparationATR and (not useAcceptanceFilter or longAcceptanceShare >= minimumAcceptanceShare))
bool shortValueContext = (not na(fastValue) and not na(slowValue) and not na(fastSlopeATR) and not na(valueSpreadATR) and fastSlopeATR <= maximumAdverseFastSlopeATR and valueSpreadATR <= maximumValueSeparationATR and (not useAcceptanceFilter or shortAcceptanceShare >= minimumAcceptanceShare))
// ============================================================================
// SECTION 12: CONFIRMED CANDLE / MICRO STRUCTURE
// ============================================================================
float candleRange = math.max(high - low, syminfo.mintick)
float bodyRatio = math.abs(close - open) / candleRange
float closeLocation = (close - low) / candleRange
bool bullishCandle = close > open and bodyRatio >= minimumBodyRatio and closeLocation >= minimumCloseLocation
bool bearishCandle = close < open and bodyRatio >= minimumBodyRatio and closeLocation <= 1.0 - minimumCloseLocation
float previousMicroHigh = ta.highest(high, continuationBreakBars)[1]
float previousMicroLow = ta.lowest(low, continuationBreakBars)[1]
float recentStopLow = ta.lowest(low, stopLookback)
float recentStopHigh = ta.highest(high, stopLookback)
float recentProximityLow = ta.lowest(low, continuationTouchBars)[1]
float recentProximityHigh = ta.highest(high, continuationTouchBars)[1]
float averageVolume = ta.sma(volume, volumeBaselineBars)[1]
float entryRVOL = not na(averageVolume) and averageVolume > 0 ? volume / averageVolume : na
[pDI, mDI, adx] = ta.dmi(14, 14)
bool volumeOK = not useRelativeVolume or (not na(entryRVOL) and entryRVOL >= minimumEntryRVOL)
bool adxOK = not useADXFilter or (not na(adx) and adx >= minimumADX)
// ============================================================================
// SECTION 13: CONTINUOUS SESSION VWAP
// ============================================================================
var float accumulatedPV = 0.0
var float accumulatedVolume = 0.0
if newTradingDay
accumulatedPV := 0.0
accumulatedVolume := 0.0
if continuousSession and barstate.isconfirmed and not na(volume) and volume > 0
accumulatedPV += hlc3 * volume
accumulatedVolume += volume
float sessionVWAP = accumulatedVolume > 0 ? accumulatedPV / accumulatedVolume : na
bool longVWAPOK = not useVWAPFilter or (not na(sessionVWAP) and close > sessionVWAP)
bool shortVWAPOK = not useVWAPFilter or (not na(sessionVWAP) and close < sessionVWAP)
// ============================================================================
// SECTION 14: FOUR INDEPENDENT ENTRY ROUTES
// ============================================================================
// A: Direct rejection from fast volume-weighted value.
bool longTap = (enableValueTap and longValueContext and bullishCandle and not na(atr) and atr > 0 and low <= fastValue + atr * valueTouchATR and low >= slowValue - atr * slowPierceATR and close > fastValue + reclaimBuffer and close > close[1])
bool shortTap = (enableValueTap and shortValueContext and bearishCandle and not na(atr) and atr > 0 and high >= fastValue - atr * valueTouchATR and high <= slowValue + atr * slowPierceATR and close < fastValue - reclaimBuffer and close < close[1])
// B: A candle previously closed at/below fast value; current close reclaims it.
bool longFastReclaim = (enableFastReclaim and longValueContext and bullishCandle and close[1] <= fastValue[1] + reclaimBuffer and close > fastValue + reclaimBuffer and close > close[1])
bool shortFastReclaim = (enableFastReclaim and shortValueContext and bearishCandle and close[1] >= fastValue[1] - reclaimBuffer and close < fastValue - reclaimBuffer and close < close[1])
// C: Regime reset across slow value; does not need earlier acceptance.
bool longSlowReclaim = (enableSlowReclaim and bullishCandle and not na(fastSlopeATR) and fastSlopeATR >= 0 and close[1] <= slowValue[1] and close > slowValue + reclaimBuffer and close > fastValue and close > close[1])
bool shortSlowReclaim = (enableSlowReclaim and bearishCandle and not na(fastSlopeATR) and fastSlopeATR <= 0 and close[1] >= slowValue[1] and close < slowValue - reclaimBuffer and close < fastValue and close < close[1])
// D: Fresh micro breakout after proximity to the migrating fast value.
bool longMicroContinuation = (enableContinuation and longValueContext and bullishCandle and fastValue > slowValue and fastSlopeATR >= 0 and close > previousMicroHigh + microBreakBuffer and close > fastValue + reclaimBuffer and not na(atr[1]) and recentProximityLow <= fastValue[1] + atr[1] * continuationProximityATR)
bool shortMicroContinuation = (enableContinuation and shortValueContext and bearishCandle and fastValue < slowValue and fastSlopeATR <= 0 and close < previousMicroLow - microBreakBuffer and close < fastValue - reclaimBuffer and not na(atr[1]) and recentProximityHigh >= fastValue[1] - atr[1] * continuationProximityATR)
bool rawLong = longTap or longFastReclaim or longSlowReclaim or longMicroContinuation
bool rawShort = shortTap or shortFastReclaim or shortSlowReclaim or shortMicroContinuation
// ============================================================================
// SECTION 15: TRADE FREQUENCY / DAILY LOSS CONTROL
// ============================================================================
var int tradesToday = 0
var int seenClosedTrades = 0
var int lastExitBar = na
var int lastOrderBar = na
var float dayStartNetProfit = na
var bool usedLongToday = false
var bool usedShortToday = false
if newTradingDay
tradesToday := 0
dayStartNetProfit := strategy.netprofit
usedLongToday := false
usedShortToday := false
if strategy.closedtrades > seenClosedTrades
seenClosedTrades := strategy.closedtrades
lastExitBar := bar_index
bool flat = strategy.position_size == 0
bool inLong = strategy.position_size > 0
bool inShort = strategy.position_size < 0
bool allowLong = tradeDirection != "Short" and (not oneTradePerDirection or not usedLongToday)
bool allowShort = tradeDirection != "Long" and (not oneTradePerDirection or not usedShortToday)
float dailyClosedPnL = strategy.netprofit - nz(dayStartNetProfit, strategy.netprofit)
bool dailyCountOK = tradesToday < maximumTradesPerDay
bool cooldownOK = na(lastExitBar) or bar_index - lastExitBar > cooldownBars
bool spacingOK = na(lastOrderBar) or bar_index - lastOrderBar >= minimumBarsBetweenEntries
bool dailyLossOK = not useDailyLossGuard or dailyClosedPnL > -maximumDailyLossVND
bool canEnter = (flat and entrySession and beforeCutoff and dailyCountOK and cooldownOK and spacingOK and dailyLossOK and volumeOK and adxOK and barstate.isconfirmed)
// ============================================================================
// SECTION 16: STRUCTURAL STOP / REWARD
// ============================================================================
float longStopReference = stopMode == "Slow Fair Value" ? slowValue : recentStopLow
float shortStopReference = stopMode == "Slow Fair Value" ? slowValue : recentStopHigh
float longStopCandidate = (not na(atr) and atr > 0 ? math.round_to_mintick(stopMode == "ATR Fixed" ? close - fixedStopATR * atr : longStopReference - atr * stopBufferATR) : na)
float shortStopCandidate = (not na(atr) and atr > 0 ? math.round_to_mintick(stopMode == "ATR Fixed" ? close + fixedStopATR * atr : shortStopReference + atr * stopBufferATR) : na)
float longRisk = close - longStopCandidate
float shortRisk = shortStopCandidate - close
bool longRiskOK = not na(longRisk) and longRisk >= minimumStopPoints and longRisk <= maximumStopPoints and longRisk * takeProfitR >= minimumGrossTarget
bool shortRiskOK = not na(shortRisk) and shortRisk >= minimumStopPoints and shortRisk <= maximumStopPoints and shortRisk * takeProfitR >= minimumGrossTarget
float longTargetCandidate = not na(longRisk) ? math.round_to_mintick(close + longRisk * takeProfitR) : na
float shortTargetCandidate = not na(shortRisk) ? math.round_to_mintick(close - shortRisk * takeProfitR) : na
bool finalLong = rawLong and allowLong and longVWAPOK and longRiskOK and canEnter
bool finalShort = rawShort and allowShort and shortVWAPOK and shortRiskOK and canEnter and not finalLong
// ============================================================================
// SECTION 17: ACTIVE TRADE STATE
// ============================================================================
var float activeStop = na
var float activeTarget = na
var float activeFill = na
var float initialFillRisk = na
var int entryBarSeen = na
var int failureCount = 0
var bool breakEvenActive = false
// ============================================================================
// SECTION 18: LONG ENTRY AND INITIAL BRACKET
// ============================================================================
if finalLong
activeStop := longStopCandidate
activeTarget := longTargetCandidate
activeFill := na
initialFillRisk := na
entryBarSeen := na
failureCount := 0
breakEvenActive := false
strategy.entry("CNPS64-L", strategy.long, comment="ACTIVE VALUE RE-ACCEPTANCE LONG", alert_message="🟢 VÀO VỊ THẾ LONG (Active Value Migration)\\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("CNPS64-L-X", from_entry="CNPS64-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
usedLongToday := true
lastOrderBar := bar_index
// ============================================================================
// SECTION 19: SHORT ENTRY AND INITIAL BRACKET
// ============================================================================
else if finalShort
activeStop := shortStopCandidate
activeTarget := shortTargetCandidate
activeFill := na
initialFillRisk := na
entryBarSeen := na
failureCount := 0
breakEvenActive := false
strategy.entry("CNPS64-S", strategy.short, comment="ACTIVE VALUE RE-ACCEPTANCE SHORT", alert_message="🔴 VÀO VỊ THẾ SHORT (Active Value Migration)\\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("CNPS64-S-X", from_entry="CNPS64-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
usedShortToday := true
lastOrderBar := bar_index
// ============================================================================
// SECTION 20: FILLED POSITION / 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(entryBarSeen) or entryBarSeen != fillBar
entryBarSeen := fillBar
activeFill := 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 ? "CNPS64-L" : "CNPS64-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 beStop = math.round_to_mintick(inLong ? fillPrice + breakEvenOffset : fillPrice - breakEvenOffset)
activeStop := inLong ? math.max(activeStop, beStop) : math.min(activeStop, beStop)
breakEvenActive := true
if inLong
strategy.exit("CNPS64-L-X", from_entry="CNPS64-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("CNPS64-S-X", from_entry="CNPS64-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 21: VALUE FAILURE / MAXIMUM HOLD
// ============================================================================
if strategy.position_size != 0 and strategy.opentrades > 0 and barstate.isconfirmed
bool migrationFailed = inLong ? close < slowValue : close > slowValue
failureCount := migrationFailed ? failureCount + 1 : 0
if useMigrationFailureExit and failureCount >= failureCloses
strategy.close(inLong ? "CNPS64-L" : "CNPS64-S", comment="FAIR VALUE ACCEPTANCE FAILED", alert_message="⚡ ĐÓNG VỊ THẾ (Phá vỡ vùng giá trị)\\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 ? "CNPS64-L" : "CNPS64-S", comment="MAXIMUM HOLD", 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 22: LUNCH / PRE-ATC FORCE CLOSE
// ============================================================================
if (lunchFlatBar or finalFlatBar) and strategy.position_size != 0
strategy.close_all(immediately=true, comment="VN30F1M CONTINUOUS SESSION FLAT", alert_message="⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End)\\n🎯 Giá đóng: " + str.tostring(close, format.mintick))
// ============================================================================
// SECTION 23: CLEAR CLOSED POSITION LEVELS
// ============================================================================
if flat and not finalLong and not finalShort
activeStop := na
activeTarget := na
activeFill := na
initialFillRisk := na
entryBarSeen := na
failureCount := 0
breakEvenActive := false
// ============================================================================
// SECTION 24: CLEAN CHART - NO TABLE
// ============================================================================
plot(showFairValue ? fastValue : na, title="Fast Volume-Weighted Fair Value", color=color.aqua, linewidth=2)
plot(showFairValue ? slowValue : na, title="Slow Volume-Weighted Fair Value", color=color.orange, linewidth=2)
plot(showVWAP ? sessionVWAP : na, title="Daily Continuous Session VWAP", color=color.gray, linewidth=1, 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(showEntrySignals and finalLong, title="CNPS64 V2 LONG", text="L", style=shape.triangleup, location=location.belowbar, color=color.teal, textcolor=color.white, size=size.small)
plotshape(showEntrySignals and finalShort, title="CNPS64 V2 SHORT", text="S", style=shape.triangledown, location=location.abovebar, color=color.red, textcolor=color.white, size=size.small)
// ============================================================================
// CNPS64 V2 - RESEARCH / EXECUTION NOTES
// ============================================================================
// 1. Four independent entry routes increase opportunity frequency.
// 2. Intraday basis is not required; only chart OHLCV.
// 3. All entries use confirmed current/past price and volume.
// 4. Market orders normally fill on the bar after the signal.
// 5. Initial protective bracket uses structural levels at signal close.
// 6. Actual filled risk / reward may differ due to next-bar execution.
// 7. Margin set to 0 disables margin constraints in this backtest.
// 8. This DOES NOT represent actual broker margin or risk limits.
// 9. More trades do not establish or guarantee profitability.
// 10. No floating diagnostic table is displayed.
// ============================================================================
2. Những khái niệm kỹ thuật cốt lõi trong CNPS64
2.1. Mô hình Vùng giá trị theo khối lượng (Value Migration Metrics)
Bot CNPS64 đo lường vùng giá trị hợp lý bằng hai đường trung bình có trọng số khối lượng (ta.vwma) tính trên giá trung bình nến hlc3 = (high + low + close) / 3:
fastValue:ta.vwma(hlc3, 8)đại diện cho vùng giá trị ngắn hạn đang dịch chuyển.slowValue:ta.vwma(hlc3, 21)đại diện cho vùng giá trị nền trung hạn.- Độ dốc chuẩn hóa (
fastSlopeATR):(fastValue - fastValue[3]) / atr, vớiatr = ta.atr(14). - Độ giãn cách hai vùng giá trị (
valueSpreadATR):(fastValue - slowValue) / atr.
Từ đó, bot xác định bối cảnh hợp lệ (longValueContext / shortValueContext):
- Với Long:
fastSlopeATR >= -0.15vàvalueSpreadATR >= -0.60(cho phépFast VWMAchững nhẹ hoặc nằm dưới nhẹSlow VWMAtrong biên độ kiểm soát). - Với Short:
fastSlopeATR <= 0.15vàvalueSpreadATR <= 0.60. - Nếu bật
useAcceptanceFilter, tỷ lệ nến đóng cửa thuận chiềuSlow VWMAtrong5nến gần nhất (longAcceptanceShare/shortAcceptanceShare) phải đạt tối thiểu0.40.
2.2. Chất lượng nến tín hiệu và Cấu trúc vi mô
Mỗi cây nến kích hoạt lệnh phải vượt qua bộ lọc hình thái nến xác nhận (bullishCandle / bearishCandle):
bodyRatio:math.abs(close - open) / math.max(high - low, syminfo.mintick) >= 0.20(thân nến chiếm ít nhất 20% biên độ nến).closeLocation:(close - low) / candleRangephải>= 0.55đối với nến Long (close > open) và<= 0.45đối với nến Short (close < open).- Cấu trúc vi mô (
Micro Structure): Bot liên tục theo dõi đỉnh/đáy trong3nến liền trước (previousMicroHigh,previousMicroLow), đáy/đỉnh tiệm cận trong3nến (recentProximityLow,recentProximityHigh) và đáy/đỉnh đặt dừng lỗ trong4nến gần nhất (recentStopLow,recentStopHigh).
2.3. Các bộ lọc bổ trợ (Session VWAP, ADX và RVOL)
Ngoài mô hình VWMA cốt lõi, bot trang bị thêm 3 bộ lọc chất lượng (mặc định tắt để giữ tần suất lệnh cao, có thể bật khi muốn siết điều kiện):
- Session VWAP (
useVWAPFilter): Tự động reset đầu mỗi ngày giao dịch (newTradingDay), cộng dồnhlc3 * volumetrong phiên liên tục sáng/chiều. Long yêu cầuclose > sessionVWAP, Short yêu cầuclose < sessionVWAP. - ADX14 (
useADXFilter): Sử dụngta.dmi(14, 14), yêu cầuadx >= 17. - Relative Volume (
useRelativeVolume): So sánh khối lượng nến hiện tại vớita.sma(volume, 25)[1], yêu cầuentryRVOL >= 0.80.
3. Nguyên lý hoạt động của CNPS64
Quy trình xử lý lệnh trên mỗi nến của CNPS64 diễn ra tuần tự theo 5 bước:
- Khởi tạo phiên và kiểm tra đồng hồ VN30F1M: Quy đổi thời gian theo múi giờ
Asia/Ho_Chi_Minh. Đầu ngày mới (newTradingDay), bot reset biến đếmtradesToday,usedLongToday,usedShortToday, bộ cộng dồnSession VWAPvà ghi nhậndayStartNetProfit. - Đánh giá bối cảnh giá trị và hình thái nến: Tính
ATR(14),Fast VWMA,Slow VWMA, kiểm tralongValueContext/shortValueContextvà xác định nến hiện tại có đạt chuẩnbullishCandlehaybearishCandle. - Quét 4 nhánh tín hiệu độc lập: Kiểm tra đồng thời 4 nhánh (Value Tap, Fast Reclaim, Slow Reclaim, Micro Continuation) để tạo cờ
rawLonghoặcrawShort. - Kiểm tra điều kiện vào lệnh & quản trị rủi ro: Xác nhận
canEnter(đangflat, đúng khung giờ, chưa chạm giới hạn ngày, hết cooldown, không vi phạm lỗ ngày) và tính toánlongRisk/shortRisknằm trong khoảng1.50 – 12.0điểm với TP tối thiểu2.50điểm. Lưu ý: nếu cảfinalLongvàfinalShortcùng thỏa mãn,finalLongđược ưu tiên (and not finalLong). - Gửi lệnh và quản trị vị thế đang mở: Gửi lệnh thị trường kèm bracket SL/TP ban đầu (
CNPS64-L/CNPS64-S). Ở các nến xác nhận tiếp theo, bot đối chiếu giá khớp thực tế (fillPrice), đóng ngay nếu khớp lệnh bất hợp lệ (INVALID NEXT-BAR FILL), cập nhật Break Even nếu bật, giám sát thoát sớm khi mấtSlow VWMAhoặc hết40 phút, và tự độngstrategy.close_alltại mốc11:25(nếu bật) và14:25.
4. Điều kiện vào lệnh Long và Short của CNPS64
4.1. Điều kiện vào lệnh Long
Lệnh Long (finalLong) được kích hoạt khi ít nhất 1 trong 4 nhánh sau thỏa mãn (rawLong), đồng thời vượt qua bộ lọc hướng (allowLong), longVWAPOK, longRiskOK và canEnter:
- Nhánh A — Value Tap (
longTap): ĐạtlongValueContextvàbullishCandle; giá thấp nhất chạm vào vùngFast VWMA(low <= fastValue + atr * 0.40) nhưng không xuyên quá sâu dướiSlow VWMA(low >= slowValue - atr * 0.80); giá đóng cửa bật lên trênfastValue + 0.10và cao hơnclose[1]. - Nhánh B — Fast Reclaim (
longFastReclaim): ĐạtlongValueContextvàbullishCandle; nến trước đóng cửa từfastValue[1] + 0.10trở xuống (close[1] <= fastValue[1] + 0.10); nến hiện tại đóng cửa lấy lại trênfastValue + 0.10vàclose > close[1]. - Nhánh C — Slow Reclaim (
longSlowReclaim): ĐạtbullishCandlevàfastSlopeATR >= 0(không yêu cầulongValueContexttrước đó); nến trước đóng cửa<= slowValue[1]; nến hiện tại đóng cửa vượt cảslowValue + 0.10lẫnfastValuevàclose > close[1]. - Nhánh D — Micro Continuation (
longMicroContinuation): ĐạtlongValueContext,bullishCandle,fastValue > slowValuevàfastSlopeATR >= 0;closephá vỡ đỉnh vi mô 3 nến (close > previousMicroHigh + 0.10) và nằm trênfastValue + 0.10; đồng thời đáy 3 nến trước từng tiệm cậnFast VWMA(recentProximityLow <= fastValue[1] + atr[1] * 0.75).
4.2. Điều kiện vào lệnh Short
Lệnh Short (finalShort) được kích hoạt đối xứng khi ít nhất 1 trong 4 nhánh sau thỏa mãn (rawShort), đồng thời đạt allowShort, shortVWAPOK, shortRiskOK, canEnter và not finalLong:
- Nhánh A — Value Tap (
shortTap): ĐạtshortValueContextvàbearishCandle;high >= fastValue - atr * 0.40vàhigh <= slowValue + atr * 0.80;close < fastValue - 0.10vàclose < close[1]. - Nhánh B — Fast Reclaim (
shortFastReclaim): ĐạtshortValueContextvàbearishCandle;close[1] >= fastValue[1] - 0.10;close < fastValue - 0.10vàclose < close[1]. - Nhánh C — Slow Reclaim (
shortSlowReclaim): ĐạtbearishCandlevàfastSlopeATR <= 0;close[1] >= slowValue[1];close < slowValue - 0.10,close < fastValuevàclose < close[1]. - Nhánh D — Micro Continuation (
shortMicroContinuation): ĐạtshortValueContext,bearishCandle,fastValue < slowValuevàfastSlopeATR <= 0;close < previousMicroLow - 0.10vàclose < fastValue - 0.10; đồng thờirecentProximityHigh >= fastValue[1] - atr[1] * 0.75.
4.3. Điều kiện kiểm soát giao dịch chung
Biến canEnter chỉ cho phép vào lệnh khi tất cả các điều kiện sau đồng thời đúng:
- Trạng thái Flat (
flat):strategy.position_size == 0(pyramiding = 0). - Khung giờ giao dịch (
entrySession&beforeCutoff): Nằm trong phiên liên tục sáng (09:05–11:20) hoặc chiều (13:05–14:15) các ngày thứ 2–thứ 6, vàtime_closephải nhỏ hơn mốc cắt phiên (11:25buổi sáng nếu bậtcloseBeforeLunch, và14:25buổi chiều). - Giới hạn tần suất:
tradesToday < 6, khoảng cách từ nến đóng lệnh gần nhấtbar_index - lastExitBar > 2(cooldownBars), khoảng cách giữa 2 lần vào lệnhbar_index - lastOrderBar >= 3(minimumBarsBetweenEntries). - Giới hạn lỗ ngày (
dailyLossOK): NếuuseDailyLossGuard = true, tổng lãi/lỗ đã đóng trong ngày (dailyClosedPnL) phải lớn hơn-2.400.000 VND. - Xác nhận nến và bộ lọc:
barstate.isconfirmedlàtrue, cùng vớivolumeOKvàadxOK.
5. Quản trị Stop Loss, Take Profit và Thoát lệnh
5.1. Cơ chế Stop Loss và bộ lọc Risk
Tại thời điểm nến tín hiệu đóng cửa, bot tính mức SL dự kiến (longStopCandidate / shortStopCandidate) được làm tròn theo syminfo.mintick dựa trên 1 trong 3 chế độ stopMode:
Micro Structure(mặc định): Lấy đáy thấp nhất4nến (recentStopLow) trừ0.15 * ATRcho Long; hoặc đỉnh cao nhất4nến (recentStopHigh) cộng0.15 * ATRcho Short.Slow Fair Value: Lấy đườngslowValuetrừ0.15 * ATRcho Long, hoặc cộng0.15 * ATRcho Short.ATR Fixed: Đặt cách giá đóng cửa1.40 * ATR(close - 1.40 * ATRcho Long,close + 1.40 * ATRcho Short).
Sau đó bot kiểm tra bộ lọc Risk (longRisk = close - longStopCandidate hoặc shortRisk = shortStopCandidate - close):
- Khoảng cách SL phải nằm trong
[1.50, 12.0]điểm (minimumStopPointsđếnmaximumStopPoints). - Khoảng cách TP dự kiến (
risk * 1.55) phải đạt tối thiểu2.50điểm (minimumGrossTarget). Nếu không thỏa, tín hiệu bị hủy bỏ.
5.2. Cơ chế Take Profit, Break Even và Thoát lệnh
- Take Profit cố định theo R: Đặt tại
close + longRisk * 1.55(Long) hoặcclose - shortRisk * 1.55(Short). - Kiểm tra khớp lệnh nến sau (
validFill): Vì lệnh thị trường thường khớp ở giá mở cửa nến tiếp theo, bot tính lạiinitialFillRiskdựa trênstrategy.position_avg_price. NếuinitialFillRisk <= syminfo.mintickhoặc TP bị đảo ngược so với giá khớp thực tế, bot đóng vị thế ngay lập tức (INVALID NEXT-BAR FILL). - Break Even (mặc định tắt): Khi
useBreakEven = truevà lợi nhuận đạtcurrentR >= 1.0, bot dời SL vềfillPrice + 0.20(Long) hoặcfillPrice - 0.20(Short), chỉ dời theo hướng có lợi. - Thoát khi mất vùng giá trị (mặc định tắt): Khi
useMigrationFailureExit = true, nếu giá đóng cửa nằm sai phía so vớislowValuetrong2nến liên tiếp (failureCloses), bot chủ động đóng lệnh (FAIR VALUE ACCEPTANCE FAILED). - Giới hạn thời gian giữ lệnh (
useTimeExit = true): Nếutime_close >= entryTimestamp + 40 * 60000(sau 40 phút), bot đóng lệnh (MAXIMUM HOLD). - Đóng lệnh cuối buổi (
lunchFlatBar/finalFlatBar): Tự độngstrategy.close_alltrước giờ nghỉ trưa (11:25) và trước phiên ATC (14:25).
5.3. Bảng tổng hợp cơ chế bảo vệ vị thế
| Cơ chế bảo vệ | Trạng thái mặc định | Ngưỡng / Điều kiện kích hoạt | Hành động của Bot |
|---|---|---|---|
| Stop Loss cấu trúc | Bật (Micro Structure) | 1.50 – 12.0 điểm, đệm 0.15 * ATR | Gắn lệnh strategy.exit bảo vệ ngay khi vào lệnh |
| Take Profit | Bật | 1.55R, tối thiểu 2.50 điểm | Chốt lời giới hạn tại activeTarget |
| Kiểm tra khớp lệnh | Luôn bật | initialFillRisk <= mintick hoặc TP sai phía | Đóng ngay (INVALID NEXT-BAR FILL) |
| Break Even | Tắt (false) | currentR >= 1.0 | Dời SL về fillPrice ± 0.20 điểm |
| Phá vỡ vùng giá trị | Tắt (false) | 2 nến liên tiếp đóng sai phía Slow VWMA | Đóng lệnh (FAIR VALUE ACCEPTANCE FAILED) |
| Thời gian giữ lệnh | Bật (true) | Giữ lệnh quá 40 phút | Đóng lệnh (MAXIMUM HOLD) |
| Đóng phiên sáng/chiều | Bật (true) | Chạm mốc 11:25 hoặc 14:25 | strategy.close_all (VN30F1M CONTINUOUS SESSION FLAT) |
| Khóa lỗ ngày | Bật (true) | dailyClosedPnL <= -2.400.000 VND | Chặn toàn bộ lệnh mới trong ngày |
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 thời gian nội ngày như
1m,3mhoặc5m). - Nhấn vào tab Pine Editor ở phía dưới màn hình, chọn tạo mới (New -> Strategy) và xóa toàn bộ code mẫu mặc định.
- Sao chép toàn bộ mã nguồn Pine Script v6 ở Mục 1 và dán vào Pine Editor.
- Nhấn Save để lưu script, sau đó nhấn Add to chart để áp dụng chiến lược lên biểu đồ.
Cách đọc bảng chẩn đoán (Diagnostics Table)
Theo thiết kế gốc trong mã nguồn (// Confirmed-bar strategy. No dashboard. và // 10. No floating diagnostic table is displayed.), Bot CNPS64 V2 không vẽ bảng chẩn đoán nổi (table.new) để giữ biểu đồ sạch sẽ, tập trung hoàn toàn vào hành động giá.
Thay vào đó, bạn có thể theo dõi trực tiếp trạng thái hệ thống thông qua các thành phần hiển thị trên biểu đồ:
- Đường màu xanh ngọc (
Fast Volume-Weighted Fair Value): ĐườngFast VWMA (8)phản ánh vùng giá trị ngắn hạn đang dịch chuyển. - Đường màu cam (
Slow Volume-Weighted Fair Value): ĐườngSlow VWMA (21)đóng vai trò trục cân bằng trung hạn. - Đường màu xám (
Daily Continuous Session VWAP): Đường VWAP phiên liên tục (hiển thị khi bậtShow Session VWAP?). - Đường đỏ & xanh lá (
Active Stop Loss/Active Take Profit): Chỉ xuất hiện khi đang có vị thế mở (strategy.position_size != 0), giúp bạn quan sát trực tiếp mức cắt lỗ (bao gồm mức đã dời Break Even) và chốt lời hiện hành. - Nhãn tín hiệu
L/S: Tam giác xanh ngọc dưới nến (L) hoặc tam giác đỏ trên nến (S) đánh dấu chính xác cây nến xác nhận kích hoạt lệnh.
7. Cách thiết lập cảnh báo tín hiệu giao dịch (Alert)
Để nhận thông báo tự động qua ứng dụng TradingView, Telegram hoặc Webhook khi CNPS64 phát sinh tín hiệu:
- Trên biểu đồ đã gắn CNPS64 VALUE V2, nhấn nút Alert (biểu tượng đồng hồ báo thức) hoặc tổ hợp phím
Alt + A. - Ở mục Condition, chọn đúng chiến lược
CNPS64 VALUE MIGRATION V2 ACTIVE HYBRID - VN30F1M. - Ở ô Message, xóa nội dung mặc định và nhập chính xác biến:
{{strategy.order.alert_message}} - Đặt tên Alert, chọn kênh thông báo (Notify in app / Webhook URL) và nhấn Create.
Bảng thông điệp Alert của CNPS64
| Sự kiện | Lệnh kích hoạt trong code | Nội dung thông điệp (alert_message / alert_profit / alert_loss) |
|---|---|---|
| Vào lệnh Long | strategy.entry("CNPS64-L", ...) | 🟢 VÀO VỊ THẾ LONG (Active Value Migration) kèm Giá vào, SL dự kiến, TP dự kiến |
| Vào lệnh Short | strategy.entry("CNPS64-S", ...) | 🔴 VÀO VỊ THẾ SHORT (Active Value Migration) kèm Giá vào, SL dự kiến, TP dự kiến |
| Chốt lời Long / Short | strategy.exit(..., alert_profit=...) | 💰 CHỐT LỜI LONG (TP HIT) hoặc 💰 CHỐT LỜI SHORT (TP HIT) kèm Giá chốt |
| Cắt lỗ Long / Short | strategy.exit(..., alert_loss=...) | 🛑 CẮT LỖ LONG (SL HIT) hoặc 🛑 CẮT LỖ SHORT (SL HIT) kèm Giá cắt |
| Thoát hòa vốn (BE) | strategy.exit(..., alert_loss=...) | 🛡️ HÒA VỐN LONG (BE HIT) hoặc 🛡️ HÒA VỐN SHORT (BE HIT) (khi breakEvenActive = true) |
| 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 |
| Phá vỡ vùng giá trị | strategy.close(..., "FAIR VALUE ACCEPTANCE FAILED") | ⚡ ĐÓNG VỊ THẾ (Phá vỡ vùng giá trị) kèm Giá đóng |
| Hết thời gian giữ lệnh | strategy.close(..., "MAXIMUM HOLD") | ⏱️ ĐÓNG VỊ THẾ (Hết thời gian giữ lệnh tối đa) kèm Giá đóng |
| Đóng vị thế hết phiên | strategy.close_all(..., "VN30F1M CONTINUOUS SESSION FLAT") | ⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End) kèm Giá đóng |
Kết luận
CNPS64 Value Migration V2 là một chiến lược giao dịch VN30F1M linh hoạt nhưng kỷ luật, kết hợp 4 nhánh vào lệnh quanh cặp đường giá trị theo khối lượng (Fast VWMA & Slow VWMA) cùng cơ chế lọc rủi ro theo cấu trúc, giới hạn thời gian giữ lệnh và khóa lỗ ngày. Hệ thống đặc biệt phù hợp trong những phiên thị trường có dòng tiền luân chuyển rõ nét quanh các vùng giá trị và xuất hiện các nhịp hồi kiểm định hoặc bứt phá ngắn hạn.
Bạn có thể tham khảo thêm các hệ thống giao dịch khác trên hệ sinh thái Phái Sinh Online như Bot CNPS50 - Trend Analysis V2 và Bot CNPS49 - Daily Open.
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.





