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

Hướng Dẫn Sử Dụng Bot CNPS62 - Lunch Reopen Reset V1.1 cho VN30F1M

Bot CNPS62 Lunch Reopen Reset V1.1 giao dịch phiên chiều VN30F1M (13:05–14:15) dựa trên vùng giá tái mở cửa sau nghỉ trưa, hỗ trợ cả Tiếp diễn phá vỡ (Acceptance Continuation) và Đảo chiều phá vỡ giả (Failed Breakout Reversal).

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

Khi giao dịch hợp đồng tương lai VN30F1M, giai đoạn mở cửa lại phiên chiều (13:00) sau giờ nghỉ trưa thường xuất hiện những nhịp rung lắc mạnh, quét thanh khoản hai đầu hoặc bứt phá theo xu hướng mới mà nhiều trader rất khó nắm bắt. Nếu vào lệnh quá sớm ngay khi mở cửa chiều, nhà đầu tư dễ dính bẫy phá vỡ giả (fakeout); ngược lại, nếu chờ quá lâu thì bỏ lỡ điểm vào có tỷ lệ Risk:Reward tốt trước khi bước vào phiên ATC.

Chiến lược CNPS62 LUNCH REOPEN RESET V1.1 - VN30F1M (viết bằng Pine Script v6 trên TradingView) được thiết kế chuyên biệt để giải quyết bài toán này. Bot chỉ tập trung quan sát cấu trúc giá cuối phiên sáng và vùng giá tái mở cửa đầu phiên chiều, từ đó tự động phân loại trạng thái thị trường để giao dịch theo hai kịch bản: Tiếp diễn chấp nhận giá (Acceptance Continuation) hoặc Đảo chiều phá vỡ giả (Failed Breakout Reversal).

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

  • Chuyên biệt cho phiên chiều (13:05–14:15): Tự động đo lường biên độ tham chiếu cuối phiên sáng và vùng Reset đầu phiên chiều bằng các nến đã đóng hoàn chỉnh (tránh lỗi khung thời gian lớn).
  • Linh hoạt 2 cơ chế vào lệnh: Hỗ trợ vào lệnh trực tiếp khi nến phá vỡ thân lớn, vào lệnh khi giá retest vùng Reset thành công, hoặc đánh đảo chiều khi cú phá vỡ thất bại và giá chui ngược lại vào vùng Reset.
  • Quản trị rủi ro chặt chẽ: Giới hạn khoảng cách Stop Loss từ 1.5 đến 14.0 điểm, kiểm tra mục tiêu lợi nhuận gộp tối thiểu 2.5 điểm, tự động thoát sớm khi phá vỡ thất bại hoặc hết thời gian giữ lệnh (40 phút).
  • Bảo vệ tài khoản đa tầng: Khóa giao dịch khi lỗ đã chốt trong ngày vượt 2.400.000 VNĐ, giới hạn tối đa 3 lệnh/buổi chiều và tự động đóng toàn bộ vị thế trước ATC lúc 14:25.

1. CNPS62 Lunch Reopen Reset V1.1 là gì?

CNPS62 là hệ thống giao dịch tự động theo phiên (Intraday Session Strategy) hoạt động dựa trên 4 trụ cột kỹ thuật chính:

  1. Cấu trúc tham chiếu cuối phiên sáng (Morning Reference Window): Xác định biên độ cao/thấp và hướng dịch chuyển trong những phút cuối phiên sáng (trước 11:30) để làm bộ lọc bối cảnh cho phiên chiều.
  2. Vùng Reset tái mở cửa phiên chiều (Afternoon Opening Reset Range): Đo vùng tích lũy/giằng co trong những phút đầu tiên sau giờ nghỉ trưa (từ 13:00) để làm mốc phá vỡ (Breakout) hoặc phá vỡ giả (Fakeout).
  3. Bộ máy trạng thái phá vỡ & xác nhận (Breakout / Failed Auction State Machine): Theo dõi hành vi giá sau khi vượt biên resetHigh hoặc resetLow trong tối đa 8 nến để quyết định tiếp diễn xu hướng hay đảo chiều.
  4. Hệ thống bảo vệ vị thế & quản trị phiên (Risk & Exit Engine): Kết hợp Stop Loss cấu trúc theo ATR(14), chốt lời cố định 1.6R, thoát lệnh sớm khi mất vùng chấp nhận giá và đóng toàn bộ vị thế lúc 14:25.

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

Nhóm thông sốTên tham số trong codeGiá trị mặc địnhÝ nghĩa thực tế
01 - Trade ControltradeDirection"Both"Chiều giao dịch cho phép (Both, Long, Short)
contracts3Tham số số hợp đồng khai báo (lưu ý hàm strategy() dùng default_qty_value=1)
maximumTradesPerDay3Số lệnh tối đa trong buổi chiều
cooldownBars3Số nến nghỉ bắt buộc sau khi đóng lệnh
02 - Morning ReferencemorningReferenceMinutes15Số phút cuối phiên sáng để lấy vùng tham chiếu (10, 15, 20, 30)
minimumMorningWidth / maximumMorningWidth1.5 / 35.0Biên độ tối thiểu / tối đa của vùng sáng (điểm)
03 - Reopen RangeafternoonOpeningMinutes5Số phút quan sát đầu phiên chiều (5, 10, 15)
minimumResetWidth / maximumResetWidthATR1.0 / 6.0Biên độ Reset tối thiểu (1.0 điểm) và tối đa (6.0 × ATR14)
04 - EntryentryMode"Both"Chế độ vào lệnh (Both, Acceptance Continuation, Failed Breakout Reversal)
minimumBreakPoints / reclaimBuffer0.3 / 0.2Điểm phá vỡ tối thiểu / biên độ chui ngược xác nhận phá vỡ giả
maximumSetupBars8Số nến tối đa chờ xác nhận sau khi có cú phá vỡ
minimumCandleBody0.25Tỷ lệ thân nến / biên độ nến tối thiểu
requireMorningAlignmentfalseYêu cầu lệnh Continuation cùng hướng phiên sáng
05 - ValidationretestTouchATR / maximumPierceATR0.55 / 0.65Biên độ chạm lại và độ xuyên thủng tối đa khi retest (× ATR14)
allowDirectBreakout / minimumBreakoutBodytrue / 0.55Cho phép vào thẳng nếu nến phá vỡ có thân ≥ 55% biên độ
06 - FiltersuseVWAPFilter / useTrendFilter / useVolumeFilterfalse / false / falseBộ lọc tùy chọn theo Session VWAP, EMA 34 và Volume SMA(20)
07 - RiskstopMode"Setup Extreme"Chế độ đặt SL (Setup Extreme, Reset Range Opposite, ATR Fixed)
stopBufferATR / fixedStopATR0.15 / 1.5Khoảng đệm SL (0.15 × ATR14) hoặc SL cố định (1.5 × ATR14)
minimumStopPoints / maximumStopPoints1.5 / 14.0Giới hạn khoảng cách SL hợp lệ (điểm)
takeProfitR / minimumGrossTarget1.6 / 2.5Tỷ lệ TP (1.6R) và mục tiêu gộp tối thiểu (2.5 điểm)
08 - ExitsuseBreakEven / breakEvenTriggerR / breakEvenOffsetfalse / 1.0 / 0.2Dời hòa vốn khi đạt 1.0R cộng thêm 0.2 điểm
useFailedAcceptanceExit / failureCloseBarstrue / 2Thoát sớm nếu giá đóng cửa thất bại 2 nến liên tiếp
useTimeExit / maximumHoldMinutestrue / 40Tự động đóng lệnh nếu giữ quá 40 phút
09 - ProtectionuseDailyLossGuard / maximumDailyLossVNDtrue / 2400000Dừng giao dịch trong ngày nếu lỗ đã chốt vượt 2.400.000 VNĐ
10 - SessionafternoonEntry / forceFlatHour:Minute"1305-1415" / 14:25Khung giờ vào lệnh chiều và giờ đóng toàn bộ trước ATC

