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

Hướng Dẫn Sử Dụng Bot CNPS94 - Initial Balance Extension V1 cho VN30F1M

Hướng dẫn chi tiết Bot CNPS94 Initial Balance Extension V1 trên TradingView cho VN30F1M: xây dựng vùng Initial Balance đầu phiên, lọc breakout bằng cấu trúc nến, cơ chế Re-arm và quản trị rủi ro SL/TP cố định.

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

Khi giao dịch hợp đồng tương lai chỉ số VN30F1M trong ngày, giai đoạn mở cửa đầu phiên thường xuất hiện nhiều nhiễu động thanh khoản và các nhịp quét hai đầu trước khi thị trường hình thành xu hướng chủ đạo. Nếu vào lệnh quá sớm trong giờ đầu tiên hoặc liên tục mua/bán đuổi theo một nhịp phá vỡ (breakout) kéo dài trên nhiều nến, nhà đầu tư rất dễ dính bẫy phá vỡ giả (false breakout) và bào mòn tài khoản.

CNPS94 INITIAL BALANCE EXTENSION V1 (tên đầy đủ trong mã nguồn: strategy(title="CNPS94 INITIAL BALANCE EXTENSION V1", shorttitle="CNPS94 IB EXTENSION")) là chiến lược giao dịch theo ngày viết bằng Pine Script v6 trên TradingView, được thiết kế chuyên biệt để khai thác các nhịp mở rộng giá sau khi vùng cân bằng đầu phiên (Initial Balance - IB) được thiết lập hoàn chỉnh.

Những điểm nổi bật cốt lõi của Bot CNPS94:

  • Xác thực vùng Initial Balance chặt chẽ: Chỉ kích hoạt giao dịch khi dữ liệu IB đầu phiên được thu thập đầy đủ 100% từ phút bắt đầu đến phút kết thúc, loại bỏ rủi ro giao dịch trên các phiên thiếu dữ liệu lịch sử.
  • Cơ chế Disarm & Re-arm chống đuổi lệnh: Mỗi hướng breakout chỉ được phép thử một lần; sau khi xuất hiện sự kiện breakout, hướng đó tự động khóa lại và chỉ mở khóa (re-arm) khi giá đóng cửa quay trở vào trong vùng IB.
  • Kiểm soát giải phẫu nến (Candle Anatomy) & Bộ đệm ATR: Kết hợp đệm phá vỡ theo ATR (0.05 * ATR), yêu cầu nến có hướng rõ ràng và tỷ lệ thân nến tối thiểu (0.35) nhằm lọc bỏ các nến râu dài thiếu xung lực.
  • Quản trị rủi ro và kỷ luật phiên VN30F1M: Cố định Stop Loss (5.0 điểm) và Take Profit (15.0 điểm) quy đổi chuẩn theo syminfo.mintick, giới hạn tối đa 3 lệnh/ngày, có thời gian nghỉ (cooldown) và tự động đóng toàn bộ vị thế trước giờ ATC (14:45).

1. CNPS94 Initial Balance Extension V1 là gì?

CNPS94 Initial Balance Extension V1 là hệ thống giao dịch theo mô hình Initial Balance Breakout (phá vỡ vùng cân bằng đầu phiên), vận hành dựa trên 4 trụ cột kỹ thuật chính:

  1. Xây dựng và đóng băng vùng Initial Balance (IB): Trong khoảng thời gian cấu hình (mặc định 09:00 – 10:00 theo múi giờ Asia/Ho_Chi_Minh), bot ghi nhận mức giá cao nhất (ibHigh) và thấp nhất (ibLow) từ các cây nến đã đóng hoàn toàn bên trong khung giờ. Sau 10:00, vùng IB được đóng băng (ibLocked := true) và kiểm tra tính toàn vẹn (completeIB).
  2. Động cơ Breakout & Bộ lọc cấu trúc nến: Sau khi IB hợp lệ, bot theo dõi giá đóng cửa vượt lên trên ibHigh + breakoutBuffer (cho Long) hoặc xuống dưới ibLow - breakoutBuffer (cho Short), đồng thời kiểm tra hướng nến, tỷ lệ thân nến (bodyRatio), vị trí đóng cửa (closePosition) và biên độ nến theo ATR.
  3. Cơ chế khóa và tái kích hoạt (Disarm / Re-arm): Ngay khi có một sự kiện phá vỡ (longBreakoutEvent hoặc shortBreakoutEvent), dù lệnh có được vào hay bị bộ lọc phụ từ chối, hướng đó lập tức bị vô hiệu hóa (armedLong := false hoặc armedShort := false). Bot chỉ tái kích hoạt hướng đó khi giá đóng cửa quay lại bên trong vùng IB đủ số nến quy định (insideBarsRequired).
  4. Hệ thống lọc đa lớp tùy chọn & Quản trị lệnh: Hỗ trợ bật/tắt linh hoạt 4 bộ lọc xu hướng/động lượng (EMA, Relative Volume, ADX/DI, H1 EMA Bias) cùng cơ chế thoát lệnh cố định SL/TP, Time Exit tùy chọn và Force Close cuối phiên.

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

