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

Hướng Dẫn Sử Dụng Bot CNPS97 - Efficiency Ratio Trend Entry V1 cho VN30F1M

Bot CNPS97 ứng dụng Kaufman Efficiency Ratio đo lường độ hiệu quả xu hướng, kết hợp Breakout cấu trúc hoặc EMA Pullback Reclaim cùng quản trị SL/TP cố định cho VN30F1M.

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

Trong giao dịch phái sinh VN30F1M, một trong những nguyên nhân lớn nhất gây thua lỗ là việc hệ thống liên tục phát tín hiệu sai trong các pha thị trường đi ngang (sideway) nhiều nhiễu. Khi giá giật lên xuống liên tục nhưng không tạo được độ dịch chuyển thực chất, các chiến lược bám xu hướng thông thường rất dễ bị quét cắt lỗ liên tiếp.

CNPS97 — tên đầy đủ trong mã nguồn là CNPS97 EFFICIENCY RATIO TREND ENTRY V1 (shorttitle="CNPS97 ER TREND") — được viết bằng Pine Script v6 trên TradingView để giải quyết triệt để bài toán phân biệt giữa “biến động nhiễu” và “xu hướng có hiệu suất cao”. Chiến lược sử dụng chỉ số Kaufman Efficiency Ratio (ER) làm bộ lọc chế độ thị trường cốt lõi, chỉ cho phép kích hoạt lệnh khi giá di chuyển có định hướng rõ rệt.

  • Đo lường hiệu quả xu hướng bằng Kaufman ER: Tách bạch giữa tổng quãng đường giá đi và độ dịch chuyển ròng, giúp loại bỏ các nhịp giật cục thiếu động lượng.
  • Hai chế độ kích hoạt ER & hai loại Trigger linh hoạt: Hỗ trợ cả Trend Continuation lẫn ER Threshold Cross, kết hợp điểm vào lệnh theo Structure Breakout hoặc EMA Pullback Reclaim.
  • Hệ thống lọc đa lớp tùy chọn & nến tín hiệu chặt chẽ: Kiểm soát cấu trúc thân nến, vị trí đóng cửa, bộ lọc EMA xu hướng, Relative Volume, ADX/DI, RSI và xu hướng khung H1 đã xác nhận.
  • Quản trị rủi ro kỷ luật trong phiên: Thiết lập Stop Loss / Take Profit cố định theo điểm (quy đổi sang tick), giới hạn số lệnh/ngày, cooldown sau thoát lệnh và tự động đóng toàn bộ vị thế trước giờ ATC.

1. CNPS97 Efficiency Ratio Trend Entry V1 là gì?

CNPS97 Efficiency Ratio Trend Entry V1 là chiến lược giao dịch theo xu hướng trong ngày (intraday) hoạt động hoàn toàn trên nến đã đóng (barstate.isconfirmed), không sử dụng dữ liệu tương lai hay pivot chưa xác nhận. Cấu trúc của bot được xây dựng trên 4 trụ cột kỹ thuật chính:

  1. Bộ máy Efficiency Ratio (ER Engine): Tính toán tỷ số hiệu quả Kaufman trên chu kỳ erLength (mặc định 10 nến) để xác nhận thị trường đang ở trạng thái xu hướng hiệu quả (efficiencyRatio >= minimumER), đồng thời dùng dấu của độ dịch chuyển ròng (close - close[erLength]) để xác định chiều Long hay Short.
  2. Bộ kích hoạt điểm vào (Entry Trigger): Cho phép chọn giữa phá vỡ cấu trúc giá (Structure Breakout vượt đỉnh/đáy breakoutLookback nến trước), hồi về chạm và giành lại EMA (EMA Pullback Reclaim), hoặc kết hợp cả hai (Either).
  3. Bộ lọc nến & động lượng đa lớp: Bắt buộc kiểm tra hình thái nến tín hiệu (nến cùng chiều, tỷ lệ thân nến tối thiểu) và cho phép bật thêm các bộ lọc chuyên sâu như EMA xu hướng, khoảng cách tới EMA, khối lượng tương đối, ADX/DI, RSI và H1 EMA Bias.
  4. Bộ kiểm soát phiên & bảo vệ vị thế: Chỉ giao dịch trong khung giờ chuẩn của VN30F1M (09:15–14:15), giới hạn tối đa 3 lệnh/ngày, tự động tính SL/TP cố định theo tick và ép đóng vị thế hết phiên lúc 14:45.

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

