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

Hướng Dẫn Sử Dụng Bot CNPS98 - NR7 Range Expansion V1 cho VN30F1M

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

Trong giao dịch phái sinh VN30F1M, thị trường thường xuyên trải qua các giai đoạn tích lũy biên độ hẹp (volatility contraction) trước khi bùng nổ theo một hướng rõ ràng (range expansion). Việc vào lệnh quá sớm khi giá đang đi ngang dễ dẫn đến quét Stop Loss liên tục, trong khi vào muộn lại mất lợi thế tỷ lệ Risk:Reward.

Chiến lược CNPS98 NR7 RANGE EXPANSION V1 (tên rút gọn: CNPS98 NR7 EXP), được viết bằng Pine Script v6 trên nền tảng TradingView, giải quyết trực tiếp bài toán này bằng cách tự động nhận diện cây nến có biên độ hẹp nhất trong chuỗi N phiên gần nhất (NR7), lưu lại vùng High/Low làm ranh giới và chỉ kích hoạt lệnh khi có xác nhận bứt phá hoặc kiểm tra lại (Retest) lúc đóng nến.

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

  • Cỗ máy trạng thái NR7 (State Machine 4 giai đoạn): Quản lý chặt chẽ từ lúc phát hiện nến nén NR7, chờ bứt phá trong cửa sổ breakoutWindow đến bước chờ Retest hoặc hủy bỏ khi hết hạn.
  • Hai chế độ vào lệnh linh hoạt: Hỗ trợ vào lệnh ngay khi nến đóng cửa bứt phá (Breakout Close) hoặc chờ giá quay lại kiểm tra biên bị phá (Breakout + Retest).
  • Hệ thống bộ lọc đa tầng tùy chọn: Tích hợp bộ lọc sức mạnh thân nến (Body Ratio), vị trí đóng cửa (Close Position), xu hướng EMA, khối lượng tương đối (Relative Volume), động lượng ADX/RSI và xu hướng khung H1.
  • Quản trị rủi ro kỷ luật: Thiết lập Stop Loss/Take Profit theo điểm chuẩn xác theo tick, giới hạn số lệnh trong ngày, khoảng nghỉ sau thoát lệnh (Cooldown) và tự động đóng toàn bộ vị thế trước giờ đóng cửa phiên (14:45).

1. CNPS98 NR7 Range Expansion V1 là gì?

CNPS98 NR7 Range Expansion V1 là hệ thống giao dịch tự động theo mô hình nén biến động và mở rộng biên độ (Volatility Contraction & Range Expansion) trên khung thời gian Intraday của VN30F1M. Chiến lược được xây dựng dựa trên 4 trụ cột kỹ thuật chính:

  1. Nhận diện vùng nén biến động (NR7 Detection): Xác định cây nến hoàn thành có biên độ High - Low hẹp nhất so với nrLength - 1 nến liền trước (mặc định 7 nến), có thể kết hợp thêm điều kiện nén theo ATR hoặc mô hình Inside Bar.
  2. Động cơ bứt phá và Retest (Breakout & Retest Engine): Theo dõi giá đóng cửa vượt qua nrHigh + breakoutBuffer (Long) hoặc phá xuống dưới nrLow - breakoutBuffer (Short) kèm bộ lọc thân nến. Ở chế độ Breakout + Retest, bot chờ giá quay lại chạm vùng biên đã phá trong phạm vi sai số và đóng nến thuận chiều bứt phá.
  3. Bộ lọc xu hướng và động lượng đa chiều: Cho phép bật/tắt độc lập các lớp lọc gồm EMA 50 (cùng độ dốc EMA), Relative Volume, ADX/DI, RSI và Confirmed H1 EMA Bias (sử dụng dữ liệu nến H1 đã đóng cửa để tránh repaint).
  4. Kiểm soát phiên và bảo vệ vị thế: Giới hạn khung giờ vào lệnh (09:15 - 14:15), giới hạn số lệnh/ngày, kiểm soát giãn cách lệnh, thoát lệnh theo SL/TP cố định, thoát lệnh theo thời gian nắm giữ (Time Exit) và ép đóng cuối phiên (14:45).

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