Source Code CNPS62 Lunch Reopen Reset V1.1

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
// CNPS62 - Lunch Reopen Reset V1.1 - VN30F1M
// Fixed Pine v6 margin and timeframe-dependent observation windows.
// Margin 12% is a backtest assumption, not actual broker margin.
strategy(title="CNPS62 LUNCH REOPEN RESET V1.1 - VN30F1M", shorttitle="CNPS62 LUNCH V1.1", overlay=true, initial_capital=100000000, currency=currency.VND, default_qty_type=strategy.fixed, default_qty_value=1, pyramiding=0, margin_long=12, margin_short=12, slippage=0, commission_type=strategy.commission.cash_per_contract, commission_value=0, process_orders_on_close=false, calc_on_order_fills=false, calc_on_every_tick=false, fill_orders_on_standard_ohlc=true, max_bars_back=5000, max_labels_count=100)

// ============================================================================
// SECTION 1: TRADE CONTROL
// ============================================================================
tradeDirection = input.string("Both", title="Trade Direction", options=["Both", "Long", "Short"], group="01 - Trade Control")
contracts = input.int(3, title="Contracts Per Trade", minval=1, maxval=20, group="01 - Trade Control")
maximumTradesPerDay = input.int(3, title="Maximum Afternoon Trades", minval=1, maxval=10, group="01 - Trade Control")
cooldownBars = input.int(3, title="Cooldown After Exit (bars)", minval=0, maxval=50, group="01 - Trade Control")

// ============================================================================
// SECTION 2: MORNING REFERENCE WINDOW
// ============================================================================
morningReferenceMinutes = input.int(15, title="Last Morning Minutes Used For Reference", options=[10, 15, 20, 30], group="02 - Morning Reference")
minimumMorningWidth = input.float(1.5, title="Minimum Morning Reference Width (points)", minval=0.0, step=0.5, group="02 - Morning Reference")
maximumMorningWidth = input.float(35.0, title="Maximum Morning Reference Width (points)", minval=2.0, step=0.5, group="02 - Morning Reference")

// ============================================================================
// SECTION 3: AFTERNOON OPENING RESET
// ============================================================================
afternoonOpeningMinutes = input.int(5, title="Afternoon Opening Observation (minutes)", options=[5, 10, 15], group="03 - Reopen Range")
minimumResetWidth = input.float(1.0, title="Minimum Reset Range Width (points)", minval=0.0, step=0.5, group="03 - Reopen Range")
maximumResetWidthATR = input.float(6.0, title="Maximum Reset Range Width x ATR14", minval=1.0, maxval=20.0, step=0.5, group="03 - Reopen Range")

// ============================================================================
// SECTION 4: ENTRY MECHANISM
// ============================================================================
entryMode = input.string("Both", title="Setup Type", options=["Both", "Acceptance Continuation", "Failed Breakout Reversal"], group="04 - Entry")
minimumBreakPoints = input.float(0.3, title="Required Close Beyond Reset Range (points)", minval=0.0, step=0.1, group="04 - Entry")
reclaimBuffer = input.float(0.2, title="Required Reclaim Into Reset Range (points)", minval=0.0, step=0.1, group="04 - Entry")
maximumSetupBars = input.int(8, title="Maximum Bars To Confirm Setup", minval=1, maxval=30, group="04 - Entry")
minimumCandleBody = input.float(0.25, title="Minimum Entry Candle Body / Range", minval=0.0, maxval=1.0, step=0.05, group="04 - Entry")
requireMorningAlignment = input.bool(false, title="Continuation Must Agree With Morning Direction?", group="04 - Entry")

// ============================================================================
// SECTION 5: RETEST / FAILURE VALIDATION
// ============================================================================
retestTouchATR = input.float(0.55, title="Retest Touch Tolerance x ATR14", minval=0.05, maxval=3.0, step=0.05, group="05 - Validation")
maximumPierceATR = input.float(0.65, title="Maximum Retest Pierce x ATR14", minval=0.05, maxval=3.0, step=0.05, group="05 - Validation")
allowDirectBreakout = input.bool(true, title="Allow Direct Strong Breakout Entry?", group="05 - Validation")
minimumBreakoutBody = input.float(0.55, title="Direct Breakout Body / Range", minval=0.1, maxval=1.0, step=0.05, group="05 - Validation")

// ============================================================================
// SECTION 6: OPTIONAL CONTEXT FILTERS
// ============================================================================
useVWAPFilter = input.bool(false, title="Require VWAP Alignment?", group="06 - Filters")
useTrendFilter = input.bool(false, title="Require EMA Trend Alignment?", group="06 - Filters")
trendEMALength = input.int(34, title="Trend EMA Length", minval=5, maxval=200, group="06 - Filters")
useVolumeFilter = input.bool(false, title="Require Entry Volume Expansion?", group="06 - Filters")
volumePeriod = input.int(20, title="Volume Baseline", minval=5, maxval=100, group="06 - Filters")
minimumVolumeRatio = input.float(0.9, title="Minimum Relative Volume", minval=0.1, maxval=5.0, step=0.05, group="06 - Filters")

// ============================================================================
// SECTION 7: RISK MANAGEMENT
// ============================================================================
stopMode = input.string("Setup Extreme", title="Stop Location", options=["Setup Extreme", "Reset Range Opposite", "ATR Fixed"], group="07 - Risk")
stopBufferATR = input.float(0.15, title="Stop Buffer x ATR14", minval=0.0, maxval=2.0, step=0.05, group="07 - Risk")
fixedStopATR = input.float(1.5, title="Fixed ATR Stop Multiple", minval=0.25, maxval=6.0, step=0.1, group="07 - Risk")
minimumStopPoints = input.float(1.5, title="Minimum Stop Distance (points)", minval=0.1, step=0.5, group="07 - Risk")
maximumStopPoints = input.float(14.0, title="Maximum Stop Distance (points)", minval=0.5, step=0.5, group="07 - Risk")
takeProfitR = input.float(1.6, title="Take Profit Multiple (R)", minval=0.25, maxval=6.0, step=0.1, group="07 - Risk")
minimumGrossTarget = input.float(2.5, title="Minimum Gross Target (points)", minval=0.0, step=0.5, group="07 - Risk")

// ============================================================================
// SECTION 8: EXIT MANAGEMENT
// ============================================================================
useBreakEven = input.bool(false, title="Enable Break Even?", group="08 - Exits")
breakEvenTriggerR = input.float(1.0, title="Break Even Trigger (R)", minval=0.25, maxval=5.0, step=0.25, group="08 - Exits")
breakEvenOffset = input.float(0.2, title="Break Even Offset (points)", minval=0.0, step=0.1, group="08 - Exits")
useFailedAcceptanceExit = input.bool(true, title="Exit When Reset-Range Acceptance Fails?", group="08 - Exits")
failureCloseBars = input.int(2, title="Consecutive Failed Closes", minval=1, maxval=5, group="08 - Exits")
useTimeExit = input.bool(true, title="Enable Maximum Hold Time?", group="08 - Exits")
maximumHoldMinutes = input.int(40, title="Maximum Hold (minutes)", minval=5, maxval=120, group="08 - Exits")