Nhóm thông sốTên tham số trong codeGiá trị mặc địnhÝ nghĩa
01. Efficiency RatioerLength / minimumER10 / 0.30Chu kỳ tính ER và ngưỡng ER tối thiểu
01. Efficiency RatioentryMode"Trend Continuation"Chế độ vào lệnh (Trend Continuation / ER Threshold Cross)
01. Efficiency RatiorequireERRising / erSlopeLookbackfalse / 2Yêu cầu ER đang tăng so với N nến trước
01. Efficiency RatiouseMinimumDisplacement / minimumDisplacementATRfalse / 0.50Yêu cầu độ dịch chuyển ròng tối thiểu theo ATR(14)
02. Entry TriggertriggerMode"Structure Breakout"Loại trigger (Structure Breakout / EMA Pullback Reclaim / Either)
02. Entry TriggerbreakoutLookback / useBreakoutBuffer3 / false (0.05 ATR)Số nến lấy đỉnh/đáy Breakout và khoảng đệm ATR
02. Entry TriggerpullbackEMALength / pullbackLookback / requireFreshEMAReclaim10 / 3 / trueThông số EMA hồi về và điều kiện cắt mới
03. Signal CandlerequireDirectionalCandle / useBodyFiltertrue / true (0.30)Yêu cầu nến cùng chiều và thân nến ≥ 30% biên độ
03. Signal CandleuseCloseLocation / useCandleRangeFilterfalse / falseLọc vị trí đóng cửa (0.60 / 0.40) và biên độ nến theo ATR
04. EMA TrenduseEMAFilter / emaLength / emaSlopeLookbackfalse / 50 / 3Bộ lọc xu hướng EMA(50), độ dốc và giới hạn khoảng cách ATR
05. Volume FilteruseVolumeFilter / volumeLength / minimumVolumeFactorfalse / 20 / 1.0Bộ lọc khối lượng tương đối so với SMA(20)
06. Momentum FiltersuseADXFilter / minimumADX / useRSIFilterfalse / 18.0 / falseBộ lọc ADX(14), hướng DI và RSI(14) (Long ≥ 52, Short ≤ 48)
07. H1 BiasuseH1Bias / h1EMALengthfalse / 50Bộ lọc xu hướng khung H1 theo EMA(50) đã đóng nến
08. Risk ManagementstopLossPoints / takeProfitPoints5.0 / 15.0Cắt lỗ 5.0 điểm và chốt lời 15.0 điểm (tỷ lệ R:R 1:3)
08. Risk ManagementuseTimeExit / maximumHoldingBarsfalse / 20Tự động đóng lệnh nếu giữ quá 20 nến
09. Trade ControltradeDirection / maximumTradesPerDay"Both" / 3Cho phép Long & Short, tối đa 3 lệnh/ngày (default_qty_value=1)
09. Trade ControlcooldownBars / minimumBarsBetweenEntries2 / 3Nghỉ 2 nến sau thoát lệnh, cách tối thiểu 3 nến giữa các lần vào
10. Trading SessionstartHour:startMinute – lastHour:lastMinute09:15 – 14:15Khung giờ nhận tín hiệu vào lệnh (Asia/Ho_Chi_Minh)
10. Trading SessionendHour:endMinute14:45Giờ ép đóng toàn bộ vị thế cuối phiên

(Lưu ý kỹ thuật: Trong nhóm 09. Trade Control có khai báo biến contracts = 3, tuy nhiên lệnh strategy.entry trong code sử dụng cấu hình mặc định default_qty_value=1 của strategy(), tức mặc định giao dịch 1 hợp đồng nếu không tùy chỉnh lại thuộc tính Properties trên TradingView).

Source Code CNPS97 Efficiency Ratio Trend Entry 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="CNPS97 EFFICIENCY RATIO TREND ENTRY V1", shorttitle="CNPS97 ER TREND", 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)

// ============================================================================
// CNPS97 - EFFICIENCY RATIO TREND ENTRY
//
// KAUFMAN EFFICIENCY RATIO:
//
// ER = ABS(Close - Close[N])
//      / SUM(ABS(Close - Close[1]), N)
//
// ER ranges from 0 to 1.
//
// ER near 0:
// High relative noise / inefficient movement.
//
// ER near 1:
// Directional and efficient movement.
//
// IMPORTANT:
// ER is non-directional.
// Net price displacement determines direction.
//
// LONG:
// 1. ER is above its threshold.
// 2. Net price displacement is positive.
// 3. A bullish continuation trigger occurs.
// 4. Optional EMA / ADX / RSI / volume / H1.
// 5. Enter LONG.
//
// SHORT:
// Symmetric negative net displacement
// and bearish continuation trigger.
//
// ENTRY MODES:
// 1. Trend Continuation
// 2. ER Threshold Cross
//
// TRIGGERS:
// 1. Structure Breakout
// 2. EMA Pullback Reclaim
// 3. Either
//
// Confirmed-bar orders only.
// No future pivots or developing HTF data.
// ============================================================================
// ============================================================================
// 01. EFFICIENCY RATIO
// ============================================================================
gER = "01. Efficiency Ratio"
erLength = input.int(10, "ER Lookback", minval=2, maxval=200, group=gER)
minimumER = input.float(0.30, "Minimum Efficiency Ratio", minval=0.0, maxval=1.0, step=0.05, group=gER)
entryMode = input.string("Trend Continuation", "ER Entry Mode", options=["Trend Continuation", "ER Threshold Cross"], group=gER)
requireERRising = input.bool(false, "Require ER Increasing", group=gER)
erSlopeLookback = input.int(2, "ER Slope Lookback", minval=1, maxval=30, group=gER)
useMinimumDisplacement = input.bool(false, "Require Minimum Net Movement", group=gER)
minimumDisplacementATR = input.float(0.50, "Minimum Net Movement / ATR", minval=0.0, step=0.10, group=gER)
atrLength = input.int(14, "ATR Length", minval=1, group=gER)