Nhóm thông sốBiến trong codeMô tảGiá trị mặc định
01. NR7 SetupnrLengthSố nến nhìn lại tìm biên độ hẹp nhất7
breakoutWindowSố nến tối đa chờ breakout sau NR75
requireStrictNRYêu cầu biên độ nhỏ hơn tuyệt đốifalse
useCompressionFilterBật bộ lọc nén theo ATRfalse (ATR=14, max=0.70)
useNRInsideBarYêu cầu nến NR7 nằm trong nến trướcfalse
02. BreakoutentryModeChế độ vào lệnh"Breakout Close"
breakoutBufferATRVùng đệm bứt phá theo ATR0.0
requireDirectionalCandleYêu cầu nến breakout đúng chiềutrue
useBodyFilterBật bộ lọc tỷ lệ thân nếntrue (min=0.30)
useCloseLocationBật bộ lọc vị trí đóng cửafalse (Long>=0.60, Short<=0.40)
03. Breakout RetestretestWindowSố nến tối đa chờ retest5
retestToleranceATRSai số chạm vùng retest theo ATR0.20
retestInvalidationATRNgưỡng hủy retest theo ATR0.20
requireRetestDirectionYêu cầu nến retest đúng chiềutrue
04. EMA TrenduseEMAFilterBật bộ lọc xu hướng EMAfalse (len=50, slopeBars=3)
05. VolumeuseVolumeFilterBật bộ lọc khối lượng tương đốifalse (MA=20, factor=1.0)
06. MomentumuseADXFilter / useRSIFilterBật bộ lọc ADX / RSIfalse (ADX>=18, RSI 52/48)
07. H1 BiasuseH1BiasBật bộ lọc xu hướng H1 EMAfalse (h1EMALength=50)
08. Risk ManagementstopLossPointsMức cắt lỗ cố định (điểm)5.0
takeProfitPointsMức chốt lời cố định (điểm)15.0
useTimeExitThoát lệnh theo số nến nắm giữfalse (max=20 nến)
09. Trade ControltradeDirectionChiều giao dịch cho phép"Both"
contractsSố hợp đồng khai báo3 (mặc định lệnh dùng default_qty_value=1)
maximumTradesPerDaySố lệnh tối đa mỗi ngày4
cooldownBars / minimumBarsBetweenEntriesNghỉ sau thoát / Giãn cách vào lệnh1 nến / 2 nến
10. Trading SessiontzMúi giờ giao dịch"Asia/Ho_Chi_Minh"
useSessionFilterLọc phiên vào lệnhtrue (09:15 – 14:15)
endHour / endMinuteGiờ ép đóng toàn bộ vị thế14:45

Source Code CNPS98 NR7 Range Expansion V1

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

//@version=6
strategy(title="CNPS98 NR7 RANGE EXPANSION V1", shorttitle="CNPS98 NR7 EXP", 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)

// ============================================================================
// CNPS98 - NR7 RANGE EXPANSION V1
//
// NR7 = Narrowest High-Low Range in N Bars.
//
// SETUP:
// 1. Detect a completed NR7 candle.
// 2. Store its High / Low.
// 3. Wait for a confirmed breakout.
// 4. Enter immediately or wait for a retest.
//
// LONG:
// Close > NR7 High + Breakout Buffer.
//
// SHORT:
// Close < NR7 Low - Breakout Buffer.
//
// RETEST MODE:
// After breakout, wait for price to revisit
// the broken boundary and close on its
// breakout side.
//
// No future pivots.
// Entries are confirmed at bar close.
// ============================================================================
// ============================================================================
// 01. NR7 SETUP
// ============================================================================
gNR = "01. NR7 Setup"
nrLength = input.int(7, "Narrow Range Lookback", minval=3, maxval=50, group=gNR)
breakoutWindow = input.int(5, "Maximum Bars After NR7", minval=1, maxval=50, group=gNR)
requireStrictNR = input.bool(false, "Require Strictly Smallest Range", group=gNR)
useCompressionFilter = input.bool(false, "Use ATR Compression Filter", group=gNR)
atrLength = input.int(14, "ATR Length", minval=1, group=gNR)
maximumNRRangeATR = input.float(0.70, "Maximum NR7 Range / ATR", minval=0.05, maxval=3.0, step=0.05, group=gNR)
useNRInsideBar = input.bool(false, "Require NR7 Inside Previous Bar", group=gNR)

// ============================================================================
// 02. BREAKOUT ENGINE
// ============================================================================
gBO = "02. Breakout"
entryMode = input.string("Breakout Close", "Entry Mode", options=["Breakout Close", "Breakout + Retest"], group=gBO)
breakoutBufferATR = input.float(0.0, "Breakout Buffer / ATR", minval=0.0, maxval=2.0, step=0.05, group=gBO)
requireDirectionalCandle = input.bool(true, "Require Bullish/Bearish Breakout", group=gBO)
useBodyFilter = input.bool(true, "Use Body Strength Filter", group=gBO)
minimumBodyRatio = input.float(0.30, "Minimum Body / Candle Range", minval=0.0, maxval=1.0, step=0.05, group=gBO)
useCloseLocation = input.bool(false, "Use Close Position Filter", group=gBO)
minimumLongClose = input.float(0.60, "Minimum Long Close Position", minval=0.0, maxval=1.0, step=0.05, group=gBO)
maximumShortClose = input.float(0.40, "Maximum Short Close Position", minval=0.0, maxval=1.0, step=0.05, group=gBO)

// ============================================================================
// 03. RETEST MODE
// ============================================================================
gRetest = "03. Breakout Retest"
retestWindow = input.int(5, "Maximum Retest Bars", minval=1, maxval=30, group=gRetest)
retestToleranceATR = input.float(0.20, "Retest Touch Tolerance / ATR", minval=0.0, maxval=2.0, step=0.05, group=gRetest)
retestInvalidationATR = input.float(0.20, "Retest Invalidation / ATR", minval=0.0, maxval=2.0, step=0.05, group=gRetest)
requireRetestDirection = input.bool(true, "Require Directional Retest Candle", group=gRetest)

// ============================================================================
// 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, maxval=300, group=gTrend)
useEMASlope = input.bool(true, "Require EMA Slope", group=gTrend)
emaSlopeBars = input.int(3, "EMA Slope Lookback", minval=1, maxval=50, group=gTrend)
requirePriceEMA = input.bool(true, "Require Price Above/Below EMA", group=gTrend)

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

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

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

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

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