// ============================================================================
// SECTION 9: DAILY RISK PROTECTION
// ============================================================================
useDailyLossGuard = input.bool(true, title="Block New Trades After Daily Closed Loss?", group="09 - Protection")
maximumDailyLossVND = input.float(2400000, title="Daily Closed Loss Threshold (VND)", minval=100000, step=100000, group="09 - Protection")

// ============================================================================
// SECTION 10: VIETNAM SESSION
// ============================================================================
string timezoneVN = "Asia/Ho_Chi_Minh"
afternoonEntry = input.session("1305-1415", title="Afternoon Entry Session", group="10 - Session")
forceFlatHour = input.int(14, title="Force Flat Hour", minval=0, maxval=23, group="10 - Session")
forceFlatMinute = input.int(25, title="Force Flat Minute", minval=0, maxval=59, group="10 - Session")

// ============================================================================
// SECTION 11: CLEAN DISPLAY
// ============================================================================
showMorningReference = input.bool(false, title="Show Morning Reference High / Low?", group="11 - Display")
showResetRange = input.bool(true, title="Show Afternoon Reset Range?", group="11 - Display")
showVWAP = input.bool(false, title="Show Session VWAP?", group="11 - Display")
showEntries = input.bool(true, title="Show Long / Short Signals?", group="11 - Display")
showTradeLevels = input.bool(true, title="Show Active Stop / Target?", group="11 - Display")

// ============================================================================
// SECTION 12: TIME ENGINE
// ============================================================================
int minuteOpen = (hour(time, timezoneVN) * 60 + minute(time, timezoneVN))
int minuteClose = (hour(time_close, timezoneVN) * 60 + minute(time_close, timezoneVN))

// Use complete chart bars for morning and afternoon observations.
// This avoids an empty 5-minute reset on a 15-minute chart.
int chartMinutes = math.max(1, int(math.ceil(timeframe.in_seconds() / 60.0)))
int effectiveMorningMinutes = (int(math.ceil(morningReferenceMinutes * 1.0 / chartMinutes)) * chartMinutes)
int effectiveAfternoonMinutes = (int(math.ceil(afternoonOpeningMinutes * 1.0 / chartMinutes)) * chartMinutes)
int morningReferenceStart = (690 - effectiveMorningMinutes)
int resetEnd = (780 + effectiveAfternoonMinutes)
int cutoffMinute = (forceFlatHour * 60 + forceFlatMinute)
bool morningContinuous = (minuteOpen >= 540 and minuteOpen < 690)
bool afternoonContinuous = (minuteOpen >= 780 and minuteOpen < 870)
bool continuousSession = (morningContinuous or afternoonContinuous)
bool morningReferenceBar = (morningContinuous and minuteOpen >= morningReferenceStart and minuteClose <= 690)
bool afternoonObservationBar = (afternoonContinuous and minuteOpen < resetEnd and minuteClose <= resetEnd)
bool resetObservationCompleted = (minuteOpen >= resetEnd and afternoonContinuous)
bool afternoonEntryBar = not na(time(timeframe.period, afternoonEntry + ":23456", timezoneVN))
int dayKey = (year(time, timezoneVN) * 10000 + month(time, timezoneVN) * 100 + dayofmonth(time, timezoneVN))
bool newTradingDay = (bar_index == 0 or dayKey != nz(dayKey[1], dayKey))
bool beforeCutoff = (not na(time_close) and minuteClose < cutoffMinute)
bool forceFlatBar = (barstate.isconfirmed and afternoonContinuous and minuteOpen < cutoffMinute and minuteClose >= cutoffMinute)

// ============================================================================
// SECTION 13: MORNING REFERENCE STRUCTURE
// ============================================================================
var float morningHigh = na
var float morningLow = na
var float morningFirstClose = na
var float morningLastClose = na
var int morningBars = 0
if newTradingDay
    morningHigh := na
    morningLow := na
    morningFirstClose := na
    morningLastClose := na
    morningBars := 0
if morningReferenceBar and barstate.isconfirmed
    morningHigh := math.max(nz(morningHigh, high), high)
    morningLow := math.min(nz(morningLow, low), low)
    morningFirstClose := (morningBars == 0 ? close : morningFirstClose)
    morningLastClose := close
    morningBars += 1
float morningWidth = (morningHigh - morningLow)
bool morningReady = (morningBars >= 1 and not na(morningWidth) and morningWidth >= minimumMorningWidth and morningWidth <= maximumMorningWidth)
bool morningBull = (not na(morningFirstClose) and morningLastClose > morningFirstClose)
bool morningBear = (not na(morningFirstClose) and morningLastClose < morningFirstClose)

// ============================================================================
// SECTION 14: AFTERNOON OPENING RESET RANGE
// ============================================================================
var float resetHigh = na
var float resetLow = na
var int resetBars = 0
if newTradingDay
    resetHigh := na
    resetLow := na
    resetBars := 0
if afternoonObservationBar and barstate.isconfirmed
    resetHigh := math.max(nz(resetHigh, high), high)
    resetLow := math.min(nz(resetLow, low), low)
    resetBars += 1
float resetWidth = (resetHigh - resetLow)
float atr = ta.atr(14)
bool resetReady = (morningReady and resetObservationCompleted and resetBars >= 1 and not na(atr) and atr > 0 and resetWidth >= minimumResetWidth and resetWidth <= maximumResetWidthATR * atr)

// ============================================================================
// SECTION 15: CANDLE / TREND / VOLUME CONTEXT
// ============================================================================
float candleRange = math.max(high - low, syminfo.mintick)
float candleBody = (math.abs(close - open) / candleRange)
float closeLocation = ((close - low) / candleRange)
float trendEMA = ta.ema(close, trendEMALength)
float averageVolumePrior = ta.sma(volume, volumePeriod)[1]
bool bullishCandle = (close > open and candleBody >= minimumCandleBody and closeLocation >= 0.55)
bool bearishCandle = (close < open and candleBody >= minimumCandleBody and closeLocation <= 0.45)
bool volumeOK = (not useVolumeFilter or (not na(averageVolumePrior) and averageVolumePrior > 0 and volume >= averageVolumePrior * minimumVolumeRatio))
bool trendLongOK = (not useTrendFilter or close > trendEMA)
bool trendShortOK = (not useTrendFilter or close < trendEMA)

// ============================================================================
// SECTION 16: SESSION VWAP
// ============================================================================
var float cumulativePV = 0.0
var float cumulativeVolume = 0.0
if newTradingDay
    cumulativePV := 0.0
    cumulativeVolume := 0.0
if (continuousSession and barstate.isconfirmed and not na(volume) and volume > 0)
    cumulativePV += hlc3 * volume
    cumulativeVolume += volume
float sessionVWAP = (cumulativeVolume > 0 ? cumulativePV / cumulativeVolume : na)
bool vwapLongOK = (not useVWAPFilter or (not na(sessionVWAP) and close > sessionVWAP))
bool vwapShortOK = (not useVWAPFilter or (not na(sessionVWAP) and close < sessionVWAP))

