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

Hướng Dẫn Sử Dụng Bot CNPS95 - ATR Volatility Expansion V1 cho VN30F1M

Bot CNPS95 (ATR Volatility Expansion V1) phát hiện giai đoạn giãn nở biến động khi Fast ATR vượt Baseline ATR, kết hợp nến xung lực và xác nhận phá vỡ giá để giao dịch theo đà trên VN30F1M.

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

Khi giao dịch hợp đồng tương lai chỉ số VN30F1M trong ngày, một trong những thách thức lớn nhất là thị trường thường xuyên rơi vào trạng thái đi ngang biên độ hẹp (sideway) rồi bất ngờ bùng nổ biến động mạnh. Nếu vào lệnh quá sớm khi thị trường chưa có động lượng, nhà giao dịch dễ bị quét dừng lỗ liên tục; ngược lại, nếu chờ quá lâu, điểm vào sẽ bị trễ và tỷ lệ Rủi ro/Lợi nhuận (R:R) không còn hấp dẫn.

Bot CNPS95 — tên đầy đủ trong mã nguồn là CNPS95 ATR VOLATILITY EXPANSION V1 (shorttitle: CNPS95 ATR EXP), được viết bằng Pine Script v6 trên TradingView — được thiết kế để giải quyết trực tiếp bài toán này bằng cách đo lường sự giãn nở biến động ngắn hạn so với nền biến động dài hạn, chỉ kích hoạt vị thế khi xuất hiện nến xung lực (Impulse Candle) kèm xác nhận phá vỡ giá (Breakout).

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

  • Đo lường giãn nở biến động (ATR Expansion Engine): So sánh Fast ATR (7) với Baseline ATR (30) để nhận diện chính xác thời điểm biến động thị trường bắt đầu bùng nổ (atrRatio >= 1.05).
  • Phân tích cấu trúc nến xung lực (Impulse Candle Anatomy): Kiểm soát biên độ nến theo bội số ATR (từ 1.20 đến 3.50 lần Fast ATR), tỷ lệ thân nến tối thiểu (0.45) và hướng nến rõ ràng, loại bỏ các nến nhiễu hoặc nến rút râu bất thường.
  • Xác nhận phá vỡ không vẽ lại (Non-repainting Breakout & Confirmed H1): Yêu cầu giá đóng cửa phá vỡ đỉnh/đáy của N nến liền trước trên nến đã đóng (barstate.isconfirmed), đồng thời hỗ trợ tùy chọn bộ lọc EMA, Volume tương đối, ADX/DI, RSI và xu hướng H1 đã xác nhận.
  • Quản trị rủi ro chặt chẽ theo phiên VN30F1M: Cố định Stop Loss (5.0 điểm), Take Profit (15.0 điểm), giới hạn tối đa 3 lệnh/ngày, có cơ chế Cooldown, khoảng cách giữa các lệnh, tùy chọn thoát lệnh theo thời gian (Time Exit) và tự động đóng toàn bộ vị thế cuối phiên lúc 14:45.

1. CNPS95 ATR Volatility Expansion V1 là gì?

CNPS95 ATR Volatility Expansion V1 là hệ thống giao dịch theo đà biến động (Volatility Expansion Momentum) hoạt động trên khung thời gian trong ngày (timeframe.isintraday). Chiến lược được xây dựng dựa trên 4 trụ cột kỹ thuật chính:

  1. Động cơ giãn nở ATR (ATR Expansion Engine): Tính toán tỷ lệ atrRatio = fastATR / baselineATR. Khi biến động ngắn hạn vượt ngưỡng 1.05 lần biến động nền, bot xác định thị trường đang bước vào pha mở rộng biên độ, với hai chế độ vào lệnh là Impulse During Expansion (vào nhiều nhịp xung lực độc lập trong suốt pha giãn nở) hoặc First Expansion Only (chỉ bắt nhịp đầu tiên khi atrRatio cắt lên ngưỡng).
  2. Bộ nhận diện nến xung lực (Impulse Candle): Đánh giá chất lượng nến tín hiệu dựa trên 4 tiêu chí: biên độ nến so với Fast ATR (rangeATR), tỷ lệ thân/biên độ (bodyRatio), hướng nến tăng/giảm (bullishCandle/bearishCandle) và tùy chọn vị trí giá đóng cửa gần cực trị nến (closePosition).
  3. Động cơ xác nhận phá vỡ (Breakout Confirmation): Chỉ sử dụng dữ liệu của các nến trước đó (high[1], low[1]) để tính kênh giá phá vỡ breakoutLookback, loại trừ nến hiện tại nhằm tránh hiện tượng tự tham chiếu, có thể cộng thêm vùng đệm theo ATR (breakoutBuffer).
  4. Hệ thống bộ lọc đa tầng & Kiểm soát rủi ro (Optional Filters & Trade Control): Tích hợp sẵn các bộ lọc tùy chọn gồm EMA Trend, Relative Volume, ADX/DI, RSI, Confirmed H1 EMA Bias cùng các hàng rào kiểm soát số lệnh/ngày, thời gian nghỉ sau khi đóng lệnh và đóng vị thế bắt buộc trước phiên ATC.

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

