Thứ Tư, 02/12/202602/12/2026

Hướng Dẫn Sử Dụng Bot CNPS96 - Choppiness Regime Breakout V1 cho VN30F1M

Bot CNPS96 sử dụng chỉ số Choppiness Index (CHOP) để nhận diện thời điểm thị trường VN30F1M chuyển từ giai đoạn đi ngang (choppy) sang có xu hướng (trending), kết hợp phá vỡ kênh giá N nến và quản trị rủi ro SL/TP cố định.

Hướng dẫn sử dụng Bot CNPS96 cho VN30F1M
Hướng dẫn sử dụng Bot CNPS96 cho VN30F1M
Mục lục
Mục lục

Khi giao dịch hợp đồng tương lai VN30F1M, một trong những nguyên nhân phổ biến nhất dẫn đến thua lỗ là việc áp dụng chiến lược đánh phá vỡ (breakout) liên tục ngay cả khi thị trường đang ở trạng thái đi ngang nhiễu loạn (choppy / range-bound). Những nhịp bứt phá thiếu động lượng trong vùng tích lũy thường nhanh chóng đảo chiều, khiến nhà đầu tư liên tiếp gặp bẫy phá vỡ giả (false breakout).

Để giải quyết bài toán phân biệt pha thị trường này, chiến lược CNPS96 CHOPPINESS REGIME BREAKOUT V1 được xây dựng trên nền tảng Pine Script v6 của TradingView. Thay vì giao dịch mọi tín hiệu vượt đỉnh hoặc thủng đáy, hệ thống sử dụng chỉ số Choppiness Index (CHOP) làm bộ lọc trạng thái cốt lõi, chỉ mở cửa sổ tìm kiếm điểm vào lệnh khi thị trường chuyển pha từ đi ngang sang có xu hướng.

Những điểm nổi bật của Bot CNPS96:

  • Nhận diện chuyển pha bằng Choppiness Index (CHOP): Chỉ kích hoạt trạng thái xu hướng khi thị trường vừa trải qua giai đoạn CHOP cao (tích lũy/nhiễu) và chỉ số CHOP cắt xuống dưới ngưỡng xu hướng.
  • Hai chế độ giao dịch linh hoạt: Hỗ trợ chế độ Breakouts During Trend Regime (cho phép nhiều nhịp phá vỡ trong pha xu hướng) và First Regime Breakout (chỉ giao dịch nhịp phá vỡ đầu tiên của mỗi pha).
  • Tín hiệu xác nhận trên nến đóng: Toàn bộ điều kiện chuyển pha, phá vỡ kênh giá N nến và kiểm tra chất lượng thân nến đều chạy trên barstate.isconfirmed, không sử dụng future pivots.
  • Quản trị rủi ro chặt chẽ: Cắt lỗ (SL) và chốt lời (TP) cố định theo điểm, giới hạn số lệnh tối đa mỗi ngày, có thời gian nghỉ (cooldown) sau thoát lệnh và tự động đóng toàn bộ vị thế cuối phiên.

1. CNPS96 Choppiness Regime Breakout V1 là gì?

CNPS96 Choppiness Regime Breakout V1 là một hệ thống giao dịch theo sự chuyển đổi trạng thái thị trường (Regime-Switching Breakout), được cấu thành từ 4 trụ cột kỹ thuật chính:

  1. Bộ đo lường Choppiness Index (CHOP): Tính tỷ lệ giữa tổng biên độ dao động thực (True Range) trong N nến với tổng biên độ giá từ đỉnh cao nhất đến đáy thấp nhất của cùng chu kỳ theo thang logarit. Nhờ đó, bot phân tách rõ giai đoạn thị trường đi ngang kém hiệu quả (CHOP >= 61.8) và giai đoạn có xu hướng (CHOP <= 55.0).
  2. Bộ quản lý trạng thái pha xu hướng (Regime Management): Khi xuất hiện tín hiệu chuyển pha hợp lệ, bot bật trạng thái activeTrendRegime và theo dõi tuổi thọ của pha (regimeAge). Pha xu hướng sẽ tự động kết thúc nếu kéo dài quá 35 nến, khi CHOP bật tăng ngược lại vượt ngưỡng 58.0, hoặc khi bước sang ngày giao dịch mới.
  3. Cấu trúc phá vỡ kênh giá & Sức mạnh nến: Trong pha xu hướng đang hoạt động, bot tìm kiếm nến đóng cửa vượt đỉnh cao nhất hoặc thủng đáy thấp nhất của 5 nến liền trước (previousChannelHigh / previousChannelLow), đồng thời yêu cầu nến phá vỡ phải đi đúng hướng và có tỷ lệ thân nến tối thiểu (>= 0.40).
  4. Hệ thống bộ lọc bổ trợ & Kiểm soát rủi ro: Tích hợp sẵn các bộ lọc tùy chọn gồm EMA xu hướng, Khối lượng tương đối (Relative Volume), ADX/DI, RSI và xu hướng khung H1 (H1 EMA Bias), đi kèm cơ chế SL/TP cố định (5.0 / 15.0 điểm) và đóng vị thế bắt buộc vào 14:45.

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

Nhóm thông sốTham số trong codeGiá trị mặc địnhÝ nghĩa
01. Choppiness IndexchopLength / choppyThreshold / trendingThreshold14 / 61.8 / 55.0Chu kỳ CHOP, ngưỡng đi ngang và ngưỡng xu hướng
01. Choppiness IndexrecentChopLookback / requireRecentChop30 / trueKiểm tra CHOP từng đạt ngưỡng đi ngang trong 30 nến trước
01. Choppiness IndexrequireChopFalling / chopSlopeBarsfalse / 1Tùy chọn yêu cầu CHOP đang giảm so với N nến trước
02. Regime ManagemententryMode"Breakouts During Trend Regime"Chế độ vào nhiều lệnh hoặc chỉ lệnh đầu tiên mỗi pha
02. Regime ManagementmaximumRegimeBars / regimeResetThreshold / useRegimeAgeFilter35 / 58.0 / trueTuổi thọ tối đa của pha (35 nến) và ngưỡng CHOP hủy pha
03. Price BreakoutbreakoutLookback / useBreakoutBuffer / breakoutBufferATR / requireFreshBreakout5 / false / 0.05 / falseKênh giá 5 nến trước, đệm ATR và yêu cầu cắt mới
04. Breakout CandlerequireDirectionalCandle / useBodyFilter / minimumBodyRatiotrue / true / 0.40Nến đúng chiều và tỷ lệ thân/biên độ tối thiểu 40%
04. Breakout CandleuseCloseLocation / minimumLongClose / maximumShortClosefalse / 0.65 / 0.35Tùy chọn lọc vị trí giá đóng cửa trong biên độ nến
04. Breakout CandleuseCandleRangeFilter / minimumCandleRangeATR / maximumCandleRangeATRfalse / 0.50 / 3.00Tùy chọn giới hạn biên độ nến theo ATR
05. EMA TrenduseEMAFilter / emaLength / requireEMASlope / emaSlopeBars / requirePriceEMAfalse / 50 / true / 3 / trueBộ lọc xu hướng và độ dốc EMA 50
06. Volume FilteruseVolumeFilter / volumeLength / minimumVolumeFactorfalse / 20 / 1.0Bộ lọc khối lượng tương đối so với SMA 20
07. Momentum FiltersuseADXFilter / diLength / adxSmoothing / minimumADX / requireDIDirectionfalse / 14 / 14 / 18.0 / falseBộ lọc sức mạnh xu hướng ADX và hướng DI+/DI-
07. Momentum FiltersuseRSIFilter / rsiLength / minimumLongRSI / maximumShortRSIfalse / 14 / 52.0 / 48.0Bộ lọc động lượng RSI theo chiều Long/Short
08. H1 BiasuseH1Bias / h1EMALengthfalse / 50Bộ lọc xu hướng khung H1 đã xác nhận qua EMA 50
09. Risk ManagementstopLossPoints / takeProfitPoints5.0 / 15.0Cắt lỗ 5.0 điểm và chốt lời 15.0 điểm cố định
09. Risk ManagementuseTimeExit / maximumHoldingBarsfalse / 20Tùy chọn đóng lệnh nếu giữ quá 20 nến
10. Trade ControltradeDirection / contracts / maximumTradesPerDay"Both" / 3 / 3Chiều giao dịch, số hợp đồng khai báo và tối đa 3 lệnh/ngày
10. Trade ControlcooldownBars / minimumBarsBetweenEntries2 / 3Số nến nghỉ sau khi đóng lệnh và giãn cách giữa các lệnh
11. Trading Sessiontz / useSessionFilter / startHour:startMinute / lastHour:lastMinute / endHour:endMinute"Asia/Ho_Chi_Minh" / true / 09:15 / 14:15 / 14:45Khung giờ nhận lệnh (09:15–14:15) và đóng phiên (14:45)
12. AlertsdisableExitAlertsfalseBật/tắt cảnh báo khi chạm SL hoặc TP
13. DisplayshowEMA / showEntryMarkers / showSLTP / showDiagnosticstrue / true / true / falseTùy chọn hiển thị EMA, điểm vào, SL/TP và bảng Diagnostics