// ============================================================================
// 02. ENTRY TRIGGER
// ============================================================================
gTrigger = "02. Entry Trigger"
triggerMode = input.string("Structure Breakout", "Trigger Type", options=["Structure Breakout", "EMA Pullback Reclaim", "Either"], group=gTrigger)
breakoutLookback = input.int(3, "Breakout Lookback", minval=1, maxval=100, group=gTrigger)
useBreakoutBuffer = input.bool(false, "Use Breakout Buffer", group=gTrigger)
breakoutBufferATR = input.float(0.05, "Breakout Buffer / ATR", minval=0.0, step=0.05, group=gTrigger)
pullbackEMALength = input.int(10, "Pullback EMA Length", minval=2, maxval=200, group=gTrigger)
pullbackLookback = input.int(3, "Pullback Touch Lookback", minval=1, maxval=30, group=gTrigger)
requireFreshEMAReclaim = input.bool(true, "Require Fresh EMA Reclaim", group=gTrigger)

// ============================================================================
// 03. SIGNAL CANDLE
// ============================================================================
gCandle = "03. Signal Candle"
requireDirectionalCandle = input.bool(true, "Require Directional Candle", group=gCandle)
useBodyFilter = input.bool(true, "Use Minimum Body Ratio", group=gCandle)
minimumBodyRatio = input.float(0.30, "Minimum Body / Range", minval=0.0, maxval=1.0, step=0.05, group=gCandle)
useCloseLocation = input.bool(false, "Use Close Location Filter", group=gCandle)
minimumLongClosePosition = input.float(0.60, "Minimum Long Close Position", minval=0.0, maxval=1.0, step=0.05, group=gCandle)
maximumShortClosePosition = input.float(0.40, "Maximum Short Close Position", minval=0.0, maxval=1.0, step=0.05, group=gCandle)
useCandleRangeFilter = input.bool(false, "Use Candle Range / ATR Filter", group=gCandle)
minimumCandleATR = input.float(0.40, "Minimum Candle Range / ATR", minval=0.0, step=0.10, group=gCandle)
maximumCandleATR = input.float(3.00, "Maximum Candle Range / ATR", minval=0.1, step=0.10, group=gCandle)

// ============================================================================
// 04. EMA TREND FILTER
// ============================================================================
gTrend = "04. EMA Trend"
useEMAFilter = input.bool(false, "Use EMA Trend Filter", group=gTrend)
emaLength = input.int(50, "Trend EMA Length", minval=2, maxval=300, group=gTrend)
requireEMASlope = input.bool(true, "Require EMA Slope Direction", group=gTrend)
emaSlopeLookback = input.int(3, "EMA Slope Lookback", minval=1, maxval=50, group=gTrend)
requirePriceEMA = input.bool(true, "Require Price Above/Below EMA", group=gTrend)
useEMADistanceFilter = input.bool(false, "Limit Distance From EMA", group=gTrend)
maximumEMADistanceATR = input.float(2.50, "Maximum EMA Distance / ATR", minval=0.1, step=0.25, group=gTrend)

