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

Hướng Dẫn Sử Dụng Bot CNPS88 - Effort vs Result Reversal V1 cho VN30F1M

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

Trong giao dịch phái sinh VN30F1M, các pha đảo chiều giả (fakeout) hoặc quét thanh khoản thường để lại dấu vết rõ nét qua sự mất cân xứng giữa nỗ lực khối lượng (Effort) và kết quả dịch chuyển giá (Result). Nếu vào lệnh quá sớm ngay khi thấy râu nến dài mà thiếu cơ chế đo lường khối lượng tương đối và bước xác nhận động lượng kế tiếp, trader rất dễ bị cuốn vào nhịp tiếp diễn xu hướng trước đó.

CNPS88 EFFORT VS RESULT REVERSAL V1 (viết bằng Pine Script v6 trên TradingView) được xây dựng để giải quyết bài toán này bằng cách lượng hóa mô hình hấp thụ thanh khoản (proxy từ giá và khối lượng, không đo trực tiếp sổ lệnh bid/ask) tại các vùng đỉnh/đáy swing gần nhất.

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

  • Đo lường Effort khách quan: So sánh khối lượng nến hiện tại với trung bình 20 nến trước đó (volume[1]), tránh tình trạng chính nến đột biến tự làm phồng đường cơ sở.
  • Đánh giá Result đa chiều: Kết hợp tỷ lệ thân nến nhỏ (<= 0.40), tỷ lệ râu từ chối giá (>= 0.25), vị trí giá đóng cửa và biên độ nến theo ATR(14).
  • Xác nhận ở nến kế tiếp: Mặc định sử dụng chế độ Next Candle Confirmation trong cửa sổ tối đa 5 nến, giúp lọc nhiễu và tự động hủy setup nếu giá phá vỡ ngược đầu còn lại.
  • Quản trị rủi ro chặt chẽ: Cài đặt sẵn Stop Loss 5.0 điểm, Take Profit 15.0 điểm (tỷ lệ R:R 1:3), giới hạn 2 lệnh/ngày, cooldown 3 nến và tự động đóng toàn bộ vị thế cuối phiên lúc 14:45.

1. CNPS88 Effort vs Result Reversal V1 là gì?

CNPS88 EFFORT VS RESULT REVERSAL V1 là hệ thống giao dịch đảo chiều trong ngày (intraday) dựa trên 4 trụ cột kỹ thuật chính:

  1. Nỗ lực khối lượng (Effort - Volume): Xác định những thanh nến có khối lượng tăng đột biến tối thiểu 1.80 lần so với trung bình 20 nến liền trước.
  2. Hiệu suất giá (Result - Price Efficiency): Tìm kiếm nến có thân hẹp (Body / Range <= 0.40), biên độ nằm trong ngưỡng hợp lý so với ATR(14) (0.40 – 2.50), đồng thời sở hữu râu nến từ chối giá rõ rệt (>= 25% biên độ nến) và giá đóng cửa nằm ở nửa thuận lợi.
  3. Vị trí cấu trúc (Swing Location): Chỉ công nhận tín hiệu hấp thụ khi nến xuất hiện gần đỉnh hoặc đáy của 15 nến trước đó (sai số cho phép 0.20 * ATR), kèm tùy chọn quét thanh khoản (Swing Sweep And Reclaim).
  4. Cơ chế xác nhận & Kiểm soát rủi ro: Lưu trạng thái Pending Long/Short và chờ nến sau phá vỡ cực trị nến tín hiệu để vào lệnh, đi kèm hệ thống SL/TP cố định theo điểm và đóng lệnh cuối phiên.

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

Nhóm thông sốTham số trong codeGiá trị mặc địnhÝ nghĩa
01. Effort - VolumevolumeLength / minimumVolumeRatio20 / 1.80So sánh volume hiện tại với SMA(20) của các nến trước
01. Effort - VolumeuseMaximumVolume / maximumVolumeRatiofalse / 6.0Tùy chọn giới hạn trần tỷ lệ khối lượng
02. Result - Price EfficiencyatrLength / maximumBodyRatio14 / 0.40Chu kỳ ATR và tỷ lệ thân nến tối đa trên toàn biên độ
02. Result - Price EfficiencyminimumWickRatio / useCloseLocation0.25 / trueTỷ lệ râu từ chối tối thiểu và lọc vị trí đóng cửa
02. Result - Price EfficiencyminimumLongClosePosition / maximumShortClosePosition0.55 / 0.45Ngưỡng vị trí đóng cửa cho Long (>= 0.55) và Short (<= 0.45)
02. Result - Price EfficiencyuseCandleRange (minimumRangeATR – maximumRangeATR)true (0.40 – 2.50)Lọc biên độ nến hợp lệ theo bội số ATR
03. Swing LocationuseSwingFilter / swingLookback / swingToleranceATRtrue / 15 / 0.20Yêu cầu nến nằm gần đỉnh/đáy 15 nến trước (±0.20 ATR)
03. Swing LocationrequireSwingSweepfalseTùy chọn bắt buộc quét qua swing rồi rút chân đóng lại
04. Entry ConfirmationentryMode / confirmationWindowNext Candle Confirmation / 5Chờ xác nhận nến sau trong tối đa 5 nến cùng ngày
04. Entry ConfirmationrequireBreakExtreme / requireConfirmCandletrue / trueYêu cầu nến xác nhận phá đỉnh/đáy setup và đúng màu nến
04. Entry ConfirmationcancelOnNewExtreme / invalidationBufferATRtrue / 0.10Hủy setup nếu giá phá ngược cực trị ±0.10 ATR
05–07. Trend & Optional FiltersuseEMAFilter / useADXFilter / useRSIFilter / useH1Biasfalse (tất cả)Các bộ lọc EMA(50), ADX(14)<=35, RSI(14) và H1 EMA(50)
08. Risk ManagementstopLossPoints / takeProfitPoints5.0 / 15.0Cắt lỗ 5.0 điểm, chốt lời 15.0 điểm
08. Risk ManagementuseTimeExit / maximumHoldingBarsfalse / 20Tùy chọn thoát lệnh theo số nến nắm giữ
09. Trade ControltradeDirection / contractsLong / 3Chiều giao dịch mặc định Long (có thể chọn Both), 3 HĐ
09. Trade ControlmaximumTradesPerDay / cooldownBars2 / 3Tối đa 2 lệnh/ngày, nghỉ 3 nến sau khi đóng lệnh
10. Trading SessionstartHour:startMinute – lastHour:lastMinute09:15 – 14:15Khung giờ cho phép mở vị thế (Asia/Ho_Chi_Minh)
10. Trading SessionendHour:endMinute14:45Giờ đóng toàn bộ vị thế cuối phiên (Force Close)

