Thứ Tư, 25/11/202625/11/2026

Hướng Dẫn Sử Dụng Bot CNPS52 - Super Envolvente V2 Quality Breakout cho VN30F1M

Hướng dẫn chi tiết Bot CNPS52 Super Envolvente V2 Quality Breakout cho VN30F1M: chiến lược phá vỡ hộp nến nhấn chìm toàn dải (Full-Range Outer Box), lọc xu hướng EMA 21/55, đặt SL Half Box Protected và thoát lệnh sớm khi phá vỡ thất bại.

Hướng Dẫn Sử Dụng Bot CNPS52 - Super Envolvente V2 Quality Breakout cho VN30F1M
Hướng Dẫn Sử Dụng Bot CNPS52 - Super Envolvente V2 Quality Breakout cho VN30F1M
Mục lục
Mục lục

Trong giao dịch hợp đồng tương lai chỉ số VN30F1M, mô hình nến nhấn chìm toàn dải (Full-Range Engulfing / Super Envolvente — cây nến hiện tại bao trùm toàn bộ đỉnh và đáy của cây nến trước đó) là một tín hiệu cho thấy sự bùng nổ biên độ và đảo chiều hoặc tiếp diễn động lượng mạnh mẽ. Tuy nhiên, điểm yếu chí mạng của các chiến lược Engulfing truyền thống (V1) là kích hoạt lệnh ngay khi giá chỉ mới đóng cửa vượt qua phần thân nến (Body) của nến Setup nhưng vẫn nằm lọt thỏm bên trong phần râu nến (Wick), dẫn đến tỷ lệ bẫy giá (Bull/Bear Trap) rất cao khi thị trường phái sinh biến động nhiễu.

Để giải quyết triệt để bài toán trên, chiến lược CNPS52 SUPER ENVOLVENTE V2 QUALITY BREAKOUT - VN30F1M (tên ngắn trên biểu đồ: CNPS52 ENV V2) được phát triển trên nền tảng Pine Script v6 của TradingView. Thay vì vào lệnh sớm trong vùng râu nến, phiên bản V2 yêu cầu nến kích hoạt (Trigger Candle) phải phá vỡ và đóng cửa vượt hẳn lên trên hoặc xuống dưới toàn bộ hộp biên độ (Full Range Outer Box) của nến Setup, đồng thời tích hợp bộ lọc xu hướng EMA đa tầng, kiểm soát kích thước hộp theo ATR và cơ chế thoát lệnh sớm khi phá vỡ thất bại.

Những điểm nổi bật cốt lõi của Bot CNPS52 Super Envolvente V2 Quality Breakout:

  • Phá vỡ toàn bộ hộp biên độ (Full-Range Outer Box Breakout): Thiết lập vùng hộp từ cây nến bao trùm toàn dải (high >= high[1] và low <= low[1]), chỉ giải ngân khi nến xác nhận trong cửa sổ 2 thanh nến kế tiếp đóng cửa vượt qua biên độ toàn hộp (hoặc chế độ Body tùy chọn).
  • Bộ lọc chất lượng nến và xu hướng đa tầng: Kiểm định nghiêm ngặt tỷ lệ thân nến (Body / Range >= 0.35), vị trí đóng cửa (Close Location >= 0.65), kích thước hộp chuẩn hóa theo ATR (0.60 – 2.50 ATR), kết hợp đồng thuận xu hướng EMA 21 / EMA 55 cùng độ dốc EMA 21.
  • Quản trị rủi ro cấu trúc (Structural Risk) và hậu kiểm khớp lệnh: Hỗ trợ 3 chế độ đặt Stop Loss (Half Box Protected, Full Box, Trigger Candle) cộng đệm 0.10 x ATR, lọc biên độ rủi ro từ 1.5 – 12.0 điểm, tự động tính lại Take Profit theo giá khớp thực tế và đóng lệnh khẩn cấp nếu trượt giá/Gap làm rủi ro vượt ngưỡng.
  • Thoát lệnh thông minh đa lớp: Kết hợp dời Stop Loss về hòa vốn (Break Even) tại 1.0R (cộng bù 0.2 điểm), đóng lệnh sớm khi phá vỡ thất bại (Failed Breakout Exit sau 2 nến đóng cửa ngược lại hộp), thoát lệnh theo thời gian (Max Hold 30 Bars) và tất toán bắt buộc cuối phiên (14:45).

1. CNPS52 Super Envolvente V2 Quality Breakout là gì?

CNPS52 Super Envolvente V2 Quality Breakout là hệ thống giao dịch định lượng theo hành động giá (Price Action Breakout) kết hợp bộ lọc xu hướng dành riêng cho hợp đồng tương lai VN30F1M. Chiến lược được xây dựng dựa trên 4 trụ cột kỹ thuật chính:

  1. Nhận diện hộp bao trùm (Outer Box Setup): Xác định cây nến có biên độ bao trùm toàn bộ đỉnh và đáy của nến liền trước (high >= high[1] và low <= low[1]), có màu nến ngược với nến trước đó, thân nến đủ lớn (>= 35% biên độ nến) và độ rộng hộp nằm trong vùng biến động chuẩn (0.60 đến 2.50 lần ATR).
  2. Xác nhận phá vỡ chất lượng cao (Quality Breakout Trigger): Trong vòng entryValidityBars (mặc định 2 nến) sau khi hình thành hộp Setup, giá phải đóng cửa vượt hẳn qua đỉnh hộp (với lệnh Long) hoặc thủng đáy hộp (với lệnh Short) với lực nến quyết liệt (thân nến >= 35%, đóng cửa ở 35% phần đỉnh/đáy nến).
  3. Bộ lọc trạng thái thị trường (Market Regime Filters): Đồng bộ hướng phá vỡ với cấu trúc xu hướng của đường trung bình động EMA 21 và EMA 55 (kèm điều kiện độ dốc EMA 21 trong 3 nến), đồng thời hỗ trợ tùy chọn bộ lọc sức mạnh xu hướng ADX(14) và khối lượng giao dịch Volume SMA(20).
  4. Cơ chế bảo vệ vị thế và kiểm soát rủi ro nội nhật (Intraday Risk & Trade Control): Giới hạn rủi ro mỗi lệnh trong khung 1.5 – 12.0 điểm, tự động dời SL về hòa vốn, cắt lệnh sớm khi giá chui ngược vào trong hộp (Failed Breakout), giới hạn số lệnh tối đa mỗi ngày (4 lệnh/ngày) và ngắt giao dịch khi chạm hạn mức lỗ ròng trong ngày (2.500.000 VNĐ).

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

Dưới đây là bảng tổng hợp toàn bộ các tham số cấu hình (input.*) được thiết lập sẵn trong mã nguồn của CNPS52:

Nhóm thông sốTên hiển thị trên TradingViewBiến trong codeGiá trị mặc địnhÝ nghĩa kỹ thuật
01 - OUTER BOX & BREAKOUTEnable Long / Enable ShortenableLong / enableShorttrue / trueBật/tắt chiều giao dịch Long và Short
01 - OUTER BOX & BREAKOUTPrevious Candle Opposite ColourrequireOppositetrueYêu cầu nến trước Setup phải ngược màu với nến Setup
01 - OUTER BOX & BREAKOUTBreakout Confirmation Window (bars)entryValidityBars2Số thanh nến tối đa chờ xác nhận phá vỡ hộp Setup
01 - OUTER BOX & BREAKOUTBreakout LevelbreakMode"Full Range"Mốc phá vỡ: "Full Range" (đỉnh/đáy hộp) hoặc "Body (original)"
01 - OUTER BOX & BREAKOUTMinimum Ticks Beyond Breakout LevelbreakBufferTicks0Số tick đệm tối thiểu cần vượt thêm qua mốc Breakout
01 - OUTER BOX & BREAKOUTSetup Minimum Body / RangeminimumSetupBody0.35Tỷ lệ thân nến / biên độ tối thiểu của nến Setup
01 - OUTER BOX & BREAKOUTBreakout Minimum Body / RangeminimumTriggerBody0.35Tỷ lệ thân nến / biên độ tối thiểu của nến phá vỡ
01 - OUTER BOX & BREAKOUTBreakout Close LocationminimumCloseLocation0.65Vị trí đóng cửa tối thiểu của nến phá vỡ (Long >= 0.65, Short <= 0.35)
01 - OUTER BOX & BREAKOUTMinimum / Maximum Outer Box Range / ATRminBoxATR / maxBoxATR0.60 / 2.50Giới hạn độ rộng hộp Setup chuẩn hóa theo ATR(14)
02 - QUALITY / TREND FILTERSUse EMA Trend FilteruseTrendFiltertrueBật bộ lọc xu hướng theo EMA Fast và EMA Slow
02 - QUALITY / TREND FILTERSFast EMA / Slow EMAfastEmaLen / slowEmaLen21 / 55Chu kỳ đường EMA nhanh (21) và EMA chậm (55)
02 - QUALITY / TREND FILTERSFast EMA Slope LookbackemaSlopeBars3Số nến tham chiếu để kiểm tra độ dốc của EMA 21
02 - QUALITY / TREND FILTERSRequire ADX StrengthuseADXFilterfalseBật/tắt bộ lọc cường độ xu hướng ADX
02 - QUALITY / TREND FILTERSADX Length / Minimum ADXadxLength / minimumADX14 / 16.0Chu kỳ tính DMI/ADX và ngưỡng ADX tối thiểu
02 - QUALITY / TREND FILTERSRequire Minimum Volume vs SMAuseVolumeFilterfalseBật/tắt bộ lọc khối lượng giao dịch so với trung bình
02 - QUALITY / TREND FILTERSVolume SMA Length / Minimum RatiovolumeLength / minVolumeRatio20 / 0.85Chu kỳ SMA Volume và tỷ lệ Volume tối thiểu so với SMA
03 - RISK & EXITSContracts per EntrypositionContracts3Tham số khai báo số hợp đồng (lệnh thực tế dùng default_qty_value=1)
03 - RISK & EXITSRisk ATR LengthatrLength14Chu kỳ ATR dùng để đo kích thước hộp và đệm Stop Loss
03 - RISK & EXITSStructural StopstopMode"Half Box Protected"Chế độ đặt SL: "Half Box Protected", "Full Box", "Trigger Candle"
03 - RISK & EXITSStructural Stop Buffer x ATRstopBufferATR0.10Khoảng đệm cộng thêm vào SL tính theo hệ số ATR
03 - RISK & EXITSMinimum / Maximum Risk (points)minimumRiskPoints / maximumRiskPoints1.5 / 12.0Khoảng rủi ro (điểm chỉ số) hợp lệ để cho phép vào lệnh
03 - RISK & EXITSTake Profit RtakeProfitR1.5Hệ số chốt lời theo bội số rủi ro ban đầu (1.5R)
03 - RISK & EXITSUse Break Even / Trigger R / OffsetuseBreakEven / breakEvenAtR / breakEvenOffsettrue / 1.0 / 0.2Dời SL về giá vốn + 0.2 điểm khi nến đóng cửa lãi >= 1.0R
03 - RISK & EXITSExit Failed Breakout EarlyuseFailureExittrueBật cơ chế thoát lệnh sớm khi phá vỡ thất bại
03 - RISK & EXITSFailure Close Tolerance x ATR / BarsfailureToleranceATR / failureBarsRequired0.15 / 2Đóng lệnh khi có 2 nến liên tiếp đóng cửa thụt lùi quá 0.15 ATR dưới mốc Break
03 - RISK & EXITSUse Time Exit / Max Hold BarsuseTimeout / maxHoldBarstrue / 30Tự động đóng vị thế nếu giữ lệnh chạm mốc 30 thanh nến
04 - TRADE CONTROLTrade DirectiontradeDirection"Both"Hướng giao dịch cho phép: "Both", "Long", "Short"
04 - TRADE CONTROLMaximum Trades / DaymaximumTradesPerDay4Số lệnh tối đa trong 1 ngày giao dịch (0 = không giới hạn)
04 - TRADE CONTROLCooldown Bars After ExitcooldownAfterExit2Số thanh nến nghỉ bắt buộc sau khi vừa đóng một giao dịch
04 - TRADE CONTROLDisable New Entries After Daily Net LossuseDailyLossStop / maximumDailyNetLosstrue / 2500000Ngừng mở lệnh mới trong ngày nếu lỗ ròng chạm 2.500.000 VNĐ
04 - TRADE CONTROLClose If Filled Stop/Risk InvalidcloseIfGapInvalidtrueĐóng lệnh ngay lập tức nếu giá khớp thực tế làm rủi ro không hợp lệ
05 - VN30F1M SESSIONMorning / Afternoon EntrymorningSession / afternoonSession"0910-1120" / "1305-1420"Khung giờ cho phép tạo Setup và mở lệnh theo giờ Việt Nam
05 - VN30F1M SESSIONForce Close Hour / MinuteforceCloseHour / forceCloseMinute14 / 45Thời điểm đóng toàn bộ vị thế cuối phiên chiều (14:45)
06 - DISPLAY / ALERTSShow EMAs / Pending / Orders / SLTP / FunnelshowEMAs, showPendingLevels, showOrders, showSLTP, showDiagnosticstrue (showSetup = false)Tùy chọn hiển thị đường EMA, mức chờ Break, mũi tên lệnh, SL/TP và bảng Funnel

Source Code CNPS52 Super Envolvente V2 Quality Breakout

Bạn có thể sao chép toàn bộ mã nguồn Pine Script v6 dưới đây để dán trực tiếp vào Pine Editor trên TradingView:

//@version=6
strategy(title="CNPS52 SUPER ENVOLVENTE V2 QUALITY BREAKOUT - VN30F1M", shorttitle="CNPS52 ENV 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, commission_type=strategy.commission.cash_per_contract, commission_value=0, slippage=0, fill_orders_on_standard_ohlc=true, process_orders_on_close=false, calc_on_order_fills=false, calc_on_every_tick=false, max_lines_count=300, max_labels_count=300, max_bars_back=5000)

// ============================================================================
// CNPS52 V2 - SUPER ENVOLVENTE (FULL-RANGE ENGULFING) FOR VN30F1M
// SOURCE DNA: current high >= prior high AND current low <= prior low;
// setup is directional, prior candle opposite by default.
// V1 weakness: trigger closed beyond BODY, potentially still inside wick.
// V2 default: trigger closes ABOVE/BELOW ENTIRE SETUP BOX.
// V2 adds trend/candle filters, mandatory risk control and failure exit.
// V2 is a modified research strategy, NOT a verified profitable system.
// ============================================================================
// 1. OUTER BOX / CONFIRMATION
string G1 = "01 - OUTER BOX & BREAKOUT"
enableLong = input.bool(true, "Enable Long", group=G1)
enableShort = input.bool(true, "Enable Short", group=G1)
requireOpposite = input.bool(true, "Previous Candle Opposite Colour", group=G1)
entryValidityBars = input.int(2, "Breakout Confirmation Window (bars)", minval=1, maxval=10, group=G1)
breakMode = input.string("Full Range", "Breakout Level", options=["Full Range", "Body (original)"], group=G1)
breakBufferTicks = input.int(0, "Minimum Ticks Beyond Breakout Level", minval=0, maxval=30, group=G1)
minimumSetupBody = input.float(0.35, "Setup Minimum Body / Range", minval=0, maxval=1, step=0.05, group=G1)
minimumTriggerBody = input.float(0.35, "Breakout Minimum Body / Range", minval=0, maxval=1, step=0.05, group=G1)
minimumCloseLocation = input.float(0.65, "Breakout Close Location", minval=0.50, maxval=1, step=0.05, group=G1)
minBoxATR = input.float(0.60, "Minimum Outer Box Range / ATR", minval=0, maxval=5, step=0.1, group=G1)
maxBoxATR = input.float(2.50, "Maximum Outer Box Range / ATR", minval=0.5, maxval=10, step=0.1, group=G1)

// 2. MARKET REGIME - ALL OPTIONAL
string G2 = "02 - QUALITY / TREND FILTERS"
useTrendFilter = input.bool(true, "Use EMA Trend Filter", group=G2)
fastEmaLen = input.int(21, "Fast EMA", minval=1, group=G2)
slowEmaLen = input.int(55, "Slow EMA", minval=2, group=G2)
emaSlopeBars = input.int(3, "Fast EMA Slope Lookback", minval=1, maxval=20, group=G2)
useADXFilter = input.bool(false, "Require ADX Strength", group=G2)
adxLength = input.int(14, "ADX Length / Smoothing", minval=2, group=G2)
minimumADX = input.float(16.0, "Minimum ADX", minval=5, maxval=60, step=1, group=G2)
useVolumeFilter = input.bool(false, "Require Minimum Volume vs SMA", group=G2)
volumeLength = input.int(20, "Volume SMA Length", minval=2, group=G2)
minVolumeRatio = input.float(0.85, "Minimum Volume / Average", minval=0.1, maxval=5, step=0.05, group=G2)

// 3. STRUCTURAL RISK AND EXITS
string G3 = "03 - RISK & EXITS"
positionContracts = input.int(3, "Contracts per Entry", minval=1, maxval=20, group=G3)
atrLength = input.int(14, "Risk ATR Length", minval=1, group=G3)
stopMode = input.string("Half Box Protected", "Structural Stop", options=["Half Box Protected", "Full Box", "Trigger Candle"], group=G3)
stopBufferATR = input.float(0.10, "Structural Stop Buffer x ATR", minval=0, maxval=2, step=0.05, group=G3)
minimumRiskPoints = input.float(1.5, "Minimum Risk (points)", minval=0.1, step=0.5, group=G3)
maximumRiskPoints = input.float(12.0, "Maximum Risk (points)", minval=0.5, step=0.5, group=G3)
takeProfitR = input.float(1.5, "Take Profit R", minval=0.25, maxval=10, step=0.1, group=G3)
useBreakEven = input.bool(true, "Use Break Even", group=G3)
breakEvenAtR = input.float(1.0, "Break Even Trigger R (close based)", minval=0.25, step=0.25, group=G3)
breakEvenOffset = input.float(0.2, "Break Even Offset (points)", minval=0, step=0.1, group=G3)
useFailureExit = input.bool(true, "Exit Failed Breakout Early", group=G3)
failureToleranceATR = input.float(0.15, "Failure Close Tolerance x ATR", minval=0, maxval=2, step=0.05, group=G3)
failureBarsRequired = input.int(2, "Consecutive Failure Closes", minval=1, maxval=5, group=G3)
useTimeout = input.bool(true, "Use Time Exit", group=G3)
maxHoldBars = input.int(30, "Max Hold Bars", minval=1, maxval=500, group=G3)

// 4. TRADE CONTROL
string G4 = "04 - TRADE CONTROL"
tradeDirection = input.string("Both", "Trade Direction", options=["Both", "Long", "Short"], group=G4)
maximumTradesPerDay = input.int(4, "Maximum Trades / Day (0 = unlimited)", minval=0, maxval=50, group=G4)
cooldownAfterExit = input.int(2, "Cooldown Bars After Exit", minval=0, maxval=100, group=G4)
useDailyLossStop = input.bool(true, "Disable New Entries After Daily Net Loss", group=G4)
maximumDailyNetLoss = input.float(2500000, "Daily Net Loss Limit (VND)", minval=100000, step=100000, group=G4)
closeIfGapInvalid = input.bool(true, "Close If Filled Stop/Risk Invalid", group=G4)

// 5. VIETNAM SESSION
string G5 = "05 - VN30F1M SESSION"
string TZ = "Asia/Ho_Chi_Minh"
morningSession = input.session("0910-1120", "Morning Entry", group=G5)
afternoonSession = input.session("1305-1420", "Afternoon Entry", group=G5)
forceCloseHour = input.int(14, "Force Close Hour", minval=0, maxval=23, group=G5)
forceCloseMinute = input.int(15 + 30, "Force Close Minute", minval=0, maxval=59, group=G5)

// 6. DISPLAY & DIAGNOSTICS
string G6 = "06 - DISPLAY / ALERTS"
showEMAs = input.bool(true, "Show EMA21 / EMA55", group=G6)
showSetup = input.bool(false, "Show Outer Box Setup Labels", group=G6)
showPendingLevels = input.bool(true, "Show Pending Full-Box Levels", group=G6)
showOrders = input.bool(true, "Show Final Entry Markers", group=G6)
showSLTP = input.bool(true, "Show Active Stop / Target", group=G6)
showDiagnostics = input.bool(true, "Show Signal Funnel", group=G6)
disableExitAlerts = input.bool(false, "Disable SL/TP Alerts", group=G6)

// 7. CORE DATA
float atr = ta.atr(atrLength)
float emaFast = ta.ema(close, fastEmaLen)
float emaSlow = ta.ema(close, slowEmaLen)
[diPlus, diMinus, adx] = ta.dmi(adxLength, adxLength)
float volumeAverage = ta.sma(volume, volumeLength)
float candleRange = math.max(high - low, syminfo.mintick)
float candleBodyRatio = math.abs(close - open) / candleRange
float candleCloseLocation = (close - low) / candleRange
bool isBullCandle = close > open
bool isBearCandle = close < open
bool prevBullCandle = close[1] > open[1]
bool prevBearCandle = close[1] < open[1]
bool outerBox = not na(high[1]) and high >= high[1] and low <= low[1]
float boxATR = (high - low) / math.max(atr, syminfo.mintick)
bool boxSizeOK = not na(boxATR) and boxATR >= minBoxATR and boxATR <= maxBoxATR
bool trendLongOK = not useTrendFilter or (emaFast > emaSlow and emaFast > emaFast[emaSlopeBars] and close > emaFast)
bool trendShortOK = not useTrendFilter or (emaFast < emaSlow and emaFast < emaFast[emaSlopeBars] and close < emaFast)
bool adxOK = not useADXFilter or (not na(adx) and adx >= minimumADX)
bool volumeOK = not useVolumeFilter or (not na(volumeAverage) and nz(volume) >= volumeAverage * minVolumeRatio)

// 8. SESSION, DAILY AND TRADE STATUS
bool inMorning = not na(time(timeframe.period, morningSession, TZ))
bool inAfternoon = not na(time(timeframe.period, afternoonSession, TZ))
bool inEntrySession = inMorning or inAfternoon
bool startEntryWindow = inEntrySession and not inEntrySession[1]
int vnDayKey = year(time, TZ) * 10000 + month(time, TZ) * 100 + dayofmonth(time, TZ)
bool newTradingDay = bar_index == 0 or vnDayKey != nz(vnDayKey[1], vnDayKey)
var int tradesToday = 0
var int seenClosedTrades = 0
var int lastExitBar = na
var int lastSubmittedBar = na
var float startingNetProfit = na
if newTradingDay
    tradesToday := 0
    startingNetProfit := strategy.netprofit
    lastExitBar := na
if strategy.closedtrades > seenClosedTrades
    seenClosedTrades := strategy.closedtrades
    lastExitBar := bar_index
float dailyNetProfit = strategy.netprofit - nz(startingNetProfit, strategy.netprofit)
bool dailyLossOK = not useDailyLossStop or dailyNetProfit > -maximumDailyNetLoss
bool flat = strategy.position_size == 0
bool canLong = tradeDirection != "Short" and enableLong
bool canShort = tradeDirection != "Long" and enableShort
bool cooldownOK = na(lastExitBar) or bar_index - lastExitBar > cooldownAfterExit
bool tradeLimitOK = maximumTradesPerDay == 0 or tradesToday < maximumTradesPerDay

// 9. PRIOR SETUP STATE - DO NOT REPLACE BEFORE CHECKING THE BREAKOUT
var float buyBoxHigh = na
var float buyBoxLow = na
var float buyBodyHigh = na
var int buySetupBar = na
var float sellBoxHigh = na
var float sellBoxLow = na
var float sellBodyLow = na
var int sellSetupBar = na
var int setupCount = 0
var int breakoutCount = 0
var int rejectedQuality = 0
var int rejectedRisk = 0
var int rejectedControls = 0
var int orderCount = 0
if newTradingDay or startEntryWindow
    buyBoxHigh := na
    buyBoxLow := na
    buyBodyHigh := na
    buySetupBar := na
    sellBoxHigh := na
    sellBoxLow := na
    sellBodyLow := na
    sellSetupBar := na
if not na(buySetupBar) and bar_index - buySetupBar > entryValidityBars
    buySetupBar := na
if not na(sellSetupBar) and bar_index - sellSetupBar > entryValidityBars
    sellSetupBar := na
bool activeBuy = not na(buySetupBar) and bar_index > buySetupBar and bar_index - buySetupBar <= entryValidityBars
bool activeSell = not na(sellSetupBar) and bar_index > sellSetupBar and bar_index - sellSetupBar <= entryValidityBars
float longBreakLevel = breakMode == "Full Range" ? buyBoxHigh : buyBodyHigh
float shortBreakLevel = breakMode == "Full Range" ? sellBoxLow : sellBodyLow
float breakBuffer = breakBufferTicks * syminfo.mintick
bool longBreak = activeBuy and isBullCandle and close > longBreakLevel + breakBuffer
bool shortBreak = activeSell and isBearCandle and close < shortBreakLevel - breakBuffer
bool triggerLongQuality = candleBodyRatio >= minimumTriggerBody and candleCloseLocation >= minimumCloseLocation and trendLongOK and adxOK and volumeOK
bool triggerShortQuality = candleBodyRatio >= minimumTriggerBody and candleCloseLocation <= 1.0 - minimumCloseLocation and trendShortOK and adxOK and volumeOK

// 10. STOP STRUCTURE AND PRE-ENTRY RISK
float stopBuffer = nz(atr, 0.0) * stopBufferATR
float longMid = (buyBoxHigh + buyBoxLow) * 0.5
float shortMid = (sellBoxHigh + sellBoxLow) * 0.5
float longStopBase = stopMode == "Full Box" ? math.min(buyBoxLow, low) : stopMode == "Trigger Candle" ? low : math.min(longMid, low)
float shortStopBase = stopMode == "Full Box" ? math.max(sellBoxHigh, high) : stopMode == "Trigger Candle" ? high : math.max(shortMid, high)
float candidateLongStop = longBreak ? math.round_to_mintick(longStopBase - stopBuffer) : na
float candidateShortStop = shortBreak ? math.round_to_mintick(shortStopBase + stopBuffer) : na
float candidateLongRisk = longBreak ? close - candidateLongStop : na
float candidateShortRisk = shortBreak ? candidateShortStop - close : na
bool longRiskOK = not na(candidateLongRisk) and candidateLongRisk >= minimumRiskPoints and candidateLongRisk <= maximumRiskPoints
bool shortRiskOK = not na(candidateShortRisk) and candidateShortRisk >= minimumRiskPoints and candidateShortRisk <= maximumRiskPoints
bool commonOK = barstate.isconfirmed and inEntrySession and flat and cooldownOK and tradeLimitOK and dailyLossOK and (na(lastSubmittedBar) or lastSubmittedBar != bar_index)
bool finalLong = commonOK and canLong and longBreak and triggerLongQuality and longRiskOK
bool finalShort = commonOK and canShort and shortBreak and triggerShortQuality and shortRiskOK and not finalLong
if barstate.isconfirmed and (longBreak or shortBreak)
    breakoutCount += 1
    if (longBreak and not triggerLongQuality) or (shortBreak and not triggerShortQuality)
        rejectedQuality += 1
    else if (longBreak and not longRiskOK) or (shortBreak and not shortRiskOK)
        rejectedRisk += 1
    else if not commonOK
        rejectedControls += 1

// 11. ORDERS / BRACKETS
var float activeStop = na
var float activeTarget = na
var float activeInitialRisk = na
var float activeBreakLevel = na
var int activeFillBar = na
var int consecutiveFailureBars = 0
var bool breakEvenActive = false
var bool pendingLong = false
var bool pendingShort = false
if finalLong
    lastSubmittedBar := bar_index
    activeStop := candidateLongStop
    activeInitialRisk := candidateLongRisk
    activeTarget := math.round_to_mintick(close + candidateLongRisk * takeProfitR)
    activeBreakLevel := longBreakLevel
    activeFillBar := na
    consecutiveFailureBars := 0
    breakEvenActive := false
    pendingLong := true
    pendingShort := false
    strategy.entry("CNPS52-L", strategy.long, comment="BOX BREAK LONG", alert_message="🟢 VÀO VỊ THẾ LONG (CNPS52)\\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\\n🛑 Cắt lỗ (SL): " + str.tostring(activeStop, format.mintick) + "\\n🎯 Chốt lời (TP): " + str.tostring(activeTarget, format.mintick))
    strategy.exit("CNPS52-L-EXIT", from_entry="CNPS52-L", stop=activeStop, limit=activeTarget, comment_profit="TP Long", comment_loss="SL Long", alert_profit="💰 CHỐT LỜI LONG (TP HIT)\\n🎯 Giá chốt lời: " + str.tostring(activeTarget, format.mintick), alert_loss="🛑 CẮT LỖ LONG (SL HIT)\\nGiá cắt lỗ: " + str.tostring(activeStop, format.mintick), disable_alert=disableExitAlerts)
    tradesToday += 1
    orderCount += 1
    buySetupBar := na
    sellSetupBar := na
else if finalShort
    lastSubmittedBar := bar_index
    activeStop := candidateShortStop
    activeInitialRisk := candidateShortRisk
    activeTarget := math.round_to_mintick(close - candidateShortRisk * takeProfitR)
    activeBreakLevel := shortBreakLevel
    activeFillBar := na
    consecutiveFailureBars := 0
    breakEvenActive := false
    pendingShort := true
    pendingLong := false
    strategy.entry("CNPS52-S", strategy.short, comment="BOX BREAK SHORT", alert_message="🔴 VÀO VỊ THẾ SHORT (CNPS52)\\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\\n🛑 Cắt lỗ (SL): " + str.tostring(activeStop, format.mintick) + "\\n🎯 Chốt lời (TP): " + str.tostring(activeTarget, format.mintick))
    strategy.exit("CNPS52-S-EXIT", from_entry="CNPS52-S", stop=activeStop, limit=activeTarget, comment_profit="TP Short", comment_loss="SL Short", alert_profit="💰 CHỐT LỜI SHORT (TP HIT)\\n🎯 Giá chốt lời: " + str.tostring(activeTarget, format.mintick), alert_loss="🛑 CẮT LỖ SHORT (SL HIT)\\nGiá cắt lỗ: " + str.tostring(activeStop, format.mintick), disable_alert=disableExitAlerts)
    tradesToday += 1
    orderCount += 1
    buySetupBar := na
    sellSetupBar := na

// 12. ARM NEW OUTER BOX ONLY AFTER ASSESSING ANY PRIOR CONFIRMATION.
// Avoid using the current candle to overwrite the prior active box first.
bool qualifiedBullSetup = barstate.isconfirmed and inEntrySession and inEntrySession[1] and outerBox and isBullCandle and (not requireOpposite or prevBearCandle) and candleBodyRatio >= minimumSetupBody and boxSizeOK
bool qualifiedBearSetup = barstate.isconfirmed and inEntrySession and inEntrySession[1] and outerBox and isBearCandle and (not requireOpposite or prevBullCandle) and candleBodyRatio >= minimumSetupBody and boxSizeOK
if not finalLong and not finalShort
    if qualifiedBullSetup
        buyBoxHigh := high
        buyBoxLow := low
        buyBodyHigh := close
        buySetupBar := bar_index
        setupCount += 1
    if qualifiedBearSetup
        sellBoxHigh := high
        sellBoxLow := low
        sellBodyLow := close
        sellSetupBar := bar_index
        setupCount += 1

// 13. FILL STATE / ACTUAL RISK / BREAK EVEN
bool inLong = strategy.position_size > 0
bool inShort = strategy.position_size < 0
if (inLong or inShort) and strategy.opentrades > 0
    int observedFillBar = strategy.opentrades.entry_bar_index(0)
    if na(activeFillBar) or observedFillBar != activeFillBar
        activeFillBar := observedFillBar
        pendingLong := false
        pendingShort := false
        float fill = strategy.position_avg_price
        float actualRisk = inLong ? fill - activeStop : activeStop - fill
        activeInitialRisk := actualRisk
        if actualRisk > syminfo.mintick and actualRisk <= maximumRiskPoints
            activeTarget := math.round_to_mintick(inLong ? fill + actualRisk * takeProfitR : fill - actualRisk * takeProfitR)
        else if closeIfGapInvalid
            strategy.close(inLong ? "CNPS52-L" : "CNPS52-S", immediately=true, comment="INVALID GAP RISK", alert_message="⚠️ ĐÓNG VỊ THẾ DO GAP/RỦI RO KHÔNG HỢP LỆ (Invalid Gap)")
    float fillPrice = strategy.position_avg_price
    bool riskValid = not na(activeInitialRisk) and activeInitialRisk > syminfo.mintick and activeInitialRisk <= maximumRiskPoints
    if riskValid and barstate.isconfirmed
        float closeProfitR = inLong ? (close - fillPrice) / activeInitialRisk : (fillPrice - close) / activeInitialRisk
        if useBreakEven and closeProfitR >= breakEvenAtR
            float bePrice = math.round_to_mintick(inLong ? fillPrice + breakEvenOffset : fillPrice - breakEvenOffset)
            activeStop := inLong ? math.max(activeStop, bePrice) : math.min(activeStop, bePrice)
            breakEvenActive := true
        if useFailureExit and not na(activeBreakLevel) and bar_index > activeFillBar
            bool failedBreak = inLong ? close < activeBreakLevel - failureToleranceATR * nz(atr, 0) : close > activeBreakLevel + failureToleranceATR * nz(atr, 0)
            consecutiveFailureBars := failedBreak ? consecutiveFailureBars + 1 : 0
            if consecutiveFailureBars >= failureBarsRequired
                strategy.close(inLong ? "CNPS52-L" : "CNPS52-S", comment="FAILED BREAKOUT", alert_message="⚡ ĐÓNG VỊ THẾ DO PHÁ VỠ THẤT BẠI (Failed Breakout)")
        if inLong
            strategy.exit("CNPS52-L-EXIT", from_entry="CNPS52-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 lời: " + str.tostring(activeTarget, format.mintick), alert_loss=breakEvenActive ? "🛡️ HÒA VỐN LONG (BE HIT)\\nGiá hòa vốn: " + str.tostring(activeStop, format.mintick) : "🛑 CẮT LỖ LONG (SL HIT)\\nGiá cắt lỗ: " + str.tostring(activeStop, format.mintick), disable_alert=disableExitAlerts)
        if inShort
            strategy.exit("CNPS52-S-EXIT", from_entry="CNPS52-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 lời: " + str.tostring(activeTarget, format.mintick), alert_loss=breakEvenActive ? "🛡️ HÒA VỐN SHORT (BE HIT)\\nGiá hòa vốn: " + str.tostring(activeStop, format.mintick) : "🛑 CẮT LỖ SHORT (SL HIT)\\nGiá cắt lỗ: " + str.tostring(activeStop, format.mintick), disable_alert=disableExitAlerts)
if useTimeout and (inLong or inShort) and not na(activeFillBar) and barstate.isconfirmed and bar_index - activeFillBar >= maxHoldBars
    strategy.close(inLong ? "CNPS52-L" : "CNPS52-S", comment="TIME EXIT", alert_message="⏱️ ĐÓNG VỊ THẾ HẾT THỜI GIAN GIỮ LỆNH (Time Exit)")
int forceMinutes = forceCloseHour * 60 + forceCloseMinute
int barStartMinutes = hour(time, TZ) * 60 + minute(time, TZ)
int barCloseMinutes = hour(time_close, TZ) * 60 + minute(time_close, TZ)
bool forceClose = barstate.isconfirmed and not na(time_close) and barStartMinutes < forceMinutes and barCloseMinutes >= forceMinutes
if forceClose and (inLong or inShort)
    strategy.close_all(immediately=true, comment="VN SESSION END", alert_message="⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End)")
if flat and not finalLong and not finalShort and not pendingLong and not pendingShort
    activeStop := na
    activeTarget := na
    activeInitialRisk := na
    activeBreakLevel := na
    activeFillBar := na
    consecutiveFailureBars := 0
    breakEvenActive := false

// 14. PLOTS AND SIGNAL FUNNEL
plot(showEMAs ? emaFast : na, "EMA Fast", color=color.new(color.teal, 0), linewidth=1)
plot(showEMAs ? emaSlow : na, "EMA Slow", color=color.new(color.gray, 25), linewidth=1)
plot(showPendingLevels and not na(buySetupBar) ? buyBoxHigh : na, "Pending Long Box High", color=color.new(color.green, 15), style=plot.style_linebr)
plot(showPendingLevels and not na(sellSetupBar) ? sellBoxLow : na, "Pending Short Box Low", color=color.new(color.red, 15), style=plot.style_linebr)
plotshape(showSetup and qualifiedBullSetup, "Bullish Outer Box", style=shape.circle, location=location.belowbar, color=color.new(color.green, 30), text="BOX", textcolor=color.white, size=size.tiny)
plotshape(showSetup and qualifiedBearSetup, "Bearish Outer Box", style=shape.circle, location=location.abovebar, color=color.new(color.red, 30), text="BOX", textcolor=color.white, size=size.tiny)
plotshape(showOrders and finalLong, "Final Long", style=shape.triangleup, location=location.belowbar, color=color.green, text="L", textcolor=color.white, size=size.tiny)
plotshape(showOrders and finalShort, "Final Short", style=shape.triangledown, location=location.abovebar, color=color.red, text="S", textcolor=color.white, size=size.tiny)
plot(showSLTP and (inLong or inShort) ? activeStop : na, "Active Stop", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showSLTP and (inLong or inShort) ? activeTarget : na, "Active Target", color=color.green, linewidth=2, style=plot.style_linebr)
var table d = table.new(position.top_right, 2, 11, border_width=1)
if barstate.islast
    if showDiagnostics
        table.cell(d, 0, 0, "CNPS52 V2")
        table.cell(d, 1, 0, "QUALITY BOX")
        table.cell(d, 0, 1, "Setup count")
        table.cell(d, 1, 1, str.tostring(setupCount))
        table.cell(d, 0, 2, "Box breaks")
        table.cell(d, 1, 2, str.tostring(breakoutCount))
        table.cell(d, 0, 3, "Reject quality")
        table.cell(d, 1, 3, str.tostring(rejectedQuality))
        table.cell(d, 0, 4, "Reject risk")
        table.cell(d, 1, 4, str.tostring(rejectedRisk))
        table.cell(d, 0, 5, "Reject controls")
        table.cell(d, 1, 5, str.tostring(rejectedControls))
        table.cell(d, 0, 6, "Orders")
        table.cell(d, 1, 6, str.tostring(orderCount))
        table.cell(d, 0, 7, "Today")
        table.cell(d, 1, 7, str.tostring(tradesToday))
        table.cell(d, 0, 8, "Daily PnL")
        table.cell(d, 1, 8, str.tostring(dailyNetProfit, "#.0"))
        table.cell(d, 0, 9, "ADX")
        table.cell(d, 1, 9, str.tostring(adx, "#.0"))
        table.cell(d, 0, 10, "Position")
        table.cell(d, 1, 10, inLong ? "LONG" : inShort ? "SHORT" : "FLAT")
    else
        table.clear(d, 0, 0, 1, 10)

// BACKTEST NOTES:
// - Outer Box by itself does not imply positive expectancy.
// - Full Range Breakout & all quality filters are V2 extensions.
// - Minimum/Maximum Risk filters are pre-entry on SIGNAL CLOSE, not guarantees.
// - Entry normally fills on next available bar; initial bracket is close-based,
//   and TP is updated from ACTUAL fill when that position is first detected.
// - Daily loss stop prevents new entries only; it does NOT cap realized loss.
// - 0 strategy margin does NOT represent VN30F1M exchange margin.
// - Backtest the exact VN30F1M contract, timeframe, dates and costs.

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

2.1. Hộp bao trùm toàn dải (Outer Box / Super Envolvente Setup)

Khác với mô hình Bullish/Bearish Engulfing thông thường chỉ yêu cầu phần thân nến hiện tại bao phủ phần thân nến trước, Super Envolvente (Outer Box) đòi hỏi cây nến hiện tại phải nuốt trọn toàn bộ biên độ đỉnh – đáy của cây nến liền trước:

$$\text{outerBox} \iff \text{High}t \ge \text{High}{t-1} \quad \text{và} \quad \text{Low}t \le \text{Low}{t-1}$$

Để tránh những cây nến Doji rút chân hai đầu hoặc nến biến động quá dị biệt (quá nhỏ do thanh khoản cạn hoặc quá lớn do tin sốc), hệ thống áp dụng đồng thời 3 chỉ số đo lường hình học nến:

  1. Tỷ lệ thân nến (candleBodyRatio): $$\text{candleBodyRatio} = \frac{|\text{Close} - \text{Open}|}{\max(\text{High} - \text{Low}, \text{mintick})} \ge 0.35$$
  2. Độ rộng hộp chuẩn hóa theo ATR (boxATR): $$\text{boxATR} = \frac{\text{High} - \text{Low}}{\max(\text{ATR}(14), \text{mintick})} \in [0.60, 2.50]$$
  3. Đảo chiều màu nến (requireOpposite = true):
    • Bullish Outer Box: Nến hiện tại là nến tăng (close > open) và nến liền trước là nến giảm (close[1] < open[1]). Khi kích hoạt, bot lưu lại hộp mua gồm: buyBoxHigh = high, buyBoxLow = low, buyBodyHigh = close.
    • Bearish Outer Box: Nến hiện tại là nến giảm (close < open) và nến liền trước là nến tăng (close[1] > open[1]). Khi kích hoạt, bot lưu lại hộp bán gồm: sellBoxHigh = high, sellBoxLow = low, sellBodyLow = close.

2.2. Hai chế độ xác nhận phá vỡ (Breakout Level) và Vị trí đóng cửa (Close Location)

Sau khi một hộp Setup hợp lệ được thiết lập tại thanh nến setupBar, bot mở ra một cửa sổ chờ xác nhận kéo dài entryValidityBars (mặc định 2 thanh nến tiếp theo). Nếu quá 2 nến mà giá chưa phá vỡ, hộp Setup sẽ tự động hết hạn (buySetupBar := na hoặc sellSetupBar := na).

Bot cung cấp 2 chế độ xác định mốc phá vỡ thông qua tham số breakMode:

Chế độ breakModeMốc phá vỡ Long (longBreakLevel)Mốc phá vỡ Short (shortBreakLevel)Đặc điểm vận hành
"Full Range" (Mặc định V2)buyBoxHigh (Đỉnh cao nhất của nến Setup)sellBoxLow (Đáy thấp nhất của nến Setup)Đòi hỏi giá đóng cửa vượt hoàn toàn khỏi râu nến của hộp Setup, loại bỏ nhiễu bên trong bóng nến.
"Body (original)" (Bản gốc V1)buyBodyHigh (Giá đóng cửa của nến Bull Setup)sellBodyLow (Giá đóng cửa của nến Bear Setup)Kích hoạt sớm hơn ngay khi vượt giá đóng cửa của nến Setup nhưng dễ vướng kháng cự/hỗ trợ tại râu nến.

Bên cạnh việc đóng cửa vượt qua mốc BreakLevel cộng thêm bộ đệm breakBuffer = breakBufferTicks * syminfo.mintick, cây nến phá vỡ (Trigger Candle) phải thỏa mãn chỉ số vị trí đóng cửa (candleCloseLocation):

$$\text{candleCloseLocation} = \frac{\text{Close} - \text{Low}}{\max(\text{High} - \text{Low}, \text{mintick})}$$

  • Với lệnh Long: Yêu cầu candleCloseLocation >= 0.65 (giá đóng cửa nằm trong 35% phần trên cùng của cây nến phá vỡ).
  • Với lệnh Short: Yêu cầu candleCloseLocation <= 1.0 - 0.65 = 0.35 (giá đóng cửa nằm trong 35% phần dưới cùng của cây nến phá vỡ).

2.3. Bộ lọc xu hướng EMA đa điều kiện và tùy chọn ADX / Volume

Để đảm bảo lệnh Breakout không đi ngược xu hướng chủ đạo trong phiên của VN30F1M, CNPS52 kiểm tra sự đồng thuận của cặp đường trung bình động EMA 21 (emaFast) và EMA 55 (emaSlow):

  • Điều kiện xu hướng Long (trendLongOK):
    1. emaFast > emaSlow (EMA 21 nằm trên EMA 55).
    2. emaFast > emaFast[3] (EMA 21 đang hướng lên so với 3 nến trước).
    3. close > emaFast (Giá đóng cửa của nến phá vỡ nằm trên EMA 21).
  • Điều kiện xu hướng Short (trendShortOK):
    1. emaFast < emaSlow (EMA 21 nằm dưới EMA 55).
    2. emaFast < emaFast[3] (EMA 21 đang dốc xuống so với 3 nến trước).
    3. close < emaFast (Giá đóng cửa của nến phá vỡ nằm dưới EMA 21).

Ngoài ra, người dùng có thể bật thêm 2 bộ lọc phụ tùy chọn:

  • Bộ lọc cường độ xu hướng ADX (useADXFilter): Yêu cầu ADX(14) >= 16.0.
  • Bộ lọc thanh khoản Volume (useVolumeFilter): Yêu cầu volume >= SMA(volume, 20) * 0.85.

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

Quy trình xử lý của Bot CNPS52 trên mỗi thanh nến được thiết kế chặt chẽ theo trình tự 5 bước nhằm chống hiện tượng ghi đè trạng thái (State Overwrite) giữa nến Setup cũ và nến hiện tại:

  1. Bước 1 – Khởi tạo ngày giao dịch và cửa sổ phiên:

    • Khi bước sang ngày giao dịch mới (newTradingDay), hệ thống reset bộ đếm tradesToday := 0, lưu mốc lợi nhuận đầu ngày startingNetProfit := strategy.netprofit và xóa lastExitBar := na.
    • Khi bắt đầu ngày mới hoặc vừa bước vào khung giờ giao dịch sáng/chiều (newTradingDay or startEntryWindow), toàn bộ các hộp Setup đang treo (buySetupBar, sellSetupBar) đều được xóa sạch để tránh dùng lại mẫu hình cũ từ phiên trước.
    • Kiểm tra hạn sử dụng của hộp Setup: Nếu bar_index - buySetupBar > entryValidityBars (quá 2 nến), hủy hộp Setup đó.
  2. Bước 2 – Đánh giá tín hiệu phá vỡ từ hộp Setup trước đó (Prior Setup Assessment):

    • Trước khi xét xem cây nến hiện tại có phải là một hộp Setup mới hay không, bot ưu tiên kiểm tra xem cây nến hiện tại có phá vỡ hộp activeBuy hoặc activeSell đã được nạp từ 1–2 nến trước hay không (longBreak / shortBreak).
    • Nếu có phá vỡ, bot tiếp tục kiểm tra chất lượng nến & xu hướng (triggerLongQuality / triggerShortQuality), tính toán mức Stop Loss cấu trúc ứng viên (candidateLongStop / candidateShortStop) và kiểm tra khoảng rủi ro (longRiskOK / shortRiskOK nằm trong 1.5 – 12.0 điểm).
    • Mọi tín hiệu phá vỡ bị từ chối đều được phân loại và cộng dồn vào bộ đếm phễu chẩn đoán (rejectedQuality, rejectedRisk, rejectedControls).
  3. Bước 3 – Phát lệnh giao dịch và thiết lập Bracket ban đầu:

    • Khi thỏa mãn đồng thời điều kiện kiểm soát chung (commonOK), chất lượng phá vỡ và biên độ rủi ro (finalLong hoặc finalShort), bot gửi lệnh strategy.entry("CNPS52-L", ...) hoặc strategy.entry("CNPS52-S", ...) cùng lệnh chờ thoát strategy.exit với activeStop và activeTarget = close +/- candidateRisk * 1.5.
    • Ngay sau khi phát lệnh, bot xóa trạng thái hộp Setup (buySetupBar := na, sellSetupBar := na) và tăng bộ đếm tradesToday += 1.
  4. Bước 4 – Nạp hộp Setup mới (Arm New Outer Box):

    • Chỉ khi thanh nến hiện tại không kích hoạt lệnh vào (not finalLong and not finalShort), bot mới kiểm tra điều kiện qualifiedBullSetup hoặc qualifiedBearSetup.
    • Lưu ý quan trọng: Điều kiện tạo Setup yêu cầu cả thanh nến hiện tại và thanh nến liền trước đều phải nằm trong phiên giao dịch (inEntrySession and inEntrySession[1]), đảm bảo cây nến đầu tiên của phiên không so sánh biên độ với cây nến cuối phiên trước.
  5. Bước 5 – Hậu kiểm giá khớp thực tế, quản trị vị thế đang mở và đóng lệnh cuối phiên:

    • Ngay tại thanh nến lệnh được khớp thực tế (observedFillBar), bot lấy giá khớp trung bình fill = strategy.position_avg_price để tính lại rủi ro thực tế (actualRisk) và cập nhật lại mức chốt lời activeTarget. Nếu trượt giá hoặc nhảy Gap làm actualRisk <= mintick hoặc actualRisk > 12.0 điểm, bot kích hoạt đóng lệnh khẩn cấp (INVALID GAP RISK).
    • Trong suốt thời gian giữ lệnh, bot theo dõi điều kiện dời SL về hòa vốn (Break Even), thoát lệnh sớm khi phá vỡ thất bại (Failed Breakout), thoát lệnh khi giữ quá 30 nến (Time Exit) và đóng toàn bộ vị thế lúc 14:45 (VN SESSION END).

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

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

Một lệnh Long (CNPS52-L) được kích hoạt khi hoàn tất tuần tự 2 giai đoạn Setup và Trigger:

  • Giai đoạn 1 – Hình thành Bullish Outer Box (qualifiedBullSetup):
    • Nến đã đóng cửa (barstate.isconfirmed), cả nến hiện tại và nến trước đó đều thuộc khung giờ giao dịch (inEntrySession and inEntrySession[1]).
    • Biên độ nến bao trùm toàn dải nến trước: high >= high[1] và low <= low[1].
    • Là nến tăng (close > open) và nến liền trước là nến giảm (close[1] < open[1] khi requireOpposite = true).
    • Tỷ lệ thân nến candleBodyRatio >= 0.35.
    • Kích thước hộp chuẩn hóa theo ATR: 0.60 <= (high - low) / ATR(14) <= 2.50.
  • Giai đoạn 2 – Phá vỡ xác nhận Long (finalLong) trong vòng 1–2 nến kế tiếp:
    • Hộp mua đang còn hiệu lực: 1 <= bar_index - buySetupBar <= 2.
    • Nến hiện tại là nến tăng (close > open) và đóng cửa vượt đỉnh hộp: close > longBreakLevel + breakBuffer (mặc định longBreakLevel = buyBoxHigh).
    • Chất lượng nến phá vỡ: candleBodyRatio >= 0.35 và vị trí đóng cửa candleCloseLocation >= 0.65.
    • Bộ lọc xu hướng (useTrendFilter = true): EMA 21 > EMA 55, EMA 21 > EMA 21[3] và close > EMA 21.
    • Thỏa mãn bộ lọc ADX và Volume (nếu bật).
    • Rủi ro dự kiến hợp lệ (longRiskOK): 1.5 <= close - candidateLongStop <= 12.0 điểm.
    • Thỏa mãn toàn bộ điều kiện kiểm soát chung (commonOK, canLong).

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

Một lệnh Short (CNPS52-S) được kích hoạt khi thỏa mãn tuần tự 2 giai đoạn Setup và Trigger (và không trùng tín hiệu finalLong trên cùng thanh nến):

  • Giai đoạn 1 – Hình thành Bearish Outer Box (qualifiedBearSetup):
    • Nến đã đóng cửa (barstate.isconfirmed), cả nến hiện tại và nến trước đó đều thuộc khung giờ giao dịch (inEntrySession and inEntrySession[1]).
    • Biên độ nến bao trùm toàn dải nến trước: high >= high[1] và low <= low[1].
    • Là nến giảm (close < open) và nến liền trước là nến tăng (close[1] > open[1] khi requireOpposite = true).
    • Tỷ lệ thân nến candleBodyRatio >= 0.35.
    • Kích thước hộp chuẩn hóa theo ATR: 0.60 <= (high - low) / ATR(14) <= 2.50.
  • Giai đoạn 2 – Phá vỡ xác nhận Short (finalShort) trong vòng 1–2 nến kế tiếp:
    • Hộp bán đang còn hiệu lực: 1 <= bar_index - sellSetupBar <= 2.
    • Nến hiện tại là nến giảm (close < open) và đóng cửa thủng đáy hộp: close < shortBreakLevel - breakBuffer (mặc định shortBreakLevel = sellBoxLow).
    • Chất lượng nến phá vỡ: candleBodyRatio >= 0.35 và vị trí đóng cửa candleCloseLocation <= 0.35.
    • Bộ lọc xu hướng (useTrendFilter = true): EMA 21 < EMA 55, EMA 21 < EMA 21[3] và close < EMA 21.
    • Thỏa mãn bộ lọc ADX và Volume (nếu bật).
    • Rủi ro dự kiến hợp lệ (shortRiskOK): 1.5 <= candidateShortStop - close <= 12.0 điểm.
    • Thỏa mãn toàn bộ điều kiện kiểm soát chung (commonOK, canShort).

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

Mọi tín hiệu Long hoặc Short đều phải vượt qua cổng kiểm soát an toàn commonOK:

  • Xác nhận đóng nến (barstate.isconfirmed): Chỉ phát tín hiệu khi thanh nến đã hoàn tất, chống repainting trong nến.
  • Khung giờ phiên Việt Nam (inEntrySession): Chỉ giao dịch trong phiên sáng 09:10 – 11:20 và phiên chiều 13:05 – 14:20 (múi giờ Asia/Ho_Chi_Minh).
  • Trạng thái không có vị thế (flat): strategy.position_size == 0 (không nhồi lệnh / pyramiding = 0).
  • Thời gian nghỉ sau thoát lệnh (cooldownOK): Phải cách thanh nến đóng lệnh gần nhất nhiều hơn 2 thanh nến (bar_index - lastExitBar > 2).
  • Giới hạn số lệnh trong ngày (tradeLimitOK): Số lệnh đã phát trong ngày tradesToday < 4 (khi maximumTradesPerDay = 4).
  • Giới hạn lỗ ròng trong ngày (dailyLossOK): Lợi nhuận ròng trong ngày dailyNetProfit > -2.500.000 VNĐ (khi useDailyLossStop = true).

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

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

CNPS52 cung cấp 3 phương pháp xác định mốc Stop Loss cơ sở (longStopBase / shortStopBase) tùy theo khẩu vị rủi ro của nhà đầu tư thông qua tham số stopMode, sau đó cộng thêm khoảng đệm biến động stopBuffer = ATR(14) * 0.10:

Chế độ stopModeCông thức longStopBase (Lệnh Long)Công thức shortStopBase (Lệnh Short)Đặc điểm quản trị rủi ro
"Half Box Protected" (Mặc định)math.min((buyBoxHigh + buyBoxLow) * 0.5, low)math.max((sellBoxHigh + sellBoxLow) * 0.5, high)Đặt SL dưới điểm giữa (50%) của hộp Setup hoặc cực trị của nến Trigger (lấy mức an toàn hơn). Cân bằng tối ưu giữa tỷ lệ R:R và độ an toàn.
"Full Box"math.min(buyBoxLow, low)math.max(sellBoxHigh, high)Đặt SL dưới đáy toàn hộp mua (hoặc trên đỉnh toàn hộp bán). Độ an toàn cao nhất nhưng khoảng SL rộng hơn.
"Trigger Candle"low (Đáy nến phá vỡ)high (Đỉnh nến phá vỡ)Đặt SL紧 sát ngay dưới đáy/đỉnh của cây nến phá vỡ. Khoảng rủi ro nhỏ, giúp đạt hệ số R nhanh nhưng dễ bị quét hơn.

Từ mốc cơ sở trên, giá cắt lỗ và rủi ro ứng viên được làm tròn theo bước giá (mintick):

  • Lệnh Long: candidateLongStop = round_to_mintick(longStopBase - stopBuffer) và candidateLongRisk = close - candidateLongStop.
  • Lệnh Short: candidateShortStop = round_to_mintick(shortStopBase + stopBuffer) và candidateShortRisk = candidateShortStop - close.
  • Bộ lọc biên độ rủi ro (minimumRiskPoints – maximumRiskPoints): Lệnh chỉ được phép thực thi nếu rủi ro nằm trong khoảng từ 1.5 điểm đến 12.0 điểm. Nếu SL quá sát (< 1.5 điểm) hoặc quá xa (> 12.0 điểm), lệnh sẽ bị từ chối và ghi nhận vào Reject risk.

5.2. Cơ chế Take Profit, Break Even và Thoát lệnh phá vỡ thất bại (Failed Breakout)

  1. Cập nhật Take Profit theo giá khớp thực tế (actualRisk):
    • Khi phát tín hiệu tại giá đóng cửa, TP ban đầu được đặt tạm tính tại close +/- candidateRisk * 1.5.
    • Ngay khi lệnh khớp trên sàn (observedFillBar), bot lấy giá khớp thực tế fill = strategy.position_avg_price để tính lại actualRisk = fill - activeStop (với Long) hoặc activeStop - fill (với Short), sau đó cập nhật lại mức chốt lời chính xác: $$\text{activeTarget} = \text{round_to_mintick}(\text{fill} \pm \text{actualRisk} \times 1.5)$$
  2. Cơ chế dời dừng lỗ về hòa vốn (Break Even):
    • Khi useBreakEven = true, tại thời điểm đóng nến, bot tính lợi nhuận hiện tại theo bội số R: $$\text{closeProfitR} = \frac{\text{Close} - \text{fillPrice}}{\text{activeInitialRisk}} \quad (\text{với Long}) \quad \text{hoặc} \quad \frac{\text{fillPrice} - \text{Close}}{\text{activeInitialRisk}} \quad (\text{với Short})$$
    • Khi closeProfitR >= 1.0 (breakEvenAtR = 1.0), mức dừng lỗ activeStop được nâng lên fillPrice + 0.2 điểm (với Long) hoặc hạ xuống fillPrice - 0.2 điểm (với Short) để bảo toàn vốn và bù phí giao dịch.
  3. Cơ chế thoát lệnh sớm khi phá vỡ thất bại (Failed Breakout Exit):
    • Từ các thanh nến sau thanh nến khớp lệnh (bar_index > activeFillBar), nếu giá không tiếp tục đi theo hướng Breakout mà quay đầu đóng cửa tụt sâu vào bên trong mốc phá vỡ quá ngưỡng dung sai 0.15 * ATR(14):
      • Long thất bại: close < activeBreakLevel - 0.15 * ATR(14)
      • Short thất bại: close > activeBreakLevel + 0.15 * ATR(14)
    • Mỗi thanh nến vi phạm liên tiếp sẽ làm tăng bộ đếm consecutiveFailureBars += 1 (nếu có 1 nến phục hồi thì bộ đếm reset về 0). Ngay khi chạm mốc 2 nến liên tiếp (failureBarsRequired = 2), bot lập tức đóng vị thế theo giá thị trường với nhãn "FAILED BREAKOUT" trước khi giá kịp chạm xuống Stop Loss ban đầu.

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

Cơ chế thoát lệnhĐiều kiện kích hoạt trong codeHành động của BotComment trên biểu đồ
Chốt lời mục tiêu (Take Profit)Giá chạm mức activeTarget (fill +/- actualRisk * 1.5)Đóng lệnh Limit qua strategy.exitTP Long / TP Short
Cắt lỗ cấu trúc (Stop Loss)Giá chạm mức activeStop khi chưa kích hoạt Break EvenĐóng lệnh Stop qua strategy.exitSL Long / SL Short
Dừng lỗ hòa vốn (Break Even Stop)Giá quay lại chạm activeStop sau khi đã đạt closeProfitR >= 1.0R (SL đã dời về fill +/- 0.2)Đóng lệnh Stop qua strategy.exitBE Long / BE Short
Bảo vệ trượt giá / Gap (Invalid Gap Risk)Ngay khi khớp lệnh, actualRisk <= mintick hoặc actualRisk > 12.0 điểm (closeIfGapInvalid = true)Đóng lệnh ngay lập tức (immediately=true)INVALID GAP RISK
Phá vỡ thất bại (Failed Breakout)Có 2 nến liên tiếp đóng cửa thụt lùi quá 0.15 x ATR so với activeBreakLevelĐóng lệnh qua strategy.close khi đóng nếnFAILED BREAKOUT
Thoát lệnh theo thời gian (Time Exit)Thời gian giữ lệnh bar_index - activeFillBar >= 30 thanh nến (useTimeout = true)Đóng lệnh qua strategy.close khi đóng nếnTIME EXIT
Đóng lệnh cuối phiên (Session End)Thanh nến bắt đầu trước 14:45 và đóng cửa từ 14:45 trở đi (forceClose)Đóng toàn bộ vị thế ngay lập tức (strategy.close_all)VN SESSION END

6. Hướng dẫn cài đặt và đọc bảng Diagnostics trên TradingView

Các bước cài đặt

  1. Đăng nhập vào TradingView, mở biểu đồ hợp đồng tương lai VN30F1M (khuyến nghị khung thời gian 3 phút hoặc 5 phút).
  2. Mở tab Pine Editor ở thanh công cụ phía dưới màn hình.
  3. Xóa đoạn mã mặc định trong trình soạn thảo, sao chép toàn bộ mã nguồn Pine Script v6 tại Mục 1 của bài viết này và dán vào Pine Editor.
  4. Nhấn Save (Lưu) và chọn Add to chart (Thêm vào biểu đồ).
  5. Mở phần Settings (Cài đặt) của chiến lược (biểu tượng bánh răng) để tinh chỉnh khung giờ, chế độ Breakout Level, Structural Stop hoặc bật thêm bộ lọc ADX / Volume theo nhu cầu.

Cách đọc bảng chẩn đoán (Diagnostics Table)

Khi tùy chọn Show Signal Funnel (showDiagnostics = true) được bật, bot sẽ hiển thị một bảng thống kê phễu tín hiệu ở góc trên bên phải màn hình (position.top_right) gồm 11 dòng dữ liệu trực quan:

Dòng hiển thịGiá trị / Biến trong codeÝ nghĩa chẩn đoán thực tế
CNPS52 V2 / QUALITY BOXTiêu đề bảngTên phiên bản chiến lược và cơ chế hộp chất lượng cao
Setup countsetupCountTổng số hộp Bullish/Bearish Outer Box hợp lệ đã được phát hiện trong lịch sử
Box breaksbreakoutCountTổng số lần giá đóng cửa phá vỡ qua mốc hộp Setup trong cửa sổ 2 nến
Reject qualityrejectedQualitySố lần phá vỡ bị từ chối do không đạt chất lượng nến (Body, Close Location) hoặc ngược xu hướng EMA / ADX / Volume
Reject riskrejectedRiskSố lần phá vỡ đạt chất lượng nhưng bị từ chối do khoảng SL nhỏ hơn 1.5 điểm hoặc lớn hơn 12.0 điểm
Reject controlsrejectedControlsSố lần phá vỡ bị từ chối do điều kiện kiểm soát (ngoài giờ phiên, đang có lệnh, vướng Cooldown, quá 4 lệnh/ngày hoặc chạm ngưỡng lỗ ngày)
OrdersorderCountTổng số lệnh giao dịch thực tế đã vượt qua toàn bộ phễu lọc và được gửi đi
TodaytradesTodaySố lệnh đã thực hiện trong ngày giao dịch hiện tại (tối đa 4 lệnh theo mặc định)
Daily PnLdailyNetProfitLợi nhuận ròng trong ngày hiện tại (VNĐ), dùng để đối chiếu với hạn mức lỗ -2.500.000 VNĐ
ADXadxGiá trị chỉ báo cường độ xu hướng ADX(14) tại thanh nến hiện tại
PositionLONG / SHORT / FLATTrạng thái vị thế hiện tại của Bot trên biểu đồ

7. Cách thiết lập cảnh báo tín hiệu giao dịch (Alert)

Để nhận thông báo tự động qua Telegram, Discord, Webhook hoặc ứng dụng TradingView khi Bot CNPS52 phát tín hiệu giao dịch trên VN30F1M, bạn thực hiện như sau:

  1. Trên biểu đồ đã cài đặt chiến lược CNPS52 ENV V2, nhấn tổ hợp phím Alt + A (hoặc bấm vào biểu tượng chiếc đồng hồ Alert trên thanh công cụ bên phải).
  2. Tại mục Condition (Điều kiện), chọn tên chiến lược CNPS52 SUPER ENVOLVENTE V2 QUALITY BREAKOUT - VN30F1M và giữ chế độ Order fills only.
  3. Tại mục Alert name (Tên cảnh báo), đặt tên gợi nhớ, ví dụ: CNPS52 - VN30F1M Auto Signal.
  4. Tại ô Message (Nội dung tin nhắn), xóa toàn bộ nội dung mặc định và nhập chính xác cú pháp động sau:
{{strategy.order.alert_message}}
  1. Chuyển sang tab Notifications (Thông báo), tích chọn Webhook URL (nếu kết nối bot tự động qua API công ty chứng khoán/Telegram) hoặc bật Notify on app, sau đó nhấn Create (Tạo).

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

Khi sử dụng biến {{strategy.order.alert_message}}, hệ thống sẽ tự động xuất ra các thông điệp tiếng Việt chi tiết theo đúng từng sự kiện được lập trình trong mã nguồn:

Sự kiện giao dịchMã lệnh / Nguồn phátNội dung alert_message / alert_profit / alert_loss thực tế
Mở vị thế Longstrategy.entry("CNPS52-L")🟢 VÀO VỊ THẾ LONG (CNPS52)
🎯 Giá vào: <close>
🛑 Cắt lỗ (SL): <activeStop>
🎯 Chốt lời (TP): <activeTarget>
Mở vị thế Shortstrategy.entry("CNPS52-S")🔴 VÀO VỊ THẾ SHORT (CNPS52)
🎯 Giá vào: <close>
🛑 Cắt lỗ (SL): <activeStop>
🎯 Chốt lời (TP): <activeTarget>
Chốt lời Long (TP Hit)strategy.exit("CNPS52-L-EXIT") (alert_profit)💰 CHỐT LỜI LONG (TP HIT)
🎯 Giá chốt lời: <activeTarget>
Chốt lời Short (TP Hit)strategy.exit("CNPS52-S-EXIT") (alert_profit)💰 CHỐT LỜI SHORT (TP HIT)
🎯 Giá chốt lời: <activeTarget>
Cắt lỗ Long (SL Hit)strategy.exit("CNPS52-L-EXIT") (alert_loss khi chưa BE)🛑 CẮT LỖ LONG (SL HIT)
Giá cắt lỗ: <activeStop>
Cắt lỗ Short (SL Hit)strategy.exit("CNPS52-S-EXIT") (alert_loss khi chưa BE)🛑 CẮT LỖ SHORT (SL HIT)
Giá cắt lỗ: <activeStop>
Hòa vốn Long (BE Hit)strategy.exit("CNPS52-L-EXIT") (alert_loss khi breakEvenActive)🛡️ HÒA VỐN LONG (BE HIT)
Giá hòa vốn: <activeStop>
Hòa vốn Short (BE Hit)strategy.exit("CNPS52-S-EXIT") (alert_loss khi breakEvenActive)🛡️ HÒA VỐN SHORT (BE HIT)
Giá hòa vốn: <activeStop>
Đóng lệnh do rủi ro Gap không hợp lệstrategy.close (INVALID GAP RISK)⚠️ ĐÓNG VỊ THẾ DO GAP/RỦI RO KHÔNG HỢP LỆ (Invalid Gap)
Đóng lệnh sớm do phá vỡ thất bạistrategy.close (FAILED BREAKOUT)⚡ ĐÓNG VỊ THẾ DO PHÁ VỠ THẤT BẠI (Failed Breakout)
Đóng lệnh hết thời gian giữ tối đastrategy.close (TIME EXIT)⏱️ ĐÓNG VỊ THẾ HẾT THỜI GIAN GIỮ LỆNH (Time Exit)
Đóng lệnh bắt buộc cuối phiên 14:45strategy.close_all (VN SESSION END)⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End)