// ============================================================================
// 05. VOLUME FILTER
// ============================================================================
gVolume = "05. Volume Filter"
useVolumeFilter = input.bool(false, "Use Relative Volume", group=gVolume)
volumeLength = input.int(20, "Volume Average 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 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, 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"
showTrendEMA = input.bool(true, "Show Trend EMA", group=gDisplay)
showPullbackEMA = input.bool(false, "Show Pullback EMA", group=gDisplay)
showBreakoutChannel = input.bool(false, "Show Breakout High/Low", group=gDisplay)
showRegimeBackground = input.bool(false, "Highlight Efficient Trend Regime", group=gDisplay)
showRawTriggerMarkers = input.bool(false, "Show Raw Trigger Dots", 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 Table", group=gDisplay)

// ============================================================================
// 13. TIME 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. ATR
// ============================================================================
float atr = ta.atr(atrLength)
bool atrReady = (not na(atr) and atr > 0)

// ============================================================================
// 16. EFFICIENCY RATIO ENGINE
// ============================================================================
//
// Net movement:
// Close - Close[N]
//
// Total traveled distance:
// SUM(ABS(Close - Previous Close), N)
//
// SMA of absolute movement * N equals
// the sum across N bars.
//
// ER approaches 1 when nearly every
// price change contributes in one direction.
//
// ER approaches 0 when price movement
// frequently reverses.
//
// ============================================================================
float netMovement = (close - close[erLength])
float absoluteNetMovement = math.abs(netMovement)
float oneBarMovement = math.abs(close - close[1])
float averageAbsoluteMovement = ta.sma(oneBarMovement, erLength)
float totalMovement = (averageAbsoluteMovement * erLength)
float efficiencyRatio = (not na(totalMovement) and totalMovement > 0 and not na(absoluteNetMovement) ? math.min(1.0, absoluteNetMovement / totalMovement) : na)
bool erReady = (not na(efficiencyRatio))
bool efficientRegime = (erReady and efficiencyRatio >= minimumER)
bool erIncreasing = (not na(efficiencyRatio[erSlopeLookback]) and efficiencyRatio > efficiencyRatio[erSlopeLookback])
bool erSlopeOK = (not requireERRising or erIncreasing)
bool erThresholdCross = ta.crossover(efficiencyRatio, minimumER)
bool erModeOK = (entryMode == "Trend Continuation" ? efficientRegime : erThresholdCross)

// ============================================================================
// 17. PRICE DIRECTION
// ============================================================================
float netMovementATR = (atrReady ? netMovement / atr : na)
bool positiveDisplacement = (not na(netMovement) and netMovement > 0)
bool negativeDisplacement = (not na(netMovement) and netMovement < 0)
bool longDisplacementOK = (positiveDisplacement and (not useMinimumDisplacement or (atrReady and netMovement >= atr * minimumDisplacementATR)))
bool shortDisplacementOK = (negativeDisplacement and (not useMinimumDisplacement or (atrReady and -netMovement >= atr * minimumDisplacementATR)))

// ============================================================================
// 18. PRICE STRUCTURE BREAKOUT
// ============================================================================
//
// Channel references are based only
// on previous candles.
//
// The current bar must CLOSE beyond
// the relevant historical boundary.
//
// ============================================================================
float previousHigh = ta.highest(high[1], breakoutLookback)
float previousLow = ta.lowest(low[1], breakoutLookback)
float breakoutBuffer = (useBreakoutBuffer and atrReady ? atr * breakoutBufferATR : 0.0)
bool bullishBreakout = (not na(previousHigh) and close > previousHigh + breakoutBuffer)
bool bearishBreakout = (not na(previousLow) and close < previousLow - breakoutBuffer)

// ============================================================================
// 19. EMA PULLBACK RECLAIM
// ============================================================================
//
// LONG:
// Recent candle low has touched EMA.
// Price is now closing above EMA.
//
// SHORT:
// Recent candle high has touched EMA.
// Price is now closing below EMA.
//
// Optional fresh cross prevents repeated
// triggers on consecutive candles.
//
// ============================================================================
float pullbackEMA = ta.ema(close, pullbackEMALength)
float previousPullbackLow = ta.lowest(low, pullbackLookback)
float previousPullbackHigh = ta.highest(high, pullbackLookback)
bool touchedEMALong = (not na(previousPullbackLow) and previousPullbackLow <= pullbackEMA)
bool touchedEMAShort = (not na(previousPullbackHigh) and previousPullbackHigh >= pullbackEMA)
bool freshLongEMAOK = (not requireFreshEMAReclaim or (not na(close[1]) and not na(pullbackEMA[1]) and close[1] <= pullbackEMA[1]))
bool freshShortEMAOK = (not requireFreshEMAReclaim or (not na(close[1]) and not na(pullbackEMA[1]) and close[1] >= pullbackEMA[1]))
bool bullishPullback = (touchedEMALong and close > pullbackEMA and freshLongEMAOK)
bool bearishPullback = (touchedEMAShort and close < pullbackEMA and freshShortEMAOK)

// ============================================================================
// 20. SELECT ENTRY TRIGGER
// ============================================================================
bool longTrigger = (triggerMode == "Structure Breakout" ? bullishBreakout : triggerMode == "EMA Pullback Reclaim" ? bullishPullback : (bullishBreakout or bullishPullback))
bool shortTrigger = (triggerMode == "Structure Breakout" ? bearishBreakout : triggerMode == "EMA Pullback Reclaim" ? bearishPullback : (bearishBreakout or bearishPullback))

// ============================================================================
// 21. SIGNAL 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 candleRangeATR = (atrReady ? candleRange / atr : na)
bool bullishCandle = close > open
bool bearishCandle = close < open
bool longCandleOK = (not requireDirectionalCandle or bullishCandle)
bool shortCandleOK = (not requireDirectionalCandle or bearishCandle)
bool bodyOK = (not useBodyFilter or bodyRatio >= minimumBodyRatio)
bool longCloseOK = (not useCloseLocation or closePosition >= minimumLongClosePosition)
bool shortCloseOK = (not useCloseLocation or closePosition <= maximumShortClosePosition)
bool candleRangeOK = (not useCandleRangeFilter or (not na(candleRangeATR) and candleRangeATR >= minimumCandleATR and candleRangeATR <= maximumCandleATR))

// ============================================================================
// 22. EMA TREND
// ============================================================================
float trendEMA = ta.ema(close, emaLength)
bool emaUp = (not na(trendEMA[emaSlopeLookback]) and trendEMA > trendEMA[emaSlopeLookback])
bool emaDown = (not na(trendEMA[emaSlopeLookback]) and trendEMA < trendEMA[emaSlopeLookback])
float emaDistanceATR = (atrReady ? math.abs(close - trendEMA) / atr : na)
bool emaDistanceOK = (not useEMADistanceFilter or (not na(emaDistanceATR) and emaDistanceATR <= maximumEMADistanceATR))
bool longEMAOK = (not useEMAFilter or ((not requireEMASlope or emaUp) and (not requirePriceEMA or close > trendEMA)))
bool shortEMAOK = (not useEMAFilter or ((not requireEMASlope or emaDown) and (not requirePriceEMA or close < trendEMA)))

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

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

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

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

// ============================================================================
// 27. LONG ER SIGNAL
// ============================================================================
bool longBase = (barstate.isconfirmed and erReady and erModeOK and erSlopeOK and longDisplacementOK and longTrigger and longCandleOK and bodyOK and longCloseOK and candleRangeOK)

// ============================================================================
// 28. SHORT ER SIGNAL
// ============================================================================
bool shortBase = (barstate.isconfirmed and erReady and erModeOK and erSlopeOK and shortDisplacementOK and shortTrigger and shortCandleOK and bodyOK and shortCloseOK and candleRangeOK)

// ============================================================================
// 29. FINAL FILTERED SIGNALS
// ============================================================================
bool rawLong = (longBase and longEMAOK and emaDistanceOK and volumeOK and adxOK and longDIOK and longRSIOK and longH1OK)
bool rawShort = (shortBase and shortEMAOK and emaDistanceOK and volumeOK and adxOK and shortDIOK and shortRSIOK and shortH1OK)

// ============================================================================
// 30. ENTRY GATES
// ============================================================================
bool canTrade = (barstate.isconfirmed and intradayOK and erReady and atrReady 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)

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

// ============================================================================
// 32. DIAGNOSTIC COUNTERS
// ============================================================================
var int efficientBarCount = 0
var int erCrossCount = 0
var int longTriggerCount = 0
var int shortTriggerCount = 0
var int longBaseCount = 0
var int shortBaseCount = 0
var int filteredLongCount = 0
var int filteredShortCount = 0
var int blockedLongCount = 0
var int blockedShortCount = 0
var int longEntryCount = 0
var int shortEntryCount = 0
var int timeExitCount = 0
var int sessionExitCount = 0

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

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

// ============================================================================
// 35. UPDATE DIAGNOSTICS
// ============================================================================
if barstate.isconfirmed
    if efficientRegime
        efficientBarCount += 1
    if erThresholdCross
        erCrossCount += 1
    if longTrigger
        longTriggerCount += 1
    if shortTrigger
        shortTriggerCount += 1
    if longBase
        longBaseCount += 1
    if shortBase
        shortBaseCount += 1
    if rawLong
        filteredLongCount += 1
    if rawShort
        filteredShortCount += 1
    if rawLong and not enterLong
        blockedLongCount += 1
    if rawShort and not enterShort
        blockedShortCount += 1

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

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

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

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

// ============================================================================
// 40. EMA PLOTS
// ============================================================================
plot(showTrendEMA ? trendEMA : na, title="Trend EMA", color=color.orange, linewidth=2)
plot(showPullbackEMA ? pullbackEMA : na, title="Pullback EMA", color=color.aqua, linewidth=1)

// ============================================================================
// 41. BREAKOUT CHANNEL
// ============================================================================
plot(showBreakoutChannel ? previousHigh : na, title="Previous Channel High", color=color.new(color.red, 45), linewidth=1, style=plot.style_stepline)
plot(showBreakoutChannel ? previousLow : na, title="Previous Channel Low", color=color.new(color.green, 45), linewidth=1, style=plot.style_stepline)

// ============================================================================
// 42. EFFICIENT TREND BACKGROUND
// ============================================================================
bgcolor(showRegimeBackground and efficientRegime ? color.new(color.aqua, 93) : na, title="Efficient Trend Regime")

// ============================================================================
// 43. RAW TRIGGER MARKERS
// ============================================================================
plotshape(showRawTriggerMarkers and longTrigger, title="Bullish Structure/Pullback Trigger", style=shape.circle, location=location.belowbar, color=color.aqua, size=size.tiny, text="ER")
plotshape(showRawTriggerMarkers and shortTrigger, title="Bearish Structure/Pullback Trigger", style=shape.circle, location=location.abovebar, color=color.orange, size=size.tiny, text="ER")

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

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

// ============================================================================
// 46. DATA WINDOW
// ============================================================================
plot(efficiencyRatio, title="Kaufman Efficiency Ratio", color=color.aqua, display=display.data_window)
plot(netMovement, title="Net Price Movement", color=color.blue, display=display.data_window)
plot(netMovementATR, title="Net Movement / ATR", color=color.orange, display=display.data_window)
plot(totalMovement, title="Total Absolute Movement", color=color.gray, display=display.data_window)
plot(atr, title="ATR", color=color.gray, 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.blue, display=display.data_window)
plot(rsi, title="RSI", color=color.fuchsia, display=display.data_window)

// ============================================================================
// 47. DIAGNOSTICS TABLE
// ============================================================================
var table diagnostics = table.new(position.top_right, 2, 24, border_width=1)
if barstate.islast
    if showDiagnostics
        table.cell(diagnostics, 0, 0, "CNPS97 V1")
        table.cell(diagnostics, 1, 0, timeframe.period)
        table.cell(diagnostics, 0, 1, "ER")
        table.cell(diagnostics, 1, 1, str.tostring(efficiencyRatio, "#.###"))
        table.cell(diagnostics, 0, 2, "ER Threshold")
        table.cell(diagnostics, 1, 2, str.tostring(minimumER, "#.##"))
        table.cell(diagnostics, 0, 3, "Efficient Regime")
        table.cell(diagnostics, 1, 3, efficientRegime ? "YES" : "NO")
        table.cell(diagnostics, 0, 4, "Net Movement")
        table.cell(diagnostics, 1, 4, str.tostring(netMovement, "#.##"))
        table.cell(diagnostics, 0, 5, "Net Move / ATR")
        table.cell(diagnostics, 1, 5, str.tostring(netMovementATR, "#.##"))
        table.cell(diagnostics, 0, 6, "ER Crosses")
        table.cell(diagnostics, 1, 6, str.tostring(erCrossCount))
        table.cell(diagnostics, 0, 7, "Efficient Bars")
        table.cell(diagnostics, 1, 7, str.tostring(efficientBarCount))
        table.cell(diagnostics, 0, 8, "Long Triggers")
        table.cell(diagnostics, 1, 8, str.tostring(longTriggerCount))
        table.cell(diagnostics, 0, 9, "Short Triggers")
        table.cell(diagnostics, 1, 9, str.tostring(shortTriggerCount))
        table.cell(diagnostics, 0, 10, "Long Bases")
        table.cell(diagnostics, 1, 10, str.tostring(longBaseCount))
        table.cell(diagnostics, 0, 11, "Short Bases")
        table.cell(diagnostics, 1, 11, str.tostring(shortBaseCount))
        table.cell(diagnostics, 0, 12, "Filtered Long")
        table.cell(diagnostics, 1, 12, str.tostring(filteredLongCount))
        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(sessionExitCount))
        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 == "Trend Continuation" ? "CONTINUATION" : "ER CROSS")
        table.cell(diagnostics, 0, 23, "Trigger")
        table.cell(diagnostics, 1, 23, triggerMode)
    else
        table.clear(diagnostics, 0, 0, 1, 23)

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

