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

Hướng Dẫn Sử Dụng Bot CNPS90 - Opening Range Breakout V2 cho VN30F1M

Bot CNPS90 Opening Range Breakout V2 xây dựng vùng giá mở cửa từ nến đã đóng, lọc phá vỡ bằng đệm ATR và độ mạnh thân nến, kết hợp cơ chế Re-arm chỉ nạp lại tín hiệu khi giá đóng cửa quay vào vùng OR cùng SL/TP cố định theo tick.

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

Khi giao dịch hợp đồng tương lai chỉ số VN30F1M, vùng giá mở cửa đầu phiên (Opening Range) thường đóng vai trò là vùng cân bằng cung – cầu quan trọng trong ngày. Tuy nhiên, nếu áp dụng chiến lược phá vỡ vùng mở cửa (Opening Range Breakout – ORB) truyền thống, trader rất dễ gặp hai vấn đề: hoặc bỏ lỡ các nhịp phá vỡ chất lượng sau khi giá kiểm tra lại vùng cân bằng, hoặc bị nhồi lệnh liên tục khi giá duy trì bên ngoài biên độ mở cửa.

CNPS90 OPENING RANGE BREAKOUT V2 (shorttitle="CNPS90 ORB V2") được viết bằng Pine Script v6 trên nền tảng TradingView để giải quyết triệt để bài toán này. Chiến lược xây dựng vùng Opening Range từ các cây nến đã đóng hoàn chỉnh, sử dụng bộ đệm ATR khi phá vỡ và áp dụng cơ chế Tiêu thụ – Tái nạp đạn (Consume & Re-arm) để chỉ cho phép tìm kiếm điểm vào mới sau khi giá thực sự đóng cửa quay trở lại bên trong vùng OR.

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

  • Không dùng dữ liệu tương lai (No future-looking): Mọi tín hiệu đều tính trên nến đã đóng (barstate.isconfirmed), kể cả bộ lọc xu hướng khung H1 sử dụng giá và EMA của nến H1 đã hoàn tất ([1]).
  • Cơ chế Re-arm kỷ luật: Sau một lần phá vỡ, hướng đó sẽ tự động khóa lại (armedLong = false hoặc armedShort = false), không vào lệnh lặp lại khi giá vẫn ở ngoài OR, và chỉ kích hoạt lại khi giá đóng cửa trở lại bên trong OR đủ số nến quy định.
  • Bộ lọc chất lượng nến & đa lớp: Kiểm soát hướng nến, độ mạnh thân nến (Body / Range), kết hợp tùy chọn lọc độ rộng OR theo ATR, EMA Trend, Relative Volume, ADX/DI và H1 Bias.
  • Quản trị rủi ro rõ ràng theo điểm/tick: Cố định Stop Loss (mặc định 5.0 điểm) và Take Profit (mặc định 15.0 điểm), hỗ trợ thoát lệnh theo thời gian nắm giữ và tự động tất toán cuối phiên trước giờ ATC (14:45).

1. CNPS90 Opening Range Breakout V2 là gì?

CNPS90 Opening Range Breakout V2 là hệ thống giao dịch theo đà phá vỡ vùng giá mở cửa đầu ngày, được thiết kế với 4 trụ cột kỹ thuật chính:

  1. Xây dựng và khóa vùng Opening Range (09:00 – 09:15): Thu thập giá cao nhất (orHigh) và thấp nhất (orLow) từ các nến đã đóng trong khung giờ thiết lập, sau đó khóa cứng biên độ khi bước sang giai đoạn afterOR và kiểm tra tính hợp lệ của độ rộng vùng OR (tùy chọn lọc theo tỷ lệ OR Width / ATR).
  2. Xác nhận phá vỡ có đệm & chất lượng nến: Mức phá vỡ được cộng/trừ thêm lớp đệm breakoutBuffer (mặc định 0.05 × ATR(14)) để hạn chế nhiễu quét biên. Nến phá vỡ phải thỏa mãn đồng thời điều kiện đóng cửa vượt ngưỡng, đúng hướng nến (tăng/giảm) và tỷ lệ thân nến tối thiểu (0.35).
  3. Cơ chế Re-entry / Re-arm thông minh: Mỗi hướng giao dịch được phép thử phá vỡ tối đa maximumAttemptsPerDirection lần/ngày (mặc định 3). Ngay khi xuất hiện sự kiện phá vỡ, trạng thái sẵn sàng của hướng đó bị tiêu thụ và chỉ được nạp lại nếu giá đóng cửa quay vào trong vùng OR đủ rearmInsideBars nến liên tiếp.
  4. Hệ thống lọc đa lớp & kiểm soát rủi ro chặt chẽ: Tích hợp các bộ lọc tùy chọn (EMA Trend, Volume tương đối, ADX/DI, H1 EMA Bias), giới hạn tối đa 3 lệnh/ngày, thời gian nghỉ sau khi đóng lệnh (cooldownBars = 1), cùng SL/TP cố định quy đổi sang tick và đóng vị thế bắt buộc lúc 14:45.

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
01. Opening RangeorStartHour / orStartMinute9 / 0Giờ bắt đầu xây dựng vùng OR (09:00)
orEndHour / orEndMinute9 / 15Giờ kết thúc và khóa vùng OR (09:15)
atrLength14Chu kỳ tính chỉ báo ATR
useORWidthFilterfalseBật/tắt lọc độ rộng vùng OR theo ATR
minimumORWidthATR / maximumORWidthATR0.20 / 6.00Biên độ OR Width / ATR tối thiểu và tối đa
02. BreakoutmaximumBreakoutMinutes300Thời gian tối đa sau OR cho phép tìm điểm phá vỡ (phút)
useBreakoutBuffer / breakoutBufferATRtrue / 0.05Bật đệm phá vỡ theo 0.05 × ATR
requireCandleDirectiontrueYêu cầu nến Long là nến tăng, nến Short là nến giảm
useBodyFilter / minimumBodyRatiotrue / 0.35Lọc tỷ lệ thân nến tối thiểu 35% biên độ nến
useCloseLocationfalseBật/tắt lọc vị trí giá đóng cửa gần cực trị nến
minimumLongClosePosition / maximumShortClosePosition0.65 / 0.35Ngưỡng vị trí đóng cửa cho Long (≥ 0.65) và Short (≤ 0.35)
03. Breakout Re-armallowReentrytrueCho phép nạp lại tín hiệu sau khi giá quay vào vùng OR
rearmInsideBars1Số nến đóng cửa liên tiếp trong OR để Re-arm
useRearmMargin / rearmMarginATRfalse / 0.05Yêu cầu giá vào sâu trong OR thêm một khoảng đệm ATR
maximumAttemptsPerDirection3Số lần thử phá vỡ tối đa cho mỗi chiều trong ngày
04. EMA TrenduseEMAFilter / emaLength / emaSlopeBarsfalse / 50 / 3Bộ lọc xu hướng EMA(50) dốc lên/xuống so với 3 nến trước
requirePriceEMAfalseYêu cầu giá đóng cửa nằm trên/dưới EMA
05. Optional FiltersuseVolumeFilter / volumeLength / volumeFactorfalse / 20 / 1.0Lọc khối lượng tương đối so với SMA(20) của volume[1]
useADXFilter / diLength / adxSmoothing / minimumADXfalse / 14 / 14 / 18.0Bộ lọc sức mạnh xu hướng ADX tối thiểu 18.0
requireDIDirectionfalseYêu cầu DI+ > DI- (Long) hoặc DI- > DI+ (Short)
06. H1 BiasuseH1Bias / h1EMALengthfalse / 50Bộ lọc xu hướng khung H1 (close[1] so với EMA(50)[1])
07. Risk ManagementstopLossPoints / takeProfitPoints5.0 / 15.0Cắt lỗ 5.0 điểm, chốt lời 15.0 điểm (tỷ lệ R:R 1:3)
useTimeExit / maximumHoldingBarsfalse / 20Thoát lệnh theo thời gian nếu giữ quá 20 nến
08. Trade ControltradeDirection"Long"Chiều giao dịch mặc định ("Long", "Short", hoặc "Both")
contracts3Số hợp đồng hiển thị cấu hình (lệnh mặc định dùng default_qty_value=1 trong strategy)
maximumTradesPerDay3Tổng số lệnh vào tối đa trong ngày
cooldownBars1Số nến nghỉ tối thiểu sau khi đóng lệnh
09. Trading SessionuseSessionFilter / tztrue / "Asia/Ho_Chi_Minh"Bật lọc phiên theo múi giờ Việt Nam
startHour:startMinute – lastHour:lastMinute09:15 – 14:15Khung giờ cho phép mở vị thế mới
endHour:endMinute14:45Thời điểm bắt buộc đóng toàn bộ vị thế (Force Close)
10. AlertsdisableExitAlertsfalseCho phép gửi cảnh báo SL/TP khi khớp lệnh thoát
11. DisplayshowEMA, showOpeningRange, showEntryMarkers, showSLTPtrueHiển thị EMA, biên OR, mũi tên vào lệnh và đường SL/TP
showDiagnosticsfalseBật/tắt bảng thống kê chẩn đoán góc trên bên phải

