Thứ Ba, 01/12/202601/12/2026

Hướng Dẫn Sử Dụng Bot CNPS57 - Failed Initial Balance Auction V1 cho VN30F1M

Hướng dẫn chi tiết Bot CNPS57 Failed Initial Balance Auction V1 cho VN30F1M: chiến lược bắt nhịp phá vỡ giả ngoài vùng cân bằng 30 phút đầu phiên (IB) và tái nhập biên độ, tích hợp bộ lọc xu hướng cực đoan và quản trị rủi ro đa tầng.

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

Trong giao dịch phái sinh VN30F1M, một trong những bẫy phổ biến nhất mà nhà đầu tư thường gặp phải là các nhịp phá vỡ giả (Failed Breakout) khỏi vùng cân bằng đầu phiên sáng. Thay vì chỉ quét râu nến (liquidity wick sweep) trong cùng một thanh nến, thị trường thường đóng cửa xác nhận bên ngoài biên độ cân bằng đầu ngày để thu hút dòng tiền mua/bán đuổi, nhưng ngay sau đó lực cầu/cung cạn kiệt khiến giá thất bại trong việc thiết lập mặt bằng giá mới và quay đầu đóng cửa ngược vào bên trong vùng cân bằng.

Chiến lược CNPS57 FAILED INITIAL BALANCE AUCTION V1 - VN30F1M (tên rút gọn: CNPS57 FAILED IB V1) được phát triển bằng Pine Script v6 trên TradingView nhằm khai thác triệt để hiện tượng đấu giá thất bại ngoài vùng cân bằng đầu ngày (Failed Initial Balance Auction):

  • Cơ chế State Machine 5 trạng thái chặt chẽ (0, 1, -1, 2, -2): Phân biệt rõ ràng giữa quét râu nến đơn thuần và một cuộc đấu giá bên ngoài thực sự (bắt buộc phải có nến đóng cửa xác nhận bên ngoài biên IB trước khi ghi nhận thất bại tái nhập vào trong IB).
  • 3 chế độ xác nhận điểm vào lệnh linh hoạt: Hỗ trợ vào lệnh ngay tại nến tái nhập (Reentry Momentum), chờ nến phá vỡ nối tiếp (Follow-Through) hoặc chờ nhịp kiểm định lại biên IB thất bại (Retest Failure).
  • Bộ lọc xu hướng ngược cực đoan (Trend Guard): Kết hợp EMA(55), độ dốc EMA chuẩn hóa theo ATR(14) và chỉ báo DMI/ADX(14) để tự động chặn các lệnh bắt đảo chiều khi thị trường đang có xu hướng một chiều quá mạnh.
  • Quản trị rủi ro cấu trúc và mục tiêu lợi nhuận thông minh: Đặt Stop Loss theo điểm cực trị thực tế của nhịp đấu giá thất bại (breakoutExtreme), kết hợp cơ chế chọn Target linh hoạt giữa IB Midpoint, Fixed R hoặc Opposite IB Edge cùng chốt chặn lỗ thực tế trong ngày (Daily Loss Guard).

1. CNPS57 Failed Initial Balance Auction V1 là gì?

CNPS57 Failed Initial Balance Auction V1 là hệ thống giao dịch định lượng theo lý thuyết Đấu giá Thị trường (Market Auction Theory) dành riêng cho hợp đồng tương lai VN30F1M, vận hành dựa trên 4 trụ cột kỹ thuật cốt lõi:

  1. Thiết lập và khóa vùng Cân bằng đầu phiên (Initial Balance - IB): Tự động ghi nhận đỉnh cao nhất (ibHigh) và đáy thấp nhất (ibLow) trong 30 phút đầu phiên sáng (từ 09:00), đồng thời kiểm tra độ rộng vùng IB (ibWidth từ 5.0 đến 70.0 điểm và tối thiểu 3 thanh nến) trước khi kích hoạt trạng thái săn tín hiệu.
  2. Nhận diện Đấu giá bên ngoài và Tái nhập thất bại (Outside Auction & Reentry): Yêu cầu giá phải đóng cửa vượt ra ngoài biên IB tối thiểu 0.40 điểm trong ít nhất 1 nến, không đi quá xa (<= 4.0 x ATR14) và phải quay lại đóng cửa bên trong biên IB (với khoảng đệm 0.20 điểm) trong vòng tối đa 55 phút.
  3. Xác nhận nến đảo chiều và Bộ lọc Regime (Confirmation & Trend Guard): Kiểm tra chất lượng thân nến đảo chiều (bodyRatio >= 0.25, vị trí đóng cửa closeLocation nằm ở nửa trên/nửa dưới thanh nến) và loại bỏ tín hiệu nếu thị trường đang có xu hướng ngược chiều cực mạnh (ADX >= 36.0 kèm độ dốc EMA(55) vượt 0.60 ATR).
  4. Bảo vệ vị thế đa tầng (Multi-Layer Risk & Exit Management): Kiểm soát khoảng cách SL cấu trúc (1.50 – 14.0 điểm), yêu cầu tỷ lệ lợi nhuận/rủi ro tối thiểu (R:R >= 1.05 và lợi nhuận gộp >= 2.50 điểm), kiểm tra trượt giá sau khớp lệnh (Invalid Gap Fill), hỗ trợ dời SL hòa vốn (Break Even), thoát lệnh khi tái nhập thất bại và đóng toàn bộ vị thế trước phiên ATC (14:25).

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

Dưới đây là toàn bộ các thông số cấu hình mặc định trong mã nguồn của CNPS57:

Nhóm thông sốTên hiển thị (Title)Biến trong codeGiá trị mặc địnhMô tả chức năng
Trade ControlTrade DirectiontradeDirection"Both"Hướng giao dịch cho phép (Both, Long, Short)
Trade ControlContracts Per Entrycontracts3Số hợp đồng cấu hình trong input (lưu ý strategy() đặt default_qty_value=1)
Trade ControlMaximum Entries Per DaymaximumTradesPerDay3Số lệnh tối đa được phép vào trong một ngày giao dịch
Trade ControlCooldown Bars After ExitcooldownBars3Số thanh nến nghỉ bắt buộc sau khi đóng một vị thế
Trade ControlOnly One Failed Auction Per Side Per Day?oneEntryPerSidePerDayfalseGiới hạn mỗi biên IB (trên/dưới) chỉ giao dịch tối đa 1 lần/ngày
Initial BalanceInitial Balance Duration After 09:00 (minutes)ibMinutes30Thời gian hình thành vùng IB tính từ 09:00 (15, 20, 30, 45, 60 phút)
Initial BalanceMinimum IB Width (points)minimumIBRange5.0Độ rộng vùng IB tối thiểu hợp lệ (điểm)
Initial BalanceMaximum IB Width (points)maximumIBRange70.0Độ rộng vùng IB tối đa hợp lệ (điểm)
Failed AuctionOutside Close Beyond IB Boundary (points)minimumBreakoutDistance0.40Khoảng cách giá đóng cửa vượt tối thiểu ra ngoài biên IB (điểm)
Failed AuctionMinimum Consecutive Outside ClosesminimumOutsideCloses1Số nến liên tiếp tối thiểu đóng cửa bên ngoài biên IB
Failed AuctionMaximum Time Until Reentry (minutes)maximumBreakoutMinutes55Thời gian tối đa (phút) từ lúc breakout đến khi tái nhập lại vào IB
Failed AuctionMaximum Failed Breakout Extension x ATR14maximumExcursionATR4.0Độ mở rộng tối đa của nhịp breakout tính theo bội số ATR(14)
Failed AuctionRequired Close Back Inside IB (points)reentryBuffer0.20Khoảng đệm điểm bắt buộc khi giá đóng cửa quay lại vào trong biên IB
ConfirmationEntry Confirmation ModeentryMode"Reentry Momentum"Chế độ xác nhận vào lệnh (Reentry Momentum, Follow-Through, Retest Failure)
ConfirmationMinimum Reversal Candle Body / RangeminimumBodyRatio0.25Tỷ lệ thân nến / biên độ nến tối thiểu của nến đảo chiều
ConfirmationFollow-Through / Retest Confirmation WindowreentryConfirmBars5Số nến tối đa chờ xác nhận cho chế độ Follow-Through hoặc Retest Failure
ConfirmationRetest Distance From IB Boundary (points)retestTolerance0.70Khoảng dung sai (điểm) tính từ biên IB khi kiểm định lại ở chế độ Retest Failure
Regime FilterAvoid Very Strong Countertrend Trades?useTrendGuardtrueBật/tắt bộ lọc tránh giao dịch ngược xu hướng cực mạnh
Regime FilterTrend EMA LengthtrendEMALength55Chu kỳ đường EMA xác định xu hướng
Regime FilterTrend EMA Slope BarstrendSlopeBars5Số thanh nến dùng để đo độ dốc của đường EMA(55)
Regime FilterStrong Trend ADX14 ThresholdstrongTrendADX36.0Ngưỡng ADX(14) xác định xu hướng đang ở mức rất mạnh
Regime FilterAdverse EMA Slope In ATR UnitsminimumAdverseSlopeATR0.60Độ dốc EMA ngược chiều tối thiểu (chuẩn hóa theo ATR(14)) bị coi là nguy hiểm
Risk ManagementTarget ModetargetMode"IB Midpoint / Fixed R"Chế độ tính TP (IB Midpoint / Fixed R, IB Midpoint Only, Fixed R Only, Opposite IB Edge)
Risk ManagementFixed Take Profit Multiple (R)fixedTargetR1.50Hệ số R chốt lời cố định khi dùng Fixed R
Risk ManagementMinimum Reward / Risk At SignalminimumRewardRisk1.05Tỷ lệ Reward/Risk tối thiểu tại thời điểm phát sinh tín hiệu
Risk ManagementMinimum Gross Reward (points)minimumGrossTarget2.50Khoảng cách mục tiêu lợi nhuận gộp tối thiểu (điểm)
Risk ManagementMinimum Structural SL (points)minimumStopPoints1.50Khoảng cách Stop Loss cấu trúc tối thiểu (điểm)
Risk ManagementMaximum Structural SL (points)maximumStopPoints14.0Khoảng cách Stop Loss cấu trúc tối đa (điểm)
Risk ManagementStop Buffer Beyond Breakout Extreme (ticks)stopBufferTicks2Số tick cộng/trừ thêm ngoài điểm cực trị breakoutExtreme để đặt SL
Risk ManagementIB Target Buffer (points)midpointTargetBuffer0.00Khoảng đệm điểm điều chỉnh mục tiêu TP theo cấu trúc IB
Exit ManagementExit If IB Reentry Fails?useFailedReentryExitfalseĐóng lệnh sớm nếu giá quay lại đóng cửa bên ngoài biên IB
Exit ManagementConsecutive Closes Back Outside IBfailureCloses2Số nến liên tiếp đóng cửa lại ra ngoài IB để kích hoạt thoát lệnh sớm
Exit ManagementUse Break Even?useBreakEvenfalseBật/tắt cơ chế dời SL về hòa vốn
Exit ManagementBreak Even Trigger (R, close-confirmed)breakEvenAtR1.0Mức lợi nhuận theo R (tính theo giá đóng cửa) để kích hoạt dời SL về hòa vốn
Exit ManagementBreak Even Offset (points)breakEvenOffset0.20Khoảng điểm cộng thêm vào giá khớp lệnh khi dời SL về hòa vốn
Exit ManagementUse Maximum Hold (minutes)?useTimeExitfalseBật/tắt giới hạn thời gian nắm giữ vị thế tối đa
Exit ManagementMaximum Hold MinutesmaximumHoldMinutes60Số phút tối đa nắm giữ lệnh trước khi tự động đóng vị thế
Exit ManagementBlock New Entries After Daily Closed Loss?useDailyLossGuardtrueChặn mở lệnh mới nếu tổng lỗ đã chốt trong ngày chạm ngưỡng
Exit ManagementDaily Realized Loss Threshold (VND)maximumDailyLossVND3000000Hạn mức lỗ đã thực hiện tối đa trong ngày (3,000,000 VND)
SessionMorning Entry WindowmorningEntry"0930-1120"Khung giờ cho phép mở vị thế mới trong phiên sáng
SessionAfternoon Entry WindowafternoonEntry"1305-1410"Khung giờ cho phép mở vị thế mới trong phiên chiều
SessionForce Close Hour / MinuteforceCloseHour / forceCloseMinute14 / 25Thời điểm bắt buộc đóng toàn bộ vị thế trước phiên ATC (14:25)
DisplayShow Initial Balance Lines? / Midpoint / …showIB, showMidpoint…true (showBreakouts = false)Các tùy chọn hiển thị đường IB, Midpoint, nhãn tín hiệu và bảng Diagnostics