// ============================================================================
// 10. TRADING SESSION
// ============================================================================
gSession = "10. Trading Session"
tz = input.string("Asia/Ho_Chi_Minh", "Timezone", group=gSession)
useSessionFilter = input.bool(true, "Use Entry Session Filter", group=gSession)
startHour = input.int(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)

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

// ============================================================================
// 12. DISPLAY
// ============================================================================
gDisplay = "12. Display"
showNRLevels = input.bool(true, "Show Active NR7 Levels", group=gDisplay)
showNRMarkers = input.bool(false, "Show NR7 Setup Markers", group=gDisplay)
showBreakoutMarkers = input.bool(false, "Show Breakout Markers", group=gDisplay)
showRetestLevel = input.bool(true, "Show Pending Retest Level", group=gDisplay)
showEMA = input.bool(true, "Show EMA", group=gDisplay)
showEntryMarkers = input.bool(true, "Show Entry Markers", group=gDisplay)
showSLTP = input.bool(true, "Show Active SL/TP", group=gDisplay)
showDiagnostics = input.bool(false, "Show Diagnostics", group=gDisplay)

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

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

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

// ============================================================================
// 16. NR7 DETECTION
// ============================================================================
//
// The current candle is evaluated only
// after its close.
//
// "Strict" requires its range to be smaller
// than every previous range in the lookback.
//
// Non-strict allows equal minimum ranges.
//
// ============================================================================
float currentRange = high - low
float previousMinimumRange = ta.lowest(currentRange[1], nrLength - 1)
bool strictNarrowRange = (not na(previousMinimumRange) and currentRange < previousMinimumRange)
bool inclusiveNarrowRange = (not na(previousMinimumRange) and currentRange <= previousMinimumRange)
bool nrRangeOK = (requireStrictNR ? strictNarrowRange : inclusiveNarrowRange)
float nrRangeATR = (not na(atr) and atr > 0 ? currentRange / atr : na)
bool compressionOK = (not useCompressionFilter or (not na(nrRangeATR) and nrRangeATR <= maximumNRRangeATR))
bool insideBarOK = (not useNRInsideBar or (high <= high[1] and low >= low[1]))
bool detectedNR7 = (barstate.isconfirmed and intradayOK and currentRange > 0 and nrRangeOK and compressionOK and insideBarOK)

// ============================================================================
// 17. CANDLE STRENGTH
// ============================================================================
float candleBody = math.abs(close - open)
float bodyRatio = (currentRange > 0 ? candleBody / currentRange : 0.0)
float closePosition = (currentRange > 0 ? (close - low) / currentRange : 0.5)
bool bullishCandle = close > open
bool bearishCandle = close < open
bool bodyOK = (not useBodyFilter or bodyRatio >= minimumBodyRatio)
bool longCandleOK = ((not requireDirectionalCandle or bullishCandle) and bodyOK and (not useCloseLocation or closePosition >= minimumLongClose))
bool shortCandleOK = ((not requireDirectionalCandle or bearishCandle) and bodyOK and (not useCloseLocation or closePosition <= maximumShortClose))

// ============================================================================
// 18. EMA FILTER
// ============================================================================
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 ((not useEMASlope or emaUp) and (not requirePriceEMA or close > ema)))
bool shortTrendOK = (not useEMAFilter or ((not useEMASlope or emaDown) and (not requirePriceEMA or close < ema)))

// ============================================================================
// 19. MOMENTUM FILTERS
// ============================================================================
bool volumeOK = (not useVolumeFilter or (not na(relativeVolume) and relativeVolume >= minimumVolumeFactor))
bool adxOK = (not useADXFilter or (not na(adx) and adx >= minimumADX))
bool longDIOK = (not requireDIDirection or diPlus > diMinus)
bool shortDIOK = (not requireDIDirection or diMinus > diPlus)
bool longRSIOK = (not useRSIFilter or (not na(rsi) and rsi >= minimumLongRSI))
bool shortRSIOK = (not useRSIFilter or (not na(rsi) and rsi <= maximumShortRSI))

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

// ============================================================================
// 21. 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 spacingOK = (na(lastEntryBar) or bar_index - lastEntryBar > minimumBarsBetweenEntries)

// ============================================================================
// 22. NR7 STATE MACHINE
// ============================================================================
//
// Stage 0 = No setup
// Stage 1 = Waiting for breakout
// Stage 2 = Waiting for LONG retest
// Stage 3 = Waiting for SHORT retest
//
// A newly detected NR7 is registered AFTER
// the previous setup's signal is evaluated.
//
// ============================================================================
var int setupStage = 0
var float nrHigh = na
var float nrLow = na
var int nrBar = na
var int nrDay = na
var float retestLevel = na
var float retestATR = na
var int breakoutBar = na
var int totalNR7 = 0
var int totalBreakouts = 0
var int longBreakoutCount = 0
var int shortBreakoutCount = 0
var int longRetestCount = 0
var int shortRetestCount = 0
var int expiredNRCount = 0
var int expiredRetestCount = 0
var int rawLongCount = 0
var int rawShortCount = 0
var int filteredLongCount = 0
var int filteredShortCount = 0
var int blockedLongCount = 0
var int blockedShortCount = 0
var int longEntryCount = 0
var int shortEntryCount = 0
var int timeExitCount = 0
var int sessionExitCount = 0
if newDay
    setupStage := 0
    nrHigh := na
    nrLow := na
    nrBar := na
    nrDay := na
    retestLevel := na
    retestATR := na
    breakoutBar := na