Source Code CNPS90 Opening Range Breakout V2

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

//@version=6
strategy(title="CNPS90 OPENING RANGE BREAKOUT V2", shorttitle="CNPS90 ORB V2", overlay=true, initial_capital=100000000, default_qty_type=strategy.fixed, default_qty_value=1, pyramiding=0, margin_long=0, margin_short=0, slippage=0, commission_type=strategy.commission.cash_per_contract, commission_value=0, fill_orders_on_standard_ohlc=true, process_orders_on_close=true, calc_on_order_fills=false, max_labels_count=300, max_lines_count=300, max_bars_back=5000)

// ============================================================================
// CNPS90 V2 - OPENING RANGE BREAKOUT RE-ENTRY
//
// 1. Build the opening range from completed candles.
// 2. Freeze OR High / OR Low.
// 3. Enter on a confirmed directional breakout.
// 4. Consume the breakout attempt for that direction.
// 5. Re-arm only after price CLOSES back inside the OR.
// 6. Allow another breakout within the daily limits.
//
// V2 focuses on increasing valid trade opportunities
// without allowing repeated entries while price
// remains continuously outside the range.
//
// No future-looking price data.
// Confirmed-bar entry signals.
// Fixed SL / TP in ticks.
// ============================================================================
// ============================================================================
// 01. OPENING RANGE
// ============================================================================
gOR = "01. Opening Range"
orStartHour = input.int(9, "OR Start Hour", minval=0, maxval=23, group=gOR)
orStartMinute = input.int(0, "OR Start Minute", minval=0, maxval=59, group=gOR)
orEndHour = input.int(9, "OR End Hour", minval=0, maxval=23, group=gOR)
orEndMinute = input.int(15, "OR End Minute", minval=0, maxval=59, group=gOR)
atrLength = input.int(14, "ATR Length", minval=1, group=gOR)
useORWidthFilter = input.bool(false, "Use OR Width Filter", group=gOR)
minimumORWidthATR = input.float(0.20, "Minimum OR Width / ATR", minval=0.0, step=0.1, group=gOR)
maximumORWidthATR = input.float(6.00, "Maximum OR Width / ATR", minval=0.1, step=0.1, group=gOR)

// ============================================================================
// 02. BREAKOUT
// ============================================================================
gBreakout = "02. Breakout"
maximumBreakoutMinutes = input.int(300, "Maximum Minutes After OR", minval=5, maxval=480, step=5, group=gBreakout)
useBreakoutBuffer = input.bool(true, "Use Breakout Buffer", group=gBreakout)
breakoutBufferATR = input.float(0.05, "Breakout Buffer / ATR", minval=0.0, step=0.05, group=gBreakout)
requireCandleDirection = input.bool(true, "Require Bullish / Bearish Candle", group=gBreakout)
useBodyFilter = input.bool(true, "Use Body Strength Filter", group=gBreakout)
minimumBodyRatio = input.float(0.35, "Minimum Candle Body / Range", minval=0.0, maxval=1.0, step=0.05, group=gBreakout)
useCloseLocation = input.bool(false, "Require Close Near Candle Extreme", group=gBreakout)
minimumLongClosePosition = input.float(0.65, "Minimum Long Close Position", minval=0.5, maxval=1.0, step=0.05, group=gBreakout)
maximumShortClosePosition = input.float(0.35, "Maximum Short Close Position", minval=0.0, maxval=0.5, step=0.05, group=gBreakout)