// ============================================================================
// SECTION 17: DAILY TRADE CONTROL
// ============================================================================
var int tradesToday = 0
var int seenClosedTrades = 0
var int lastExitBar = na
var int lastEntrySignalBar = na
var float dayStartNetProfit = na
if newTradingDay
    tradesToday := 0
    dayStartNetProfit := strategy.netprofit
if strategy.closedtrades > seenClosedTrades
    seenClosedTrades := strategy.closedtrades
    lastExitBar := bar_index
bool flat = strategy.position_size == 0
bool inLong = strategy.position_size > 0
bool inShort = strategy.position_size < 0
bool allowLong = tradeDirection != "Short"
bool allowShort = tradeDirection != "Long"
float dailyClosedPnL = (strategy.netprofit - nz(dayStartNetProfit, strategy.netprofit))
bool tradeCountOK = (tradesToday < maximumTradesPerDay)
bool cooldownOK = (na(lastExitBar) or bar_index - lastExitBar > cooldownBars)
bool lossGuardOK = (not useDailyLossGuard or dailyClosedPnL > -maximumDailyLossVND)
bool oneOrderPerBar = (na(lastEntrySignalBar) or bar_index != lastEntrySignalBar)
bool commonEntryOK = (flat and resetReady and afternoonEntryBar and beforeCutoff and tradeCountOK and cooldownOK and lossGuardOK and oneOrderPerBar and volumeOK and barstate.isconfirmed)

// ============================================================================
// SECTION 18: BREAKOUT / FAILED AUCTION STATE
// ============================================================================
var int setupState = 0
var int breakoutBar = na
var float breakoutHigh = na
var float breakoutLow = na
var float breakoutReference = na
bool rawLong = false
bool rawShort = false
bool rawLongContinuation = false
bool rawShortContinuation = false
float candidateStopAnchor = na
float tradeFailureLevel = na
int tradeSetupType = 0
if newTradingDay
    setupState := 0
    breakoutBar := na
    breakoutHigh := na
    breakoutLow := na

// ============================================================================
// SECTION 19: PROCESS EXISTING UPSIDE BREAKOUT
// ============================================================================
if (setupState == 1 and barstate.isconfirmed and bar_index > breakoutBar)
    bool expired = (bar_index - breakoutBar > maximumSetupBars)
    bool failed = (close < resetHigh - reclaimBuffer)
    if (expired or not afternoonEntryBar or not beforeCutoff)
        setupState := 0
    else if failed
        if (entryMode != "Acceptance Continuation" and bearishCandle)
            rawShort := true
            candidateStopAnchor := math.max(breakoutHigh, high)
            tradeFailureLevel := resetHigh
            tradeSetupType := -1
        setupState := 0
    else
        bool touched = (low <= resetHigh + atr * retestTouchATR and low >= resetHigh - atr * maximumPierceATR)
        bool held = (close >= resetHigh + minimumBreakPoints and bullishCandle)
        if (entryMode != "Failed Breakout Reversal" and touched and held)
            rawLong := true
            rawLongContinuation := true
            candidateStopAnchor := math.min(low, resetHigh)
            tradeFailureLevel := resetHigh
            tradeSetupType := 1
            setupState := 0

// ============================================================================
// SECTION 20: PROCESS EXISTING DOWNSIDE BREAKOUT
// ============================================================================
if (setupState == -1 and barstate.isconfirmed and bar_index > breakoutBar)
    bool expired = (bar_index - breakoutBar > maximumSetupBars)
    bool failed = (close > resetLow + reclaimBuffer)
    if (expired or not afternoonEntryBar or not beforeCutoff)
        setupState := 0
    else if failed
        if (entryMode != "Acceptance Continuation" and bullishCandle)
            rawLong := true
            candidateStopAnchor := math.min(breakoutLow, low)
            tradeFailureLevel := resetLow
            tradeSetupType := -1
        setupState := 0
    else
        bool touched = (high >= resetLow - atr * retestTouchATR and high <= resetLow + atr * maximumPierceATR)
        bool held = (close <= resetLow - minimumBreakPoints and bearishCandle)
        if (entryMode != "Failed Breakout Reversal" and touched and held)
            rawShort := true
            rawShortContinuation := true
            candidateStopAnchor := math.max(high, resetLow)
            tradeFailureLevel := resetLow
            tradeSetupType := 1
            setupState := 0

// ============================================================================
// SECTION 21: DETECT FRESH RESET-RANGE BREAKOUT
// ============================================================================
bool freshUpsideBreak = (resetReady and close > resetHigh + minimumBreakPoints and close[1] <= resetHigh + minimumBreakPoints and bullishCandle)
bool freshDownsideBreak = (resetReady and close < resetLow - minimumBreakPoints and close[1] >= resetLow - minimumBreakPoints and bearishCandle)
if (setupState == 0 and not rawLong and not rawShort and commonEntryOK)
    if freshUpsideBreak
        breakoutBar := bar_index
        breakoutHigh := high
        breakoutLow := low
        breakoutReference := resetHigh
        setupState := 1
        if (allowDirectBreakout and candleBody >= minimumBreakoutBody and entryMode != "Failed Breakout Reversal")
            rawLong := true
            rawLongContinuation := true
            candidateStopAnchor := math.min(low, resetHigh)
            tradeFailureLevel := resetHigh
            tradeSetupType := 1
            setupState := 0
    else if freshDownsideBreak
        breakoutBar := bar_index
        breakoutHigh := high
        breakoutLow := low
        breakoutReference := resetLow
        setupState := -1
        if (allowDirectBreakout and candleBody >= minimumBreakoutBody and entryMode != "Failed Breakout Reversal")
            rawShort := true
            rawShortContinuation := true
            candidateStopAnchor := math.max(high, resetLow)
            tradeFailureLevel := resetLow
            tradeSetupType := 1
            setupState := 0

// ============================================================================
// SECTION 22: ENTRY QUALITY / STRUCTURAL RISK
// ============================================================================
float longAnchor = (stopMode == "Reset Range Opposite" ? resetLow : candidateStopAnchor)
float shortAnchor = (stopMode == "Reset Range Opposite" ? resetHigh : candidateStopAnchor)
float candidateLongStop = (not na(atr) and atr > 0 ? math.round_to_mintick(stopMode == "ATR Fixed" ? close - atr * fixedStopATR : longAnchor - atr * stopBufferATR) : na)
float candidateShortStop = (not na(atr) and atr > 0 ? math.round_to_mintick(stopMode == "ATR Fixed" ? close + atr * fixedStopATR : shortAnchor + atr * stopBufferATR) : na)
float longRisk = (close - candidateLongStop)
float shortRisk = (candidateShortStop - close)
bool longRiskOK = (not na(longRisk) and longRisk >= minimumStopPoints and longRisk <= maximumStopPoints and longRisk * takeProfitR >= minimumGrossTarget)
bool shortRiskOK = (not na(shortRisk) and shortRisk >= minimumStopPoints and shortRisk <= maximumStopPoints and shortRisk * takeProfitR >= minimumGrossTarget)
bool longMorningOK = (not requireMorningAlignment or not rawLongContinuation or morningBull)
bool shortMorningOK = (not requireMorningAlignment or not rawShortContinuation or morningBear)
bool finalLong = (rawLong and allowLong and longMorningOK and trendLongOK and vwapLongOK and longRiskOK and commonEntryOK)
bool finalShort = (rawShort and allowShort and shortMorningOK and trendShortOK and vwapShortOK and shortRiskOK and commonEntryOK and not finalLong)
float candidateLongTarget = (not na(longRisk) ? math.round_to_mintick(close + longRisk * takeProfitR) : na)
float candidateShortTarget = (not na(shortRisk) ? math.round_to_mintick(close - shortRisk * takeProfitR) : na)