// ============================================================================
// 23. BREAKOUT LEVELS
// ============================================================================
float breakoutBuffer = (not na(atr) ? atr * breakoutBufferATR : 0.0)
float longBreakLevel = (setupStage == 1 ? nrHigh + breakoutBuffer : na)
float shortBreakLevel = (setupStage == 1 ? nrLow - breakoutBuffer : na)

// ============================================================================
// 24. SETUP EXPIRATION
// ============================================================================
bool nrWindowOK = (setupStage == 1 and nrDay == dayKey and not na(nrBar) and bar_index > nrBar and bar_index - nrBar <= breakoutWindow)
bool retestWindowOK = ((setupStage == 2 or setupStage == 3) and not na(breakoutBar) and bar_index > breakoutBar and bar_index - breakoutBar <= retestWindow)

// ============================================================================
// 25. BREAKOUT SIGNALS
// ============================================================================
bool longBreakout = (barstate.isconfirmed and nrWindowOK and not na(longBreakLevel) and close > longBreakLevel and longCandleOK)
bool shortBreakout = (barstate.isconfirmed and nrWindowOK and not na(shortBreakLevel) and close < shortBreakLevel and shortCandleOK)

// ============================================================================
// 26. RETEST SIGNALS
// ============================================================================
float retestTolerance = (not na(retestATR) ? retestATR * retestToleranceATR : 0.0)
float retestInvalidation = (not na(retestATR) ? retestATR * retestInvalidationATR : 0.0)
bool longRetest = (barstate.isconfirmed and setupStage == 2 and retestWindowOK and not na(retestLevel) and low <= retestLevel + retestTolerance and close > retestLevel and (not requireRetestDirection or bullishCandle))
bool shortRetest = (barstate.isconfirmed and setupStage == 3 and retestWindowOK and not na(retestLevel) and high >= retestLevel - retestTolerance and close < retestLevel and (not requireRetestDirection or bearishCandle))

// ============================================================================
// 27. ENTRY MODE SELECTION
// ============================================================================
bool retestMode = (entryMode == "Breakout + Retest")
bool longBase = (retestMode ? longRetest : longBreakout)
bool shortBase = (retestMode ? shortRetest : shortBreakout)

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

// ============================================================================
// 29. ENTRY GATE
// ============================================================================
bool canTrade = (barstate.isconfirmed and intradayOK and flat and strategy.opentrades == 0 and tradesToday < maximumTradesPerDay and cooldownOK and spacingOK and entrySessionOK and beforeForceClose)
bool enterLong = (canTrade and allowLong and rawLong and not rawShort)
bool enterShort = (canTrade and allowShort and rawShort and not rawLong)

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

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

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

// ============================================================================
// 33. SETUP STATE UPDATE
// ============================================================================
//
// Process current signals before registering
// a new setup.
//
// A new NR7 cannot cause an entry on its
// own formation candle.
//
// ============================================================================
if barstate.isconfirmed
    if longBase
        rawLongCount += 1
    if shortBase
        rawShortCount += 1
    if rawLong
        filteredLongCount += 1
    if rawShort
        filteredShortCount += 1
    if rawLong and not enterLong
        blockedLongCount += 1
    if rawShort and not enterShort
        blockedShortCount += 1

    // --------------------------------------------------------
    // EXPIRE NR7 SETUP
    // --------------------------------------------------------
    bool nrExpired = (setupStage == 1 and not na(nrBar) and (nrDay != dayKey or bar_index - nrBar > breakoutWindow))
    if nrExpired
        setupStage := 0
        expiredNRCount += 1

    // --------------------------------------------------------
    // EXPIRE / INVALIDATE RETEST
    // --------------------------------------------------------
    bool retestExpired = ((setupStage == 2 or setupStage == 3) and not na(breakoutBar) and bar_index - breakoutBar > retestWindow)
    bool invalidLongRetest = (setupStage == 2 and not na(retestLevel) and close < retestLevel - retestInvalidation)
    bool invalidShortRetest = (setupStage == 3 and not na(retestLevel) and close > retestLevel + retestInvalidation)
    if (retestExpired or invalidLongRetest or invalidShortRetest)
        setupStage := 0
        expiredRetestCount += 1

    // --------------------------------------------------------
    // HANDLE LONG BREAKOUT
    // --------------------------------------------------------
    if longBreakout
        totalBreakouts += 1
        longBreakoutCount += 1
        if retestMode and allowLong
            setupStage := 2
            breakoutBar := bar_index
            retestLevel := nrHigh
            retestATR := atr
        else
            setupStage := 0

    // --------------------------------------------------------
    // HANDLE SHORT BREAKOUT
    // --------------------------------------------------------
    if shortBreakout
        totalBreakouts += 1
        shortBreakoutCount += 1
        if retestMode and allowShort
            setupStage := 3
            breakoutBar := bar_index
            retestLevel := nrLow
            retestATR := atr
        else
            setupStage := 0

    // --------------------------------------------------------
    // CONSUME RETEST SETUPS
    // --------------------------------------------------------
    if longRetest
        longRetestCount += 1
        setupStage := 0
    if shortRetest
        shortRetestCount += 1
        setupStage := 0

    // --------------------------------------------------------
    // REGISTER NEW NR7
    // --------------------------------------------------------
    bool canRegister = (detectedNR7 and setupStage == 0 and flat and not enterLong and not enterShort and entrySessionOK and beforeForceClose and tradesToday < maximumTradesPerDay)
    if canRegister
        setupStage := 1
        nrHigh := high
        nrLow := low
        nrBar := bar_index
        nrDay := dayKey
        totalNR7 += 1

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

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

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

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

