Hướng Dẫn Sử Dụng Bot CNPS92 - PDH PDL Sweep Delayed Reclaim V2 cho VN30F1M
TradingviewBot CNPS92 PDH PDL Sweep Delayed Reclaim V2 tự động hóa chiến lược quét thanh khoản đỉnh/đáy ngày hôm trước (PDH/PDL) kết hợp state machine tách biệt pha quét và pha reclaim trên VN30F1M.

Mục lục
Khi giao dịch hợp đồng tương lai chỉ số VN30F1M, các vùng đỉnh và đáy của phiên trước (PDH – Previous Day High và PDL – Previous Day Low) luôn là điểm tập trung thanh khoản lớn, nơi thường xuyên xảy ra các nhịp phá vỡ giả (fake breakout / liquidity sweep) nhằm quét cắt lỗ trước khi giá đảo chiều quay lại vùng giá trị. Tuy nhiên, nếu bắt đảo chiều ngay khi giá vừa xuyên qua PDH/PDL thì rất dễ bị cuốn theo xu hướng phá vỡ thật, còn nếu chờ quá lâu lại lỡ mất điểm vào tối ưu.
Bot CNPS92 với tên đầy đủ trong mã nguồn là CNPS92 PDH PDL SWEEP DELAYED RECLAIM V2 (shorttitle="CNPS92 SWEEP V2"), được viết trên nền tảng Pine Script v6 của TradingView, giải quyết bài toán này bằng kiến trúc State Machine tách biệt hoàn toàn pha quét thanh khoản (Sweep) và pha lấy lại mốc giá (Reclaim).
Những điểm nổi bật cốt lõi của Bot CNPS92:
- Mốc tham chiếu Daily xác nhận cứng: Chỉ sử dụng
PDH,PDL,PDCtừ nến ngày đã đóng cửa hoàn toàn (high[1],low[1],close[1]), không dùng đỉnh/đáy ngày đang hình thành. - Hỗ trợ Delayed Reclaim: Cho phép giá lấy lại mốc PDH/PDL ngay trên nến quét hoặc trong vòng
reclaimWindow(mặc định 5 nến) sau đó, tránh bỏ lỡ các nhịp phục hồi diễn ra từ từ. - Hai chế độ xác nhận điểm vào lệnh: Vào ngay khi đóng nến Reclaim (
Reclaim Candle Close) hoặc chờ nến tiếp theo xác nhận phá vỡ mức Trigger (Next Candle Confirmation) với cơ chế hủy setup nếu thủng cực trị quét. - Chống lặp tín hiệu & kiểm soát rủi ro chặt chẽ: Tích hợp cơ chế
Re-arm(chỉ kích hoạt lại trạng thái sẵn sàng quét sau khi giá quay về vùng hợp lệ), giới hạn số lệnh/ngày, cooldown sau thoát lệnh, SL/TP cố định theo điểm và tự động đóng vị thế cuối phiên.
1. CNPS92 PDH PDL Sweep Delayed Reclaim V2 là gì?
CNPS92 PDH PDL Sweep Delayed Reclaim V2 là hệ thống giao dịch theo hành động giá (Price Action) kết hợp quản trị trạng thái tự động trên khung thời gian nội nhật (timeframe.isintraday). Chiến lược được xây dựng dựa trên 4 trụ cột kỹ thuật chính:
- Hệ thống mốc tham chiếu ngày trước (Previous Day Levels): Lấy dữ liệu
PDH,PDL,PDCtừ khung Daily đã xác nhận kết hợp bộ lọc biên độ ngày trước theo ATR (useDayRangeFilter) để đảm bảo bối cảnh biến động phù hợp. - Máy trạng thái quét thanh khoản & Reclaim (Sweep State Machine): Tách riêng 4 pha độc lập cho hai chiều Long/Short (
SEEK→SWEPT→RECLAIMED→RESET), giúp bot không phát tín hiệu liên tục khi giá duy trì ngoài biên PDH/PDL. - Bộ xác nhận & lọc đa tầng (Confirmation & Filters): Hỗ trợ xác nhận nến kế tiếp, kiểm tra giữ mốc đã reclaim, hủy setup khi phá cực trị quét, kèm các bộ lọc tùy chọn gồm EMA Trend, Relative Volume, ADX tối đa và H1 EMA Bias.
- Quản trị rủi ro & phiên giao dịch (Risk & Session Engine): Tính toán Stop Loss và Take Profit theo số điểm cố định quy đổi ra tick, hỗ trợ thoát lệnh theo thời gian nắm giữ (
useTimeExit), giới hạn lệnh/ngày, cooldown và Force Close cuối phiên theo múi giờAsia/Ho_Chi_Minh.
Bảng thông số mặc định
| Nhóm thông số | Tên tham số (Input) | Giá trị mặc định | Ý nghĩa |
|---|---|---|---|
| 01. Previous Day Levels | atrLength | 14 | Chu kỳ tính ATR |
useDayRangeFilter | false | Bật/tắt lọc biên độ ngày trước theo ATR | |
minimumDayRangeATR / maximumDayRangeATR | 1.0 / 40.0 | Biên độ (PDH - PDL) / ATR tối thiểu / tối đa | |
| 02. Liquidity Sweep | sweepBufferATR | 0.0 | Khoảng vượt biên tối thiểu để tính là Sweep (theo ATR) |
reclaimWindow | 5 | Số nến tối đa cho phép kể từ lúc Sweep để Reclaim | |
reclaimBufferATR | 0.0 | Khoảng đệm đóng nến quay lại bên trong (theo ATR) | |
requireFreshSweep | false | Yêu cầu nến trước đó chưa vượt biên Sweep | |
useSweepWickFilter / minimumWickRatio | false / 0.20 | Lọc tỷ lệ râu nến từ chối trên tổng biên độ nến Reclaim | |
useCloseLocation / minimumLongClosePosition / maximumShortClosePosition | false / 0.50 / 0.50 | Lọc vị trí giá đóng cửa trong thân-râu nến Reclaim | |
| 03. Entry Confirmation | entryMode | "Reclaim Candle Close" | Chế độ vào lệnh (hoặc "Next Candle Confirmation") |
confirmationWindow | 5 | Số nến tối đa chờ xác nhận sau khi Reclaim | |
confirmationLevel | "Signal Close" | Mức Trigger xác nhận (Reclaimed Level, Signal Close, Signal Midpoint, Signal High/Low) | |
requireDirection | false | Yêu cầu nến xác nhận cùng màu (tăng cho Long, giảm cho Short) | |
requireLevelHold | true | Yêu cầu giá đóng cửa vẫn giữ được mốc PDH/PDL đã Reclaim | |
cancelOnSweepExtremeBreak / invalidationATR | true / 0.10 | Hủy setup chờ nếu giá phá cực trị Sweep quá 0.10 * ATR | |
maximumSetupsPerDirection | 5 | Số lần Reclaim tối đa mỗi chiều trong ngày | |
| 04. EMA Trend | useEMAFilter / emaLength / emaSlopeBars / requirePriceEMA | false / 50 / 3 / false | Lọc xu hướng theo độ dốc EMA50 và vị trí giá so với EMA |
| 05. Optional Filters | useVolumeFilter / volumeLength / minimumVolumeFactor | false / 20 / 1.0 | Lọc khối lượng tương đối so với SMA20 của volume[1] |
useADXFilter / diLength / adxSmoothing / maximumADX | false / 14 / 14 / 35.0 | Lọc ADX tối đa để tránh thị trường có xu hướng quá mạnh | |
| 06. H1 Bias | useH1Bias / h1EMALength | false / 50 | Lọc hướng giao dịch theo EMA50 khung H1 đã đóng nến |
| 07. Risk Management | stopLossPoints / takeProfitPoints | 5.0 / 15.0 | Mức Stop Loss (5 điểm) và Take Profit (15 điểm) |
useTimeExit / maximumHoldingBars | false / 20 | Đóng lệnh nếu nắm giữ đủ số nến tối đa | |
| 08. Trade Control | tradeDirection / contracts | "Both" / 3 | Chiều giao dịch cho phép và tham số số hợp đồng |
maximumTradesPerDay / cooldownBars | 3 / 1 | Tối đa 3 lệnh/ngày; nghỉ tối thiểu 1 nến sau khi đóng lệnh | |
| 09. Trading Session | tz / useSessionFilter | "Asia/Ho_Chi_Minh" / true | Múi giờ Việt Nam, bật lọc phiên |
Entry Window (startHour:Minute – lastHour:Minute) | 09:00 – 14:15 | Khung giờ cho phép mở vị thế mới | |
Force Close (endHour:Minute) | 14:45 | Thời điểm bắt buộc đóng toàn bộ vị thế cuối ngày | |
| 10. Alerts & 11. Display | disableExitAlerts / showDiagnostics | false / false | Bật/tắt cảnh báo SL/TP và bảng Diagnostics |
Source Code CNPS92 PDH PDL Sweep Delayed Reclaim V2
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="CNPS92 PDH PDL SWEEP DELAYED RECLAIM V2", shorttitle="CNPS92 SWEEP V2", 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)
// ============================================================================
// CNPS92 V2 - PREVIOUS DAY HIGH / LOW SWEEP
// + DELAYED RECLAIM
//
// LONG:
// 1. Price trades below confirmed Previous Day Low.
// 2. Save the liquidity sweep event.
// 3. Allow price to reclaim PDL on the same
// candle or within N future candles.
// 4. Enter on reclaim OR wait for confirmation.
//
// SHORT:
// 1. Price trades above confirmed Previous Day High.
// 2. Save the sweep event.
// 3. Wait for price to close back below PDH.
// 4. Enter on reclaim OR later confirmation.
//
// IMPORTANT:
// - Confirmed previous DAILY levels.
// - No use of the developing daily high/low.
// - State machine separates sweep from reclaim.
// - No repeated signals while price stays
// continuously beyond the swept level.
// - Daily reset and pending setup expiration.
// - Fixed SL / TP and position controls.
// ============================================================================
// ============================================================================
// 01. PREVIOUS DAY REFERENCE
// ============================================================================
gLevels = "01. Previous Day Levels"
atrLength = input.int(14, "ATR Length", minval=1, group=gLevels)
useDayRangeFilter = input.bool(false, "Use Previous Day Range Filter", group=gLevels)
minimumDayRangeATR = input.float(1.0, "Minimum Daily Range / ATR", minval=0.0, step=0.5, group=gLevels)
maximumDayRangeATR = input.float(40.0, "Maximum Daily Range / ATR", minval=1.0, step=1.0, group=gLevels)
// ============================================================================
// 02. LIQUIDITY SWEEP
// ============================================================================
gSweep = "02. Liquidity Sweep"
sweepBufferATR = input.float(0.0, "Minimum Sweep Distance / ATR", minval=0.0, step=0.05, group=gSweep)
reclaimWindow = input.int(5, "Maximum Bars To Reclaim", minval=0, maxval=50, group=gSweep)
reclaimBufferATR = input.float(0.0, "Reclaim Buffer / ATR", minval=0.0, step=0.05, group=gSweep)
requireFreshSweep = input.bool(false, "Require Previous Bar Not Swept", group=gSweep)
useSweepWickFilter = input.bool(false, "Require Rejection Wick On Reclaim", group=gSweep)
minimumWickRatio = input.float(0.20, "Minimum Rejection Wick / Range", minval=0.0, maxval=1.0, step=0.05, group=gSweep)
useCloseLocation = input.bool(false, "Use Reclaim Close Location Filter", group=gSweep)
minimumLongClosePosition = input.float(0.50, "Minimum Long Close Position", minval=0.0, maxval=1.0, step=0.05, group=gSweep)
maximumShortClosePosition = input.float(0.50, "Maximum Short Close Position", minval=0.0, maxval=1.0, step=0.05, group=gSweep)
// ============================================================================
// 03. ENTRY CONFIRMATION
// ============================================================================
gConfirm = "03. Entry Confirmation"
entryMode = input.string("Reclaim Candle Close", "Entry Mode", options=["Reclaim Candle Close", "Next Candle Confirmation"], group=gConfirm)
confirmationWindow = input.int(5, "Confirmation Window", minval=1, maxval=50, group=gConfirm)
confirmationLevel = input.string("Signal Close", "Confirmation Level", options=["Reclaimed Level", "Signal Close", "Signal Midpoint", "Signal High/Low"], group=gConfirm)
requireDirection = input.bool(false, "Require Bullish/Bearish Entry Candle", group=gConfirm)
requireLevelHold = input.bool(true, "Require Price To Hold Reclaimed Level", group=gConfirm)
cancelOnSweepExtremeBreak = input.bool(true, "Cancel If Sweep Extreme Breaks", group=gConfirm)
invalidationATR = input.float(0.10, "Invalidation Buffer / ATR", minval=0.0, step=0.05, group=gConfirm)
maximumSetupsPerDirection = input.int(5, "Maximum Reclaims / Direction / Day", minval=1, maxval=30, group=gConfirm)
// ============================================================================
// 04. EMA TREND FILTER
// ============================================================================
gTrend = "04. EMA Trend"
useEMAFilter = input.bool(false, "Use EMA Trend Filter", group=gTrend)
emaLength = input.int(50, "EMA Length", minval=2, 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)
// ============================================================================
// 05. OPTIONAL FILTERS
// ============================================================================
gFilters = "05. Optional Filters"
useVolumeFilter = input.bool(false, "Use Volume Filter", group=gFilters)
volumeLength = input.int(20, "Volume Average Length", minval=2, group=gFilters)
minimumVolumeFactor = input.float(1.0, "Minimum Relative Volume", minval=0.1, step=0.1, group=gFilters)
useADXFilter = input.bool(false, "Use Maximum ADX", 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)
// ============================================================================
// 06. CONFIRMED H1 BIAS
// ============================================================================
gH1 = "06. H1 Bias"
useH1Bias = input.bool(false, "Use Confirmed H1 EMA Bias", group=gH1)
h1EMALength = input.int(50, "H1 EMA Length", minval=2, group=gH1)
// ============================================================================
// 07. RISK MANAGEMENT
// ============================================================================
gRisk = "07. 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 Maximum Holding Bars", group=gRisk)
maximumHoldingBars = input.int(20, "Maximum Holding Bars", minval=1, maxval=200, group=gRisk)
// ============================================================================
// 08. TRADE CONTROL
// ============================================================================
gTrade = "08. Trade Control"
tradeDirection = input.string("Both", "Trade Direction", options=["Long", "Short", "Both"], group=gTrade)
contracts = input.int(3, "Contracts", minval=1, maxval=100, group=gTrade)
maximumTradesPerDay = input.int(3, "Maximum Trades Per Day", minval=1, maxval=20, group=gTrade)
cooldownBars = input.int(1, "Cooldown After Exit (Bars)", minval=0, maxval=100, group=gTrade)
bool allowLong = (tradeDirection == "Long" or tradeDirection == "Both")
bool allowShort = (tradeDirection == "Short" or tradeDirection == "Both")
// ============================================================================
// 09. TRADING SESSION
// ============================================================================
gSession = "09. Trading Session"
tz = input.string("Asia/Ho_Chi_Minh", "Timezone", group=gSession)
useSessionFilter = input.bool(true, "Use Entry Session Filter", group=gSession)
startHour = input.int(9, "Entry Start Hour", minval=0, maxval=23, group=gSession)
startMinute = input.int(0, "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)
// ============================================================================
// 10. ALERTS
// ============================================================================
gAlerts = "10. Alerts"
disableExitAlerts = input.bool(false, "Disable SL/TP Alerts", group=gAlerts)
// ============================================================================
// 11. DISPLAY
// ============================================================================
gDisplay = "11. Display"
showPDLevels = input.bool(true, "Show Previous Day High/Low", group=gDisplay)
showPDC = input.bool(false, "Show Previous Day Close", group=gDisplay)
showEMA = input.bool(true, "Show EMA", group=gDisplay)
showSweepMarkers = input.bool(false, "Show Sweep Markers", group=gDisplay)
showReclaimMarkers = input.bool(false, "Show Reclaim Markers", 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)
// ============================================================================
// 12. 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)
// ============================================================================
// 13. DAILY COUNTERS
// ============================================================================
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
var int longSetupsToday = 0
var int shortSetupsToday = 0
if newDay
tradesToday := 0
longSetupsToday := 0
shortSetupsToday := 0
// ============================================================================
// 14. CONFIRMED DAILY OHLC
// ============================================================================
//
// Previous COMPLETED daily candle.
//
// The daily [1] offset makes these
// reference levels available without
// using developing daily values.
//
// ============================================================================
[pdh, pdl, pdc] = request.security(syminfo.tickerid, "D", [high[1], low[1], close[1]], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
bool levelsReady = (intradayOK and not na(pdh) and not na(pdl) and pdh > pdl)
// ============================================================================
// 15. INDICATORS
// ============================================================================
float atr = ta.atr(atrLength)
float ema = ta.ema(close, emaLength)
float averageVolume = ta.sma(volume[1], volumeLength)
float relativeVolume = (not na(volume) and not na(averageVolume) and averageVolume > 0 ? volume / averageVolume : na)
[diPlus, diMinus, adx] = ta.dmi(diLength, adxSmoothing)
float previousDayRange = (levelsReady ? pdh - pdl : na)
float previousDayRangeATR = (not na(previousDayRange) and not na(atr) and atr > 0 ? previousDayRange / atr : na)
bool dayRangeOK = (not useDayRangeFilter or (not na(previousDayRangeATR) and previousDayRangeATR >= minimumDayRangeATR and previousDayRangeATR <= maximumDayRangeATR))
// ============================================================================
// 16. SWEEP / RECLAIM DISTANCES
// ============================================================================
float sweepBuffer = (not na(atr) ? atr * sweepBufferATR : 0.0)
float reclaimBuffer = (not na(atr) ? atr * reclaimBufferATR : 0.0)
float invalidationBuffer = (not na(atr) ? atr * invalidationATR : 0.0)
// ============================================================================
// 17. CANDLE ANATOMY
// ============================================================================
float candleRange = high - low
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 closePosition = (candleRange > 0 ? (close - low) / candleRange : 0.5)
bool bullishCandle = close > open
bool bearishCandle = close < open
bool longWickOK = (not useSweepWickFilter or lowerWickRatio >= minimumWickRatio)
bool shortWickOK = (not useSweepWickFilter or upperWickRatio >= minimumWickRatio)
bool longCloseOK = (not useCloseLocation or closePosition >= minimumLongClosePosition)
bool shortCloseOK = (not useCloseLocation or closePosition <= maximumShortClosePosition)
// ============================================================================
// 18. EMA FILTER
// ============================================================================
bool emaUp = (not na(ema[emaSlopeBars]) and ema > ema[emaSlopeBars])
bool emaDown = (not na(ema[emaSlopeBars]) and ema < ema[emaSlopeBars])
bool longTrendOK = (not useEMAFilter or (emaUp and (not requirePriceEMA or close > ema)))
bool shortTrendOK = (not useEMAFilter or (emaDown and (not requirePriceEMA or close < ema)))
// ============================================================================
// 19. OPTIONAL FILTERS
// ============================================================================
bool volumeOK = (not useVolumeFilter or (not na(relativeVolume) and relativeVolume >= minimumVolumeFactor))
bool adxOK = (not useADXFilter or (not na(adx) and adx <= maximumADX))
// ============================================================================
// 20. CONFIRMED H1 FILTER
// ============================================================================
[h1EMA, h1Close] = request.security(syminfo.tickerid, "60", [ta.ema(close, h1EMALength)[1], close[1]], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
bool validH1Chart = (timeframe.isintraday and timeframe.in_seconds() < 3600)
bool longH1OK = (not useH1Bias or (validH1Chart and not na(h1EMA) and not na(h1Close) and h1Close > h1EMA))
bool shortH1OK = (not useH1Bias or (validH1Chart and not na(h1EMA) and not na(h1Close) and h1Close < h1EMA))
// ============================================================================
// 21. POSITION / COOLDOWN
// ============================================================================
bool flat = strategy.position_size == 0
bool inLong = strategy.position_size > 0
bool inShort = strategy.position_size < 0
var int lastExitBar = na
var int lastEntryBar = na
bool newClosedTrade = (strategy.closedtrades > nz(strategy.closedtrades[1], 0))
if newClosedTrade
lastExitBar := bar_index
bool cooldownOK = (na(lastExitBar) or bar_index - lastExitBar > cooldownBars)
bool freshEntryBar = (na(lastEntryBar) or lastEntryBar != bar_index)
// ============================================================================
// 22. SWEEP STATE MACHINE
// ============================================================================
//
// SEEK:
// Both sides may independently await a sweep.
//
// SWEPT:
// Price has crossed a PDH/PDL boundary.
// Allow reclaim within reclaimWindow bars.
//
// RECLAIMED:
// Price closes back on the inside.
// Either enter immediately or create
// a pending price confirmation setup.
//
// RESET:
// Re-arm sweep detection after price
// returns to the valid side of its level.
//
// ============================================================================
var bool longSweepActive = false
var bool shortSweepActive = false
var bool longSweepReady = true
var bool shortSweepReady = true
var int longSweepBar = na
var int shortSweepBar = na
var float longSweepExtreme = na
var float shortSweepExtreme = na
var float longSweepATR = na
var float shortSweepATR = na
var bool pendingLong = false
var bool pendingShort = false
var int longReclaimBar = na
var int shortReclaimBar = na
var int longReclaimDay = na
var int shortReclaimDay = na
var float longSignalHigh = na
var float longSignalLow = na
var float longSignalClose = na
var float longReference = na
var float longInvalidExtreme = na
var float longSignalATR = na
var float shortSignalHigh = na
var float shortSignalLow = na
var float shortSignalClose = na
var float shortReference = na
var float shortInvalidExtreme = na
var float shortSignalATR = na
var int longSweepCount = 0
var int shortSweepCount = 0
var int longReclaimCount = 0
var int shortReclaimCount = 0
var int longBaseCount = 0
var int shortBaseCount = 0
var int filteredLongCount = 0
var int filteredShortCount = 0
var int expiredSweepCount = 0
var int expiredConfirmCount = 0
var int longEntryCount = 0
var int shortEntryCount = 0
bool confirmationMode = (entryMode == "Next Candle Confirmation")
// ============================================================================
// 23. DAILY SWEEP RESET
// ============================================================================
if newDay
longSweepActive := false
shortSweepActive := false
longSweepReady := true
shortSweepReady := true
longSweepBar := na
shortSweepBar := na
longSweepExtreme := na
shortSweepExtreme := na
longSweepATR := na
shortSweepATR := na
pendingLong := false
pendingShort := false
longReclaimBar := na
shortReclaimBar := na
longReclaimDay := na
shortReclaimDay := na
longSignalHigh := na
longSignalLow := na
longSignalClose := na
longReference := na
longInvalidExtreme := na
longSignalATR := na
shortSignalHigh := na
shortSignalLow := na
shortSignalClose := na
shortReference := na
shortInvalidExtreme := na
shortSignalATR := na
// ============================================================================
// 24. SWEEP DETECTION
// ============================================================================
bool freshLongOK = (not requireFreshSweep or low[1] >= pdl - sweepBuffer)
bool freshShortOK = (not requireFreshSweep or high[1] <= pdh + sweepBuffer)
bool canFindSweep = (barstate.isconfirmed and levelsReady and dayRangeOK and entrySessionOK and beforeForceClose and flat and tradesToday < maximumTradesPerDay)
bool startLongSweep = (canFindSweep and allowLong and longSweepReady and not longSweepActive and not pendingLong and longSetupsToday < maximumSetupsPerDirection and low < pdl - sweepBuffer and freshLongOK)
bool startShortSweep = (canFindSweep and allowShort and shortSweepReady and not shortSweepActive and not pendingShort and shortSetupsToday < maximumSetupsPerDirection and high > pdh + sweepBuffer and freshShortOK)
bool ambiguousSweep = (startLongSweep and startShortSweep)
if startLongSweep and not ambiguousSweep
longSweepActive := true
longSweepReady := false
longSweepBar := bar_index
longSweepExtreme := low
longSweepATR := atr
longSweepCount += 1
if startShortSweep and not ambiguousSweep
shortSweepActive := true
shortSweepReady := false
shortSweepBar := bar_index
shortSweepExtreme := high
shortSweepATR := atr
shortSweepCount += 1
// ============================================================================
// 25. UPDATE ACTIVE SWEEP EXTREMES
// ============================================================================
if barstate.isconfirmed
if longSweepActive
longSweepExtreme := math.min(longSweepExtreme, low)
if shortSweepActive
shortSweepExtreme := math.max(shortSweepExtreme, high)
// ============================================================================
// 26. SWEEP TIMEOUT
// ============================================================================
bool longSweepExpired = (longSweepActive and not na(longSweepBar) and bar_index - longSweepBar > reclaimWindow)
bool shortSweepExpired = (shortSweepActive and not na(shortSweepBar) and bar_index - shortSweepBar > reclaimWindow)
if barstate.isconfirmed
if longSweepExpired
longSweepActive := false
longSweepBar := na
expiredSweepCount += 1
if shortSweepExpired
shortSweepActive := false
shortSweepBar := na
expiredSweepCount += 1
// ============================================================================
// 27. RECLAIM EVENTS
// ============================================================================
//
// Same-bar reclaim is supported.
//
// Delayed reclaim is also supported
// while the sweep remains active.
//
// No extra wick restriction by default
// because delayed reclaim may occur
// on an ordinary directional candle.
//
// ============================================================================
bool longReclaimEvent = (barstate.isconfirmed and longSweepActive and not longSweepExpired and not na(longSweepBar) and bar_index - longSweepBar <= reclaimWindow and close > pdl + reclaimBuffer and longWickOK and longCloseOK)
bool shortReclaimEvent = (barstate.isconfirmed and shortSweepActive and not shortSweepExpired and not na(shortSweepBar) and bar_index - shortSweepBar <= reclaimWindow and close < pdh - reclaimBuffer and shortWickOK and shortCloseOK)
bool ambiguousReclaim = (longReclaimEvent and shortReclaimEvent)
bool qualifiedLongReclaim = (longReclaimEvent and not ambiguousReclaim)
bool qualifiedShortReclaim = (shortReclaimEvent and not ambiguousReclaim)
// ============================================================================
// 28. CONFIRMATION LEVELS
// ============================================================================
float longTrigger = (confirmationLevel == "Reclaimed Level" ? longReference : confirmationLevel == "Signal High/Low" ? longSignalHigh : confirmationLevel == "Signal Midpoint" ? (longSignalHigh + longSignalLow) / 2.0 : longSignalClose)
float shortTrigger = (confirmationLevel == "Reclaimed Level" ? shortReference : confirmationLevel == "Signal High/Low" ? shortSignalLow : confirmationLevel == "Signal Midpoint" ? (shortSignalHigh + shortSignalLow) / 2.0 : shortSignalClose)
bool longWindowOK = (pendingLong and longReclaimDay == dayKey and not na(longReclaimBar) and bar_index > longReclaimBar and bar_index - longReclaimBar <= confirmationWindow)
bool shortWindowOK = (pendingShort and shortReclaimDay == dayKey and not na(shortReclaimBar) and bar_index > shortReclaimBar and bar_index - shortReclaimBar <= confirmationWindow)
float longInvalidBuffer = (not na(longSignalATR) ? longSignalATR * invalidationATR : invalidationBuffer)
float shortInvalidBuffer = (not na(shortSignalATR) ? shortSignalATR * invalidationATR : invalidationBuffer)
bool longExtremeOK = (not cancelOnSweepExtremeBreak or (not na(longInvalidExtreme) and low >= longInvalidExtreme - longInvalidBuffer))
bool shortExtremeOK = (not cancelOnSweepExtremeBreak or (not na(shortInvalidExtreme) and high <= shortInvalidExtreme + shortInvalidBuffer))
bool longHoldOK = (not requireLevelHold or (not na(longReference) and close > longReference))
bool shortHoldOK = (not requireLevelHold or (not na(shortReference) and close < shortReference))
bool longDirectionOK = (not requireDirection or bullishCandle)
bool shortDirectionOK = (not requireDirection or bearishCandle)
// ============================================================================
// 29. CONFIRMED PRICE ENTRIES
// ============================================================================
bool confirmedLong = (barstate.isconfirmed and longWindowOK and longExtremeOK and longHoldOK and longDirectionOK and not na(longTrigger) and close > longTrigger)
bool confirmedShort = (barstate.isconfirmed and shortWindowOK and shortExtremeOK and shortHoldOK and shortDirectionOK and not na(shortTrigger) and close < shortTrigger)
bool longBase = (confirmationMode ? confirmedLong : qualifiedLongReclaim)
bool shortBase = (confirmationMode ? confirmedShort : qualifiedShortReclaim)
// ============================================================================
// 30. FINAL FILTERS
// ============================================================================
bool rawLong = (longBase and longTrendOK and volumeOK and adxOK and longH1OK)
bool rawShort = (shortBase and shortTrendOK and volumeOK and adxOK and shortH1OK)
// ============================================================================
// 31. ENTRY GATES
// ============================================================================
bool canTrade = (barstate.isconfirmed and intradayOK and levelsReady and dayRangeOK and flat and strategy.opentrades == 0 and tradesToday < maximumTradesPerDay and cooldownOK and freshEntryBar and entrySessionOK and beforeForceClose)
bool enterLong = (canTrade and allowLong and rawLong and not rawShort)
bool enterShort = (canTrade and allowShort and rawShort and not rawLong)
// ============================================================================
// 32. SL / TP IN TICKS
// ============================================================================
int slTicks = math.max(1, int(math.round(stopLossPoints / syminfo.mintick)))
int tpTicks = math.max(1, int(math.round(takeProfitPoints / syminfo.mintick)))
float effectiveSL = slTicks * syminfo.mintick
float effectiveTP = tpTicks * syminfo.mintick
// ============================================================================
// 33. LONG ENTRY
// ============================================================================
if enterLong
strategy.entry("Long", strategy.long, comment="PDL DELAYED RECLAIM LONG", alert_message="🟢 VÀO VỊ THẾ LONG (CNPS92)\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\n🛑 SL dự kiến: " + str.tostring(close - slTicks * syminfo.mintick, format.mintick) + "\n🎯 TP dự kiến: " + str.tostring(close + tpTicks * syminfo.mintick, format.mintick))
tradesToday += 1
longEntryCount += 1
lastEntryBar := bar_index
// ============================================================================
// 34. SHORT ENTRY
// ============================================================================
if enterShort
strategy.entry("Short", strategy.short, comment="PDH DELAYED RECLAIM SHORT", alert_message="🔴 VÀO VỊ THẾ SHORT (CNPS92)\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\n🛑 SL dự kiến: " + str.tostring(close + slTicks * syminfo.mintick, format.mintick) + "\n🎯 TP dự kiến: " + str.tostring(close - tpTicks * syminfo.mintick, format.mintick))
tradesToday += 1
shortEntryCount += 1
lastEntryBar := bar_index
// ============================================================================
// 35. UPDATE RECLAIM / PENDING STATE
// ============================================================================
//
// Register reclaim after entry evaluation.
// Confirmation-mode entries therefore
// occur only on later candles.
//
// ============================================================================
if barstate.isconfirmed
if longBase
longBaseCount += 1
if shortBase
shortBaseCount += 1
if rawLong
filteredLongCount += 1
if rawShort
filteredShortCount += 1
// --------------------------------------------------------
// EXPIRE PENDING LONG
// --------------------------------------------------------
if pendingLong
bool longExpired = (longReclaimDay != dayKey or bar_index - longReclaimBar > confirmationWindow)
bool longInvalid = ((cancelOnSweepExtremeBreak and not na(longInvalidExtreme) and low < longInvalidExtreme - longInvalidBuffer) or (requireLevelHold and not na(longReference) and close <= longReference))
if (longExpired or longInvalid or confirmedLong or enterLong)
if longExpired or longInvalid
expiredConfirmCount += 1
pendingLong := false
longReclaimBar := na
// --------------------------------------------------------
// EXPIRE PENDING SHORT
// --------------------------------------------------------
if pendingShort
bool shortExpired = (shortReclaimDay != dayKey or bar_index - shortReclaimBar > confirmationWindow)
bool shortInvalid = ((cancelOnSweepExtremeBreak and not na(shortInvalidExtreme) and high > shortInvalidExtreme + shortInvalidBuffer) or (requireLevelHold and not na(shortReference) and close >= shortReference))
if (shortExpired or shortInvalid or confirmedShort or enterShort)
if shortExpired or shortInvalid
expiredConfirmCount += 1
pendingShort := false
shortReclaimBar := na
// --------------------------------------------------------
// CONSUME QUALIFIED LONG RECLAIM
// --------------------------------------------------------
if qualifiedLongReclaim
longSweepActive := false
longSweepBar := na
longReclaimCount += 1
longSetupsToday += 1
if confirmationMode and not pendingLong
pendingLong := true
longReclaimBar := bar_index
longReclaimDay := dayKey
longSignalHigh := high
longSignalLow := low
longSignalClose := close
longReference := pdl
longInvalidExtreme := longSweepExtreme
longSignalATR := atr
// --------------------------------------------------------
// CONSUME QUALIFIED SHORT RECLAIM
// --------------------------------------------------------
if qualifiedShortReclaim
shortSweepActive := false
shortSweepBar := na
shortReclaimCount += 1
shortSetupsToday += 1
if confirmationMode and not pendingShort
pendingShort := true
shortReclaimBar := bar_index
shortReclaimDay := dayKey
shortSignalHigh := high
shortSignalLow := low
shortSignalClose := close
shortReference := pdh
shortInvalidExtreme := shortSweepExtreme
shortSignalATR := atr
// --------------------------------------------------------
// RE-ARM AFTER RETURNING INSIDE
// --------------------------------------------------------
//
// The original sweep must be finished
// before a new sweep can start.
//
// At least one later candle is required
// after the original sweep.
//
// --------------------------------------------------------
bool longCanRearm = (not longSweepActive and not pendingLong and not longSweepReady and not na(longSweepExtreme) and close > pdl + reclaimBuffer and not qualifiedLongReclaim)
bool shortCanRearm = (not shortSweepActive and not pendingShort and not shortSweepReady and not na(shortSweepExtreme) and close < pdh - reclaimBuffer and not qualifiedShortReclaim)
if longCanRearm
longSweepReady := true
if shortCanRearm
shortSweepReady := true
// ============================================================================
// 36. LONG EXIT
// ============================================================================
strategy.exit("Long Exit", from_entry="Long", profit=tpTicks, loss=slTicks, comment_profit="TP Long", comment_loss="SL Long", alert_profit="💰 CHỐT LỜI LONG (TP HIT - CNPS92)\n🎯 Giá chốt: " + str.tostring(close, format.mintick), alert_loss="🛑 CẮT LỖ LONG (SL HIT - CNPS92)\n🎯 Giá cắt: " + str.tostring(close, format.mintick), disable_alert=disableExitAlerts)
// ============================================================================
// 37. SHORT EXIT
// ============================================================================
strategy.exit("Short Exit", from_entry="Short", profit=tpTicks, loss=slTicks, comment_profit="TP Short", comment_loss="SL Short", alert_profit="💰 CHỐT LỜI SHORT (TP HIT - CNPS92)\n🎯 Giá chốt: " + str.tostring(close, format.mintick), alert_loss="🛑 CẮT LỖ SHORT (SL HIT - CNPS92)\n🎯 Giá cắt: " + str.tostring(close, format.mintick), disable_alert=disableExitAlerts)
// ============================================================================
// 38. OPTIONAL TIME EXIT
// ============================================================================
int barsHeld = (strategy.opentrades > 0 ? bar_index - strategy.opentrades.entry_bar_index(0) : 0)
bool timeExit = (useTimeExit and strategy.position_size != 0 and barsHeld >= maximumHoldingBars and barstate.isconfirmed)
if timeExit and not forceCloseBar
strategy.close_all(immediately=true, comment="Time Exit", alert_message="⏱️ ĐÓNG VỊ THẾ QUÁ THỜI GIAN (Time Exit - CNPS92)\n🎯 Giá đóng: " + str.tostring(close, format.mintick))
// ============================================================================
// 39. SESSION FORCE CLOSE
// ============================================================================
if (barstate.isconfirmed and forceCloseBar and strategy.position_size != 0)
strategy.close_all(immediately=true, comment="Session End", alert_message="⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End - CNPS92)\n🎯 Giá đóng: " + str.tostring(close, format.mintick))
// ============================================================================
// 40. PREVIOUS DAY LEVEL PLOTS
// ============================================================================
plot(showPDLevels ? pdh : na, title="Previous Day High", color=color.red, linewidth=2, style=plot.style_stepline)
plot(showPDLevels ? pdl : na, title="Previous Day Low", color=color.lime, linewidth=2, style=plot.style_stepline)
plot(showPDC ? pdc : na, title="Previous Day Close", color=color.gray, linewidth=1, style=plot.style_stepline)
// ============================================================================
// 41. EMA PLOT
// ============================================================================
plot(showEMA ? ema : na, title="EMA Trend", color=color.orange, linewidth=2)
// ============================================================================
// 42. RAW SWEEP MARKERS
// ============================================================================
plotshape(showSweepMarkers and startLongSweep and not ambiguousSweep, title="PDL Sweep Detected", style=shape.circle, location=location.belowbar, color=color.new(color.green, 25), size=size.tiny, text="SW")
plotshape(showSweepMarkers and startShortSweep and not ambiguousSweep, title="PDH Sweep Detected", style=shape.circle, location=location.abovebar, color=color.new(color.red, 25), size=size.tiny, text="SW")
// ============================================================================
// 43. RECLAIM MARKERS
// ============================================================================
plotshape(showReclaimMarkers and qualifiedLongReclaim, title="PDL Reclaimed", style=shape.circle, location=location.belowbar, color=color.aqua, size=size.tiny, text="RC")
plotshape(showReclaimMarkers and qualifiedShortReclaim, title="PDH Reclaimed", style=shape.circle, location=location.abovebar, color=color.orange, size=size.tiny, text="RC")
// ============================================================================
// 44. PENDING CONFIRMATION LEVELS
// ============================================================================
plot(showPendingLevels and pendingLong ? longTrigger : na, title="Pending Long Trigger", color=color.aqua, linewidth=2, style=plot.style_linebr)
plot(showPendingLevels and pendingShort ? shortTrigger : na, title="Pending Short Trigger", color=color.fuchsia, linewidth=2, style=plot.style_linebr)
// ============================================================================
// 45. ENTRY MARKERS
// ============================================================================
plotshape(showEntryMarkers and enterLong, title="CNPS92 V2 LONG", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, text="LONG", textcolor=color.white)
plotshape(showEntryMarkers and enterShort, title="CNPS92 V2 SHORT", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small, text="SHORT", textcolor=color.white)
// ============================================================================
// 46. 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)
// ============================================================================
// 47. DATA WINDOW
// ============================================================================
plot(previousDayRange, title="Previous Day Range", color=color.gray, display=display.data_window)
plot(previousDayRangeATR, title="Previous Day Range / ATR", color=color.blue, display=display.data_window)
plot(relativeVolume, title="Relative Volume", color=color.purple, display=display.data_window)
plot(atr, title="ATR", color=color.gray, display=display.data_window)
plot(adx, title="ADX", color=color.orange, display=display.data_window)
// ============================================================================
// 48. DIAGNOSTICS TABLE
// ============================================================================
var table diagnostics = table.new(position.top_right, 2, 20, border_width=1)
if barstate.islast
if showDiagnostics
table.cell(diagnostics, 0, 0, "CNPS92 V2")
table.cell(diagnostics, 1, 0, timeframe.period)
table.cell(diagnostics, 0, 1, "PDH")
table.cell(diagnostics, 1, 1, str.tostring(pdh, "#.##"))
table.cell(diagnostics, 0, 2, "PDL")
table.cell(diagnostics, 1, 2, str.tostring(pdl, "#.##"))
table.cell(diagnostics, 0, 3, "Levels Ready")
table.cell(diagnostics, 1, 3, levelsReady ? "YES" : "NO")
table.cell(diagnostics, 0, 4, "Long Sweeps")
table.cell(diagnostics, 1, 4, str.tostring(longSweepCount))
table.cell(diagnostics, 0, 5, "Short Sweeps")
table.cell(diagnostics, 1, 5, str.tostring(shortSweepCount))
table.cell(diagnostics, 0, 6, "Long Reclaims")
table.cell(diagnostics, 1, 6, str.tostring(longReclaimCount))
table.cell(diagnostics, 0, 7, "Short Reclaims")
table.cell(diagnostics, 1, 7, str.tostring(shortReclaimCount))
table.cell(diagnostics, 0, 8, "Long Bases")
table.cell(diagnostics, 1, 8, str.tostring(longBaseCount))
table.cell(diagnostics, 0, 9, "Short Bases")
table.cell(diagnostics, 1, 9, str.tostring(shortBaseCount))
table.cell(diagnostics, 0, 10, "Filtered Long")
table.cell(diagnostics, 1, 10, str.tostring(filteredLongCount))
table.cell(diagnostics, 0, 11, "Filtered Short")
table.cell(diagnostics, 1, 11, str.tostring(filteredShortCount))
table.cell(diagnostics, 0, 12, "Long Entries")
table.cell(diagnostics, 1, 12, str.tostring(longEntryCount))
table.cell(diagnostics, 0, 13, "Short Entries")
table.cell(diagnostics, 1, 13, str.tostring(shortEntryCount))
table.cell(diagnostics, 0, 14, "Sweep Timeouts")
table.cell(diagnostics, 1, 14, str.tostring(expiredSweepCount))
table.cell(diagnostics, 0, 15, "Confirm Timeouts")
table.cell(diagnostics, 1, 15, str.tostring(expiredConfirmCount))
table.cell(diagnostics, 0, 16, "Active Long Sweep")
table.cell(diagnostics, 1, 16, longSweepActive ? "YES" : "NO")
table.cell(diagnostics, 0, 17, "Active Short Sweep")
table.cell(diagnostics, 1, 17, shortSweepActive ? "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")
else
table.clear(diagnostics, 0, 0, 1, 19)
2. Những khái niệm kỹ thuật cốt lõi trong CNPS92
2.1. Mốc thanh khoản PDH/PDL xác nhận cứng & Bộ lọc biên độ ngày
Bot lấy dữ liệu từ khung ngày ("D") thông qua request.security(syminfo.tickerid, "D", [high[1], low[1], close[1]], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on). Việc dùng offset [1] giúp cố định đỉnh (pdh), đáy (pdl) và giá đóng cửa (pdc) của phiên liền trước đã hoàn tất, loại bỏ hoàn toàn hiện tượng thay đổi mốc tham chiếu trong ngày (no developing daily high/low).
Khi useDayRangeFilter được bật, bot tính tỷ số previousDayRangeATR = (pdh - pdl) / atr (với atr = ta.atr(14)). Chỉ những ngày có biên độ nằm trong [minimumDayRangeATR, maximumDayRangeATR] (mặc định 1.0 – 40.0) mới thỏa mãn dayRangeOK.
2.2. State Machine quét thanh khoản (Sweep) & Delayed Reclaim
Khác với các bot chỉ kiểm tra râu nến trên một thanh đơn lẻ, CNPS92 dùng máy trạng thái lưu vết riêng cho 2 chiều:
- Pha Sweep (
longSweepActive/shortSweepActive): Kích hoạt khi giá xuyên qua biênpdl - sweepBuffer(hoặcpdh + sweepBuffer), vớisweepBuffer = atr * sweepBufferATR. Trong lúc đang active, bot liên tục cập nhật cực trị quét (longSweepExtreme = math.min(longSweepExtreme, low)vàshortSweepExtreme = math.max(shortSweepExtreme, high)). Nếu quáreclaimWindownến (mặc định 5 nến) mà giá chưa đóng cửa quay lại bên trong, Sweep hết hạn (expiredSweepCount += 1). - Pha Reclaim (
qualifiedLongReclaim/qualifiedShortReclaim): Xảy ra khi nến đóng cửa (barstate.isconfirmed) quay lại bên trong vùng giá trị (close > pdl + reclaimBuffervới Long,close < pdh - reclaimBuffervới Short), hỗ trợ cả Same-bar Reclaim (quét và rút chân ngay trên 1 nến) lẫn Delayed Reclaim (quét trước, đóng cửa quay lại sau tối đareclaimWindownến). Ngoài ra có thể siết thêm bộ lọc râu nến (lowerWickRatio/upperWickRatio >= minimumWickRatio) và vị trí đóng cửa (closePosition = (close - low) / (high - low)). - Cơ chế Re-arm (
longSweepReady/shortSweepReady): Sau khi một Sweep đã hoàn tất và không còn pending, bot chỉ cho phép tìm Sweep mới (longSweepReady := true) khi giá đã đóng cửa quay về phía hợp lệ bên trong (close > pdl + reclaimBufferhoặcclose < pdh - reclaimBuffer) ở một nến sau đó. Điều này ngăn việc phát tín hiệu lặp đi lặp lại nếu giá đi ngang hoặc trượt liên tục bên ngoài biên.
2.3. Hai chế độ vào lệnh & Các bộ lọc bối cảnh
- Chế độ vào lệnh (
entryMode):Reclaim Candle Close(mặc định): Sử dụng ngay sự kiệnqualifiedLongReclaim/qualifiedShortReclaimlàm tín hiệu nền (longBase/shortBase).Next Candle Confirmation: Khi có Reclaim, bot đưa setup vào trạng thái chờ (pendingLong/pendingShort) trong tối đaconfirmationWindownến (mặc định 5 nến). Nến xác nhận phải đóng cửa vượt mứcTrigger(tùy chọn theoReclaimed Level,Signal Close,Signal Midpoint, hoặcSignal High/Low), giữ được mốc đã reclaim nếurequireLevelHold = true, và chưa phá cực trị quét quáinvalidationATR(0.10 * ATR) nếucancelOnSweepExtremeBreak = true.
- Các bộ lọc tùy chọn (
Final Filters):- EMA Trend (
useEMAFilter): Yêu cầuema > ema[emaSlopeBars](EMA50 dốc lên so với 3 nến trước) cho Long và dốc xuống cho Short; có thể kèm điều kiệnclose > ema/close < ema(requirePriceEMA). - Volume (
useVolumeFilter): TínhrelativeVolume = volume / ta.sma(volume[1], 20)và yêu cầu>= minimumVolumeFactor(mặc định1.0). - ADX tối đa (
useADXFilter): Yêu cầuadx <= maximumADX(mặc định35.0, chu kỳDI=14,Smoothing=14) nhằm tránh bắt đảo chiều khi thị trường đang có xu hướng một chiều quá mạnh. - H1 EMA Bias (
useH1Bias): Áp dụng trên biểu đồ có khung nhỏ hơn 1 giờ (timeframe.in_seconds() < 3600), lấy[ta.ema(close, h1EMALength)[1], close[1]]từ khung"60"đã đóng nến để chỉ Long khih1Close > h1EMAvà Short khih1Close < h1EMA.
- EMA Trend (
3. Nguyên lý hoạt động của CNPS92
Quy trình vận hành trên mỗi nến đã đóng cửa (barstate.isconfirmed) diễn ra tuần tự theo 5 bước:
- Khởi tạo phiên mới (
newDay): Khi sang ngày giao dịch mới theo múi giờAsia/Ho_Chi_Minh, toàn bộ biến đếm (tradesToday,longSetupsToday,shortSetupsToday) và trạng thái Sweep/Pending của ngày cũ được reset về trạng thái ban đầu (longSweepReady := true,shortSweepReady := true). - Phát hiện Liquidity Sweep: Khi đủ điều kiện môi trường (
levelsReady,dayRangeOK,entrySessionOK,beforeForceClose,flat,tradesToday < maximumTradesPerDay), nếu giá xuyên xuống dướipdl - sweepBuffer(hoặc lên trênpdh + sweepBuffer) và không xảy ra quét 2 đầu cùng lúc (not ambiguousSweep), bot kích hoạtlongSweepActivehoặcshortSweepActivevà ghi nhận cực trị quét. - Theo dõi Reclaim & Đánh giá điểm vào: Trong vòng
reclaimWindownến, nếu giá đóng cửa quay lại bên trong PDL/PDH và vượt qua các bộ lọc hình thái nến (longWickOK,longCloseOK), sự kiệnqualifiedLongReclaim/qualifiedShortReclaimđược ghi nhận. Tùy theoentryMode, bot sẽ đánh giá vào lệnh ngay hoặc chuyển sang trạng tháipendingchờ nến xác nhận. - Kiểm tra bộ lọc & Gửi lệnh: Tín hiệu nền (
longBase/shortBase) đi qua tầng lọcrawLong/rawShort(EMA, Volume, ADX, H1 Bias) và cổng kiểm soátcanTrade(không có vị thế mở, đạt cooldown, chưa chạm giới hạn lệnh ngày, trong khung giờ vào lệnh). Nếu hợp lệ và không xung đột 2 chiều (rawLong and not rawShort), bot gửi lệnh quastrategy.entry. - Quản trị vị thế & Re-arm: Sau khi vào lệnh, hệ thống gắn
strategy.exitvới SL/TP cố định, theo dõiuseTimeExitvàforceCloseBar(14:45). Đồng thời, các setup pending quá hạn hoặc vi phạm cực trị sẽ bị hủy, và trạng tháiSweepReadyđược nạp lại (re-arm) khi giá ổn định bên trong mốc PDH/PDL.
4. Điều kiện vào lệnh Long và Short của CNPS92
4.1. Điều kiện vào lệnh Long
Lệnh Long (enterLong) được kích hoạt khi đồng thời thỏa mãn:
- Phát hiện Sweep đáy ngày trước:
longSweepActiveđang bật (giá đã từng tạolow < pdl - sweepBuffervà nếu bậtrequireFreshSweepthìlow[1] >= pdl - sweepBuffer), chưa quáreclaimWindownến. - Sự kiện Reclaim PDL: Nến đóng cửa trên
pdl + reclaimBuffer, đồng thời đạtlongWickOK(nếu bật lọc râu dưới) vàlongCloseOK(nếu bật lọc vị trí đóng cửa) và không trùngshortReclaimEvent. - Xác nhận tín hiệu (
longBase):- Nếu
entryMode == "Reclaim Candle Close": Thỏa ngay tại nến Reclaim. - Nếu
entryMode == "Next Candle Confirmation": Trong vòngconfirmationWindownến sau Reclaim (cùng ngàydayKey), giá đóng cửa vượtlongTrigger(close > longTrigger), giữ mốcpdl(close > longReferencenếurequireLevelHold = true), không phá đáy quét (low >= longInvalidExtreme - longInvalidBuffernếucancelOnSweepExtremeBreak = true) và là nến tăng nếu bậtrequireDirection.
- Nếu
- Bộ lọc cuối (
rawLong): Thỏa mãnlongTrendOK(EMA dốc lên),volumeOK,adxOKvàlongH1OK(nếu bật), đồng thờinot rawShortvàallowLongđược bật.
4.2. Điều kiện vào lệnh Short
Lệnh Short (enterShort) được kích hoạt khi đồng thời thỏa mãn:
- Phát hiện Sweep đỉnh ngày trước:
shortSweepActiveđang bật (giá đã từng tạohigh > pdh + sweepBuffervà nếu bậtrequireFreshSweepthìhigh[1] <= pdh + sweepBuffer), chưa quáreclaimWindownến. - Sự kiện Reclaim PDH: Nến đóng cửa dưới
pdh - reclaimBuffer, đồng thời đạtshortWickOK(nếu bật lọc râu trên) vàshortCloseOK(nếu bật lọc vị trí đóng cửa) và không trùnglongReclaimEvent. - Xác nhận tín hiệu (
shortBase):- Nếu
entryMode == "Reclaim Candle Close": Thỏa ngay tại nến Reclaim. - Nếu
entryMode == "Next Candle Confirmation": Trong vòngconfirmationWindownến sau Reclaim (cùng ngàydayKey), giá đóng cửa dướishortTrigger(close < shortTrigger), giữ mốcpdh(close < shortReferencenếurequireLevelHold = true), không phá đỉnh quét (high <= shortInvalidExtreme + shortInvalidBuffernếucancelOnSweepExtremeBreak = true) và là nến giảm nếu bậtrequireDirection.
- Nếu
- Bộ lọc cuối (
rawShort): Thỏa mãnshortTrendOK(EMA dốc xuống),volumeOK,adxOKvàshortH1OK(nếu bật), đồng thờinot rawLongvàallowShortđược bật.
4.3. Điều kiện kiểm soát giao dịch chung
Mọi lệnh vào mới đều phải vượt qua cổng canTrade:
- Nến đã đóng cửa & Khung nội nhật:
barstate.isconfirmed,timeframe.isintradayvàlevelsReady(pdh > pdl). - Trạng thái Flat tuyệt đối:
strategy.position_size == 0vàstrategy.opentrades == 0(pyramiding=0). - Giới hạn tần suất:
tradesToday < maximumTradesPerDay(mặc định tối đa 3 lệnh/ngày),longSetupsToday/shortSetupsToday < maximumSetupsPerDirection(mặc định 5 setup/chiều/ngày). - Cooldown & Chống trùng nến:
bar_index - lastExitBar > cooldownBars(mặc định nghỉ ít nhất 1 nến sau khi đóng lệnh) vàlastEntryBar != bar_index. - Khung giờ giao dịch (
Asia/Ho_Chi_Minh): Nếu bậtuseSessionFilter, nến vào lệnh phải cóopenMinutes >= 09:00vàcloseMinutes <= 14:15, đồng thời phải trước giờ đóng cưỡng bức14: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
Bot sử dụng mức cắt lỗ cố định theo điểm số từ tham số stopLossPoints (mặc định 5.0 điểm), quy đổi sang đơn vị tick của hợp đồng VN30F1M:
slTicks = math.max(1, int(math.round(stopLossPoints / syminfo.mintick)))effectiveSL = slTicks * syminfo.mintick- Với vị thế Long, SL đặt tại
strategy.position_avg_price - effectiveSL. Với vị thế Short, SL đặt tạistrategy.position_avg_price + effectiveSL.
5.2. Cơ chế Take Profit và thoát lệnh theo thời gian / cuối phiên
- Take Profit cố định: Quy đổi từ
takeProfitPoints(mặc định15.0điểm, tương ứng tỷ lệ R:R 1:3 so với SL 5.0 điểm) thànhtpTicks = math.max(1, int(math.round(takeProfitPoints / syminfo.mintick))). Bot không sử dụng Break Even hay Trailing Stop trong mã nguồn. - Time Exit (tùy chọn): Khi bật
useTimeExit = true, nếu số nến nắm giữbarsHeld = bar_index - strategy.opentrades.entry_bar_index(0) >= maximumHoldingBars(mặc định20nến) tại nến đóng cửa (và chưa đến giờforceCloseBar), bot gọistrategy.close_all(immediately=true)với comment"Time Exit". - Session Force Close: Tại nến đầu tiên thỏa
openMinutes < 14:45vàcloseMinutes >= 14:45(forceCloseBar), nếu vẫn còn vị thế mở, bot tự động đóng toàn bộ vị thế bằngstrategy.close_all(immediately=true)với comment"Session End".
5.3. Bảng tổng hợp cơ chế bảo vệ vị thế
| Cơ chế thoát lệnh | Tham số điều khiển | Giá trị mặc định | Hành vi thực tế trong code |
|---|---|---|---|
| Stop Loss cố định | stopLossPoints | 5.0 điểm | Quy đổi ra slTicks, gắn cứng qua strategy.exit |
| Take Profit cố định | takeProfitPoints | 15.0 điểm | Quy đổi ra tpTicks, gắn cứng qua strategy.exit |
| Time Exit (tùy chọn) | useTimeExit / maximumHoldingBars | false / 20 nến | Đóng toàn bộ vị thế nếu giữ đủ 20 nến |
| Session Force Close | endHour / endMinute | 14:45 | Bắt buộc đóng toàn bộ vị thế cuối phiên mỗi ngày |
6. Hướng dẫn cài đặt và đọc bảng Diagnostics trên TradingView
Các bước cài đặt
- Mở biểu đồ hợp đồng phái sinh VN30F1M trên TradingView ở khung thời gian nội nhật (ví dụ
5m,15m; nếu bậtuseH1Biasbắt buộc khung thời gian biểu đồ phải nhỏ hơn 1 giờ). - Nhấn mở tab Pine Editor ở thanh công cụ phía dưới màn hình.
- Xóa toàn bộ code mẫu mặc định, sao chép 100% mã nguồn CNPS92 PDH PDL Sweep Delayed Reclaim V2 ở Mục 1 và dán vào Pine Editor.
- Nhấn Save để lưu script, sau đó nhấn Add to chart để đưa chiến lược lên biểu đồ.
- Vào biểu tượng bánh răng (Settings) của chiến lược để bật
Show Diagnosticsnếu muốn theo dõi bảng thống kê trực tiếp trên chart.
Cách đọc bảng chẩn đoán (Diagnostics Table)
Khi bật showDiagnostics = true, bảng 2 cột x 20 dòng ở góc trên bên phải (position.top_right) hiển thị các thông số vận hành theo thời gian thực:
- Dòng 0 – 3 (
CNPS92 V2,PDH,PDL,Levels Ready): Khung thời gian đang chạy, giá trị đỉnh/đáy ngày trước và trạng thái sẵn sàng của mốc tham chiếu (YES/NO). - Dòng 4 – 7 (
Long Sweeps,Short Sweeps,Long Reclaims,Short Reclaims): Tổng số lần phát hiện quét thanh khoản và số lần giá đóng cửa lấy lại mốc PDL/PDH thành công. - Dòng 8 – 11 (
Long Bases,Short Bases,Filtered Long,Filtered Short): Số tín hiệu nền đạt điều kiện vào lệnh (sau khi quaentryMode) và số tín hiệu vượt qua toàn bộ bộ lọc EMA, Volume, ADX, H1 Bias. - Dòng 12 – 15 (
Long Entries,Short Entries,Sweep Timeouts,Confirm Timeouts): Số lệnh Long/Short thực tế đã vào, số lần Sweep hết hạn vì không kịp Reclaim, và số setup Pending bị hủy do quá hạn hoặc phá cực trị. - Dòng 16 – 19 (
Active Long Sweep,Active Short Sweep,Trades Today,Position): Trạng thái đang có Sweep kích hoạt hay không, số lệnh đã giao dịch trong ngày trên tổng hạn mức (tradesToday/maximumTradesPerDay), và vị thế hiện tại (LONG,SHORThoặcFLAT).
7. Cách thiết lập cảnh báo tín hiệu giao dịch (Alert)
Để nhận thông báo tự động về điện thoại, trình duyệt hoặc đẩy lệnh qua Webhook sang hệ thống giao dịch tự động:
- Nhấn vào biểu tượng Alert (Đồng hồ báo thức) trên TradingView.
- Ở mục Condition, chọn đúng tên chiến lược CNPS92 PDH PDL SWEEP DELAYED RECLAIM V2.
- Ở 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}}. - Nếu không muốn nhận thông báo khi chạm SL/TP, bạn có thể tích chọn
Disable SL/TP Alerts(disableExitAlerts = true) trong phần cài đặt bot. - Nhấn Create để kích hoạt cảnh báo.
Bảng thông điệp Alert của CNPS92
| Sự kiện | Nguồn phát trong code | Nội dung thông điệp (alert_message / alert_profit / alert_loss) |
|---|---|---|
| Vào lệnh Long | strategy.entry("Long", ...) | 🟢 VÀO VỊ THẾ LONG (CNPS92) + Giá vào, SL dự kiến, TP dự kiến |
| Vào lệnh Short | strategy.entry("Short", ...) | 🔴 VÀO VỊ THẾ SHORT (CNPS92) + Giá vào, SL dự kiến, TP dự kiến |
| Chốt lời Long / Short | strategy.exit(..., alert_profit=...) | 💰 CHỐT LỜI LONG (TP HIT - CNPS92) / 💰 CHỐT LỜI SHORT (TP HIT - CNPS92) + Giá chốt |
| Cắt lỗ Long / Short | strategy.exit(..., alert_loss=...) | 🛑 CẮT LỖ LONG (SL HIT - CNPS92) / 🛑 CẮT LỖ SHORT (SL HIT - CNPS92) + Giá cắt |
| Thoát theo thời gian | strategy.close_all(..., comment="Time Exit") | ⏱️ ĐÓNG VỊ THẾ QUÁ THỜI GIAN (Time Exit - CNPS92) + Giá đóng |
| Đóng lệnh cuối phiên | strategy.close_all(..., comment="Session End") | ⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End - CNPS92) + Giá đóng |
Kết luận
Bot CNPS92 (PDH PDL Sweep Delayed Reclaim V2) là một hệ thống giao dịch có cấu trúc chặt chẽ cho VN30F1M, nổi bật ở việc tách bạch pha quét thanh khoản và pha Reclaim bằng State Machine, hỗ trợ cả vào lệnh ngay lẫn chờ nến xác nhận, đồng thời kiểm soát rủi ro rõ ràng với SL/TP cố định và tự động đóng vị thế lúc 14:45. Chiến lược đặc biệt phù hợp trong những phiên thị trường có các nhịp rũ bỏ (stop-hunt) quanh biên độ ngày trước rồi quay lại vùng cân bằng, hoặc có thể kết hợp thêm bộ lọc EMA/H1 Bias để bám theo xu hướng chủ đạo.
Bạn có thể tham khảo thêm các hệ thống giao dịch phái sinh khác trên TradingView như Bot CNPS50 - Trend Analysis V2 và Bot CNPS49 - Daily Open.
Thông tin chỉ mang tính tham khảo, không phải khuyến nghị đầu tư. Kết quả kiểm thử quá khứ không đảm bảo lợi nhuận trong tương lai.
Thông tin trong bài chỉ mang tính tham khảo, không phải khuyến nghị mua bán. Giao dịch phái sinh có rủi ro cao do sử dụng đòn bẩy; nhà đầu tư tự chịu trách nhiệm với quyết định của mình.