Nhóm thông sốTham số trong codeGiá trị mặc địnhÝ nghĩa
01. Initial BalanceibStartHour / ibStartMinute9 / 0Giờ bắt đầu tính IB (09:00)
ibEndHour / ibEndMinute10 / 0Giờ kết thúc tính IB (10:00)
atrLength14Chu kỳ tính chỉ báo ATR
useIBWidthFilterfalseBật/tắt lọc độ rộng IB theo ATR (1.00 – 12.0 ATR)
02. IB BreakoutuseBreakoutBuffer / breakoutBufferATRtrue / 0.05Bộ đệm phá vỡ cộng/trừ thêm 0.05 * ATR
requireFreshCrosstrueYêu cầu nến trước đó đóng cửa chưa vượt mức phá vỡ
requireDirectionalCandletrueNến breakout Long phải là nến tăng, Short là nến giảm
useBodyFilter / minimumBodyRatiotrue / 0.35Thân nến chiếm tối thiểu 35% biên độ nến
useCloseLocationfalseLọc vị trí đóng cửa (Long >= 0.65, Short <= 0.35)
useBreakoutRangeFilterfalseLọc biên độ nến breakout theo ATR (0.40 – 3.00)
03. Breakout Re-armallowReentrytrueCho phép tái kích hoạt breakout sau khi giá hồi về IB
insideBarsRequired1Số nến đóng cửa liên tiếp trong IB để Re-arm
useInsideMargin / insideMarginATRfalse / 0.05Yêu cầu giá đóng sâu vào trong IB thêm 0.05 * ATR
maximumAttemptsPerDirection3Số lần thử breakout tối đa mỗi hướng trong ngày
04. EMA TrenduseEMAFilter / emaLength / emaSlopeBarsfalse / 50 / 3Bộ lọc xu hướng và độ dốc đường EMA 50
requirePriceEMAfalseYêu cầu giá đóng cửa nằm trên/dưới EMA
05. Volume FilteruseVolumeFilter / volumeLength / minimumVolumeFactorfalse / 20 / 1.0Lọc khối lượng tương đối so với SMA 20 phiên trước
06. ADX FilteruseADXFilter / diLength / adxSmoothing / minimumADXfalse / 14 / 14 / 18.0Lọc sức mạnh xu hướng ADX tối thiểu 18.0
requireDIDirectionfalseYêu cầu hướng +DI > -DI (Long) hoặc -DI > +DI (Short)
07. H1 BiasuseH1Bias / h1EMALengthfalse / 50Bộ lọc xu hướng khung 1 giờ (H1 EMA 50 đã xác nhận)
08. Risk ManagementstopLossPoints / takeProfitPoints5.0 / 15.0Mức cắt lỗ (5.0 điểm) và chốt lời (15.0 điểm) cố định
useTimeExit / maximumHoldingBarsfalse / 20Đóng lệnh theo thời gian sau 20 nến nắm giữ
09. Trade ControltradeDirection / contracts"Both" / 3Chiều giao dịch và tham số số hợp đồng khai báo
maximumTradesPerDay / cooldownBars3 / 1Tối đa 3 lệnh/ngày, nghỉ 1 nến sau khi đóng lệnh
10. Trading Sessiontz / useSessionFilter"Asia/Ho_Chi_Minh" / trueMúi giờ Việt Nam và bộ lọc khung giờ vào lệnh
startHour:startMinute – lastHour:lastMinute10:00 – 14:15Khung giờ cho phép mở vị thế mới
endHour:endMinute14:45Thời điểm bắt buộc đóng toàn bộ vị thế (Force Close)

Source Code CNPS94 Initial Balance Extension 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="CNPS94 INITIAL BALANCE EXTENSION V1", shorttitle="CNPS94 IB EXTENSION", 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)

// ============================================================================
// CNPS94 - INITIAL BALANCE EXTENSION V1
//
// LONG:
// 1. Build IB High/Low during first hour.
// 2. Freeze the completed Initial Balance.
// 3. Price closes above IB High + breakout buffer.
// 4. Confirm candle strength and optional filters.
// 5. Enter LONG.
//
// SHORT:
// 1. Price closes below IB Low - breakout buffer.
// 2. Confirm bearish momentum.
// 3. Enter SHORT.
//
// RE-ARM:
// Once a directional breakout attempt occurs,
// that direction is disarmed.
// Re-arm only after price closes inside IB.
//
// Features:
// - Confirmed-bar signals
// - Complete IB coverage validation
// - Optional IB width filtering
// - Adjustable breakout strength
// - Optional EMA / Volume / ADX / H1
// - Fixed SL / TP
// - Daily trade limits and cooldown
// - Session force close
// - Chart markers and diagnostics
//
// Intended for intraday chart backtesting.
// ============================================================================
// ============================================================================
// 01. INITIAL BALANCE
// ============================================================================
gIB = "01. Initial Balance"
ibStartHour = input.int(9, "IB Start Hour", minval=0, maxval=23, group=gIB)
ibStartMinute = input.int(0, "IB Start Minute", minval=0, maxval=59, group=gIB)
ibEndHour = input.int(10, "IB End Hour", minval=0, maxval=23, group=gIB)
ibEndMinute = input.int(0, "IB End Minute", minval=0, maxval=59, group=gIB)
atrLength = input.int(14, "ATR Length", minval=1, maxval=200, group=gIB)
useIBWidthFilter = input.bool(false, "Use IB Width Filter", group=gIB)
minimumIBWidthATR = input.float(1.00, "Minimum IB Width / ATR", minval=0.0, step=0.1, group=gIB)
maximumIBWidthATR = input.float(12.0, "Maximum IB Width / ATR", minval=0.1, step=0.5, group=gIB)

// ============================================================================
// 02. BREAKOUT ENGINE
// ============================================================================
gBreakout = "02. IB Breakout"
useBreakoutBuffer = input.bool(true, "Use Breakout Buffer", group=gBreakout)
breakoutBufferATR = input.float(0.05, "Breakout Buffer / ATR", minval=0.0, step=0.05, group=gBreakout)
requireFreshCross = input.bool(true, "Require Fresh Close Breakout", group=gBreakout)
requireDirectionalCandle = input.bool(true, "Require Bullish/Bearish Candle", group=gBreakout)
useBodyFilter = input.bool(true, "Use Candle Body Filter", group=gBreakout)
minimumBodyRatio = input.float(0.35, "Minimum Body / Candle Range", minval=0.0, maxval=1.0, step=0.05, group=gBreakout)
useCloseLocation = input.bool(false, "Use Close Position Filter", group=gBreakout)
minimumLongClosePosition = input.float(0.65, "Minimum Long Close Position", minval=0.0, maxval=1.0, step=0.05, group=gBreakout)
maximumShortClosePosition = input.float(0.35, "Maximum Short Close Position", minval=0.0, maxval=1.0, step=0.05, group=gBreakout)
useBreakoutRangeFilter = input.bool(false, "Use Breakout Candle Range Filter", group=gBreakout)
minimumBreakoutRangeATR = input.float(0.40, "Minimum Breakout Range / ATR", minval=0.0, step=0.1, group=gBreakout)
maximumBreakoutRangeATR = input.float(3.00, "Maximum Breakout Range / ATR", minval=0.1, step=0.1, group=gBreakout)