Source Code CNPS88 Effort vs Result Reversal 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="CNPS88 EFFORT VS RESULT REVERSAL V1", shorttitle="CNPS88 EFFORT RESULT", 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)

// ============================================================================
// CNPS88 - EFFORT VS RESULT REVERSAL
//
// EFFORT:
// High relative volume compared with previous bars.
//
// RESULT:
// Small real body relative to total candle range,
// with rejection wick at a recent swing extreme.
//
// BULLISH:
// High volume + low price progress + lower rejection.
// Then require upside confirmation.
//
// BEARISH:
// High volume + low price progress + upper rejection.
// Then require downside confirmation.
//
// Setup and confirmation occur on separate bars
// in the default mode.
//
// This is a volume/price proxy for absorption,
// not direct bid/ask order-flow measurement.
// ============================================================================
// ============================================================================
// 01. EFFORT - VOLUME
// ============================================================================
gEffort = "01. Effort - Volume"
volumeLength = input.int(20, "Volume Average Length", minval=2, maxval=300, group=gEffort)
minimumVolumeRatio = input.float(1.80, "Minimum Volume Ratio", minval=0.1, step=0.1, group=gEffort)
useMaximumVolume = input.bool(false, "Use Maximum Volume Ratio", group=gEffort)
maximumVolumeRatio = input.float(6.0, "Maximum Volume Ratio", minval=1.0, step=0.5, group=gEffort)

// ============================================================================
// 02. RESULT - CANDLE EFFICIENCY
// ============================================================================
gResult = "02. Result - Price Efficiency"
atrLength = input.int(14, "ATR Length", minval=1, group=gResult)
maximumBodyRatio = input.float(0.40, "Maximum Body / Candle Range", minval=0.05, maxval=1.0, step=0.05, group=gResult)
minimumWickRatio = input.float(0.25, "Minimum Rejection Wick / Range", minval=0.0, maxval=1.0, step=0.05, group=gResult)
useCloseLocation = input.bool(true, "Require Rejection Close Location", group=gResult)
minimumLongClosePosition = input.float(0.55, "Minimum Long Close Position", minval=0.0, maxval=1.0, step=0.05, group=gResult)
maximumShortClosePosition = input.float(0.45, "Maximum Short Close Position", minval=0.0, maxval=1.0, step=0.05, group=gResult)
useCandleRange = input.bool(true, "Filter Candle Range / ATR", group=gResult)
minimumRangeATR = input.float(0.40, "Minimum Candle Range / ATR", minval=0.0, step=0.1, group=gResult)
maximumRangeATR = input.float(2.50, "Maximum Candle Range / ATR", minval=0.1, step=0.1, group=gResult)

// ============================================================================
// 03. SWING LOCATION
// ============================================================================
gSwing = "03. Swing Location"
useSwingFilter = input.bool(true, "Require Recent Swing Extreme", group=gSwing)
swingLookback = input.int(15, "Swing Lookback", minval=3, maxval=200, group=gSwing)
swingToleranceATR = input.float(0.20, "Swing Proximity / ATR", minval=0.0, step=0.05, group=gSwing)
requireSwingSweep = input.bool(false, "Require Swing Sweep And Reclaim", group=gSwing)

// ============================================================================
// 04. CONFIRMATION
// ============================================================================
gConfirm = "04. Entry Confirmation"
entryMode = input.string("Next Candle Confirmation", "Entry Mode", options=["Signal Candle Close", "Next Candle Confirmation"], group=gConfirm)
confirmationWindow = input.int(5, "Maximum Confirmation Bars", minval=1, maxval=30, group=gConfirm)
requireBreakExtreme = input.bool(true, "Require Break Of Setup High/Low", group=gConfirm)
useBreakoutBuffer = input.bool(false, "Use Breakout Buffer", group=gConfirm)
breakoutBufferATR = input.float(0.05, "Breakout Buffer / ATR", minval=0.0, step=0.05, group=gConfirm)
requireConfirmCandle = input.bool(true, "Require Bullish/Bearish Confirmation", group=gConfirm)
cancelOnNewExtreme = input.bool(true, "Cancel On Opposite Extreme Break", group=gConfirm)
invalidationBufferATR = input.float(0.10, "Invalidation Buffer / ATR", minval=0.0, step=0.05, group=gConfirm)

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

// ============================================================================
// 06. OPTIONAL FILTERS
// ============================================================================
gFilters = "06. Optional Filters"
useADXFilter = input.bool(false, "Use Maximum ADX Filter", group=gFilters)
diLength = input.int(14, "DI Length", minval=2, group=gFilters)
adxSmoothing = input.int(14, "ADX Smoothing", minval=2, group=gFilters)
maximumADX = input.float(35.0, "Maximum ADX", minval=1.0, step=1.0, group=gFilters)
useRSIFilter = input.bool(false, "Use RSI Filter", group=gFilters)
rsiLength = input.int(14, "RSI Length", minval=2, group=gFilters)
longRSIMax = input.float(65.0, "Maximum RSI For Long", minval=1.0, maxval=100, group=gFilters)
shortRSIMin = input.float(35.0, "Minimum RSI For Short", minval=0.0, maxval=99, group=gFilters)