(Lưu ý kỹ thuật: Trong hàm strategy(), bot cấu hình default_qty_type=strategy.fixed, default_qty_value=1 và lệnh strategy.entry() không truyền tham số qty, nên khối lượng thực thi mặc định trên biểu đồ là 1 hợp đồng mỗi lệnh dù tham số contracts khai báo giá trị 3.)

Source Code CNPS96 Choppiness Regime Breakout 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
strategy(title="CNPS96 CHOPPINESS REGIME BREAKOUT V1", shorttitle="CNPS96 CHOP BREAK", overlay=true, initial_capital=100000000, 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, fill_orders_on_standard_ohlc=true, process_orders_on_close=true, calc_on_order_fills=false, max_labels_count=300, max_lines_count=300, max_bars_back=5000)

// ============================================================================
// CNPS96 - CHOPPINESS REGIME BREAKOUT V1
//
// CORE IDEA:
//
// A market often alternates between:
// 1. CHOPPY / RANGE-BOUND REGIME
// 2. DIRECTIONAL / TRENDING REGIME
//
// The Choppiness Index measures the ratio of
// cumulative True Range to total price range.
//
// CHOP = 100 * log10(Sum(TR, N) /
//                    (HighestHigh(N) - LowestLow(N)))
//              / log10(N)
//
// HIGH CHOP:
// Price movement is relatively inefficient.
//
// LOW CHOP:
// Price movement is relatively directional.
//
// SIGNAL PROCESS:
//
// 1. Detect a recent high-CHOP period.
// 2. Wait for CHOP to cross below trend threshold.
// 3. Activate a trend-transition window.
// 4. Require a confirmed price channel breakout.
// 5. Apply candle and optional trend filters.
// 6. Enter LONG or SHORT.
//
// MODES:
//
// A. Breakouts During Trend Regime
//    Multiple qualifying breakouts are possible
//    during the active regime.
//
// B. First Regime Breakout
//    At most one breakout attempt per regime.
//
// Features:
// - Confirmed-bar signals
// - No future pivots
// - Optional EMA / ADX / RSI / Volume / H1
// - Fixed SL / TP
// - Max trades per day
// - Entry spacing and cooldown
// - Session force close
// - Diagnostics and alerts
// ============================================================================
// ============================================================================
// 01. CHOPPINESS INDEX
// ============================================================================
gCHOP = "01. Choppiness Index"
chopLength = input.int(14, "CHOP Length", minval=3, maxval=200, group=gCHOP)
choppyThreshold = input.float(61.8, "Choppy Threshold", minval=30.0, maxval=100.0, step=0.5, group=gCHOP)
trendingThreshold = input.float(55.0, "Trending Threshold", minval=1.0, maxval=80.0, step=0.5, group=gCHOP)
recentChopLookback = input.int(30, "Recent Choppy Lookback", minval=2, maxval=300, group=gCHOP)
requireRecentChop = input.bool(true, "Require Recent High CHOP", group=gCHOP)
requireChopFalling = input.bool(false, "Require CHOP Still Falling", group=gCHOP)
chopSlopeBars = input.int(1, "CHOP Slope Lookback", minval=1, maxval=20, group=gCHOP)

// ============================================================================
// 02. REGIME MANAGEMENT
// ============================================================================
gRegime = "02. Regime Management"
entryMode = input.string("Breakouts During Trend Regime", "Entry Mode", options=["Breakouts During Trend Regime", "First Regime Breakout"], group=gRegime)
maximumRegimeBars = input.int(35, "Maximum Active Regime Bars", minval=1, maxval=300, group=gRegime)
regimeResetThreshold = input.float(58.0, "Deactivate If CHOP Rises Above", minval=1.0, maxval=100.0, step=0.5, group=gRegime)
useRegimeAgeFilter = input.bool(true, "Limit Regime Duration", group=gRegime)

// ============================================================================
// 03. PRICE STRUCTURE BREAKOUT
// ============================================================================
gBreakout = "03. Price Breakout"
breakoutLookback = input.int(5, "Break Previous N Candles", minval=1, maxval=200, group=gBreakout)
useBreakoutBuffer = input.bool(false, "Use Breakout Buffer", group=gBreakout)
breakoutBufferATR = input.float(0.05, "Breakout Buffer / ATR", minval=0.0, maxval=3.0, step=0.05, group=gBreakout)
requireFreshBreakout = input.bool(false, "Require Fresh Cross Of Channel", group=gBreakout)

// ============================================================================
// 04. BREAKOUT CANDLE
// ============================================================================
gCandle = "04. Breakout Candle"
requireDirectionalCandle = input.bool(true, "Require Bullish/Bearish Candle", group=gCandle)
useBodyFilter = input.bool(true, "Use Minimum Body Ratio", group=gCandle)
minimumBodyRatio = input.float(0.40, "Minimum Body / Candle Range", minval=0.0, maxval=1.0, step=0.05, group=gCandle)
useCloseLocation = input.bool(false, "Use Close Location", group=gCandle)
minimumLongClose = input.float(0.65, "Minimum LONG Close Position", minval=0.0, maxval=1.0, step=0.05, group=gCandle)
maximumShortClose = input.float(0.35, "Maximum SHORT Close Position", minval=0.0, maxval=1.0, step=0.05, group=gCandle)
useCandleRangeFilter = input.bool(false, "Filter Candle Range / ATR", group=gCandle)
minimumCandleRangeATR = input.float(0.50, "Minimum Candle Range / ATR", minval=0.0, step=0.10, group=gCandle)
maximumCandleRangeATR = input.float(3.00, "Maximum Candle Range / ATR", minval=0.1, step=0.10, group=gCandle)

// ============================================================================
// 05. EMA TREND FILTER
// ============================================================================
gTrend = "05. EMA Trend"
useEMAFilter = input.bool(false, "Use EMA Trend Filter", group=gTrend)
emaLength = input.int(50, "EMA Length", minval=2, maxval=300, group=gTrend)
requireEMASlope = input.bool(true, "Require EMA Slope Direction", group=gTrend)
emaSlopeBars = input.int(3, "EMA Slope Lookback", minval=1, maxval=50, group=gTrend)
requirePriceEMA = input.bool(true, "Require Price Above/Below EMA", group=gTrend)