2.1. Kaufman Efficiency Ratio (ER) và độ dịch chuyển ròng

Trái tim của CNPS97 là chỉ số Kaufman Efficiency Ratio (ER) đo lường mức độ “mạch lạc” của chuyển động giá trong cửa sổ erLength (mặc định 10 nến):

$$\text{ER} = \frac{|\text{Close} - \text{Close}[N]|}{\sum_{i=0}^{N-1} |\text{Close}[i] - \text{Close}[i+1]|}$$

Trong code, bot tính totalMovement = ta.sma(math.abs(close - close[1]), erLength) * erLength và giới hạn efficiencyRatio = math.min(1.0, absoluteNetMovement / totalMovement).

  • ER tiến gần 0: Giá đi quãng đường dài nhưng không dịch chuyển được bao xa (thị trường nhiễu, giật hai chiều).
  • ER tiến gần 1: Hầu hết các nến đều đóng góp vào một hướng duy nhất (xu hướng sạch, hiệu quả cao).

Vì ER là chỉ số không có hướng (luôn nằm trong [0, 1]), bot sử dụng biến netMovement = close - close[erLength] để phân định phe: netMovement > 0 là lực đẩy tăng, netMovement < 0 là lực đẩy giảm. Nếu bật useMinimumDisplacement, độ dịch chuyển ròng phải đạt tối thiểu atr * minimumDisplacementATR (mặc định 0.50 ATR).