// ============================================================================
// 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=1, 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("Long", "Trade Direction", options=["Long", "Short", "Both"], group=gTrade)
contracts = input.int(3, "Contracts", minval=1, maxval=100, group=gTrade)
maximumTradesPerDay = input.int(2, "Maximum Trades Per Day", minval=1, maxval=20, group=gTrade)
cooldownBars = input.int(3, "Cooldown After Exit (Bars)", 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"
useSessionFilter = input.bool(true, "Use Entry Session Filter", group=gSession)
tz = input.string("Asia/Ho_Chi_Minh", "Timezone", group=gSession)
startHour = input.int(9, "Entry Start Hour", minval=0, maxval=23, group=gSession)
startMinute = input.int(15, "Entry Start Minute", minval=0, maxval=59, group=gSession)
lastHour = input.int(14, "Last Entry Hour", minval=0, maxval=23, group=gSession)
lastMinute = input.int(15, "Last Entry Minute", minval=0, maxval=59, group=gSession)
endHour = input.int(14, "Force Close Hour", minval=0, maxval=23, group=gSession)
endMinute = input.int(45, "Force Close Minute", minval=0, maxval=59, group=gSession)

// ============================================================================
// 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)
showEffortMarkers = input.bool(false, "Show High Effort Dots", group=gDisplay)
showSetupMarkers = input.bool(false, "Show Effort/Result Setup Dots", group=gDisplay)
showSwingLevels = input.bool(false, "Show Swing Levels", group=gDisplay)
showPendingLevels = input.bool(true, "Show Pending Confirmation Levels", group=gDisplay)
showEntryMarkers = input.bool(true, "Show Entry Markers", group=gDisplay)
showSLTP = input.bool(true, "Show Active SL/TP", group=gDisplay)
showDiagnostics = input.bool(false, "Show Diagnostics", group=gDisplay)

// ============================================================================
// 13. 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 COUNTER
// ============================================================================
int dayKey = (year(time, tz) * 10000 + month(time, tz) * 100 + dayofmonth(time, tz))
bool newDay = (na(dayKey[1]) or dayKey != dayKey[1])
var int tradesToday = 0
if newDay
    tradesToday := 0

// ============================================================================
// 15. INDICATORS
// ============================================================================
float atr = ta.atr(atrLength)
float ema = ta.ema(close, emaLength)
float rsi = ta.rsi(close, rsiLength)
[diPlus, diMinus, adx] = ta.dmi(diLength, adxSmoothing)

// ============================================================================
// 16. EFFORT CALCULATION
// ============================================================================
//
// Compare current volume with a moving
// average of PREVIOUS candles only.
//
// Current high-volume candle does not
// inflate its own reference average.
//
// ============================================================================
float previousAverageVolume = ta.sma(volume[1], volumeLength)
float volumeRatio = (not na(volume) and not na(previousAverageVolume) and previousAverageVolume > 0 ? volume / previousAverageVolume : na)
bool highEffort = (not na(volumeRatio) and volumeRatio >= minimumVolumeRatio and (not useMaximumVolume or volumeRatio <= maximumVolumeRatio))

// ============================================================================
// 17. RESULT CALCULATION
// ============================================================================
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 lowerWick = (math.min(open, close) - low)
float upperWick = (high - math.max(open, close))
float lowerWickRatio = (candleRange > 0 ? lowerWick / candleRange : 0.0)
float upperWickRatio = (candleRange > 0 ? upperWick / candleRange : 0.0)
float candleRangeATR = (not na(atr) and atr > 0 ? candleRange / atr : na)
bool lowResult = (candleRange > 0 and bodyRatio <= maximumBodyRatio)
bool candleRangeOK = (not useCandleRange or (not na(candleRangeATR) and candleRangeATR >= minimumRangeATR and candleRangeATR <= maximumRangeATR))
bool bullishRejection = (lowerWickRatio >= minimumWickRatio and (not useCloseLocation or closePosition >= minimumLongClosePosition))
bool bearishRejection = (upperWickRatio >= minimumWickRatio and (not useCloseLocation or closePosition <= maximumShortClosePosition))

// ============================================================================
// 18. SWING EXTREMES
// ============================================================================
//
// Exclude current candle from swing levels.
//
// ============================================================================
float previousSwingHigh = ta.highest(high[1], swingLookback)
float previousSwingLow = ta.lowest(low[1], swingLookback)
float swingTolerance = (not na(atr) ? atr * swingToleranceATR : 0.0)
bool nearSwingLow = (not na(previousSwingLow) and low <= previousSwingLow + swingTolerance)
bool nearSwingHigh = (not na(previousSwingHigh) and high >= previousSwingHigh - swingTolerance)
bool longSwingOK = (not useSwingFilter or nearSwingLow)
bool shortSwingOK = (not useSwingFilter or nearSwingHigh)
bool longSweepOK = (not requireSwingSweep or (not na(previousSwingLow) and low < previousSwingLow and close > previousSwingLow))
bool shortSweepOK = (not requireSwingSweep or (not na(previousSwingHigh) and high > previousSwingHigh and close < previousSwingHigh))

// ============================================================================
// 19. EFFORT VS RESULT SETUPS
// ============================================================================
bool bullishSetup = (barstate.isconfirmed and highEffort and lowResult and candleRangeOK and bullishRejection and longSwingOK and longSweepOK)
bool bearishSetup = (barstate.isconfirmed and highEffort and lowResult and candleRangeOK and bearishRejection and shortSwingOK and shortSweepOK)

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

// ============================================================================
// 21. ADX / RSI FILTERS
// ============================================================================
bool adxOK = (not useADXFilter or (not na(adx) and adx <= maximumADX))
bool longRSIOK = (not useRSIFilter or (not na(rsi) and rsi <= longRSIMax))
bool shortRSIOK = (not useRSIFilter or (not na(rsi) and rsi >= shortRSIMin))

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

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

// ============================================================================
// 24. PENDING SETUP STATE
// ============================================================================
//
// Save high/low/close of each confirmed
// Effort vs Result setup.
//
// In confirmation mode, orders may only
// be submitted on subsequent candles.
//
// ============================================================================
var bool pendingLong = false
var bool pendingShort = false
var int longSignalBar = na
var int shortSignalBar = na
var int longSignalDay = na
var int shortSignalDay = na
var float longSignalHigh = na
var float longSignalLow = na
var float longSignalClose = na
var float shortSignalHigh = na
var float shortSignalLow = na
var float shortSignalClose = na
var int effortCount = 0
var int lowResultCount = 0
var int bullSetupCount = 0
var int bearSetupCount = 0
var int longBaseCount = 0
var int shortBaseCount = 0
var int filteredLongCount = 0
var int filteredShortCount = 0
var int expiredLongCount = 0
var int expiredShortCount = 0
var int longEntryCount = 0
var int shortEntryCount = 0
bool confirmationMode = (entryMode == "Next Candle Confirmation")

// ============================================================================
// 25. CONFIRMATION WINDOW
// ============================================================================
bool validLongWindow = (pendingLong and not na(longSignalBar) and longSignalDay == dayKey and bar_index > longSignalBar and bar_index - longSignalBar <= confirmationWindow)
bool validShortWindow = (pendingShort and not na(shortSignalBar) and shortSignalDay == dayKey and bar_index > shortSignalBar and bar_index - shortSignalBar <= confirmationWindow)
float breakoutBuffer = (useBreakoutBuffer and not na(atr) ? atr * breakoutBufferATR : 0.0)
float invalidationBuffer = (not na(atr) ? atr * invalidationBufferATR : 0.0)

// ============================================================================
// 26. SETUP INVALIDATION
// ============================================================================
bool longInvalid = (validLongWindow and cancelOnNewExtreme and not na(longSignalLow) and low < longSignalLow - invalidationBuffer)
bool shortInvalid = (validShortWindow and cancelOnNewExtreme and not na(shortSignalHigh) and high > shortSignalHigh + invalidationBuffer)

// ============================================================================
// 27. CONFIRMATION PRICE ACTION
// ============================================================================
bool longCandleOK = (not requireConfirmCandle or close > open)
bool shortCandleOK = (not requireConfirmCandle or close < open)
bool longPriceOK = (validLongWindow and (requireBreakExtreme ? (not na(longSignalHigh) and close > longSignalHigh + breakoutBuffer) : (not na(longSignalClose) and close > longSignalClose)))
bool shortPriceOK = (validShortWindow and (requireBreakExtreme ? (not na(shortSignalLow) and close < shortSignalLow - breakoutBuffer) : (not na(shortSignalClose) and close < shortSignalClose)))
bool confirmedLong = (barstate.isconfirmed and longPriceOK and longCandleOK and not longInvalid)
bool confirmedShort = (barstate.isconfirmed and shortPriceOK and shortCandleOK and not shortInvalid)

// ============================================================================
// 28. ENTRY BASES
// ============================================================================
bool longBase = (confirmationMode ? confirmedLong : bullishSetup)
bool shortBase = (confirmationMode ? confirmedShort : bearishSetup)

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

// ============================================================================
// 30. ENTRY GATES
// ============================================================================
bool canTrade = (barstate.isconfirmed and intradayOK and flat and strategy.opentrades == 0 and tradesToday < maximumTradesPerDay and cooldownOK and freshEntryBar 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. RISK MANAGEMENT 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. LONG ENTRY
// ============================================================================
if enterLong
    strategy.entry("Long", strategy.long, comment="Effort Result LONG", alert_message="🟢 VÀO VỊ THẾ LONG (CNPS88)\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\n🛑 Cắt lỗ (SL): " + str.tostring(close - effectiveSL, format.mintick) + "\n💰 Chốt lời (TP): " + str.tostring(close + effectiveTP, format.mintick))
    tradesToday += 1
    longEntryCount += 1
    lastEntryBar := bar_index

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

// ============================================================================
// 34. UPDATE SETUP STATE
// ============================================================================
//
// State updates occur AFTER current-bar
// entry conditions are evaluated.
//
// The setup cannot confirm itself on
// its own candle.
//
// ============================================================================
if barstate.isconfirmed
    if highEffort
        effortCount += 1
    if highEffort and lowResult
        lowResultCount += 1
    if bullishSetup
        bullSetupCount += 1
    if bearishSetup
        bearSetupCount += 1
    if longBase
        longBaseCount += 1
    if shortBase
        shortBaseCount += 1
    if rawLong
        filteredLongCount += 1
    if rawShort
        filteredShortCount += 1

    // --------------------------------------------------------
    // NEW DAY RESET
    // --------------------------------------------------------
    if newDay
        pendingLong := false
        pendingShort := false
        longSignalBar := na
        shortSignalBar := na
        longSignalDay := na
        shortSignalDay := na
        longSignalHigh := na
        longSignalLow := na
        longSignalClose := na
        shortSignalHigh := na
        shortSignalLow := na
        shortSignalClose := na

    // --------------------------------------------------------
    // LONG EXPIRATION
    // --------------------------------------------------------
    if pendingLong and not na(longSignalBar)
        bool longExpired = (longSignalDay != dayKey or bar_index - longSignalBar > confirmationWindow)
        bool longInvalidNow = (cancelOnNewExtreme and not na(longSignalLow) and low < longSignalLow - invalidationBuffer)
        if longExpired or longInvalidNow or enterLong
            if longExpired or longInvalidNow
                expiredLongCount += 1
            pendingLong := false
            longSignalBar := na

    // --------------------------------------------------------
    // SHORT EXPIRATION
    // --------------------------------------------------------
    if pendingShort and not na(shortSignalBar)
        bool shortExpired = (shortSignalDay != dayKey or bar_index - shortSignalBar > confirmationWindow)
        bool shortInvalidNow = (cancelOnNewExtreme and not na(shortSignalHigh) and high > shortSignalHigh + invalidationBuffer)
        if shortExpired or shortInvalidNow or enterShort
            if shortExpired or shortInvalidNow
                expiredShortCount += 1
            pendingShort := false
            shortSignalBar := na

    // --------------------------------------------------------
    // REGISTER NEW SETUP
    // --------------------------------------------------------
    bool canRegister = (confirmationMode and intradayOK and flat and entrySessionOK and beforeForceClose and tradesToday < maximumTradesPerDay and not enterLong and not enterShort)
    if (canRegister and bullishSetup and not bearishSetup and not pendingLong and not pendingShort)
        pendingLong := true
        longSignalBar := bar_index
        longSignalDay := dayKey
        longSignalHigh := high
        longSignalLow := low
        longSignalClose := close
    if (canRegister and bearishSetup and not bullishSetup and not pendingShort and not pendingLong)
        pendingShort := true
        shortSignalBar := bar_index
        shortSignalDay := dayKey
        shortSignalHigh := high
        shortSignalLow := low
        shortSignalClose := close

// ============================================================================
// 35. 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 (CNPS88 - TP HIT)\n🎯 Giá chốt lời: " + str.tostring(strategy.position_avg_price + effectiveTP, format.mintick), alert_loss="🛑 CẮT LỖ LONG (CNPS88 - SL HIT)\n💥 Giá cắt lỗ: " + str.tostring(strategy.position_avg_price - effectiveSL, format.mintick), disable_alert=disableExitAlerts)

// ============================================================================
// 36. 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 (CNPS88 - TP HIT)\n🎯 Giá chốt lời: " + str.tostring(strategy.position_avg_price - effectiveTP, format.mintick), alert_loss="🛑 CẮT LỖ SHORT (CNPS88 - SL HIT)\n💥 Giá cắt lỗ: " + str.tostring(strategy.position_avg_price + effectiveSL, format.mintick), disable_alert=disableExitAlerts)

// ============================================================================
// 37. 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Ế HẾT THỜI GIAN (CNPS88 - Time Exit)\n📌 Giá đóng: " + str.tostring(close, format.mintick))

// ============================================================================
// 38. 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 (CNPS88 - Session End)\n📌 Giá đóng: " + str.tostring(close, format.mintick))

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

// ============================================================================
// 40. SWING LEVELS
// ============================================================================
plot(showSwingLevels ? previousSwingHigh : na, title="Previous Swing High", color=color.new(color.red, 40), linewidth=1, style=plot.style_stepline)
plot(showSwingLevels ? previousSwingLow : na, title="Previous Swing Low", color=color.new(color.green, 40), linewidth=1, style=plot.style_stepline)

// ============================================================================
// 41. EFFORT MARKERS
// ============================================================================
//
// Disabled by default.
//
// ============================================================================
plotshape(showEffortMarkers and highEffort, title="High Effort", style=shape.circle, location=location.bottom, color=color.gray, size=size.tiny, text="EV")

// ============================================================================
// 42. SETUP MARKERS
// ============================================================================
plotshape(showSetupMarkers and bullishSetup, title="Bullish Effort/Result", style=shape.circle, location=location.belowbar, color=color.aqua, size=size.tiny, text="ER")
plotshape(showSetupMarkers and bearishSetup, title="Bearish Effort/Result", style=shape.circle, location=location.abovebar, color=color.orange, size=size.tiny, text="ER")

// ============================================================================
// 43. PENDING CONFIRMATION LEVELS
// ============================================================================
plot(showPendingLevels and pendingLong ? longSignalHigh : na, title="Pending Long High", color=color.aqua, linewidth=2, style=plot.style_linebr)
plot(showPendingLevels and pendingLong ? longSignalLow : na, title="Pending Long Low", color=color.new(color.green, 20), linewidth=1, style=plot.style_linebr)
plot(showPendingLevels and pendingShort ? shortSignalHigh : na, title="Pending Short High", color=color.new(color.orange, 20), linewidth=1, style=plot.style_linebr)
plot(showPendingLevels and pendingShort ? shortSignalLow : na, title="Pending Short Low", color=color.fuchsia, linewidth=2, style=plot.style_linebr)

// ============================================================================
// 44. ENTRY MARKERS
// ============================================================================
plotshape(showEntryMarkers and enterLong, title="CNPS88 LONG", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, text="LONG", textcolor=color.white)
plotshape(showEntryMarkers and enterShort, title="CNPS88 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(volumeRatio, title="Effort Volume Ratio", color=color.blue, display=display.data_window)
plot(bodyRatio, title="Result Body Ratio", color=color.orange, display=display.data_window)
plot(candleRangeATR, title="Candle Range / ATR", color=color.gray, display=display.data_window)
plot(lowerWickRatio, title="Lower Wick Ratio", color=color.green, display=display.data_window)
plot(upperWickRatio, title="Upper Wick Ratio", color=color.red, display=display.data_window)
plot(atr, title="ATR", color=color.gray, display=display.data_window)
plot(adx, title="ADX", color=color.purple, display=display.data_window)

// ============================================================================
// 47. DIAGNOSTICS
// ============================================================================
var table diagnostics = table.new(position.top_right, 2, 20, border_width=1)
if showDiagnostics and barstate.islast
    table.cell(diagnostics, 0, 0, "CNPS88 V1")
    table.cell(diagnostics, 1, 0, timeframe.period)
    table.cell(diagnostics, 0, 1, "Volume Ratio")
    table.cell(diagnostics, 1, 1, str.tostring(volumeRatio, "#.##"))
    table.cell(diagnostics, 0, 2, "Body Ratio")
    table.cell(diagnostics, 1, 2, str.tostring(bodyRatio, "#.##"))
    table.cell(diagnostics, 0, 3, "High Effort")
    table.cell(diagnostics, 1, 3, str.tostring(effortCount))
    table.cell(diagnostics, 0, 4, "Low Result")
    table.cell(diagnostics, 1, 4, str.tostring(lowResultCount))
    table.cell(diagnostics, 0, 5, "Bull Setups")
    table.cell(diagnostics, 1, 5, str.tostring(bullSetupCount))
    table.cell(diagnostics, 0, 6, "Bear Setups")
    table.cell(diagnostics, 1, 6, str.tostring(bearSetupCount))
    table.cell(diagnostics, 0, 7, "Long Bases")
    table.cell(diagnostics, 1, 7, str.tostring(longBaseCount))
    table.cell(diagnostics, 0, 8, "Short Bases")
    table.cell(diagnostics, 1, 8, str.tostring(shortBaseCount))
    table.cell(diagnostics, 0, 9, "Filtered Long")
    table.cell(diagnostics, 1, 9, str.tostring(filteredLongCount))
    table.cell(diagnostics, 0, 10, "Filtered Short")
    table.cell(diagnostics, 1, 10, str.tostring(filteredShortCount))
    table.cell(diagnostics, 0, 11, "Long Entries")
    table.cell(diagnostics, 1, 11, str.tostring(longEntryCount))
    table.cell(diagnostics, 0, 12, "Short Entries")
    table.cell(diagnostics, 1, 12, str.tostring(shortEntryCount))
    table.cell(diagnostics, 0, 13, "Pending Long")
    table.cell(diagnostics, 1, 13, pendingLong ? "YES" : "NO")
    table.cell(diagnostics, 0, 14, "Pending Short")
    table.cell(diagnostics, 1, 14, pendingShort ? "YES" : "NO")
    table.cell(diagnostics, 0, 15, "Expired Long")
    table.cell(diagnostics, 1, 15, str.tostring(expiredLongCount))
    table.cell(diagnostics, 0, 16, "Expired Short")
    table.cell(diagnostics, 1, 16, str.tostring(expiredShortCount))
    table.cell(diagnostics, 0, 17, "EMA Up")
    table.cell(diagnostics, 1, 17, emaUp ? "YES" : "NO")
    table.cell(diagnostics, 0, 18, "Trades Today")
    table.cell(diagnostics, 1, 18, str.tostring(tradesToday) + "/" + str.tostring(maximumTradesPerDay))
    table.cell(diagnostics, 0, 19, "Position")
    table.cell(diagnostics, 1, 19, inLong ? "LONG" : inShort ? "SHORT" : "FLAT")

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

2.1. Đo lường Nỗ lực (Effort) bằng Volume tương đối không tự lạm phát

Bot tính mức khối lượng tham chiếu dựa trên trung bình SMA(volume[1], 20) — tức loại trừ hoàn toàn thanh nến hiện tại ra khỏi mẫu trung bình:

  • volumeRatio = volume / previousAverageVolume
  • Điều kiện highEffort thỏa mãn khi volumeRatio >= 1.80 (và <= 6.0 nếu bật useMaximumVolume). Cách tính này giúp một cây nến có khối lượng đột biến cực lớn không tự kéo đường trung bình lên cao, giữ nguyên độ nhạy của tín hiệu.

2.2. Đánh giá Kết quả (Result) và Râu từ chối giá

Để xác định sự hấp thụ (khối lượng lớn nhưng giá không đi xa được), CNPS88 đo cấu trúc hình học của nến:

  • Thân nến nhỏ (lowResult): bodyRatio = |close - open| / (high - low) <= 0.40.
  • Biên độ chuẩn hóa theo ATR (candleRangeOK): (high - low) / ATR(14) phải nằm trong khoảng [0.40, 2.50] khi useCandleRange = true, loại bỏ các nến quá bé (nhiễu) hoặc quá giãn (tin tức bất thường).
  • Râu nến và vị trí đóng cửa:
    • bullishRejection: Râu dưới chiếm tối thiểu 25% biên độ nến (lowerWickRatio >= 0.25) và vị trí đóng cửa (close - low) / candleRange >= 0.55.
    • bearishRejection: Râu trên chiếm tối thiểu 25% biên độ nến (upperWickRatio >= 0.25) và vị trí đóng cửa <= 0.45.

2.3. Vị trí Swing và Cửa sổ xác nhận nến sau

  • Swing Location: Bot lấy previousSwingHigh = ta.highest(high[1], 15) và previousSwingLow = ta.lowest(low[1], 15) (loại trừ nến hiện tại). Nến setup phải chạm hoặc nằm trong vùng dung sai 0.20 * ATR(14) quanh các mốc này. Nếu bật requireSwingSweep, giá phải thực sự quét qua đáy/đỉnh swing rồi đóng cửa rút lại vào trong.
  • Confirmation Window & Invalidation: Trong chế độ mặc định Next Candle Confirmation, setup không tự xác nhận trên chính nó mà mở cửa sổ chờ tối đa 5 nến cùng ngày (dayKey). Nếu giá phá ngược đầu còn lại quá 0.10 * ATR(14) (cancelOnNewExtreme = true), setup bị hủy ngay lập tức.
  • Bộ lọc tùy chọn (tắt mặc định): Hỗ trợ thêm bộ lọc xu hướng EMA(50) (emaSlopeBars = 3), ADX(14) <= 35.0, RSI(14) (<= 65 cho Long, >= 35 cho Short) và H1 EMA(50) thông qua request.security trên khung 60 phút.

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

Quy trình vận hành của Bot CNPS88 diễn ra tuần tự theo từng thanh nến đã đóng (barstate.isconfirmed) như sau:

  1. Khởi tạo phiên và bộ đếm ngày: Khi sang ngày mới (newDay), bot đặt lại tradesToday = 0 và xóa toàn bộ trạng thái pendingLong/pendingShort của ngày cũ.
  2. Đánh giá Effort vs Result & Swing: Trên mỗi nến đóng trong phiên, bot tính volumeRatio, bodyRatio, lowerWickRatio/upperWickRatio, candleRangeATR và kiểm tra khoảng cách tới previousSwingLow/previousSwingHigh để xác định bullishSetup hoặc bearishSetup.
  3. Kiểm tra xác nhận & Bộ lọc xu hướng:
    • Nếu đang ở chế độ Next Candle Confirmation, bot kiểm tra các nến tiếp theo trong cửa sổ 5 nến xem có vượt đỉnh/đáy của nến setup và đóng nến đúng hướng hay không (confirmedLong / confirmedShort), đồng thời không vi phạm điều kiện hủy (longInvalid / shortInvalid).
    • Sau đó áp dụng các bộ lọc tùy chọn (EMA, ADX, RSI, H1 Bias) để tạo ra rawLong / rawShort.
  4. Kiểm tra cổng vào lệnh (canTrade) & Gửi lệnh: Nếu thỏa mãn toàn bộ điều kiện phiên, trạng thái flat, giới hạn lệnh ngày và cooldown, bot gửi lệnh strategy.entry (lưu ý: strategy() khai báo default_qty_value=1 trong khi input contracts=3 chưa được truyền vào tham số qty của strategy.entry, do đó mặc định backtest chạy 1 hợp đồng trừ khi chỉnh lại default_qty_value hoặc thêm qty=contracts).
  5. Cập nhật trạng thái Setup & Quản trị thoát lệnh: Việc đăng ký pendingLong/pendingShort mới luôn diễn ra sau bước kiểm tra vào lệnh của nến hiện tại để đảm bảo một nến setup không tự xác nhận chính nó. Khi có vị thế mở, bot theo dõi SL/TP cố định, Time Exit (nếu bật) và đóng toàn bộ lúc 14:45.

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

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

Lệnh Long được kích hoạt (enterLong) khi canTrade = true, allowLong = true, not ambiguousSignal (không trùng tín hiệu Short) và thỏa mãn chuỗi điều kiện rawLong:

  • Setup Bullish (bullishSetup):
    • highEffort: volume / SMA(volume[1], 20) >= 1.80 (và <= 6.0 nếu bật useMaximumVolume).
    • lowResult: bodyRatio <= 0.40 và candleRange / ATR(14) nằm trong [0.40, 2.50] (nếu bật useCandleRange).
    • bullishRejection: lowerWickRatio >= 0.25 và (close - low) / candleRange >= 0.55.
    • longSwingOK: low <= previousSwingLow + 0.20 * ATR(14) (và low < previousSwingLow đồng thời close > previousSwingLow nếu bật requireSwingSweep).
  • Xác nhận (longBase):
    • Với chế độ mặc định Next Candle Confirmation: Trong vòng 1 đến 5 nến sau setup (cùng ngày), nến xác nhận phải có close > longSignalHigh (cộng 0.05 * ATR nếu bật useBreakoutBuffer), là nến tăng (close > open), và không vi phạm low < longSignalLow - 0.10 * ATR.
    • Với chế độ Signal Candle Close: Vào ngay khi bullishSetup hoàn thành.
  • Bộ lọc bổ sung (nếu bật): ema > ema[3] (và close > ema nếu bật requirePriceEMA), adx <= 35.0, rsi <= 65.0, và h1Close > h1EMA (trên khung nhỏ hơn H1).

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

Lệnh Short được kích hoạt (enterShort) khi canTrade = true, allowShort = true (lưu ý mặc định tradeDirection = "Long", cần đổi sang "Short" hoặc "Both" nếu muốn giao dịch chiều Short), not ambiguousSignal và thỏa mãn rawShort:

  • Setup Bearish (bearishSetup):
    • highEffort: volume / SMA(volume[1], 20) >= 1.80.
    • lowResult: bodyRatio <= 0.40 và candleRange / ATR(14) nằm trong [0.40, 2.50].
    • bearishRejection: upperWickRatio >= 0.25 và (close - low) / candleRange <= 0.45.
    • shortSwingOK: high >= previousSwingHigh - 0.20 * ATR(14) (và quét đỉnh rồi đóng dưới previousSwingHigh nếu bật requireSwingSweep).
  • Xác nhận (shortBase):
    • Với chế độ mặc định Next Candle Confirmation: Trong vòng 1 đến 5 nến sau setup (cùng ngày), nến xác nhận phải có close < shortSignalLow (trừ 0.05 * ATR nếu bật useBreakoutBuffer), là nến giảm (close < open), và không vi phạm high > shortSignalHigh + 0.10 * ATR.
  • Bộ lọc bổ sung (nếu bật): ema < ema[3] (và close < ema), adx <= 35.0, rsi >= 35.0, và h1Close < h1EMA.

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

Cổng canTrade yêu cầu đồng thời tất cả các điều kiện sau:

  • Nến đã đóng & Khung intraday: barstate.isconfirmed và timeframe.isintraday.
  • Trạng thái Flat: strategy.position_size == 0 và strategy.opentrades == 0 (pyramiding=0).
  • Khung giờ giao dịch (Asia/Ho_Chi_Minh): Khi useSessionFilter = true, thời gian mở nến >= 09:15, thời gian đóng nến <= 14:15, và trước giờ đóng bắt buộc (closeMinutes < 14:45).
  • Giới hạn tần suất: tradesToday < 2 (maximumTradesPerDay = 2).
  • Cooldown sau thoát lệnh: bar_index - lastExitBar > 3 (cooldownBars = 3) và lastEntryBar != bar_index.

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

5.1. Cơ chế Stop Loss

CNPS88 sử dụng Stop Loss cố định theo điểm, quy đổi ra số tick theo syminfo.mintick (với VN30F1M là 0.1 điểm/tick):

  • slTicks = math.max(1, int(math.round(stopLossPoints / syminfo.mintick))) (mặc định 5.0 điểm = 50 ticks).
  • Vị thế Long đặt SL tại strategy.position_avg_price - effectiveSL.
  • Vị thế Short đặt SL tại strategy.position_avg_price + effectiveSL.
  • Bot không áp dụng bộ lọc Min–Max Risk theo khoảng cách SL thực tế vì SL được cố định trực tiếp bằng tham số điểm.

5.2. Cơ chế Take Profit và Thoát lệnh theo thời gian

  • Take Profit cố định: tpTicks = math.max(1, int(math.round(takeProfitPoints / syminfo.mintick))) (mặc định 15.0 điểm = 150 ticks, tỷ lệ R:R 1:3).
  • Không sử dụng Break Even hoặc Trailing Stop: Mã nguồn CNPS88 không có cơ chế dời hòa vốn hay trailing stop; vị thế giữ nguyên mức SL/TP ban đầu cho đến khi chạm mục tiêu hoặc kích hoạt thoát lệnh theo thời gian.
  • Time Exit (tùy chọn, mặc định false): Nếu bật useTimeExit, khi số nến nắm giữ barsHeld >= 20 (maximumHoldingBars), bot đóng toàn bộ vị thế qua strategy.close_all.
  • Force Close cuối phiên: Vào cây nến có openMinutes < 14:45 và closeMinutes >= 14:45 (forceCloseBar), bot tự động gọi strategy.close_all(immediately=true, comment="Session End") để không giữ vị thế qua đêm.

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

Cơ chếTrạng thái mặc địnhThông số / Điều kiện kích hoạtHành động thực thi
Stop Loss cố địnhBậtstopLossPoints = 5.0 điểm (slTicks)Đóng vị thế khi giá chạm mức cắt lỗ
Take Profit cố địnhBậttakeProfitPoints = 15.0 điểm (tpTicks)Đóng vị thế chốt lời tại R:R 1:3
Break Even / TrailingKhông cóKhông lập trình trong codeGiữ nguyên SL/TP cố định
Time ExitTắt (false)barsHeld >= 20 nến (useTimeExit = true)Đóng toàn bộ vị thế (Time Exit)
Force Close cuối phiênBậtNến chạm mốc 14:45 (Asia/Ho_Chi_Minh)Đóng toàn bộ vị thế (Session End)

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

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

  1. Mở biểu đồ hợp đồng tương lai VN30F1M trên TradingView (khuyến nghị khung thời gian intraday như M5 hoặc M15).
  2. Mở tab Pine Editor ở thanh công cụ phía dưới.
  3. Xóa mã mặc định, sao chép toàn bộ mã nguồn Pine Script v6 từ Mục 1 và dán vào Pine Editor.
  4. Nhấn Save để lưu script, sau đó nhấn Add to chart để đưa chiến lược lên biểu đồ.
  5. Vào phần Settings (Cài đặt) của chiến lược: nếu muốn giao dịch cả 2 chiều Long & Short, hãy đổi Trade Direction từ Long sang Both, đồng thời bật Show Diagnostics nếu cần theo dõi bảng thống kê trực tiếp.

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

Khi bật showDiagnostics = true, bảng 20 dòng sẽ hiển thị ở góc trên bên phải (position.top_right) trên thanh nến cuối cùng (barstate.islast):

Dòng hiển thịÝ nghĩa thực tế trong code
CNPS88 V1Tên phiên bản và khung thời gian biểu đồ (timeframe.period)
Volume Ratio / Body RatioTỷ lệ khối lượng nến hiện tại và tỷ lệ thân nến trên biên độ
High Effort / Low ResultTổng số nến đạt ngưỡng khối lượng cao và tổng số nến vừa cao volume vừa hẹp thân
Bull Setups / Bear SetupsSố lượng setup Effort vs Result tăng/giảm hợp lệ đã xuất hiện
Long Bases / Short BasesSố lần thỏa điều kiện cơ sở (sau bước xác nhận nến sau hoặc nến tín hiệu)
Filtered Long / Filtered ShortSố tín hiệu vượt qua các bộ lọc EMA, ADX, RSI, H1 Bias
Long Entries / Short EntriesTổng số lệnh Long và Short thực tế đã vào
Pending Long / Pending ShortTrạng thái đang chờ xác nhận nến sau (YES / NO)
Expired Long / Expired ShortSố lượng setup bị hết hạn cửa sổ 5 nến hoặc bị hủy do phá ngược cực trị
EMA UpTrạng thái độ dốc đường EMA (YES nếu ema > ema[3], ngược lại NO)
Trades Today / PositionSố lệnh đã vào trong ngày (x/2) và trạng thái vị thế hiện tại (LONG / SHORT / FLAT)

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

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

  1. Nhấn biểu tượng Alert (Đồng hồ báo thức) trên thanh công cụ TradingView.
  2. Ở mục Condition, chọn chiến lược CNPS88 EFFORT VS RESULT REVERSAL V1.
  3. Ở mục Message, xóa nội dung mặc định và nhập chính xác cú pháp: {{strategy.order.alert_message}}.
  4. Nếu muốn ẩn các cảnh báo chạm SL/TP, bạn có thể tích chọn Disable SL/TP Alerts trong phần cài đặt của bot.

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

Loại sự kiệnTham số trong codeNội dung thông điệp Alert
Vào lệnh Longstrategy.entry("Long", ..., alert_message=...)🟢 VÀO VỊ THẾ LONG (CNPS88)\n🎯 Giá vào: <close>\n🛑 Cắt lỗ (SL): <close - effectiveSL>\n💰 Chốt lời (TP): <close + effectiveTP>
Vào lệnh Shortstrategy.entry("Short", ..., alert_message=...)🔴 VÀO VỊ THẾ SHORT (CNPS88)\n🎯 Giá vào: <close>\n🛑 Cắt lỗ (SL): <close + effectiveSL>\n💰 Chốt lời (TP): <close - effectiveTP>
Chốt lời Longstrategy.exit("Long Exit", ..., alert_profit=...)💰 CHỐT LỜI LONG (CNPS88 - TP HIT)\n🎯 Giá chốt lời: <avg_price + effectiveTP>
Cắt lỗ Longstrategy.exit("Long Exit", ..., alert_loss=...)🛑 CẮT LỖ LONG (CNPS88 - SL HIT)\n💥 Giá cắt lỗ: <avg_price - effectiveSL>
Chốt lời Shortstrategy.exit("Short Exit", ..., alert_profit=...)💰 CHỐT LỜI SHORT (CNPS88 - TP HIT)\n🎯 Giá chốt lời: <avg_price - effectiveTP>
Cắt lỗ Shortstrategy.exit("Short Exit", ..., alert_loss=...)🛑 CẮT LỖ SHORT (CNPS88 - SL HIT)\n💥 Giá cắt lỗ: <avg_price + effectiveSL>
Đóng hết thời gianstrategy.close_all(..., comment="Time Exit")⏱️ ĐÓNG VỊ THẾ HẾT THỜI GIAN (CNPS88 - Time Exit)\n📌 Giá đóng: <close>
Đóng hết phiênstrategy.close_all(..., comment="Session End")⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (CNPS88 - Session End)\n📌 Giá đóng: <close>

Kết luận

CNPS88 EFFORT VS RESULT REVERSAL V1 là một chiến lược bắt đảo chiều có kỷ luật cao nhờ kết hợp định lượng giữa khối lượng đột biến, cấu trúc nến từ chối giá tại vùng đỉnh/đáy swing và bước xác nhận động lượng ở nến kế tiếp. Hệ thống phát huy hiệu quả tốt nhất trong các nhịp thị trường có vùng biên độ rõ ràng hoặc các pha quét thanh khoản quá đà cuối sóng đẩy trên VN30F1M.

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

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