// ============================================================================
// SECTION 23: ACTIVE TRADE STATE
// ============================================================================
var float activeStop = na
var float activeTarget = na
var float activeFill = na
var float initialFillRisk = na
var float activeFailureLevel = na
var int activeSetupType = 0
var int entryBarSeen = na
var int failureCount = 0
var bool breakEvenActive = false

// ============================================================================
// SECTION 24: LONG ENTRY
// ============================================================================
if finalLong
    activeStop := candidateLongStop
    activeTarget := candidateLongTarget
    activeFailureLevel := tradeFailureLevel
    activeSetupType := tradeSetupType
    activeFill := na
    initialFillRisk := na
    entryBarSeen := na
    failureCount := 0
    breakEvenActive := false
    strategy.entry("CNPS62-L", strategy.long, comment="LUNCH RESET LONG", alert_message="🟢 VÀO VỊ THẾ LONG (Lunch Reopen Reset)\\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\\n🛑 SL dự kiến: " + str.tostring(activeStop, format.mintick) + "\\n🎯 TP dự kiến: " + str.tostring(activeTarget, format.mintick))
    strategy.exit("CNPS62-L-X", from_entry="CNPS62-L", stop=activeStop, limit=activeTarget, comment_profit="TP Long", comment_loss="SL Long", alert_profit="💰 CHỐT LỜI LONG (TP HIT)\\n🎯 Giá chốt: " + str.tostring(activeTarget, format.mintick), alert_loss="🛑 CẮT LỖ LONG (SL HIT)\\n🎯 Giá cắt: " + str.tostring(activeStop, format.mintick))
    tradesToday += 1
    lastEntrySignalBar := bar_index
    setupState := 0

// ============================================================================
// SECTION 25: SHORT ENTRY
// ============================================================================
else if finalShort
    activeStop := candidateShortStop
    activeTarget := candidateShortTarget
    activeFailureLevel := tradeFailureLevel
    activeSetupType := tradeSetupType
    activeFill := na
    initialFillRisk := na
    entryBarSeen := na
    failureCount := 0
    breakEvenActive := false
    strategy.entry("CNPS62-S", strategy.short, comment="LUNCH RESET SHORT", alert_message="🔴 VÀO VỊ THẾ SHORT (Lunch Reopen Reset)\\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\\n🛑 SL dự kiến: " + str.tostring(activeStop, format.mintick) + "\\n🎯 TP dự kiến: " + str.tostring(activeTarget, format.mintick))
    strategy.exit("CNPS62-S-X", from_entry="CNPS62-S", stop=activeStop, limit=activeTarget, comment_profit="TP Short", comment_loss="SL Short", alert_profit="💰 CHỐT LỜI SHORT (TP HIT)\\n🎯 Giá chốt: " + str.tostring(activeTarget, format.mintick), alert_loss="🛑 CẮT LỖ SHORT (SL HIT)\\n🎯 Giá cắt: " + str.tostring(activeStop, format.mintick))
    tradesToday += 1
    lastEntrySignalBar := bar_index
    setupState := 0

// ============================================================================
// SECTION 26: FILL VALIDATION / OPTIONAL BREAK EVEN
// ============================================================================
if (strategy.position_size != 0 and strategy.opentrades > 0 and barstate.isconfirmed)
    int actualEntryBar = (strategy.opentrades.entry_bar_index(0))
    float actualEntry = (strategy.position_avg_price)
    if na(entryBarSeen) or actualEntryBar != entryBarSeen
        entryBarSeen := actualEntryBar
        activeFill := actualEntry
        initialFillRisk := (inLong ? actualEntry - activeStop : activeStop - actualEntry)
    bool validFill = (not na(initialFillRisk) and initialFillRisk > syminfo.mintick and (inLong ? activeTarget > actualEntry : activeTarget < actualEntry))
    if not validFill
        strategy.close(inLong ? "CNPS62-L" : "CNPS62-S", immediately=true, comment="INVALID FILL RISK", alert_message="🔄 ĐÓNG VỊ THẾ (Khớp lệnh không hợp lệ)\\n🎯 Giá đóng: " + str.tostring(close, format.mintick))
    else
        float openR = (inLong ? (close - actualEntry) / initialFillRisk : (actualEntry - close) / initialFillRisk)
        if useBreakEven and openR >= breakEvenTriggerR
            float newStop = math.round_to_mintick(inLong ? actualEntry + breakEvenOffset : actualEntry - breakEvenOffset)
            activeStop := (inLong ? math.max(activeStop, newStop) : math.min(activeStop, newStop))
            breakEvenActive := true
        if inLong
            strategy.exit("CNPS62-L-X", from_entry="CNPS62-L", stop=activeStop, limit=activeTarget, comment_profit="TP Long", comment_loss=breakEvenActive ? "BE Long" : "SL Long", alert_profit="💰 CHỐT LỜI LONG (TP HIT)\\n🎯 Giá chốt: " + str.tostring(activeTarget, format.mintick), alert_loss=breakEvenActive ? ("🛡️ HÒA VỐN LONG (BE HIT)\\n🎯 Giá thoát: " + str.tostring(activeStop, format.mintick)) : ("🛑 CẮT LỖ LONG (SL HIT)\\n🎯 Giá cắt: " + str.tostring(activeStop, format.mintick)))
        else
            strategy.exit("CNPS62-S-X", from_entry="CNPS62-S", stop=activeStop, limit=activeTarget, comment_profit="TP Short", comment_loss=breakEvenActive ? "BE Short" : "SL Short", alert_profit="💰 CHỐT LỜI SHORT (TP HIT)\\n🎯 Giá chốt: " + str.tostring(activeTarget, format.mintick), alert_loss=breakEvenActive ? ("🛡️ HÒA VỐN SHORT (BE HIT)\\n🎯 Giá thoát: " + str.tostring(activeStop, format.mintick)) : ("🛑 CẮT LỖ SHORT (SL HIT)\\n🎯 Giá cắt: " + str.tostring(activeStop, format.mintick)))

// ============================================================================
// SECTION 27: ACCEPTANCE FAILURE / TIME EXIT
// ============================================================================
if (strategy.position_size != 0 and strategy.opentrades > 0 and barstate.isconfirmed)
    bool failedAcceptance = (activeSetupType == 1 ? (inLong ? close < activeFailureLevel - reclaimBuffer : close > activeFailureLevel + reclaimBuffer) : (inLong ? close < activeFailureLevel - minimumBreakPoints : close > activeFailureLevel + minimumBreakPoints))
    failureCount := (failedAcceptance ? failureCount + 1 : 0)
    if (useFailedAcceptanceExit and failureCount >= failureCloseBars)
        strategy.close(inLong ? "CNPS62-L" : "CNPS62-S", comment="RESET ACCEPTANCE FAILED", alert_message="⚡ ĐÓNG VỊ THẾ (Phá vỡ thất bại)\\n🎯 Giá đóng: " + str.tostring(close, format.mintick))
    int entryTime = (strategy.opentrades.entry_time(0))
    if (useTimeExit and not na(time_close) and time_close >= entryTime + maximumHoldMinutes * 60000)
        strategy.close(inLong ? "CNPS62-L" : "CNPS62-S", comment="MAX HOLD TIME", alert_message="⏱️ ĐÓNG VỊ THẾ (Hết thời gian giữ lệnh tối đa)\\n🎯 Giá đóng: " + str.tostring(close, format.mintick))