// ============================================================================
// 38. NR7 LEVELS
// ============================================================================
plot(showNRLevels and setupStage == 1 ? nrHigh : na, title="NR7 High", color=color.aqua, linewidth=2, style=plot.style_linebr)
plot(showNRLevels and setupStage == 1 ? nrLow : na, title="NR7 Low", color=color.fuchsia, linewidth=2, style=plot.style_linebr)

// ============================================================================
// 39. RETEST LEVEL
// ============================================================================
plot(showRetestLevel and (setupStage == 2 or setupStage == 3) ? retestLevel : na, title="Pending Retest Level", color=color.yellow, linewidth=2, style=plot.style_linebr)

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

// ============================================================================
// 41. NR7 MARKERS
// ============================================================================
plotshape(showNRMarkers and detectedNR7, title="NR7 Detected", style=shape.circle, location=location.belowbar, color=color.gray, size=size.tiny, text="NR7")

// ============================================================================
// 42. BREAKOUT MARKERS
// ============================================================================
plotshape(showBreakoutMarkers and longBreakout, title="NR7 Bullish Breakout", style=shape.circle, location=location.belowbar, color=color.aqua, size=size.tiny, text="BO")
plotshape(showBreakoutMarkers and shortBreakout, title="NR7 Bearish Breakout", style=shape.circle, location=location.abovebar, color=color.orange, size=size.tiny, text="BO")

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

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

// ============================================================================
// 45. DATA WINDOW
// ============================================================================
plot(currentRange, title="Candle Range", color=color.gray, display=display.data_window)
plot(previousMinimumRange, title="Previous Minimum Range", color=color.blue, display=display.data_window)
plot(nrRangeATR, title="Current Range / ATR", color=color.aqua, display=display.data_window)
plot(bodyRatio, title="Candle Body Ratio", color=color.orange, display=display.data_window)
plot(atr, title="ATR", color=color.gray, display=display.data_window)
plot(relativeVolume, title="Relative Volume", color=color.purple, display=display.data_window)
plot(adx, title="ADX", color=color.blue, display=display.data_window)

// ============================================================================
// 46. DIAGNOSTICS TABLE
// ============================================================================
var table diagnostics = table.new(position.top_right, 2, 23, border_width=1)
if barstate.islast
    if showDiagnostics
        table.cell(diagnostics, 0, 0, "CNPS98 V1")
        table.cell(diagnostics, 1, 0, timeframe.period)
        table.cell(diagnostics, 0, 1, "NR7 Range")
        table.cell(diagnostics, 1, 1, str.tostring(currentRange, "#.##"))
        table.cell(diagnostics, 0, 2, "Minimum Range")
        table.cell(diagnostics, 1, 2, str.tostring(previousMinimumRange, "#.##"))
        table.cell(diagnostics, 0, 3, "NR7 Detected")
        table.cell(diagnostics, 1, 3, detectedNR7 ? "YES" : "NO")
        table.cell(diagnostics, 0, 4, "Total NR7")
        table.cell(diagnostics, 1, 4, str.tostring(totalNR7))
        table.cell(diagnostics, 0, 5, "Setup Stage")
        table.cell(diagnostics, 1, 5, str.tostring(setupStage))
        table.cell(diagnostics, 0, 6, "NR7 High")
        table.cell(diagnostics, 1, 6, str.tostring(nrHigh, "#.##"))
        table.cell(diagnostics, 0, 7, "NR7 Low")
        table.cell(diagnostics, 1, 7, str.tostring(nrLow, "#.##"))
        table.cell(diagnostics, 0, 8, "Breakouts")
        table.cell(diagnostics, 1, 8, str.tostring(totalBreakouts))
        table.cell(diagnostics, 0, 9, "Long Breakouts")
        table.cell(diagnostics, 1, 9, str.tostring(longBreakoutCount))
        table.cell(diagnostics, 0, 10, "Short Breakouts")
        table.cell(diagnostics, 1, 10, str.tostring(shortBreakoutCount))
        table.cell(diagnostics, 0, 11, "Long Retests")
        table.cell(diagnostics, 1, 11, str.tostring(longRetestCount))
        table.cell(diagnostics, 0, 12, "Short Retests")
        table.cell(diagnostics, 1, 12, str.tostring(shortRetestCount))
        table.cell(diagnostics, 0, 13, "Expired NR7")
        table.cell(diagnostics, 1, 13, str.tostring(expiredNRCount))
        table.cell(diagnostics, 0, 14, "Expired Retests")
        table.cell(diagnostics, 1, 14, str.tostring(expiredRetestCount))
        table.cell(diagnostics, 0, 15, "Filtered Long")
        table.cell(diagnostics, 1, 15, str.tostring(filteredLongCount))
        table.cell(diagnostics, 0, 16, "Filtered Short")
        table.cell(diagnostics, 1, 16, str.tostring(filteredShortCount))
        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, "Time Exits")
        table.cell(diagnostics, 1, 19, str.tostring(timeExitCount))
        table.cell(diagnostics, 0, 20, "Session Exits")
        table.cell(diagnostics, 1, 20, str.tostring(sessionExitCount))
        table.cell(diagnostics, 0, 21, "Trades Today")
        table.cell(diagnostics, 1, 21, str.tostring(tradesToday) + "/" + str.tostring(maximumTradesPerDay))
        table.cell(diagnostics, 0, 22, "Position")
        table.cell(diagnostics, 1, 22, inLong ? "LONG" : inShort ? "SHORT" : "FLAT")
    else
        table.clear(diagnostics, 0, 0, 1, 22)

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