Source Code CNPS57 Failed Initial Balance Auction 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
// CNPS57 independent strategy research for VN30F1M.
// Failed Initial Balance Auction: accepted breakout -> failure -> range reentry.
strategy(title="CNPS57 FAILED INITIAL BALANCE AUCTION V1 - VN30F1M", shorttitle="CNPS57 FAILED IB V1", overlay=true, initial_capital=100000000, currency=currency.VND, default_qty_type=strategy.fixed, default_qty_value=1, pyramiding=0, margin_long=0, margin_short=0, slippage=0, commission_type=strategy.commission.cash_per_contract, commission_value=0, fill_orders_on_standard_ohlc=true, process_orders_on_close=false, calc_on_order_fills=false, calc_on_every_tick=false, max_labels_count=300, max_lines_count=300, max_bars_back=5000)

// ============================================================================
// CNPS57 FAILED INITIAL BALANCE AUCTION V1
//
// HYPOTHESIS:
//
// Morning Initial Balance (IB) = High / Low formed during first 30 minutes.
//
// SHORT:
// Confirmed Close ABOVE IB High
// -> Auction attempts to establish higher prices
// -> Price closes BACK INSIDE IB
// -> Bearish confirmation
// -> SHORT.
//
// LONG:
// Confirmed Close BELOW IB Low
// -> Auction attempts to establish lower prices
// -> Price closes BACK INSIDE IB
// -> Bullish confirmation
// -> LONG.
//
// STOP:
// Beyond the extreme of the failed outside auction.
//
// TARGET:
// IB midpoint if adequate RR, otherwise Fixed R.
//
// The breakout must CLOSE outside IB before any failure is eligible.
// This is different from a same-bar liquidity wick sweep.
//
// VN30F1M / 3 CONTRACTS / CURRENT CHART TIMEFRAME.
// ============================================================================
// ============================================================================
// SECTION 1: TRADE CONTROL
// ============================================================================
tradeDirection = input.string("Both", title="Trade Direction", options=["Both", "Long", "Short"], group="Trade Control")
contracts = input.int(3, title="Contracts Per Entry", minval=1, maxval=20, group="Trade Control")
maximumTradesPerDay = input.int(3, title="Maximum Entries Per Day", minval=1, maxval=20, group="Trade Control")
cooldownBars = input.int(3, title="Cooldown Bars After Exit", minval=0, maxval=100, group="Trade Control")
oneEntryPerSidePerDay = input.bool(false, title="Only One Failed Auction Per Side Per Day?", group="Trade Control")

// ============================================================================
// SECTION 2: INITIAL BALANCE CONSTRUCTION
// ============================================================================
ibMinutes = input.int(30, title="Initial Balance Duration After 09:00 (minutes)", options=[15, 20, 30, 45, 60], group="Initial Balance")
minimumIBRange = input.float(5.0, title="Minimum IB Width (points)", minval=0.0, step=0.5, group="Initial Balance")
maximumIBRange = input.float(70.0, title="Maximum IB Width (points)", minval=5.0, step=1.0, group="Initial Balance")

// ============================================================================
// SECTION 3: OUTSIDE AUCTION AND REENTRY
// ============================================================================
minimumBreakoutDistance = input.float(0.40, title="Outside Close Beyond IB Boundary (points)", minval=0.0, step=0.1, group="Failed Auction")
minimumOutsideCloses = input.int(1, title="Minimum Consecutive Outside Closes", minval=1, maxval=8, group="Failed Auction")
maximumBreakoutMinutes = input.int(55, title="Maximum Time Until Reentry (minutes)", minval=5, maxval=180, group="Failed Auction")
maximumExcursionATR = input.float(4.0, title="Maximum Failed Breakout Extension x ATR14", minval=0.5, maxval=15.0, step=0.25, group="Failed Auction")
reentryBuffer = input.float(0.20, title="Required Close Back Inside IB (points)", minval=0.0, step=0.1, group="Failed Auction")

// ============================================================================
// SECTION 4: ENTRY CONFIRMATION
// ============================================================================
entryMode = input.string("Reentry Momentum", title="Entry Confirmation Mode", options=["Reentry Momentum", "Follow-Through", "Retest Failure"], group="Confirmation")
minimumBodyRatio = input.float(0.25, title="Minimum Reversal Candle Body / Range", minval=0.0, maxval=1.0, step=0.05, group="Confirmation")
reentryConfirmBars = input.int(5, title="Follow-Through / Retest Confirmation Window", minval=1, maxval=20, group="Confirmation")
retestTolerance = input.float(0.70, title="Retest Distance From IB Boundary (points)", minval=0.0, maxval=10.0, step=0.1, group="Confirmation")

// ============================================================================
// SECTION 5: OPTIONAL TREND FILTER
// ============================================================================
useTrendGuard = input.bool(true, title="Avoid Very Strong Countertrend Trades?", group="Regime Filter")
trendEMALength = input.int(55, title="Trend EMA Length", minval=5, maxval=300, group="Regime Filter")
trendSlopeBars = input.int(5, title="Trend EMA Slope Bars", minval=1, maxval=50, group="Regime Filter")
strongTrendADX = input.float(36.0, title="Strong Trend ADX14 Threshold", minval=10.0, maxval=60.0, step=1.0, group="Regime Filter")
minimumAdverseSlopeATR = input.float(0.60, title="Adverse EMA Slope In ATR Units", minval=0.05, maxval=5.0, step=0.05, group="Regime Filter")

// ============================================================================
// SECTION 6: RISK / TARGET
// ============================================================================
targetMode = input.string("IB Midpoint / Fixed R", title="Target Mode", options=["IB Midpoint / Fixed R", "IB Midpoint Only", "Fixed R Only", "Opposite IB Edge"], group="Risk Management")
fixedTargetR = input.float(1.50, title="Fixed Take Profit Multiple (R)", minval=0.25, maxval=8.0, step=0.10, group="Risk Management")
minimumRewardRisk = input.float(1.05, title="Minimum Reward / Risk At Signal", minval=0.50, maxval=5.0, step=0.05, group="Risk Management")
minimumGrossTarget = input.float(2.50, title="Minimum Gross Reward (points)", minval=0.0, step=0.5, group="Risk Management")
minimumStopPoints = input.float(1.50, title="Minimum Structural SL (points)", minval=0.1, step=0.5, group="Risk Management")
maximumStopPoints = input.float(14.0, title="Maximum Structural SL (points)", minval=0.5, step=0.5, group="Risk Management")
stopBufferTicks = input.int(2, title="Stop Buffer Beyond Breakout Extreme (ticks)", minval=0, maxval=100, group="Risk Management")
midpointTargetBuffer = input.float(0.00, title="IB Target Buffer (points)", minval=0.0, maxval=5.0, step=0.1, group="Risk Management")

// ============================================================================
// SECTION 7: OPTIONAL EARLY EXITS
// ============================================================================
useFailedReentryExit = input.bool(false, title="Exit If IB Reentry Fails?", group="Exit Management")
failureCloses = input.int(2, title="Consecutive Closes Back Outside IB", minval=1, maxval=5, group="Exit Management")
useBreakEven = input.bool(false, title="Use Break Even?", group="Exit Management")
breakEvenAtR = input.float(1.0, title="Break Even Trigger (R, close-confirmed)", minval=0.25, step=0.25, group="Exit Management")
breakEvenOffset = input.float(0.20, title="Break Even Offset (points)", minval=0.0, step=0.10, group="Exit Management")
useTimeExit = input.bool(false, title="Use Maximum Hold (minutes)?", group="Exit Management")
maximumHoldMinutes = input.int(60, title="Maximum Hold Minutes", minval=5, maxval=240, group="Exit Management")
useDailyLossGuard = input.bool(true, title="Block New Entries After Daily Closed Loss?", group="Exit Management")
maximumDailyLossVND = input.float(3000000, title="Daily Realized Loss Threshold (VND)", minval=100000, step=100000, group="Exit Management")