// ============================================================================
// 03. RE-ENTRY / RE-ARM
// ============================================================================
gRearm = "03. Breakout Re-arm"
allowReentry = input.bool(true, "Allow New Breakout After OR Re-entry", group=gRearm)
rearmInsideBars = input.int(1, "Consecutive Closes Inside OR", minval=1, maxval=20, group=gRearm)
useRearmMargin = input.bool(false, "Require Distance Inside OR", group=gRearm)
rearmMarginATR = input.float(0.05, "Re-arm Margin / ATR", minval=0.0, step=0.05, group=gRearm)
maximumAttemptsPerDirection = input.int(3, "Maximum Breakout Attempts / Direction / Day", minval=1, maxval=20, group=gRearm)

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

// ============================================================================
// 05. OPTIONAL FILTERS
// ============================================================================
gFilters = "05. Optional Filters"
useVolumeFilter = input.bool(false, "Use Relative Volume Filter", group=gFilters)
volumeLength = input.int(20, "Volume MA Length", minval=2, group=gFilters)
volumeFactor = input.float(1.0, "Minimum Relative Volume", minval=0.1, step=0.1, group=gFilters)
useADXFilter = input.bool(false, "Use Minimum ADX", group=gFilters)
diLength = input.int(14, "DI Length", minval=2, group=gFilters)
adxSmoothing = input.int(14, "ADX Smoothing", minval=2, group=gFilters)
minimumADX = input.float(18.0, "Minimum ADX", minval=1.0, step=1.0, group=gFilters)
requireDIDirection = input.bool(false, "Require DI Direction", group=gFilters)

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

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

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

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

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

// ============================================================================
// 11. DISPLAY
// ============================================================================
gDisplay = "11. Display"
showEMA = input.bool(true, "Show EMA", group=gDisplay)
showOpeningRange = input.bool(true, "Show OR High / Low", group=gDisplay)
showORMidpoint = input.bool(false, "Show OR Midpoint", group=gDisplay)
showORBackground = input.bool(false, "Highlight OR Building", group=gDisplay)
showRawBreakoutMarkers = input.bool(false, "Show Breakout Attempt Dots", group=gDisplay)
showRearmMarkers = input.bool(false, "Show Re-arm Markers", group=gDisplay)
showEntryMarkers = input.bool(true, "Show Entry Markers", group=gDisplay)
showSLTP = input.bool(true, "Show Active SL / TP", group=gDisplay)
showDiagnostics = input.bool(false, "Show Diagnostics", group=gDisplay)

// ============================================================================
// 12. TIME ENGINE
// ============================================================================
int openMinutes = (hour(time, tz) * 60 + minute(time, tz))
int closeMinutes = (hour(time_close, tz) * 60 + minute(time_close, tz))
int orStartMinutes = (orStartHour * 60 + orStartMinute)
int orEndMinutes = (orEndHour * 60 + orEndMinute)
int entryStartMinutes = (startHour * 60 + startMinute)
int lastEntryMinutes = (lastHour * 60 + lastMinute)
int forceCloseMinutes = (endHour * 60 + endMinute)
bool intradayOK = timeframe.isintraday
bool validORSettings = (orEndMinutes > orStartMinutes)
bool validChartResolution = (intradayOK and validORSettings and timeframe.in_seconds() <= (orEndMinutes - orStartMinutes) * 60)
bool insideOR = (validChartResolution and openMinutes >= orStartMinutes and closeMinutes <= orEndMinutes)
bool afterOR = (validChartResolution and openMinutes >= orEndMinutes)
bool breakoutTimeOK = (afterOR and closeMinutes <= orEndMinutes + maximumBreakoutMinutes)
bool entrySessionOK = (not useSessionFilter or (openMinutes >= entryStartMinutes and closeMinutes <= lastEntryMinutes))
bool beforeForceClose = (closeMinutes < forceCloseMinutes)
bool forceCloseBar = (openMinutes < forceCloseMinutes and closeMinutes >= forceCloseMinutes)

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

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

// ============================================================================
// 15. OPENING RANGE STATE
// ============================================================================
var float orHigh = na
var float orLow = na
var float orWidth = na
var float orWidthATR = na
var int orBars = 0
var bool orLocked = false
var bool orWidthOK = false
var bool armedLong = false
var bool armedShort = false
var int longAttemptsToday = 0
var int shortAttemptsToday = 0
var int consecutiveInsideBars = 0
var int totalORDays = 0
var int rejectedORDays = 0
var int totalLongAttempts = 0
var int totalShortAttempts = 0
var int totalRearms = 0
if newDay
    orHigh := na
    orLow := na
    orWidth := na
    orWidthATR := na
    orBars := 0
    orLocked := false
    orWidthOK := false
    armedLong := false
    armedShort := false
    longAttemptsToday := 0
    shortAttemptsToday := 0
    consecutiveInsideBars := 0

// ============================================================================
// 16. BUILD OPENING RANGE
// ============================================================================
if (barstate.isconfirmed and insideOR and not orLocked)
    orHigh := (na(orHigh) ? high : math.max(orHigh, high))
    orLow := (na(orLow) ? low : math.min(orLow, low))
    orBars += 1

// ============================================================================
// 17. FREEZE OPENING RANGE
// ============================================================================
if (barstate.isconfirmed and afterOR and not orLocked and orBars > 0)
    orLocked := true
    orWidth := orHigh - orLow
    orWidthATR := (not na(atr) and atr > 0 ? orWidth / atr : na)
    orWidthOK := (orWidth > 0 and (not useORWidthFilter or (not na(orWidthATR) and orWidthATR >= minimumORWidthATR and orWidthATR <= maximumORWidthATR)))
    armedLong := orWidthOK
    armedShort := orWidthOK
    totalORDays += 1
    if not orWidthOK
        rejectedORDays += 1