Nhóm thông sốTên tham số trong codeGiá trị mặc địnhÝ nghĩa
01. ATR ExpansionfastATRLength / baselineATRLength7 / 30Chu kỳ Fast ATR và Baseline ATR
01. ATR ExpansionminimumATRRatio1.05Tỷ lệ tối thiểu Fast ATR / Baseline ATR để kích hoạt giãn nở
01. ATR ExpansionentryMode"Impulse During Expansion"Chế độ vào lệnh (Impulse During Expansion hoặc First Expansion Only)
01. ATR ExpansionrequireATRIncreasing / atrIncreaseLookbackfalse / 1Tùy chọn yêu cầu Fast ATR đang tăng so với 1 nến trước
02. Impulse CandleminimumRangeATR / maximumRangeATR1.20 / 3.50Biên độ nến hợp lệ so với Fast ATR (useMaximumRange = true)
02. Impulse CandleminimumBodyRatio0.45Tỷ lệ tối thiểu giữa thân nến và toàn bộ biên độ nến
02. Impulse CandlerequireDirectionalCandletrueBắt buộc nến tăng cho Long (close > open) và nến giảm cho Short (close < open)
02. Impulse CandleuseCloseLocation (minLong / maxShort)false (0.65 / 0.35)Tùy chọn yêu cầu giá đóng cửa nằm gần đỉnh/đáy nến
03. BreakoutuseBreakoutFilter / breakoutLookbacktrue / 1Bắt buộc giá đóng cửa phá vỡ đỉnh/đáy 1 nến trước đó
03. BreakoutuseBreakoutBuffer / breakoutBufferATRfalse / 0.05Vùng đệm phá vỡ tính theo tỷ lệ Fast ATR
04. EMA TrenduseEMAFilter / emaLength / emaSlopeBarsfalse / 50 / 3Bộ lọc xu hướng EMA 50, độ dốc 3 nến (requireEMASlope = true, requirePriceEMA = true)
04. EMA TrenduseDistanceFilter / maximumDistanceATRfalse / 2.50Giới hạn khoảng cách tối đa từ giá đến EMA theo ATR
05. Volume FilteruseVolumeFilter / volumeLength / minimumVolumeFactorfalse / 20 / 1.0Bộ lọc khối lượng tương đối so với SMA 20 của volume[1]
06. Momentum FiltersuseADXFilter / diLength / adxSmoothing / minimumADXfalse / 14 / 14 / 18.0Bộ lọc ADX tối thiểu và tùy chọn hướng DI (requireDIDirection = false)
06. Momentum FiltersuseRSIFilter / rsiLength (Long / Short)false / 14 (52.0 / 48.0)Bộ lọc động lượng RSI tối thiểu cho Long và tối đa cho Short
07. H1 BiasuseH1Bias / h1EMALengthfalse / 50Bộ lọc xu hướng khung H1 đã đóng nến (close[1] vs EMA 50[1])
08. Risk ManagementstopLossPoints / takeProfitPoints5.0 / 15.0Cắt lỗ cố định 5.0 điểm và chốt lời cố định 15.0 điểm
08. Risk ManagementuseTimeExit / maximumHoldingBarsfalse / 20Tùy chọn đóng lệnh nếu giữ quá 20 nến
09. Trade ControltradeDirection / contracts"Both" / 3Chiều giao dịch (Both) và tham số số hợp đồng khai báo (3)
09. Trade ControlmaximumTradesPerDay / cooldownBars / minimumBarsBetweenEntries3 / 2 / 3Tối đa 3 lệnh/ngày, nghỉ 2 nến sau thoát lệnh, cách 3 nến giữa 2 lần vào
10. Trading Sessiontz / useSessionFilter"Asia/Ho_Chi_Minh" / trueMúi giờ Việt Nam, vào lệnh 09:15–14:15, đóng bắt buộc lúc 14:45
11–12. Alerts & DisplaydisableExitAlerts / showEMA / showSLTP / showDiagnosticsfalse / true / true / falseCấu hình tắt alert thoát lệnh và hiển thị EMA, SL/TP, bảng chẩn đoán

Source Code CNPS95 ATR Volatility 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="CNPS95 ATR VOLATILITY EXPANSION V1", shorttitle="CNPS95 ATR 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)

// ============================================================================
// CNPS95 - ATR VOLATILITY EXPANSION V1
//
// CORE LOGIC:
//
// 1. Fast ATR is compared with baseline ATR.
// 2. Detect volatility expansion.
// 3. Identify a directional large-range candle.
// 4. Require price breakout confirmation.
// 5. Enter in the direction of the impulse.
//
// LONG:
// - Volatility is expanding.
// - Bullish candle range >= ATR threshold.
// - Price breaks the preceding candle high.
// - Optional trend / momentum / volume filters.
//
// SHORT:
// - Same structure, bearish direction.
//
// ENTRY MODES:
//
// A. Impulse During Expansion
//    Multiple independent impulse opportunities
//    while the volatility regime remains active.
//
// B. First Expansion Only
//    A single trigger when ATR crosses the
//    expansion threshold from below.
//
// All entry signals use confirmed candles.
// No future pivots or unconfirmed HTF data.
// ============================================================================
// ============================================================================
// 01. ATR EXPANSION ENGINE
// ============================================================================
gATR = "01. ATR Expansion"
fastATRLength = input.int(7, "Fast ATR Length", minval=1, maxval=100, group=gATR)
baselineATRLength = input.int(30, "Baseline ATR Length", minval=2, maxval=300, group=gATR)
minimumATRRatio = input.float(1.05, "Minimum Fast ATR / Baseline ATR", minval=0.50, maxval=5.00, step=0.05, group=gATR)
entryMode = input.string("Impulse During Expansion", "Entry Mode", options=["Impulse During Expansion", "First Expansion Only"], group=gATR)
requireATRIncreasing = input.bool(false, "Require Fast ATR Increasing", group=gATR)
atrIncreaseLookback = input.int(1, "ATR Increase Lookback", minval=1, maxval=20, group=gATR)