// ============================================================================
// 06. VOLUME FILTER
// ============================================================================
gVolume = "06. Volume Filter"
useVolumeFilter = input.bool(false, "Use Relative Volume Filter", group=gVolume)
volumeLength = input.int(20, "Volume MA Length", minval=2, maxval=200, group=gVolume)
minimumVolumeFactor = input.float(1.0, "Minimum Relative Volume", minval=0.1, maxval=10.0, step=0.1, group=gVolume)

// ============================================================================
// 07. ADX / RSI FILTERS
// ============================================================================
gMomentum = "07. Momentum Filters"
useADXFilter = input.bool(false, "Use Minimum ADX", group=gMomentum)
diLength = input.int(14, "DI Length", minval=2, group=gMomentum)
adxSmoothing = input.int(14, "ADX Smoothing", minval=2, group=gMomentum)
minimumADX = input.float(18.0, "Minimum ADX", minval=1.0, step=1.0, group=gMomentum)
requireDIDirection = input.bool(false, "Require DI Direction", group=gMomentum)
useRSIFilter = input.bool(false, "Use RSI Momentum Filter", group=gMomentum)
rsiLength = input.int(14, "RSI Length", minval=2, group=gMomentum)
minimumLongRSI = input.float(52.0, "Minimum LONG RSI", minval=1.0, maxval=100.0, group=gMomentum)
maximumShortRSI = input.float(48.0, "Maximum SHORT RSI", minval=0.0, maxval=99.0, group=gMomentum)

// ============================================================================
// 08. CONFIRMED H1 BIAS
// ============================================================================
gH1 = "08. H1 Bias"
useH1Bias = input.bool(false, "Use Confirmed H1 EMA Bias", group=gH1)
h1EMALength = input.int(50, "H1 EMA Length", minval=2, group=gH1)

// ============================================================================
// 09. RISK MANAGEMENT
// ============================================================================
gRisk = "09. Risk Management"
stopLossPoints = input.float(5.0, "Stop Loss (Points)", minval=0.1, step=0.5, group=gRisk)
takeProfitPoints = input.float(15.0, "Take Profit (Points)", minval=0.1, step=0.5, group=gRisk)
useTimeExit = input.bool(false, "Use Time Exit", group=gRisk)
maximumHoldingBars = input.int(20, "Maximum Holding Bars", minval=1, maxval=200, group=gRisk)

// ============================================================================
// 10. TRADE CONTROL
// ============================================================================
gTrade = "10. Trade Control"
tradeDirection = input.string("Both", "Trade Direction", options=["Long", "Short", "Both"], group=gTrade)
contracts = input.int(3, "Contracts", minval=1, maxval=100, group=gTrade)
maximumTradesPerDay = input.int(3, "Maximum Trades Per Day", minval=1, maxval=20, group=gTrade)
cooldownBars = input.int(2, "Cooldown After Exit (Bars)", minval=0, maxval=100, group=gTrade)
minimumBarsBetweenEntries = input.int(3, "Minimum Bars Between Entries", minval=0, maxval=100, group=gTrade)
bool allowLong = (tradeDirection == "Long" or tradeDirection == "Both")
bool allowShort = (tradeDirection == "Short" or tradeDirection == "Both")

// ============================================================================
// 11. TRADING SESSION
// ============================================================================
gSession = "11. Trading Session"
tz = input.string("Asia/Ho_Chi_Minh", "Timezone", group=gSession)
useSessionFilter = input.bool(true, "Use Entry Session Filter", group=gSession)
startHour = input.int(9, "Entry Start Hour", minval=0, maxval=23, group=gSession)
startMinute = input.int(15, "Entry Start Minute", minval=0, maxval=59, group=gSession)
lastHour = input.int(14, "Last Entry Hour", minval=0, maxval=23, group=gSession)
lastMinute = input.int(15, "Last Entry Minute", minval=0, maxval=59, group=gSession)
endHour = input.int(14, "Force Close Hour", minval=0, maxval=23, group=gSession)
endMinute = input.int(45, "Force Close Minute", minval=0, maxval=59, group=gSession)

// ============================================================================
// 12. ALERTS
// ============================================================================
gAlerts = "12. Alerts"
disableExitAlerts = input.bool(false, "Disable SL/TP Alerts", group=gAlerts)

// ============================================================================
// 13. DISPLAY
// ============================================================================
gDisplay = "13. Display"
showEMA = input.bool(true, "Show EMA", group=gDisplay)
showBreakoutChannel = input.bool(false, "Show Breakout Channel", group=gDisplay)
showRegimeBackground = input.bool(false, "Highlight Active Trend Regime", group=gDisplay)
showRegimeMarkers = input.bool(false, "Show Regime Transition Markers", group=gDisplay)
showRawBreakoutMarkers = input.bool(false, "Show Raw Breakout Dots", group=gDisplay)
showEntryMarkers = input.bool(true, "Show Entry Markers", group=gDisplay)
showSLTP = input.bool(true, "Show Active SL/TP", group=gDisplay)
showDiagnostics = input.bool(false, "Show Diagnostics", group=gDisplay)

// ============================================================================
// 14. CLOCK ENGINE
// ============================================================================
int openMinutes = (hour(time, tz) * 60 + minute(time, tz))
int closeMinutes = (hour(time_close, tz) * 60 + minute(time_close, tz))
int entryStartMinutes = (startHour * 60 + startMinute)
int lastEntryMinutes = (lastHour * 60 + lastMinute)
int forceCloseMinutes = (endHour * 60 + endMinute)
bool intradayOK = timeframe.isintraday
bool entrySessionOK = (not useSessionFilter or (openMinutes >= entryStartMinutes and closeMinutes <= lastEntryMinutes))
bool beforeForceClose = (closeMinutes < forceCloseMinutes)
bool forceCloseBar = (openMinutes < forceCloseMinutes and closeMinutes >= forceCloseMinutes)

// ============================================================================
// 15. DAILY RESET
// ============================================================================
int dayKey = (year(time, tz) * 10000 + month(time, tz) * 100 + dayofmonth(time, tz))
bool newDay = (na(dayKey[1]) or dayKey != dayKey[1])
var int tradesToday = 0
if newDay
    tradesToday := 0

// ============================================================================
// 16. CHOPPINESS CALCULATION
// ============================================================================
//
// CHOP = 100 * log10(TR Sum / Price Range)
//              / log10(Length)
//
// Sum(TR, N) is computed with:
// SMA(TR, N) * N
//
// Both numerator and price-range denominator
// use the same lookback period.
//
// CHOP can be undefined if price range is zero.
//
// ============================================================================
float trueRange = ta.tr(true)
float trSum = (ta.sma(trueRange, chopLength) * chopLength)
float highestCHOPHigh = ta.highest(high, chopLength)
float lowestCHOPLow = ta.lowest(low, chopLength)
float chopPriceRange = (highestCHOPHigh - lowestCHOPLow)
float chopRatio = (not na(trSum) and chopPriceRange > 0 ? trSum / chopPriceRange : na)
float chop = (not na(chopRatio) and chopRatio > 0 ? 100.0 * math.log10(chopRatio) / math.log10(chopLength) : na)
bool chopReady = (not na(chop))

// ============================================================================
// 17. PREVIOUS CHOPPY REGIME
// ============================================================================
//
// The prior N candles are used to
// determine whether a choppy phase
// recently occurred.
//
// The current candle is excluded
// from the historical high-CHOP test.
//
// ============================================================================
float previousHighestCHOP = ta.highest(chop[1], recentChopLookback)
bool recentChoppyRegime = (not na(previousHighestCHOP) and previousHighestCHOP >= choppyThreshold)
bool recentChopOK = (not requireRecentChop or recentChoppyRegime)
bool chopFalling = (not na(chop[chopSlopeBars]) and chop < chop[chopSlopeBars])
bool chopSlopeOK = (not requireChopFalling or chopFalling)