// ============================================================================
// 18. BREAKOUT LEVELS
// ============================================================================
float breakoutBuffer = (useBreakoutBuffer and not na(atr) ? atr * breakoutBufferATR : 0.0)
float longBreakLevel = (orLocked and not na(orHigh) ? orHigh + breakoutBuffer : na)
float shortBreakLevel = (orLocked and not na(orLow) ? orLow - breakoutBuffer : na)

// ============================================================================
// 19. RAW BREAKOUT EVENT
// ============================================================================
//
// A breakout is counted only if:
// - OR is locked.
// - Its direction is armed.
// - Price crosses beyond the OR boundary.
// - The directional attempt limit is available.
//
// Price cannot repeatedly generate breakouts
// while remaining outside the range.
//
// ============================================================================
bool longBreakoutEvent = (barstate.isconfirmed and orLocked and orWidthOK and breakoutTimeOK and armedLong and longAttemptsToday < maximumAttemptsPerDirection and not na(longBreakLevel) and close > longBreakLevel and close[1] <= longBreakLevel)
bool shortBreakoutEvent = (barstate.isconfirmed and orLocked and orWidthOK and breakoutTimeOK and armedShort and shortAttemptsToday < maximumAttemptsPerDirection and not na(shortBreakLevel) and close < shortBreakLevel and close[1] >= shortBreakLevel)

// ============================================================================
// 20. CANDLE CONFIRMATION
// ============================================================================
float candleRange = high - low
float candleBody = math.abs(close - open)
float bodyRatio = (candleRange > 0 ? candleBody / candleRange : 0.0)
float closePosition = (candleRange > 0 ? (close - low) / candleRange : 0.5)
bool bullishCandle = close > open
bool bearishCandle = close < open
bool longCandleOK = (not requireCandleDirection or bullishCandle)
bool shortCandleOK = (not requireCandleDirection or bearishCandle)
bool bodyOK = (not useBodyFilter or bodyRatio >= minimumBodyRatio)
bool longCloseOK = (not useCloseLocation or closePosition >= minimumLongClosePosition)
bool shortCloseOK = (not useCloseLocation or closePosition <= maximumShortClosePosition)

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

// ============================================================================
// 22. ADX / VOLUME
// ============================================================================
bool volumeOK = (not useVolumeFilter or (not na(relativeVolume) and relativeVolume >= volumeFactor))
bool adxOK = (not useADXFilter or (not na(adx) and adx >= minimumADX))
bool longDIOK = (not requireDIDirection or (not na(diPlus) and not na(diMinus) and diPlus > diMinus))
bool shortDIOK = (not requireDIDirection or (not na(diPlus) and not na(diMinus) and diMinus > diPlus))

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

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

// ============================================================================
// 25. BASE AND FILTERED SIGNALS
// ============================================================================
bool longBase = (longBreakoutEvent and longCandleOK and bodyOK and longCloseOK)
bool shortBase = (shortBreakoutEvent and shortCandleOK and bodyOK and shortCloseOK)
bool rawLong = (longBase and longTrendOK and volumeOK and adxOK and longDIOK and longH1OK)
bool rawShort = (shortBase and shortTrendOK and volumeOK and adxOK and shortDIOK and shortH1OK)

// ============================================================================
// 26. ENTRY GATES
// ============================================================================
bool canTrade = (barstate.isconfirmed and validChartResolution and orLocked and orWidthOK and flat and strategy.opentrades == 0 and tradesToday < maximumTradesPerDay and cooldownOK and freshEntryBar and entrySessionOK and beforeForceClose and breakoutTimeOK)
bool enterLong = (canTrade and allowLong and rawLong and not rawShort)
bool enterShort = (canTrade and allowShort and rawShort and not rawLong)

// ============================================================================
// 27. RISK IN TICKS
// ============================================================================
int slTicks = math.max(1, int(math.round(stopLossPoints / syminfo.mintick)))
int tpTicks = math.max(1, int(math.round(takeProfitPoints / syminfo.mintick)))
float effectiveSL = slTicks * syminfo.mintick
float effectiveTP = tpTicks * syminfo.mintick

// ============================================================================
// 28. DIAGNOSTICS COUNTERS
// ============================================================================
var int longBaseCount = 0
var int shortBaseCount = 0
var int filteredLongCount = 0
var int filteredShortCount = 0
var int blockedLongCount = 0
var int blockedShortCount = 0
var int longEntryCount = 0
var int shortEntryCount = 0

// ============================================================================
// 29. LONG ENTRY
// ============================================================================
if enterLong
    strategy.entry("Long", strategy.long, comment="ORB Re-entry LONG", alert_message="🟢 VÀO VỊ THẾ LONG (CNPS90)\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\n🛑 Cắt lỗ (SL): " + str.tostring(close - effectiveSL, format.mintick) + "\n💰 Chốt lời (TP): " + str.tostring(close + effectiveTP, format.mintick))
    tradesToday += 1
    longEntryCount += 1
    lastEntryBar := bar_index

// ============================================================================
// 30. SHORT ENTRY
// ============================================================================
if enterShort
    strategy.entry("Short", strategy.short, comment="ORB Re-entry SHORT", alert_message="🔴 VÀO VỊ THẾ SHORT (CNPS90)\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\n🛑 Cắt lỗ (SL): " + str.tostring(close + effectiveSL, format.mintick) + "\n💰 Chốt lời (TP): " + str.tostring(close - effectiveTP, format.mintick))
    tradesToday += 1
    shortEntryCount += 1
    lastEntryBar := bar_index

// ============================================================================
// 31. CONSUME BREAKOUT ATTEMPTS
// ============================================================================
if barstate.isconfirmed
    if longBreakoutEvent
        armedLong := false
        longAttemptsToday += 1
        totalLongAttempts += 1
    if shortBreakoutEvent
        armedShort := false
        shortAttemptsToday += 1
        totalShortAttempts += 1
    if longBase
        longBaseCount += 1
    if shortBase
        shortBaseCount += 1
    if rawLong
        filteredLongCount += 1
    if rawShort
        filteredShortCount += 1
    if rawLong and not enterLong
        blockedLongCount += 1
    if rawShort and not enterShort
        blockedShortCount += 1