// ============================================================================
// 03. RE-ARM / RE-ENTRY
// ============================================================================
gRearm = "03. Breakout Re-arm"
allowReentry = input.bool(true, "Allow Subsequent IB Breakouts", group=gRearm)
insideBarsRequired = input.int(1, "Consecutive Closes Inside IB", minval=1, maxval=20, group=gRearm)
useInsideMargin = input.bool(false, "Require Deeper Return Into IB", group=gRearm)
insideMarginATR = input.float(0.05, "Inside Margin / ATR", minval=0.0, step=0.05, group=gRearm)
maximumAttemptsPerDirection = input.int(3, "Maximum Breakout Attempts / Direction", minval=1, maxval=20, group=gRearm)

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

// ============================================================================
// 05. VOLUME FILTER
// ============================================================================
gVolume = "05. 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, step=0.1, group=gVolume)

// ============================================================================
// 06. ADX FILTER
// ============================================================================
gADX = "06. ADX Filter"
useADXFilter = input.bool(false, "Use Minimum ADX", group=gADX)
diLength = input.int(14, "DI Length", minval=2, group=gADX)
adxSmoothing = input.int(14, "ADX Smoothing", minval=2, group=gADX)
minimumADX = input.float(18.0, "Minimum ADX", minval=1.0, step=1.0, group=gADX)
requireDIDirection = input.bool(false, "Require DI Direction", group=gADX)

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

// ============================================================================
// 08. RISK MANAGEMENT
// ============================================================================
gRisk = "08. 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)

// ============================================================================
// 09. TRADE CONTROL
// ============================================================================
gTrade = "09. 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(1, "Cooldown After Exit (Bars)", minval=0, maxval=100, group=gTrade)
bool allowLong = (tradeDirection == "Long" or tradeDirection == "Both")
bool allowShort = (tradeDirection == "Short" or tradeDirection == "Both")

// ============================================================================
// 10. TRADING SESSION
// ============================================================================
gSession = "10. 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(10, "Entry Start Hour", minval=0, maxval=23, group=gSession)
startMinute = input.int(0, "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)

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

// ============================================================================
// 12. DISPLAY
// ============================================================================
gDisplay = "12. Display"
showEMA = input.bool(true, "Show EMA", group=gDisplay)
showIBLevels = input.bool(true, "Show IB High/Low", group=gDisplay)
showIBMidpoint = input.bool(false, "Show IB Midpoint", group=gDisplay)
showExtensionLevels = input.bool(false, "Show IB 0.5x Extension", group=gDisplay)
showIBBackground = input.bool(false, "Highlight IB Formation", group=gDisplay)
showRawBreakoutMarkers = input.bool(false, "Show Breakout Attempt Dots", group=gDisplay)
showRearmMarkers = input.bool(false, "Show Re-arm Markers", 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)

// ============================================================================
// 13. CLOCK ENGINE
// ============================================================================
int openMinutes = (hour(time, tz) * 60 + minute(time, tz))
int closeMinutes = (hour(time_close, tz) * 60 + minute(time_close, tz))
int ibStartMinutes = (ibStartHour * 60 + ibStartMinute)
int ibEndMinutes = (ibEndHour * 60 + ibEndMinute)
int entryStartMinutes = (startHour * 60 + startMinute)
int lastEntryMinutes = (lastHour * 60 + lastMinute)
int forceCloseMinutes = (endHour * 60 + endMinute)
bool intradayOK = timeframe.isintraday
bool validIBSettings = (ibEndMinutes > ibStartMinutes)
int ibDurationSeconds = (ibEndMinutes - ibStartMinutes) * 60
bool validChartResolution = (intradayOK and validIBSettings and timeframe.in_seconds() <= ibDurationSeconds)
bool insideIB = (validChartResolution and openMinutes >= ibStartMinutes and closeMinutes <= ibEndMinutes)
bool afterIB = (validChartResolution and openMinutes >= ibEndMinutes)
bool entrySessionOK = (not useSessionFilter or (openMinutes >= entryStartMinutes and closeMinutes <= lastEntryMinutes))
bool beforeForceClose = (closeMinutes < forceCloseMinutes)
bool forceCloseBar = (openMinutes < forceCloseMinutes and closeMinutes >= forceCloseMinutes)

// ============================================================================
// 14. 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

// ============================================================================
// 15. INDICATORS
// ============================================================================
float atr = ta.atr(atrLength)
float ema = ta.ema(close, emaLength)
float previousAverageVolume = ta.sma(volume[1], volumeLength)
float relativeVolume = (not na(volume) and not na(previousAverageVolume) and previousAverageVolume > 0 ? volume / previousAverageVolume : na)
[diPlus, diMinus, adx] = ta.dmi(diLength, adxSmoothing)

// ============================================================================
// 16. INITIAL BALANCE STATE
// ============================================================================
var float ibHigh = na
var float ibLow = na
var float ibWidth = na
var float ibWidthATR = na
var int ibBarCount = 0
var int firstIBOpen = na
var int lastIBClose = na
var bool ibLocked = false
var bool ibValid = false
var bool armedLong = false
var bool armedShort = false
var int longAttemptsToday = 0
var int shortAttemptsToday = 0
var int insideCount = 0
var int totalIBDays = 0
var int invalidIBDays = 0
var int totalLongAttempts = 0
var int totalShortAttempts = 0
var int totalRearms = 0

// ============================================================================
// 17. RESET IB AT NEW DAY
// ============================================================================
if newDay
    ibHigh := na
    ibLow := na
    ibWidth := na
    ibWidthATR := na
    ibBarCount := 0
    firstIBOpen := na
    lastIBClose := na
    ibLocked := false
    ibValid := false
    armedLong := false
    armedShort := false
    longAttemptsToday := 0
    shortAttemptsToday := 0
    insideCount := 0

// ============================================================================
// 18. BUILD INITIAL BALANCE
// ============================================================================
//
// Only completed bars fully contained
// within the configured IB are counted.
//
// ============================================================================
if (barstate.isconfirmed and insideIB and not ibLocked)
    if ibBarCount == 0
        firstIBOpen := openMinutes
    ibHigh := (na(ibHigh) ? high : math.max(ibHigh, high))
    ibLow := (na(ibLow) ? low : math.min(ibLow, low))
    ibBarCount += 1
    lastIBClose := closeMinutes

// ============================================================================
// 19. FREEZE INITIAL BALANCE
// ============================================================================
//
// The complete-range check prevents a
// partial historical IB from being traded.
//
// Chart timeframes must align with the
// configured session boundaries.
//
// ============================================================================
if (barstate.isconfirmed and afterIB and not ibLocked and ibBarCount > 0)
    ibLocked := true
    ibWidth := ibHigh - ibLow
    ibWidthATR := (not na(atr) and atr > 0 ? ibWidth / atr : na)
    bool completeIB = (firstIBOpen == ibStartMinutes and lastIBClose == ibEndMinutes)
    bool widthOK = (not useIBWidthFilter or (not na(ibWidthATR) and ibWidthATR >= minimumIBWidthATR and ibWidthATR <= maximumIBWidthATR))
    ibValid := (completeIB and ibWidth > 0 and widthOK)
    armedLong := ibValid
    armedShort := ibValid
    totalIBDays += 1
    if not ibValid
        invalidIBDays += 1

// ============================================================================
// 20. BREAKOUT LEVELS
// ============================================================================
float breakoutBuffer = (useBreakoutBuffer and not na(atr) ? atr * breakoutBufferATR : 0.0)
float longBreakLevel = (ibValid ? ibHigh + breakoutBuffer : na)
float shortBreakLevel = (ibValid ? ibLow - breakoutBuffer : na)

// ============================================================================
// 21. RAW BREAKOUT EVENTS
// ============================================================================
//
// A breakout attempt is registered once.
//
// If filtered out, the direction is still
// disarmed until a valid return into IB.
//
// This avoids chasing the same breakout
// repeatedly across consecutive bars.
//
// ============================================================================
bool longBreakoutEvent = (barstate.isconfirmed and ibLocked and ibValid and afterIB and armedLong and longAttemptsToday < maximumAttemptsPerDirection and not na(longBreakLevel) and close > longBreakLevel and (not requireFreshCross or close[1] <= longBreakLevel))
bool shortBreakoutEvent = (barstate.isconfirmed and ibLocked and ibValid and afterIB and armedShort and shortAttemptsToday < maximumAttemptsPerDirection and not na(shortBreakLevel) and close < shortBreakLevel and (not requireFreshCross or close[1] >= shortBreakLevel))

// ============================================================================
// 22. BREAKOUT CANDLE ANATOMY
// ============================================================================
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 >= minimumLongClosePosition)
bool shortCloseOK = (not useCloseLocation or closePosition <= maximumShortClosePosition)
bool breakoutRangeOK = (not useBreakoutRangeFilter or (not na(candleRangeATR) and candleRangeATR >= minimumBreakoutRangeATR and candleRangeATR <= maximumBreakoutRangeATR))