// ============================================================================
// 18. REGIME TRANSITION EVENT
// ============================================================================
//
// Transition occurs when CHOP moves
// from >= trendingThreshold to
// below trendingThreshold.
//
// A recent choppy period is optional
// but enabled by default.
//
// ============================================================================
bool chopTransition = ta.crossunder(chop, trendingThreshold)
bool qualifyingTransition = (barstate.isconfirmed and chopReady and chopTransition and recentChopOK and chopSlopeOK)

// ============================================================================
// 19. TREND REGIME STATE
// ============================================================================
var bool regimeActive = false
var int regimeStartBar = na
var bool firstBreakoutConsumed = false
var int totalRegimeTransitions = 0
var int totalRegimeDeactivations = 0
var int totalRegimeBreakoutAttempts = 0
if newDay
    regimeActive := false
    regimeStartBar := na
    firstBreakoutConsumed := false

// ------------------------------------------------------------
// END A PREVIOUS REGIME
// ------------------------------------------------------------
bool regimeTooOld = (useRegimeAgeFilter and not na(regimeStartBar) and bar_index - regimeStartBar > maximumRegimeBars)
bool regimeChopReversal = (chopReady and chop > regimeResetThreshold)
if barstate.isconfirmed and regimeActive
    if regimeTooOld or regimeChopReversal
        regimeActive := false
        regimeStartBar := na
        firstBreakoutConsumed := false
        totalRegimeDeactivations += 1

// ------------------------------------------------------------
// ACTIVATE A NEW REGIME
// ------------------------------------------------------------
if qualifyingTransition
    regimeActive := true
    regimeStartBar := bar_index
    firstBreakoutConsumed := false
    totalRegimeTransitions += 1
int regimeAge = (regimeActive and not na(regimeStartBar) ? bar_index - regimeStartBar : na)
bool activeTrendRegime = (regimeActive and chopReady and chop <= regimeResetThreshold)

// ============================================================================
// 20. ENTRY MODE
// ============================================================================
bool firstBreakoutMode = (entryMode == "First Regime Breakout")
bool regimeEntryAllowed = (activeTrendRegime and (not firstBreakoutMode or not firstBreakoutConsumed))

// ============================================================================
// 21. ATR / BREAKOUT LEVELS
// ============================================================================
float atr = ta.atr(14)
float previousChannelHigh = ta.highest(high[1], breakoutLookback)
float previousChannelLow = ta.lowest(low[1], breakoutLookback)
float breakoutBuffer = (useBreakoutBuffer and not na(atr) ? atr * breakoutBufferATR : 0.0)
float longBreakoutLevel = (not na(previousChannelHigh) ? previousChannelHigh + breakoutBuffer : na)
float shortBreakoutLevel = (not na(previousChannelLow) ? previousChannelLow - breakoutBuffer : na)

// ============================================================================
// 22. DIRECTIONAL BREAKOUT
// ============================================================================
bool bullishChannelBreak = (not na(longBreakoutLevel) and close > longBreakoutLevel)
bool bearishChannelBreak = (not na(shortBreakoutLevel) and close < shortBreakoutLevel)
bool freshLongBreak = (not requireFreshBreakout or (not na(close[1]) and close[1] <= longBreakoutLevel))
bool freshShortBreak = (not requireFreshBreakout or (not na(close[1]) and close[1] >= shortBreakoutLevel))
bool rawLongBreakout = (barstate.isconfirmed and regimeEntryAllowed and bullishChannelBreak and freshLongBreak)
bool rawShortBreakout = (barstate.isconfirmed and regimeEntryAllowed and bearishChannelBreak and freshShortBreak)

// ============================================================================
// 23. CANDLE STRENGTH
// ============================================================================
float candleRange = high - low
float candleBody = math.abs(close - open)
float bodyRatio = (candleRange > 0 ? candleBody / candleRange : 0.0)
float closePosition = (candleRange > 0 ? (close - low) / candleRange : 0.5)
float candleRangeATR = (not na(atr) and atr > 0 ? candleRange / atr : na)
bool bullishCandle = close > open
bool bearishCandle = close < open
bool longCandleOK = (not requireDirectionalCandle or bullishCandle)
bool shortCandleOK = (not requireDirectionalCandle or bearishCandle)
bool bodyOK = (not useBodyFilter or bodyRatio >= minimumBodyRatio)
bool longCloseOK = (not useCloseLocation or closePosition >= minimumLongClose)
bool shortCloseOK = (not useCloseLocation or closePosition <= maximumShortClose)
bool candleRangeOK = (not useCandleRangeFilter or (not na(candleRangeATR) and candleRangeATR >= minimumCandleRangeATR and candleRangeATR <= maximumCandleRangeATR))

// ============================================================================
// 24. EMA TREND
// ============================================================================
float ema = ta.ema(close, emaLength)
bool emaUp = (not na(ema[emaSlopeBars]) and ema > ema[emaSlopeBars])
bool emaDown = (not na(ema[emaSlopeBars]) and ema < ema[emaSlopeBars])
bool longEMAOK = (not useEMAFilter or ((not requireEMASlope or emaUp) and (not requirePriceEMA or close > ema)))
bool shortEMAOK = (not useEMAFilter or ((not requireEMASlope or emaDown) and (not requirePriceEMA or close < ema)))

// ============================================================================
// 25. RELATIVE VOLUME
// ============================================================================
float averageVolume = ta.sma(volume[1], volumeLength)
float relativeVolume = (not na(volume) and not na(averageVolume) and averageVolume > 0 ? volume / averageVolume : na)
bool volumeOK = (not useVolumeFilter or (not na(relativeVolume) and relativeVolume >= minimumVolumeFactor))

// ============================================================================
// 26. ADX / DI / RSI
// ============================================================================
[diPlus, diMinus, adx] = ta.dmi(diLength, adxSmoothing)
float rsi = ta.rsi(close, rsiLength)
bool adxOK = (not useADXFilter or (not na(adx) and adx >= minimumADX))
bool longDIOK = (not requireDIDirection or (not na(diPlus) and not na(diMinus) and diPlus > diMinus))
bool shortDIOK = (not requireDIDirection or (not na(diPlus) and not na(diMinus) and diMinus > diPlus))
bool longRSIOK = (not useRSIFilter or (not na(rsi) and rsi >= minimumLongRSI))
bool shortRSIOK = (not useRSIFilter or (not na(rsi) and rsi <= maximumShortRSI))

