Hướng Dẫn Sử Dụng Bot CNPS93 - Previous Day Close Reclaim V1 cho VN30F1M
TradingviewBot CNPS93 tự động giao dịch VN30F1M theo mô hình tái chiếm giá đóng cửa ngày trước (Previous Day Close Reclaim) trên nến xác nhận, tích hợp bộ lọc độ lệch ATR, đệm Reclaim, xác nhận nến kế tiếp và quản trị rủi ro SL/TP cố định.

Mục lục
Trong giao dịch phái sinh VN30F1M, vùng giá đóng cửa của phiên liền trước (Previous Day Close – PDC) luôn là một mốc tâm lý và thanh khoản cực kỳ quan trọng. Tuy nhiên, nếu chỉ giao dịch đơn thuần mỗi khi giá cắt qua PDC, trader rất dễ dính bẫy nhiễu (whipsaw), đặc biệt là các pha quét thanh khoản đầu phiên hoặc các cú phá vỡ giả do khoảng trống giá (gap) qua đêm.
CNPS93 PREVIOUS DAY CLOSE RECLAIM V1 (shorttitle="CNPS93 PDC RECLAIM") là chiến lược giao dịch tự động viết bằng Pine Script v6 trên TradingView, được thiết kế chuyên biệt để giải quyết bài toán trên thông qua mô hình tái chiếm PDC (PDC Reclaim).
Những điểm nổi bật cốt lõi của Bot CNPS93:
- Lọc độ lệch trước khi tái chiếm (Excursion Filter): Yêu cầu giá phải có nhịp đi lệch khỏi PDC tối thiểu theo bội số ATR trước khi quay lại tái chiếm, giúp loại bỏ các pha đi ngang sát mốc PDC.
- Đệm tái chiếm & chống nhiễu Gap (Reclaim Buffer & Overnight Gap Protection): Sử dụng khoảng đệm theo ATR để xác nhận lực cắt qua PDC dứt khoát và tùy chọn bỏ qua nến đầu ngày.
- Hai chế độ vào lệnh linh hoạt: Hỗ trợ vào lệnh ngay khi nến Reclaim đóng cửa (
Reclaim Candle Close) hoặc chờ nến kế tiếp xác nhận (Next Candle Confirmation) với cơ chế hủy setup nếu đánh mất mốc PDC. - Quản trị rủi ro chặt chẽ: Cố định Stop Loss / Take Profit theo điểm, giới hạn số lệnh trong ngày, thời gian nghỉ (cooldown) sau khi thoát lệnh và tự động đóng toàn bộ vị thế trước giờ ATC.
1. CNPS93 Previous Day Close Reclaim V1 là gì?
CNPS93 là hệ thống giao dịch theo hành động giá quanh mốc tham chiếu PDC kết hợp với biến động ATR, được xây dựng trên 4 trụ cột kỹ thuật chính:
- Xác định mốc PDC chuẩn xác (Confirmed Daily OHLC): Lấy dữ liệu
[close[1], high[1], low[1]]từ nến ngày (D) đã hoàn tất, hoàn toàn không sử dụng dữ liệu tương lai (no lookahead repaint). - Đo lường độ lệch giá & tín hiệu Reclaim: Chỉ công nhận tín hiệu khi giá đã từng đi ra ngoài vùng PDC một khoảng
minimumExcursionATR * ATRtrongexcursionLookbacknến gần nhất, sau đó đóng cửa quay trở lại vượt quaPDC ± reclaimBuffer. - Bộ lọc đa tầng tùy chọn: Cho phép kết hợp lọc xu hướng EMA50 (độ dốc và vị trí giá), Relative Volume, ADX/DI và Confirmed H1 EMA Bias (trên khung thời gian nhỏ hơn 1 giờ).
- Kiểm soát phiên & quản trị vị thế: Chỉ hoạt động trên khung intraday trong khung giờ quy định (
09:00 – 14:15), giới hạn số lệnh/ngày, có cơ chế Time Exit tùy chọn và bắt buộc Force Session Close lúc14:45.
Bảng thông số mặc định
| Nhóm thông số | Tên tham số | Giá trị mặc định | Ý nghĩa |
|---|---|---|---|
| 01. Previous Day Close | ATR Length | 14 | Chu kỳ tính chỉ báo ATR |
Require Previous Price Excursion | true | Bật bộ lọc độ lệch giá trước khi Reclaim | |
Excursion Lookback | 8 | Số nến nhìn lại để kiểm tra độ lệch giá | |
Minimum Excursion / ATR | 0.10 | Độ lệch tối thiểu so với PDC tính theo ATR | |
Use PDC Reclaim Buffer | true | Bật khoảng đệm ATR khi vượt lại PDC | |
Reclaim Buffer / ATR | 0.05 | Độ lớn khoảng đệm tái chiếm theo ATR | |
Ignore Overnight Gap Reclaim | true | Bỏ qua nến đầu tiên của ngày giao dịch | |
| 02. Signal Candle | Require Directional Signal Candle | true | Yêu cầu nến tín hiệu cùng hướng (xanh/đỏ) |
Use Minimum Body Ratio | false (0.35) | Lọc tỷ lệ thân nến tối thiểu trên biên độ nến | |
Use Close Location Filter | false (0.60 / 0.40) | Lọc vị trí giá đóng cửa trong biên độ nến | |
| 03. Entry Confirmation | Entry Mode | "Reclaim Candle Close" | Chế độ vào lệnh ngay hoặc chờ nến xác nhận |
Confirmation Window (Bars) | 5 | Số nến tối đa chờ xác nhận ở chế độ Confirm | |
Confirmation Trigger | "Signal Close" | Mức giá kích hoạt xác nhận (PDC, Signal Close, Signal High/Low) | |
Require Confirmation Candle Direction | true | Nến xác nhận phải cùng hướng vị thế | |
Require PDC To Hold | true (0.05 ATR) | Hủy setup nếu giá đóng cửa mất mốc PDC quá đệm | |
Maximum Setups / Direction / Day | 5 | Số setup tối đa mỗi chiều trong ngày | |
| 04. EMA Trend | Use EMA Trend Filter | false (50, slope 3) | Bật bộ lọc xu hướng theo độ dốc EMA50 |
Require Price Above/Below EMA | false | Yêu cầu giá đóng cửa nằm trên/dưới EMA50 | |
| 05. Optional Filters | Use Relative Volume | false (20, 1.0) | Lọc khối lượng tương đối so với SMA20 |
Use Minimum ADX | false (14, 14, 18.0) | Lọc sức mạnh xu hướng ADX tối thiểu | |
Require Directional DI | false | Yêu cầu +DI > -DI (Long) hoặc -DI > +DI (Short) | |
| 06. Confirmed H1 Bias | Use Confirmed H1 EMA Bias | false (50) | Lọc xu hướng khung H1 theo EMA50 đã đóng nến |
| 07. Risk Management | Stop Loss (Points) | 5.0 | Mức cắt lỗ cố định theo điểm |
Take Profit (Points) | 15.0 | Mức chốt lời cố định theo điểm | |
Use Time Exit | false (20 nến) | Bật đóng lệnh nếu giữ quá số nến tối đa | |
| 08. Trade Control | Trade Direction | "Both" | Chiều giao dịch (Long, Short, Both) |
Contracts | 3 | Tham số số hợp đồng khai báo trong Trade Control | |
Maximum Trades Per Day | 3 | Số lệnh vào tối đa mỗi ngày | |
Cooldown After Exit (Bars) | 1 | Số nến nghỉ tối thiểu sau khi đóng lệnh | |
| 09. Trading Session | Timezone | "Asia/Ho_Chi_Minh" | Múi giờ Việt Nam |
Use Entry Session Filter | true (09:00 – 14:15) | Khung giờ cho phép tìm kiếm và vào lệnh | |
Force Close Hour / Minute | 14:45 | Thời điểm đóng toàn bộ vị thế trước ATC | |
| 10. Alerts & 11. Display | Disable SL/TP Alerts | false | Bật/tắt cảnh báo riêng cho SL và TP |
Show Diagnostics | false | Bật/tắt bảng chẩn đoán góc trên bên phải |
Source Code CNPS93 Previous Day Close Reclaim 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="CNPS93 PREVIOUS DAY CLOSE RECLAIM V1", shorttitle="CNPS93 PDC RECLAIM", 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)
// ============================================================================
// CNPS93 - PREVIOUS DAY CLOSE RECLAIM
//
// LONG:
// 1. Price moves below the previous day's close.
// 2. Excursion distance meets the selected threshold.
// 3. A completed candle closes back above PDC.
// 4. Enter immediately or wait for confirmation.
//
// SHORT:
// 1. Price moves above the previous day's close.
// 2. A completed candle closes back below PDC.
// 3. Enter immediately or wait for confirmation.
//
// PDC is read from the previous COMPLETED daily candle.
// No future daily prices are used.
//
// Trading logic:
// - Confirmed candles only
// - Fixed SL / TP
// - Daily trade limit
// - Cooldown after exits
// - Optional EMA / ADX / Volume / H1
// - Optional confirmation setup
// - Diagnostics
// ============================================================================
// ============================================================================
// 01. PREVIOUS DAY CLOSE
// ============================================================================
gPDC = "01. Previous Day Close"
atrLength = input.int(14, "ATR Length", minval=1, group=gPDC)
useExcursionFilter = input.bool(true, "Require Previous Price Excursion", group=gPDC)
excursionLookback = input.int(8, "Excursion Lookback", minval=1, maxval=100, group=gPDC)
minimumExcursionATR = input.float(0.10, "Minimum Excursion / ATR", minval=0.0, step=0.05, group=gPDC)
useReclaimBuffer = input.bool(true, "Use PDC Reclaim Buffer", group=gPDC)
reclaimBufferATR = input.float(0.05, "Reclaim Buffer / ATR", minval=0.0, step=0.05, group=gPDC)
ignoreFirstBarOfDay = input.bool(true, "Ignore Overnight Gap Reclaim", group=gPDC)
// ============================================================================
// 02. SIGNAL CANDLE
// ============================================================================
gCandle = "02. Signal Candle"
requireCandleDirection = input.bool(true, "Require Directional Signal Candle", group=gCandle)
useBodyFilter = input.bool(false, "Use Minimum Body Ratio", group=gCandle)
minimumBodyRatio = input.float(0.35, "Minimum Body / Range", minval=0.0, maxval=1.0, step=0.05, group=gCandle)
useCloseLocation = input.bool(false, "Use Close Location Filter", group=gCandle)
minimumLongClosePosition = input.float(0.60, "Minimum LONG Close Position", minval=0.0, maxval=1.0, step=0.05, group=gCandle)
maximumShortClosePosition = input.float(0.40, "Maximum SHORT Close Position", minval=0.0, maxval=1.0, step=0.05, group=gCandle)
// ============================================================================
// 03. 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 (Bars)", minval=1, maxval=50, group=gConfirm)
confirmationLevel = input.string("Signal Close", "Confirmation Trigger", options=["PDC", "Signal Close", "Signal High/Low"], group=gConfirm)
requireConfirmCandle = input.bool(true, "Require Confirmation Candle Direction", group=gConfirm)
requirePDCHold = input.bool(true, "Require PDC To Hold", group=gConfirm)
invalidationATR = input.float(0.05, "Invalidation Buffer / ATR", minval=0.0, step=0.05, group=gConfirm)
maxSetupsPerDirection = input.int(5, "Maximum Setups / Direction / Day", minval=1, maxval=30, group=gConfirm)
// ============================================================================
// 04. EMA 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. VOLUME / ADX
// ============================================================================
gFilters = "05. Optional Filters"
useVolumeFilter = input.bool(false, "Use Relative Volume", 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 Minimum ADX", group=gFilters)
diLength = input.int(14, "DI Length", minval=2, group=gFilters)
adxSmoothing = input.int(14, "ADX Smoothing", minval=2, group=gFilters)
minimumADX = input.float(18.0, "Minimum ADX", minval=1.0, step=1.0, group=gFilters)
requireDIDirection = input.bool(false, "Require Directional DI", group=gFilters)
// ============================================================================
// 06. CONFIRMED H1 BIAS
// ============================================================================
gH1 = "06. Confirmed 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 Time Exit", 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. 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"
showPDC = input.bool(true, "Show Previous Day Close", group=gDisplay)
showPDH_PDL = input.bool(false, "Show Previous Day High/Low", group=gDisplay)
showEMA = input.bool(true, "Show EMA", group=gDisplay)
showSetupMarkers = input.bool(false, "Show Reclaim Setup Dots", group=gDisplay)
showPendingLevels = input.bool(true, "Show Pending Confirmation", 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]
bool sameDayAsPreviousBar = not newDay
var int tradesToday = 0
var int longSetupsToday = 0
var int shortSetupsToday = 0
if newDay
tradesToday := 0
longSetupsToday := 0
shortSetupsToday := 0
// ============================================================================
// 14. CONFIRMED PREVIOUS DAILY OHLC
// ============================================================================
//
// [1] is evaluated on the DAILY timeframe.
// Only completed daily candles are used.
//
// Continuous futures data may use adjusted prices.
// Verify PDC against the intended contract series.
// ============================================================================
[pdc, pdh, pdl] = request.security(syminfo.tickerid, "D", [close[1], high[1], low[1]], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
bool pdcReady = intradayOK and not na(pdc)
// ============================================================================
// 15. INDICATORS
// ============================================================================
float atr = ta.atr(atrLength)
float ema = ta.ema(close, emaLength)
float previousAverageVolume = ta.sma(volume[1], volumeLength)
float relativeVolume = (not na(volume) and not na(previousAverageVolume) and previousAverageVolume > 0 ? volume / previousAverageVolume : na)
[diPlus, diMinus, adx] = ta.dmi(diLength, adxSmoothing)
// ============================================================================
// 16. PREVIOUS EXCURSION
// ============================================================================
float previousLowestLow = ta.lowest(low[1], excursionLookback)
float previousHighestHigh = ta.highest(high[1], excursionLookback)
float excursionDistance = (not na(atr) ? atr * minimumExcursionATR : 0.0)
bool longExcursionOK = (not useExcursionFilter or (not na(previousLowestLow) and previousLowestLow < pdc - excursionDistance))
bool shortExcursionOK = (not useExcursionFilter or (not na(previousHighestHigh) and previousHighestHigh > pdc + excursionDistance))
// ============================================================================
// 17. RECLAIM EVENTS
// ============================================================================
//
// A signal is a crossing of the daily reference.
//
// Optional gap protection requires the previous
// intraday bar to belong to the same trading day.
//
// ============================================================================
float reclaimBuffer = (useReclaimBuffer and not na(atr) ? atr * reclaimBufferATR : 0.0)
bool dayBoundaryOK = (not ignoreFirstBarOfDay or sameDayAsPreviousBar)
bool bullishCross = (barstate.isconfirmed and pdcReady and dayBoundaryOK and not na(close[1]) and close[1] <= pdc and close > pdc + reclaimBuffer)
bool bearishCross = (barstate.isconfirmed and pdcReady and dayBoundaryOK and not na(close[1]) and close[1] >= pdc and close < pdc - reclaimBuffer)
// ============================================================================
// 18. CANDLE ANATOMY
// ============================================================================
float candleRange = high - low
float candleBody = math.abs(close - open)
float bodyRatio = (candleRange > 0 ? candleBody / candleRange : 0.0)
float closePosition = (candleRange > 0 ? (close - low) / candleRange : 0.5)
bool bullishCandle = close > open
bool bearishCandle = close < open
bool longCandleOK = (not requireCandleDirection or bullishCandle)
bool shortCandleOK = (not requireCandleDirection or bearishCandle)
bool bodyOK = (not useBodyFilter or bodyRatio >= minimumBodyRatio)
bool longCloseOK = (not useCloseLocation or closePosition >= minimumLongClosePosition)
bool shortCloseOK = (not useCloseLocation or closePosition <= maximumShortClosePosition)
// ============================================================================
// 19. RECLAIM SETUPS
// ============================================================================
bool bullishSetup = (bullishCross and longExcursionOK and longCandleOK and bodyOK and longCloseOK)
bool bearishSetup = (bearishCross and shortExcursionOK and shortCandleOK and bodyOK and shortCloseOK)
// ============================================================================
// 20. EMA TREND 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)))
// ============================================================================
// 21. VOLUME / ADX / DI
// ============================================================================
bool volumeOK = (not useVolumeFilter or (not na(relativeVolume) and relativeVolume >= minimumVolumeFactor))
bool adxOK = (not useADXFilter or (not na(adx) and adx >= minimumADX))
bool longDIOK = (not requireDIDirection or (not na(diPlus) and not na(diMinus) and diPlus > diMinus))
bool shortDIOK = (not requireDIDirection or (not na(diPlus) and not na(diMinus) and diMinus > diPlus))
// ============================================================================
// 22. CONFIRMED H1 BIAS
// ============================================================================
[h1EMA, h1Close] = request.security(syminfo.tickerid, "60", [ta.ema(close, h1EMALength)[1], close[1]], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
bool validH1Chart = (timeframe.isintraday and timeframe.in_seconds() < 3600)
bool longH1OK = (not useH1Bias or (validH1Chart and not na(h1EMA) and not na(h1Close) and h1Close > h1EMA))
bool shortH1OK = (not useH1Bias or (validH1Chart and not na(h1EMA) and not na(h1Close) and h1Close < h1EMA))
// ============================================================================
// 23. POSITION / COOLDOWN
// ============================================================================
bool flat = strategy.position_size == 0
bool inLong = strategy.position_size > 0
bool inShort = strategy.position_size < 0
var int lastExitBar = na
var int lastEntryBar = na
bool newClosedTrade = (strategy.closedtrades > nz(strategy.closedtrades[1], 0))
if newClosedTrade
lastExitBar := bar_index
bool cooldownOK = (na(lastExitBar) or bar_index - lastExitBar > cooldownBars)
bool freshEntryBar = (na(lastEntryBar) or lastEntryBar != bar_index)
// ============================================================================
// 24. SETUP STORAGE
// ============================================================================
var bool pendingLong = false
var bool pendingShort = false
var int longSetupBar = na
var int shortSetupBar = na
var int longSetupDay = na
var int shortSetupDay = na
var float longSignalHigh = na
var float longSignalClose = na
var float longReference = na
var float longSetupATR = na
var float shortSignalLow = na
var float shortSignalClose = na
var float shortReference = na
var float shortSetupATR = na
var int bullCrossCount = 0
var int bearCrossCount = 0
var int bullSetupCount = 0
var int bearSetupCount = 0
var int longBaseCount = 0
var int shortBaseCount = 0
var int filteredLongCount = 0
var int filteredShortCount = 0
var int expiredLongCount = 0
var int expiredShortCount = 0
var int blockedLongCount = 0
var int blockedShortCount = 0
var int longEntryCount = 0
var int shortEntryCount = 0
bool confirmationMode = (entryMode == "Next Candle Confirmation")
// ============================================================================
// 25. CONFIRMATION WINDOWS
// ============================================================================
bool longWindowOK = (pendingLong and not na(longSetupBar) and longSetupDay == dayKey and bar_index > longSetupBar and bar_index - longSetupBar <= confirmationWindow)
bool shortWindowOK = (pendingShort and not na(shortSetupBar) and shortSetupDay == dayKey and bar_index > shortSetupBar and bar_index - shortSetupBar <= confirmationWindow)
// ============================================================================
// 26. CONFIRMATION TRIGGERS
// ============================================================================
float longTrigger = (confirmationLevel == "Signal High/Low" ? longSignalHigh : confirmationLevel == "Signal Close" ? longSignalClose : longReference)
float shortTrigger = (confirmationLevel == "Signal High/Low" ? shortSignalLow : confirmationLevel == "Signal Close" ? shortSignalClose : shortReference)
float longInvalidBuffer = (not na(longSetupATR) ? longSetupATR * invalidationATR : 0.0)
float shortInvalidBuffer = (not na(shortSetupATR) ? shortSetupATR * invalidationATR : 0.0)
bool longHoldOK = (not requirePDCHold or (not na(longReference) and close > longReference - longInvalidBuffer))
bool shortHoldOK = (not requirePDCHold or (not na(shortReference) and close < shortReference + shortInvalidBuffer))
bool longConfirmCandleOK = (not requireConfirmCandle or bullishCandle)
bool shortConfirmCandleOK = (not requireConfirmCandle or bearishCandle)
bool confirmedLong = (barstate.isconfirmed and longWindowOK and longHoldOK and longConfirmCandleOK and not na(longTrigger) and close > longTrigger)
bool confirmedShort = (barstate.isconfirmed and shortWindowOK and shortHoldOK and shortConfirmCandleOK and not na(shortTrigger) and close < shortTrigger)
// ============================================================================
// 27. ENTRY BASE SIGNALS
// ============================================================================
bool longBase = (confirmationMode ? confirmedLong : bullishSetup)
bool shortBase = (confirmationMode ? confirmedShort : bearishSetup)
// ============================================================================
// 28. FINAL FILTERED SIGNALS
// ============================================================================
bool rawLong = (longBase and longTrendOK and volumeOK and adxOK and longDIOK and longH1OK)
bool rawShort = (shortBase and shortTrendOK and volumeOK and adxOK and shortDIOK and shortH1OK)
// ============================================================================
// 29. ENTRY CONTROL
// ============================================================================
bool canTrade = (barstate.isconfirmed and intradayOK and pdcReady 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 and (confirmationMode or longSetupsToday < maxSetupsPerDirection))
bool enterShort = (canTrade and allowShort and rawShort and not rawLong and (confirmationMode or shortSetupsToday < maxSetupsPerDirection))
// ============================================================================
// 30. 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
// ============================================================================
// 31. LONG ENTRY
// ============================================================================
if enterLong
strategy.entry("Long", strategy.long, comment="PDC RECLAIM LONG", alert_message="🟢 VÀO VỊ THẾ LONG (CNPS93)\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
// ============================================================================
// 32. SHORT ENTRY
// ============================================================================
if enterShort
strategy.entry("Short", strategy.short, comment="PDC RECLAIM SHORT", alert_message="🔴 VÀO VỊ THẾ SHORT (CNPS93)\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
// ============================================================================
// 33. SETUP STATE UPDATE
// ============================================================================
//
// Evaluate pending signals first.
// Then expire or register new setups.
// This prevents same-candle confirmation
// in confirmation mode.
//
// ============================================================================
if barstate.isconfirmed
if bullishCross
bullCrossCount += 1
if bearishCross
bearCrossCount += 1
if bullishSetup
bullSetupCount += 1
if bearishSetup
bearSetupCount += 1
if longBase
longBaseCount += 1
if shortBase
shortBaseCount += 1
if rawLong
filteredLongCount += 1
if rawShort
filteredShortCount += 1
if rawLong and not enterLong
blockedLongCount += 1
if rawShort and not enterShort
blockedShortCount += 1
// --------------------------------------------------------
// RESET PREVIOUS-DAY PENDING SIGNALS
// --------------------------------------------------------
if newDay
pendingLong := false
pendingShort := false
longSetupBar := na
shortSetupBar := na
longSetupDay := na
shortSetupDay := na
longSignalHigh := na
longSignalClose := na
longReference := na
longSetupATR := na
shortSignalLow := na
shortSignalClose := na
shortReference := na
shortSetupATR := na
// --------------------------------------------------------
// LONG EXPIRATION
// --------------------------------------------------------
if pendingLong and not na(longSetupBar)
bool longExpired = (longSetupDay != dayKey or bar_index - longSetupBar > confirmationWindow)
bool longInvalid = (requirePDCHold and not na(longReference) and close <= longReference - longInvalidBuffer)
if longExpired or longInvalid or confirmedLong
if longExpired or longInvalid
expiredLongCount += 1
pendingLong := false
longSetupBar := na
// --------------------------------------------------------
// SHORT EXPIRATION
// --------------------------------------------------------
if pendingShort and not na(shortSetupBar)
bool shortExpired = (shortSetupDay != dayKey or bar_index - shortSetupBar > confirmationWindow)
bool shortInvalid = (requirePDCHold and not na(shortReference) and close >= shortReference + shortInvalidBuffer)
if shortExpired or shortInvalid or confirmedShort
if shortExpired or shortInvalid
expiredShortCount += 1
pendingShort := false
shortSetupBar := na
// --------------------------------------------------------
// REGISTER NEW SETUPS
// --------------------------------------------------------
bool canRegister = (confirmationMode and intradayOK and pdcReady and flat and entrySessionOK and beforeForceClose and tradesToday < maximumTradesPerDay and not enterLong and not enterShort)
if (canRegister and allowLong and bullishSetup and not bearishSetup and not pendingLong and not pendingShort and longSetupsToday < maxSetupsPerDirection)
pendingLong := true
longSetupBar := bar_index
longSetupDay := dayKey
longSignalHigh := high
longSignalClose := close
longReference := pdc
longSetupATR := atr
longSetupsToday += 1
if (canRegister and allowShort and bearishSetup and not bullishSetup and not pendingShort and not pendingLong and shortSetupsToday < maxSetupsPerDirection)
pendingShort := true
shortSetupBar := bar_index
shortSetupDay := dayKey
shortSignalLow := low
shortSignalClose := close
shortReference := pdc
shortSetupATR := atr
shortSetupsToday += 1
// --------------------------------------------------------
// COUNT IMMEDIATE-MODE SETUPS
// --------------------------------------------------------
if not confirmationMode
if enterLong
longSetupsToday += 1
if enterShort
shortSetupsToday += 1
// ============================================================================
// 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 (TP HIT - CNPS93)\n🎯 Giá chốt: " + str.tostring(close, format.mintick), alert_loss="🛑 CẮT LỖ LONG (SL HIT - CNPS93)\n🎯 Giá cắt: " + str.tostring(close, 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 (TP HIT - CNPS93)\n🎯 Giá chốt: " + str.tostring(close, format.mintick), alert_loss="🛑 CẮT LỖ SHORT (SL HIT - CNPS93)\n🎯 Giá cắt: " + str.tostring(close, 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Ế QUÁ THỜI GIAN (Time Exit - CNPS93)\n🎯 Giá đóng: " + str.tostring(close, format.mintick))
// ============================================================================
// 37. FORCE SESSION 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 - CNPS93)\n🎯 Giá đóng: " + str.tostring(close, format.mintick))
// ============================================================================
// 38. REFERENCE LEVEL PLOTS
// ============================================================================
plot(showPDC ? pdc : na, title="Previous Day Close", color=color.aqua, linewidth=2, style=plot.style_stepline)
plot(showPDH_PDL ? pdh : na, title="Previous Day High", color=color.red, linewidth=1, style=plot.style_stepline)
plot(showPDH_PDL ? pdl : na, title="Previous Day Low", color=color.green, linewidth=1, style=plot.style_stepline)
// ============================================================================
// 39. EMA PLOT
// ============================================================================
plot(showEMA ? ema : na, title="EMA50", color=color.orange, linewidth=2)
// ============================================================================
// 40. SETUP MARKERS
// ============================================================================
plotshape(showSetupMarkers and bullishSetup, title="Bullish PDC Reclaim", style=shape.circle, location=location.belowbar, color=color.aqua, size=size.tiny, text="PDC")
plotshape(showSetupMarkers and bearishSetup, title="Bearish PDC Reclaim", style=shape.circle, location=location.abovebar, color=color.orange, size=size.tiny, text="PDC")
// ============================================================================
// 41. 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)
// ============================================================================
// 42. ENTRY MARKERS
// ============================================================================
plotshape(showEntryMarkers and enterLong, title="CNPS93 LONG", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, text="LONG", textcolor=color.white)
plotshape(showEntryMarkers and enterShort, title="CNPS93 SHORT", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small, text="SHORT", textcolor=color.white)
// ============================================================================
// 43. 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)
// ============================================================================
// 44. DATA WINDOW
// ============================================================================
plot(atr, title="ATR", color=color.gray, display=display.data_window)
plot(relativeVolume, title="Relative Volume", color=color.blue, display=display.data_window)
plot(bodyRatio, title="Candle Body Ratio", color=color.orange, display=display.data_window)
plot(adx, title="ADX", color=color.purple, display=display.data_window)
plot(longTrigger, title="Stored Long Trigger", color=color.green, display=display.data_window)
plot(shortTrigger, title="Stored Short Trigger", color=color.red, display=display.data_window)
// ============================================================================
// 45. DIAGNOSTICS
// ============================================================================
var table diagnostics = table.new(position.top_right, 2, 21, border_width=1)
if barstate.islast
if showDiagnostics
table.cell(diagnostics, 0, 0, "CNPS93 V1")
table.cell(diagnostics, 1, 0, timeframe.period)
table.cell(diagnostics, 0, 1, "PDC")
table.cell(diagnostics, 1, 1, str.tostring(pdc, "#.##"))
table.cell(diagnostics, 0, 2, "PDC Ready")
table.cell(diagnostics, 1, 2, pdcReady ? "YES" : "NO")
table.cell(diagnostics, 0, 3, "Bull Crosses")
table.cell(diagnostics, 1, 3, str.tostring(bullCrossCount))
table.cell(diagnostics, 0, 4, "Bear Crosses")
table.cell(diagnostics, 1, 4, str.tostring(bearCrossCount))
table.cell(diagnostics, 0, 5, "Bull Setups")
table.cell(diagnostics, 1, 5, str.tostring(bullSetupCount))
table.cell(diagnostics, 0, 6, "Bear Setups")
table.cell(diagnostics, 1, 6, str.tostring(bearSetupCount))
table.cell(diagnostics, 0, 7, "Long Bases")
table.cell(diagnostics, 1, 7, str.tostring(longBaseCount))
table.cell(diagnostics, 0, 8, "Short Bases")
table.cell(diagnostics, 1, 8, str.tostring(shortBaseCount))
table.cell(diagnostics, 0, 9, "Filtered Long")
table.cell(diagnostics, 1, 9, str.tostring(filteredLongCount))
table.cell(diagnostics, 0, 10, "Filtered Short")
table.cell(diagnostics, 1, 10, str.tostring(filteredShortCount))
table.cell(diagnostics, 0, 11, "Blocked Long")
table.cell(diagnostics, 1, 11, str.tostring(blockedLongCount))
table.cell(diagnostics, 0, 12, "Blocked Short")
table.cell(diagnostics, 1, 12, str.tostring(blockedShortCount))
table.cell(diagnostics, 0, 13, "Long Entries")
table.cell(diagnostics, 1, 13, str.tostring(longEntryCount))
table.cell(diagnostics, 0, 14, "Short Entries")
table.cell(diagnostics, 1, 14, str.tostring(shortEntryCount))
table.cell(diagnostics, 0, 15, "Expired Long")
table.cell(diagnostics, 1, 15, str.tostring(expiredLongCount))
table.cell(diagnostics, 0, 16, "Expired Short")
table.cell(diagnostics, 1, 16, str.tostring(expiredShortCount))
table.cell(diagnostics, 0, 17, "Pending Long")
table.cell(diagnostics, 1, 17, pendingLong ? "YES" : "NO")
table.cell(diagnostics, 0, 18, "Pending Short")
table.cell(diagnostics, 1, 18, pendingShort ? "YES" : "NO")
table.cell(diagnostics, 0, 19, "Trades Today")
table.cell(diagnostics, 1, 19, str.tostring(tradesToday) + "/" + str.tostring(maximumTradesPerDay))
table.cell(diagnostics, 0, 20, "Position")
table.cell(diagnostics, 1, 20, inLong ? "LONG" : inShort ? "SHORT" : "FLAT")
else
table.clear(diagnostics, 0, 0, 1, 20)
2. Những khái niệm kỹ thuật cốt lõi trong CNPS93
2.1. Mốc PDC và Bộ lọc độ lệch Excursion (Excursion Filter)
Chiến lược đọc giá đóng cửa (pdc), đỉnh (pdh) và đáy (pdl) từ nến ngày hoàn tất gần nhất thông qua hàm:
request.security(syminfo.tickerid, "D", [close[1], high[1], low[1]], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
Để tránh tình trạng giá chỉ dao động lình xình quanh đường PDC gây tín hiệu giả, CNPS93 tính độ lệch cực trị trong excursionLookback = 8 nến trước đó:
previousLowestLow = ta.lowest(low[1], 8)vàpreviousHighestHigh = ta.highest(high[1], 8)- Khoảng cách tối thiểu:
excursionDistance = atr * minimumExcursionATR(mặc định0.10 * ATR(14)). - Chiều Long đòi hỏi
previousLowestLow < pdc - excursionDistance; chiều Short đòi hỏipreviousHighestHigh > pdc + excursionDistance.
2.2. Khoảng đệm Reclaim Buffer & Giải phẫu nến tín hiệu (Candle Anatomy)
Khi giá quay lại cắt qua PDC trên nến đã đóng (barstate.isconfirmed), bot áp dụng khoảng đệm reclaimBuffer = atr * 0.05 (khi useReclaimBuffer = true) để chắc chắn giá đã thoát khỏi vùng nhiễu:
- Bullish Cross:
close[1] <= pdcvàclose > pdc + reclaimBuffer. - Bearish Cross:
close[1] >= pdcvàclose < pdc - reclaimBuffer.
Bên cạnh đó, nến tín hiệu còn được kiểm tra cấu trúc qua các chỉ số:
- Hướng nến (
requireCandleDirection): Nến xanh (close > open) cho Long và nến đỏ (close < open) cho Short. - Tỷ lệ thân nến (
bodyRatio):math.abs(close - open) / (high - low) >= 0.35(tùy chọn). - Vị trí đóng cửa (
closePosition):(close - low) / (high - low)đạt tối thiểu0.60với Long hoặc tối đa0.40với Short (tùy chọn).
2.3. Hai chế độ vào lệnh & Bộ lọc đa khung/chỉ báo
Bot hỗ trợ hai cơ chế vào lệnh qua tham số entryMode:
- Reclaim Candle Close (Mặc định): Vào lệnh trực tiếp ngay khi nến Reclaim đóng cửa thỏa mãn toàn bộ bộ lọc.
- Next Candle Confirmation: Lưu setup vào trạng thái chờ (
pendingLong/pendingShort) trong tối đaconfirmationWindow = 5nến cùng ngày. Lệnh chỉ kích hoạt khi một nến sau đóng cửa vượt qua mứclongTrigger/shortTrigger(chọn từPDC,Signal ClosehoặcSignal High/Low), đồng thời giá không vi phạm vùngPDC ∓ invalidationATR * ATR.
Ngoài ra, người dùng có thể bật thêm các bộ lọc bổ trợ:
- EMA Trend Filter: Kiểm tra độ dốc
ema > ema[3](hoặc<cho Short) vớiEMA(50)và tùy chọn vị trí giá so với EMA. - Relative Volume:
volume / ta.sma(volume[1], 20) >= 1.0. - ADX / DI:
adx >= 18.0(chu kỳ 14) và tùy chọn chiều+DI / -DI. - Confirmed H1 Bias: Dùng
close[1]vàEMA(50)[1]trên khung60phút (chỉ hiệu lực khi chạy trên biểu đồ nhỏ hơn H1).
3. Nguyên lý hoạt động của CNPS93
Quy trình vận hành của CNPS93 trên mỗi nến hoàn tất (barstate.isconfirmed) diễn ra theo 5 bước tuần tự:
- Khởi tạo phiên & đếm bộ đếm ngày: Khi phát hiện
newDaytheo múi giờAsia/Ho_Chi_Minh, bot đặt lạitradesToday,longSetupsToday,shortSetupsTodayvề0và xóa các setup chờ từ phiên trước. - Phát hiện sự kiện Reclaim (
bullishSetup/bearishSetup): Kiểm trapdcReady, điều kiện không phải nến đầu ngày (dayBoundaryOK), nến cắt quaPDC ± reclaimBuffer, thỏa mãnExcursionvà hình thái nến. - Xử lý trạng thái Setup & Xác nhận: Nếu ở chế độ
Next Candle Confirmation, bot cập nhật hoặc hủy các setup quá hạn (> 5nến) hoặc mất mốc PDC (longInvalid/shortInvalid), sau đó mới đăng ký setup mới nếu đủ điều kiện. - Lọc xu hướng & kiểm soát vào lệnh (
canTrade): Kiểm trarawLong/rawShortqua các bộ lọc EMA, Volume, ADX, H1 Bias, đồng thời xác minhflat,tradesToday < 3,cooldownOK,entrySessionOK(09:00 – 14:15) vàbeforeForceClose(< 14:45). - Gửi lệnh & Quản trị thoát lệnh: Thực thi
strategy.entry, gắn lệnh chờstrategy.exitvới SL/TP cố định, theo dõiTime Exit(nếu bật) và đóng toàn bộ vị thế tại nến14:45.
4. Điều kiện vào lệnh Long và Short của CNPS93
4.1. Điều kiện vào lệnh Long
Bot thực thi enterLong khi tất cả các điều kiện sau cùng thỏa mãn:
canTradehợp lệ vàallowLongđược bật ("Long"hoặc"Both").- Tín hiệu nền (
longBase):- Nếu ở chế độ
Reclaim Candle Close:bullishSetupxảy ra (close[1] <= pdcvàclose > pdc + reclaimBuffer, giá đáy 8 nến trước< pdc - 0.10 * ATR, nến tăngclose > open, thỏa lọc body/close location nếu bật) vàlongSetupsToday < maxSetupsPerDirection. - Nếu ở chế độ
Next Candle Confirmation: CópendingLonghợp lệ trong cửa sổ 5 nến cùng ngày, giá giữ trênpdc - 0.05 * ATR, nến xác nhận là nến tăng (nếu bật) vàclose > longTrigger.
- Nếu ở chế độ
- Thỏa các bộ lọc tùy chọn (nếu bật):
longTrendOK(EMA dốc lên),volumeOK,adxOK,longDIOK(+DI > -DI),longH1OK(H1 đóng cửa trên EMA50 H1). - Không đồng thời xuất hiện
rawShorttrên cùng nến.
4.2. Điều kiện vào lệnh Short
Bot thực thi enterShort khi tất cả các điều kiện sau cùng thỏa mãn:
canTradehợp lệ vàallowShortđược bật ("Short"hoặc"Both").- Tín hiệu nền (
shortBase):- Nếu ở chế độ
Reclaim Candle Close:bearishSetupxảy ra (close[1] >= pdcvàclose < pdc - reclaimBuffer, giá đỉnh 8 nến trước> pdc + 0.10 * ATR, nến giảmclose < open, thỏa lọc body/close location nếu bật) vàshortSetupsToday < maxSetupsPerDirection. - Nếu ở chế độ
Next Candle Confirmation: CópendingShorthợp lệ trong cửa sổ 5 nến cùng ngày, giá giữ dướipdc + 0.05 * ATR, nến xác nhận là nến giảm (nếu bật) vàclose < shortTrigger.
- Nếu ở chế độ
- Thỏa các bộ lọc tùy chọn (nếu bật):
shortTrendOK(EMA dốc xuống),volumeOK,adxOK,shortDIOK(-DI > +DI),shortH1OK(H1 đóng cửa dưới EMA50 H1). - Không đồng thời xuất hiện
rawLongtrên cùng nến.
4.3. Điều kiện kiểm soát giao dịch chung
Mọi lệnh vào mới đều bị ràng buộc bởi biến canTrade:
- Chỉ chạy trên khung intraday (
timeframe.isintraday) khi dữ liệupdcđã sẵn sàng và nến đã đóng (barstate.isconfirmed). - Trạng thái tài khoản đang Flat (
strategy.position_size == 0vàstrategy.opentrades == 0). - Số lệnh trong ngày chưa vượt quá giới hạn (
tradesToday < 3). - Đã qua thời gian nghỉ sau lệnh đóng trước đó:
bar_index - lastExitBar > cooldownBars(mặc địnhcooldownBars = 1) và không trùng nến vào lệnh trước (freshEntryBar). - Nằm trong khung giờ vào lệnh (
09:00đến14:15) và trước giờ đóng cưỡng bức (closeMinutes < 14:45).
5. Quản trị Stop Loss, Take Profit và Thoát lệnh
5.1. Cơ chế Stop Loss và quy đổi Tick
CNPS93 sử dụng mức cắt lỗ cố định theo điểm qua tham số stopLossPoints = 5.0 và quy đổi chính xác 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 Long:
SL = strategy.position_avg_price - effectiveSL; với Short:SL = strategy.position_avg_price + effectiveSL.
5.2. Cơ chế Take Profit, Time Exit và Force Session Close
- Take Profit cố định: Mặc định
takeProfitPoints = 15.0(tỷ lệ Risk:Reward1:3), quy đổi tương tự sangtpTicks = math.max(1, int(math.round(takeProfitPoints / syminfo.mintick))). Bot không sử dụng Break Even hay Trailing Stop. - Time Exit (tùy chọn): Khi
useTimeExit = true(mặc địnhfalse), nếu số nến giữ lệnhbarsHeld >= maximumHoldingBars(mặc định20nến) tại thời điểm nến đóng và chưa đếnforceCloseBar, bot gọistrategy.close_all(immediately=true, comment="Time Exit"). - Force Session Close: Tại nến chạm hoặc vượt mốc
14:45(openMinutes < 885 and closeMinutes >= 885) khi nến đóng, nếu còn vị thế mở, bot tự động đóng toàn bộ vớicomment="Session End"để tránh giữ lệnh qua đêm.
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 | Giá trị mặc định | Hành động của Bot |
|---|---|---|---|
| Stop Loss (SL) | Giá chạm mức lỗ cố định | 5.0 điểm (slTicks) | Đóng vị thế qua strategy.exit (SL Long / SL Short) |
| Take Profit (TP) | Giá chạm mức lời cố định | 15.0 điểm (tpTicks) | Chốt lời qua strategy.exit (TP Long / TP Short) |
| Time Exit | Giữ lệnh đủ số nến tối đa (khi bật) | false (20 nến) | Đóng toàn bộ vị thế (Time Exit) |
| Force Session Close | Nến đóng qua mốc 14:45 (giờ VN) | Luôn bật (14:45) | Đóng toàn bộ vị thế cuối ngày (Session End) |
6. Hướng dẫn cài đặt và đọc bảng Diagnostics trên TradingView
Các bước cài đặt
- Mở biểu đồ VN30F1M (nên dùng khung thời gian intraday như
M5hoặcM15) trên TradingView. - Mở tab Pine Editor ở phía dưới màn hình, xóa code mặc định và dán toàn bộ mã nguồn CNPS93 từ Mục 1 vào.
- Nhấn Save (Lưu) và chọn Add to chart (Thêm vào biểu đồ).
- Mở phần Settings (Cài đặt) của chiến lược để điều chỉnh các thông số như
Entry Mode,Stop Loss,Take Profit, hoặc bậtShow Diagnosticskhi cần theo dõi chi tiết.
Cách đọc bảng chẩn đoán (Diagnostics Table)
Khi bật Show Diagnostics = true, bảng thống kê 21 dòng sẽ hiển thị ở góc trên bên phải biểu đồ (position.top_right):
- CNPS93 V1 / PDC / PDC Ready: Cho biết khung thời gian đang chạy, giá đóng cửa ngày trước (
PDC) và trạng thái sẵn sàng của dữ liệu (YES/NO). - Bull Crosses / Bear Crosses: Tổng số lần giá cắt lên/xuống qua
PDC ± reclaimBuffer. - Bull Setups / Bear Setups: Số lần thỏa mãn đầy đủ điều kiện Reclaim (gồm Excursion và cấu trúc nến).
- Long Bases / Short Bases: Số tín hiệu cơ sở đạt chuẩn theo
Entry Modeđã chọn. - Filtered Long / Filtered Short: Số tín hiệu vượt qua toàn bộ bộ lọc EMA, Volume, ADX, H1 Bias.
- Blocked Long / Blocked Short: Số tín hiệu hợp lệ nhưng bị chặn do vướng điều kiện kiểm soát (
canTradenhư hết lượt/ngày, đang có lệnh, ngoài giờ, cooldown). - Long Entries / Short Entries: Tổng số lệnh Long/Short đã thực sự khớp.
- Expired Long / Expired Short: Số setup ở chế độ Confirmation bị quá hạn hoặc mất mốc PDC.
- Pending Long / Pending Short: Trạng thái đang chờ nến xác nhận (
YES/NO). - Trades Today / Position: Số lệnh đã giao dịch trong ngày trên giới hạn tối đa (
x/3) và vị thế hiện tại (LONG,SHORT,FLAT).
7. Cách thiết lập cảnh báo tín hiệu giao dịch (Alert)
Để nhận thông báo tự động qua TradingView App, Email hoặc Webhook khi bot phát lệnh:
- Nhấn vào biểu tượng Alert (Cảnh báo) hoặc phím tắt
Alt + Atrên biểu đồ đã gắn CNPS93. - Ở mục Condition, chọn chiến lược
CNPS93 PREVIOUS DAY CLOSE RECLAIM V1. - Ở ô Message, xóa nội dung mặc định và điền chính xác cú pháp:
{{strategy.order.alert_message}}. - Nhấn Create để kích hoạt. Nếu không muốn nhận thông báo khi chạm SL/TP, bạn có thể tích chọn
Disable SL/TP Alertstrong phần cài đặt của bot.
Bảng thông điệp Alert của CNPS93
| Sự kiện | Thuộc tính trong code | Nội dung thông điệp Alert |
|---|---|---|
| Vào lệnh Long | alert_message | 🟢 VÀO VỊ THẾ LONG (CNPS93)\n🎯 Giá vào: <close>\n🛑 SL dự kiến: <SL>\n🎯 TP dự kiến: <TP> |
| Vào lệnh Short | alert_message | 🔴 VÀO VỊ THẾ SHORT (CNPS93)\n🎯 Giá vào: <close>\n🛑 SL dự kiến: <SL>\n🎯 TP dự kiến: <TP> |
| Chốt lời Long | alert_profit | 💰 CHỐT LỜI LONG (TP HIT - CNPS93)\n🎯 Giá chốt: <close> |
| Cắt lỗ Long | alert_loss | 🛑 CẮT LỖ LONG (SL HIT - CNPS93)\n🎯 Giá cắt: <close> |
| Chốt lời Short | alert_profit | 💰 CHỐT LỜI SHORT (TP HIT - CNPS93)\n🎯 Giá chốt: <close> |
| Cắt lỗ Short | alert_loss | 🛑 CẮT LỖ SHORT (SL HIT - CNPS93)\n🎯 Giá cắt: <close> |
| Đóng quá thời gian | alert_message | ⏱️ ĐÓNG VỊ THẾ QUÁ THỜI GIAN (Time Exit - CNPS93)\n🎯 Giá đóng: <close> |
| Đóng hết phiên | alert_message | ⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End - CNPS93)\n🎯 Giá đóng: <close> |
Kết luận
CNPS93 PREVIOUS DAY CLOSE RECLAIM V1 là một chiến lược giao dịch phái sinh VN30F1M bài bản, tận dụng hiệu quả tâm lý thị trường quanh mốc PDC kết hợp cùng bộ lọc độ lệch ATR, cơ chế xác nhận nến linh hoạt và kỷ luật đóng lệnh cuối ngày. Hệ thống đặc biệt phù hợp với các phiên thị trường có nhịp quét thanh khoản hoặc kiểm định lại vùng giá đóng cửa hôm trước rồi hình thành xu hướng rõ ràng trong ngày.
Bạn có thể tham khảo thêm các hệ thống bot giao dịch khác tại chuyên mục: 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.