// ============================================================================
// 23. EMA TREND
// ============================================================================
bool emaUp = (not na(ema[emaSlopeBars]) and ema > ema[emaSlopeBars])
bool emaDown = (not na(ema[emaSlopeBars]) and ema < ema[emaSlopeBars])
bool longTrendOK = (not useEMAFilter or (emaUp and (not requirePriceEMA or close > ema)))
bool shortTrendOK = (not useEMAFilter or (emaDown and (not requirePriceEMA or close < ema)))

// ============================================================================
// 24. VOLUME / ADX / DI
// ============================================================================
bool volumeOK = (not useVolumeFilter or (not na(relativeVolume) and relativeVolume >= minimumVolumeFactor))
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))

// ============================================================================
// 25. 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))

// ============================================================================
// 26. 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 freshEntryBar = (na(lastEntryBar) or lastEntryBar != bar_index)

// ============================================================================
// 27. BASE SIGNALS
// ============================================================================
bool longBase = (longBreakoutEvent and longCandleOK and bodyOK and longCloseOK and breakoutRangeOK)
bool shortBase = (shortBreakoutEvent and shortCandleOK and bodyOK and shortCloseOK and breakoutRangeOK)

// ============================================================================
// 28. FINAL FILTERED SIGNALS
// ============================================================================
bool rawLong = (longBase and longTrendOK and volumeOK and adxOK and longDIOK and longH1OK)
bool rawShort = (shortBase and shortTrendOK and volumeOK and adxOK and shortDIOK and shortH1OK)

// ============================================================================
// 29. ENTRY GATES
// ============================================================================
bool canTrade = (barstate.isconfirmed and validChartResolution and ibLocked and ibValid and afterIB and flat and strategy.opentrades == 0 and tradesToday < maximumTradesPerDay and cooldownOK and freshEntryBar and entrySessionOK and beforeForceClose)
bool enterLong = (canTrade and allowLong and rawLong and not rawShort)
bool enterShort = (canTrade and allowShort and rawShort and not rawLong)

// ============================================================================
// 30. RISK 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

// ============================================================================
// 31. DIAGNOSTIC COUNTERS
// ============================================================================
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