// ============================================================================
// SECTION 8: VN30F1M SESSION
// ============================================================================
string strategyTimezone = "Asia/Ho_Chi_Minh"
morningEntry = input.session("0930-1120", title="Morning Entry Window", group="Session")
afternoonEntry = input.session("1305-1410", title="Afternoon Entry Window", group="Session")
forceCloseHour = input.int(14, title="Force Close Hour", minval=0, maxval=23, group="Session")
forceCloseMinute = input.int(14, title="Force Close Minute (Before ATC)", minval=0, maxval=59, group="Session")

// ============================================================================
// SECTION 9: DISPLAY / DIAGNOSTICS
// ============================================================================
showIB = input.bool(true, "Show Initial Balance Lines?", group="Display")
showMidpoint = input.bool(true, "Show IB Midpoint?", group="Display")
showBreakouts = input.bool(false, "Show Outside Breakout Marks?", group="Display")
showReentries = input.bool(true, "Show Failed Auction / Reentry Marks?", group="Display")
showEntries = input.bool(true, "Show Final Entries?", group="Display")
showStops = input.bool(true, "Show Active Stop / Target?", group="Display")
showDiagnostics = input.bool(true, "Show Signal Funnel Diagnostics?", group="Display")

// ============================================================================
// SECTION 10: TRADING CLOCK
// ============================================================================
int openMinute = hour(time, strategyTimezone) * 60 + minute(time, strategyTimezone)
int closeMinute = hour(time_close, strategyTimezone) * 60 + minute(time_close, strategyTimezone)
int ibEndMinute = 540 + ibMinutes
int sessionEndMinute = forceCloseHour * 60 + forceCloseMinute
bool continuousMorning = openMinute >= 540 and openMinute < 690
bool continuousAfternoon = openMinute >= 780 and openMinute < 870
bool inIBWindow = continuousMorning and openMinute >= 540 and closeMinute <= ibEndMinute
bool ibTimeCompleted = openMinute >= ibEndMinute
bool firstAfternoonBar = continuousAfternoon and not continuousAfternoon[1]
bool inMorningEntry = not na(time(timeframe.period, morningEntry + ":23456", strategyTimezone))
bool inAfternoonEntry = not na(time(timeframe.period, afternoonEntry + ":23456", strategyTimezone))
bool entrySession = inMorningEntry or inAfternoonEntry
int dayKey = (year(time, strategyTimezone) * 10000 + month(time, strategyTimezone) * 100 + dayofmonth(time, strategyTimezone))
bool newTradingDay = bar_index == 0 or dayKey != nz(dayKey[1], dayKey)
bool beforeForceClose = not na(time_close) and closeMinute < sessionEndMinute
bool forceCloseBar = (barstate.isconfirmed and not na(time_close) and openMinute < sessionEndMinute and closeMinute >= sessionEndMinute)

// ============================================================================
// SECTION 11: BUILD AND FREEZE INITIAL BALANCE
// ============================================================================
var float ibHigh = na
var float ibLow = na
var int ibBars = 0
if newTradingDay
    ibHigh := na
    ibLow := na
    ibBars := 0
if inIBWindow and barstate.isconfirmed
    ibHigh := math.max(nz(ibHigh, high), high)
    ibLow := math.min(nz(ibLow, low), low)
    ibBars += 1
float ibMid = (ibHigh + ibLow) / 2.0
float ibWidth = ibHigh - ibLow
bool ibReady = (ibTimeCompleted and ibBars >= 3 and not na(ibHigh) and not na(ibLow) and ibWidth >= minimumIBRange and ibWidth <= maximumIBRange)

// ============================================================================
// SECTION 12: VOLATILITY AND CANDLE QUALITY
// ============================================================================
float atr = ta.atr(14)
float trendEMA = ta.ema(close, trendEMALength)
[pDI, mDI, adx] = ta.dmi(14, 14)
float candleRange = math.max(high - low, syminfo.mintick)
float bodyRatio = math.abs(close - open) / candleRange
float closeLocation = (close - low) / candleRange
bool bearReversalCandle = (close < open and bodyRatio >= minimumBodyRatio and closeLocation <= 0.50)
bool bullReversalCandle = (close > open and bodyRatio >= minimumBodyRatio and closeLocation >= 0.50)
float emaSlopeATR = (not na(atr) and atr > 0 ? (trendEMA - trendEMA[trendSlopeBars]) / atr : 0.0)
bool dangerousShortTrend = (useTrendGuard and not na(adx) and adx >= strongTrendADX and emaSlopeATR >= minimumAdverseSlopeATR and close > trendEMA and pDI > mDI)
bool dangerousLongTrend = (useTrendGuard and not na(adx) and adx >= strongTrendADX and emaSlopeATR <= -minimumAdverseSlopeATR and close < trendEMA and mDI > pDI)

// ============================================================================
// SECTION 13: DAILY COUNTERS / RISK GUARD
// ============================================================================
var int tradesToday = 0
var int closedTradesSeen = 0
var int lastExitBar = na
var int lastEntrySignalBar = na
var float startDayNetProfit = na
var bool usedUpperAuction = false
var bool usedLowerAuction = false
var int upperBreakouts = 0
var int lowerBreakouts = 0
var int upperFailures = 0
var int lowerFailures = 0
var int rejectedTrend = 0
var int rejectedRisk = 0
var int rejectedTarget = 0
var int rejectedControls = 0
var int longEntries = 0
var int shortEntries = 0
var int midpointEntries = 0
var int fixedREntries = 0
var int oppositeEdgeEntries = 0
if newTradingDay
    tradesToday := 0
    startDayNetProfit := strategy.netprofit
    usedUpperAuction := false
    usedLowerAuction := false
if strategy.closedtrades > closedTradesSeen
    closedTradesSeen := strategy.closedtrades
    lastExitBar := bar_index
bool flat = strategy.position_size == 0
bool inLong = strategy.position_size > 0
bool inShort = strategy.position_size < 0
bool allowLong = tradeDirection != "Short"
bool allowShort = tradeDirection != "Long"
bool cooldownOK = na(lastExitBar) or bar_index - lastExitBar > cooldownBars
bool dailyLimitOK = tradesToday < maximumTradesPerDay
float closedPnLToday = strategy.netprofit - nz(startDayNetProfit, strategy.netprofit)
bool lossGuardOK = (not useDailyLossGuard or closedPnLToday > -maximumDailyLossVND)
bool onlyOneOrderThisBar = (na(lastEntrySignalBar) or lastEntrySignalBar != bar_index)
bool commonEntryOK = (flat and ibReady and entrySession and beforeForceClose and cooldownOK and dailyLimitOK and lossGuardOK and onlyOneOrderThisBar and barstate.isconfirmed)

// ============================================================================
// SECTION 14: FAILED AUCTION STATE MACHINE
// ============================================================================
//
// State  0 = Waiting for breakout.
// State  1 = Confirmed close ABOVE IB High.
// State -1 = Confirmed close BELOW IB Low.
// State  2 = Upper auction reentered, awaiting confirmation.
// State -2 = Lower auction reentered, awaiting confirmation.
//
// ============================================================================
var int auctionState = 0
var int breakoutStartTime = na
var int outsideCloseCount = 0
var bool sufficientOutsideCloses = false
var float breakoutExtreme = na
var int reentryBar = na
var float reentryHigh = na
var float reentryLow = na
bool newUpperBreakout = false
bool newLowerBreakout = false
bool upperReentry = false
bool lowerReentry = false
bool rawLong = false
bool rawShort = false
bool upperSideAllowed = (not oneEntryPerSidePerDay or not usedUpperAuction)
bool lowerSideAllowed = (not oneEntryPerSidePerDay or not usedLowerAuction)
if newTradingDay or firstAfternoonBar
    auctionState := 0
    breakoutStartTime := na
    outsideCloseCount := 0
    sufficientOutsideCloses := false
    breakoutExtreme := na
    reentryBar := na
    reentryHigh := na
    reentryLow := na
if (barstate.isconfirmed and ibReady and beforeForceClose and (continuousMorning or continuousAfternoon))
    bool upperOutside = close >= ibHigh + minimumBreakoutDistance
    bool lowerOutside = close <= ibLow - minimumBreakoutDistance
    bool insideUpper = (close < ibHigh - reentryBuffer and close > ibLow)
    bool insideLower = (close > ibLow + reentryBuffer and close < ibHigh)
    bool expiredBreakout = (not na(breakoutStartTime) and time_close - breakoutStartTime > maximumBreakoutMinutes * 60000)

    // ========================================================================
    // STATE 0: DETECT CONFIRMED OUTSIDE CLOSE
    // ========================================================================
    if auctionState == 0
        if upperOutside and upperSideAllowed
            auctionState := 1
            breakoutStartTime := time_close
            outsideCloseCount := 1
            sufficientOutsideCloses := minimumOutsideCloses <= 1
            breakoutExtreme := high
            newUpperBreakout := true
            upperBreakouts += 1
        else if lowerOutside and lowerSideAllowed
            auctionState := -1
            breakoutStartTime := time_close
            outsideCloseCount := 1
            sufficientOutsideCloses := minimumOutsideCloses <= 1
            breakoutExtreme := low
            newLowerBreakout := true
            lowerBreakouts += 1

    // ========================================================================
    // STATE 1: UPPER OUTSIDE AUCTION
    // ========================================================================
    else if auctionState == 1
        breakoutExtreme := math.max(breakoutExtreme, high)
        bool extendedTooFar = (not na(atr) and atr > 0 and breakoutExtreme - ibHigh > maximumExcursionATR * atr)
        if expiredBreakout or extendedTooFar
            auctionState := 0
        else if upperOutside
            outsideCloseCount += 1
            sufficientOutsideCloses := (sufficientOutsideCloses or outsideCloseCount >= minimumOutsideCloses)
        else if insideUpper and sufficientOutsideCloses
            upperReentry := true
            upperFailures += 1
            reentryBar := bar_index
            reentryHigh := high
            reentryLow := low
            if entryMode == "Reentry Momentum"
                rawShort := bearReversalCandle
                auctionState := 0
            else
                auctionState := 2
        else if not upperOutside
            outsideCloseCount := 0

    // ========================================================================
    // STATE -1: LOWER OUTSIDE AUCTION
    // ========================================================================
    else if auctionState == -1
        breakoutExtreme := math.min(breakoutExtreme, low)
        bool extendedTooFar = (not na(atr) and atr > 0 and ibLow - breakoutExtreme > maximumExcursionATR * atr)
        if expiredBreakout or extendedTooFar
            auctionState := 0
        else if lowerOutside
            outsideCloseCount += 1
            sufficientOutsideCloses := (sufficientOutsideCloses or outsideCloseCount >= minimumOutsideCloses)
        else if insideLower and sufficientOutsideCloses
            lowerReentry := true
            lowerFailures += 1
            reentryBar := bar_index
            reentryHigh := high
            reentryLow := low
            if entryMode == "Reentry Momentum"
                rawLong := bullReversalCandle
                auctionState := 0
            else
                auctionState := -2
        else if not lowerOutside
            outsideCloseCount := 0

    // ========================================================================
    // STATE 2: UPPER REENTRY CONFIRMATION
    // ========================================================================
    else if auctionState == 2
        bool expiredConfirm = bar_index - reentryBar > reentryConfirmBars
        bool failedConfirm = close > ibHigh + reentryBuffer
        if expiredConfirm or failedConfirm
            auctionState := 0
        else if bar_index > reentryBar
            bool closeStillInsideIB = (close > ibLow and close < ibHigh - reentryBuffer)
            bool followThrough = (entryMode == "Follow-Through" and closeStillInsideIB and close < reentryLow and bearReversalCandle)
            bool retestFailure = (entryMode == "Retest Failure" and closeStillInsideIB and high >= ibHigh - retestTolerance and bearReversalCandle)
            if followThrough or retestFailure
                rawShort := true
                breakoutExtreme := math.max(breakoutExtreme, high)
                auctionState := 0

    // ========================================================================
    // STATE -2: LOWER REENTRY CONFIRMATION
    // ========================================================================
    else if auctionState == -2
        bool expiredConfirm = bar_index - reentryBar > reentryConfirmBars
        bool failedConfirm = close < ibLow - reentryBuffer
        if expiredConfirm or failedConfirm
            auctionState := 0
        else if bar_index > reentryBar
            bool closeStillInsideIB = (close < ibHigh and close > ibLow + reentryBuffer)
            bool followThrough = (entryMode == "Follow-Through" and closeStillInsideIB and close > reentryHigh and bullReversalCandle)
            bool retestFailure = (entryMode == "Retest Failure" and closeStillInsideIB and low <= ibLow + retestTolerance and bullReversalCandle)
            if followThrough or retestFailure
                rawLong := true
                breakoutExtreme := math.min(breakoutExtreme, low)
                auctionState := 0