// ============================================================================
// SECTION 28: FORCE FLAT BEFORE ATC
// ============================================================================
if forceFlatBar and strategy.position_size != 0
    strategy.close_all(immediately=true, comment="PRE-ATC FLAT", alert_message="⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End)\\n🎯 Giá đóng: " + str.tostring(close, format.mintick))

// ============================================================================
// SECTION 29: CLEANUP
// ============================================================================
if flat and not finalLong and not finalShort
    activeStop := na
    activeTarget := na
    activeFill := na
    initialFillRisk := na
    activeFailureLevel := na
    activeSetupType := 0
    entryBarSeen := na
    failureCount := 0
    breakEvenActive := false

// ============================================================================
// SECTION 30: PLOTS - NO DASHBOARD
// ============================================================================
plot(showMorningReference and morningReady ? morningHigh : na, title="Morning Reference High", color=color.new(color.gray, 50), style=plot.style_linebr)
plot(showMorningReference and morningReady ? morningLow : na, title="Morning Reference Low", color=color.new(color.gray, 50), style=plot.style_linebr)
plot(showResetRange and resetReady ? resetHigh : na, title="Afternoon Reset High", color=color.new(color.teal, 20), linewidth=2, style=plot.style_linebr)
plot(showResetRange and resetReady ? resetLow : na, title="Afternoon Reset Low", color=color.new(color.red, 20), linewidth=2, style=plot.style_linebr)
plot(showVWAP ? sessionVWAP : na, title="Session VWAP", color=color.orange, style=plot.style_linebr)
plot(showTradeLevels and strategy.position_size != 0 ? activeStop : na, title="Stop Loss", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showTradeLevels and strategy.position_size != 0 ? activeTarget : na, title="Take Profit", color=color.green, linewidth=2, style=plot.style_linebr)
plotshape(showEntries and finalLong, title="CNPS62 Long", style=shape.triangleup, location=location.belowbar, text="L", color=color.teal, textcolor=color.white, size=size.small)
plotshape(showEntries and finalShort, title="CNPS62 Short", style=shape.triangledown, location=location.abovebar, text="S", color=color.red, textcolor=color.white, size=size.small)

// ============================================================================
// CNPS62 V1.1 - EXECUTION NOTES
// ============================================================================
// 1. Explicit 12% simulated margin avoids Pine v6's 100% default.
// 2. Actual broker margin requirements may differ.
// 3. Observation windows use complete intraday chart bars.
// 4. Morning reference requires at least one completed bar.
// 5. Maximum structural stop distance is 14 points.
// 6. Signals use confirmed candles without future data.
// 7. Trades are still subject to other entry and risk filters.
// 8. No dashboard is displayed.
// 9. Profitability and TradingView compilation are not verified.
// ============================================================================

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

2.1. Động cơ thời gian nến hoàn chỉnh (Complete-Bar Time Engine)

Khác với các bot cố định số phút cứng, CNPS62 quy đổi khung thời gian biểu đồ (chartMinutes = math.max(1, math.ceil(timeframe.in_seconds() / 60.0))) để tính cửa sổ quan sát theo bội số nguyên của nến:

  • effectiveMorningMinutes = ceil(morningReferenceMinutes / chartMinutes) * chartMinutes: Lấy các nến hoàn chỉnh cuối phiên sáng kết thúc trước hoặc đúng 11:30 (phút 690).
  • effectiveAfternoonMinutes = ceil(afternoonOpeningMinutes / chartMinutes) * chartMinutes: Lấy các nến hoàn chỉnh đầu phiên chiều bắt đầu từ 13:00 (phút 780). Nhờ cơ chế này, nếu bạn chạy bot trên khung 15 phút với cấu hình quan sát 5 phút đầu chiều, vùng Reset vẫn có ít nhất 1 nến hoàn chỉnh thay vì bị rỗng (na).

2.2. Bộ lọc chất lượng nến và vùng giá (Candle & Range Quality)

Bot chuẩn hóa chất lượng nến dựa trên 2 thước đo:

  • Tỷ lệ thân nến (candleBody): abs(close - open) / max(high - low, mintick) phải đạt tối thiểu 0.25 (hoặc 0.55 nếu vào lệnh phá vỡ trực tiếp allowDirectBreakout).
  • Vị trí đóng cửa (closeLocation): (close - low) / candleRange. Nến tăng (bullishCandle) yêu cầu đóng cửa tăng (close > open) và closeLocation >= 0.55; nến giảm (bearishCandle) yêu cầu đóng cửa giảm (close < open) và closeLocation <= 0.45.
  • Điều kiện vùng giá hợp lệ: Vùng tham chiếu sáng (morningWidth) phải nằm trong 1.5–35.0 điểm; vùng Reset đầu chiều (resetWidth) phải nằm trong 1.0 điểm đến 6.0 × ATR(14).

2.3. Bộ lọc bối cảnh tùy chọn (VWAP, EMA, Volume & Morning Alignment)

Mặc định các bộ lọc phụ đều đang tắt (false), cho phép bạn bật thêm khi muốn siết chặt tín hiệu:

  • Session VWAP: Tính lũy kế từ đầu ngày trong phiên liên tục (cumulativePV / cumulativeVolume), Long yêu cầu close > sessionVWAP, Short yêu cầu close < sessionVWAP.
  • Trend EMA: Dùng ta.ema(close, 34), Long cần giá đóng cửa trên EMA, Short cần dưới EMA.
  • Volume Expansion: So sánh khối lượng nến hiện tại với trung bình 20 phiên trước đó (volume >= ta.sma(volume, 20)[1] * 0.9).
  • Morning Alignment: Khi bật requireMorningAlignment, các lệnh Continuation chỉ vào khi cùng chiều xu hướng cuối phiên sáng (morningBull hoặc morningBear).

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

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

  1. Khởi tạo đầu ngày & đo vùng tham chiếu sáng: Khi newTradingDay kích hoạt, bot reset toàn bộ biến trạng thái, VWAP và bộ đếm lệnh. Trong morningReferenceMinutes cuối phiên sáng (mặc định 15 phút trước 11:30), bot ghi nhận morningHigh, morningLow và hướng tăng/giảm (morningBull / morningBear).
  2. Hình thành vùng Reset đầu phiên chiều: Từ 13:00, bot quan sát afternoonOpeningMinutes (mặc định 5 phút) để tạo vùng resetHigh – resetLow. Chỉ khi cả vùng sáng và vùng Reset đạt chuẩn (resetReady == true), bot mới sẵn sàng tìm điểm phá vỡ.
  3. Phát hiện phá vỡ & kích hoạt bộ đếm trạng thái (setupState): Khi nến đóng cửa vượt biên resetHigh + 0.3 (hoặc dưới resetLow - 0.3), nếu nến đủ mạnh (candleBody >= 0.55) và bật allowDirectBreakout, bot vào lệnh tiếp diễn ngay. Nếu không, bot chuyển setupState sang 1 (tăng) hoặc -1 (giảm) để chờ xác nhận trong tối đa 8 nến.
  4. Xác nhận Retest hoặc Đảo chiều thất bại: Trong cửa sổ 8 nến chờ, nếu giá quay lại chạm vùng biên Reset trong phạm vi cho phép rồi bật tăng/giảm tiếp, bot vào lệnh Acceptance Continuation (tradeSetupType = 1). Ngược lại, nếu giá chui ngược lại vào vùng Reset vượt ngưỡng reclaimBuffer (0.2 điểm) kèm nến đảo chiều, bot kích hoạt Failed Breakout Reversal (tradeSetupType = -1).
  5. Kiểm tra rủi ro, gửi lệnh & quản trị thoát: Trước khi phát lệnh strategy.entry, bot tính khoảng cách SL/TP, kiểm tra điều kiện rủi ro (1.5–14.0 điểm) và bộ đếm ngày. Sau khi khớp lệnh, bot liên tục giám sát xác nhận giá, thời gian giữ lệnh (40 phút) và tự động đóng sạch vị thế lúc 14:25.

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

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