// ============================================================================
// 32. RE-ARM AFTER RETURN INTO OR
// ============================================================================
//
// Price MUST close back inside the OR.
//
// Re-arm never happens on an outside candle.
// Optional margin makes re-arm more conservative.
//
// Both directions may be armed independently.
//
// ============================================================================
float rearmMargin = (useRearmMargin and not na(atr) ? atr * rearmMarginATR : 0.0)
bool priceInsideOR = (orLocked and not na(orHigh) and not na(orLow) and close < orHigh - rearmMargin and close > orLow + rearmMargin)
bool rearmedThisBar = false
if barstate.isconfirmed and orLocked
    if priceInsideOR
        consecutiveInsideBars += 1
    else
        consecutiveInsideBars := 0
    bool enoughInsideBars = (consecutiveInsideBars >= rearmInsideBars)
    if (allowReentry and enoughInsideBars and breakoutTimeOK and orWidthOK)
        if (not armedLong and longAttemptsToday < maximumAttemptsPerDirection)
            armedLong := true
            rearmedThisBar := true
        if (not armedShort and shortAttemptsToday < maximumAttemptsPerDirection)
            armedShort := true
            rearmedThisBar := true
    if rearmedThisBar
        totalRearms += 1

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

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

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

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

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

// ============================================================================
// 38. OPENING RANGE PLOTS
// ============================================================================
plot(showOpeningRange ? orHigh : na, title="Opening Range High", color=color.aqua, linewidth=2, style=plot.style_linebr)
plot(showOpeningRange ? orLow : na, title="Opening Range Low", color=color.fuchsia, linewidth=2, style=plot.style_linebr)
float orMidpoint = (not na(orHigh) and not na(orLow) ? (orHigh + orLow) / 2.0 : na)
plot(showORMidpoint ? orMidpoint : na, title="Opening Range Midpoint", color=color.gray, linewidth=1, style=plot.style_linebr)
bgcolor(showORBackground and insideOR ? color.new(color.blue, 92) : na, title="Opening Range Background")

// ============================================================================
// 39. OPTIONAL MARKERS
// ============================================================================
plotshape(showRawBreakoutMarkers and longBreakoutEvent, title="Long Breakout Attempt", style=shape.circle, location=location.belowbar, color=color.aqua, size=size.tiny, text="BO")
plotshape(showRawBreakoutMarkers and shortBreakoutEvent, title="Short Breakout Attempt", style=shape.circle, location=location.abovebar, color=color.orange, size=size.tiny, text="BO")
plotshape(showRearmMarkers and rearmedThisBar, title="ORB Re-armed", style=shape.circle, location=location.bottom, color=color.gray, size=size.tiny, text="RE")

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

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

// ============================================================================
// 42. DATA WINDOW
// ============================================================================
plot(orWidth, title="OR Width (Points)", color=color.blue, display=display.data_window)
plot(orWidthATR, title="OR Width / ATR", color=color.aqua, display=display.data_window)
plot(relativeVolume, title="Relative Volume", color=color.gray, display=display.data_window)
plot(bodyRatio, title="Breakout Body Ratio", color=color.orange, display=display.data_window)
plot(atr, title="ATR", color=color.gray, display=display.data_window)
plot(adx, title="ADX", color=color.purple, display=display.data_window)

// ============================================================================
// 43. DIAGNOSTICS
// ============================================================================
var table diagnostics = table.new(position.top_right, 2, 22, border_width=1)
if showDiagnostics and barstate.islast
    table.cell(diagnostics, 0, 0, "CNPS90 V2")
    table.cell(diagnostics, 1, 0, timeframe.period)
    table.cell(diagnostics, 0, 1, "OR Locked")
    table.cell(diagnostics, 1, 1, orLocked ? "YES" : "NO")
    table.cell(diagnostics, 0, 2, "OR Bars")
    table.cell(diagnostics, 1, 2, str.tostring(orBars))
    table.cell(diagnostics, 0, 3, "OR Width")
    table.cell(diagnostics, 1, 3, str.tostring(orWidth, "#.##"))
    table.cell(diagnostics, 0, 4, "OR Width / ATR")
    table.cell(diagnostics, 1, 4, str.tostring(orWidthATR, "#.##"))
    table.cell(diagnostics, 0, 5, "OR Valid")
    table.cell(diagnostics, 1, 5, orWidthOK ? "YES" : "NO")
    table.cell(diagnostics, 0, 6, "OR Days")
    table.cell(diagnostics, 1, 6, str.tostring(totalORDays))
    table.cell(diagnostics, 0, 7, "Rejected OR")
    table.cell(diagnostics, 1, 7, str.tostring(rejectedORDays))
    table.cell(diagnostics, 0, 8, "Long Attempts")
    table.cell(diagnostics, 1, 8, str.tostring(totalLongAttempts))
    table.cell(diagnostics, 0, 9, "Short Attempts")
    table.cell(diagnostics, 1, 9, str.tostring(totalShortAttempts))
    table.cell(diagnostics, 0, 10, "Re-arms")
    table.cell(diagnostics, 1, 10, str.tostring(totalRearms))
    table.cell(diagnostics, 0, 11, "Long Bases")
    table.cell(diagnostics, 1, 11, str.tostring(longBaseCount))
    table.cell(diagnostics, 0, 12, "Short Bases")
    table.cell(diagnostics, 1, 12, str.tostring(shortBaseCount))
    table.cell(diagnostics, 0, 13, "Filtered Long")
    table.cell(diagnostics, 1, 13, str.tostring(filteredLongCount))
    table.cell(diagnostics, 0, 14, "Filtered Short")
    table.cell(diagnostics, 1, 14, str.tostring(filteredShortCount))
    table.cell(diagnostics, 0, 15, "Blocked Long")
    table.cell(diagnostics, 1, 15, str.tostring(blockedLongCount))
    table.cell(diagnostics, 0, 16, "Blocked Short")
    table.cell(diagnostics, 1, 16, str.tostring(blockedShortCount))
    table.cell(diagnostics, 0, 17, "Long Entries")
    table.cell(diagnostics, 1, 17, str.tostring(longEntryCount))
    table.cell(diagnostics, 0, 18, "Short Entries")
    table.cell(diagnostics, 1, 18, str.tostring(shortEntryCount))
    table.cell(diagnostics, 0, 19, "Armed Long / Short")
    table.cell(diagnostics, 1, 19, (armedLong ? "Y" : "N") + " / " + (armedShort ? "Y" : "N"))
    table.cell(diagnostics, 0, 20, "Trades Today")
    table.cell(diagnostics, 1, 20, str.tostring(tradesToday) + "/" + str.tostring(maximumTradesPerDay))
    table.cell(diagnostics, 0, 21, "Position")
    table.cell(diagnostics, 1, 21, inLong ? "LONG" : inShort ? "SHORT" : "FLAT")

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