2.1. Nhận diện nến nén biên độ NR7 và bộ lọc nén

Biên độ nến hiện tại được tính bằng currentRange = high - low, sau đó so sánh với biên độ nhỏ nhất của nrLength - 1 (mặc định 6) nến liền trước: previousMinimumRange = ta.lowest(currentRange[1], nrLength - 1).

  • Nếu requireStrictNR = false (mặc định), nến hiện tại thỏa điều kiện khi currentRange <= previousMinimumRange (cho phép bằng giá trị nhỏ nhất). Nếu bật true, biên độ phải nhỏ hơn tuyệt đối (<).
  • Hai lớp lọc tùy chọn bổ sung gồm:
    • ATR Compression Filter: Yêu cầu tỷ lệ currentRange / atr <= maximumNRRangeATR (0.70).
    • NR7 Inside Bar: Yêu cầu high <= high[1] và low >= low[1].
  • Nến NR7 chỉ được xác nhận khi nến đã đóng (barstate.isconfirmed), trên biểu đồ Intraday (timeframe.isintraday) và có currentRange > 0.

2.2. Đánh giá sức mạnh nến (Candle Strength) và đệm bứt phá

Để hạn chế các cú phá vỡ giả (false breakout) bằng râu nến, CNPS98 đo lường cấu trúc nến bứt phá qua:

  • Tỷ lệ thân nến (bodyRatio): math.abs(close - open) / currentRange. Mặc định useBodyFilter = true yêu cầu bodyRatio >= 0.30.
  • Chiều nến (requireDirectionalCandle): Mặc định true, yêu cầu nến xanh (close > open) cho Long và nến đỏ (close < open) cho Short.
  • Vị trí đóng cửa (closePosition): (close - low) / currentRange (tùy chọn useCloseLocation, mặc định false, ngưỡng Long >= 0.60, Short <= 0.40).
  • Đệm bứt phá (breakoutBuffer): atr * breakoutBufferATR (mặc định 0.0), tạo ra hai ngưỡng kích hoạt longBreakLevel = nrHigh + breakoutBuffer và shortBreakLevel = nrLow - breakoutBuffer.

2.3. Bộ máy trạng thái NR7 (State Machine) và bộ lọc đa tầng

Hệ thống vận hành qua 4 trạng thái setupStage:

  • Stage 0: Chưa có setup.
  • Stage 1: Đã ghi nhận nến NR7 (nrHigh, nrLow, nrBar, nrDay), đang chờ nến đóng cửa bứt phá trong tối đa breakoutWindow (5 nến) và cùng ngày giao dịch.
  • Stage 2 / Stage 3: Đã bứt phá tăng (Stage 2) hoặc giảm (Stage 3) ở chế độ Breakout + Retest, đang chờ giá quay lại kiểm tra retestLevel (nrHigh hoặc nrLow) trong tối đa retestWindow (5 nến).

Ngoài ra, bot cung cấp các bộ lọc tùy chọn (mặc định false) trước khi cho phép tín hiệu đi qua:

  • EMA Trend (useEMAFilter): Lọc theo EMA 50, độ dốc ema > ema[3] và giá nằm trên/dưới EMA.
  • Relative Volume (useVolumeFilter): So sánh volume / ta.sma(volume[1], 20) >= 1.0.
  • Momentum (useADXFilter, useRSIFilter): Yêu cầu ADX >= 18.0 (tùy chọn hướng DI+/DI-) và RSI (>= 52.0 cho Long, <= 48.0 cho Short).
  • Confirmed H1 Bias (useH1Bias): Lấy EMA 50 và giá đóng cửa của nến H1 đã hoàn tất ([1]) qua request.security (chỉ áp dụng cho khung dưới 60 phút).

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

Quy trình xử lý trên mỗi cây nến đã đóng (barstate.isconfirmed) diễn ra theo 5 bước tuần tự sau:

  1. Khởi tạo phiên mới & Reset biến ngày: Khi dayKey thay đổi (newDay), bot đưa tradesToday := 0 và xóa sạch toàn bộ trạng thái setupStage := 0, nrHigh, nrLow, retestLevel của ngày cũ.
  2. Đánh giá tín hiệu Breakout / Retest trên setup hiện có: Nếu đang ở Stage 1, bot kiểm tra điều kiện bứt phá qua longBreakLevel hoặc shortBreakLevel. Nếu đang ở Stage 2/3, bot kiểm tra điều kiện nến chạm vùng retestLevel và đóng cửa thuận chiều.
  3. Kiểm tra bộ lọc và cổng vào lệnh (Entry Gate): Tín hiệu đạt chuẩn đi qua các bộ lọc xu hướng/động lượng (rawLong / rawShort), sau đó qua cổng kiểm tra trạng thái flat, giới hạn lệnh ngày, cooldown, khoảng cách nến và khung giờ giao dịch để phát lệnh strategy.entry.
  4. Cập nhật trạng thái & đăng ký NR7 mới: Sau khi xử lý tín hiệu hiện tại (và hủy setup nếu hết hạn nrExpired hoặc retestExpired/invalidRetest), nếu setupStage == 0, vị thế đang flat và chưa vào lệnh trên nến hiện tại, bot mới đăng ký cây nến NR7 vừa hình thành vào Stage 1. Lưu ý: nến NR7 không bao giờ tự kích hoạt lệnh ngay trên chính nó.
  5. Quản trị thoát lệnh: Lệnh mở được bảo vệ ngay bởi strategy.exit (SL/TP), kiểm tra thêm điều kiện thoát theo thời gian (Time Exit) hoặc đóng toàn bộ khi chạm giờ kết thúc phiên (14:45).

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

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