Tín hiệu finalLong được kích hoạt khi thỏa mãn commonEntryOK, allowLong (tradeDirection != "Short"), các bộ lọc bối cảnh (longMorningOK, trendLongOK, vwapLongOK), longRiskOK và một trong ba kịch bản tín hiệu rawLong:

  • Kịch bản 1 – Phá vỡ tăng trực tiếp (Direct Continuation): Đang ở trạng thái chờ (setupState == 0), nến đóng cửa xác nhận close > resetHigh + 0.3 (với close[1] <= resetHigh + 0.3), là bullishCandle, allowDirectBreakout = true, candleBody >= 0.55 và entryMode != "Failed Breakout Reversal".
  • Kịch bản 2 – Retest biên trên thành công (Retest Continuation): Sau khi đã có freshUpsideBreak (setupState == 1) trong vòng 8 nến, nến hiện tại có giá thấp nhất chạm vùng biên trên (low <= resetHigh + 0.55 * ATR14 và low >= resetHigh - 0.65 * ATR14), đồng thời đóng cửa giữ vững close >= resetHigh + 0.3 với bullishCandle (khi entryMode != "Failed Breakout Reversal").
  • Kịch bản 3 – Phá vỡ giảm thất bại (Failed Breakout Reversal): Sau khi đã có freshDownsideBreak (setupState == -1) trong vòng 8 nến, giá quay đầu đóng cửa vượt lại lên trên biên dưới close > resetLow + 0.2 kèm bullishCandle (khi entryMode != "Acceptance Continuation").

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

Tín hiệu finalShort được kích hoạt khi thỏa mãn commonEntryOK, allowShort (tradeDirection != "Long"), các bộ lọc bối cảnh (shortMorningOK, trendShortOK, vwapShortOK), shortRiskOK, không trùng finalLong, và một trong ba kịch bản tín hiệu rawShort:

  • Kịch bản 1 – Phá vỡ giảm trực tiếp (Direct Continuation): Đang ở setupState == 0, nến đóng cửa close < resetLow - 0.3 (với close[1] >= resetLow - 0.3), là bearishCandle, allowDirectBreakout = true, candleBody >= 0.55 và entryMode != "Failed Breakout Reversal".
  • Kịch bản 2 – Retest biên dưới thành công (Retest Continuation): Sau khi đã có freshDownsideBreak (setupState == -1) trong vòng 8 nến, nến hiện tại có giá cao nhất chạm vùng biên dưới (high >= resetLow - 0.55 * ATR14 và high <= resetLow + 0.65 * ATR14), đồng thời đóng cửa close <= resetLow - 0.3 với bearishCandle (khi entryMode != "Failed Breakout Reversal").
  • Kịch bản 3 – Phá vỡ tăng thất bại (Failed Breakout Reversal): Sau khi đã có freshUpsideBreak (setupState == 1) trong vòng 8 nến, giá quay đầu đóng cửa tụt xuống dưới biên trên close < resetHigh - 0.2 kèm bearishCandle (khi entryMode != "Acceptance Continuation").

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

Mọi tín hiệu Long/Short đều phải vượt qua cổng kiểm soát commonEntryOK:

  • Trạng thái tài khoản: Đang không có vị thế (flat, strategy.position_size == 0) và nến đã đóng xác nhận (barstate.isconfirmed).
  • Khung giờ giao dịch: Nằm trong phiên vào lệnh chiều 1305-1415 (Thứ 2 – Thứ 6, múi giờ Asia/Ho_Chi_Minh) và thời điểm đóng nến trước giờ đóng phiên 14:25 (beforeCutoff).
  • Giới hạn tần suất: Số lệnh trong ngày tradesToday < 3, không phát quá 1 lệnh trên cùng 1 nến (oneOrderPerBar), và đã qua đủ cooldownBars (bar_index - lastExitBar > 3).
  • Bảo vệ lỗ ngày (Daily Loss Guard): Nếu bật useDailyLossGuard, lãi/lỗ đã chốt trong ngày (dailyClosedPnL) phải lớn hơn -2.400.000 VNĐ.

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

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

Bot cung cấp 3 chế độ đặt Stop Loss (stopMode), làm tròn theo bước giá tối thiểu (math.round_to_mintick):

  • Setup Extreme (Mặc định): Đặt SL tại điểm cực trị của setup (candidateStopAnchor: đáy nến retest/vùng Reset đối với Long Continuation, đáy vùng phá vỡ giả đối với Long Reversal, và tương tự ngược lại cho Short) cộng/trừ thêm khoảng đệm 0.15 × ATR(14).
  • Reset Range Opposite: Đặt SL tại biên đối diện của vùng Reset (resetLow - 0.15 × ATR14 cho Long; resetHigh + 0.15 × ATR14 cho Short).
  • ATR Fixed: Đặt SL cố định cách giá đóng cửa 1.5 × ATR(14).

Sau khi tính longRisk hoặc shortRisk, bot áp dụng bộ lọc chất lượng rủi ro:

  • Khoảng cách SL phải nằm trong [1.5, 14.0] điểm.
  • Mục tiêu lợi nhuận gộp (risk * 1.6) phải đạt tối thiểu 2.5 điểm (minimumGrossTarget).

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

  • Take Profit cố định: Tính theo bội số takeProfitR = 1.6 lần rủi ro dự kiến (close ± risk * 1.6).
  • Kiểm tra khớp lệnh thực tế (Fill Validation): Khi lệnh đã khớp, bot tính initialFillRisk dựa trên strategy.position_avg_price. Nếu initialFillRisk <= mintick hoặc giá TP nằm ngược chiều giá khớp, bot lập tức đóng vị thế (INVALID FILL RISK).
  • Dời hòa vốn (Break Even): Mặc định tắt (useBreakEven = false). Khi bật, nếu lợi nhuận mở đạt 1.0R, SL được kéo về actualEntry + 0.2 điểm (Long) hoặc actualEntry - 0.2 điểm (Short).
  • Thoát sớm khi phá vỡ thất bại (Failed Acceptance Exit): Mặc định bật (useFailedAcceptanceExit = true). Nếu giá đóng cửa quay ngược qua mốc activeFailureLevel (reclaimBuffer = 0.2 với lệnh Continuation, hoặc minimumBreakPoints = 0.3 với lệnh Reversal) trong 2 nến liên tiếp, bot chủ động cắt lệnh (RESET ACCEPTANCE FAILED).
  • Thoát theo thời gian & Hết phiên: Đóng lệnh nếu giữ quá 40 phút (MAX HOLD TIME), và đóng toàn bộ vị thế bằng lệnh thị trường ngay tại nến chạm 14:25 (PRE-ATC FLAT).

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