2.1. Xây dựng vùng Opening Range và kiểm định khung thời gian (Time Engine)

Bot kiểm tra chặt chẽ điều kiện biểu đồ trước khi tính toán vùng OR:

  • Biểu đồ phải là khung trong ngày (timeframe.isintraday), giờ kết thúc OR phải lớn hơn giờ bắt đầu (orEndMinutes > orStartMinutes), và chu kỳ nến của biểu đồ không được lớn hơn độ dài vùng OR (timeframe.in_seconds() <= (orEndMinutes - orStartMinutes) * 60). Với mặc định 09:00 – 09:15, bạn có thể chạy tốt trên các khung 1m, 3m, 5m, hoặc 15m.
  • Trong suốt khoảng insideOR, các nến đã đóng sẽ liên tục cập nhật orHigh = math.max(orHigh, high) và orLow = math.min(orLow, low). Khi nến đầu tiên sau 09:15 đóng cửa (afterOR), vùng OR được khóa cứng (orLocked := true) và tính orWidth = orHigh - orLow, orWidthATR = orWidth / ta.atr(14). Nếu bật useORWidthFilter, orWidthATR phải nằm trong [0.20, 6.00].

2.2. Mức phá vỡ có đệm ATR và xác nhận chất lượng nến

Thay vì kích hoạt ngay khi giá chạm orHigh hoặc orLow, CNPS90 V2 cộng thêm khoảng đệm biến động breakoutBuffer = atr * breakoutBufferATR (mặc định 0.05 × ATR(14)):

  • longBreakLevel = orHigh + breakoutBuffer
  • shortBreakLevel = orLow - breakoutBuffer

Đồng thời, nến phá vỡ được đánh giá chất lượng qua 3 thước đo:

  • Hướng nến: Long yêu cầu close > open, Short yêu cầu close < open.
  • Tỷ lệ thân nến (bodyRatio): |close - open| / (high - low) ≥ 0.35, đảm bảo lực đẩy dứt khoát thay vì nến Doji râu dài.
  • Vị trí đóng cửa (closePosition): (close - low) / (high - low). Nếu bật useCloseLocation, nến Long cần đóng ở phần trên (≥ 0.65) và nến Short cần đóng ở phần dưới (≤ 0.35).

2.3. Cơ chế Consume & Re-arm và bộ lọc xu hướng/động lượng

Điểm khác biệt lớn nhất của CNPS90 V2 là vòng đời trạng thái armedLong / armedShort:

  • Ngay khi xảy ra longBreakoutEvent hoặc shortBreakoutEvent, hướng tương ứng bị tiêu thụ (armedLong := false / armedShort := false) bất kể lệnh có bị chặn bởi các bộ lọc phụ hay không.
  • Để được nạp lại (rearmedThisBar), giá bắt buộc phải đóng cửa quay vào bên trong vùng OR (close < orHigh - rearmMargin và close > orLow + rearmMargin) đủ rearmInsideBars nến liên tiếp.