2.2. Hai cơ chế kích hoạt điểm vào: Structure Breakout & EMA Pullback Reclaim

Khi ER xác nhận xu hướng đủ hiệu quả (erModeOK), CNPS97 yêu cầu một tín hiệu hành động giá cụ thể để bóp cò lệnh:

  • Structure Breakout (mặc định): Tính đỉnh/đáy của breakoutLookback nến liền trước (previousHigh = ta.highest(high[1], 3), previousLow = ta.lowest(low[1], 3)). Nến hiện tại phải đóng cửa vượt qua biên độ này (cộng/trừ thêm breakoutBuffer theo ATR nếu bật useBreakoutBuffer).
  • EMA Pullback Reclaim: Tính pullbackEMA = ta.ema(close, 10). Giá trong pullbackLookback (3 nến gần nhất) phải có nhịp chạm vào EMA (low <= pullbackEMA với Long, high >= pullbackEMA với Short), sau đó nến hiện tại đóng cửa giành lại phía trên/dưới EMA. Nếu bật requireFreshEMAReclaim (mặc định true), nến liền trước (close[1]) phải nằm ở phía ngược lại để tránh kích hoạt lặp lại liên tiếp.
  • Either: Chấp nhận một trong hai tín hiệu trên.

2.3. Giải phẫu nến tín hiệu và các bộ lọc xác nhận tùy chọn

Mỗi nến kích hoạt tín hiệu đều phải vượt qua lớp kiểm tra cấu trúc nến (03. Signal Candle):

  • Nến cùng chiều (requireDirectionalCandle = true): Long phải là nến xanh (close > open), Short phải là nến đỏ (close < open).
  • Tỷ lệ thân nến (useBodyFilter = true): bodyRatio = abs(close - open) / (high - low) >= 0.30.
  • Tùy chọn nâng cao (mặc định tắt): Lọc vị trí đóng cửa (closePosition), biên độ nến theo ATR (candleRange / atr), bộ lọc xu hướng trendEMA(50) kèm độ dốc và khoảng cách tối đa tới EMA, khối lượng tương đối (relativeVolume), ADX(14) & hướng DI+/DI-, RSI(14), và xu hướng khung H1 (request.security(..., "60", ..., lookahead=barmerge.lookahead_on) lấy giá trị nến H1 đã đóng [1] để đảm bảo không repaint).

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

Quy trình vận hành của CNPS97 trên mỗi nến đã đóng (barstate.isconfirmed) diễn ra tuần tự qua 5 bước:

  1. Khởi tạo phiên và đếm ngày mới: Kiểm tra dayKey theo múi giờ Asia/Ho_Chi_Minh. Khi sang ngày giao dịch mới (newDay), bộ đếm tradesToday được reset về 0. Đồng thời tính toán khung giờ giao dịch entrySessionOK (09:15–14:15) và cờ ép đóng cuối phiên forceCloseBar (14:45).
  2. Đo lường chế độ thị trường (ER Engine): Tính ATR(14), efficiencyRatio và netMovement. Kiểm tra điều kiện chế độ xu hướng hiệu quả (efficientRegime hoặc erThresholdCross) cùng hướng dịch chuyển ròng.
  3. Kiểm tra Trigger và giải phẫu nến: Đánh giá tín hiệu Structure Breakout hoặc EMA Pullback Reclaim kết hợp điều kiện thân nến, hướng nến để hình thành tín hiệu nền longBase / shortBase.
  4. Áp dụng các bộ lọc nâng cao & cổng an toàn: Đưa qua các bộ lọc EMA, Volume, ADX, RSI, H1 Bias (nếu bật) để ra rawLong / rawShort. Kiểm tra cổng an toàn canTrade (không có vị thế mở, chưa chạm giới hạn lệnh ngày, hết cooldown, đúng giờ phiên) và loại bỏ trường hợp tín hiệu lưỡng tính (ambiguousSignal = rawLong and rawShort).
  5. Thực thi và quản trị lệnh: Gửi lệnh strategy.entry, gắn ngay lệnh bảo vệ strategy.exit với SL/TP cố định theo tick, theo dõi tùy chọn Time Exit và tự động strategy.close_all tại nến 14:45.

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

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