Cơ chế bảo vệTham số chínhĐiều kiện kích hoạtHành động của Bot
Stop Loss cấu trúcstopMode = "Setup Extreme", 0.15 × ATR14Giá chạm mức activeStopCắt lỗ tự động qua strategy.exit
Take Profit cố địnhtakeProfitR = 1.6, minimumGrossTarget = 2.5Giá chạm mức activeTargetChốt lời tự động qua strategy.exit
Kiểm tra khớp lệnhinitialFillRisk > syminfo.mintickGiá khớp làm SL/TP mất hiệu lựcĐóng ngay lập tức (INVALID FILL RISK)
Dời hòa vốn (BE)useBreakEven = false, 1.0R, offset 0.2Lãi mở đạt >= 1.0RDời activeStop về giá vốn ± 0.2 điểm
Phá vỡ thất bạiuseFailedAcceptanceExit = true, 2 nếnGiá đóng cửa ngược mốc activeFailureLevel 2 nếnChủ động đóng lệnh (RESET ACCEPTANCE FAILED)
Giới hạn thời gianuseTimeExit = true, 40 phúttime_close >= entryTime + 40 phútĐóng lệnh (MAX HOLD TIME)
Đóng trước ATCforceFlatHour = 14, forceFlatMinute = 25Nến đóng chạm hoặc vượt 14:25strategy.close_all (PRE-ATC FLAT)

6. Hướng dẫn cài đặt và đọc hiển thị 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 nhỏ như 1m, 3m hoặc 5m để quan sát sát diễn biến vùng Reset đầu phiên chiều).
  2. Mở tab Pine Editor ở phía dưới màn hình, xóa toàn bộ mã mặc định.
  3. Sao chép toàn bộ mã nguồn Pine Script v6 ở Mục 1 và dán vào Pine Editor.
  4. Nhấn Save để lưu script, sau đó nhấn Add to chart để gắn chiến lược lên biểu đồ.

Cách đọc hiển thị trên biểu đồ (Clean Display)

Theo thiết kế của mã nguồn (SECTION 30: PLOTS - NO DASHBOARD), Bot CNPS62 không hiển thị bảng thống kê (table.new) nhằm giữ biểu đồ thông thoáng tối đa. Thay vào đó, bot vẽ trực tiếp các thành phần sau lên đồ thị giá:

  • Afternoon Reset High / Low: Hai đường ngang màu xanh ngọc (teal) và đỏ (red) đánh dấu biên trên – biên dưới của vùng Reset đầu phiên chiều (bật mặc định qua showResetRange = true).
  • Morning Reference High / Low & Session VWAP: Các đường tham chiếu phiên sáng màu xám và đường VWAP màu cam (tắt mặc định, có thể bật trong mục 11 - Display).
  • Tín hiệu Long / Short: Mũi tên tam giác xanh chữ L dưới nến và tam giác đỏ chữ S trên nến (showEntries = true).
  • Active Stop / Target: Đường Stop Loss màu đỏ và Take Profit màu xanh lá hiển thị trực tiếp khi đang có vị thế mở (showTradeLevels = true).

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, Telegram hoặc Webhook khi bot phát sinh tín hiệu:

  1. Sau khi gắn CNPS62 lên biểu đồ VN30F1M và tinh chỉnh thông số, nhấn nút Alert (Chuông) trên thanh công cụ TradingView.
  2. Tại mục Condition, chọn chiến lược CNPS62 LUNCH REOPEN RESET V1.1 - VN30F1M.
  3. Tại ô Message, xóa nội dung mặc định và nhập chính xác cú pháp:
    {{strategy.order.alert_message}}
  4. Chọn kênh nhận thông báo (Notify on app, Webhook URL…) và nhấn Create.

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

Sự kiệnLoại hàm gọi trong codeNội dung thông điệp (alert_message / alert_profit / alert_loss)
Vào lệnh Longstrategy.entry("CNPS62-L")🟢 VÀO VỊ THẾ LONG (Lunch Reopen Reset)\n🎯 Giá vào: <giá>\n🛑 SL dự kiến: <SL>\n🎯 TP dự kiến: <TP>
Vào lệnh Shortstrategy.entry("CNPS62-S")🔴 VÀO VỊ THẾ SHORT (Lunch Reopen Reset)\n🎯 Giá vào: <giá>\n🛑 SL dự kiến: <SL>\n🎯 TP dự kiến: <TP>
Chốt lời Long / Shortstrategy.exit (alert_profit)💰 CHỐT LỜI LONG (TP HIT)\n🎯 Giá chốt: <TP> / 💰 CHỐT LỜI SHORT (TP HIT)\n🎯 Giá chốt: <TP>
Cắt lỗ Long / Shortstrategy.exit (alert_loss)🛑 CẮT LỖ LONG (SL HIT)\n🎯 Giá cắt: <SL> / 🛑 CẮT LỖ SHORT (SL HIT)\n🎯 Giá cắt: <SL>
Hòa vốn Long / Shortstrategy.exit (alert_loss khi breakEvenActive)🛡️ HÒA VỐN LONG (BE HIT)\n🎯 Giá thoát: <SL> / 🛡️ HÒA VỐN SHORT (BE HIT)\n🎯 Giá thoát: <SL>
Khớp lệnh lỗistrategy.close🔄 ĐÓNG VỊ THẾ (Khớp lệnh không hợp lệ)\n🎯 Giá đóng: <giá>
Phá vỡ thất bạistrategy.close⚡ ĐÓNG VỊ THẾ (Phá vỡ thất bại)\n🎯 Giá đóng: <giá>
Quá thời gian giữstrategy.close⏱️ ĐÓNG VỊ THẾ (Hết thời gian giữ lệnh tối đa)\n🎯 Giá đóng: <giá>
Đóng hết phiên (14:25)strategy.close_all⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End)\n🎯 Giá đóng: <giá>

Kết luận

CNPS62 Lunch Reopen Reset V1.1 là một hệ thống giao dịch kỷ luật cao dành riêng cho phiên chiều VN30F1M, giúp trader khai thác hiệu quả nhịp tái định giá sau giờ nghỉ trưa mà không phải chịu rủi ro giữ lệnh qua trưa hay qua phiên ATC. Nhờ kết hợp linh hoạt giữa đánh tiếp diễn phá vỡ, đánh đảo chiều phá vỡ giả cùng cơ chế cắt lỗ sớm khi mất vùng chấp nhận giá, bot đặc biệt phù hợp với những phiên thị trường có nhịp mở cửa chiều rõ ràng hoặc các phiên quét thanh khoản hai đầu trước khi định hình xu hướng.

Bạn có thể tham khảo thêm các hệ thống giao dịch VN30F1M khác như Bot CNPS50 - Trend Analysis V2 và Bot CNPS49 - Daily Open để đa dạng hóa danh mục chiến lược theo từng trạng thái thị trường.

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