Ngoài ra, bot cung cấp các bộ lọc tùy chọn (mặc định tắt để giữ sự tinh gọn):

  • EMA Trend: Kiểm tra độ dốc ema > ema[3] (hoặc < cho Short) với EMA(50) và tùy chọn giá nằm trên/dưới EMA.
  • Relative Volume: volume / ta.sma(volume[1], 20) ≥ 1.0.
  • ADX / DI: ADX(14, 14) ≥ 18.0 và tùy chọn DI+ > DI- / DI- > DI+.
  • Confirmed H1 Bias: Dùng request.security(..., "60", ...[1], lookahead=barmerge.lookahead_on) để lấy close[1] và EMA(50)[1] của nến H1 đã đóng hoàn chỉnh (chỉ áp dụng trên khung nhỏ hơn H1).

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

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

  1. Khởi tạo đầu ngày (newDay): Reset toàn bộ biến trạng thái trong ngày gồm tradesToday = 0, orHigh/orLow = na, orLocked = false, armedLong/armedShort = false, longAttemptsToday/shortAttemptsToday = 0, consecutiveInsideBars = 0.
  2. Xây dựng & Khóa Opening Range: Thu thập biên độ giá trong khung 09:00 – 09:15. Sau 09:15, khóa orHigh/orLow, kiểm tra orWidthOK, và kích hoạt armedLong = true, armedShort = true.
  3. Phát hiện phá vỡ & Tiêu thụ lượt thử: Khi giá đóng cửa cắt qua longBreakLevel (từ dưới lên) hoặc shortBreakLevel (từ trên xuống) trong thời gian breakoutTimeOK (≤ 300 phút sau OR), sự kiện phá vỡ được ghi nhận và trạng thái armed của chiều đó lập tức chuyển về false.
  4. Xác nhận bộ lọc & Gửi lệnh: Tín hiệu đi qua lớp xác nhận nến (longBase/shortBase), các bộ lọc xu hướng/khối lượng (rawLong/rawShort), và cổng kiểm soát giao dịch (canTrade). Nếu thỏa mãn và không xung đột hai chiều, bot gửi lệnh strategy.entry.
  5. Quản trị & Tái nạp đạn: Trong khi nắm giữ vị thế, lệnh strategy.exit tự động đặt SL/TP theo tick. Song song đó, nếu giá quay đầu đóng cửa vào trong vùng OR đủ số nến quy định và chưa hết lượt thử trong ngày, bot sẽ nạp lại trạng thái armed để sẵn sàng cho nhịp phá vỡ tiếp theo. Cuối phiên lúc 14:45, mọi vị thế mở sẽ bị đóng tự động.

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

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

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

  • Biểu đồ cho phép giao dịch chiều Long (tradeDirection là "Long" hoặc "Both" — lưu ý mặc định trong code là "Long").
  • Xuất hiện longBreakoutEvent: Vùng OR đã khóa (orLocked), độ rộng hợp lệ (orWidthOK), còn trong thời gian phá vỡ (breakoutTimeOK), đang ở trạng thái sẵn sàng (armedLong), số lần thử Long trong ngày < maximumAttemptsPerDirection (3), và giá đóng cửa cắt lên mức đệm: close > longBreakLevel với close[1] <= longBreakLevel.
  • Thỏa mãn xác nhận nến (longBase): Nến tăng (close > open, nếu bật requireCandleDirection), tỷ lệ thân nến bodyRatio ≥ 0.35 (nếu bật useBodyFilter), và vị trí đóng cửa closePosition ≥ 0.65 (nếu bật useCloseLocation).
  • Thỏa mãn các bộ lọc tùy chọn đang bật (rawLong): EMA dốc lên (longTrendOK), khối lượng tương đối đạt chuẩn (volumeOK), ADX đạt ngưỡng (adxOK), DI+ > DI- (longDIOK), và giá H1 trên EMA H1 (longH1OK).
  • Không đồng thời xuất hiện tín hiệu rawShort (not rawShort) và vượt qua toàn bộ cổng kiểm soát canTrade.

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

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

  • Biểu đồ cho phép giao dịch chiều Short (tradeDirection là "Short" hoặc "Both").
  • Xuất hiện shortBreakoutEvent: Vùng OR đã khóa, độ rộng hợp lệ, còn trong breakoutTimeOK, đang sẵn sàng (armedShort), shortAttemptsToday < 3, và giá đóng cửa cắt xuống dưới mức đệm: close < shortBreakLevel với close[1] >= shortBreakLevel.
  • Thỏa mãn xác nhận nến (shortBase): Nến giảm (close < open, nếu bật requireCandleDirection), bodyRatio ≥ 0.35 (nếu bật useBodyFilter), và closePosition ≤ 0.35 (nếu bật useCloseLocation).
  • Thỏa mãn các bộ lọc tùy chọn đang bật (rawShort): EMA dốc xuống (shortTrendOK), volumeOK, adxOK, DI- > DI+ (shortDIOK), và giá H1 dưới EMA H1 (shortH1OK).
  • Không đồng thời xuất hiện tín hiệu rawLong (not rawLong) và vượt qua cổng kiểm soát canTrade.

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

Mọi lệnh vào mới đều phải vượt qua hàng rào kiểm soát canTrade:

  • Không nhồi lệnh: Vị thế hiện tại phải phẳng (strategy.position_size == 0 và strategy.opentrades == 0), đồng thời không vào 2 lệnh trên cùng một cây nến (freshEntryBar).
  • Giới hạn tần suất ngày: tradesToday < maximumTradesPerDay (mặc định tối đa 3 lệnh/ngày).
  • Thời gian nghỉ (Cooldown): Số nến kể từ lần thoát lệnh gần nhất phải lớn hơn cooldownBars (bar_index - lastExitBar > 1).
  • Khung giờ giao dịch: Nếu bật useSessionFilter, nến phải nằm trong khung 09:15 – 14:15 (entrySessionOK), trước giờ đóng phiên 14:45 (beforeForceClose), và không vượt quá maximumBreakoutMinutes (300 phút sau 09:15).

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

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

CNPS90 V2 sử dụng mức cắt lỗ và chốt lời cố định theo điểm số, sau đó làm tròn và quy đổi chính xác sang đơn vị tick nhỏ nhất của sản phẩm (syminfo.mintick, với VN30F1M là 0.1 điểm):

  • slTicks = math.max(1, int(math.round(stopLossPoints / syminfo.mintick))) → Mặc định 5.0 / 0.1 = 50 ticks (effectiveSL = 5.0 điểm).
  • tpTicks = math.max(1, int(math.round(takeProfitPoints / syminfo.mintick))) → Mặc định 15.0 / 0.1 = 150 ticks (effectiveTP = 15.0 điểm).

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

Bot không sử dụng cơ chế dời hòa vốn (Break Even) hay Trailing Stop, mà quản trị vị thế bằng 3 cơ chế thoát lệnh độc lập và dứt khoát:

  • Chốt lời / Cắt lỗ cố định (strategy.exit): Đặt ngay lập tức cho lệnh "Long" và "Short" với khoảng cách tpTicks và slTicks tính từ giá khớp trung bình strategy.position_avg_price.
  • Thoát lệnh theo thời gian (Time Exit): Nếu bật useTimeExit, khi số nến nắm giữ vị thế barsHeld >= maximumHoldingBars (mặc định 20 nến) trên nến đã đóng (và chưa tới nến đóng phiên), bot gọi strategy.close_all(immediately=true) để giải phóng vốn khỏi các nhịp đi ngang kéo dài.
  • Tất toán cuối phiên (Session Force Close): Tại cây nến chạm mốc 14:45 (openMinutes < forceCloseMinutes và closeMinutes >= forceCloseMinutes), nếu vẫn còn vị thế mở, bot tự động đóng toàn bộ trước phiên ATC.

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