Bot mở vị thế Long (enterLong) khi canTrade == true, allowLong == true, không bị ambiguousSignal và thỏa mãn toàn bộ chuỗi điều kiện sau:

  1. Chế độ ER đạt chuẩn (erModeOK & erSlopeOK): efficiencyRatio >= 0.30 (chế độ Trend Continuation) hoặc efficiencyRatio vừa cắt lên trên 0.30 (chế độ ER Threshold Cross). Nếu bật requireERRising, ER phải lớn hơn erSlopeLookback nến trước.
  2. Dịch chuyển ròng dương (longDisplacementOK): close - close[erLength] > 0 (và >= atr * minimumDisplacementATR nếu bật useMinimumDisplacement).
  3. Có Trigger tăng (longTrigger): close > previousHigh + breakoutBuffer (nếu chọn Structure Breakout) hoặc giá gần đây chạm pullbackEMA(10) rồi đóng cửa > pullbackEMA với close[1] <= pullbackEMA[1] (nếu chọn EMA Pullback Reclaim).
  4. Nến tín hiệu đạt chuẩn: Là nến tăng (close > open), bodyRatio >= 0.30, cùng các điều kiện vị trí đóng cửa / biên độ ATR nếu được bật.
  5. Bộ lọc phụ trợ (nếu bật): Giá trên trendEMA(50) và EMA dốc lên, khoảng cách EMA hợp lệ, relativeVolume >= 1.0, ADX >= 18.0 (DI+ > DI-), RSI >= 52.0, và nến H1 đã đóng có h1Close > h1EMA(50).

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

Bot mở vị thế Short (enterShort) đối xứng hoàn toàn với Long khi canTrade == true, allowShort == true, không bị ambiguousSignal:

  1. Chế độ ER đạt chuẩn (erModeOK & erSlopeOK): Tương tự chiều Long.
  2. Dịch chuyển ròng âm (shortDisplacementOK): close - close[erLength] < 0 (và -netMovement >= atr * minimumDisplacementATR nếu bật useMinimumDisplacement).
  3. Có Trigger giảm (shortTrigger): close < previousLow - breakoutBuffer (với Structure Breakout) hoặc giá gần đây chạm pullbackEMA(10) rồi đóng cửa < pullbackEMA với close[1] >= pullbackEMA[1] (với EMA Pullback Reclaim).
  4. Nến tín hiệu đạt chuẩn: Là nến giảm (close < open), bodyRatio >= 0.30, cùng các điều kiện vị trí đóng cửa / biên độ ATR nếu được bật.
  5. Bộ lọc phụ trợ (nếu bật): Giá dưới trendEMA(50) và EMA dốc xuống, khoảng cách EMA hợp lệ, relativeVolume >= 1.0, ADX >= 18.0 (DI- > DI+), RSI <= 48.0, và nến H1 đã đóng có h1Close < h1EMA(50).

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

Tất cả lệnh mới đều bị chặn nếu không thỏa mãn khối kiểm soát canTrade:

  • Nến đã xác nhận & khung intraday: barstate.isconfirmed == true và timeframe.isintraday == true, đồng thời erReady và atrReady phải sẵn sàng.
  • Trạng thái Flat: strategy.position_size == 0 và strategy.opentrades == 0 (pyramiding=0, không nhồi lệnh).
  • Giới hạn số lệnh ngày: tradesToday < maximumTradesPerDay (mặc định tối đa 3 lệnh/ngày).
  • Cooldown & khoảng cách giữa các lệnh: bar_index - lastExitBar > cooldownBars (mặc định nghỉ hơn 2 nến sau khi đóng lệnh) và bar_index - lastEntryBar > minimumBarsBetweenEntries (cách hơn 3 nến giữa các lần vào lệnh).
  • Khung giờ giao dịch: Nằm trong 09:15–14:15 (entrySessionOK) và trước giờ ép đóng 14:45 (beforeForceClose).

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

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

CNPS97 sử dụng cơ chế cắt lỗ cố định theo điểm (stopLossPoints = 5.0), được quy đổi sang đơn vị tick tối thiểu của sàn (syminfo.mintick, với VN30F1M là 0.1 điểm tương đương 50 ticks):

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