// ============================================================================
// 02. IMPULSE CANDLE
// ============================================================================
gImpulse = "02. Impulse Candle"
minimumRangeATR = input.float(1.20, "Minimum Candle Range / Fast ATR", minval=0.10, maxval=10.00, step=0.10, group=gImpulse)
useMaximumRange = input.bool(true, "Reject Excessively Large Candles", group=gImpulse)
maximumRangeATR = input.float(3.50, "Maximum Candle Range / Fast ATR", minval=0.20, maxval=20.00, step=0.10, group=gImpulse)
minimumBodyRatio = input.float(0.45, "Minimum Body / Candle Range", minval=0.00, maxval=1.00, step=0.05, group=gImpulse)
requireDirectionalCandle = input.bool(true, "Require Bullish/Bearish Candle", group=gImpulse)
useCloseLocation = input.bool(false, "Require Close Near Candle Extreme", group=gImpulse)
minimumLongCloseLocation = input.float(0.65, "Minimum Long Close Position", minval=0.0, maxval=1.0, step=0.05, group=gImpulse)
maximumShortCloseLocation = input.float(0.35, "Maximum Short Close Position", minval=0.0, maxval=1.0, step=0.05, group=gImpulse)

// ============================================================================
// 03. BREAKOUT CONFIRMATION
// ============================================================================
gBreakout = "03. Breakout Confirmation"
useBreakoutFilter = input.bool(true, "Require Price Breakout", group=gBreakout)
breakoutLookback = input.int(1, "Break Previous N Candles", minval=1, maxval=100, group=gBreakout)
useBreakoutBuffer = input.bool(false, "Use Breakout Buffer", group=gBreakout)
breakoutBufferATR = input.float(0.05, "Breakout Buffer / Fast ATR", minval=0.0, maxval=2.0, step=0.05, group=gBreakout)

// ============================================================================
// 04. EMA TREND FILTER
// ============================================================================
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)
requireEMASlope = input.bool(true, "Require EMA Slope Direction", 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)
useDistanceFilter = input.bool(false, "Limit Distance From EMA", group=gTrend)
maximumDistanceATR = input.float(2.50, "Maximum Distance From EMA / ATR", minval=0.1, maxval=20.0, step=0.25, group=gTrend)

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