Bot mở vị thế Long (enterLong) khi canTrade, allowLong và rawLong đều đúng (đồng thời not rawShort):

  • Tín hiệu gốc (longBase):
    • Ở chế độ Breakout Close: Đang ở Stage 1, còn trong cửa sổ breakoutWindow cùng ngày, close > nrHigh + breakoutBuffer và nến đạt longCandleOK (nến tăng, bodyRatio >= 0.30).
    • Ở chế độ Breakout + Retest: Đang ở Stage 2, còn trong retestWindow, low <= retestLevel + retestTolerance (chạm vùng nrHigh trong phạm vi 0.20 * ATR), close > retestLevel và nến tăng (nếu bật requireRetestDirection).
  • Bộ lọc bổ sung (nếu được bật): Thỏa longTrendOK (EMA), volumeOK, adxOK, longDIOK, longRSIOK và longH1OK.

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

Bot mở vị thế Short (enterShort) khi canTrade, allowShort và rawShort đều đúng (đồng thời not rawLong):

  • Tín hiệu gốc (shortBase):
    • Ở chế độ Breakout Close: Đang ở Stage 1, còn trong cửa sổ breakoutWindow cùng ngày, close < nrLow - breakoutBuffer và nến đạt shortCandleOK (nến giảm, bodyRatio >= 0.30).
    • Ở chế độ Breakout + Retest: Đang ở Stage 3, còn trong retestWindow, high >= retestLevel - retestTolerance (chạm vùng nrLow trong phạm vi 0.20 * ATR), close < retestLevel và nến giảm (nếu bật requireRetestDirection).
  • Bộ lọc bổ sung (nếu được bật): Thỏa shortTrendOK (EMA), volumeOK, adxOK, shortDIOK, shortRSIOK và shortH1OK.

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

Mọi lệnh vào đều phải vượt qua hàng rào an toàn gồm:

  • Nến đã đóng (barstate.isconfirmed) trên biểu đồ Intraday (timeframe.isintraday).
  • Tài khoản đang đứng ngoài thị trường: flat (strategy.position_size == 0) và strategy.opentrades == 0 (pyramiding=0).
  • Số lệnh trong ngày chưa vượt trần: tradesToday < maximumTradesPerDay (mặc định tối đa 4 lệnh/ngày).
  • Thỏa khoảng nghỉ sau thoát lệnh (bar_index - lastExitBar > cooldownBars, mặc định 1 nến) và giãn cách giữa các lần vào lệnh (bar_index - lastEntryBar > minimumBarsBetweenEntries, mặc định 2 nến).
  • Nằm trong khung giờ vào lệnh 09:15 - 14:15 (entrySessionOK) và trước giờ ép đóng phiên 14:45 (beforeForceClose).

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

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

CNPS98 sử dụng mức cắt lỗ cố định theo điểm thông qua stopLossPoints (mặc định 5.0 điểm) và quy đổi chính xác sang đơn vị tick của VN30F1M:

  • slTicks = math.max(1, int(math.round(stopLossPoints / syminfo.mintick)))
  • effectiveSL = slTicks * syminfo.mintick
  • Lệnh dừng lỗ được gắn trực tiếp qua strategy.exit ngay khi vị thế được mở (Long: entry_price - effectiveSL, Short: entry_price + effectiveSL).

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

  • Take Profit cố định: Tính theo takeProfitPoints (mặc định 15.0 điểm, tương ứng tỷ lệ Risk:Reward = 1:3 với SL 5.0 điểm), quy đổi thành tpTicks. Bot không sử dụng Break Even hay Trailing Stop trong phiên bản V1 này.
  • Thoát lệnh theo thời gian (Time Exit - tùy chọn): Nếu bật useTimeExit = true, khi số nến nắm giữ barsHeld >= maximumHoldingBars (mặc định 20 nến) và chưa rơi vào nến ép đóng phiên, bot gọi strategy.close_all(immediately=true) để đóng vị thế.
  • Ép đóng cuối phiên (Session Force Close): Tại cây nến có openMinutes < 14:45 và closeMinutes >= 14:45 (forceCloseBar), bot tự động đóng toàn bộ vị thế đang mở để tránh rủi ro qua đêm (Overnight Gap).

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