Khoảng cắt lỗ này được gắn trực tiếp vào strategy.exit ngay khi lệnh khớp và vẽ thành đường màu đỏ (Long SL / Short SL) trên biểu đồ khi showSLTP = true. Bot không sử dụng bộ lọc Min–Max Risk trước khi vào lệnh.

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

  • Take Profit cố định: takeProfitPoints = 15.0 (tỷ lệ R:R mặc định 1:3), quy đổi sang tpTicks = math.max(1, int(math.round(takeProfitPoints / syminfo.mintick))).
  • Thoát lệnh theo thời gian (useTimeExit): Mặc định false. Nếu bật, khi số nến nắm giữ barsHeld >= maximumHoldingBars (mặc định 20 nến) tại nến đã đóng (và không trùng nến ép đóng phiên), bot đóng toàn bộ vị thế bằng strategy.close_all(immediately=true, comment="Time Exit").
  • Ép đóng hết phiên (forceCloseBar): Tại nến giao qua mốc 14:45 (openMinutes < 14:45 và closeMinutes >= 14:45), nếu vẫn còn vị thế, bot bắt buộc đóng sạch bằng strategy.close_all(immediately=true, comment="Session End") để không giữ lệnh qua đêm.
  • (Lưu ý: Bot không tích hợp cơ chế dời hòa vốn Break Even hay Trailing Stop).

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

Cơ chế thoát lệnhĐiều kiện kích hoạtMặc địnhHành động trong code
Stop Loss cố địnhGiá chạm mức lỗ slTicks5.0 điểmstrategy.exit(..., loss=slTicks)
Take Profit cố địnhGiá chạm mức lãi tpTicks15.0 điểmstrategy.exit(..., profit=tpTicks)
Time ExitbarsHeld >= maximumHoldingBarsTắt (20 nến)strategy.close_all(immediately=true, comment="Time Exit")
Session Force CloseNến đóng chạm mốc 14:45Bật (14:45)strategy.close_all(immediately=true, comment="Session End")

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

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

  1. Mở biểu đồ hợp đồng tương lai VN30F1M trên TradingView (khuyến nghị khung thời gian intraday như M5 hoặc M15; lưu ý nếu bật useH1Bias thì khung biểu đồ bắt buộc phải nhỏ hơn H1).
  2. Nhấn vào tab Pine Editor ở thanh công cụ phía dưới màn hình.
  3. Xóa mã mặc định, sao chép toàn bộ Source Code CNPS97 ở Mục 1 và dán vào Pine Editor.
  4. Nhấn Save (Lưu), đặt tên script (ví dụ: CNPS97 ER Trend), sau đó nhấn Add to chart (Thêm vào biểu đồ).
  5. Nhấn biểu tượng bánh răng Settings của chiến lược để bật/tắt các bộ lọc nâng cao hoặc bật Show Diagnostics Table nếu muốn theo dõi bảng thống kê trực tiếp.

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

Khi bật showDiagnostics = true trong nhóm 12. Display, bot hiển thị một bảng 24 dòng ở góc trên bên phải biểu đồ (position.top_right) giúp bạn kiểm tra nhanh sức khỏe tín hiệu:

  • ER / ER Threshold / Efficient Regime: Giá trị ER hiện tại, ngưỡng minimumER và trạng thái YES/NO cho biết thị trường có đang ở chế độ xu hướng hiệu quả hay không.
  • Net Movement / Net Move / ATR: Độ dịch chuyển ròng hiện tại theo điểm và theo bội số ATR.
  • ER Crosses / Efficient Bars: Tổng số lần ER cắt lên ngưỡng và tổng số nến đạt trạng thái hiệu quả trong lịch sử biểu đồ.
  • Long/Short Triggers & Long/Short Bases: Số lần Trigger xảy ra và số lần vượt qua bộ lọc ER + giải phẫu nến.
  • Filtered Long/Short & Blocked Long/Short: Số tín hiệu qua toàn bộ bộ lọc phụ trợ, và số tín hiệu bị chặn bởi cổng kiểm soát (canTrade như hết giờ, đủ lệnh ngày, đang có vị thế hoặc cooldown).
  • Long/Short Entries, Time Exits, Session Exits: Thống kê số lệnh thực tế đã vào và số lần thoát do hết giờ/hết phiên.
  • Trades Today / Position / Entry Mode / Trigger: Số lệnh đã giao dịch trong ngày hiện tại (tradesToday/3), vị thế hiện tại (LONG, SHORT hoặc FLAT), chế độ ER và loại Trigger đang kích hoạt.

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 CNPS97 vào hoặc đóng lệnh:

  1. Trên biểu đồ đã gắn chiến lược CNPS97, nhấn nút Alert (biểu tượng đồng hồ) hoặc tổ hợp phím Alt + A.
  2. Ở mục Condition, chọn đúng tên chiến lược CNPS97 EFFICIENCY RATIO TREND ENTRY V1.
  3. Ở mục Message, xóa nội dung mặc định và điền chính xác biến: {{strategy.order.alert_message}}.
  4. Nếu không muốn nhận thông báo khi chạm SL/TP tự động, bạn có thể tích chọn Disable SL/TP Alerts (disableExitAlerts = true) trong phần cài đặt của bot.
  5. Nhấn Create để kích hoạt cảnh báo.

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

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

Kết luận

CNPS97 EFFICIENCY RATIO TREND ENTRY V1 là một hệ thống giao dịch theo xu hướng có tính kỷ luật cao, nổi bật nhờ khả năng lượng hóa độ “sạch” của xu hướng thông qua Kaufman Efficiency Ratio. Bot phát huy hiệu quả tốt nhất trong các phiên VN30F1M có dòng tiền định hướng rõ ràng, bứt phá dứt khoát hoặc hồi về EMA gọn gàng sau khi phá vỡ vùng tích lũy nhiễu, đồng thời giữ tỷ lệ R:R cố định 1:3 và đóng vị thế an toàn trước phiên ATC.

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

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

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

Đinh Mạnh Đạt

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

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

Giao dịch & cuộc sống

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