Hướng Dẫn Sử Dụng Bot CNPS98 - NR7 Range Expansion V1 cho VN30F1M
Tradingview
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ướngEMA, khối lượng tương đối (Relative Volume), động lượngADX/RSIvà xu hướng khungH1. - 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:
- 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 - Lowhẹp nhất so vớinrLength - 1nế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 theoATRhoặc mô hình Inside Bar. - Độ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ướinrLow - 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á. - 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,RSIvàConfirmed H1 EMA Bias(sử dụng dữ liệu nến H1 đã đóng cửa để tránh repaint). - 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 code | Mô tả | Giá trị mặc định |
|---|---|---|---|
| 01. NR7 Setup | nrLength | Số nến nhìn lại tìm biên độ hẹp nhất | 7 |
breakoutWindow | Số nến tối đa chờ breakout sau NR7 | 5 | |
requireStrictNR | Yêu cầu biên độ nhỏ hơn tuyệt đối | false | |
useCompressionFilter | Bật bộ lọc nén theo ATR | false (ATR=14, max=0.70) | |
useNRInsideBar | Yêu cầu nến NR7 nằm trong nến trước | false | |
| 02. Breakout | entryMode | Chế độ vào lệnh | "Breakout Close" |
breakoutBufferATR | Vùng đệm bứt phá theo ATR | 0.0 | |
requireDirectionalCandle | Yêu cầu nến breakout đúng chiều | true | |
useBodyFilter | Bật bộ lọc tỷ lệ thân nến | true (min=0.30) | |
useCloseLocation | Bật bộ lọc vị trí đóng cửa | false (Long>=0.60, Short<=0.40) | |
| 03. Breakout Retest | retestWindow | Số nến tối đa chờ retest | 5 |
retestToleranceATR | Sai số chạm vùng retest theo ATR | 0.20 | |
retestInvalidationATR | Ngưỡng hủy retest theo ATR | 0.20 | |
requireRetestDirection | Yêu cầu nến retest đúng chiều | true | |
| 04. EMA Trend | useEMAFilter | Bật bộ lọc xu hướng EMA | false (len=50, slopeBars=3) |
| 05. Volume | useVolumeFilter | Bật bộ lọc khối lượng tương đối | false (MA=20, factor=1.0) |
| 06. Momentum | useADXFilter / useRSIFilter | Bật bộ lọc ADX / RSI | false (ADX>=18, RSI 52/48) |
| 07. H1 Bias | useH1Bias | Bật bộ lọc xu hướng H1 EMA | false (h1EMALength=50) |
| 08. Risk Management | stopLossPoints | Mức cắt lỗ cố định (điểm) | 5.0 |
takeProfitPoints | Mức chốt lời cố định (điểm) | 15.0 | |
useTimeExit | Thoát lệnh theo số nến nắm giữ | false (max=20 nến) | |
| 09. Trade Control | tradeDirection | Chiều giao dịch cho phép | "Both" |
contracts | Số hợp đồng khai báo | 3 (mặc định lệnh dùng default_qty_value=1) | |
maximumTradesPerDay | Số lệnh tối đa mỗi ngày | 4 | |
cooldownBars / minimumBarsBetweenEntries | Nghỉ sau thoát / Giãn cách vào lệnh | 1 nến / 2 nến | |
| 10. Trading Session | tz | Múi giờ giao dịch | "Asia/Ho_Chi_Minh" |
useSessionFilter | Lọc phiên vào lệnh | true (09:15 – 14:15) | |
endHour / endMinute | Giờ é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 khicurrentRange <= previousMinimumRange(cho phép bằng giá trị nhỏ nhất). Nếu bậttrue, 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].
- ATR Compression Filter: Yêu cầu tỷ lệ
- 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 địnhuseBodyFilter = trueyêu cầubodyRatio >= 0.30. - Chiều nến (
requireDirectionalCandle): Mặc địnhtrue, 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ọnuseCloseLocation, mặc địnhfalse, ngưỡng Long>= 0.60, Short<= 0.40). - Đệm bứt phá (
breakoutBuffer):atr * breakoutBufferATR(mặc định0.0), tạo ra hai ngưỡng kích hoạtlongBreakLevel = nrHigh + breakoutBuffervà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 đabreakoutWindow(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 traretestLevel(nrHighhoặcnrLow) trong tối đaretestWindow(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 theoEMA 50, độ dốcema > ema[3]và giá nằm trên/dưới EMA. - Relative Volume (
useVolumeFilter): So sánhvolume / ta.sma(volume[1], 20) >= 1.0. - Momentum (
useADXFilter,useRSIFilter): Yêu cầuADX >= 18.0(tùy chọn hướngDI+/DI-) vàRSI(>= 52.0cho Long,<= 48.0cho Short). - Confirmed H1 Bias (
useH1Bias): LấyEMA 50và giá đóng cửa của nến H1 đã hoàn tất ([1]) quarequest.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:
- Khởi tạo phiên mới & Reset biến ngày: Khi
dayKeythay đổi (newDay), bot đưatradesToday := 0và xóa sạch toàn bộ trạng tháisetupStage := 0,nrHigh,nrLow,retestLevelcủa ngày cũ. - Đá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á qualongBreakLevelhoặcshortBreakLevel. Nếu đang ởStage 2/3, bot kiểm tra điều kiện nến chạm vùngretestLevelvà đóng cửa thuận chiều. - 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áiflat, giới hạn lệnh ngày, cooldown, khoảng cách nến và khung giờ giao dịch để phát lệnhstrategy.entry. - 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
nrExpiredhoặcretestExpired/invalidRetest), nếusetupStage == 0, vị thế đangflatvà 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àoStage 1. Lưu ý: nến NR7 không bao giờ tự kích hoạt lệnh ngay trên chính nó. - 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ổbreakoutWindowcùng ngày,close > nrHigh + breakoutBuffervà nến đạtlongCandleOK(nến tăng,bodyRatio >= 0.30). - Ở chế độ
Breakout + Retest: Đang ởStage 2, còn trongretestWindow,low <= retestLevel + retestTolerance(chạm vùngnrHightrong phạm vi0.20 * ATR),close > retestLevelvà nến tăng (nếu bậtrequireRetestDirection).
- Ở chế độ
- Bộ lọc bổ sung (nếu được bật): Thỏa
longTrendOK(EMA),volumeOK,adxOK,longDIOK,longRSIOKvà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ổbreakoutWindowcùng ngày,close < nrLow - breakoutBuffervà nến đạtshortCandleOK(nến giảm,bodyRatio >= 0.30). - Ở chế độ
Breakout + Retest: Đang ởStage 3, còn trongretestWindow,high >= retestLevel - retestTolerance(chạm vùngnrLowtrong phạm vi0.20 * ATR),close < retestLevelvà nến giảm (nếu bậtrequireRetestDirection).
- Ở chế độ
- Bộ lọc bổ sung (nếu được bật): Thỏa
shortTrendOK(EMA),volumeOK,adxOK,shortDIOK,shortRSIOKvà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 đa4lệnh/ngày). - Thỏa khoảng nghỉ sau thoát lệnh (
bar_index - lastExitBar > cooldownBars, mặc định1nến) và giãn cách giữa các lần vào lệnh (bar_index - lastEntryBar > minimumBarsBetweenEntries, mặc định2nến). - Nằm trong khung giờ vào lệnh
09:15 - 14:15(entrySessionOK) và trước giờ ép đóng phiên14: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.exitngay 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 định15.0điểm, tương ứng tỷ lệ Risk:Reward = 1:3 với SL5.0điểm), quy đổi thànhtpTicks. 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ậtuseTimeExit = true, khi số nến nắm giữbarsHeld >= maximumHoldingBars(mặc định20nến) và chưa rơi vào nến ép đóng phiên, bot gọistrategy.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:45và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ạt | Hành động của Bot |
|---|---|---|---|
| Stop Loss cố định | 5.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ố định | 15.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ến | barsHeld >= maximumHoldingBars | Đóng toàn bộ vị thế (Time Exit) |
| Session Force Close | 14: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
- 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ụ:
5mhoặc15m). - Nhấn vào tab Pine Editor ở thanh công cụ phía dưới màn hình.
- 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.
- Nhấn Save (Lưu), đặt tên tùy chọn và nhấn Add to chart (Thêm vào biểu đồ).
- 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 ClosevàBreakout + Retest, đồng thời tích chọnShow Diagnosticsnế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ạngsố_lệnh/tối_đa, ví dụ1/4) vàPosition(LONG,SHORThoặcFLAT).
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:
- 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. - Ở mục Condition, chọn tên chiến lược
CNPS98 NR7 RANGE EXPANSION V1. - Ở 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}}. - 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 = truetrong phần cài đặt bot).
Bảng thông điệp Alert của CNPS98
| Sự kiện | Loại hàm gọi | Thông điệp Alert thực tế trong code |
|---|---|---|
| Vào lệnh Long | strategy.entry | 🟢 VÀO VỊ THẾ LONG (CNPS98) kèm Giá vào, SL dự kiến, TP dự kiến |
| Vào lệnh Short | strategy.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 / Short | strategy.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 / Short | strategy.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 gian | strategy.close_all | ⏱️ ĐÓNG VỊ THẾ QUÁ THỜI GIAN (Time Exit - CNPS98) kèm Giá đóng |
| Đóng cuối phiên | strategy.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.