Kết luận

Bot CNPS52 Super Envolvente V2 Quality Breakout là một bản nâng cấp toàn diện cho phương pháp giao dịch theo mô hình nến nhấn chìm toàn dải (Full-Range Engulfing) trên thị trường phái sinh VN30F1M. Bằng cách bắt buộc cây nến xác nhận phải đóng cửa vượt ra ngoài toàn bộ đỉnh/đáy của hộp Setup (Full Range Breakout), kết hợp cùng bộ lọc xu hướng EMA 21 / EMA 55, quản trị dừng lỗ cấu trúc Half Box Protected và cơ chế thoát lệnh sớm khi có 2 nến liên tiếp thất bại (Failed Breakout Exit), chiến lược giúp nhà đầu tư loại bỏ đáng kể các tín hiệu bẫy giá trong vùng râu nến và kiểm soát chặt chẽ rủi ro trong phiên. Hệ thống hoạt động hiệu quả nhất trong các phiên thị trường có nhịp tích lũy ngắn rồi bùng nổ theo xu hướng rõ ràng.

Để đa dạng hóa danh mục hệ thống giao dịch tự động trên VN30F1M, bạn có thể tham khảo thêm các chiến lược bổ trợ như Bot CNPS50 - Trend Analysis V2 (tập trung vào nhịp hồi quy chất lượng cao theo xu hướng) và Bot CNPS49 - Daily Open (giao dịch theo mốc giá mở cửa phiên hàng ngày).

Thông tin chỉ mang tính tham khảo, không phải khuyến nghị đầu tư. Kết quả kiểm thử quá khứ không đảm bảo lợi nhuận trong tương lai.

Thông tin trong bài chỉ mang tính tham khảo, không phải khuyến nghị mua bán. Giao dịch phái sinh có rủi ro cao do sử dụng đòn bẩy; nhà đầu tư tự chịu trách nhiệm với quyết định của mình.

Đinh Mạnh Đạt

Nhà nghiên cứu định lượng, chuyên sâu về dữ liệu Open Interest và quản trị vị thế.

Bản tin phái sinh mỗi phiên
Nhận bản tin mỗi phiên + Dự báo Nhịp đập phái sinh

Giao dịch & cuộc sống

Xem tất cả →
Cộng đồng