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

Hướng Dẫn Sử Dụng Bot CNPS85 - Volume Climax Reversal V1 cho VN30F1M

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

Trong giao dịch hợp đồng tương lai VN30F1M, những nhịp quét thanh khoản mạnh tại các vùng đỉnh/đáy ngắn hạn thường đi kèm sự bùng nổ đột biến về khối lượng (Volume Climax). Nếu vào lệnh bắt đáy/đỉnh quá sớm khi nến chưa đóng cửa hoặc chưa có dấu hiệu từ chối giá rõ ràng, trader rất dễ bị cuốn theo quán tính phá vỡ giả (false breakout) hoặc dính độ trễ do dữ liệu đa khung thời gian chưa xác nhận.

CNPS85 VOLUME CLIMAX REVERSAL V1 (tên hiển thị ngắn: CNPS85 VOL CLIMAX) là chiến lược giao dịch định lượng viết bằng Pine Script v6 trên TradingView, được thiết kế chuyên biệt để nhận diện các nến bùng nổ khối lượng kết hợp từ chối giá tại vùng cực trị Swing, sau đó chờ xác nhận theo máy trạng thái (State Machine) trước khi kích hoạt vị thế.

  • Tham chiếu không tự làm nhiễu (Non-Repainting Reference): Trung bình khối lượng (volume[1]) và đỉnh/đáy Swing (high[1] / low[1]) đều loại trừ hoàn toàn nến hiện tại; toàn bộ tín hiệu và dữ liệu H1 đều chỉ dùng nến đã đóng cửa (barstate.isconfirmed, [1]).
  • Máy trạng thái xác nhận nến sau (Next Candle Confirmation): Mặc định lưu nến Climax thành thiết lập chờ (pendingLong / pendingShort) trong tối đa 3 nến cùng ngày và tự động hủy nếu giá phá ngược cực trị nến Climax.
  • Bộ lọc đa tầng linh hoạt: Tích hợp lọc biên độ nến theo ATR, bộ lọc xu hướng EMA, ADX tối đa, RSI và thiên hướng khung H1 (useH1Bias).
  • Quản trị rủi ro chuẩn xác theo Tick: Tính toán Stop Loss (5.0 điểm) và Take Profit (15.0 điểm) từ giá khớp lệnh thực tế, hỗ trợ đóng lệnh theo thời gian nắm giữ và tự động tất toán cuối phiên lúc 14:45.

1. CNPS85 Volume Climax Reversal V1 là gì?

CNPS85 Volume Climax Reversal V1 là hệ thống giao dịch đảo chiều ngắn hạn (Reversal) trong phiên (Intraday), kết hợp 4 trụ cột kỹ thuật cốt lõi:

  1. Bùng nổ khối lượng (Volume Climax): Phát hiện thời điểm dòng tiền đột biến gấp nhiều lần mức trung bình lịch sử (climaxFactor = 2.0) và có tùy chọn loại bỏ các nhịp nhiễu thanh khoản quá cực đoan (maximumVolumeFactor = 8.0).
  2. Vùng cực trị Swing (Price Extreme): Xác định giá đang tiếp cận hoặc rút chân quét qua vùng đỉnh/đáy swingLookback (15 nến trước) trong phạm vi dung sai 0.10 * ATR(14).
  3. Nến từ chối giá (Rejection Candle): Đánh giá cấu trúc nến qua vị trí đóng cửa (closePosition), chiều nến, tỷ lệ râu nến từ chối và giới hạn biên độ nến hợp lý so với ATR (0.80 * ATR đến 4.0 * ATR).
  4. Xác nhận & Quản trị vị thế (Confirmation & Risk Engine): Điều phối thiết lập chờ qua State Machine, áp dụng các bộ lọc xu hướng/động lượng tùy chọn, kiểm soát giới hạn lệnh/ngày, thời gian nghỉ (cooldown) và thoát lệnh tự động.

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