// ============================================================================
// 27. CONFIRMED H1 BIAS
// ============================================================================
[h1EMA, h1Close] = request.security(syminfo.tickerid, "60", [ta.ema(close, h1EMALength)[1], close[1]], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
bool validH1Chart = (timeframe.isintraday and timeframe.in_seconds() < 3600)
bool longH1OK = (not useH1Bias or (validH1Chart and not na(h1EMA) and not na(h1Close) and h1Close > h1EMA))
bool shortH1OK = (not useH1Bias or (validH1Chart and not na(h1EMA) and not na(h1Close) and h1Close < h1EMA))

// ============================================================================
// 28. POSITION / COOLDOWN
// ============================================================================
bool flat = (strategy.position_size == 0)
bool inLong = (strategy.position_size > 0)
bool inShort = (strategy.position_size < 0)
var int lastExitBar = na
var int lastEntryBar = na
bool newClosedTrade = (strategy.closedtrades > nz(strategy.closedtrades[1], 0))
if newClosedTrade
    lastExitBar := bar_index
bool cooldownOK = (na(lastExitBar) or bar_index - lastExitBar > cooldownBars)
bool entrySpacingOK = (na(lastEntryBar) or bar_index - lastEntryBar > minimumBarsBetweenEntries)

// ============================================================================
// 29. LONG BASE SIGNAL
// ============================================================================
bool longBase = (rawLongBreakout and longCandleOK and bodyOK and longCloseOK and candleRangeOK)

// ============================================================================
// 30. SHORT BASE SIGNAL
// ============================================================================
bool shortBase = (rawShortBreakout and shortCandleOK and bodyOK and shortCloseOK and candleRangeOK)

// ============================================================================
// 31. FINAL FILTERED SIGNALS
// ============================================================================
bool rawLong = (longBase and longEMAOK and volumeOK and adxOK and longDIOK and longRSIOK and longH1OK)
bool rawShort = (shortBase and shortEMAOK and volumeOK and adxOK and shortDIOK and shortRSIOK and shortH1OK)

// ============================================================================
// 32. ENTRY GATES
// ============================================================================
bool canTrade = (barstate.isconfirmed and intradayOK and chopReady and regimeEntryAllowed and flat and strategy.opentrades == 0 and tradesToday < maximumTradesPerDay and cooldownOK and entrySpacingOK and entrySessionOK and beforeForceClose)
bool ambiguousSignal = (rawLong and rawShort)
bool enterLong = (canTrade and allowLong and rawLong and not ambiguousSignal)
bool enterShort = (canTrade and allowShort and rawShort and not ambiguousSignal)

// ============================================================================
// 33. FIXED SL / TP IN TICKS
// ============================================================================
int slTicks = math.max(1, int(math.round(stopLossPoints / syminfo.mintick)))
int tpTicks = math.max(1, int(math.round(takeProfitPoints / syminfo.mintick)))
float effectiveSL = (slTicks * syminfo.mintick)
float effectiveTP = (tpTicks * syminfo.mintick)

// ============================================================================
// 34. DIAGNOSTIC COUNTERS
// ============================================================================
var int choppyBarCount = 0
var int trendingBarCount = 0
var int longBreakoutCount = 0
var int shortBreakoutCount = 0
var int longBaseCount = 0
var int shortBaseCount = 0
var int filteredLongCount = 0
var int filteredShortCount = 0
var int blockedLongCount = 0
var int blockedShortCount = 0
var int longEntryCount = 0
var int shortEntryCount = 0
var int timeExitCount = 0
var int sessionExitCount = 0

// ============================================================================
// 35. LONG ENTRY
// ============================================================================
if enterLong
    strategy.entry("Long", strategy.long, comment="CHOP BREAKOUT LONG", alert_message="🟢 VÀO VỊ THẾ LONG (CNPS96)\\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\\n🛑 SL dự kiến: " + str.tostring(close - slTicks * syminfo.mintick, format.mintick) + "\\n🎯 TP dự kiến: " + str.tostring(close + tpTicks * syminfo.mintick, format.mintick))
    tradesToday += 1
    longEntryCount += 1
    lastEntryBar := bar_index

// ============================================================================
// 36. SHORT ENTRY
// ============================================================================
if enterShort
    strategy.entry("Short", strategy.short, comment="CHOP BREAKOUT SHORT", alert_message="🔴 VÀO VỊ THẾ SHORT (CNPS96)\\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\\n🛑 SL dự kiến: " + str.tostring(close + slTicks * syminfo.mintick, format.mintick) + "\\n🎯 TP dự kiến: " + str.tostring(close - tpTicks * syminfo.mintick, format.mintick))
    tradesToday += 1
    shortEntryCount += 1
    lastEntryBar := bar_index

// ============================================================================
// 37. CONSUME FIRST BREAKOUT MODE
// ============================================================================
//
// First Regime Breakout mode consumes
// the first raw price breakout attempt,
// whether or not filters approve the trade.
//
// This avoids repeatedly entering after
// the initial regime breakout.
//
// ============================================================================
bool qualifiedBreakoutAttempt = (rawLongBreakout or rawShortBreakout)
if (barstate.isconfirmed and firstBreakoutMode and qualifiedBreakoutAttempt)
    firstBreakoutConsumed := true
    totalRegimeBreakoutAttempts += 1

// ============================================================================
// 38. UPDATE DIAGNOSTICS
// ============================================================================
if barstate.isconfirmed
    if chop >= choppyThreshold
        choppyBarCount += 1
    if chop <= trendingThreshold
        trendingBarCount += 1
    if rawLongBreakout
        longBreakoutCount += 1
    if rawShortBreakout
        shortBreakoutCount += 1
    if longBase
        longBaseCount += 1
    if shortBase
        shortBaseCount += 1
    if rawLong
        filteredLongCount += 1
    if rawShort
        filteredShortCount += 1
    if rawLong and not enterLong
        blockedLongCount += 1
    if rawShort and not enterShort
        blockedShortCount += 1

// ============================================================================
// 39. LONG EXIT
// ============================================================================
strategy.exit("Long Exit", from_entry="Long", profit=tpTicks, loss=slTicks, comment_profit="TP Long", comment_loss="SL Long", alert_profit="💰 CHỐT LỜI LONG (TP HIT - CNPS96)\\n🎯 Giá chốt: " + str.tostring(close, format.mintick), alert_loss="🛑 CẮT LỖ LONG (SL HIT - CNPS96)\\n🎯 Giá cắt: " + str.tostring(close, format.mintick), disable_alert=disableExitAlerts)

// ============================================================================
// 40. SHORT EXIT
// ============================================================================
strategy.exit("Short Exit", from_entry="Short", profit=tpTicks, loss=slTicks, comment_profit="TP Short", comment_loss="SL Short", alert_profit="💰 CHỐT LỜI SHORT (TP HIT - CNPS96)\\n🎯 Giá chốt: " + str.tostring(close, format.mintick), alert_loss="🛑 CẮT LỖ SHORT (SL HIT - CNPS96)\\n🎯 Giá cắt: " + str.tostring(close, format.mintick), disable_alert=disableExitAlerts)

// ============================================================================
// 41. OPTIONAL TIME EXIT
// ============================================================================
int barsHeld = (strategy.opentrades > 0 ? bar_index - strategy.opentrades.entry_bar_index(0) : 0)
bool timeExit = (useTimeExit and strategy.position_size != 0 and barsHeld >= maximumHoldingBars and barstate.isconfirmed)
if timeExit and not forceCloseBar
    strategy.close_all(immediately=true, comment="Time Exit", alert_message="⏱️ ĐÓNG VỊ THẾ QUÁ THỜI GIAN (Time Exit - CNPS96)\\n🎯 Giá đóng: " + str.tostring(close, format.mintick))
    timeExitCount += 1

// ============================================================================
// 42. SESSION FORCE CLOSE
// ============================================================================
if (barstate.isconfirmed and forceCloseBar and strategy.position_size != 0)
    strategy.close_all(immediately=true, comment="Session End", alert_message="⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End - CNPS96)\\n🎯 Giá đóng: " + str.tostring(close, format.mintick))
    sessionExitCount += 1

// ============================================================================
// 43. EMA PLOT
// ============================================================================
plot(showEMA ? ema : na, title="EMA Trend", color=color.orange, linewidth=2)

// ============================================================================
// 44. BREAKOUT CHANNEL
// ============================================================================
plot(showBreakoutChannel ? previousChannelHigh : na, title="Previous Channel High", color=color.new(color.red, 45), linewidth=1, style=plot.style_stepline)
plot(showBreakoutChannel ? previousChannelLow : na, title="Previous Channel Low", color=color.new(color.green, 45), linewidth=1, style=plot.style_stepline)

// ============================================================================
// 45. REGIME BACKGROUND
// ============================================================================
bgcolor(showRegimeBackground and activeTrendRegime ? color.new(color.aqua, 92) : na, title="Active Trend Regime")

// ============================================================================
// 46. REGIME TRANSITION MARKERS
// ============================================================================
plotshape(showRegimeMarkers and qualifyingTransition, title="CHOP Regime Transition", style=shape.circle, location=location.bottom, color=color.aqua, size=size.tiny, text="REG")

// ============================================================================
// 47. RAW BREAKOUT MARKERS
// ============================================================================
plotshape(showRawBreakoutMarkers and rawLongBreakout, title="CHOP Long Breakout", style=shape.circle, location=location.belowbar, color=color.aqua, size=size.tiny, text="BO")
plotshape(showRawBreakoutMarkers and rawShortBreakout, title="CHOP Short Breakout", style=shape.circle, location=location.abovebar, color=color.orange, size=size.tiny, text="BO")

// ============================================================================
// 48. ENTRY MARKERS
// ============================================================================
plotshape(showEntryMarkers and enterLong, title="CNPS96 LONG", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, text="LONG", textcolor=color.white)
plotshape(showEntryMarkers and enterShort, title="CNPS96 SHORT", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small, text="SHORT", textcolor=color.white)

// ============================================================================
// 49. ACTIVE SL / TP
// ============================================================================
float longSL = (inLong ? strategy.position_avg_price - effectiveSL : na)
float longTP = (inLong ? strategy.position_avg_price + effectiveTP : na)
float shortSL = (inShort ? strategy.position_avg_price + effectiveSL : na)
float shortTP = (inShort ? strategy.position_avg_price - effectiveTP : na)
plot(showSLTP ? longSL : na, title="Long SL", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showSLTP ? longTP : na, title="Long TP", color=color.green, linewidth=2, style=plot.style_linebr)
plot(showSLTP ? shortSL : na, title="Short SL", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showSLTP ? shortTP : na, title="Short TP", color=color.green, linewidth=2, style=plot.style_linebr)

// ============================================================================
// 50. DATA WINDOW
// ============================================================================
plot(chop, title="Choppiness Index", color=color.aqua, display=display.data_window)
plot(previousHighestCHOP, title="Highest Previous CHOP", color=color.orange, display=display.data_window)
plot(regimeAge, title="Regime Age (Bars)", color=color.gray, display=display.data_window)
plot(atr, title="ATR", color=color.gray, display=display.data_window)
plot(bodyRatio, title="Body Ratio", color=color.green, display=display.data_window)
plot(relativeVolume, title="Relative Volume", color=color.purple, display=display.data_window)
plot(adx, title="ADX", color=color.blue, display=display.data_window)
plot(rsi, title="RSI", color=color.fuchsia, display=display.data_window)

// ============================================================================
// 51. DIAGNOSTICS TABLE
// ============================================================================
var table diagnostics = table.new(position.top_right, 2, 25, border_width=1)
if barstate.islast
    if showDiagnostics
        table.cell(diagnostics, 0, 0, "CNPS96 V1")
        table.cell(diagnostics, 1, 0, timeframe.period)
        table.cell(diagnostics, 0, 1, "CHOP")
        table.cell(diagnostics, 1, 1, str.tostring(chop, "#.##"))
        table.cell(diagnostics, 0, 2, "Recent High CHOP")
        table.cell(diagnostics, 1, 2, str.tostring(previousHighestCHOP, "#.##"))
        table.cell(diagnostics, 0, 3, "Recent Chop OK")
        table.cell(diagnostics, 1, 3, recentChopOK ? "YES" : "NO")
        table.cell(diagnostics, 0, 4, "Trend Regime")
        table.cell(diagnostics, 1, 4, activeTrendRegime ? "ACTIVE" : "OFF")
        table.cell(diagnostics, 0, 5, "Regime Age")
        table.cell(diagnostics, 1, 5, str.tostring(regimeAge))
        table.cell(diagnostics, 0, 6, "Transitions")
        table.cell(diagnostics, 1, 6, str.tostring(totalRegimeTransitions))
        table.cell(diagnostics, 0, 7, "Deactivations")
        table.cell(diagnostics, 1, 7, str.tostring(totalRegimeDeactivations))
        table.cell(diagnostics, 0, 8, "Choppy Bars")
        table.cell(diagnostics, 1, 8, str.tostring(choppyBarCount))
        table.cell(diagnostics, 0, 9, "Trending Bars")
        table.cell(diagnostics, 1, 9, str.tostring(trendingBarCount))
        table.cell(diagnostics, 0, 10, "Long Breakouts")
        table.cell(diagnostics, 1, 10, str.tostring(longBreakoutCount))
        table.cell(diagnostics, 0, 11, "Short Breakouts")
        table.cell(diagnostics, 1, 11, str.tostring(shortBreakoutCount))
        table.cell(diagnostics, 0, 12, "Long Bases")
        table.cell(diagnostics, 1, 12, str.tostring(longBaseCount))
        table.cell(diagnostics, 0, 13, "Short Bases")
        table.cell(diagnostics, 1, 13, str.tostring(shortBaseCount))
        table.cell(diagnostics, 0, 14, "Filtered Long")
        table.cell(diagnostics, 1, 14, str.tostring(filteredLongCount))
        table.cell(diagnostics, 0, 15, "Filtered Short")
        table.cell(diagnostics, 1, 15, str.tostring(filteredShortCount))
        table.cell(diagnostics, 0, 16, "Blocked Long")
        table.cell(diagnostics, 1, 16, str.tostring(blockedLongCount))
        table.cell(diagnostics, 0, 17, "Blocked Short")
        table.cell(diagnostics, 1, 17, str.tostring(blockedShortCount))
        table.cell(diagnostics, 0, 18, "Long Entries")
        table.cell(diagnostics, 1, 18, str.tostring(longEntryCount))
        table.cell(diagnostics, 0, 19, "Short Entries")
        table.cell(diagnostics, 1, 19, str.tostring(shortEntryCount))
        table.cell(diagnostics, 0, 20, "Time Exits")
        table.cell(diagnostics, 1, 20, str.tostring(timeExitCount))
        table.cell(diagnostics, 0, 21, "Session Exits")
        table.cell(diagnostics, 1, 21, str.tostring(sessionExitCount))
        table.cell(diagnostics, 0, 22, "Trades Today")
        table.cell(diagnostics, 1, 22, str.tostring(tradesToday) + "/" + str.tostring(maximumTradesPerDay))
        table.cell(diagnostics, 0, 23, "Position")
        table.cell(diagnostics, 1, 23, inLong ? "LONG" : inShort ? "SHORT" : "FLAT")
        table.cell(diagnostics, 0, 24, "Entry Mode")
        table.cell(diagnostics, 1, 24, firstBreakoutMode ? "FIRST" : "REGIME")
    else
        table.clear(diagnostics, 0, 0, 1, 24)

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

2.1. Choppiness Index (CHOP) và sự kiện chuyển pha

Trong code, CHOP được tính chính xác trên cùng chu kỳ chopLength (mặc định 14) theo công thức:

$$CHOP = 100 \times \frac{\log_{10}\left(\frac{\text{SMA}(TR, N) \times N}{\text{Highest}(high, N) - \text{Lowest}(low, N)}\right)}{\log_{10}(N)}$$

  • Giá trị CHOP cao (>= 61.8): Tổng True Range lớn hơn nhiều so với biên độ giá thực tế, cho thấy giá đang đi ngang giằng co kém hiệu quả.
  • Giá trị CHOP thấp (<= 55.0): Đường đi của giá hiệu quả và mang tính định hướng rõ ràng.

Để tránh bắt nhầm nhiễu, sự kiện chuyển pha (qualifyingTransition) chỉ được xác nhận khi nến đã đóng (barstate.isconfirmed), chop cắt xuống dưới trendingThreshold (55.0), đồng thời trong 30 nến liền trước (chop[1] trong recentChopLookback) từng xuất hiện giá trị CHOP đạt từ 61.8 trở lên (nếu bật requireRecentChop).

2.2. Quản lý trạng thái Regime và hai chế độ vào lệnh

Ngay khi qualifyingTransition xảy ra, biến trạng thái regimeActive được bật true và ghi nhận regimeStartBar := bar_index. Trạng thái pha xu hướng activeTrendRegime chỉ duy trì khi regimeActive == true và chop <= regimeResetThreshold (58.0). Pha xu hướng bị hủy bỏ trong 3 trường hợp:

  1. Bước sang ngày giao dịch mới (newDay).
  2. Tuổi của pha vượt quá giới hạn (bar_index - regimeStartBar > 35 khi bật useRegimeAgeFilter).
  3. Chỉ số CHOP đảo chiều tăng vượt 58.0 (regimeChopReversal).

Bot cung cấp 2 chế độ vận hành (entryMode):

  • Breakouts During Trend Regime (mặc định): Cho phép thực hiện nhiều lệnh phá vỡ hợp lệ miễn là activeTrendRegime vẫn còn hiệu lực.
  • First Regime Breakout: Biến firstBreakoutConsumed sẽ lập tức chuyển sang true ngay khi xuất hiện nhịp phá vỡ giá đầu tiên (rawLongBreakout hoặc rawShortBreakout), bất kể các bộ lọc phụ có duyệt vào lệnh hay không. Điều này giúp loại bỏ việc vào lệnh đuổi ở các nhịp sau.

2.3. Kênh phá vỡ giá và bộ lọc sức mạnh nến

Kênh giá được xác định từ breakoutLookback (5) nến liền trước (không tính nến hiện tại):

  • previousChannelHigh = ta.highest(high[1], 5)
  • previousChannelLow = ta.lowest(low[1], 5)

Nếu bật useBreakoutBuffer, bot cộng/trừ thêm khoảng đệm 0.05 * ATR(14) vào hai biên kênh giá. Khi nến đóng vượt biên, bot đánh giá tiếp chất lượng nến qua bodyRatio = |close - open| / (high - low) (mặc định tối thiểu 0.40), cùng các tùy chọn bổ sung như vị trí đóng cửa (closePosition) và biên độ nến theo ATR (candleRange / atr).

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

Quy trình vận hành khép kín của CNPS96 trên mỗi cây nến intraday diễn ra theo 5 bước tuần tự:

  1. Khởi tạo phiên mới: Khi phát hiện newDay theo múi giờ Asia/Ho_Chi_Minh, bot đưa bộ đếm tradesToday về 0, tắt regimeActive và đặt lại firstBreakoutConsumed := false.
  2. Đo lường & kích hoạt Regime: Tính chop và kiểm tra đỉnh CHOP trong 30 nến trước (previousHighestCHOP). Khi chop cắt xuống dưới 55.0 trên nến đóng, pha xu hướng được kích hoạt và theo dõi liên tục qua regimeAge.
  3. Phát hiện phá vỡ kênh giá: Khi regimeEntryAllowed đang bật, bot kiểm tra xem close có vượt longBreakoutLevel hoặc thủng shortBreakoutLevel để tạo tín hiệu rawLongBreakout / rawShortBreakout.
  4. Sàng lọc tín hiệu & kiểm tra cổng vào lệnh: Tín hiệu phá vỡ phải đi qua bộ lọc nến (longBase / shortBase), các bộ lọc xu hướng/động lượng tùy chọn (EMA, Volume, ADX/DI, RSI, H1 Bias) và cổng kiểm soát canTrade (phiên, giới hạn lệnh/ngày, cooldown, giãn cách nến, không trùng hai chiều).
  5. Thực thi & quản trị vị thế: Gửi lệnh kèm SL/TP cố định tính bằng ticks. Trong lúc giữ vị thế, bot theo dõi điều kiện Time Exit (nếu bật) và luôn cưỡng bức đóng toàn bộ vị thế tại nến đóng phiên 14:45.

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

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

Lệnh Long (enterLong) được kích hoạt khi thỏa mãn đồng thời các điều kiện sau:

  • Cho phép chiều Long (tradeDirection là "Long" hoặc "Both").
  • Đang trong pha xu hướng hợp lệ (regimeEntryAllowed == true).
  • Giá đóng cửa vượt biên trên kênh giá: close > longBreakoutLevel (và close[1] <= longBreakoutLevel nếu bật requireFreshBreakout).
  • Thỏa bộ lọc nến (longBase): nến tăng (close > open), tỷ lệ thân nến bodyRatio >= 0.40, cùng các điều kiện tùy chọn longCloseOK (closePosition >= 0.65) và candleRangeOK.
  • Thỏa các bộ lọc bổ trợ nếu được kích hoạt:
    • EMA Trend: ema > ema[3] và close > ema.
    • Volume: volume / sma(volume[1], 20) >= 1.0.
    • Momentum: adx >= 18.0, diPlus > diMinus (nếu bật requireDIDirection), rsi >= 52.0.
    • H1 Bias: Biểu đồ nhỏ hơn 60 phút và nến H1 đã đóng có h1Close > h1EMA.
  • Cổng canTrade == true và không xảy ra tín hiệu hai chiều đồng thời (not ambiguousSignal).

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

Lệnh Short (enterShort) được kích hoạt khi thỏa mãn đồng thời các điều kiện sau:

  • Cho phép chiều Short (tradeDirection là "Short" hoặc "Both").
  • Đang trong pha xu hướng hợp lệ (regimeEntryAllowed == true).
  • Giá đóng cửa thủng biên dưới kênh giá: close < shortBreakoutLevel (và close[1] >= shortBreakoutLevel nếu bật requireFreshBreakout).
  • Thỏa bộ lọc nến (shortBase): nến giảm (close < open), tỷ lệ thân nến bodyRatio >= 0.40, cùng các điều kiện tùy chọn shortCloseOK (closePosition <= 0.35) và candleRangeOK.
  • Thỏa các bộ lọc bổ trợ nếu được kích hoạt:
    • EMA Trend: ema < ema[3] và close < ema.
    • Volume: volume / sma(volume[1], 20) >= 1.0.
    • Momentum: adx >= 18.0, diMinus > diPlus (nếu bật requireDIDirection), rsi <= 48.0.
    • H1 Bias: Biểu đồ nhỏ hơn 60 phút và nến H1 đã đóng có h1Close < h1EMA.
  • Cổng canTrade == true và không xảy ra tín hiệu hai chiều đồng thời (not ambiguousSignal).

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

Biến canTrade đóng vai trò chốt chặn cuối cùng trước khi gửi lệnh:

  • Xác nhận nến & khung giờ: Nến đã đóng (barstate.isconfirmed), biểu đồ thuộc khung intraday (timeframe.isintraday) và chỉ số CHOP đã sẵn sàng (chopReady).
  • Trạng thái tài khoản: Không có vị thế đang mở (strategy.position_size == 0 và strategy.opentrades == 0).
  • Giới hạn số lệnh/ngày: tradesToday < 3 (tự động reset khi qua ngày mới).
  • Cooldown & Giãn cách lệnh: Cách lần thoát lệnh gần nhất lớn hơn 2 nến (bar_index - lastExitBar > cooldownBars) và cách lần vào lệnh gần nhất lớn hơn 3 nến (bar_index - lastEntryBar > minimumBarsBetweenEntries).
  • Khung giờ giao dịch (Asia/Ho_Chi_Minh): Thời gian mở nến từ 09:15 trở đi, thời gian đóng nến không quá 14:15 (entrySessionOK) và phải trước mốc đóng phiên 14:45 (beforeForceClose).

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

5.1. Cơ chế Stop Loss và Take Profit cố định

Bot CNPS96 sử dụng mức cắt lỗ và chốt lời cố định theo số điểm, sau đó quy đổi sang ticks dựa trên syminfo.mintick của hợp đồng VN30F1M (tối thiểu 1 tick):

  • Stop Loss (stopLossPoints): Mặc định 5.0 điểm (slTicks = math.max(1, int(math.round(5.0 / syminfo.mintick)))).
  • Take Profit (takeProfitPoints): Mặc định 15.0 điểm (tpTicks = math.max(1, int(math.round(15.0 / syminfo.mintick)))), tương ứng tỷ lệ Risk:Reward là 1:3.

Hệ thống không áp dụng bộ lọc Min–Max Risk theo ATR như một số bot khác mà giữ cố định khoảng cách SL/TP để đồng nhất kỳ vọng lợi nhuận trên mỗi pha breakout.

5.2. Cơ chế Time Exit và Force Close cuối phiên

  • Break Even / Trailing Stop: Phiên bản V1 hiện tại không tích hợp dời hòa vốn (Break Even) hay Trailing Stop.
  • Thoát lệnh theo thời gian (useTimeExit): Mặc định tắt (false). Khi bật, nếu vị thế đã giữ số nến barsHeld >= 20 trên nến đã đóng và chưa rơi vào nến đóng phiên, bot sẽ chủ động đóng vị thế với nhãn "Time Exit".
  • Đóng vị thế cuối phiên (forceCloseBar): Khi nến có thời gian mở trước 14:45 và thời gian đóng từ 14:45 trở đi, nếu còn vị thế mở, bot lập tức gọi strategy.close_all(immediately=true, comment="Session End") để tránh giữ lệnh qua đêm.

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

Cơ chế bảo vệTrạng thái mặc địnhCách thức hoạt động
Stop Loss cố địnhBật (5.0 điểm)Gắn sẵn qua strategy.exit với loss=slTicks ngay khi khớp lệnh
Take Profit cố địnhBật (15.0 điểm)Gắn sẵn qua strategy.exit với profit=tpTicks (R:R 1:3)
Time ExitTắt (20 nến)Đóng toàn bộ vị thế bằng strategy.close_all nếu giữ quá số nến quy định
Session Force CloseBật (14:45)Bắt buộc đóng hết vị thế tại nến kết thúc phiên (Session End)
Break Even / TrailingKhông hỗ trợBot giữ nguyên mức SL/TP cố định từ lúc vào lệnh

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

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

  1. Mở biểu đồ VN30F1M trên TradingView và chọn khung thời gian intraday phù hợp (ví dụ M5 hoặc M15; lưu ý khung phải nhỏ hơn 1H nếu bạn bật useH1Bias).
  2. Nhấn vào tab Pine Editor ở phía dưới màn hình, xóa toàn bộ mã nguồn mẫu mặc định.
  3. Sao chép toàn bộ mã nguồn Pine Script v6 ở Mục 1 và dán vào Pine Editor.
  4. Nhấn Save để lưu script, sau đó nhấn Add to chart để đưa chiến lược lên biểu đồ.

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

Khi bật showDiagnostics = true trong phần cài đặt 13. Display, bot sẽ vẽ một bảng thống kê 25 dòng ở góc trên bên phải (position.top_right) trên nến cuối cùng (barstate.islast):

  • Thông số trạng thái hiện tại: CNPS96 V1 (kèm khung thời gian), CHOP (giá trị CHOP hiện tại), Recent High CHOP (đỉnh CHOP trong 30 nến trước), Recent Chop OK (YES/NO), Trend Regime (ACTIVE/OFF), Regime Age (số nến đã trôi qua trong pha hiện tại).
  • Thống kê chuyển pha & nến: Transitions (số lần chuyển pha), Deactivations (số lần kết thúc pha), Choppy Bars (số nến CHOP >= 61.8), Trending Bars (số nến CHOP <= 55.0).
  • Phễu lọc tín hiệu: Long/Short Breakouts (số lần phá vỡ kênh giá) → Long/Short Bases (đạt chuẩn nến) → Filtered Long/Short (qua hết bộ lọc phụ) → Blocked Long/Short (bị chặn bởi cổng canTrade) → Long/Short Entries (số lệnh thực tế đã vào).
  • Thống kê thoát lệnh & tài khoản: Time Exits, Session Exits, Trades Today (số lệnh hôm nay trên giới hạn tối đa), Position (LONG/SHORT/FLAT) và Entry Mode (FIRST/REGIME).

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 hoặc kết nối webhook thực thi lệnh từ CNPS96:

  1. Trên biểu đồ đã gắn chiến lược, nhấn nút Create Alert (hoặc tổ hợp phím Alt + A).
  2. Tại mục Condition, chọn đúng tên chiến lược CNPS96 CHOPPINESS REGIME BREAKOUT V1.
  3. Tại ô Message, xóa nội dung mặc định và nhập chính xác biến: {{strategy.order.alert_message}}.
  4. Nếu chỉ muốn nhận cảnh báo vào lệnh/đóng phiên và bỏ qua cảnh báo SL/TP, bạn có thể tích chọn Disable SL/TP Alerts (disableExitAlerts = true) trong phần cài đặt bot.

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

Sự kiệnNguồn kích hoạt trong codeNội dung thông điệp (alert_message / alert_profit / alert_loss)
Vào lệnh Longstrategy.entry("Long", ...)🟢 VÀO VỊ THẾ LONG (CNPS96)\n🎯 Giá vào: <close>\n🛑 SL dự kiến: <SL>\n🎯 TP dự kiến: <TP>
Vào lệnh Shortstrategy.entry("Short", ...)🔴 VÀO VỊ THẾ SHORT (CNPS96)\n🎯 Giá vào: <close>\n🛑 SL dự kiến: <SL>\n🎯 TP dự kiến: <TP>
Chốt lời Longstrategy.exit("Long Exit", ...)💰 CHỐT LỜI LONG (TP HIT - CNPS96)\n🎯 Giá chốt: <close>
Cắt lỗ Longstrategy.exit("Long Exit", ...)🛑 CẮT LỖ LONG (SL HIT - CNPS96)\n🎯 Giá cắt: <close>
Chốt lời Shortstrategy.exit("Short Exit", ...)💰 CHỐT LỜI SHORT (TP HIT - CNPS96)\n🎯 Giá chốt: <close>
Cắt lỗ Shortstrategy.exit("Short Exit", ...)🛑 CẮT LỖ SHORT (SL HIT - CNPS96)\n🎯 Giá cắt: <close>
Thoát quá thời gianstrategy.close_all(..., comment="Time Exit")⏱️ ĐÓNG VỊ THẾ QUÁ THỜI GIAN (Time Exit - CNPS96)\n🎯 Giá đóng: <close>
Đóng hết phiênstrategy.close_all(..., comment="Session End")⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End - CNPS96)\n🎯 Giá đóng: <close>

Kết luận

CNPS96 CHOPPINESS REGIME BREAKOUT V1 là một hệ thống giao dịch phá vỡ có kỷ luật cao nhờ sử dụng Choppiness Index làm bộ lọc trạng thái nền tảng. Bot phát huy hiệu quả tốt nhất trong những giai đoạn VN30F1M có sự luân phiên rõ rệt giữa các vùng nén biên độ đi ngang và các nhịp bứt phá xu hướng mạnh, giúp hạn chế đáng kể tình trạng giao dịch quá mức (overtrading) trong vùng nhiễu.

Bạn có thể tham khảo thêm các hệ thống giao dịch phái sinh khác như Bot CNPS50 - Trend Analysis V2 và Bot CNPS49 - Daily Open để đa dạng hóa góc nhìn và chiến lược giao dịch.

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

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

Đ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