Hướng Dẫn Sử Dụng Bot CNPS61 - Volatility Compression Release V1 cho VN30F1M
TradingviewBot CNPS61 Volatility Compression Release V1 nhận diện vùng nén biến động trên nến đã đóng, lọc breakout theo ATR/thân nến và xác nhận bằng Retest hoặc Follow-Through trên VN30F1M.

Mục lục
Trong giao dịch hợp đồng tương lai VN30F1M, thị trường thường xuyên trải qua các giai đoạn đi ngang biên độ hẹp (tích lũy/nén biến động) trước khi bùng nổ theo một hướng rõ ràng. Tuy nhiên, nếu giao dịch phá vỡ (breakout) một cách cảm tính, nhà đầu tư rất dễ mắc bẫy phá vỡ giả (false breakout), vào lệnh khi nến đã chạy quá xa làm tỷ lệ Risk/Reward kém, hoặc giữ lệnh quá lâu qua giờ nghỉ trưa và phiên ATC đầy rủi ro.
CNPS61 VOLATILITY COMPRESSION RELEASE V1 - VN30F1M (shorttitle: CNPS61 VCR V1) là chiến lược giao dịch tự động viết bằng Pine Script v6 trên TradingView, được thiết kế chuyên biệt để giải quyết bài toán nắm bắt cú bung biến động từ vùng nén giá có kiểm soát.
Những điểm nổi bật cốt lõi của Bot CNPS61:
- Đo lường nén biến động đa chiều (Closed-Bar): Xác định hộp nén hoàn toàn trên các nến đã đóng (
[1]), kết hợp thu hẹp biên độ giá so với lịch sử, co thắt ATR (Fast ATR / Slow ATR) và tùy chọn cạn kiệt khối lượng. - Cỗ máy trạng thái 4 bước (State Machine): Tách bạch giai đoạn nạp hộp nén, phát hiện nến breakout đạt chuẩn biên độ/thân nến, và chờ nến sau xác nhận bằng Retest biên hộp hoặc Follow-Through tiếp diễn.
- Quản trị rủi ro & thoát lệnh chủ động: Tích hợp bộ lọc khoảng cách SL (
1.5 – 10.0điểm), tỷ lệR:R >= 1.10, cắt lỗ sớm khi giá quay đầu vào trong hộp (Acceptance Failure Exit), giới hạn thời gian giữ lệnh tối đa (45phút) và tự động đóng vị thế trước giờ nghỉ trưa (11:25) lẫn trước ATC (14:25). - Bảo vệ tài khoản theo ngày: Ngừng mở vị thế mới nếu lỗ đã chốt trong ngày chạm ngưỡng
2,400,000 VND.
1. CNPS61 Volatility Compression Release V1 là gì?
CNPS61 VOLATILITY COMPRESSION RELEASE V1 là hệ thống giao dịch theo cơ chế nén biến động – giải phóng xung lượng (Volatility Compression Release) dành riêng cho khung thời gian trong ngày của VN30F1M. Chiến lược vận hành dựa trên 4 trụ cột kỹ thuật chính:
- Nhận diện vùng nén giá (Compression Window): Tìm kiếm các cụm
9nến liên tiếp có biên độ thu hẹp đáng kể so với đường cơ sở35nến và nằm trong giới hạn bội số ATR, đồng thời kiểm tra sự co thắt củaATR(7)so vớiATR(21). - Sàng lọc chất lượng nến phá vỡ (Breakout Quality): Chỉ công nhận cú phá vỡ khi nến đóng cửa vượt biên hộp tối thiểu
0.30điểm, có biên độ mở rộng hợp lý (0.70x – 2.80x ATR), thân nến đặc (>= 35%) và giá đóng cửa nằm gần cực trị theo đúng hướng phá vỡ. - Xác nhận chấp nhận giá (Entry Confirmation): Thay vì đuổi giá mù quáng, chế độ mặc định
Hybrid Retest / Follow-Throughyêu cầu nến tiếp theo chứng minh lực thị trường thông qua nhịp kiểm tra lại biên hộp thành công (Retest) hoặc đóng cửa vượt cực trị nến breakout (Follow-Through). - Kiểm soát rủi ro & phiên giao dịch VN30F1M: Chuẩn hóa khung giờ sáng/chiều theo múi giờ
Asia/Ho_Chi_Minh, giới hạn số lệnh/ngày, thời gian nghỉ (cooldown) sau khi thoát lệnh và cơ chế thoát lệnh khẩn cấp khi breakout thất bại.
Bảng thông số mặc định
| Nhóm thông số | Tên tham số trong code | Giá trị mặc định | Ý nghĩa |
|---|---|---|---|
| 01 - Trade Control | tradeDirection | "Both" | Chiều giao dịch (Both, Long, Short) |
contracts | 3 | Số hợp đồng mỗi lệnh | |
maximumTradesPerDay | 4 | Số lệnh tối đa trong ngày | |
cooldownBars | 3 | Số nến nghỉ sau khi đóng vị thế | |
oneTradePerDirection | false | Giới hạn tối đa 1 lệnh mỗi chiều/ngày | |
| 02 - Compression | compressionBars | 9 | Số nến quan sát tạo hộp nén |
baselineBars | 35 | Chu kỳ trung bình độ rộng hộp & volume | |
maximumRelativeWidth | 0.90 | Tỷ lệ tối đa Box Width / Average Box Width | |
maximumBoxATR | 6.0 | Độ rộng hộp tối đa theo bội số ATR(21) | |
minimumBoxPoints | 1.5 | Độ rộng hộp tối thiểu (điểm) | |
| 03 - Volatility | fastATRLength / slowATRLength | 7 / 21 | Chu kỳ ATR nhanh và ATR chậm |
maximumATRRatio | 1.10 | Tỷ lệ tối đa Fast ATR / Slow ATR | |
requireVolatilityContraction | true | Bắt buộc co thắt ATR khi nén | |
useDryVolume / dryVolumeRatio | false / 1.00 | Lọc khối lượng thấp khi nén | |
| 04 - Breakout | minimumBreakoutPoints | 0.30 | Mức đóng cửa vượt biên hộp tối thiểu (điểm) |
minimumExpansionATR / maximumExpansionATR | 0.70 / 2.80 | Biên độ nến breakout so với ATR(21) trước đó | |
minimumBreakBodyRatio | 0.35 | Tỷ lệ Thân nến / Biên độ tối thiểu | |
minimumBreakCloseLocation | 0.65 | Vị trí đóng cửa tối thiểu (tính từ đáy nến) | |
useBreakoutVolume / minimumBreakoutVolumeRatio | false / 1.10 | Lọc khối lượng đột biến khi breakout | |
| 05 - Entry | entryMode | "Hybrid Retest / Follow-Through" | Chế độ xác nhận vào lệnh |
maximumBoxAgeBars | 12 | Tuổi thọ tối đa của hộp nén chờ breakout (nến) | |
confirmationWindowBars | 7 | Số nến tối đa chờ xác nhận sau breakout | |
minimumConfirmBodyRatio | 0.20 | Tỷ lệ thân nến xác nhận tối thiểu | |
followThroughPoints | 0.30 | Mức đóng cửa vượt cực trị breakout (điểm) | |
retestTouchATR / maximumRetestPierceATR | 0.45 / 0.50 | Bán kính chạm biên ngoài & độ xuyên tối đa trong hộp | |
retestHoldPoints / invalidationClosePoints | 0.10 / 0.30 | Ngưỡng giữ ngoài biên & ngưỡng hủy breakout | |
| 06 - Filters | useTrendFilter / trendEMALength / trendSlopeBars | false / 34 / 5 | Bộ lọc xu hướng EMA và độ dốc |
useVWAPFilter | false | Bộ lọc vị thế so với Session VWAP | |
| 07 - Risk | stopMode | "Breakout / Retest Structure" | Cách đặt Stop Loss |
stopBufferATR / fixedStopATR | 0.15 / 1.60 | Khoảng đệm SL theo ATR / SL cố định | |
minimumStopPoints / maximumStopPoints | 1.50 / 10.0 | Khoảng cách SL tối thiểu – tối đa (điểm) | |
| 08 - Target | targetMode / takeProfitR | "Fixed R" / 1.60 | Chế độ TP và hệ số R mục tiêu |
boxProjection | 1.00 | Hệ số phóng chiếu độ rộng hộp | |
minimumRewardRisk / minimumGrossTarget | 1.10 / 2.50 | Tỷ lệ R:R tối thiểu & TP gộp tối thiểu (điểm) | |
| 09 - Exits | useAcceptanceFailureExit / failureCloses | true / 2 | Thoát khi có 2 nến đóng quay lại trong hộp |
useBreakEven / breakEvenAtR / breakEvenOffset | false / 1.00 / 0.20 | Cơ chế dời SL về hòa vốn | |
useTimeExit / maximumHoldMinutes | true / 45 | Thời gian giữ lệnh tối đa (phút) | |
| 10 - Daily Protection | useDailyLossGuard / maximumDailyLossVND | true / 2,400,000 | Chặn vào lệnh mới khi lỗ chốt ngày vượt ngưỡng |
| 11 - Session | morningEntry / afternoonEntry | "0910-1120" / "1305-1415" | Khung giờ cho phép vào lệnh sáng/chiều |
closeBeforeLunch / lunchFlatMinute | true / 25 | Đóng toàn bộ vị thế trước 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 CNPS61 Volatility Compression Release 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
// CNPS61 - Original VN30F1M strategy research.
// Volatility Compression Release: closed-bar compression -> range breakout
// -> accepted continuation or boundary retest. No dashboard.
strategy(title="CNPS61 VOLATILITY COMPRESSION RELEASE V1 - VN30F1M", shorttitle="CNPS61 VCR V1", 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=150)
// ============================================================================
// SECTION 1: TRADE CONTROL
// ============================================================================
tradeDirection = input.string("Both", title="Trade Direction", options=["Both", "Long", "Short"], group="01 - Trade Control")
contracts = input.int(3, title="Contracts Per Trade", minval=1, maxval=20, group="01 - Trade Control")
maximumTradesPerDay = input.int(4, title="Maximum Trades Per Day", minval=1, maxval=20, group="01 - Trade Control")
cooldownBars = input.int(3, title="Cooldown After Position Exit (bars)", minval=0, maxval=100, group="01 - Trade Control")
oneTradePerDirection = input.bool(false, title="Only One Trade Per Direction Per Day?", group="01 - Trade Control")
// ============================================================================
// SECTION 2: COMPRESSION WINDOW
// ============================================================================
compressionBars = input.int(9, title="Compression Observation Bars", minval=4, maxval=60, group="02 - Compression")
baselineBars = input.int(35, title="Range Baseline Lookback", minval=10, maxval=200, group="02 - Compression")
maximumRelativeWidth = input.float(0.90, title="Maximum Box Width / Average Box Width", minval=0.20, maxval=1.50, step=0.05, group="02 - Compression")
maximumBoxATR = input.float(6.0, title="Maximum Compression Box Width x ATR", minval=1.0, maxval=20.0, step=0.5, group="02 - Compression")
minimumBoxPoints = input.float(1.5, title="Minimum Compression Box Width (points)", minval=0.0, step=0.5, group="02 - Compression")
// ============================================================================
// SECTION 3: VOLATILITY CONTRACTION
// ============================================================================
fastATRLength = input.int(7, title="Fast ATR Length", minval=2, maxval=50, group="03 - Volatility")
slowATRLength = input.int(21, title="Slow ATR Length", minval=5, maxval=100, group="03 - Volatility")
maximumATRRatio = input.float(1.10, title="Maximum Fast ATR / Slow ATR", minval=0.30, maxval=2.00, step=0.05, group="03 - Volatility")
requireVolatilityContraction = input.bool(true, title="Require ATR Contraction?", group="03 - Volatility")
useDryVolume = input.bool(false, title="Require Low Volume During Compression?", group="03 - Volatility")
dryVolumeRatio = input.float(1.00, title="Maximum Compression Volume / Baseline", minval=0.20, maxval=2.00, step=0.05, group="03 - Volatility")
// ============================================================================
// SECTION 4: BREAKOUT QUALITY
// ============================================================================
minimumBreakoutPoints = input.float(0.30, title="Minimum Close Beyond Compression Box (points)", minval=0.0, step=0.1, group="04 - Breakout")
minimumExpansionATR = input.float(0.70, title="Minimum Breakout Candle Range x Prior ATR", minval=0.10, maxval=5.0, step=0.05, group="04 - Breakout")
maximumExpansionATR = input.float(2.80, title="Maximum Breakout Candle Range x Prior ATR", minval=0.50, maxval=10.0, step=0.10, group="04 - Breakout")
minimumBreakBodyRatio = input.float(0.35, title="Minimum Breakout Candle Body / Range", minval=0.0, maxval=1.0, step=0.05, group="04 - Breakout")
minimumBreakCloseLocation = input.float(0.65, title="Minimum Breakout Close Location", minval=0.50, maxval=0.95, step=0.05, group="04 - Breakout")
useBreakoutVolume = input.bool(false, title="Require Breakout Relative Volume?", group="04 - Breakout")
minimumBreakoutVolumeRatio = input.float(1.10, title="Minimum Breakout Volume / Prior Average", minval=0.10, maxval=5.0, step=0.05, group="04 - Breakout")
// ============================================================================
// SECTION 5: ENTRY MODE / SETUP LIFETIME
// ============================================================================
entryMode = input.string("Hybrid Retest / Follow-Through", title="Entry Confirmation Mode", options=["Hybrid Retest / Follow-Through", "Breakout Close", "Retest Only", "Follow-Through Only"], group="05 - Entry")
maximumBoxAgeBars = input.int(12, title="Maximum Bars To Break Compression Box", minval=1, maxval=100, group="05 - Entry")
confirmationWindowBars = input.int(7, title="Maximum Bars After Breakout", minval=1, maxval=30, group="05 - Entry")
minimumConfirmBodyRatio = input.float(0.20, title="Minimum Entry Candle Body / Range", minval=0.0, maxval=1.0, step=0.05, group="05 - Entry")
followThroughPoints = input.float(0.30, title="Close Beyond Breakout Extreme (points)", minval=0.0, step=0.1, group="05 - Entry")
retestTouchATR = input.float(0.45, title="Retest Touch Radius Outside Box x ATR", minval=0.05, maxval=3.0, step=0.05, group="05 - Entry")
maximumRetestPierceATR = input.float(0.50, title="Maximum Retest Wick Inside Box x ATR", minval=0.05, maxval=3.0, step=0.05, group="05 - Entry")
retestHoldPoints = input.float(0.10, title="Retest Close Beyond Box Boundary (points)", minval=0.0, step=0.1, group="05 - Entry")
invalidationClosePoints = input.float(0.30, title="Cancel Breakout When Price Closes Inside Box", minval=0.0, step=0.1, group="05 - Entry")
// ============================================================================
// SECTION 6: TREND ALIGNMENT FILTERS
// ============================================================================
useTrendFilter = input.bool(false, title="Require Directional EMA Trend?", group="06 - Filters")
trendEMALength = input.int(34, title="Trend EMA Length", minval=5, maxval=200, group="06 - Filters")
trendSlopeBars = input.int(5, title="Trend EMA Slope Lookback", minval=1, maxval=50, group="06 - Filters")
minimumSlopeATR = input.float(0.00, title="Minimum EMA Slope In Signal Direction / ATR", minval=-1.0, maxval=3.0, step=0.05, group="06 - Filters")
useVWAPFilter = input.bool(false, title="Trade Only On Correct Side Of Session VWAP?", group="06 - Filters")
// ============================================================================
// SECTION 7: STOP LOSS
// ============================================================================
stopMode = input.string("Breakout / Retest Structure", title="Stop Location", options=["Breakout / Retest Structure", "Opposite Box Edge", "ATR Fixed"], group="07 - Risk")
stopBufferATR = input.float(0.15, title="Stop Buffer Beyond Structure x ATR", minval=0.0, maxval=2.0, step=0.05, group="07 - Risk")
fixedStopATR = input.float(1.60, title="ATR Fixed Stop x ATR", minval=0.25, maxval=6.0, step=0.1, group="07 - Risk")
minimumStopPoints = input.float(1.50, title="Minimum Stop Distance (points)", minval=0.1, step=0.5, group="07 - Risk")
maximumStopPoints = input.float(10.0, title="Maximum Stop Distance (points)", minval=0.5, step=0.5, group="07 - Risk")
// ============================================================================
// SECTION 8: TARGET MANAGEMENT
// ============================================================================
targetMode = input.string("Fixed R", title="Take Profit Mode", options=["Fixed R", "Box Width Projection"], group="08 - Target")
takeProfitR = input.float(1.60, title="Take Profit Multiple (R)", minval=0.25, maxval=8.0, step=0.1, group="08 - Target")
boxProjection = input.float(1.00, title="Box Width Projection Multiple", minval=0.20, maxval=5.0, step=0.10, group="08 - Target")
minimumRewardRisk = input.float(1.10, title="Minimum Reward / Risk", minval=0.50, maxval=5.0, step=0.05, group="08 - Target")
minimumGrossTarget = input.float(2.50, title="Minimum Gross Target (points)", minval=0.0, step=0.5, group="08 - Target")
// ============================================================================
// SECTION 9: POSITION EXITS
// ============================================================================
useAcceptanceFailureExit = input.bool(true, title="Exit When Price Re-Accepts Inside Compression Box?", group="09 - Exits")
failureCloses = input.int(2, title="Consecutive Closes Inside Box", minval=1, maxval=5, group="09 - Exits")
useBreakEven = input.bool(false, title="Use Break Even?", group="09 - Exits")
breakEvenAtR = input.float(1.00, title="Break Even Trigger (R)", minval=0.25, maxval=5.0, step=0.25, group="09 - Exits")
breakEvenOffset = input.float(0.20, title="Break Even Offset (points)", minval=0.0, step=0.1, group="09 - Exits")
useTimeExit = input.bool(true, title="Use Maximum Hold Minutes?", group="09 - Exits")
maximumHoldMinutes = input.int(45, title="Maximum Hold Minutes", minval=5, maxval=240, group="09 - Exits")
// ============================================================================
// SECTION 10: DAILY RISK GUARD
// ============================================================================
useDailyLossGuard = input.bool(true, title="Block New Entries After Daily Closed Loss?", group="10 - Daily Protection")
maximumDailyLossVND = input.float(2400000, title="Daily Closed Loss Threshold (VND)", minval=100000, step=100000, group="10 - Daily Protection")
// ============================================================================
// SECTION 11: VN30F1M TRADING SESSION
// ============================================================================
string timezoneVN = "Asia/Ho_Chi_Minh"
morningEntry = input.session("0910-1120", title="Morning Entry Window", group="11 - Session")
afternoonEntry = input.session("1305-1415", title="Afternoon Entry Window", group="11 - Session")
closeBeforeLunch = input.bool(true, title="Force Flat Before Lunch?", group="11 - Session")
lunchFlatMinute = input.int(25, title="Lunch Force Flat Minute (11:xx)", minval=15, maxval=30, group="11 - Session")
finalFlatHour = input.int(14, title="End Of Day Flat Hour", minval=0, maxval=23, group="11 - Session")
finalFlatMinute = input.int(25, title="End Of Day Flat Minute", minval=0, maxval=59, group="11 - Session")
// ============================================================================
// SECTION 12: DISPLAY - CLEAN CHART / NO TABLE
// ============================================================================
showCompressionBox = input.bool(true, title="Show Armed Compression Box?", group="12 - Display")
showVWAP = input.bool(false, title="Show Session VWAP?", group="12 - Display")
showBreakoutMarkers = input.bool(false, title="Show Confirmed Breakouts?", group="12 - Display")
showEntryMarkers = input.bool(true, title="Show Long / Short Entries?", group="12 - Display")
showTradeLevels = input.bool(true, title="Show Active Stop / Target?", group="12 - Display")
// ============================================================================
// SECTION 13: TIME 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 morningBegins = continuousMorning and not continuousMorning[1]
bool afternoonBegins = continuousAfternoon and not continuousAfternoon[1]
bool morningEntryBar = not na(time(timeframe.period, morningEntry + ":23456", timezoneVN))
bool afternoonEntryBar = not na(time(timeframe.period, afternoonEntry + ":23456", timezoneVN))
bool entrySession = (morningEntryBar or afternoonEntryBar) and continuousSession
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 beforeCutoffs = (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 endFlatBar = (barstate.isconfirmed and continuousAfternoon and minuteOpen < finalCutoff and minuteClose >= finalCutoff)
var int barsSinceSessionStart = 0
if newTradingDay or morningBegins or afternoonBegins
barsSinceSessionStart := continuousSession ? 1 : 0
else if continuousSession
barsSinceSessionStart += 1
else
barsSinceSessionStart := 0
// ============================================================================
// SECTION 14: VOLATILITY / VOLUME / CANDLE METRICS
// ============================================================================
float atrFast = ta.atr(fastATRLength)
float atrSlow = ta.atr(slowATRLength)
float trendEMA = ta.ema(close, trendEMALength)
float candleRange = math.max(high - low, syminfo.mintick)
float candleBodyRatio = math.abs(close - open) / candleRange
float closeLocation = (close - low) / candleRange
float emaSlopeATR = not na(atrSlow) and atrSlow > 0 ? (trendEMA - trendEMA[trendSlopeBars]) / atrSlow : 0.0
float volumeAverage = ta.sma(volume, baselineBars)
float volumeAveragePrior = volumeAverage[1]
bool bullishBreakCandle = (close > open and candleBodyRatio >= minimumBreakBodyRatio and closeLocation >= minimumBreakCloseLocation)
bool bearishBreakCandle = (close < open and candleBodyRatio >= minimumBreakBodyRatio and closeLocation <= 1.0 - minimumBreakCloseLocation)
bool bullishConfirmCandle = (close > open and candleBodyRatio >= minimumConfirmBodyRatio and closeLocation >= 0.50)
bool bearishConfirmCandle = (close < open and candleBodyRatio >= minimumConfirmBodyRatio and closeLocation <= 0.50)
bool longTrendOK = not useTrendFilter or (close > trendEMA and emaSlopeATR >= minimumSlopeATR)
bool shortTrendOK = not useTrendFilter or (close < trendEMA and emaSlopeATR <= -minimumSlopeATR)
bool breakoutVolumeOK = (not useBreakoutVolume or (not na(volumeAveragePrior) and volumeAveragePrior > 0 and volume >= volumeAveragePrior * minimumBreakoutVolumeRatio))
// ============================================================================
// SECTION 15: SESSION-ANCHORED VWAP
// ============================================================================
var float cumulativePV = 0.0
var float cumulativeVolume = 0.0
if newTradingDay
cumulativePV := 0.0
cumulativeVolume := 0.0
if continuousSession and barstate.isconfirmed and not na(volume) and volume > 0
cumulativePV += hlc3 * volume
cumulativeVolume += volume
float sessionVWAP = cumulativeVolume > 0 ? cumulativePV / cumulativeVolume : na
bool longVWAPOK = not useVWAPFilter or (not na(sessionVWAP) and close > sessionVWAP)
bool shortVWAPOK = not useVWAPFilter or (not na(sessionVWAP) and close < sessionVWAP)
// ============================================================================
// SECTION 16: HISTORICAL COMPRESSION MEASUREMENT - EXCLUDE CURRENT BAR
// ============================================================================
float rollingWindowHigh = ta.highest(high, compressionBars)
float rollingWindowLow = ta.lowest(low, compressionBars)
float rollingWindowWidth = rollingWindowHigh - rollingWindowLow
float historicalWidthBaseline = ta.sma(rollingWindowWidth, baselineBars)
float candidateBoxHigh = rollingWindowHigh[1]
float candidateBoxLow = rollingWindowLow[1]
float candidateBoxWidth = candidateBoxHigh - candidateBoxLow
float previousBaselineWidth = historicalWidthBaseline[1]
float previousSlowATR = atrSlow[1]
float previousFastATR = atrFast[1]
float priorCompressionVolume = ta.sma(volume, compressionBars)[1]
float priorBaselineVolume = volumeAverage[1]
bool enoughSessionHistory = (continuousSession and barsSinceSessionStart > compressionBars)
bool compressedWidth = (not na(candidateBoxWidth) and not na(previousBaselineWidth) and previousBaselineWidth > 0 and candidateBoxWidth >= minimumBoxPoints and candidateBoxWidth <= previousBaselineWidth * maximumRelativeWidth and not na(previousSlowATR) and previousSlowATR > 0 and candidateBoxWidth <= previousSlowATR * maximumBoxATR)
bool compressedATR = (not requireVolatilityContraction or (not na(previousFastATR) and not na(previousSlowATR) and previousSlowATR > 0 and previousFastATR / previousSlowATR <= maximumATRRatio))
bool compressionVolumeOK = (not useDryVolume or (not na(priorCompressionVolume) and not na(priorBaselineVolume) and priorBaselineVolume > 0 and priorCompressionVolume <= priorBaselineVolume * dryVolumeRatio))
bool compressionQualified = (enoughSessionHistory and compressedWidth and compressedATR and compressionVolumeOK and barstate.isconfirmed)
// ============================================================================
// SECTION 17: DAILY CONTROL / POSITION STATE
// ============================================================================
var int tradesToday = 0
var int seenClosedTrades = 0
var int lastExitBar = na
var int lastOrderBar = na
var float dayStartingNetProfit = na
var bool tradedLongToday = false
var bool tradedShortToday = false
if newTradingDay
tradesToday := 0
dayStartingNetProfit := strategy.netprofit
tradedLongToday := false
tradedShortToday := 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 tradedLongToday)
bool allowShort = tradeDirection != "Long" and (not oneTradePerDirection or not tradedShortToday)
float dailyClosedPnL = strategy.netprofit - nz(dayStartingNetProfit, strategy.netprofit)
bool tradeCountOK = tradesToday < maximumTradesPerDay
bool cooldownOK = na(lastExitBar) or bar_index - lastExitBar > cooldownBars
bool oncePerBar = na(lastOrderBar) or lastOrderBar != bar_index
bool dailyLossOK = not useDailyLossGuard or dailyClosedPnL > -maximumDailyLossVND
bool commonEntryOK = (flat and entrySession and beforeCutoffs and tradeCountOK and cooldownOK and dailyLossOK and oncePerBar and barstate.isconfirmed)
// ============================================================================
// SECTION 18: COMPRESSION / BREAKOUT STATE MACHINE
// ============================================================================
// State 0: No valid compression box.
// State 1: Box armed, waiting for first accepted breakout.
// State 2: Upside breakout detected, awaiting later-bar confirmation.
// State -2: Downside breakout detected, awaiting later-bar confirmation.
// ============================================================================
var int setupState = 0
var float boxHigh = na
var float boxLow = na
var float boxWidth = na
var int boxArmedBar = na
var int breakoutBar = na
var float breakoutHigh = na
var float breakoutLow = na
var float breakoutBoundary = na
bool breakoutLongMarker = false
bool breakoutShortMarker = false
bool rawLong = false
bool rawShort = false
float entryStopAnchor = na
if newTradingDay or morningBegins or afternoonBegins or lunchFlatBar or endFlatBar
setupState := 0
boxHigh := na
boxLow := na
boxWidth := na
boxArmedBar := na
breakoutBar := na
// ============================================================================
// SECTION 19: ARM A COMPLETED COMPRESSION BOX
// ============================================================================
if (setupState == 0 and flat and entrySession and beforeCutoffs and compressionQualified and tradeCountOK and dailyLossOK)
boxHigh := candidateBoxHigh
boxLow := candidateBoxLow
boxWidth := candidateBoxWidth
boxArmedBar := bar_index
setupState := 1
// ============================================================================
// SECTION 20: CHECK FIRST BREAKOUT OF ARMED BOX
// ============================================================================
if setupState == 1 and barstate.isconfirmed
bool boxExpired = bar_index - boxArmedBar > maximumBoxAgeBars
if boxExpired or not entrySession or not beforeCutoffs
setupState := 0
else
bool acceptableExpansion = (not na(previousSlowATR) and previousSlowATR > 0 and candleRange >= previousSlowATR * minimumExpansionATR and candleRange <= previousSlowATR * maximumExpansionATR)
bool upperBreak = (close > boxHigh + minimumBreakoutPoints and close[1] <= boxHigh + minimumBreakoutPoints and bullishBreakCandle and acceptableExpansion and breakoutVolumeOK)
bool lowerBreak = (close < boxLow - minimumBreakoutPoints and close[1] >= boxLow - minimumBreakoutPoints and bearishBreakCandle and acceptableExpansion and breakoutVolumeOK)
if upperBreak and allowLong and longTrendOK and longVWAPOK
breakoutBar := bar_index
breakoutHigh := high
breakoutLow := low
breakoutBoundary := boxHigh
breakoutLongMarker := true
if entryMode == "Breakout Close"
rawLong := true
entryStopAnchor := math.min(boxHigh, low)
setupState := 0
else
setupState := 2
else if lowerBreak and allowShort and shortTrendOK and shortVWAPOK
breakoutBar := bar_index
breakoutHigh := high
breakoutLow := low
breakoutBoundary := boxLow
breakoutShortMarker := true
if entryMode == "Breakout Close"
rawShort := true
entryStopAnchor := math.max(boxLow, high)
setupState := 0
else
setupState := -2
// ============================================================================
// SECTION 21: ACCEPTED UPSIDE BREAKOUT / RETEST / FOLLOW-THROUGH
// ============================================================================
if setupState == 2 and barstate.isconfirmed and bar_index > breakoutBar
bool expired = bar_index - breakoutBar > confirmationWindowBars
bool failed = close < boxHigh - invalidationClosePoints
if expired or failed or not entrySession or not beforeCutoffs
setupState := 0
else
bool retestHeld = (not na(atrSlow) and atrSlow > 0 and low <= boxHigh + atrSlow * retestTouchATR and low >= boxHigh - atrSlow * maximumRetestPierceATR and close >= boxHigh + retestHoldPoints and bullishConfirmCandle)
bool continuationConfirmed = (close > breakoutHigh + followThroughPoints and bullishConfirmCandle and close > boxHigh + retestHoldPoints)
bool acceptRetest = entryMode != "Follow-Through Only" and retestHeld
bool acceptFollow = entryMode != "Retest Only" and continuationConfirmed
if (acceptRetest or acceptFollow) and longTrendOK and longVWAPOK
rawLong := true
entryStopAnchor := acceptRetest ? math.min(boxHigh, low, breakoutLow) : math.min(boxHigh, breakoutLow)
setupState := 0
// ============================================================================
// SECTION 22: ACCEPTED DOWNSIDE BREAKOUT / RETEST / FOLLOW-THROUGH
// ============================================================================
if setupState == -2 and barstate.isconfirmed and bar_index > breakoutBar
bool expired = bar_index - breakoutBar > confirmationWindowBars
bool failed = close > boxLow + invalidationClosePoints
if expired or failed or not entrySession or not beforeCutoffs
setupState := 0
else
bool retestHeld = (not na(atrSlow) and atrSlow > 0 and high >= boxLow - atrSlow * retestTouchATR and high <= boxLow + atrSlow * maximumRetestPierceATR and close <= boxLow - retestHoldPoints and bearishConfirmCandle)
bool continuationConfirmed = (close < breakoutLow - followThroughPoints and bearishConfirmCandle and close < boxLow - retestHoldPoints)
bool acceptRetest = entryMode != "Follow-Through Only" and retestHeld
bool acceptFollow = entryMode != "Retest Only" and continuationConfirmed
if (acceptRetest or acceptFollow) and shortTrendOK and shortVWAPOK
rawShort := true
entryStopAnchor := acceptRetest ? math.max(boxLow, high, breakoutHigh) : math.max(boxLow, breakoutHigh)
setupState := 0
// ============================================================================
// SECTION 23: STOP AND TARGET VALIDATION
// ============================================================================
float longStopStructure = stopMode == "Opposite Box Edge" ? boxLow : entryStopAnchor
float shortStopStructure = stopMode == "Opposite Box Edge" ? boxHigh : entryStopAnchor
float candidateLongStop = (not na(atrSlow) and atrSlow > 0 ? math.round_to_mintick(stopMode == "ATR Fixed" ? close - fixedStopATR * atrSlow : longStopStructure - stopBufferATR * atrSlow) : na)
float candidateShortStop = (not na(atrSlow) and atrSlow > 0 ? math.round_to_mintick(stopMode == "ATR Fixed" ? close + fixedStopATR * atrSlow : shortStopStructure + stopBufferATR * atrSlow) : na)
float longRisk = close - candidateLongStop
float shortRisk = candidateShortStop - close
float targetLong = (targetMode == "Box Width Projection" ? math.round_to_mintick(boxHigh + boxWidth * boxProjection) : math.round_to_mintick(close + longRisk * takeProfitR))
float targetShort = (targetMode == "Box Width Projection" ? math.round_to_mintick(boxLow - boxWidth * boxProjection) : math.round_to_mintick(close - shortRisk * takeProfitR))
float longReward = targetLong - close
float shortReward = close - targetShort
bool longRiskOK = not na(longRisk) and longRisk >= minimumStopPoints and longRisk <= maximumStopPoints
bool shortRiskOK = not na(shortRisk) and shortRisk >= minimumStopPoints and shortRisk <= maximumStopPoints
bool longRewardOK = longRiskOK and not na(longReward) and longReward >= minimumGrossTarget and longReward / longRisk >= minimumRewardRisk
bool shortRewardOK = shortRiskOK and not na(shortReward) and shortReward >= minimumGrossTarget and shortReward / shortRisk >= minimumRewardRisk
bool finalLong = rawLong and allowLong and longTrendOK and longVWAPOK and longRewardOK and commonEntryOK
bool finalShort = rawShort and allowShort and shortTrendOK and shortVWAPOK and shortRewardOK and commonEntryOK and not finalLong
// ============================================================================
// SECTION 24: ACTIVE POSITION STATE
// ============================================================================
var float activeStop = na
var float activeTarget = na
var float actualEntryPrice = na
var float initialFillRisk = na
var float activeBreakoutBoundary = na
var int actualEntryBar = na
var int acceptanceFailureCount = 0
var bool breakEvenActive = false
// ============================================================================
// SECTION 25: LONG ENTRY AND INITIAL PROTECTION
// ============================================================================
if finalLong
activeStop := candidateLongStop
activeTarget := targetLong
actualEntryPrice := na
initialFillRisk := na
actualEntryBar := na
activeBreakoutBoundary := boxHigh
acceptanceFailureCount := 0
breakEvenActive := false
strategy.entry("CNPS61-L", strategy.long, comment="VOLATILITY RELEASE LONG", alert_message="🟢 VÀO VỊ THẾ LONG (Volatility Compression Release)\\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("CNPS61-L-X", from_entry="CNPS61-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
tradedLongToday := true
lastOrderBar := bar_index
setupState := 0
// ============================================================================
// SECTION 26: SHORT ENTRY AND INITIAL PROTECTION
// ============================================================================
else if finalShort
activeStop := candidateShortStop
activeTarget := targetShort
actualEntryPrice := na
initialFillRisk := na
actualEntryBar := na
activeBreakoutBoundary := boxLow
acceptanceFailureCount := 0
breakEvenActive := false
strategy.entry("CNPS61-S", strategy.short, comment="VOLATILITY RELEASE SHORT", alert_message="🔴 VÀO VỊ THẾ SHORT (Volatility Compression Release)\\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("CNPS61-S-X", from_entry="CNPS61-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
tradedShortToday := true
lastOrderBar := bar_index
setupState := 0
// ============================================================================
// SECTION 27: FILL VALIDATION / 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(actualEntryBar) or actualEntryBar != fillBar
actualEntryBar := fillBar
actualEntryPrice := 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 ? "CNPS61-L" : "CNPS61-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 openR = (inLong ? close - fillPrice : fillPrice - close) / initialFillRisk
if useBreakEven and openR >= 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("CNPS61-L-X", from_entry="CNPS61-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("CNPS61-S-X", from_entry="CNPS61-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 28: BREAKOUT FAILURE / TIME EXIT
// ============================================================================
if strategy.position_size != 0 and strategy.opentrades > 0 and barstate.isconfirmed
bool failedAcceptance = (inLong ? close < activeBreakoutBoundary - invalidationClosePoints : close > activeBreakoutBoundary + invalidationClosePoints)
acceptanceFailureCount := failedAcceptance ? acceptanceFailureCount + 1 : 0
if useAcceptanceFailureExit and acceptanceFailureCount >= failureCloses
strategy.close(inLong ? "CNPS61-L" : "CNPS61-S", comment="COMPRESSION BREAKOUT FAILED", alert_message="⚡ ĐÓNG VỊ THẾ (Phá vỡ 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 ? "CNPS61-L" : "CNPS61-S", comment="MAX HOLD MINUTES", 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 29: LUNCH / BEFORE ATC FORCE FLAT
// ============================================================================
if (lunchFlatBar or endFlatBar) 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 30: CLEAR CLOSED POSITION STATE
// ============================================================================
if flat and not finalLong and not finalShort
activeStop := na
activeTarget := na
actualEntryPrice := na
initialFillRisk := na
activeBreakoutBoundary := na
actualEntryBar := na
acceptanceFailureCount := 0
breakEvenActive := false
// ============================================================================
// SECTION 31: CLEAN CHART PLOTS - NO DASHBOARD
// ============================================================================
plot(showCompressionBox and setupState != 0 ? boxHigh : na, title="Compression Box High", color=color.new(color.teal, 20), linewidth=2, style=plot.style_linebr)
plot(showCompressionBox and setupState != 0 ? boxLow : na, title="Compression Box Low", color=color.new(color.red, 20), linewidth=2, style=plot.style_linebr)
plot(showVWAP ? sessionVWAP : na, title="Continuous Session VWAP", color=color.orange, linewidth=1, style=plot.style_linebr)
plot(showTradeLevels and strategy.position_size != 0 ? activeStop : na, title="Active Structural Stop", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showTradeLevels and strategy.position_size != 0 ? activeTarget : na, title="Active Profit Target", color=color.green, linewidth=2, style=plot.style_linebr)
// ============================================================================
// SECTION 32: SIGNAL MARKERS
// ============================================================================
plotshape(showBreakoutMarkers and breakoutLongMarker, title="Compression Upside Breakout", style=shape.circle, location=location.belowbar, color=color.new(color.teal, 45), size=size.tiny)
plotshape(showBreakoutMarkers and breakoutShortMarker, title="Compression Downside Breakout", style=shape.circle, location=location.abovebar, color=color.new(color.red, 45), size=size.tiny)
plotshape(showEntryMarkers and finalLong, title="CNPS61 Long", style=shape.triangleup, location=location.belowbar, text="L", textcolor=color.white, color=color.teal, size=size.small)
plotshape(showEntryMarkers and finalShort, title="CNPS61 Short", style=shape.triangledown, location=location.abovebar, text="S", textcolor=color.white, color=color.red, size=size.small)
// ============================================================================
// CNPS61 V1: BACKTEST ASSUMPTIONS
// ============================================================================
// 1. Compression uses ONLY completed earlier candles ([1] bounds).
// 2. A new squeeze can break out on the current confirmed candle.
// 3. Retest / follow-through entries require a LATER candle.
// 4. No order book, future bars, lookahead or floating diagnostic table.
// 5. Market entries normally fill after the signal close.
// 6. The protective bracket is fixed at signal-close-based levels.
// 7. Realized R differs when the next-bar fill differs from signal close.
// 8. The realized daily-loss guard blocks NEW entries, not open losses.
// 9. Simulated zero strategy margin is not real futures margin.
// 10. No TradingView compilation or profitability claim is implied.
// ============================================================================
2. Những khái niệm kỹ thuật cốt lõi trong CNPS61
2.1. Đo lường vùng nén biến động trên nến đã đóng (Closed-Bar Compression)
Trong SECTION 16, bot không lấy đỉnh/đáy của nến đang chạy mà sử dụng hoàn toàn dữ liệu từ nến đã đóng liền trước ([1]):
candidateBoxHigh = ta.highest(high, 9)[1]vàcandidateBoxLow = ta.lowest(low, 9)[1], tạo thành độ rộng hộpcandidateBoxWidth.- Độ rộng hộp nén phải đồng thời thỏa mãn:
- Tối thiểu
1.5điểm (minimumBoxPoints) để tránh nhiễu quá nhỏ. - Không vượt quá
0.90lần đường cơ sởhistoricalWidthBaseline[1](trung bình động 35 nến của độ rộng hộp 9 nến). - Không vượt quá
6.0lầnatrSlow[1](ATR(21)).
- Tối thiểu
- Đồng thời,
compressedATRkiểm tra sự co thắt biến động ngắn hạn:atrFast[1] / atrSlow[1] <= 1.10(ATR(7) / ATR(21)). Phiên cũng phải tích lũy đủ lịch sử (barsSinceSessionStart > 9).
2.2. Chuẩn hóa chất lượng nến Breakout & Bộ lọc xu hướng
Để tránh các cú phá vỡ yếu ớt hoặc râu nến quét thanh khoản, SECTION 14 và SECTION 20 tính toán:
candleBodyRatio = math.abs(close - open) / candleRange: Thân nến breakout phải chiếm tối thiểu35%biên độ nến.closeLocation = (close - low) / candleRange: Nến tăng breakout phải đóng ở vùng65%phía trên (>= 0.65); nến giảm breakout phải đóng ở vùng35%phía dưới (<= 0.35).acceptableExpansion: Biên độ nến breakout phải nằm trong khoảng0.70đến2.80lầnatrSlow[1](vừa đủ xung lượng nhưng không bị quá giãn).- Ngoài ra, người dùng có thể bật thêm bộ lọc EMA(34) kèm độ dốc (
trendSlopeBars = 5) và Session VWAP (cumulativePV / cumulativeVolumereset mỗi ngày giao dịch mới).
2.3. Xác nhận Retest và Follow-Through sau Breakout
Khi chế độ mặc định "Hybrid Retest / Follow-Through" được chọn, nến breakout chỉ đưa bot từ trạng thái 1 sang 2 (tăng) hoặc -2 (giảm). Trên các nến sau đó (bar_index > breakoutBar), bot kiểm tra 2 kịch bản vào lệnh hợp lệ:
- Retest (
retestHeld): Giá lùi về sát biên hộp trong bán kính0.45 * atrSlowbên ngoài hộp, phần râu nến không đâm ngược vào trong hộp quá0.50 * atrSlow, sau đó đóng cửa giữ ngoài biên ít nhất0.10điểm với nến xác nhận cùng chiều (candleBodyRatio >= 0.20). - Follow-Through (
continuationConfirmed): Giá đóng cửa bứt phá tiếp vượt cực trị của chính nến breakout (breakoutHighhoặcbreakoutLow) ít nhất0.30điểm, kèm điều kiện nến xác nhận cùng chiều.
3. Nguyên lý hoạt động của CNPS61
Hệ thống vận hành theo chu trình khép kín 5 bước trên mỗi nến xác nhận (barstate.isconfirmed):
- Khởi tạo phiên & làm sạch trạng thái: Khi sang ngày mới (
newTradingDay), đầu phiên sáng (09:00), đầu phiên chiều (13:00) hoặc tại các mốclunchFlatBar/endFlatBar, toàn bộsetupState, biên hộp nén (boxHigh,boxLow) và bộ đếm phiên được reset về0. - Nạp hộp nén (
setupState == 0 -> 1): Khi vị thế đang phẳng (flat), nằm trong giờ vào lệnh hợp lệ vàcompressionQualifiedđạt chuẩn, bot lưu lại biên trên/dưới của hộp và chuyển sang trạng thái chờ breakout. - Phát hiện cú phá vỡ đầu tiên (
setupState == 1 -> 2 / -2): Trong tối đa12nến kể từ lúc nạp hộp, nếu xuất hiện nến breakout đạt chuẩn biên độ, thân nến, vị trí đóng cửa và vượt biên hộp>= 0.30điểm, bot đánh dấubreakoutBar. Nếu chọn"Breakout Close", bot phát tín hiệu ngay; ngược lại sẽ chuyển sang trạng thái chờ xác nhận. - Xác nhận & Kiểm duyệt Risk/Reward: Trong cửa sổ
7nến sau breakout, nếu có tín hiệu Retest hoặc Follow-Through hợp lệ (và giá không đóng ngược vào trong hộp quá0.30điểm), bot tính toánactiveStop,activeTarget, kiểm tra khoảng cách SL (1.5 – 10.0điểm) vàR:R >= 1.10trước khi gửi lệnhstrategy.entry. - Giám sát vị thế & Thoát lệnh: Sau khi khớp lệnh ở nến kế tiếp, bot kiểm tra tính hợp lệ của giá khớp (
validFill), theo dõiacceptanceFailureCount, bộ đếm thời gian giữ lệnh (45phút), tùy chọn Break Even và đóng toàn bộ vị thế trước giờ nghỉ trưa/ATC.
4. Điều kiện vào lệnh Long và Short của CNPS61
4.1. Điều kiện vào lệnh Long
Bot chỉ kích hoạt finalLong khi thỏa mãn đầy đủ chuỗi điều kiện sau:
- Hộp nén hợp lệ đã được nạp (
setupState == 1) và xuất hiệnupperBreak:close > boxHigh + 0.30vàclose[1] <= boxHigh + 0.30.- Nến tăng (
close > open),candleBodyRatio >= 0.35,closeLocation >= 0.65, biên độ nến trong[0.70, 2.80] * atrSlow[1]. - Đạt bộ lọc volume breakout (nếu bật
useBreakoutVolume).
- Thỏa mãn chiều giao dịch (
tradeDirection != "Short") và chưa chạm giới hạn 1 lệnh Long/ngày (nếu bậtoneTradePerDirection). - Thỏa mãn bộ lọc xu hướng
longTrendOK(nếu bật EMA) vàlongVWAPOK(nếu bật Session VWAP). - Xác nhận điểm vào theo
entryMode(vào ngay khi Breakout Close, hoặc ở nến sau đạtretestHeld/continuationConfirmedtrước khi hết hạn7nến hoặc bị hủy doclose < boxHigh - 0.30). - Khoảng cách SL (
longRisk) nằm trong[1.50, 10.0]điểm,longReward >= 2.50điểm vàlongReward / longRisk >= 1.10.
4.2. Điều kiện vào lệnh Short
Bot chỉ kích hoạt finalShort (và not finalLong) khi thỏa mãn đối xứng:
- Xuất hiện
lowerBreak:close < boxLow - 0.30vàclose[1] >= boxLow - 0.30.- Nến giảm (
close < open),candleBodyRatio >= 0.35,closeLocation <= 0.35, biên độ nến trong[0.70, 2.80] * atrSlow[1].
- Thỏa mãn
allowShort, bộ lọcshortTrendOKvàshortVWAPOK(nếu bật). - Xác nhận điểm vào theo
entryMode(Breakout Close, hoặc ở nến sau đạtretestHeld/continuationConfirmedtrước khi hết hạn7nến hoặc bị hủy doclose > boxLow + 0.30). - Khoảng cách SL (
shortRisk) nằm trong[1.50, 10.0]điểm,shortReward >= 2.50điểm vàshortReward / shortRisk >= 1.10.
4.3. Điều kiện kiểm soát giao dịch chung
Mọi lệnh Long/Short đều phải đi qua cổng commonEntryOK:
- Vị thế phẳng:
strategy.position_size == 0(pyramiding = 0, không nhồi lệnh). - Khung giờ VN30F1M: Nằm trong phiên sáng
09:10 – 11:20hoặc chiều13:05 – 14:15(giờ Việt Nam) vàbeforeCutoffs(trước mốc cắt lệnh trưa/chiều). - Số lệnh & Cooldown:
tradesToday < 4và số nến kể từ lần thoát lệnh gần nhất lớn hơn3nến (bar_index - lastExitBar > 3). - Giới hạn lỗ ngày: Khi
useDailyLossGuard = true, tổng lãi/lỗ đã chốt trong ngày phải lớn hơn-2,400,000 VND. - Chống trùng lặp:
oncePerBar(tối đa 1 lệnh trên mỗi nến đóng).
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 Stop Loss (stopMode), làm tròn theo syminfo.mintick:
- Breakout / Retest Structure (Mặc định): Neo SL tại điểm thấp nhất (với Long) hoặc cao nhất (với Short) giữa biên hộp breakout, cực trị nến breakout và cực trị nến retest, sau đó cộng/trừ thêm khoảng đệm
0.15 * atrSlow. - Opposite Box Edge: Đặt SL ở biên đối diện của hộp nén (
boxLowcho Long,boxHighcho Short) cộng/trừ đệm0.15 * atrSlow. - ATR Fixed: Đặt SL cách giá đóng cửa tín hiệu một khoảng cố định
1.60 * atrSlow.
Nếu khoảng cách SL sau khi tính nằm ngoài vùng [1.50, 10.0] điểm, tín hiệu sẽ bị từ chối ngay từ bước kiểm duyệt.
5.2. Cơ chế Take Profit, Break Even và Thoát lệnh sớm
- Take Profit (
targetMode):Fixed R(Mặc định): Đặt TP theo bội số1.60 Rtính từ giá đóng cửa tín hiệu.Box Width Projection: Đặt TP bằng biên hộp cộng/trừ1.00 * boxWidth.- Mục tiêu lợi nhuận gộp phải đạt tối thiểu
2.50điểm và tỷ lệR:R >= 1.10.
- Break Even (Tùy chọn, mặc định tắt): Khi
useBreakEven = truevà lợi nhuận mở đạt1.00 Rso vớifillPrice, SL được dời vềfillPrice + 0.20(Long) hoặcfillPrice - 0.20(Short). - Thoát lệnh khi phá vỡ thất bại (
Acceptance Failure Exit): Mặc định bật; nếu có2nến liên tiếp đóng cửa quay lại sâu vào trong hộp nén quá0.30điểm tính từactiveBreakoutBoundary, bot chủ động đóng vị thế. - Thoát lệnh theo thời gian (
Time Exit) & Hết phiên: Đóng vị thế nếu giữ lệnh đạt45phút, hoặc cưỡng chế đóng toàn bộ lúc11:25và14:25.
5.3. Bảng tổng hợp cơ chế bảo vệ vị thế
| Cơ chế bảo vệ | Tham số kích hoạt mặc định | Hành động của Bot CNPS61 |
|---|---|---|
| Stop Loss cấu trúc | stopMode = "Breakout / Retest Structure", đệm 0.15x ATR | Đóng lệnh khi chạm activeStop (SL Long / SL Short) |
| Take Profit | targetMode = "Fixed R", takeProfitR = 1.60 | Chốt lời giới hạn tại activeTarget (TP Long / TP Short) |
| Kiểm tra khớp lệnh | validFill tại SECTION 27 | Đóng ngay nếu giá khớp nến sau làm initialFillRisk <= mintick hoặc sai chiều TP |
| Dời hòa vốn (BE) | useBreakEven = false, kích hoạt 1.00 R, offset 0.20 | Dời activeStop về vùng có lãi nhẹ khi đạt ngưỡng R |
| Phá vỡ thất bại | useAcceptanceFailureExit = true, failureCloses = 2 | Đóng lệnh thị trường khi 2 nến liên tiếp đóng vào trong hộp > 0.30 điểm |
| Giới hạn thời gian | useTimeExit = true, maximumHoldMinutes = 45 | Đóng lệnh thị trường khi thời gian nắm giữ đạt 45 phút |
| Đóng hết phiên | 11:25 (trưa) và 14:25 (cuối ngày) | strategy.close_all tránh rủi ro qua trưa và phiên ATC |
| Bảo vệ lỗ ngày | useDailyLossGuard = true, 2,400,000 VND | Chặn không mở vị thế mới trong ngày khi lỗ chốt chạm ngưỡng |
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 intraday như M1, M3 hoặc M5).
- Mở tab Pine Editor ở phía dưới màn hình, xóa code mẫu mặc định.
- Sao chép toàn bộ mã nguồn CNPS61 tại Mục 1 và dán vào Pine Editor.
- Nhấn Save (Lưu), đặt tên chiến lược rồi nhấn Add to chart (Thêm vào biểu đồ).
- Mở biểu tượng bánh răng (Settings) của chiến lược để điều chỉnh số hợp đồng (
contracts = 3), chế độ vào lệnh (entryMode) hoặc bật/tắt các bộ lọc EMA/VWAP theo khẩu vị rủi ro.
Cách đọc bảng chẩn đoán (Diagnostics Table)
Khác với nhiều bot có bảng thống kê nổi che khuất nến, CNPS61 được thiết kế theo triết lý tối giản (Clean Chart / No Dashboard) và không vẽ bảng table.new (Diagnostics Table) lên màn hình. Thay vào đó, toàn bộ trạng thái vận hành của bot được thể hiện trực tiếp, gọn gàng trên biểu đồ giá thông qua các lớp hiển thị ở SECTION 31 và SECTION 32:
- Đường biên hộp nén (
Compression Box Highmàu xanh teal /Compression Box Lowmàu đỏ): Chỉ hiển thị khisetupState != 0, giúp bạn biết bot đã nạp hộp nén và đang theo dõi vùng giá nào. - Đường quản trị lệnh (
Active Structural Stopmàu đỏ /Active Profit Targetmàu xanh lá): Tự động xuất hiện ngay khi đang giữ vị thế, cho biết chính xác mức SL (bao gồm cả khi đã dời sang Break Even) và TP hiện tại. - Đường Session VWAP (màu cam): Ẩn mặc định; bật
Show Session VWAP?trong mục Display nếu muốn quan sát ngưỡng VWAP theo ngày. - Nhãn tín hiệu (
L/S): Hình tam giác xanh/đỏ đánh dấu chính xác nến xác nhận vào lệnh Long/Short; có thể bật thêmShow Confirmed Breakouts?để hiện chấm tròn tại nến breakout ban đầ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 thời gian thực qua ứng dụng TradingView, Email hoặc Webhook kết nối với hệ thống đặt lệnh tự động:
- Nhấn vào biểu tượng Alert (hình đồng hồ báo thức) trên thanh công cụ TradingView.
- Ở mục Condition, chọn đúng tên chiến lược CNPS61 VOLATILITY COMPRESSION RELEASE V1 - VN30F1M.
- Ở ô Message, xóa nội dung mặc định và điền chính xác biến placeholder:
{{strategy.order.alert_message}} - Nhấn Create để kích hoạt cảnh báo.
Bảng thông điệp Alert của CNPS61
| Sự kiện | Loại thông báo | Nội dung Alert thực tế trong code |
|---|---|---|
| Vào lệnh Long | alert_message | 🟢 VÀO VỊ THẾ LONG (Volatility Compression Release)\n🎯 Giá vào: <close>\n🛑 SL dự kiến: <activeStop>\n🎯 TP dự kiến: <activeTarget> |
| Vào lệnh Short | alert_message | 🔴 VÀO VỊ THẾ SHORT (Volatility Compression Release)\n🎯 Giá vào: <close>\n🛑 SL dự kiến: <activeStop>\n🎯 TP dự kiến: <activeTarget> |
| Chốt lời Long / Short | alert_profit | 💰 CHỐT LỜI LONG (TP HIT) / 💰 CHỐT LỜI SHORT (TP HIT)\n🎯 Giá chốt: <activeTarget> |
| Cắt lỗ Long / Short | alert_loss | 🛑 CẮT LỖ LONG (SL HIT) / 🛑 CẮT LỖ SHORT (SL HIT)\n🎯 Giá cắt: <activeStop> |
| Hòa vốn Long / Short | alert_loss (khi breakEvenActive) | 🛡️ HÒA VỐN LONG (BE HIT) / 🛡️ HÒA VỐN SHORT (BE HIT)\n🎯 Giá thoát: <activeStop> |
| Khớp lệnh không hợp lệ | alert_message (strategy.close) | 🔄 ĐÓNG VỊ THẾ (Khớp lệnh không hợp lệ)\n🎯 Giá đóng: <close> |
| Phá vỡ thất bại | alert_message (strategy.close) | ⚡ ĐÓNG VỊ THẾ (Phá vỡ thất bại)\n🎯 Giá đóng: <close> |
| Hết thời gian giữ lệnh | alert_message (strategy.close) | ⏱️ ĐÓNG VỊ THẾ (Hết thời gian giữ lệnh tối đa)\n🎯 Giá đóng: <close> |
| Đóng hết phiên | alert_message (strategy.close_all) | ⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End)\n🎯 Giá đóng: <close> |
Kết luận
CNPS61 VOLATILITY COMPRESSION RELEASE V1 là một hệ thống giao dịch VN30F1M có kỷ luật chặt chẽ, đặc biệt phù hợp với bối cảnh thị trường chuyển từ trạng thái tích lũy biên độ hẹp sang bùng nổ xu hướng trong phiên. Nhờ kết hợp đo lường nén biến động trên nến đã đóng, xác nhận Retest/Follow-Through và bộ khung thoát lệnh đa tầng (SL cấu trúc, Acceptance Failure Exit, Time Exit, Force Flat cuối phiên và Daily Loss Guard), bot giúp hạn chế tối đa rủi ro nhiễu và bảo vệ vốn hiệu quả.
Bạn có thể tham khảo thêm các hệ thống giao dịch khác trên phaisinh.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.