Nhóm thông sốTên biến / Tham sốGiá trị mặc địnhÝ nghĩa trong code
01. Volume ClimaxvolumeLength20Số nến trước đó tính SMA khối lượng
01. Volume ClimaxclimaxFactor2.0Hệ số khối lượng tối thiểu so với trung bình
01. Volume ClimaxuseMaximumVolume / maximumVolumeFactorfalse / 8.0Tùy chọn loại bỏ nến có khối lượng vượt ngưỡng tối đa
02. Price ExtremeswingLookback / atrLength15 / 14Chu kỳ tìm đỉnh/đáy Swing và chu kỳ tính ATR
02. Price ExtremeuseSwingFilter / swingToleranceATRtrue / 0.10Bật lọc Swing với biên độ dung sai theo ATR
02. Price ExtremerequireSwingSweepfalseYêu cầu nến quét qua mức Swing rồi đóng cửa ngược lại
03. Rejection CandlelongClosePosition / shortClosePosition0.65 / 0.35Vị trí giá đóng cửa tối thiểu (Long) / tối đa (Short)
03. Rejection CandlerequireCandleDirectiontrueYêu cầu nến xanh cho Long và nến đỏ cho Short
03. Rejection CandleuseWickFilter / minimumWickRatiofalse / 0.25Tùy chọn lọc tỷ lệ râu nến từ chối trên biên độ nến
03. Rejection CandleuseRangeFilter / minimumRangeATRtrue / 0.80Biên độ nến tối thiểu theo ATR
03. Rejection CandleuseMaximumRange / maximumRangeATRtrue / 4.0Loại bỏ nến quá lớn vượt quá 4.0 lần ATR
04. Entry ConfirmationentryMode"Next Candle Confirmation"Chế độ vào lệnh: xác nhận nến sau hoặc đóng nến Climax
04. Entry ConfirmationconfirmationWindow3Số nến tối đa chờ xác nhận sau nến Climax
04. Entry ConfirmationrequireConfirmationCandle / requireCloseProgresstrue / trueNến xác nhận đúng chiều và đóng cửa vượt giá đóng Climax
04. Entry ConfirmationrequireBreakClimaxExtreme / cancelOnNewExtremefalse / truePhá cực trị thuận chiều / Hủy setup nếu phá cực trị ngược
05. EMA TrenduseEMAFilter / emaLength / emaSlopeBarsfalse / 50 / 3Lọc độ dốc EMA50 (tùy chọn requirePriceEMA = false)
06. Optional FiltersuseADXFilter / maximumADXfalse / 35.0Lọc ADX(14,14) không vượt quá ngưỡng cho phép
06. Optional FiltersuseRSIFilter / longRSIMax / shortRSIMinfalse / 60.0 / 40.0Lọc RSI(14) tránh mua quá cao hoặc bán quá thấp
07. H1 BiasuseH1Bias / h1EMALengthfalse / 50Lọc xu hướng theo nến H1 đã đóng và EMA50 khung H1
08. Risk ManagementstopLossPoints / takeProfitPoints5.0 / 15.0Cắt lỗ và chốt lời cố định theo điểm
08. Risk ManagementuseTimeExit / maximumHoldingBarsfalse / 20Tùy chọn đóng lệnh sau số nến nắm giữ tối đa
09. Trade ControltradeDirection / contracts"Long" / 3Hướng giao dịch (Long/Short/Both); lưu ý strategy() đặt default_qty_value=1
09. Trade ControlmaximumTradesPerDay / cooldownBars2 / 3Giới hạn số lệnh/ngày và số nến nghỉ sau khi đóng lệnh
10. SessionuseSessionFilter / tztrue / "Asia/Ho_Chi_Minh"Lọc khung giờ giao dịch theo múi giờ Việt Nam
10. SessionGiờ vào lệnh & Tất toán09:15 – 14:15 / 14:45Nhận lệnh từ 09:15 đến 14:15; đóng toàn bộ ở 14:45
11. Alerts & DisplaydisableExitAlerts / showDiagnosticsfalse / falseTắt cảnh báo SL/TP; bật bảng chẩn đoán trên biểu đồ

Source Code CNPS85 Volume Climax 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="CNPS85 VOLUME CLIMAX REVERSAL V1", shorttitle="CNPS85 VOL CLIMAX", 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)

// ============================================================================
// CNPS85 - VOLUME CLIMAX REVERSAL
//
// LONG:
// 1. Volume surges above its historical average.
// 2. Price tests or sweeps a recent swing low.
// 3. Candle rejects lower prices.
// 4. Optional confirmation on later candles.
// 5. LONG.
//
// SHORT:
// 1. Volume surges.
// 2. Price tests or sweeps a recent swing high.
// 3. Candle rejects higher prices.
// 4. Optional confirmation.
// 5. SHORT.
//
// Notes:
// - Volume reference excludes the current candle.
// - Swing reference excludes the current candle.
// - Only confirmed candles generate entries.
// - No unconfirmed HTF data.
// - SL / TP are measured from actual entry fill.
// ============================================================================
// ============================================================================
// 01. VOLUME CLIMAX
// ============================================================================
gVolume = "01. Volume Climax"
volumeLength = input.int(20, "Volume Average Length", minval=2, maxval=300, group=gVolume)
climaxFactor = input.float(2.0, "Minimum Volume / Average", minval=0.1, step=0.1, group=gVolume)
useMaximumVolume = input.bool(false, "Reject Excessive Volume Spikes", group=gVolume)
maximumVolumeFactor = input.float(8.0, "Maximum Volume / Average", minval=1.0, step=0.5, group=gVolume)

// ============================================================================
// 02. PRICE EXTREME
// ============================================================================
gExtreme = "02. Price Extreme"
swingLookback = input.int(15, "Swing Extreme Lookback", minval=3, maxval=200, group=gExtreme)
atrLength = input.int(14, "ATR Length", minval=1, group=gExtreme)
useSwingFilter = input.bool(true, "Require Recent Swing Extreme", group=gExtreme)
swingToleranceATR = input.float(0.10, "Swing Proximity / ATR", minval=0.0, step=0.05, group=gExtreme)
requireSwingSweep = input.bool(false, "Require Swing Level Sweep", group=gExtreme)

// ============================================================================
// 03. REJECTION CANDLE
// ============================================================================
gRejection = "03. Rejection Candle"
longClosePosition = input.float(0.65, "Minimum Long Close Position", minval=0.50, maxval=1.0, step=0.05, group=gRejection)
shortClosePosition = input.float(0.35, "Maximum Short Close Position", minval=0.0, maxval=0.50, step=0.05, group=gRejection)
requireCandleDirection = input.bool(true, "Require Bullish / Bearish Candle", group=gRejection)
useWickFilter = input.bool(false, "Require Rejection Wick", group=gRejection)
minimumWickRatio = input.float(0.25, "Minimum Wick / Candle Range", minval=0.0, maxval=1.0, step=0.05, group=gRejection)
useRangeFilter = input.bool(true, "Require Minimum Candle Range", group=gRejection)
minimumRangeATR = input.float(0.80, "Minimum Candle Range / ATR", minval=0.0, step=0.1, group=gRejection)
useMaximumRange = input.bool(true, "Reject Excessively Large Candle", group=gRejection)
maximumRangeATR = input.float(4.0, "Maximum Candle Range / ATR", minval=0.1, step=0.1, group=gRejection)