// ============================================================================
// SECTION 15: STRUCTURAL SL AND TARGET OBJECTIVES
// ============================================================================
float shortStopCandidate = (not na(breakoutExtreme) and rawShort ? math.round_to_mintick(breakoutExtreme + stopBufferTicks * syminfo.mintick) : na)
float longStopCandidate = (not na(breakoutExtreme) and rawLong ? math.round_to_mintick(breakoutExtreme - stopBufferTicks * syminfo.mintick) : na)
float shortRisk = shortStopCandidate - close
float longRisk = close - longStopCandidate
bool shortRiskOK = (not na(shortRisk) and shortRisk >= minimumStopPoints and shortRisk <= maximumStopPoints)
bool longRiskOK = (not na(longRisk) and longRisk >= minimumStopPoints and longRisk <= maximumStopPoints)
float midpointShortTarget = math.round_to_mintick(ibMid + midpointTargetBuffer)
float midpointLongTarget = math.round_to_mintick(ibMid - midpointTargetBuffer)
float oppositeShortTarget = math.round_to_mintick(ibLow + midpointTargetBuffer)
float oppositeLongTarget = math.round_to_mintick(ibHigh - midpointTargetBuffer)
float fixedShortTarget = math.round_to_mintick(close - shortRisk * fixedTargetR)
float fixedLongTarget = math.round_to_mintick(close + longRisk * fixedTargetR)
bool midpointShortOK = (shortRiskOK and not na(ibMid) and close - midpointShortTarget >= minimumGrossTarget and (close - midpointShortTarget) / shortRisk >= minimumRewardRisk)
bool midpointLongOK = (longRiskOK and not na(ibMid) and midpointLongTarget - close >= minimumGrossTarget and (midpointLongTarget - close) / longRisk >= minimumRewardRisk)
bool useMidpointShort = (targetMode == "IB Midpoint Only" or (targetMode == "IB Midpoint / Fixed R" and midpointShortOK))
bool useMidpointLong = (targetMode == "IB Midpoint Only" or (targetMode == "IB Midpoint / Fixed R" and midpointLongOK))
float shortTarget = (targetMode == "Opposite IB Edge" ? oppositeShortTarget : useMidpointShort ? midpointShortTarget : fixedShortTarget)
float longTarget = (targetMode == "Opposite IB Edge" ? oppositeLongTarget : useMidpointLong ? midpointLongTarget : fixedLongTarget)
float shortReward = close - shortTarget
float longReward = longTarget - close
bool shortTargetOK = (shortRiskOK and not na(shortReward) and shortReward >= minimumGrossTarget and shortReward / shortRisk >= minimumRewardRisk)
bool longTargetOK = (longRiskOK and not na(longReward) and longReward >= minimumGrossTarget and longReward / longRisk >= minimumRewardRisk)

// ============================================================================
// SECTION 16: FINAL ENTRY APPROVAL
// ============================================================================
bool longQuality = not dangerousLongTrend
bool shortQuality = not dangerousShortTrend
bool finalLong = (rawLong and allowLong and longQuality and longTargetOK and commonEntryOK)
bool finalShort = (rawShort and allowShort and shortQuality and shortTargetOK and commonEntryOK and not finalLong)
if rawLong or rawShort
    if ((rawLong and not longQuality) or (rawShort and not shortQuality))
        rejectedTrend += 1
    else if ((rawLong and not longRiskOK) or (rawShort and not shortRiskOK))
        rejectedRisk += 1
    else if ((rawLong and not longTargetOK) or (rawShort and not shortTargetOK))
        rejectedTarget += 1
    else if not finalLong and not finalShort
        rejectedControls += 1

// ============================================================================
// SECTION 17: ENTRY ORDERS AND PROTECTIVE BRACKETS
// ============================================================================
var float activeStop = na
var float activeTarget = na
var float originalFillRisk = na
var int seenEntryBar = na
var int reentryFailureCloses = 0
var bool breakEvenActive = false

// ============================================================================
// LONG ENTRY
// ============================================================================
if finalLong
    activeStop := longStopCandidate
    activeTarget := longTarget
    originalFillRisk := na
    seenEntryBar := na
    reentryFailureCloses := 0
    breakEvenActive := false
    strategy.entry("CNPS57-L", strategy.long, comment="FAILED IB LOWER AUCTION", alert_message="🟢 VÀO VỊ THẾ LONG (CNPS57)\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\n🛑 Cắt lỗ (SL): " + str.tostring(activeStop, format.mintick) + "\n🎯 Chốt lời (TP): " + str.tostring(activeTarget, format.mintick))
    strategy.exit("CNPS57-L-X", from_entry="CNPS57-L", stop=activeStop, limit=activeTarget, comment_profit="TP Long", comment_loss="SL Long", alert_profit="💰 CHỐT LỜI LONG (TP HIT)\n🎯 Giá chốt lời: " + str.tostring(activeTarget, format.mintick), alert_loss="🛑 CẮT LỖ LONG (SL HIT)\nGiá cắt lỗ: " + str.tostring(activeStop, format.mintick))
    lastEntrySignalBar := bar_index
    tradesToday += 1
    longEntries += 1
    usedLowerAuction := true
    if targetMode == "Opposite IB Edge"
        oppositeEdgeEntries += 1
    else if useMidpointLong
        midpointEntries += 1
    else
        fixedREntries += 1

// ============================================================================
// SHORT ENTRY
// ============================================================================
else if finalShort
    activeStop := shortStopCandidate
    activeTarget := shortTarget
    originalFillRisk := na
    seenEntryBar := na
    reentryFailureCloses := 0
    breakEvenActive := false
    strategy.entry("CNPS57-S", strategy.short, comment="FAILED IB UPPER AUCTION", alert_message="🔴 VÀO VỊ THẾ SHORT (CNPS57)\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\n🛑 Cắt lỗ (SL): " + str.tostring(activeStop, format.mintick) + "\n🎯 Chốt lời (TP): " + str.tostring(activeTarget, format.mintick))
    strategy.exit("CNPS57-S-X", from_entry="CNPS57-S", stop=activeStop, limit=activeTarget, comment_profit="TP Short", comment_loss="SL Short", alert_profit="💰 CHỐT LỜI SHORT (TP HIT)\n🎯 Giá chốt lời: " + str.tostring(activeTarget, format.mintick), alert_loss="🛑 CẮT LỖ SHORT (SL HIT)\nGiá cắt lỗ: " + str.tostring(activeStop, format.mintick))
    lastEntrySignalBar := bar_index
    tradesToday += 1
    shortEntries += 1
    usedUpperAuction := true
    if targetMode == "Opposite IB Edge"
        oppositeEdgeEntries += 1
    else if useMidpointShort
        midpointEntries += 1
    else
        fixedREntries += 1