// ============================================================================
// 06. ADX / RSI FILTERS
// ============================================================================
gMomentum = "06. Momentum Filters"
useADXFilter = input.bool(false, "Use Minimum ADX", 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, step=1.0, group=gMomentum)
requireDIDirection = input.bool(false, "Require DI Direction", group=gMomentum)
useRSIFilter = input.bool(false, "Use RSI Momentum 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, maxval=300, 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(3, "Maximum Trades Per Day", minval=1, maxval=20, group=gTrade)
cooldownBars = input.int(2, "Cooldown After Exit (Bars)", minval=0, maxval=100, group=gTrade)
minimumBarsBetweenEntries = input.int(3, "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"
showEMA = input.bool(true, "Show EMA", group=gDisplay)
showExpansionBackground = input.bool(false, "Highlight Volatility Expansion", group=gDisplay)
showImpulseMarkers = input.bool(false, "Show Raw Impulse Dots", group=gDisplay)
showEntryMarkers = input.bool(true, "Show LONG/SHORT Markers", group=gDisplay)
showSLTP = input.bool(true, "Show Active SL/TP", group=gDisplay)
showDiagnostics = input.bool(false, "Show Diagnostics Table", group=gDisplay)

// ============================================================================
// 13. SESSION CLOCK
// ============================================================================
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. ATR CORE
// ============================================================================
//
// Fast ATR:
// Measures short-term average true range.
//
// Baseline ATR:
// Measures the longer-term volatility level.
//
// Expansion ratio:
// Fast ATR / Baseline ATR.
//
// A ratio above 1 indicates the recent
// volatility is greater than its baseline.
//
// ============================================================================
float fastATR = ta.atr(fastATRLength)
float baselineATR = ta.atr(baselineATRLength)
float atrRatio = (not na(fastATR) and not na(baselineATR) and baselineATR > 0 ? fastATR / baselineATR : na)
bool atrDataReady = (not na(atrRatio) and not na(fastATR) and fastATR > 0)
bool atrExpansionActive = (atrDataReady and atrRatio >= minimumATRRatio)
bool atrIncreasing = (not na(fastATR[atrIncreaseLookback]) and fastATR > fastATR[atrIncreaseLookback])
bool atrIncreaseOK = (not requireATRIncreasing or atrIncreasing)
bool firstATRExpansion = (atrExpansionActive and not na(atrRatio[1]) and atrRatio[1] < minimumATRRatio)
bool expansionModeOK = (entryMode == "Impulse During Expansion" ? atrExpansionActive : firstATRExpansion)
bool volatilityOK = (expansionModeOK and atrIncreaseOK)

// ============================================================================
// 16. IMPULSE CANDLE ANATOMY
// ============================================================================
float candleRange = high - low
float candleBody = math.abs(close - open)
float bodyRatio = (candleRange > 0 ? candleBody / candleRange : 0.0)
float closePosition = (candleRange > 0 ? (close - low) / candleRange : 0.5)
float rangeATR = (atrDataReady ? candleRange / fastATR : na)
bool bullishCandle = close > open
bool bearishCandle = close < open
bool impulseRangeOK = (not na(rangeATR) and rangeATR >= minimumRangeATR and (not useMaximumRange or rangeATR <= maximumRangeATR))
bool impulseBodyOK = (bodyRatio >= minimumBodyRatio)
bool longCandleOK = (not requireDirectionalCandle or bullishCandle)
bool shortCandleOK = (not requireDirectionalCandle or bearishCandle)
bool longCloseOK = (not useCloseLocation or closePosition >= minimumLongCloseLocation)
bool shortCloseOK = (not useCloseLocation or closePosition <= maximumShortCloseLocation)

// ============================================================================
// 17. BREAKOUT ENGINE
// ============================================================================
//
// Use previous candles only.
// Current candle is excluded from
// the price channel levels.
//
// ============================================================================
float previousHigh = ta.highest(high[1], breakoutLookback)
float previousLow = ta.lowest(low[1], breakoutLookback)
float breakoutBuffer = (useBreakoutBuffer and atrDataReady ? fastATR * breakoutBufferATR : 0.0)
bool longBreakoutOK = (not useBreakoutFilter or (not na(previousHigh) and close > previousHigh + breakoutBuffer))
bool shortBreakoutOK = (not useBreakoutFilter or (not na(previousLow) and close < previousLow - breakoutBuffer))

// ============================================================================
// 18. EMA TREND
// ============================================================================
float ema = ta.ema(close, emaLength)
bool emaUp = (not na(ema[emaSlopeBars]) and ema > ema[emaSlopeBars])
bool emaDown = (not na(ema[emaSlopeBars]) and ema < ema[emaSlopeBars])
float emaDistanceATR = (atrDataReady ? math.abs(close - ema) / fastATR : na)
bool distanceOK = (not useDistanceFilter or (not na(emaDistanceATR) and emaDistanceATR <= maximumDistanceATR))
bool longEMAOK = (not useEMAFilter or ((not requireEMASlope or emaUp) and (not requirePriceEMA or close > ema)))
bool shortEMAOK = (not useEMAFilter or ((not requireEMASlope or emaDown) and (not requirePriceEMA or close < ema)))

// ============================================================================
// 19. RELATIVE VOLUME
// ============================================================================
float averageVolume = ta.sma(volume[1], volumeLength)
float relativeVolume = (not na(volume) and not na(averageVolume) and averageVolume > 0 ? volume / averageVolume : na)
bool volumeOK = (not useVolumeFilter or (not na(relativeVolume) and relativeVolume >= minimumVolumeFactor))

// ============================================================================
// 20. ADX / DI / RSI
// ============================================================================
[diPlus, diMinus, adx] = ta.dmi(diLength, adxSmoothing)
float rsi = ta.rsi(close, rsiLength)
bool adxOK = (not useADXFilter or (not na(adx) and adx >= minimumADX))
bool longDIOK = (not requireDIDirection or (not na(diPlus) and not na(diMinus) and diPlus > diMinus))
bool shortDIOK = (not requireDIDirection or (not na(diPlus) and not na(diMinus) and diMinus > diPlus))
bool longRSIOK = (not useRSIFilter or (not na(rsi) and rsi >= minimumLongRSI))
bool shortRSIOK = (not useRSIFilter or (not na(rsi) and rsi <= maximumShortRSI))

// ============================================================================
// 21. CONFIRMED H1 BIAS
// ============================================================================
//
// Request the PREVIOUS completed H1
// candle with lookahead_on.
//
// This is deliberately not the
// currently developing H1 value.
//
// ============================================================================
[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))

// ============================================================================
// 22. POSITION STATE
// ============================================================================
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 entrySpacingOK = (na(lastEntryBar) or bar_index - lastEntryBar > minimumBarsBetweenEntries)

// ============================================================================
// 23. LONG IMPULSE
// ============================================================================
bool longImpulse = (barstate.isconfirmed and volatilityOK and impulseRangeOK and impulseBodyOK and longCandleOK and longCloseOK and longBreakoutOK)

// ============================================================================
// 24. SHORT IMPULSE
// ============================================================================
bool shortImpulse = (barstate.isconfirmed and volatilityOK and impulseRangeOK and impulseBodyOK and shortCandleOK and shortCloseOK and shortBreakoutOK)

// ============================================================================
// 25. FINAL FILTERED SIGNALS
// ============================================================================
bool rawLong = (longImpulse and longEMAOK and distanceOK and volumeOK and adxOK and longDIOK and longRSIOK and longH1OK)
bool rawShort = (shortImpulse and shortEMAOK and distanceOK and volumeOK and adxOK and shortDIOK and shortRSIOK and shortH1OK)

// ============================================================================
// 26. ENTRY GATES
// ============================================================================
bool canTrade = (barstate.isconfirmed and intradayOK and atrDataReady and flat and strategy.opentrades == 0 and tradesToday < maximumTradesPerDay and cooldownOK and entrySpacingOK and entrySessionOK and beforeForceClose)
bool ambiguousSignal = (rawLong and rawShort)
bool enterLong = (canTrade and allowLong and rawLong and not ambiguousSignal)
bool enterShort = (canTrade and allowShort and rawShort and not ambiguousSignal)

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

// ============================================================================
// 28. DIAGNOSTIC COUNTERS
// ============================================================================
var int expansionBarCount = 0
var int firstExpansionCount = 0
var int largeCandleCount = 0
var int longImpulseCount = 0
var int shortImpulseCount = 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 forceExitCount = 0

// ============================================================================
// 29. LONG ENTRY
// ============================================================================
if enterLong
    strategy.entry("Long", strategy.long, comment="ATR EXPANSION LONG", alert_message="🟢 VÀO VỊ THẾ LONG (CNPS95)\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

// ============================================================================
// 30. SHORT ENTRY
// ============================================================================
if enterShort
    strategy.entry("Short", strategy.short, comment="ATR EXPANSION SHORT", alert_message="🔴 VÀO VỊ THẾ SHORT (CNPS95)\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

// ============================================================================
// 31. UPDATE DIAGNOSTICS
// ============================================================================
if barstate.isconfirmed
    if atrExpansionActive
        expansionBarCount += 1
    if firstATRExpansion
        firstExpansionCount += 1
    if impulseRangeOK
        largeCandleCount += 1
    if longImpulse
        longImpulseCount += 1
    if shortImpulse
        shortImpulseCount += 1
    if rawLong
        filteredLongCount += 1
    if rawShort
        filteredShortCount += 1
    if rawLong and not enterLong
        blockedLongCount += 1
    if rawShort and not enterShort
        blockedShortCount += 1

// ============================================================================
// 32. 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 - CNPS95)\n🎯 Giá chốt: " + str.tostring(close, format.mintick), alert_loss="🛑 CẮT LỖ LONG (SL HIT - CNPS95)\n🎯 Giá cắt: " + str.tostring(close, format.mintick), disable_alert=disableExitAlerts)

// ============================================================================
// 33. 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 - CNPS95)\n🎯 Giá chốt: " + str.tostring(close, format.mintick), alert_loss="🛑 CẮT LỖ SHORT (SL HIT - CNPS95)\n🎯 Giá cắt: " + str.tostring(close, format.mintick), disable_alert=disableExitAlerts)

// ============================================================================
// 34. 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 - CNPS95)\n🎯 Giá đóng: " + str.tostring(close, format.mintick))
    timeExitCount += 1

// ============================================================================
// 35. 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 - CNPS95)\n🎯 Giá đóng: " + str.tostring(close, format.mintick))
    forceExitCount += 1

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

// ============================================================================
// 37. EXPANSION BACKGROUND
// ============================================================================
bgcolor(showExpansionBackground and atrExpansionActive ? color.new(color.aqua, 92) : na, title="ATR Expansion Background")

// ============================================================================
// 38. RAW IMPULSE MARKERS
// ============================================================================
plotshape(showImpulseMarkers and longImpulse, title="Bullish ATR Impulse", style=shape.circle, location=location.belowbar, color=color.aqua, size=size.tiny, text="EXP")
plotshape(showImpulseMarkers and shortImpulse, title="Bearish ATR Impulse", style=shape.circle, location=location.abovebar, color=color.orange, size=size.tiny, text="EXP")

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

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

// ============================================================================
// 41. DATA WINDOW
// ============================================================================
plot(fastATR, title="Fast ATR", color=color.aqua, display=display.data_window)
plot(baselineATR, title="Baseline ATR", color=color.gray, display=display.data_window)
plot(atrRatio, title="Fast ATR / Baseline ATR", color=color.blue, display=display.data_window)
plot(rangeATR, title="Candle Range / Fast ATR", color=color.orange, display=display.data_window)
plot(bodyRatio, title="Candle Body Ratio", color=color.green, display=display.data_window)
plot(relativeVolume, title="Relative Volume", color=color.purple, display=display.data_window)
plot(adx, title="ADX", color=color.gray, display=display.data_window)
plot(rsi, title="RSI", color=color.fuchsia, display=display.data_window)
plot(emaDistanceATR, title="Distance From EMA / ATR", color=color.orange, display=display.data_window)

// ============================================================================
// 42. 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, "CNPS95 V1")
        table.cell(diagnostics, 1, 0, timeframe.period)
        table.cell(diagnostics, 0, 1, "ATR Ratio")
        table.cell(diagnostics, 1, 1, str.tostring(atrRatio, "#.###"))
        table.cell(diagnostics, 0, 2, "Fast ATR")
        table.cell(diagnostics, 1, 2, str.tostring(fastATR, "#.##"))
        table.cell(diagnostics, 0, 3, "Baseline ATR")
        table.cell(diagnostics, 1, 3, str.tostring(baselineATR, "#.##"))
        table.cell(diagnostics, 0, 4, "Expansion Active")
        table.cell(diagnostics, 1, 4, atrExpansionActive ? "YES" : "NO")
        table.cell(diagnostics, 0, 5, "Expansion Bars")
        table.cell(diagnostics, 1, 5, str.tostring(expansionBarCount))
        table.cell(diagnostics, 0, 6, "First Expansions")
        table.cell(diagnostics, 1, 6, str.tostring(firstExpansionCount))
        table.cell(diagnostics, 0, 7, "Large Candles")
        table.cell(diagnostics, 1, 7, str.tostring(largeCandleCount))
        table.cell(diagnostics, 0, 8, "Range / ATR")
        table.cell(diagnostics, 1, 8, str.tostring(rangeATR, "#.##"))
        table.cell(diagnostics, 0, 9, "Body Ratio")
        table.cell(diagnostics, 1, 9, str.tostring(bodyRatio, "#.##"))
        table.cell(diagnostics, 0, 10, "Long Impulses")
        table.cell(diagnostics, 1, 10, str.tostring(longImpulseCount))
        table.cell(diagnostics, 0, 11, "Short Impulses")
        table.cell(diagnostics, 1, 11, str.tostring(shortImpulseCount))
        table.cell(diagnostics, 0, 12, "Filtered Long")
        table.cell(diagnostics, 1, 12, str.tostring(filteredLongCount))
        table.cell(diagnostics, 0, 13, "Filtered Short")
        table.cell(diagnostics, 1, 13, str.tostring(filteredShortCount))
        table.cell(diagnostics, 0, 14, "Blocked Long")
        table.cell(diagnostics, 1, 14, str.tostring(blockedLongCount))
        table.cell(diagnostics, 0, 15, "Blocked Short")
        table.cell(diagnostics, 1, 15, str.tostring(blockedShortCount))
        table.cell(diagnostics, 0, 16, "Long Entries")
        table.cell(diagnostics, 1, 16, str.tostring(longEntryCount))
        table.cell(diagnostics, 0, 17, "Short Entries")
        table.cell(diagnostics, 1, 17, str.tostring(shortEntryCount))
        table.cell(diagnostics, 0, 18, "Time Exits")
        table.cell(diagnostics, 1, 18, str.tostring(timeExitCount))
        table.cell(diagnostics, 0, 19, "Session Exits")
        table.cell(diagnostics, 1, 19, str.tostring(forceExitCount))
        table.cell(diagnostics, 0, 20, "Trades Today")
        table.cell(diagnostics, 1, 20, str.tostring(tradesToday) + "/" + str.tostring(maximumTradesPerDay))
        table.cell(diagnostics, 0, 21, "Position")
        table.cell(diagnostics, 1, 21, inLong ? "LONG" : inShort ? "SHORT" : "FLAT")
        table.cell(diagnostics, 0, 22, "Entry Mode")
        table.cell(diagnostics, 1, 22, entryMode == "Impulse During Expansion" ? "IMPULSE" : "FIRST ONLY")
    else
        table.clear(diagnostics, 0, 0, 1, 22)

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

2.1. Động cơ giãn nở biến động (ATR Expansion Engine)

Bot không sử dụng ATR đơn lẻ mà dùng tỷ lệ giữa Fast ATR (ta.atr(7)) và Baseline ATR (ta.atr(30)):

  • Tỷ lệ giãn nở (atrRatio): fastATR / baselineATR (yêu cầu baselineATR > 0 và fastATR > 0).
  • Trạng thái giãn nở (atrExpansionActive): Kích hoạt khi atrRatio >= 1.05 (minimumATRRatio). Điều này cho thấy biên độ dao động ngắn hạn đã vượt trội hơn ít nhất 5% so với mức nền trung hạn.
  • Hai chế độ kích hoạt (entryMode):
    • "Impulse During Expansion": Cho phép tìm kiếm nhiều cơ hội xung lực độc lập chừng nào atrExpansionActive còn duy trì.
    • "First Expansion Only": Chỉ kích hoạt đúng 1 lần tại nến đầu tiên atrRatio cắt từ dưới 1.05 lên (atrExpansionActive hiện tại đúng và atrRatio[1] < 1.05).
  • Tùy chọn gia tốc ATR (requireATRIncreasing): Khi bật, yêu cầu fastATR > fastATR[atrIncreaseLookback].

2.2. Giải phẫu nến xung lực (Impulse Candle Anatomy) và Phá vỡ (Breakout)

Mỗi cây nến đóng cửa (barstate.isconfirmed) được đo lường chi tiết qua 4 chỉ số:

  • Biên độ chuẩn hóa (rangeATR): (high - low) / fastATR. Nến hợp lệ phải có rangeATR >= 1.20 (đủ lực đẩy) và nếu useMaximumRange = true thì rangeATR <= 3.50 (tránh các nến tin tức quá dài gây trượt giá hoặc SL xa).
  • Tỷ lệ thân nến (bodyRatio): math.abs(close - open) / (high - low) >= 0.45, đảm bảo lực mua/bán thực chất, không phải nến Doji hay nến có râu quá dài.
  • Vị trí đóng cửa (closePosition): (close - low) / (high - low). Nếu bật useCloseLocation, nến Long cần đóng cửa ở phần trên (>= 0.65) và nến Short cần đóng cửa ở phần dưới (<= 0.35).
  • Xác nhận phá vỡ (longBreakoutOK / shortBreakoutOK): Tính mức cao nhất previousHigh = ta.highest(high[1], breakoutLookback) và thấp nhất previousLow = ta.lowest(low[1], breakoutLookback) của N nến trước (loại trừ nến hiện tại). Giá đóng cửa phải vượt hẳn previousHigh + breakoutBuffer (với Long) hoặc thủng previousLow - breakoutBuffer (với Short), trong đó breakoutBuffer = fastATR * 0.05 nếu bật useBreakoutBuffer.

2.3. Hệ thống bộ lọc xu hướng, khối lượng và động lượng tùy chọn

Mặc định các bộ lọc phụ đều ở trạng thái false để giữ nguyên bản chất bắt biến động thuần túy, nhưng người dùng có thể bật từng lớp lọc để tinh chỉnh độ nhiễu:

  • EMA Trend (useEMAFilter): Dùng ta.ema(close, 50). Khi bật, kiểm tra độ dốc ema > ema[3] (hoặc < với Short) và vị trí giá close > ema (hoặc <). Ngoài ra, useDistanceFilter giới hạn khoảng cách math.abs(close - ema) / fastATR <= 2.50 để tránh đuổi giá khi đã đi quá xa EMA.
  • Relative Volume (useVolumeFilter): So sánh volume hiện tại với ta.sma(volume[1], 20). Yêu cầu relativeVolume >= 1.0 để đảm bảo có dòng tiền tham gia.
  • ADX / DI / RSI (useADXFilter, requireDIDirection, useRSIFilter): Dùng ta.dmi(14, 14) yêu cầu adx >= 18.0, có thể kèm diPlus > diMinus (Long) / diMinus > diPlus (Short) và ta.rsi(close, 14) đạt >= 52.0 (Long) hoặc <= 48.0 (Short).
  • Confirmed H1 Bias (useH1Bias): Chỉ hoạt động trên biểu đồ intraday nhỏ hơn 1 giờ (timeframe.in_seconds() < 3600). Bot gọi request.security(syminfo.tickerid, "60", [ta.ema(close, 50)[1], close[1]], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on) để lấy dữ liệu của nến H1 đã hoàn tất liền trước, tuyệt đối không dùng nến H1 đang chạy.

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

Quy trình vận hành của Bot CNPS95 trên mỗi cây nến được thực hiện tuần tự qua 5 bước:

  1. Khởi tạo phiên & Reset ngày: Khi bước sang ngày giao dịch mới theo múi giờ Asia/Ho_Chi_Minh (newDay), bộ đếm tradesToday được đặt lại về 0. Đồng thời, bot theo dõi newClosedTrade để cập nhật lastExitBar phục vụ tính toán thời gian nghỉ (Cooldown).
  2. Đo lường trạng thái giãn nở ATR: Ở mỗi nến, bot tính fastATR, baselineATR và atrRatio. Nếu atrRatio >= 1.05 (hoặc cắt lên 1.05 trong chế độ First Expansion Only) và thỏa mãn điều kiện ATR tăng (nếu bật), trạng thái volatilityOK được kích hoạt.
  3. Sàng lọc nến xung lực & Phá vỡ: Khi nến đóng cửa (barstate.isconfirmed), bot kiểm tra impulseRangeOK, impulseBodyOK, hướng nến (longCandleOK/shortCandleOK), vị trí đóng cửa và điều kiện phá vỡ đỉnh/đáy trước đó để hình thành longImpulse hoặc shortImpulse.
  4. Kiểm tra bộ lọc phụ & Cổng vào lệnh (Entry Gates): Tín hiệu xung lực đi qua các bộ lọc tùy chọn (rawLong/rawShort), sau đó kiểm tra cổng canTrade (đúng khung giờ phiên, chưa đạt giới hạn lệnh ngày, hết cooldown, đủ khoảng cách giữa các lệnh, đang flat và không có tín hiệu Long/Short trùng nhau) trước khi gửi lệnh strategy.entry.
  5. Quản trị & Thoát lệnh: Ngay khi có vị thế, strategy.exit tự động đặt lệnh chờ SL/TP cố định theo tick. Nếu bật useTimeExit, bot kiểm tra số nến nắm giữ để đóng lệnh khi quá hạn. Cuối cùng, tại nến chạm mốc 14:45 (forceCloseBar), mọi vị thế đang mở sẽ bị đóng bằng strategy.close_all.

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

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

Lệnh Long (enterLong) được kích hoạt khi canTrade == true, allowLong == true, ambiguousSignal == false và thỏa mãn đồng thời:

  • Nến đã xác nhận: barstate.isconfirmed == true.
  • Giãn nở biến động (volatilityOK): atrRatio >= 1.05 (hoặc cắt lên từ dưới 1.05 nếu chọn First Expansion Only) và thỏa mãn atrIncreaseOK.
  • Nến xung lực tăng:
    • Biên độ nến rangeATR nằm trong khoảng [1.20, 3.50] (nếu bật useMaximumRange).
    • Tỷ lệ thân nến bodyRatio >= 0.45.
    • Nến tăng (close > open) nếu bật requireDirectionalCandle.
    • closePosition >= 0.65 nếu bật useCloseLocation.
  • Phá vỡ tăng (longBreakoutOK): close > ta.highest(high[1], breakoutLookback) + breakoutBuffer (nếu bật useBreakoutFilter).
  • Bộ lọc tùy chọn (nếu bật): Giá trên EMA 50 và EMA dốc lên (longEMAOK), khoảng cách tới EMA <= 2.50 ATR (distanceOK), khối lượng tương đối >= 1.0 (volumeOK), ADX >= 18.0 (adxOK), DI+ > DI- (longDIOK), RSI >= 52.0 (longRSIOK), và giá đóng cửa nến H1 trước đó nằm trên EMA 50 H1 (longH1OK).

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

Lệnh Short (enterShort) được kích hoạt khi canTrade == true, allowShort == true, ambiguousSignal == false và thỏa mãn đồng thời:

  • Nến đã xác nhận: barstate.isconfirmed == true.
  • Giãn nở biến động (volatilityOK): Tương tự chiều Long.
  • Nến xung lực giảm:
    • Biên độ nến rangeATR nằm trong khoảng [1.20, 3.50] (nếu bật useMaximumRange).
    • Tỷ lệ thân nến bodyRatio >= 0.45.
    • Nến giảm (close < open) nếu bật requireDirectionalCandle.
    • closePosition <= 0.35 nếu bật useCloseLocation.
  • Phá vỡ giảm (shortBreakoutOK): close < ta.lowest(low[1], breakoutLookback) - breakoutBuffer (nếu bật useBreakoutFilter).
  • Bộ lọc tùy chọn (nếu bật): Giá dưới EMA 50 và EMA dốc xuống (shortEMAOK), distanceOK, volumeOK, adxOK, DI- > DI+ (shortDIOK), RSI <= 48.0 (shortRSIOK), và giá đóng cửa nến H1 trước đó nằm dưới EMA 50 H1 (shortH1OK).

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

Cổng kiểm soát canTrade và ambiguousSignal đảm bảo bot luôn giao dịch an toàn:

  • Khung thời gian & Phiên giao dịch: Biểu đồ phải là intraday (timeframe.isintraday). Nếu bật useSessionFilter, giờ mở nến phải từ 09:15 trở đi và giờ đóng nến <= 14:15, đồng thời phải trước giờ đóng phiên bắt buộc (closeMinutes < 14:45).
  • Trạng thái vị thế (flat): strategy.position_size == 0 và strategy.opentrades == 0 (với pyramiding=0, bot không nhồi lệnh).
  • Giới hạn tần suất: tradesToday < 3 (maximumTradesPerDay).
  • Cooldown & Giãn cách lệnh: Sau khi đóng một lệnh, phải chờ qua hơn 2 nến (bar_index - lastExitBar > cooldownBars) và khoảng cách từ lần vào lệnh trước phải lớn hơn 3 nến (bar_index - lastEntryBar > minimumBarsBetweenEntries).
  • Chống tín hiệu mâu thuẫn: not (rawLong and rawShort).

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

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

Bot sử dụng mức cắt lỗ cố định theo điểm chỉ số (stopLossPoints = 5.0), được quy đổi chính xác sang đơn vị tick của sàn qua hàm:

  • slTicks = math.max(1, int(math.round(stopLossPoints / syminfo.mintick)))
  • effectiveSL = slTicks * syminfo.mintick

Với VN30F1M (mintick = 0.1), 5.0 điểm tương ứng 50 ticks. Lệnh cắt lỗ được đặt ngay lập tức thông qua strategy.exit("Long Exit", ...) hoặc strategy.exit("Short Exit", ...) dựa trên giá khớp trung bình (strategy.position_avg_price).

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

  • Chốt lời cố định (Take Profit): takeProfitPoints = 15.0 (tương đương 150 ticks trên VN30F1M), tạo tỷ lệ Rủi ro/Lợi nhuận mặc định 1:3. Bot không sử dụng cơ chế dời hòa vốn (Break Even) hay Trailing Stop trong phiên bản V1 này.
  • Thoát lệnh theo thời gian (useTimeExit): Mặc định tắt (false). Nếu bật, bot đếm số nến đã giữ lệnh barsHeld = bar_index - strategy.opentrades.entry_bar_index(0). Khi barsHeld >= 20 (maximumHoldingBars) trên nến đã đóng (và không trùng nến đóng phiên), bot đóng toàn bộ vị thế bằng strategy.close_all(immediately=true, comment="Time Exit").
  • Đóng vị thế cuối phiên (Session Force Close): Tại cây nến có openMinutes < 14:45 và closeMinutes >= 14:45 (forceCloseBar), nếu vẫn còn vị thế mở, bot tự động thực thi strategy.close_all(immediately=true, comment="Session End") để tránh giữ lệnh qua đêm hoặc qua phiên ATC.

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

Cơ chế thoát lệnhTham số điều khiểnGiá trị mặc địnhHành vi thực tế trong code
Cắt lỗ cố định (SL)stopLossPoints5.0 điểm (50 ticks)Đặt lệnh chờ loss=slTicks ngay khi mở vị thế
Chốt lời cố định (TP)takeProfitPoints15.0 điểm (150 ticks)Đặt lệnh chờ profit=tpTicks với tỷ lệ R:R = 1:3
Thoát lệnh quá thời gianuseTimeExit / maximumHoldingBarsfalse / 20 nếnĐóng thị trường (close_all) nếu giữ lệnh đủ 20 nến
Đóng hết phiên (ATC)endHour / endMinute14:45Bắt buộc close_all tại nến vượt mốc 14:45

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 phái sinh VN30F1M trên TradingView và chọn khung thời gian intraday phù hợp (ví dụ M5 hoặc M15; lưu ý nếu bật useH1Bias thì khung thời gian biểu đồ bắt buộc phải nhỏ hơn 1 giờ).
  2. Mở tab Pine Editor ở phía dưới màn hình, xóa code mẫu mặc định.
  3. Sao chép toàn bộ mã nguồn Pine Script v6 ở Mục 1 và dán vào Pine Editor.
  4. Nhấn Save để lưu script, sau đó nhấn Add to chart để áp dụng chiến lược lên biểu đồ và xem kết quả kiểm thử trong tab Strategy Tester.

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

Khi bật tùy chọn Show Diagnostics Table (showDiagnostics = true), bot sẽ vẽ một bảng thống kê 2 cột x 23 dòng tại góc trên bên phải (position.top_right) ở nến cuối cùng (barstate.islast):

  • Thông số ATR & Nến hiện tại: CNPS95 V1 (kèm khung thời gian), ATR Ratio, Fast ATR, Baseline ATR, Expansion Active (YES/NO), Range / ATR, Body Ratio.
  • Thống kê bộ đếm tích lũy toàn lịch sử: Expansion Bars (số nến giãn nở), First Expansions (số lần bắt đầu giãn nở), Large Candles (số nến đạt biên độ chuẩn), Long Impulses / Short Impulses (số nến xung lực thô), Filtered Long / Filtered Short (số tín hiệu qua bộ lọc), Blocked Long / Blocked Short (số tín hiệu đạt chuẩn nhưng bị chặn bởi cổng canTrade như hết lượt ngày, đang có lệnh, ngoài giờ hoặc cooldown).
  • Thống kê giao dịch & Trạng thái: Long Entries, Short Entries, Time Exits, Session Exits, Trades Today (dạng x/3), Position (LONG / SHORT / FLAT) và Entry Mode (IMPULSE hoặc FIRST ONLY).

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, Email hoặc Webhook kết nối bot đặt lệnh tự động:

  1. Nhấn 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 Alt + A.
  2. Ở mục Condition, chọn đúng tên chiến lược CNPS95 ATR VOLATILITY EXPANSION V1.
  3. Ở ô Message, xóa nội dung mặc định và nhập chính xác cú pháp: {{strategy.order.alert_message}}.
  4. Nhấn Create để kích hoạt. Nếu không muốn nhận thông báo khi chạm SL/TP, bạn có thể tích chọn Disable SL/TP Alerts (disableExitAlerts = true) trong phần cài đặt của bot.

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

Sự kiệnNội dung alert_message / alert_profit / alert_loss trong code
Vào lệnh Long🟢 VÀO VỊ THẾ LONG (CNPS95)
🎯 Giá vào: <close>
🛑 SL dự kiến: <close - SL>
🎯 TP dự kiến: <close + TP>
Vào lệnh Short🔴 VÀO VỊ THẾ SHORT (CNPS95)
🎯 Giá vào: <close>
🛑 SL dự kiến: <close + SL>
🎯 TP dự kiến: <close - TP>
Chốt lời Long (alert_profit)💰 CHỐT LỜI LONG (TP HIT - CNPS95)
🎯 Giá chốt: <close>
Cắt lỗ Long (alert_loss)🛑 CẮT LỖ LONG (SL HIT - CNPS95)
🎯 Giá cắt: <close>
Chốt lời Short (alert_profit)💰 CHỐT LỜI SHORT (TP HIT - CNPS95)
🎯 Giá chốt: <close>
Cắt lỗ Short (alert_loss)🛑 CẮT LỖ SHORT (SL HIT - CNPS95)
🎯 Giá cắt: <close>
Thoát lệnh quá thời gian⏱️ ĐÓNG VỊ THẾ QUÁ THỜI GIAN (Time Exit - CNPS95)
🎯 Giá đóng: <close>
Đóng vị thế hết phiên⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End - CNPS95)
🎯 Giá đóng: <close>

Kết luận

Bot CNPS95 (ATR Volatility Expansion V1) là một chiến lược giao dịch phái sinh VN30F1M có cấu trúc rõ ràng, minh bạch và hoàn toàn không vẽ lại (non-repainting). Nhờ kết hợp giữa bộ đo giãn nở biến động Fast ATR / Baseline ATR, tiêu chuẩn nến xung lực và xác nhận phá vỡ giá kèm tỷ lệ R:R cố định 1:3, hệ thống đặc biệt phù hợp trong các phiên thị trường chuyển từ tích lũy sang bứt phá xu hướng mạnh.

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 như Bot CNPS50 - Trend Analysis V2 và Bot CNPS49 - Daily Open để đa dạng hóa góc nhìn và chiến lược giao dịch.

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