// ============================================================================
// 04. ENTRY CONFIRMATION
// ============================================================================
gConfirm = "04. Entry Confirmation"
entryMode = input.string("Next Candle Confirmation", "Entry Mode", options=["Climax Candle Close", "Next Candle Confirmation"], group=gConfirm)
confirmationWindow = input.int(3, "Maximum Confirmation Bars", minval=1, maxval=20, group=gConfirm)
requireConfirmationCandle = input.bool(true, "Require Confirmation Candle Direction", group=gConfirm)
requireCloseProgress = input.bool(true, "Require Close Beyond Climax Close", group=gConfirm)
requireBreakClimaxExtreme = input.bool(false, "Require Break Climax High / Low", group=gConfirm)
cancelOnNewExtreme = input.bool(true, "Cancel If Climax Extreme Is Broken", 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(60.0, "Maximum RSI For Long", minval=1.0, maxval=100.0, group=gFilters)
shortRSIMin = input.float(40.0, "Minimum RSI For Short", minval=0.0, maxval=99.0, 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=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("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. SESSION
// ============================================================================
gSession = "10. 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)
showClimaxMarkers = input.bool(false, "Show Volume Climax Dots", group=gDisplay)
showSignalMarkers = input.bool(false, "Show Rejection Setup Dots", group=gDisplay)
showPendingLevels = input.bool(false, "Show Pending Confirmation Levels", group=gDisplay)
showEntryMarkers = input.bool(true, "Show Entry Markers", group=gDisplay)
showSwingLevels = input.bool(false, "Show Swing Levels", group=gDisplay)
showSLTP = input.bool(true, "Show 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. TRADING DAY
// ============================================================================
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 / EMA / VOLUME
// ============================================================================
float atr = ta.atr(atrLength)
float ema = ta.ema(close, emaLength)

// Previous bars only.
// The climax candle is NOT included
// in its own average-volume reference.
float previousAverageVolume = ta.sma(volume[1], volumeLength)
float volumeRatio = (not na(volume) and not na(previousAverageVolume) and previousAverageVolume > 0 ? volume / previousAverageVolume : na)
bool volumeClimax = (not na(volumeRatio) and volumeRatio >= climaxFactor and (not useMaximumVolume or volumeRatio <= maximumVolumeFactor))

// ============================================================================
// 16. SWING EXTREME LEVELS
// ============================================================================
float previousSwingHigh = ta.highest(high[1], swingLookback)
float previousSwingLow = ta.lowest(low[1], swingLookback)
bool swingReady = (not na(previousSwingHigh) and not na(previousSwingLow) and not na(atr) and atr > 0)
float swingTolerance = (not na(atr) ? atr * swingToleranceATR : 0.0)
bool nearSwingLow = (swingReady and low <= previousSwingLow + swingTolerance)
bool nearSwingHigh = (swingReady and high >= previousSwingHigh - swingTolerance)
bool longSwingOK = (not useSwingFilter or nearSwingLow)
bool shortSwingOK = (not useSwingFilter or nearSwingHigh)
bool longSweepOK = (not requireSwingSweep or (swingReady and low < previousSwingLow and close > previousSwingLow))
bool shortSweepOK = (not requireSwingSweep or (swingReady and high > previousSwingHigh and close < previousSwingHigh))

// ============================================================================
// 17. CANDLE ANATOMY
// ============================================================================
float candleRange = (high - low)
float candleBody = math.abs(close - open)
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)
bool bullishCandle = (close > open)
bool bearishCandle = (close < open)

// ============================================================================
// 18. CLIMAX PRICE REJECTION
// ============================================================================
bool longCloseOK = (closePosition >= longClosePosition)
bool shortCloseOK = (closePosition <= shortClosePosition)
bool longDirectionOK = (not requireCandleDirection or bullishCandle)
bool shortDirectionOK = (not requireCandleDirection or bearishCandle)
bool longWickOK = (not useWickFilter or lowerWickRatio >= minimumWickRatio)
bool shortWickOK = (not useWickFilter or upperWickRatio >= minimumWickRatio)
bool minimumRangeOK = (not useRangeFilter or (not na(atr) and atr > 0 and candleRange >= atr * minimumRangeATR))
bool maximumRangeOK = (not useMaximumRange or (not na(atr) and atr > 0 and candleRange <= atr * maximumRangeATR))

// ============================================================================
// 19. BULLISH / BEARISH CLIMAX
// ============================================================================
bool bullishClimax = (barstate.isconfirmed and volumeClimax and longSwingOK and longSweepOK and longCloseOK and longDirectionOK and longWickOK and minimumRangeOK and maximumRangeOK)
bool bearishClimax = (barstate.isconfirmed and volumeClimax and shortSwingOK and shortSweepOK and shortCloseOK and shortDirectionOK and shortWickOK and minimumRangeOK and maximumRangeOK)

// ============================================================================
// 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 AND RSI
// ============================================================================
[diPlus, diMinus, adx] = ta.dmi(diLength, adxSmoothing)
float rsi = ta.rsi(close, rsiLength)
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 AND 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. CLIMAX STATE MACHINE
// ============================================================================
//
// A climax candle is saved as a pending
// reversal setup.
//
// In confirmation mode:
// A later candle must confirm direction.
//
// A setup is invalidated if price breaks
// the opposite extreme of the climax bar.
//
// We do not overwrite an active same-side
// setup on every subsequent climax.
//
// ============================================================================
var bool pendingLong = false
var bool pendingShort = false
var int longClimaxBar = na
var int shortClimaxBar = na
var int longClimaxDay = na
var int shortClimaxDay = na
var float longClimaxHigh = na
var float longClimaxLow = na
var float longClimaxClose = na
var float shortClimaxHigh = na
var float shortClimaxLow = na
var float shortClimaxClose = na
var int rawClimaxCount = 0
var int bullClimaxCount = 0
var int bearClimaxCount = 0
var int expiredLongCount = 0
var int expiredShortCount = 0
var int longBaseCount = 0
var int shortBaseCount = 0
var int filteredLongCount = 0
var int filteredShortCount = 0
var int longEntryCount = 0
var int shortEntryCount = 0
bool confirmationMode = (entryMode == "Next Candle Confirmation")

// ============================================================================
// 25. CONFIRMATION WINDOW
// ============================================================================
bool validLongWindow = (pendingLong and not na(longClimaxBar) and longClimaxDay == dayKey and bar_index > longClimaxBar and bar_index - longClimaxBar <= confirmationWindow)
bool validShortWindow = (pendingShort and not na(shortClimaxBar) and shortClimaxDay == dayKey and bar_index > shortClimaxBar and bar_index - shortClimaxBar <= confirmationWindow)

// ============================================================================
// 26. PRICE CONFIRMATION
// ============================================================================
bool longConfirmationCandleOK = (not requireConfirmationCandle or bullishCandle)
bool shortConfirmationCandleOK = (not requireConfirmationCandle or bearishCandle)
bool longProgressOK = (not requireCloseProgress or (not na(longClimaxClose) and close > longClimaxClose))
bool shortProgressOK = (not requireCloseProgress or (not na(shortClimaxClose) and close < shortClimaxClose))
bool longExtremeBreakOK = (not requireBreakClimaxExtreme or (not na(longClimaxHigh) and close > longClimaxHigh))
bool shortExtremeBreakOK = (not requireBreakClimaxExtreme or (not na(shortClimaxLow) and close < shortClimaxLow))
bool longNotInvalid = (not cancelOnNewExtreme or (not na(longClimaxLow) and low >= longClimaxLow))
bool shortNotInvalid = (not cancelOnNewExtreme or (not na(shortClimaxHigh) and high <= shortClimaxHigh))
bool confirmedLong = (barstate.isconfirmed and validLongWindow and longConfirmationCandleOK and longProgressOK and longExtremeBreakOK and longNotInvalid)
bool confirmedShort = (barstate.isconfirmed and validShortWindow and shortConfirmationCandleOK and shortProgressOK and shortExtremeBreakOK and shortNotInvalid)

// ============================================================================
// 27. ENTRY BASES
// ============================================================================
bool longBase = (confirmationMode ? confirmedLong : bullishClimax)
bool shortBase = (confirmationMode ? confirmedShort : bearishClimax)

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

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

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

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

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

// ============================================================================
// 33. UPDATE CLIMAX STATE
// ============================================================================
//
// Signals are evaluated before this update.
//
// A new climax candle cannot confirm itself
// in Next Candle Confirmation mode.
//
// ============================================================================
if barstate.isconfirmed
    if volumeClimax
        rawClimaxCount += 1
    if bullishClimax
        bullClimaxCount += 1
    if bearishClimax
        bearClimaxCount += 1
    if longBase
        longBaseCount += 1
    if shortBase
        shortBaseCount += 1
    if rawLong
        filteredLongCount += 1
    if rawShort
        filteredShortCount += 1

    // --------------------------------------------------------
    // RESET ON NEW DAY
    // --------------------------------------------------------
    if newDay
        pendingLong := false
        pendingShort := false
        longClimaxBar := na
        shortClimaxBar := na
        longClimaxDay := na
        shortClimaxDay := na
        longClimaxHigh := na
        longClimaxLow := na
        longClimaxClose := na
        shortClimaxHigh := na
        shortClimaxLow := na
        shortClimaxClose := na

    // --------------------------------------------------------
    // LONG SETUP EXPIRATION / INVALIDATION
    // --------------------------------------------------------
    if pendingLong and not na(longClimaxBar)
        bool longExpired = (bar_index - longClimaxBar > confirmationWindow)
        bool longInvalid = (cancelOnNewExtreme and not na(longClimaxLow) and low < longClimaxLow)
        if longExpired or longInvalid
            pendingLong := false
            longClimaxBar := na
            expiredLongCount += 1

    // --------------------------------------------------------
    // SHORT SETUP EXPIRATION / INVALIDATION
    // --------------------------------------------------------
    if pendingShort and not na(shortClimaxBar)
        bool shortExpired = (bar_index - shortClimaxBar > confirmationWindow)
        bool shortInvalid = (cancelOnNewExtreme and not na(shortClimaxHigh) and high > shortClimaxHigh)
        if shortExpired or shortInvalid
            pendingShort := false
            shortClimaxBar := na
            expiredShortCount += 1

    // --------------------------------------------------------
    // CONSUME CONFIRMED ENTRY
    // --------------------------------------------------------
    if enterLong
        pendingLong := false
        longClimaxBar := na
    if enterShort
        pendingShort := false
        shortClimaxBar := na

    // --------------------------------------------------------
    // REGISTER NEW CLIMAX SETUP
    // --------------------------------------------------------
    bool canRegister = (confirmationMode and intradayOK and flat and entrySessionOK and beforeForceClose and not enterLong and not enterShort)
    if (canRegister and bullishClimax and not pendingLong)
        pendingLong := true
        longClimaxBar := bar_index
        longClimaxDay := dayKey
        longClimaxHigh := high
        longClimaxLow := low
        longClimaxClose := close
        pendingShort := false
        shortClimaxBar := na
    if (canRegister and bearishClimax and not pendingShort)
        pendingShort := true
        shortClimaxBar := bar_index
        shortClimaxDay := dayKey
        shortClimaxHigh := high
        shortClimaxLow := low
        shortClimaxClose := close
        pendingLong := false
        longClimaxBar := na

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

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

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

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

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

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

// ============================================================================
// 40. VOLUME CLIMAX MARKERS
// ============================================================================
//
// OFF by default to keep chart clean.
//
// ============================================================================
plotshape(showClimaxMarkers and volumeClimax, title="Volume Climax", style=shape.circle, location=location.bottom, color=color.gray, size=size.tiny, text="VC")

// ============================================================================
// 41. REVERSAL SETUP MARKERS
// ============================================================================
plotshape(showSignalMarkers and bullishClimax, title="Bullish Climax Setup", style=shape.circle, location=location.belowbar, color=color.aqua, size=size.tiny, text="VC")
plotshape(showSignalMarkers and bearishClimax, title="Bearish Climax Setup", style=shape.circle, location=location.abovebar, color=color.orange, size=size.tiny, text="VC")

// ============================================================================
// 42. PENDING CONFIRMATION LEVELS
// ============================================================================
plot(showPendingLevels and pendingLong ? longClimaxHigh : na, title="Pending Long High", color=color.aqua, linewidth=2, style=plot.style_linebr)
plot(showPendingLevels and pendingLong ? longClimaxLow : na, title="Pending Long Low", color=color.green, linewidth=1, style=plot.style_linebr)
plot(showPendingLevels and pendingShort ? shortClimaxHigh : na, title="Pending Short High", color=color.orange, linewidth=1, style=plot.style_linebr)
plot(showPendingLevels and pendingShort ? shortClimaxLow : na, title="Pending Short Low", color=color.red, linewidth=2, style=plot.style_linebr)

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

// ============================================================================
// 44. ACTIVE SL / TP
// ============================================================================
float longSL = (inLong ? strategy.position_avg_price - effectiveSL : na)
float longTP = (inLong ? strategy.position_avg_price + effectiveTP : na)
float shortSL = (inShort ? strategy.position_avg_price + effectiveSL : na)
float shortTP = (inShort ? strategy.position_avg_price - effectiveTP : na)
plot(showSLTP ? longSL : na, title="Long SL", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showSLTP ? longTP : na, title="Long TP", color=color.green, linewidth=2, style=plot.style_linebr)
plot(showSLTP ? shortSL : na, title="Short SL", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showSLTP ? shortTP : na, title="Short TP", color=color.green, linewidth=2, style=plot.style_linebr)

// ============================================================================
// 45. DATA WINDOW
// ============================================================================
plot(volumeRatio, title="Climax Volume Ratio", color=color.blue, display=display.data_window)
plot(previousAverageVolume, title="Previous Average Volume", color=color.gray, display=display.data_window)
plot(closePosition, title="Candle Close Position", color=color.orange, 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)
plot(rsi, title="RSI", color=color.blue, display=display.data_window)

// ============================================================================
// 46. DIAGNOSTICS
// ============================================================================
var table diagnostics = table.new(position.top_right, 2, 19, border_width=1)
if showDiagnostics and barstate.islast
    table.cell(diagnostics, 0, 0, "CNPS85 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, "Raw Climax Bars")
    table.cell(diagnostics, 1, 2, str.tostring(rawClimaxCount))
    table.cell(diagnostics, 0, 3, "Bullish Climax")
    table.cell(diagnostics, 1, 3, str.tostring(bullClimaxCount))
    table.cell(diagnostics, 0, 4, "Bearish Climax")
    table.cell(diagnostics, 1, 4, str.tostring(bearClimaxCount))
    table.cell(diagnostics, 0, 5, "Long Bases")
    table.cell(diagnostics, 1, 5, str.tostring(longBaseCount))
    table.cell(diagnostics, 0, 6, "Short Bases")
    table.cell(diagnostics, 1, 6, str.tostring(shortBaseCount))
    table.cell(diagnostics, 0, 7, "Filtered Long")
    table.cell(diagnostics, 1, 7, str.tostring(filteredLongCount))
    table.cell(diagnostics, 0, 8, "Filtered Short")
    table.cell(diagnostics, 1, 8, str.tostring(filteredShortCount))
    table.cell(diagnostics, 0, 9, "Long Entries")
    table.cell(diagnostics, 1, 9, str.tostring(longEntryCount))
    table.cell(diagnostics, 0, 10, "Short Entries")
    table.cell(diagnostics, 1, 10, str.tostring(shortEntryCount))
    table.cell(diagnostics, 0, 11, "Pending Long")
    table.cell(diagnostics, 1, 11, pendingLong ? "YES" : "NO")
    table.cell(diagnostics, 0, 12, "Pending Short")
    table.cell(diagnostics, 1, 12, pendingShort ? "YES" : "NO")
    table.cell(diagnostics, 0, 13, "Expired Long")
    table.cell(diagnostics, 1, 13, str.tostring(expiredLongCount))
    table.cell(diagnostics, 0, 14, "Expired Short")
    table.cell(diagnostics, 1, 14, str.tostring(expiredShortCount))
    table.cell(diagnostics, 0, 15, "EMA Up")
    table.cell(diagnostics, 1, 15, emaUp ? "YES" : "NO")
    table.cell(diagnostics, 0, 16, "EMA Down")
    table.cell(diagnostics, 1, 16, emaDown ? "YES" : "NO")
    table.cell(diagnostics, 0, 17, "Trades Today")
    table.cell(diagnostics, 1, 17, str.tostring(tradesToday) + "/" + str.tostring(maximumTradesPerDay))
    table.cell(diagnostics, 0, 18, "Position")
    table.cell(diagnostics, 1, 18, inLong ? "LONG" : inShort ? "SHORT" : "FLAT")

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

2.1. Volume Climax loại trừ nến hiện tại

Để tránh hiện tượng nến bùng nổ tự làm tăng mẫu số trung bình khối lượng, CNPS85 tính trung bình khối lượng trên volume[1] thay vì volume:

  • previousAverageVolume = ta.sma(volume[1], volumeLength) (mặc định 20 nến trước).
  • volumeRatio = volume / previousAverageVolume.
  • Nến đạt chuẩn Volume Climax khi volumeRatio >= climaxFactor (2.0). Nếu bật useMaximumVolume, hệ thống yêu cầu thêm volumeRatio <= maximumVolumeFactor (8.0) để tránh giao dịch tại các nến tin tức bất thường.

2.2. Cấu trúc nến từ chối giá (Candle Anatomy & Rejection) và Swing Extreme

Hệ thống đo lường đồng thời vị trí giá tiếp xúc vùng cực trị và cấu trúc giải phẫu của cây nến:

  • Swing Extreme: previousSwingHigh = ta.highest(high[1], swingLookback) và previousSwingLow = ta.lowest(low[1], swingLookback) (mặc định 15 nến trước, không tính nến hiện tại). Khoảng dung sai swingTolerance = atr * swingToleranceATR (0.10 * ATR(14)).
  • Vị trí đóng cửa (closePosition): Tính bằng (close - low) / (high - low). Nến từ chối giảm (Long) phải đóng cửa ở vùng 35% trên cùng (closePosition >= 0.65); nến từ chối tăng (Short) phải đóng cửa ở vùng 35% dưới cùng (closePosition <= 0.35).
  • Bộ lọc biên độ ATR: Mặc định bắt buộc biên độ nến (high - low) phải đạt tối thiểu 0.80 * ATR và không vượt quá 4.0 * ATR để loại bỏ các nến Doji quá nhỏ hoặc nến biến động dị thường.

2.3. Bộ lọc xu hướng, động lượng và H1 Bias (Tùy chọn)

Ngoài tín hiệu cốt lõi, bot cung cấp 3 lớp lọc bổ trợ (mặc định tắt, có thể bật tùy chế độ thị trường):

  • EMA Trend Filter (useEMAFilter): Kiểm tra độ dốc EMA50 qua emaSlopeBars (3 nến) và tùy chọn giá nằm trên/dưới EMA (requirePriceEMA).
  • ADX & RSI (useADXFilter, useRSIFilter): Giới hạn ADX(14, 14) <= 35.0 để tránh đảo chiều ngược xu hướng quá mạnh; lọc RSI(14) <= 60.0 cho Long và >= 40.0 cho Short.
  • Confirmed H1 Bias (useH1Bias): Sử dụng request.security(..., "60", ...[1], lookahead=barmerge.lookahead_on) để chỉ lấy giá đóng cửa và EMA50 của cây nến H1 đã đóng hoàn toàn, đồng thời chỉ kích hoạt trên các khung thời gian nhỏ hơn 1 giờ (timeframe.in_seconds() < 3600).

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

Mỗi cây nến đóng cửa (barstate.isconfirmed) được xử lý theo quy trình tuần tự 5 bước trong CNPS85:

  1. Khởi tạo phiên và đếm ngày mới: Khi dayKey thay đổi, bot đặt lại bộ đếm tradesToday := 0 và xóa toàn bộ trạng thái chờ pendingLong / pendingShort của ngày cũ.
  2. Đánh giá nến Volume Climax (bullishClimax / bearishClimax): Kiểm tra đồng thời điều kiện khối lượng đột biến, vùng Swing, vị trí đóng cửa, chiều nến, tỷ lệ râu nến (nếu bật) và biên độ ATR.
  3. Kiểm tra xác nhận theo State Machine:
    • Ở chế độ mặc định Next Candle Confirmation, bot kiểm tra xem có thiết lập chờ hợp lệ từ nến trước trong phạm vi confirmationWindow (3 nến cùng ngày) hay không.
    • Ở chế độ Climax Candle Close, nến Climax đóng cửa sẽ tạo ngay tín hiệu cơ sở longBase / shortBase.
  4. Lọc rủi ro & gửi lệnh: Kiểm tra các bộ lọc bổ sung (EMA, ADX, RSI, H1 Bias), kiểm tra điều kiện cổng giao dịch (canTrade), tránh tín hiệu mâu thuẫn hai chiều (not ambiguousSignal) rồi gọi strategy.entry().
  5. Cập nhật trạng thái chờ cuối nến: Sau khi đánh giá tín hiệu xong, bot mới hủy các setup hết hạn/bị phá cực trị hoặc đăng ký nến Climax mới thành pendingLong / pendingShort (lưu ý một nến Climax mới không thể tự xác nhận chính nó trong cùng một nến).

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

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

Lệnh Long được kích hoạt khi allowLong bật (tradeDirection là "Long" hoặc "Both"), thỏa canTrade, not ambiguousSignal và thỏa mãn chuỗi điều kiện sau:

  1. Thiết lập bullishClimax (Nến Climax tăng):
    • volumeClimax đúng (volumeRatio >= 2.0, và <= 8.0 nếu bật useMaximumVolume).
    • Vùng đáy Swing: low <= previousSwingLow + 0.10 * ATR (khi bật useSwingFilter); nếu bật requireSwingSweep, phải có low < previousSwingLow và close > previousSwingLow.
    • Cấu trúc nến: closePosition >= 0.65, nến tăng close > open (khi requireCandleDirection = true), tỷ lệ râu dưới lowerWickRatio >= 0.25 (nếu bật useWickFilter), và biên độ nến nằm trong [0.80 * ATR, 4.0 * ATR].
  2. Xác nhận vào lệnh (longBase):
    • Nếu chọn Next Candle Confirmation: Đang có pendingLong cùng ngày trong vòng 1–3 nến sau nến Climax (validLongWindow), nến xác nhận là nến tăng (close > open), đóng cửa cao hơn giá đóng nến Climax (close > longClimaxClose), chưa phá đáy nến Climax (low >= longClimaxLow), và vượt đỉnh nến Climax nếu bật requireBreakClimaxExtreme.
    • Nếu chọn Climax Candle Close: Sử dụng trực tiếp bullishClimax.
  3. Các bộ lọc tùy chọn (nếu bật): ema > ema[3] (và close > ema nếu bật requirePriceEMA), adx <= 35.0, rsi <= 60.0, và trên khung H1 đã đóng h1Close > h1EMA.

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

Lệnh Short được kích hoạt khi allowShort bật (tradeDirection là "Short" hoặc "Both"), thỏa canTrade, not ambiguousSignal và thỏa mãn chuỗi điều kiện sau:

  1. Thiết lập bearishClimax (Nến Climax giảm):
    • volumeClimax đúng (volumeRatio >= 2.0, và <= 8.0 nếu bật useMaximumVolume).
    • Vùng đỉnh Swing: high >= previousSwingHigh - 0.10 * ATR (khi bật useSwingFilter); nếu bật requireSwingSweep, phải có high > previousSwingHigh và close < previousSwingHigh.
    • Cấu trúc nến: closePosition <= 0.35, nến giảm close < open (khi requireCandleDirection = true), tỷ lệ râu trên upperWickRatio >= 0.25 (nếu bật useWickFilter), và biên độ nến nằm trong [0.80 * ATR, 4.0 * ATR].
  2. Xác nhận vào lệnh (shortBase):
    • Nếu chọn Next Candle Confirmation: Đang có pendingShort cùng ngày trong vòng 1–3 nến sau nến Climax (validShortWindow), nến xác nhận là nến giảm (close < open), đóng cửa thấp hơn giá đóng nến Climax (close < shortClimaxClose), chưa phá đỉnh nến Climax (high <= shortClimaxHigh), và phá đáy nến Climax nếu bật requireBreakClimaxExtreme.
    • Nếu chọn Climax Candle Close: Sử dụng trực tiếp bearishClimax.
  3. Các bộ lọc tùy chọn (nếu bật): ema < ema[3] (và close < ema nếu bật requirePriceEMA), adx <= 35.0, rsi >= 40.0, và trên khung H1 đã đóng h1Close < h1EMA.

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

Biến canTrade yêu cầu đồng thời tất cả các cổng kiểm soát sau trước khi gửi lệnh:

  • Chỉ giao dịch trên nến đã đóng và khung Intraday: barstate.isconfirmed và timeframe.isintraday.
  • Trạng thái tài khoản rỗng (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 2 lệnh/ngày).
  • Thời gian nghỉ sau thoát lệnh (Cooldown): bar_index - lastExitBar > cooldownBars (mặc định nghỉ hơn 3 nến sau nến đóng lệnh trước đó) và không vào lại trên chính nến vừa vào (freshEntryBar).
  • Khung giờ giao dịch Việt Nam (Asia/Ho_Chi_Minh): Khi useSessionFilter = true, thời điểm mở nến >= 09:15 và đóng nến <= 14:15, đồng thời phải đóng nến trước giờ tất toán 14:45 (beforeForceClose).

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

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

CNPS85 không dùng SL theo ATR hay đỉnh/đáy nến mà sử dụng khoảng cắt lỗ cố định theo điểm, quy đổi chính xác sang bước giá (syminfo.mintick) của hợp đồng VN30F1M (0.1 điểm/tick):

  • slTicks = math.max(1, int(math.round(stopLossPoints / syminfo.mintick))) → Mặc định 5.0 điểm (50 ticks).
  • effectiveSL = slTicks * syminfo.mintick.
  • Mức cắt lỗ thực tế được tính từ giá khớp lệnh trung bình (strategy.position_avg_price - effectiveSL cho Long và strategy.position_avg_price + effectiveSL cho Short).

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

  • Take Profit cố định: tpTicks = math.max(1, int(math.round(takeProfitPoints / syminfo.mintick))) → Mặc định 15.0 điểm (150 ticks), tạo tỷ lệ Risk:Reward danh nghĩa 1:3. Bot không sử dụng Break Even hay Trailing Stop trong phiên bản V1 này.
  • Time Exit (Tùy chọn): Khi bật useTimeExit = true, nếu số nến nắm giữ barsHeld >= maximumHoldingBars (mặc định 20 nến) tại thời điểm nến đóng cửa (và không trùng nến forceCloseBar), bot gọi strategy.close_all() với ghi chú "Time Exit".
  • Force Close cuối phiên: Tại cây nến có openMinutes < 14:45 và closeMinutes >= 14:45 (forceCloseBar), nếu vẫn còn vị thế mở, bot tự động đóng toàn bộ bằng strategy.close_all() với ghi chú "Session End" để tránh rủi ro qua đêm (ATC/ATO).

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ạt trong codeGiá trị mặc địnhGhi chú trên biểu đồ / lệnh
Stop Loss (Cắt lỗ)Giá chạm strategy.position_avg_price ± effectiveSL5.0 điểm (50 ticks)SL Long / SL Short
Take Profit (Chốt lời)Giá chạm strategy.position_avg_price ± effectiveTP15.0 điểm (150 ticks)TP Long / TP Short
Time Exit (Hết thời gian)useTimeExit = true và barsHeld >= maximumHoldingBarsTắt (false / 20 nến)Time Exit
Force Close (Hết phiên)Nến vắt qua mốc endHour:endMinute (14:45)Bật mặc địnhSession 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 phái sinh VN30F1M trên TradingView (khung thời gian khuyến nghị trong phiên như M5 hoặc M15).
  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 và dán toàn bộ mã nguồn CNPS85 VOLUME CLIMAX REVERSAL V1 đã sao chép ở Mục 1.
  4. Nhấn Save (Lưu), sau đó nhấn Add to chart (Thêm vào biểu đồ).
  5. Vào phần Cài đặt (Settings) của chiến lược để bật các lớp hiển thị tùy chọn như Show Diagnostics, Show Volume Climax Dots, Show Swing Levels hoặc điều chỉnh Trade Direction sang "Both" nếu muốn giao dịch cả hai chiều Long và Short.

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

Khi bật Show Diagnostics = true, bot sẽ vẽ một bảng thống kê gồm 19 dòng ở góc trên bên phải biểu đồ (position.top_right):

  • CNPS85 V1 / Khung thời gian: Hiển thị phiên bản bot và timeframe.period hiện tại.
  • Volume Ratio: Tỷ lệ khối lượng nến hiện tại so với trung bình 20 nến trước.
  • Raw Climax Bars / Bullish Climax / Bearish Climax: Tổng số nến đạt ngưỡng Volume Climax và số nến đạt chuẩn từ chối giá theo chiều tăng/giảm.
  • Long Bases / Short Bases: Số tín hiệu cơ sở hình thành (sau bước xác nhận nến nếu dùng Next Candle Confirmation).
  • Filtered Long / Filtered Short: Số tín hiệu vượt qua toàn bộ các bộ lọc xu hướng/động lượng (EMA, ADX, RSI, H1).
  • Long Entries / Short Entries: Số lệnh thực tế đã được gửi vào thị trường.
  • Pending Long / Pending Short (YES/NO): Trạng thái hiện tại có đang chờ nến xác nhận hay không.
  • Expired Long / Expired Short: Số thiết lập bị hết hạn quá 3 nến hoặc bị hủy do phá cực trị ngược chiều.
  • EMA Up / EMA Down (YES/NO): Hướng dốc hiện tại của đường EMA50.
  • Trades Today: Số lệnh đã giao dịch trong ngày trên tổng giới hạn (ví dụ: 1/2).
  • Position: Trạng thái vị thế đang nắm giữ (LONG, SHORT, hoặc FLAT).

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

Để nhận thông báo tự động hoặc kết nối Webhook đẩy lệnh sang hệ thống giao dịch tự động, bạn thiết lập Alert trên TradingView như sau:

  1. Nhấn vào biểu tượng Cảnh báo (Alert) trên thanh công cụ TradingView.
  2. Ở mục Condition (Điều kiện), chọn tên chiến lược CNPS85 VOLUME CLIMAX REVERSAL V1.
  3. Ở ô Message (Thông điệp), xóa nội dung mặc định và điền chính xác cú pháp:
    {{strategy.order.alert_message}}
  4. Nhấn Create để kích hoạt cảnh báo. Nếu muốn tắt riêng cảnh báo khi chạm SL/TP (chỉ giữ cảnh báo vào lệnh, Time Exit và Session End), bạn có thể tích chọn Disable SL/TP Alerts (disableExitAlerts = true) trong cài đặt bot.

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

Loại sự kiệnTham số trong codeNội dung thông điệp Alert thực tế
Vào lệnh Longstrategy.entry("Long", ...)🟢 VÀO VỊ THẾ LONG (CNPS85)\n🎯 Giá vào: <giá>\n🛑 Cắt lỗ (SL): <giá>\n💰 Chốt lời (TP): <giá>
Vào lệnh Shortstrategy.entry("Short", ...)🔴 VÀO VỊ THẾ SHORT (CNPS85)\n🎯 Giá vào: <giá>\n🛑 Cắt lỗ (SL): <giá>\n💰 Chốt lời (TP): <giá>
Chốt lời Longalert_profit (Long Exit)💰 CHỐT LỜI LONG (CNPS85 - TP HIT)\n🎯 Giá chốt lời: <giá>
Cắt lỗ Longalert_loss (Long Exit)🛑 CẮT LỖ LONG (CNPS85 - SL HIT)\n💥 Giá cắt lỗ: <giá>
Chốt lời Shortalert_profit (Short Exit)💰 CHỐT LỜI SHORT (CNPS85 - TP HIT)\n🎯 Giá chốt lời: <giá>
Cắt lỗ Shortalert_loss (Short Exit)🛑 CẮT LỖ SHORT (CNPS85 - SL HIT)\n💥 Giá cắt lỗ: <giá>
Hết thời gian nắm giữstrategy.close_all (Time Exit)⏱️ ĐÓNG VỊ THẾ HẾT THỜI GIAN (CNPS85 - Time Exit)\n📌 Giá đóng: <giá>
Tất toán hết phiênstrategy.close_all (Session End)⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (CNPS85 - Session End)\n📌 Giá đóng: <giá>

Kết luận

CNPS85 Volume Climax Reversal V1 là một hệ thống giao dịch đảo chiều chặt chẽ, giải quyết tốt điểm yếu của các chiến lược bắt đỉnh/đáy thông thường nhờ kết hợp Volume Climax không tự làm nhiễu, vùng Swing Extreme, cấu trúc nến từ chối giá và State Machine xác nhận nến kế tiếp. Chiến lược phát huy hiệu quả rõ nét nhất khi thị trường VN30F1M xuất hiện các nhịp rũ bỏ (shakeout) hoặc quét thanh khoản mạnh tại hỗ trợ/kháng cự ngắn hạn trong biên độ dao động ổn định.

Bạn có thể tham khảo thêm các hệ thống giao dịch khác trên hệ sinh thái như Bot CNPS50 - Trend Analysis V2 và Bot CNPS49 - Daily Open để đa dạng hóa danh mục chiến lược.

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