// ============================================================================
// SECTION 18: AFTER-FILL STOP AND BREAK EVEN
// ============================================================================
if (strategy.position_size != 0 and strategy.opentrades > 0 and barstate.isconfirmed)
    int fillBar = strategy.opentrades.entry_bar_index(0)
    float fillPrice = strategy.position_avg_price
    if na(seenEntryBar) or seenEntryBar != fillBar
        seenEntryBar := fillBar
        originalFillRisk := (inLong ? fillPrice - activeStop : activeStop - fillPrice)
    float actualReward = (inLong ? activeTarget - fillPrice : fillPrice - activeTarget)
    bool validFill = (not na(originalFillRisk) and originalFillRisk > syminfo.mintick and actualReward > 0)
    if not validFill
        strategy.close(inLong ? "CNPS57-L" : "CNPS57-S", immediately=true, comment="INVALID GAP FILL", alert_message="⚠️ ĐÓNG VỊ THẾ DO GAP/RỦI RO KHÔNG HỢP LỆ (Invalid Gap)")
    else
        float currentR = (inLong ? (close - fillPrice) / originalFillRisk : (fillPrice - close) / originalFillRisk)
        if useBreakEven and currentR >= breakEvenAtR
            float breakEvenStop = math.round_to_mintick(inLong ? fillPrice + breakEvenOffset : fillPrice - breakEvenOffset)
            activeStop := (inLong ? math.max(activeStop, breakEvenStop) : math.min(activeStop, breakEvenStop))
            breakEvenActive := true
        if inLong
            strategy.exit("CNPS57-L-X", from_entry="CNPS57-L", stop=activeStop, limit=activeTarget, comment_profit="TP Long", comment_loss=breakEvenActive ? "BE Long" : "SL Long", alert_profit="💰 CHỐT LỜI LONG (TP HIT)\n🎯 Giá chốt lời: " + str.tostring(activeTarget, format.mintick), alert_loss=breakEvenActive ? "🛡️ HÒA VỐN LONG (BE HIT)\nGiá hòa vốn: " + str.tostring(activeStop, format.mintick) : "🛑 CẮT LỖ LONG (SL HIT)\nGiá cắt lỗ: " + str.tostring(activeStop, format.mintick))
        else
            strategy.exit("CNPS57-S-X", from_entry="CNPS57-S", stop=activeStop, limit=activeTarget, comment_profit="TP Short", comment_loss=breakEvenActive ? "BE Short" : "SL Short", alert_profit="💰 CHỐT LỜI SHORT (TP HIT)\n🎯 Giá chốt lời: " + str.tostring(activeTarget, format.mintick), alert_loss=breakEvenActive ? "🛡️ HÒA VỐN SHORT (BE HIT)\nGiá hòa vốn: " + str.tostring(activeStop, format.mintick) : "🛑 CẮT LỖ SHORT (SL HIT)\nGiá cắt lỗ: " + str.tostring(activeStop, format.mintick))

// ============================================================================
// SECTION 19: OPTIONAL EARLY EXIT
// ============================================================================
if (strategy.position_size != 0 and strategy.opentrades > 0 and barstate.isconfirmed)
    bool failedReentry = (inLong ? close < ibLow - reentryBuffer : close > ibHigh + reentryBuffer)
    reentryFailureCloses := (failedReentry ? reentryFailureCloses + 1 : 0)
    if useFailedReentryExit and reentryFailureCloses >= failureCloses
        strategy.close(inLong ? "CNPS57-L" : "CNPS57-S", comment="IB REENTRY FAILED", alert_message="⚡ ĐÓNG VỊ THẾ DO TÁI NHẬP IB THẤT BẠI (Reentry Failed)")
    int entryTime = strategy.opentrades.entry_time(0)
    if useTimeExit and time_close >= entryTime + maximumHoldMinutes * 60000
        strategy.close(inLong ? "CNPS57-L" : "CNPS57-S", comment="TIME EXIT", alert_message="⏱️ ĐÓNG VỊ THẾ HẾT THỜI GIAN GIỮ LỆNH (Time Exit)")

// ============================================================================
// SECTION 20: FORCE CLOSE BEFORE ATC / CLEANUP
// ============================================================================
if forceCloseBar and strategy.position_size != 0
    strategy.close_all(immediately=true, comment="FORCED FLAT BEFORE ATC", alert_message="⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End)")
if flat and not finalLong and not finalShort
    activeStop := na
    activeTarget := na
    originalFillRisk := na
    seenEntryBar := na
    reentryFailureCloses := 0
    breakEvenActive := false

// ============================================================================
// SECTION 21: CHART DISPLAY
// ============================================================================
plot(showIB and ibReady ? ibHigh : na, title="Initial Balance High", color=color.new(color.red, 15), linewidth=2, style=plot.style_linebr)
plot(showIB and ibReady ? ibLow : na, title="Initial Balance Low", color=color.new(color.teal, 15), linewidth=2, style=plot.style_linebr)
plot(showMidpoint and ibReady ? ibMid : na, title="Initial Balance Midpoint", color=color.new(color.orange, 20), linewidth=1, style=plot.style_linebr)
plot(showStops and strategy.position_size != 0 ? activeStop : na, title="Active Structural Stop", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showStops and strategy.position_size != 0 ? activeTarget : na, title="Frozen Profit Target", color=color.green, linewidth=2, style=plot.style_linebr)
plotshape(showBreakouts and newUpperBreakout, title="Outside Close Above IB", text="BO+", style=shape.circle, location=location.abovebar, color=color.new(color.red, 45), size=size.tiny)
plotshape(showBreakouts and newLowerBreakout, title="Outside Close Below IB", text="BO-", style=shape.circle, location=location.belowbar, color=color.new(color.teal, 45), size=size.tiny)
plotshape(showReentries and upperReentry, title="Upper Auction Reentered IB", text="FAIL-H", style=shape.circle, location=location.abovebar, color=color.new(color.red, 10), textcolor=color.white, size=size.tiny)
plotshape(showReentries and lowerReentry, title="Lower Auction Reentered IB", text="FAIL-L", style=shape.circle, location=location.belowbar, color=color.new(color.teal, 10), textcolor=color.white, size=size.tiny)
plotshape(showEntries and finalLong, title="CNPS57 Long", text="LONG", style=shape.triangleup, location=location.belowbar, color=color.teal, textcolor=color.white, size=size.small)
plotshape(showEntries and finalShort, title="CNPS57 Short", text="SHORT", style=shape.triangledown, location=location.abovebar, color=color.red, textcolor=color.white, size=size.small)

// ============================================================================
// SECTION 22: SIGNAL FUNNEL DIAGNOSTICS
// ============================================================================
var table diagnostics = table.new(position.top_right, 2, 17, border_width=1)
if barstate.islast
    if showDiagnostics
        table.cell(diagnostics, 0, 0, "CNPS57 V1")
        table.cell(diagnostics, 1, 0, timeframe.period)
        table.cell(diagnostics, 0, 1, "IB Ready / Bars")
        table.cell(diagnostics, 1, 1, (ibReady ? "YES" : "NO") + " / " + str.tostring(ibBars))
        table.cell(diagnostics, 0, 2, "IB High / Low")
        table.cell(diagnostics, 1, 2, str.tostring(ibHigh, format.mintick) + " / " + str.tostring(ibLow, format.mintick))
        table.cell(diagnostics, 0, 3, "IB Width")
        table.cell(diagnostics, 1, 3, str.tostring(ibWidth, "#.0"))
        table.cell(diagnostics, 0, 4, "State")
        table.cell(diagnostics, 1, 4, str.tostring(auctionState))
        table.cell(diagnostics, 0, 5, "Upper / Lower BO")
        table.cell(diagnostics, 1, 5, str.tostring(upperBreakouts) + " / " + str.tostring(lowerBreakouts))
        table.cell(diagnostics, 0, 6, "Failed Upper / Lower")
        table.cell(diagnostics, 1, 6, str.tostring(upperFailures) + " / " + str.tostring(lowerFailures))
        table.cell(diagnostics, 0, 7, "Reject Trend")
        table.cell(diagnostics, 1, 7, str.tostring(rejectedTrend))
        table.cell(diagnostics, 0, 8, "Reject Stop")
        table.cell(diagnostics, 1, 8, str.tostring(rejectedRisk))
        table.cell(diagnostics, 0, 9, "Reject Target")
        table.cell(diagnostics, 1, 9, str.tostring(rejectedTarget))
        table.cell(diagnostics, 0, 10, "Reject Control")
        table.cell(diagnostics, 1, 10, str.tostring(rejectedControls))
        table.cell(diagnostics, 0, 11, "Long Entries")
        table.cell(diagnostics, 1, 11, str.tostring(longEntries))
        table.cell(diagnostics, 0, 12, "Short Entries")
        table.cell(diagnostics, 1, 12, str.tostring(shortEntries))
        table.cell(diagnostics, 0, 13, "Mid / Fixed / Edge")
        table.cell(diagnostics, 1, 13, str.tostring(midpointEntries) + " / " + str.tostring(fixedREntries) + " / " + str.tostring(oppositeEdgeEntries))
        table.cell(diagnostics, 0, 14, "Trades Today")
        table.cell(diagnostics, 1, 14, str.tostring(tradesToday))
        table.cell(diagnostics, 0, 15, "PnL Today (closed)")
        table.cell(diagnostics, 1, 15, str.tostring(closedPnLToday, "#.0"))
        table.cell(diagnostics, 0, 16, "Position")
        table.cell(diagnostics, 1, 16, inLong ? "LONG" : inShort ? "SHORT" : "FLAT")
    else
        table.clear(diagnostics, 0, 0, 1, 16)

// ============================================================================
// RESEARCH LIMITATIONS
// ============================================================================
//
// 1. Initial Balance is based on continuous session bars from 09:00.
// 2. Incomplete historical bars may give incomplete IB observations.
// 3. At least one confirmed outside close is required before reentry.
// 4. There is no lookahead or future-bar pivot usage.
// 5. Initial SL / TP use the signal close, with next-bar market entry.
// 6. Target stays frozen, including after actual fill.
// 7. Initial risk remains fixed when optional Break Even is enabled.
// 8. Daily realized loss guard only blocks NEW entries.
// 9. Session force-flat is simulated at the selected chart bar close.
// 10. Zero margin is a backtest setting, not actual required margin.
// 11. This V1 has not been verified profitable or compiled on TradingView.

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

2.1. Vùng Cân Bằng Đầu Phiên (Initial Balance - IB) và Điều kiện khóa IB (ibReady)

Trong lý thuyết Market Profile, Initial Balance (IB) là vùng giá được thiết lập bởi các thành viên thị trường trong giai đoạn mở cửa phiên liên tục buổi sáng. Trong CNPS57, cửa sổ thu thập IB (inIBWindow) bắt đầu từ 09:00 (openMinute >= 540) và kết thúc tại 540 + ibMinutes (mặc định 30 phút, tương ứng 09:30):

  • Trên mỗi thanh nến đã đóng cửa (barstate.isconfirmed) nằm trong inIBWindow, bot cập nhật:
    • ibHigh := math.max(nz(ibHigh, high), high)
    • ibLow := math.min(nz(ibLow, low), low)
    • ibBars += 1
  • Điểm giữa vùng IB (ibMid) và độ rộng vùng IB (ibWidth) được tính bằng: $$\text{ibMid} = \frac{\text{ibHigh} + \text{ibLow}}{2.0}, \quad \text{ibWidth} = \text{ibHigh} - \text{ibLow}$$
  • Vùng IB chỉ được coi là hợp lệ và khóa cố định cho cả ngày (ibReady = true) khi thỏa mãn đồng thời 4 điều kiện:
    1. Đã qua thời gian hình thành IB (openMinute >= ibEndMinute, tức từ 09:30 trở đi).
    2. Có ít nhất 3 thanh nến được ghi nhận trong cửa sổ IB (ibBars >= 3).
    3. Đã xác định được giá trị ibHigh và ibLow.
    4. Độ rộng vùng IB nằm trong ngưỡng cho phép: minimumIBRange (5.0) <= ibWidth <= maximumIBRange (70.0).