Cơ chế bảo vệTham số mặc địnhĐiều kiện kích hoạtHành động của Bot
Stop Loss cố định5.0 điểm (slTicks)Giá chạm ngưỡng cắt lỗĐóng vị thế qua strategy.exit (SL Long / SL Short)
Take Profit cố định15.0 điểm (tpTicks)Giá chạm ngưỡng chốt lờiĐóng vị thế qua strategy.exit (TP Long / TP Short)
Time Exit (tùy chọn)useTimeExit = false, 20 nếnbarsHeld >= maximumHoldingBarsĐóng toàn bộ vị thế (Time Exit)
Session Force Close14:45 (Asia/Ho_Chi_Minh)Nến kết thúc phiên (forceCloseBar)Ép đóng toàn bộ vị thế (Session End)

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

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

  1. Mở biểu đồ hợp đồng tương lai VN30F1M trên TradingView, chọn khung thời gian Intraday phù hợp (ví dụ: 5m hoặc 15m).
  2. Nhấn vào tab Pine Editor ở thanh công cụ phía dưới màn hình.
  3. Xóa toàn bộ đoạn mã mẫu có sẵn, sau đó sao chép và dán toàn bộ mã nguồn CNPS98 NR7 Range Expansion V1 ở Mục 1 vào trình soạn thảo.
  4. Nhấn Save (Lưu), đặt tên tùy chọn và nhấn Add to chart (Thêm vào biểu đồ).
  5. Mở phần Settings (Cài đặt) của chiến lược để bật/tắt các bộ lọc (EMA, Volume, ADX/RSI, H1 Bias) hoặc chuyển đổi giữa Breakout Close và Breakout + Retest, đồng thời tích chọn Show Diagnostics nếu muốn theo dõi bảng thống kê trực tiếp.

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

Khi bật showDiagnostics = true, bảng table.new ở góc trên bên phải biểu đồ (2 cột, 23 hàng) sẽ hiển thị chi tiết trạng thái vận hành theo thời gian thực:

  • Thông số nến hiện tại: CNPS98 V1 (khung thời gian), NR7 Range (biên độ nến hiện tại), Minimum Range (biên độ nhỏ nhất chuỗi trước), NR7 Detected (YES/NO).
  • Trạng thái State Machine: Setup Stage (0: trống, 1: chờ breakout, 2: chờ Long retest, 3: chờ Short retest), NR7 High, NR7 Low.
  • Thống kê vòng đời tín hiệu: Total NR7, Breakouts (Long Breakouts, Short Breakouts), Long Retests, Short Retests, Expired NR7, Expired Retests.
  • Thống kê lọc & khớp lệnh: Filtered Long, Filtered Short, Long Entries, Short Entries, Time Exits, Session Exits.
  • Kiểm soát phiên: Trades Today (hiển thị dạng số_lệnh/tối_đa, ví dụ 1/4) và Position (LONG, SHORT hoặc FLAT).

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

Để nhận thông báo tự động qua ứng dụng TradingView, Telegram hoặc Webhook khi Bot CNPS98 phát sinh lệnh, bạn thực hiện như sau:

  1. Nhấn vào biểu tượng Alert (Đồng hồ báo thức) trên thanh công cụ bên phải hoặc nhấn phím tắt Alt + A.
  2. Ở mục Condition, chọn tên chiến lược CNPS98 NR7 RANGE EXPANSION V1.
  3. Ở mục Message, xóa nội dung mặc định và điền chính xác cú pháp: {{strategy.order.alert_message}}.
  4. Nhấn Create để kích hoạt cảnh báo (lưu ý: nếu muốn tắt cảnh báo SL/TP mà chỉ nhận cảnh báo vào lệnh, hãy bật Disable SL/TP Alerts = true trong phần cài đặt bot).

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

Sự kiệnLoại hàm gọiThông điệp Alert thực tế trong code
Vào lệnh Longstrategy.entry🟢 VÀO VỊ THẾ LONG (CNPS98) kèm Giá vào, SL dự kiến, TP dự kiến
Vào lệnh Shortstrategy.entry🔴 VÀO VỊ THẾ SHORT (CNPS98) kèm Giá vào, SL dự kiến, TP dự kiến
Chốt lời Long / Shortstrategy.exit (alert_profit)💰 CHỐT LỜI LONG (TP HIT - CNPS98) / 💰 CHỐT LỜI SHORT (TP HIT - CNPS98) kèm Giá chốt
Cắt lỗ Long / Shortstrategy.exit (alert_loss)🛑 CẮT LỖ LONG (SL HIT - CNPS98) / 🛑 CẮT LỖ SHORT (SL HIT - CNPS98) kèm Giá cắt
Thoát theo thời gianstrategy.close_all⏱️ ĐÓNG VỊ THẾ QUÁ THỜI GIAN (Time Exit - CNPS98) kèm Giá đóng
Đóng cuối phiênstrategy.close_all⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End - CNPS98) kèm Giá đóng

Kết luận

CNPS98 NR7 Range Expansion V1 là một chiến lược giao dịch phái sinh VN30F1M có cấu trúc logic chặt chẽ, minh bạch và không sử dụng dữ liệu tương lai. Điểm mạnh lớn nhất của hệ thống nằm ở khả năng kiên nhẫn chờ thị trường nén biên độ (NR7) để tìm điểm bùng nổ có xác suất cao, kết hợp tỷ lệ Risk:Reward mặc định 1:3 (SL 5.0 / TP 15.0 điểm) và kỷ luật đóng vị thế cuối phiên lúc 14:45. Chiến lược phát huy hiệu quả tốt nhất trong các phiên thị trường có nhịp tích lũy rõ ràng trước khi mở rộng biên độ theo xu hướng.

Bạn có thể tham khảo thêm các hệ thống giao dịch khác trên hệ sinh thái: 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