Cơ chế thoát lệnhĐiều kiện kích hoạtHành động trong codeTham số mặc định
Stop Loss cố địnhGiá chạm mức lỗ slTicks từ giá vào trung bìnhstrategy.exit(..., loss=slTicks)5.0 điểm (50 ticks)
Take Profit cố địnhGiá chạm mức lời tpTicks từ giá vào trung bìnhstrategy.exit(..., profit=tpTicks)15.0 điểm (150 ticks)
Time Exit (tùy chọn)Bật useTimeExit và giữ lệnh ≥ maximumHoldingBars nếnstrategy.close_all(immediately=true)false / 20 nến
Session Force CloseNến đóng qua mốc 14:45 khi vẫn còn vị thếstrategy.close_all(immediately=true)14:45 (Asia/Ho_Chi_Minh)

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

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

  1. Mở biểu đồ hợp đồng tương lai VN30F1M trên TradingView, chọn khung thời gian phù hợp (khuyến nghị 1m, 3m hoặc 5m, bắt buộc ≤ 15m để xây dựng vùng OR 09:00 – 09:15).
  2. Nhấn vào tab Pine Editor ở phía dưới màn hình, xóa code mẫu mặc định.
  3. Sao chép toàn bộ mã nguồn Pine Script v6 ở Mục 1 và dán vào Pine Editor.
  4. Nhấn Save để lưu script, sau đó nhấn Add to chart để gắn bot lên biểu đồ.
  5. Mở phần Settings (Cài đặt) của chiến lược để kiểm tra thông số Trade Direction (mặc định đang để "Long", hãy chuyển sang "Both" nếu muốn giao dịch cả hai chiều Long và Short) và bật Show Diagnostics nếu cần theo dõi thông số thống kê.

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

Khi bật tùy chọn Show Diagnostics = true, bảng diagnostics gồm 22 dòng sẽ hiển thị ở góc trên bên phải biểu đồ (position.top_right):

Dòng hiển thịÝ nghĩa thực tế trong code
CNPS90 V2Tên bot và khung thời gian hiện tại của biểu đồ (timeframe.period).
OR Locked / OR BarsTrạng thái vùng OR đã khóa (YES/NO) và số lượng nến hình thành vùng OR.
OR Width / OR Width / ATRĐộ rộng vùng OR tính bằng điểm và tỷ lệ so với ATR(14).
OR ValidKết quả kiểm tra độ rộng OR có hợp lệ hay không (YES/NO).
OR Days / Rejected ORTổng số ngày có vùng OR và số ngày bị loại do không đạt bộ lọc độ rộng.
Long Attempts / Short AttemptsTổng số lần thử phá vỡ lên và xuống trên toàn bộ dữ liệu kiểm thử.
Re-armsTổng số lần bot nạp lại trạng thái sẵn sàng sau khi giá đóng cửa quay vào OR.
Long Bases / Short BasesSố tín hiệu đạt điều kiện phá vỡ + xác nhận nến trước khi qua bộ lọc phụ.
Filtered Long / Filtered ShortSố tín hiệu vượt qua tất cả bộ lọc (EMA, Volume, ADX, H1 Bias).
Blocked Long / Blocked ShortSố tín hiệu hợp lệ nhưng bị chặn bởi cổng kiểm soát (canTrade như hết lượt ngày, cooldown, ngoài giờ).
Long Entries / Short EntriesTổng số lệnh Long và Short thực tế đã vào.
Armed Long / ShortTrạng thái sẵn sàng hiện tại của hai chiều (Y hoặc N).
Trades TodaySố lệnh đã vào trong ngày hiện tại trên tổng giới hạn (tradesToday/maximumTradesPerDay).
PositionTrạng thái vị thế hiện tại (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ín hiệu giao dịch tự động hoặc kết nối Webhook đặt lệnh, bạn thực hiện theo các bước sau:

  1. Trên thanh công cụ biểu đồ TradingView, nhấn vào biểu tượng Alert (Đồng hồ báo thức) hoặc nhấn tổ hợp phím Alt + A.
  2. Ở mục Condition, chọn chiến lược CNPS90 OPENING RANGE BREAKOUT V2.
  3. Ở phần Message, xóa nội dung mặc định và nhập duy nhất biến: {{strategy.order.alert_message}}.
  4. Thiết lập kênh nhận thông báo (Ứng dụng TradingView, Email, hoặc Webhook URL) và nhấn Create.
  5. Nếu muốn tắt riêng cảnh báo khi chạm SL/TP và chỉ nhận cảnh báo vào lệnh / đóng phiên, hãy tick chọn Disable SL / TP Alerts (disableExitAlerts = true) trong cài đặt bot.

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

Loại sự kiệnHành độngNội dung thông điệp (alert_message / alert_profit / alert_loss)
Vào lệnh Longstrategy.entry("Long", ...)🟢 VÀO VỊ THẾ LONG (CNPS90) kèm Giá vào, Cắt lỗ (SL), Chốt lời (TP).
Vào lệnh Shortstrategy.entry("Short", ...)🔴 VÀO VỊ THẾ SHORT (CNPS90) kèm Giá vào, Cắt lỗ (SL), Chốt lời (TP).
Chốt lời Long / Shortstrategy.exit (alert_profit)💰 CHỐT LỜI LONG/SHORT (CNPS90 - TP HIT) kèm Giá chốt lời.
Cắt lỗ Long / Shortstrategy.exit (alert_loss)🛑 CẮT LỖ LONG/SHORT (CNPS90 - SL HIT) kèm Giá cắt lỗ.
Hết thời gian giữ lệnhstrategy.close_all (Time Exit)⏱️ ĐÓNG VỊ THẾ HẾT THỜI GIAN (CNPS90 - Time Exit) kèm Giá đóng.
Đóng vị thế cuối phiênstrategy.close_all (Session End)⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (CNPS90 - Session End) kèm Giá đóng.

Kết luận

CNPS90 Opening Range Breakout V2 là một hệ thống giao dịch ORB hiện đại, giải quyết tốt điểm yếu cố hữu của chiến lược phá vỡ thông thường nhờ cơ chế Consume & Re-arm: hạn chế vào lệnh đuổi khi giá đã đi xa ngoài biên độ mở cửa, đồng thời không bỏ lỡ cơ hội nếu giá quay lại vùng cân bằng và bứt phá lần nữa. Với cấu trúc SL/TP cố định tỷ lệ 1:3 mặc định, lọc nến rõ ràng và đóng lệnh trước ATC lúc 14:45, bot đặc biệt phù hợp với các phiên thị trường có xu hướng rõ ràng sau giai đoạn tích lũy đầu ngày.

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

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

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

Đinh Mạnh Đạt

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

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

Giao dịch & cuộc sống

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