2.2. Máy trạng thái Đấu giá thất bại (Failed Auction State Machine) và 3 chế độ xác nhận

Khác với các bot bắt quét thanh khoản trong cùng 1 thanh nến, CNPS57 sử dụng biến trạng thái auctionState gồm 5 giá trị (0, 1, -1, 2, -2) để theo dõi toàn bộ vòng đời của một cuộc đấu giá bên ngoài biên IB. Máy trạng thái này được reset về 0 khi sang ngày mới (newTradingDay) hoặc tại thanh nến đầu tiên của phiên chiều (firstAfternoonBar).

  • Trạng thái 0 (Waiting for breakout): Chờ nến đóng cửa xác nhận bên ngoài biên IB ít nhất một khoảng minimumBreakoutDistance (0.40 điểm):
    • Phá vỡ lên (upperOutside): close >= ibHigh + 0.40 và biên trên được phép giao dịch (upperSideAllowed) → chuyển sang auctionState = 1, lưu thời điểm breakoutStartTime := time_close, khởi tạo breakoutExtreme := high.
    • Phá vỡ xuống (lowerOutside): close <= ibLow - 0.40 và biên dưới được phép giao dịch (lowerSideAllowed) → chuyển sang auctionState = -1, lưu thời điểm breakoutStartTime := time_close, khởi tạo breakoutExtreme := low.
  • Trạng thái 1 / -1 (Outside Auction): Theo dõi nhịp đấu giá bên ngoài biên IB:
    • Liên tục cập nhật điểm cực trị breakoutExtreme (math.max với biên trên, math.min với biên dưới).
    • Hủy bỏ nhịp đấu giá (reset về 0) nếu quá thời gian tối đa (time_close - breakoutStartTime > maximumBreakoutMinutes * 60000, mặc định 55 phút) hoặc giá đi quá xa khỏi biên IB (breakoutExtreme - ibHigh > maximumExcursionATR * atr đối với biên trên, hoặc ibLow - breakoutExtreme > maximumExcursionATR * atr đối với biên dưới, mặc định 4.0 x ATR14).
    • Đếm số nến liên tiếp đóng cửa ngoài IB (outsideCloseCount). Khi đã đủ số nến đóng cửa ngoài IB (sufficientOutsideCloses, mặc định >= 1 nến) và giá đóng cửa quay ngược vào bên trong vùng IB vượt qua đệm reentryBuffer (0.20 điểm):
      • Tái nhập từ biên trên (insideUpper): close < ibHigh - 0.20 và close > ibLow.
      • Tái nhập từ biên dưới (insideLower): close > ibLow + 0.20 và close < ibHigh.
    • Khi tái nhập thành công, bot lưu lại thông tin thanh nến tái nhập (reentryBar, reentryHigh, reentryLow) và xử lý theo entryMode:
Chế độ entryModeTrạng thái xử lýĐiều kiện kích hoạt tín hiệu thô (rawLong / rawShort)
Reentry Momentum (Mặc định)Ngay tại trạng thái 1 hoặc -1 (sau đó reset về 0)Ngay tại thanh nến đóng cửa tái nhập vào trong IB, thanh nến đó phải là nến đảo chiều hợp lệ (bearReversalCandle cho Short, bullReversalCandle cho Long).
Follow-ThroughChuyển sang trạng thái 2 (Short) hoặc -2 (Long) trong tối đa reentryConfirmBars (5 nến)Tại các nến sau nến tái nhập (bar_index > reentryBar), giá vẫn đóng cửa bên trong IB (closeStillInsideIB), đóng cửa vượt qua cực trị của nến tái nhập (close < reentryLow cho Short, close > reentryHigh cho Long) và là nến đảo chiều hợp lệ.
Retest FailureChuyển sang trạng thái 2 (Short) hoặc -2 (Long) trong tối đa reentryConfirmBars (5 nến)Tại các nến sau nến tái nhập (bar_index > reentryBar), giá vẫn đóng cửa bên trong IB (closeStillInsideIB), có râu nến quay lại kiểm định biên IB trong phạm vi retestTolerance (high >= ibHigh - 0.70 cho Short, low <= ibLow + 0.70 cho Long) và kết thúc bằng nến đảo chiều hợp lệ.

(Lưu ý ở trạng thái 2 và -2: Nếu quá 5 nến xác nhận hoặc giá đóng cửa ngược ra ngoài biên IB vượt reentryBuffer, máy trạng thái sẽ hủy tín hiệu và reset về 0).

2.3. Tiêu chuẩn Nến đảo chiều và Bộ lọc Xu hướng cực đoan (Trend Guard)

Để tránh bắt đỉnh/đáy vào những thanh nến yếu hoặc chống lại một xu hướng một chiều quá mạnh (Trend Day), CNPS57 áp dụng 2 bộ lọc định lượng:

  1. Chất lượng nến đảo chiều (bearReversalCandle / bullReversalCandle):
    • Biên độ nến: candleRange = math.max(high - low, syminfo.mintick)
    • Tỷ lệ thân nến: bodyRatio = math.abs(close - open) / candleRange >= minimumBodyRatio (0.25)
    • Vị trí đóng cửa: closeLocation = (close - low) / candleRange
    • Nến đảo chiều giảm (bearReversalCandle): Nến đỏ (close < open), bodyRatio >= 0.25 và đóng cửa ở nửa dưới thanh nến (closeLocation <= 0.50).
    • Nến đảo chiều tăng (bullReversalCandle): Nến xanh (close > open), bodyRatio >= 0.25 và đóng cửa ở nửa trên thanh nến (closeLocation >= 0.50).
  2. Bộ lọc xu hướng ngược cực đoan (useTrendGuard = true):
    • Độ dốc đường EMA(55) trong 5 thanh nến chuẩn hóa theo ATR(14): $$\text{emaSlopeATR} = \frac{\text{trendEMA} - \text{trendEMA}[5]}{\text{ATR}(14)}$$
    • Chặn lệnh Short (dangerousShortTrend) khi: ADX(14) >= 36.0, emaSlopeATR >= 0.60, close > trendEMA và +DI > -DI.
    • Chặn lệnh Long (dangerousLongTrend) khi: ADX(14) >= 36.0, emaSlopeATR <= -0.60, close < trendEMA và -DI > +DI.

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

Quy trình vận hành của CNPS57 diễn ra tuần tự qua 5 bước trong mỗi phiên giao dịch VN30F1M:

  1. Bước 1 – Khởi tạo ngày mới và đo lường vùng IB (09:00 – 09:30): Khi bắt đầu ngày giao dịch mới (newTradingDay), bot xóa dữ liệu IB cũ, đặt lại bộ đếm lệnh tradesToday := 0 và ghi nhận mốc lợi nhuận đầu ngày startDayNetProfit. Trong 30 phút đầu phiên sáng, bot ghi nhận ibHigh, ibLow và kiểm tra điều kiện ibReady.
  2. Bước 2 – Theo dõi Đấu giá bên ngoài biên IB (State 0 → State 1 / -1): Sau khi ibReady = true, nếu giá đóng cửa vượt lên trên ibHigh + 0.40 hoặc thủng xuống dưới ibLow - 0.40, bot kích hoạt trạng thái theo dõi đấu giá bên ngoài, ghi nhận thời gian bắt đầu và liên tục cập nhật điểm cực trị breakoutExtreme. Nếu nhịp phá vỡ kéo dài quá 55 phút hoặc mở rộng quá 4.0 x ATR(14), bot coi đó là nhịp breakout thật sự và hủy trạng thái chờ đảo chiều.
  3. Bước 3 – Phát hiện Tái nhập (Reentry) và Xác nhận tín hiệu (rawLong / rawShort): Khi giá quay đầu đóng cửa vào bên trong vùng IB (cách biên tối thiểu 0.20 điểm), bot kiểm tra điều kiện nến đảo chiều ngay lập tức (nếu chọn Reentry Momentum) hoặc chuyển sang trạng thái 2 / -2 chờ tối đa 5 nến để xác nhận theo Follow-Through / Retest Failure.
  4. Bước 4 – Kiểm tra bộ lọc Rủi ro, Mục tiêu lợi nhuận và Phê duyệt lệnh (finalLong / finalShort): Khi có rawLong hoặc rawShort, bot tính toán mức Stop Loss cấu trúc dựa trên breakoutExtreme, kiểm tra khoảng cách SL (1.50 – 14.0 điểm), xác định Target theo chế độ targetMode, kiểm tra lợi nhuận gộp (>= 2.50 điểm), tỷ lệ R:R >= 1.05, bộ lọc Trend Guard và các điều kiện kiểm soát phiên (commonEntryOK). Nếu bị từ chối ở bước nào, bộ đếm chẩn đoán tương ứng (rejectedTrend, rejectedRisk, rejectedTarget, rejectedControls) sẽ tăng thêm 1.
  5. Bước 5 – Thực thi lệnh, Bảo vệ sau khớp lệnh và Đóng vị thế cuối phiên: Khi finalLong hoặc finalShort hợp lệ, bot gửi lệnh strategy.entry kèm lệnh chờ strategy.exit (SL/TP). Ngay khi lệnh được khớp ở thanh nến tiếp theo, bot kiểm tra rủi ro thực tế (validFill) để chống trượt giá qua SL/TP, theo dõi điều kiện dời SL về hòa vốn (Break Even), thoát lệnh sớm nếu tái nhập thất bại hoặc hết thời gian giữ lệnh, và đóng toàn bộ vị thế tại thanh nến 14:25 trước phiên ATC.

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

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