// ============================================================================
// 32. LONG ENTRY
// ============================================================================
if enterLong
    strategy.entry("Long", strategy.long, comment="IB EXTENSION LONG", alert_message="🟢 VÀO VỊ THẾ LONG (CNPS94)\\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

// ============================================================================
// 33. SHORT ENTRY
// ============================================================================
if enterShort
    strategy.entry("Short", strategy.short, comment="IB EXTENSION SHORT", alert_message="🔴 VÀO VỊ THẾ SHORT (CNPS94)\\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

// ============================================================================
// 34. CONSUME BREAKOUT ATTEMPTS
// ============================================================================
if barstate.isconfirmed
    if longBreakoutEvent
        armedLong := false
        longAttemptsToday += 1
        totalLongAttempts += 1
    if shortBreakoutEvent
        armedShort := false
        shortAttemptsToday += 1
        totalShortAttempts += 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

// ============================================================================
// 35. RE-ARM STATE
// ============================================================================
//
// Returning inside IB is mandatory.
// The return must be confirmed by CLOSE.
//
// Re-arming does not immediately enter
// a new position. A later breakout is needed.
//
// ============================================================================
float insideMargin = (useInsideMargin and not na(atr) ? atr * insideMarginATR : 0.0)
bool priceInsideIB = (ibLocked and ibValid and not na(ibHigh) and not na(ibLow) and close < ibHigh - insideMargin and close > ibLow + insideMargin)
bool rearmedThisBar = false
if barstate.isconfirmed and ibLocked
    if priceInsideIB
        insideCount += 1
    else
        insideCount := 0
    bool enoughInsideBars = (insideCount >= insideBarsRequired)
    if (allowReentry and enoughInsideBars and ibValid and beforeForceClose)
        if (not armedLong and longAttemptsToday < maximumAttemptsPerDirection)
            armedLong := true
            rearmedThisBar := true
        if (not armedShort and shortAttemptsToday < maximumAttemptsPerDirection)
            armedShort := true
            rearmedThisBar := true
    if rearmedThisBar
        totalRearms += 1

// ============================================================================
// 36. 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 - CNPS94)\\n🎯 Giá chốt: " + str.tostring(close, format.mintick), alert_loss="🛑 CẮT LỖ LONG (SL HIT - CNPS94)\\n🎯 Giá cắt: " + str.tostring(close, format.mintick), disable_alert=disableExitAlerts)

// ============================================================================
// 37. 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 - CNPS94)\\n🎯 Giá chốt: " + str.tostring(close, format.mintick), alert_loss="🛑 CẮT LỖ SHORT (SL HIT - CNPS94)\\n🎯 Giá cắt: " + str.tostring(close, format.mintick), disable_alert=disableExitAlerts)

// ============================================================================
// 38. 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 - CNPS94)\\n🎯 Giá đóng: " + str.tostring(close, format.mintick))

// ============================================================================
// 39. 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 - CNPS94)\\n🎯 Giá đóng: " + str.tostring(close, format.mintick))

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

// ============================================================================
// 41. INITIAL BALANCE PLOTS
// ============================================================================
plot(showIBLevels ? ibHigh : na, title="IB High", color=color.aqua, linewidth=2, style=plot.style_linebr)
plot(showIBLevels ? ibLow : na, title="IB Low", color=color.fuchsia, linewidth=2, style=plot.style_linebr)
float ibMidpoint = (not na(ibHigh) and not na(ibLow) ? (ibHigh + ibLow) / 2.0 : na)
plot(showIBMidpoint ? ibMidpoint : na, title="IB Midpoint", color=color.gray, linewidth=1, style=plot.style_linebr)

// ============================================================================
// 42. OPTIONAL EXTENSION TARGETS
// ============================================================================
float upperExtension = (ibLocked and ibValid ? ibHigh + ibWidth * 0.5 : na)
float lowerExtension = (ibLocked and ibValid ? ibLow - ibWidth * 0.5 : na)
plot(showExtensionLevels ? upperExtension : na, title="IB +0.5 Extension", color=color.new(color.green, 40), linewidth=1, style=plot.style_linebr)
plot(showExtensionLevels ? lowerExtension : na, title="IB -0.5 Extension", color=color.new(color.red, 40), linewidth=1, style=plot.style_linebr)
bgcolor(showIBBackground and insideIB ? color.new(color.blue, 92) : na, title="IB Formation Background")

// ============================================================================
// 43. RAW BREAKOUT MARKERS
// ============================================================================
plotshape(showRawBreakoutMarkers and longBreakoutEvent, title="IB Long Breakout Attempt", style=shape.circle, location=location.belowbar, color=color.aqua, size=size.tiny, text="IB")
plotshape(showRawBreakoutMarkers and shortBreakoutEvent, title="IB Short Breakout Attempt", style=shape.circle, location=location.abovebar, color=color.orange, size=size.tiny, text="IB")

// ============================================================================
// 44. RE-ARM MARKERS
// ============================================================================
plotshape(showRearmMarkers and rearmedThisBar, title="IB Re-armed", style=shape.circle, location=location.bottom, color=color.gray, size=size.tiny, text="RE")

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

// ============================================================================
// 46. 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)

// ============================================================================
// 47. DATA WINDOW
// ============================================================================
plot(ibWidth, title="IB Width (Points)", color=color.blue, display=display.data_window)
plot(ibWidthATR, title="IB Width / ATR", color=color.aqua, display=display.data_window)
plot(relativeVolume, title="Relative Volume", color=color.gray, display=display.data_window)
plot(bodyRatio, title="Candle Body Ratio", color=color.orange, display=display.data_window)
plot(atr, title="ATR", color=color.gray, display=display.data_window)
plot(adx, title="ADX", color=color.purple, display=display.data_window)

// ============================================================================
// 48. DIAGNOSTICS
// ============================================================================
var table diagnostics = table.new(position.top_right, 2, 23, border_width=1)
if barstate.islast
    if showDiagnostics
        table.cell(diagnostics, 0, 0, "CNPS94 V1")
        table.cell(diagnostics, 1, 0, timeframe.period)
        table.cell(diagnostics, 0, 1, "IB Locked")
        table.cell(diagnostics, 1, 1, ibLocked ? "YES" : "NO")
        table.cell(diagnostics, 0, 2, "IB Valid")
        table.cell(diagnostics, 1, 2, ibValid ? "YES" : "NO")
        table.cell(diagnostics, 0, 3, "IB Bars")
        table.cell(diagnostics, 1, 3, str.tostring(ibBarCount))
        table.cell(diagnostics, 0, 4, "IB Width")
        table.cell(diagnostics, 1, 4, str.tostring(ibWidth, "#.##"))
        table.cell(diagnostics, 0, 5, "IB Width / ATR")
        table.cell(diagnostics, 1, 5, str.tostring(ibWidthATR, "#.##"))
        table.cell(diagnostics, 0, 6, "Total IB Days")
        table.cell(diagnostics, 1, 6, str.tostring(totalIBDays))
        table.cell(diagnostics, 0, 7, "Invalid IB Days")
        table.cell(diagnostics, 1, 7, str.tostring(invalidIBDays))
        table.cell(diagnostics, 0, 8, "Long Attempts")
        table.cell(diagnostics, 1, 8, str.tostring(totalLongAttempts))
        table.cell(diagnostics, 0, 9, "Short Attempts")
        table.cell(diagnostics, 1, 9, str.tostring(totalShortAttempts))
        table.cell(diagnostics, 0, 10, "Re-arms")
        table.cell(diagnostics, 1, 10, str.tostring(totalRearms))
        table.cell(diagnostics, 0, 11, "Long Bases")
        table.cell(diagnostics, 1, 11, str.tostring(longBaseCount))
        table.cell(diagnostics, 0, 12, "Short Bases")
        table.cell(diagnostics, 1, 12, str.tostring(shortBaseCount))
        table.cell(diagnostics, 0, 13, "Filtered Long")
        table.cell(diagnostics, 1, 13, str.tostring(filteredLongCount))
        table.cell(diagnostics, 0, 14, "Filtered Short")
        table.cell(diagnostics, 1, 14, str.tostring(filteredShortCount))
        table.cell(diagnostics, 0, 15, "Blocked Long")
        table.cell(diagnostics, 1, 15, str.tostring(blockedLongCount))
        table.cell(diagnostics, 0, 16, "Blocked Short")
        table.cell(diagnostics, 1, 16, str.tostring(blockedShortCount))
        table.cell(diagnostics, 0, 17, "Long Entries")
        table.cell(diagnostics, 1, 17, str.tostring(longEntryCount))
        table.cell(diagnostics, 0, 18, "Short Entries")
        table.cell(diagnostics, 1, 18, str.tostring(shortEntryCount))
        table.cell(diagnostics, 0, 19, "Armed Long")
        table.cell(diagnostics, 1, 19, armedLong ? "YES" : "NO")
        table.cell(diagnostics, 0, 20, "Armed Short")
        table.cell(diagnostics, 1, 20, armedShort ? "YES" : "NO")
        table.cell(diagnostics, 0, 21, "Trades Today")
        table.cell(diagnostics, 1, 21, str.tostring(tradesToday) + "/" + str.tostring(maximumTradesPerDay))
        table.cell(diagnostics, 0, 22, "Position")
        table.cell(diagnostics, 1, 22, inLong ? "LONG" : inShort ? "SHORT" : "FLAT")
    else
        table.clear(diagnostics, 0, 0, 1, 22)

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

2.1. Initial Balance (IB) & Kiểm tra tính toàn vẹn phiên

Trong CNPS94, vùng Initial Balance được xây dựng từ các cây nến đã đóng (barstate.isconfirmed) nằm trọn vẹn trong khung giờ cấu hình (openMinutes >= ibStartMinutes và closeMinutes <= ibEndMinutes), với ibHigh = math.max(ibHigh, high) và ibLow = math.min(ibLow, low).

Điểm đặc biệt của bot là cơ chế kiểm tra tính toàn vẹn completeIB:

  • Khung thời gian biểu đồ phải là intraday và nhỏ hơn hoặc bằng thời lượng IB (timeframe.in_seconds() <= ibDurationSeconds).
  • Nến đầu tiên của IB phải mở cửa đúng bằng ibStartMinutes (firstIBOpen == ibStartMinutes) và nến cuối cùng phải đóng cửa đúng bằng ibEndMinutes (lastIBClose == ibEndMinutes).
  • Độ rộng vùng cân bằng ibWidth = ibHigh - ibLow phải lớn hơn 0. Nếu bật useIBWidthFilter, tỷ lệ ibWidthATR = ibWidth / atr phải nằm trong [minimumIBWidthATR, maximumIBWidthATR] (mặc định 1.00 – 12.0).

2.2. Bộ đệm Breakout & Giải phẫu nến (Candle Anatomy)

Để tránh tín hiệu nhiễu khi giá chỉ nhú nhẹ qua biên IB, bot tính bộ đệm theo biến động thực tế:

  • breakoutBuffer = atr * breakoutBufferATR (mặc định 0.05 * ATR(14)).
  • Mức kích hoạt phá vỡ: longBreakLevel = ibHigh + breakoutBuffer và shortBreakLevel = ibLow - breakoutBuffer.

Mỗi cây nến breakout còn được chấm điểm qua các chỉ số giải phẫu nến:

  • Tỷ lệ thân nến (bodyRatio): math.abs(close - open) / (high - low), yêu cầu mặc định >= 0.35.
  • Vị trí giá đóng cửa (closePosition): (close - low) / (high - low). Nếu bật useCloseLocation, Long cần đóng ở phần trên (>= 0.65), Short cần đóng ở phần dưới (<= 0.35).
  • Biên độ nến theo ATR (candleRangeATR): (high - low) / atr, nếu bật useBreakoutRangeFilter phải nằm trong 0.40 – 3.00 ATR.

2.3. Cơ chế Disarm / Re-arm & Các bộ lọc xu hướng tùy chọn

Khác với các bot breakout thông thường dễ bị vào lệnh lặp đi lặp lại trên cùng một nhịp sóng, CNPS94 sử dụng máy trạng thái armedLong và armedShort:

  • Khi ibValid được xác nhận sau 10:00, cả hai hướng đều ở trạng thái sẵn sàng (armedLong = true, armedShort = true).
  • Ngay khi longBreakoutEvent xảy ra, armedLong bị đặt về false và bộ đếm longAttemptsToday tăng thêm 1 (tương tự cho Short).
  • Muốn kích hoạt lại (rearmedThisBar), giá phải đóng cửa quay vào bên trong IB (close < ibHigh - insideMargin và close > ibLow + insideMargin) đủ insideBarsRequired nến liên tiếp (mặc định 1 nến), đồng thời số lần thử trong ngày chưa chạm maximumAttemptsPerDirection (3 lần).

Ngoài ra, bot tích hợp 4 bộ lọc tùy chọn (mặc định tắt để giữ tín hiệu thuần IB):

  • EMA Trend (emaLength = 50): Kiểm tra độ dốc ema > ema[emaSlopeBars] (với Long) hoặc < (với Short), và tùy chọn giá đóng cửa nằm trên/dưới EMA.
  • Relative Volume (volumeLength = 20): Tính tỷ lệ volume / ta.sma(volume[1], 20) >= 1.0.
  • ADX / DI (diLength = 14, adxSmoothing = 14): Yêu cầu adx >= 18.0 và tùy chọn hướng diPlus > diMinus (hoặc ngược lại).
  • Confirmed H1 Bias (h1EMALength = 50): Lấy dữ liệu [ta.ema(close, 50)[1], close[1]] từ khung 60 phút qua request.security (chỉ hoạt động trên khung biểu đồ < 60 phút).

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

Quy trình vận hành khép kín trong mỗi phiên giao dịch của Bot CNPS94 diễn ra qua 5 bước tuần tự:

  1. Khởi tạo phiên mới (newDay): Khi bước sang ngày giao dịch mới theo múi giờ Asia/Ho_Chi_Minh, toàn bộ biến trạng thái (ibHigh, ibLow, ibLocked, ibValid, armedLong, armedShort, tradesToday, longAttemptsToday, shortAttemptsToday, insideCount) được đặt lại về giá trị ban đầu.
  2. Thu thập & Đóng băng IB: Từ 09:00 đến 10:00, bot cập nhật ibHigh và ibLow trên từng nến đóng cửa. Ngay tại nến đóng đầu tiên sau 10:00 (afterIB), vùng IB bị khóa, kiểm tra completeIB và widthOK. Nếu hợp lệ, armedLong và armedShort được bật.
  3. Phát hiện & Xác thực Breakout: Khi giá đóng cửa vượt longBreakLevel hoặc thủng shortBreakLevel, bot ghi nhận sự kiện breakout, tiêu thụ lượt thử của hướng đó (armed := false), rồi kiểm tra giải phẫu nến (longBase / shortBase) và các bộ lọc xu hướng tùy chọn (rawLong / rawShort).
  4. Kiểm tra cổng vào lệnh & Gửi lệnh: Nếu thỏa mãn toàn bộ điều kiện ở cổng vào lệnh (canTrade), bot gửi lệnh strategy.entry tại giá đóng cửa (process_orders_on_close=true), tăng bộ đếm tradesToday và ghi nhận lastEntryBar.
  5. Quản trị vị thế & Re-arm: Trong lúc nắm giữ hoặc chờ cơ hội mới, bot duy trì lệnh strategy.exit với SL/TP cố định, theo dõi số nến hồi về IB để Re-arm nếu allowReentry = true, và bắt buộc đóng mọi vị thế khi đến 14:45.

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

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

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

  • Sự kiện phá vỡ lên (longBreakoutEvent): Nến đã đóng cửa (barstate.isconfirmed), sau giờ IB (afterIB), ibLocked và ibValid đều đúng, armedLong == true, longAttemptsToday < maximumAttemptsPerDirection, close > ibHigh + breakoutBuffer, và nếu bật requireFreshCross thì nến trước đó phải có close[1] <= longBreakLevel.
  • Cấu trúc nến tăng (longBase): Nến tăng (close > open nếu bật requireDirectionalCandle), bodyRatio >= minimumBodyRatio (0.35), thỏa mãn closePosition >= 0.65 (nếu bật useCloseLocation) và candleRangeATR nằm trong vùng cho phép (nếu bật useBreakoutRangeFilter).
  • Bộ lọc phụ (rawLong): Thỏa mãn các bộ lọc đang bật gồm EMA Trend (longTrendOK), Volume (volumeOK), ADX (adxOK), DI Direction (longDIOK) và H1 EMA Bias (longH1OK).
  • Cổng kiểm soát (canTrade & allowLong): tradeDirection là "Long" hoặc "Both", rawShort là false, và các điều kiện kiểm soát chung đều hợp lệ.

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

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

  • Sự kiện phá vỡ xuống (shortBreakoutEvent): Nến đã đóng cửa, sau giờ IB, IB hợp lệ và đã khóa, armedShort == true, shortAttemptsToday < maximumAttemptsPerDirection, close < ibLow - breakoutBuffer, và nếu bật requireFreshCross thì nến trước đó phải có close[1] >= shortBreakLevel.
  • Cấu trúc nến giảm (shortBase): Nến giảm (close < open nếu bật requireDirectionalCandle), bodyRatio >= minimumBodyRatio (0.35), thỏa mãn closePosition <= 0.35 (nếu bật useCloseLocation) và candleRangeATR đạt chuẩn (nếu bật useBreakoutRangeFilter).
  • Bộ lọc phụ (rawShort): Thỏa mãn EMA Trend (shortTrendOK), Volume (volumeOK), ADX (adxOK), DI Direction (shortDIOK) và H1 EMA Bias (shortH1OK).
  • Cổng kiểm soát (canTrade & allowShort): tradeDirection là "Short" hoặc "Both", rawLong là false, và các điều kiện kiểm soát chung đều hợp lệ.

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

Mọi tín hiệu vào lệnh đều phải vượt qua cổng kiểm soát canTrade:

  • Biểu đồ & IB hợp lệ: Khung thời gian là intraday (timeframe.isintraday), độ phân giải biểu đồ nhỏ hơn hoặc bằng thời lượng IB (<= 60 phút), ibLocked == true và ibValid == true.
  • Trạng thái vị thế phẳng (Flat): strategy.position_size == 0 và strategy.opentrades == 0 (không nhồi lệnh, pyramiding=0).
  • Giới hạn lệnh trong ngày: tradesToday < maximumTradesPerDay (mặc định tối đa 3 lệnh/ngày).
  • Thời gian nghỉ (Cooldown) & Chống trùng nến: bar_index - lastExitBar > cooldownBars (mặc định nghỉ ít nhất 1 nến sau khi đóng lệnh) và lastEntryBar != bar_index.
  • Khung giờ giao dịch: Nến nằm trong khung giờ vào lệnh (10:00 – 14:15 nếu bật useSessionFilter) và trước thời điểm đóng phiên (closeMinutes < forceCloseMinutes, tức trước 14:45).

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

5.1. Cơ chế Stop Loss và quy đổi Tick

CNPS94 áp dụng cơ chế cắt lỗ cố định theo điểm và quy đổi chính xác sang đơn vị bước giá (syminfo.mintick) của hợp đồng tương lai VN30F1M:

  • slTicks = math.max(1, int(math.round(stopLossPoints / syminfo.mintick)))
  • Với mặc định stopLossPoints = 5.0 và mintick = 0.1 trên VN30F1M, mức cắt lỗ tương đương 50 ticks (5.0 điểm).
  • Mức giá SL hiển thị trên biểu đồ: strategy.position_avg_price - effectiveSL (với Long) và strategy.position_avg_price + effectiveSL (với Short).

5.2. Cơ chế Take Profit, Time Exit và Session Force Close

  • Take Profit cố định: Quy đổi tương tự tpTicks = math.max(1, int(math.round(takeProfitPoints / syminfo.mintick))). Mặc định takeProfitPoints = 15.0 điểm, mang lại tỷ lệ Risk : Reward = 1 : 3 (5.0 điểm rủi ro đổi lấy 15.0 điểm lợi nhuận mục tiêu).
  • Thoát lệnh theo thời gian (Time Exit - tùy chọn): Khi bật useTimeExit = true, nếu vị thế đã nắm giữ đủ barsHeld >= maximumHoldingBars (mặc định 20 nến) mà chưa chạm SL/TP, bot sẽ đóng toàn bộ vị thế bằng strategy.close_all(immediately=true, comment="Time Exit").
  • Đóng vị thế bắt buộc cuối phiên (Session Force Close): Tại cây nến chạm mốc 14:45 (openMinutes < forceCloseMinutes và closeMinutes >= forceCloseMinutes), nếu vẫn còn vị thế mở, bot tự động đóng toàn bộ bằng strategy.close_all(immediately=true, comment="Session End") để tránh rủi ro qua đêm hoặc nhảy gap phiên ATC.

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ạtHành động thực thiTrạng thái mặc định
Stop Loss cố địnhGiá chạm entry ± 5.0 điểm (slTicks)Đóng vị thế qua strategy.exit (SL Long / SL Short)Bật (5.0 điểm)
Take Profit cố địnhGiá chạm entry ± 15.0 điểm (tpTicks)Chốt lời qua strategy.exit (TP Long / TP Short)Bật (15.0 điểm)
Time ExitbarsHeld >= maximumHoldingBars (20 nến)Đóng toàn bộ vị thế (Time Exit)Tắt (false)
Session Force CloseNến chạm mốc 14:45 (forceCloseBar)Đóng toàn bộ vị thế (Session End)Luôn bật

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 đồ hợp đồng tương lai VN30F1M trên TradingView, chọn khung thời gian intraday phù hợp (khuyến nghị 5m hoặc 15m để chia hết khung IB 09:00 – 10:00 và có số nến đủ lớn).
  2. Mở tab Pine Editor ở thanh công cụ phía dưới màn hình.
  3. Xóa code mẫu mặc định, sao chép toàn bộ mã nguồn CNPS94 INITIAL BALANCE EXTENSION V1 tại 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 đồ.
  5. Mở phần Settings (Cài đặt) của chiến lược để bật/tắt các bộ lọc (EMA, Volume, ADX, H1 Bias) hoặc bật Show Diagnostics để theo dõi bảng thống kê trực tiếp.

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

Khi bật showDiagnostics = true, bảng diagnostics (2 cột, 23 dòng) ở góc trên bên phải biểu đồ sẽ hiển thị các thông số vận hành thực tế:

  • IB Locked / IB Valid / IB Bars: Cho biết vùng IB hôm nay đã khóa chưa (YES/NO), có hợp lệ hoàn chỉnh không và gồm bao nhiêu nến.
  • IB Width / IB Width / ATR: Độ rộng vùng cân bằng đầu phiên tính bằng điểm và theo hệ số ATR.
  • Total IB Days / Invalid IB Days: Tổng số ngày đã hình thành IB trên lịch sử biểu đồ và số ngày IB bị loại do thiếu dữ liệu hoặc sai độ rộng.
  • Long Attempts / Short Attempts / Re-arms: Tổng số lần thử phá vỡ lên/xuống và số lần bot tái kích hoạt sau khi giá hồi về IB.
  • Long Bases / Short Bases & Filtered Long / Filtered Short: Số tín hiệu đạt chuẩn cấu trúc nến và số tín hiệu vượt qua toàn bộ bộ lọc phụ.
  • Blocked Long / Blocked Short: Số tín hiệu đã qua bộ lọc nhưng bị chặn tại cổng vào lệnh (do hết lượt lệnh ngày, đang có vị thế, đang trong cooldown hoặc ngoài giờ).
  • Long Entries / Short Entries: Tổng số lệnh Long/Short đã thực sự khớp.
  • Armed Long / Armed Short / Trades Today / Position: Trạng thái sẵn sàng hiện tại của hai hướng, số lệnh đã vào trong ngày trên giới hạn tối đa (x/3) và vị thế hiện tại (LONG / SHORT / FLAT).

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

Để nhận thông báo tự động qua ứng dụng TradingView hoặc đẩy tín hiệu qua Webhook:

  1. Nhấp vào biểu tượng Alert (Đồng hồ báo thức) trên thanh công cụ TradingView.
  2. Tại mục Condition, chọn tên chiến lược CNPS94 INITIAL BALANCE EXTENSION V1.
  3. Tại ô Message, xóa nội dung mặc định và điền đúng cú pháp: {{strategy.order.alert_message}}.
  4. Nhấn Create để kích hoạt cảnh báo. Nếu chỉ muốn nhận cảnh báo vào lệnh và đóng phiên (bỏ qua thông báo SL/TP), hãy tick chọn Disable SL/TP Alerts trong cài đặt của bot.

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

Loại sự kiệnTham số 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 (CNPS94)\n🎯 Giá vào: <close>\n🛑 SL dự kiến: <close - SL>\n🎯 TP dự kiến: <close + TP>
Vào lệnh Shortstrategy.entry("Short", ...)🔴 VÀO VỊ THẾ SHORT (CNPS94)\n🎯 Giá vào: <close>\n🛑 SL dự kiến: <close + SL>\n🎯 TP dự kiến: <close - TP>
Chốt lời Long / Shortstrategy.exit(..., alert_profit=...)💰 CHỐT LỜI LONG/SHORT (TP HIT - CNPS94)\n🎯 Giá chốt: <close>
Cắt lỗ Long / Shortstrategy.exit(..., alert_loss=...)🛑 CẮT LỖ LONG/SHORT (SL HIT - CNPS94)\n🎯 Giá cắt: <close>
Đóng lệnh quá thời gianstrategy.close_all(..., comment="Time Exit")⏱️ ĐÓNG VỊ THẾ QUÁ THỜI GIAN (Time Exit - CNPS94)\n🎯 Giá đóng: <close>
Đóng lệnh cuối phiênstrategy.close_all(..., comment="Session End")⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End - CNPS94)\n🎯 Giá đóng: <close>

Kết luận

Bot CNPS94 - Initial Balance Extension V1 là một hệ thống giao dịch phái sinh VN30F1M kỷ luật và chặt chẽ, giải quyết tốt bài toán nhiễu động đầu phiên nhờ cơ chế xác thực vùng Initial Balance toàn vẹn, kiểm soát giải phẫu nến breakout và khóa/mở khóa (Disarm/Re-arm) chống mua bán đuổi. Chiến lược đặc biệt phù hợp với các phiên thị trường có biên độ cân bằng rõ ràng trong giờ đầu tiên và xuất hiện xu hướng mở rộng dứt khoát sau 10:00 sáng.

Bạn có thể tham khảo thêm các hệ thống giao dịch VN30F1M khác trên hệ sinh thái Phái Sinh Online như Bot CNPS50 - Trend Analysis V2 và Bot CNPS49 - Daily Open.

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

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

Đ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