Lệnh Long (CNPS57-L - comment "FAILED IB LOWER AUCTION") được kích hoạt khi thỏa mãn đồng thời tất cả các điều kiện sau:

  1. Cho phép giao dịch chiều Long: tradeDirection != "Short" và nếu bật oneEntryPerSidePerDay thì biên dưới chưa được sử dụng trong ngày (not usedLowerAuction).
  2. Đấu giá biên dưới thất bại và xác nhận tái nhập (rawLong = true):
    • Giá đã có ít nhất 1 nến đóng cửa xác nhận dưới biên dưới IB: close <= ibLow - 0.40 (trạng thái -1).
    • Nhịp phá vỡ xuống chưa quá 55 phút và điểm thấp nhất breakoutExtreme không vượt quá ibLow - 4.0 * ATR(14).
    • Giá quay lại đóng cửa bên trong vùng IB: close > ibLow + 0.20 và close < ibHigh.
    • Thỏa mãn nến đảo chiều tăng (bullReversalCandle: close > open, bodyRatio >= 0.25, closeLocation >= 0.50) theo chế độ entryMode đã chọn (Reentry Momentum, Follow-Through, hoặc Retest Failure).
  3. Không vi phạm bộ lọc xu hướng giảm cực đoan (longQuality = not dangerousLongTrend): Không xảy ra tình trạng đồng thời ADX(14) >= 36.0, emaSlopeATR <= -0.60, close < EMA(55) và -DI > +DI.
  4. Hợp lệ về Stop Loss và Target (longTargetOK = true):
    • Khoảng cách rủi ro longRisk = close - longStopCandidate nằm trong đoạn [1.50, 14.0] điểm.
    • Khoảng cách lợi nhuận kỳ vọng longReward = longTarget - close >= 2.50 điểm.
    • Tỷ lệ longReward / longRisk >= 1.05.
  5. Thỏa mãn điều kiện kiểm soát giao dịch chung (commonEntryOK = true).

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

Lệnh Short (CNPS57-S - comment "FAILED IB UPPER AUCTION") được kích hoạt khi không có lệnh finalLong cùng thanh nến và thỏa mãn đồng thời các điều kiện sau:

  1. Cho phép giao dịch chiều Short: tradeDirection != "Long" và nếu bật oneEntryPerSidePerDay thì biên trên chưa được sử dụng trong ngày (not usedUpperAuction).
  2. Đấu giá biên trên thất bại và xác nhận tái nhập (rawShort = true):
    • Giá đã có ít nhất 1 nến đóng cửa xác nhận trên biên trên IB: close >= ibHigh + 0.40 (trạng thái 1).
    • Nhịp phá vỡ lên chưa quá 55 phút và điểm cao nhất breakoutExtreme không vượt quá ibHigh + 4.0 * ATR(14).
    • Giá quay lại đóng cửa bên trong vùng IB: close < ibHigh - 0.20 và close > ibLow.
    • Thỏa mãn nến đảo chiều giảm (bearReversalCandle: close < open, bodyRatio >= 0.25, closeLocation <= 0.50) theo chế độ entryMode đã chọn.
  3. Không vi phạm bộ lọc xu hướng tăng cực đoan (shortQuality = not dangerousShortTrend): Không xảy ra tình trạng đồng thời ADX(14) >= 36.0, emaSlopeATR >= 0.60, close > EMA(55) và +DI > -DI.
  4. Hợp lệ về Stop Loss và Target (shortTargetOK = true):
    • Khoảng cách rủi ro shortRisk = shortStopCandidate - close nằm trong đoạn [1.50, 14.0] điểm.
    • Khoảng cách lợi nhuận kỳ vọng shortReward = close - shortTarget >= 2.50 điểm.
    • Tỷ lệ shortReward / shortRisk >= 1.05.
  5. Thỏa mãn điều kiện kiểm soát giao dịch chung (commonEntryOK = true).

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

Mọi tín hiệu Long/Short chỉ được phép gửi lệnh khi biến commonEntryOK trả về true, bao gồm:

  • Trạng thái không có vị thế (flat): strategy.position_size == 0.
  • Vùng IB đã sẵn sàng (ibReady): Đã qua 09:30, có tối thiểu 3 thanh nến IB và độ rộng IB từ 5.0 đến 70.0 điểm.
  • Nằm trong khung giờ cho phép vào lệnh (entrySession):
    • Phiên sáng (morningEntry): 09:30 – 11:20 (từ Thứ Hai đến Thứ Sáu).
    • Phiên chiều (afternoonEntry): 13:05 – 14:10 (từ Thứ Hai đến Thứ Sáu).
  • Trước giờ đóng lệnh bắt buộc (beforeForceClose): Thời gian đóng nến closeMinute < 14:25 (865 phút).
  • Thời gian nghỉ sau khi thoát lệnh (cooldownOK): Đã qua ít nhất cooldownBars (3 thanh nến) kể từ thanh nến đóng lệnh gần nhất (bar_index - lastExitBar > 3).
  • Giới hạn số lệnh trong ngày (dailyLimitOK): tradesToday < maximumTradesPerDay (tối đa 3 lệnh/ngày).
  • Chốt chặn lỗ thực tế trong ngày (lossGuardOK): Khi bật useDailyLossGuard = true, tổng lợi nhuận đã chốt trong ngày closedPnLToday phải lớn hơn -3,000,000 VND (closedPnLToday > -maximumDailyLossVND).
  • Chống trùng lệnh trên cùng một thanh nến (onlyOneOrderThisBar) và thanh nến đã đóng cửa xác nhận (barstate.isconfirmed).

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

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

Điểm cắt lỗ ban đầu của CNPS57 được đặt hoàn toàn theo cấu trúc giá thực tế của nhịp đấu giá thất bại (breakoutExtreme) cộng thêm khoảng đệm stopBufferTicks (mặc định 2 ticks):

  • Stop Loss cho lệnh Long (longStopCandidate): $$\text{longStopCandidate} = \text{round_to_mintick}(\text{breakoutExtreme} - \text{stopBufferTicks} \times \text{syminfo.mintick})$$
  • Stop Loss cho lệnh Short (shortStopCandidate): $$\text{shortStopCandidate} = \text{round_to_mintick}(\text{breakoutExtreme} + \text{stopBufferTicks} \times \text{syminfo.mintick})$$

(Trong đó breakoutExtreme là mức giá thấp nhất của toàn bộ nhịp phá vỡ dưới đối với lệnh Long, hoặc mức giá cao nhất của toàn bộ nhịp phá vỡ trên đối với lệnh Short).

Bộ lọc khoảng cách Stop Loss (longRiskOK / shortRiskOK): Khoảng cách rủi ro tính từ giá đóng cửa nến tín hiệu đến Stop Loss (longRisk = close - longStopCandidate hoặc shortRisk = shortStopCandidate - close) bắt buộc phải nằm trong biên độ: $$\text{minimumStopPoints } (1.50) \le \text{Risk} \le \text{maximumStopPoints } (14.0)$$ Nếu SL quá ngắn (< 1.50 điểm) hoặc quá xa (> 14.0 điểm), tín hiệu sẽ bị từ chối và ghi nhận vào bộ đếm Reject Stop.

5.2. Cơ chế Take Profit, Break Even và Thoát lệnh sớm

Cách tính mục tiêu chốt lời (longTarget / shortTarget)

Bot cung cấp 4 chế độ xác định mục tiêu chốt lời qua tham số targetMode (với midpointTargetBuffer mặc định bằng 0.00 điểm):

  1. IB Midpoint / Fixed R (Mặc định):
    • Ưu tiên đặt TP tại điểm giữa vùng IB (ibMid - midpointTargetBuffer cho Long, ibMid + midpointTargetBuffer cho Short) nếu khoảng cách tới ibMid đạt lợi nhuận gộp tối thiểu >= 2.50 điểm (minimumGrossTarget) và tỷ lệ R:R >= 1.05 (minimumRewardRisk).
    • Nếu mục tiêu ibMid không đủ xa để đạt chuẩn R:R hoặc minimumGrossTarget, bot tự động chuyển sang mục tiêu theo bội số rủi ro cố định Fixed R (close + longRisk * 1.50 cho Long, close - shortRisk * 1.50 cho Short).
  2. IB Midpoint Only: Chỉ đặt TP tại vùng ibMid (nếu không đủ >= 2.50 điểm hoặc R:R < 1.05 thì từ chối vào lệnh).
  3. Fixed R Only: Luôn đặt TP cố định theo hệ số fixedTargetR (1.50R).
  4. Opposite IB Edge: Đặt TP tại biên đối diện của vùng IB (ibHigh - midpointTargetBuffer cho Long, ibLow + midpointTargetBuffer cho Short).

Mức activeTarget được khóa cố định tại thời điểm phát sinh tín hiệu (Frozen Profit Target) và giữ nguyên sau khi khớp lệnh.

Kiểm tra sau khớp lệnh (After-Fill Gap Protection) và Dời hòa vốn (Break Even)

Khi vị thế đang mở (strategy.position_size != 0), tại mỗi thanh nến đóng cửa:

  • Kiểm tra khớp lệnh hợp lệ (validFill): Bot tính rủi ro thực tế sau khi khớp lệnh originalFillRisk (dựa trên giá khớp trung bình fillPrice = strategy.position_avg_price và activeStop) cùng lợi nhuận thực tế còn lại actualReward (từ fillPrice tới activeTarget). Nếu do nhảy Gap đầu nến khiến originalFillRisk <= syminfo.mintick hoặc actualReward <= 0, bot lập tức đóng lệnh thị trường (INVALID GAP FILL).
  • Dời Stop Loss về hòa vốn (useBreakEven): Khi bật tùy chọn này, nếu lợi nhuận hiện tại tính theo giá đóng cửa đạt ngưỡng currentR >= breakEvenAtR (1.0R), bot sẽ nâng mức activeStop lên fillPrice + breakEvenOffset (+0.20 điểm cho lệnh Long) hoặc hạ xuống fillPrice - breakEvenOffset (-0.20 điểm cho lệnh Short) và chuyển trạng thái breakEvenActive := true.

Cơ chế thoát lệnh sớm tùy chọn (Optional Early Exits)

  • Thoát lệnh khi tái nhập IB thất bại (useFailedReentryExit): Khi đang giữ lệnh mà giá lại đóng cửa văng ra ngoài biên IB vượt quá reentryBuffer (close < ibLow - 0.20 khi đang Long, hoặc close > ibHigh + 0.20 khi đang Short) liên tiếp đủ failureCloses (2 nến), bot sẽ chủ động đóng lệnh (IB REENTRY FAILED).
  • Thoát lệnh theo thời gian nắm giữ tối đa (useTimeExit): Nếu thời gian giữ lệnh vượt quá maximumHoldMinutes (60 phút) tính từ entry_time(0), bot sẽ đóng vị thế (TIME EXIT).

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

Cơ chế bảo vệĐiều kiện kích hoạt trong codeHành động thực thiComment trên biểu đồ
Stop Loss cấu trúcGiá chạm activeStop (breakoutExtreme ± 2 ticks) khi breakEvenActive = falseĐóng vị thế qua strategy.exitSL Long / SL Short
Break Even StopuseBreakEven = true, sau khi currentR >= 1.0, giá quay lại chạm fillPrice ± 0.20Đóng vị thế hòa vốn qua strategy.exitBE Long / BE Short
Take Profit (TP)Giá chạm activeTarget (IB Midpoint, Fixed 1.50R hoặc Opposite IB Edge)Chốt lời vị thế qua strategy.exitTP Long / TP Short
Invalid Gap FillSau khi khớp lệnh, originalFillRisk <= syminfo.mintick hoặc actualReward <= 0strategy.close(..., immediately=true)INVALID GAP FILL
IB Reentry Failed ExituseFailedReentryExit = true và có 2 nến liên tiếp đóng cửa ngược ra ngoài biên IBstrategy.close(...)IB REENTRY FAILED
Time ExituseTimeExit = true và time_close >= entryTime + 60 phútstrategy.close(...)TIME EXIT
Force Close trước ATCThanh nến đóng cửa chạm hoặc vượt mốc 14:25 (forceCloseBar = true)strategy.close_all(immediately=true)FORCED FLAT BEFORE ATC

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 (khuyến nghị khung thời gian 3 phút hoặc 5 phút để đảm bảo trong 30 phút đầu phiên có từ 6 đến 10 thanh nến, đáp ứng điều kiện ibBars >= 3).
  2. Mở tab Pine Editor ở thanh công cụ phía dưới màn hình.
  3. Xóa đoạn mã mặc định trong trình soạn thảo, sao chép toàn bộ mã nguồn CNPS57 tại Mục 1 bài viết này và dán vào Pine Editor.
  4. Nhấn Save để lưu script và nhấn Add to chart (Thêm vào biểu đồ).
  5. Mở phần Settings (Cài đặt) của chiến lược để tùy chỉnh các tham số như Entry Confirmation Mode, Target Mode, hoặc bật thêm Use Break Even? và Exit If IB Reentry Fails? tùy theo khẩu vị rủi ro.

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

Khi bật tùy chọn Show Signal Funnel Diagnostics? (showDiagnostics = true), bot sẽ hiển thị một bảng thống kê phễu tín hiệu gồm 17 dòng ở góc trên bên phải biểu đồ (position.top_right):

Dòng hiển thịÝ nghĩa thông số thực tế trong code
CNPS57 V1Tên phiên bản chiến lược và khung thời gian hiện tại của biểu đồ (timeframe.period).
IB Ready / BarsTrạng thái vùng IB đã hợp lệ để giao dịch hay chưa (YES / NO) và số thanh nến đã thu thập trong cửa sổ IB (ibBars).
IB High / LowMức giá đỉnh cao nhất (ibHigh) và đáy thấp nhất (ibLow) của vùng Cân bằng đầu phiên hiện tại.
IB WidthĐộ rộng của vùng IB tính bằng điểm (ibHigh - ibLow).
StateTrạng thái hiện tại của máy trạng thái đấu giá (0: chờ breakout, 1/-1: đang đấu giá ngoài biên trên/dưới, 2/-2: đã tái nhập IB và đang chờ nến xác nhận).
Upper / Lower BOTổng số lần giá đóng cửa phá vỡ xác nhận ra ngoài biên trên (upperBreakouts) và biên dưới (lowerBreakouts).
Failed Upper / LowerTổng số lần nhịp đấu giá biên trên/biên dưới thất bại và đóng cửa tái nhập vào lại bên trong vùng IB (upperFailures / lowerFailures).
Reject TrendSố tín hiệu thô bị từ chối do vi phạm bộ lọc xu hướng ngược cực đoan (rejectedTrend).
Reject StopSố tín hiệu thô bị từ chối do khoảng cách SL nằm ngoài biên độ [1.50, 14.0] điểm (rejectedRisk).
Reject TargetSố tín hiệu thô bị từ chối do mục tiêu TP không đạt tối thiểu 2.50 điểm hoặc R:R < 1.05 (rejectedTarget).
Reject ControlSố tín hiệu thô bị từ chối bởi các bộ lọc kiểm soát phiên như ngoài khung giờ, đang giữ lệnh, dính cooldown, chạm giới hạn lệnh ngày hoặc chạm ngưỡng lỗ ngày (rejectedControls).
Long EntriesTổng số lệnh Long đã được thực thi trên dữ liệu lịch sử biểu đồ (longEntries).
Short EntriesTổng số lệnh Short đã được thực thi trên dữ liệu lịch sử biểu đồ (shortEntries).
Mid / Fixed / EdgePhân bổ số lệnh đã vào theo từng loại mục tiêu chốt lời: IB Midpoint / Fixed R / Opposite IB Edge.
Trades TodaySố lệnh đã vào trong ngày giao dịch hiện tại (tradesToday).
PnL Today (closed)Lợi nhuận ròng đã chốt trong ngày hiện tại (closedPnLToday, tính theo VND).
PositionTrạng thái vị thế hiện tại của bot: LONG, SHORT hoặc 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, Popup, Email hoặc kết nối Webhook khi CNPS57 phát sinh lệnh, bạn thực hiện theo các bước sau:

  1. Nhấn vào biểu tượng Alert (Cảnh báo) trên thanh công cụ bên phải của TradingView (hoặc tổ hợp phím Alt + A).
  2. Tại mục Condition (Điều kiện): Chọn chiến lược CNPS57 FAILED INITIAL BALANCE AUCTION V1 - VN30F1M.
  3. Tại mục Order fills only: Chọn chế độ nhận cảnh báo khi lệnh của chiến lược được kích hoạt.
  4. Tại mục Message (Nội dung tin nhắn): Xóa nội dung mặc định và nhập chính xác biến động của TradingView:
    {{strategy.order.alert_message}}
  5. Nhấn Create (Tạo) để hoàn tất.

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

Khi sử dụng cú pháp {{strategy.order.alert_message}}, bot sẽ tự động xuất ra các thông điệp tiếng Việt chi tiết đã được lập trình sẵn trong code cho từng sự kiện:

Sự kiện giao dịchMã lệnh / Hàm gọiNội dung thông điệp (alert_message / alert_profit / alert_loss)
Mở vị thế Longstrategy.entry("CNPS57-L")🟢 VÀO VỊ THẾ LONG (CNPS57)
🎯 Giá vào: <close>
🛑 Cắt lỗ (SL): <activeStop>
🎯 Chốt lời (TP): <activeTarget>
Mở vị thế Shortstrategy.entry("CNPS57-S")🔴 VÀO VỊ THẾ SHORT (CNPS57)
🎯 Giá vào: <close>
🛑 Cắt lỗ (SL): <activeStop>
🎯 Chốt lời (TP): <activeTarget>
Chốt lời lệnh Long (TP)strategy.exit("CNPS57-L-X")💰 CHỐT LỜI LONG (TP HIT)
🎯 Giá chốt lời: <activeTarget>
Chốt lời lệnh Short (TP)strategy.exit("CNPS57-S-X")💰 CHỐT LỜI SHORT (TP HIT)
🎯 Giá chốt lời: <activeTarget>
Cắt lỗ lệnh Long (SL)strategy.exit("CNPS57-L-X")🛑 CẮT LỖ LONG (SL HIT)
Giá cắt lỗ: <activeStop>
Cắt lỗ lệnh Short (SL)strategy.exit("CNPS57-S-X")🛑 CẮT LỖ SHORT (SL HIT)
Giá cắt lỗ: <activeStop>
Dừng lệnh Hòa vốn Long (BE)strategy.exit("CNPS57-L-X")🛡️ HÒA VỐN LONG (BE HIT)
Giá hòa vốn: <activeStop>
Dừng lệnh Hòa vốn Short (BE)strategy.exit("CNPS57-S-X")🛡️ HÒA VỐN SHORT (BE HIT)
Giá hòa vốn: <activeStop>
Đóng lệnh do trượt Gap không hợp lệstrategy.close(...)⚠️ ĐÓNG VỊ THẾ DO GAP/RỦI RO KHÔNG HỢP LỆ (Invalid Gap)
Đóng lệnh do tái nhập IB thất bạistrategy.close(...)⚡ ĐÓNG VỊ THẾ DO TÁI NHẬP IB THẤT BẠI (Reentry Failed)
Đóng lệnh do hết thời gian giữ lệnhstrategy.close(...)⏱️ ĐÓNG VỊ THẾ HẾT THỜI GIAN GIỮ LỆNH (Time Exit)
Đóng toàn bộ vị thế cuối phiên (14:25)strategy.close_all(...)⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End)

Kết luận

CNPS57 Failed Initial Balance Auction V1 là một hệ thống giao dịch đảo chiều về vùng cân bằng (Mean Reversion / Failed Auction) có cấu trúc chặt chẽ và minh bạch dành cho VN30F1M. Điểm mạnh lớn nhất của hệ thống nằm ở máy trạng thái 5 bước giúp loại bỏ hoàn toàn các tín hiệu nhiễu chưa có đóng cửa xác nhận bên ngoài biên IB, kết hợp với bộ lọc xu hướng cực đoan (Trend Guard), cơ chế chọn mục tiêu thông minh giữa IB Midpoint và Fixed R, cùng bảng chẩn đoán phễu tín hiệu (Signal Funnel Diagnostics) giúp nhà đầu tư theo dõi chính xác lý do từng tín hiệu được chấp nhận hay từ chối.

Chiến lược này phát huy hiệu quả tối ưu trong các phiên thị trường đi ngang biên độ rộng (Rotational / Balance Day) hoặc các phiên bẫy thanh khoản hai đầu vùng cân bằng buổi sáng trước khi quay về điểm cân bằng IB Midpoint. Để đa dạng hóa danh mục hệ thống giao dịch tự động cho cả những phiên có xu hướng mạnh, bạn có thể tham khảo thêm 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