Hướng Dẫn Sử Dụng Bot CNPS91 - Opening Range Failed Break V1 cho VN30F1M
Tradingview
Mục lục
Khi giao dịch hợp đồng tương lai chỉ số VN30F1M, giai đoạn mở cửa đầu phiên sáng (09:00 – 09:15) thường tạo ra biên độ dao động đầu ngày (Opening Range). Tuy nhiên, rất nhiều nhịp bứt phá khỏi biên độ này chỉ là bẫy thanh khoản (False Breakout / Liquidity Sweep) khiến nhà giao dịch dễ bị dính cắt lỗ ngay sau khi đu theo xu hướng.
CNPS91 OPENING RANGE FAILED BREAK V1 (viết bằng Pine Script v6 trên TradingView) được thiết kế chuyên biệt để nhận diện và khai thác các cú phá vỡ giả vùng mở cửa. Thay vì đuổi theo giá khi vừa phá đỉnh/đáy đầu phiên, bot chờ giá quét qua biên Opening Range, rút chân quay lại vào trong vùng giá mở cửa và xác nhận lực đảo chiều trước khi mở vị thế.
- Khóa vùng Opening Range chặt chẽ: Chỉ xác nhận vùng mở cửa khi có đủ dữ liệu nến trọn vẹn từ
09:00đến09:15(mặc định) và tùy chọn lọc độ rộng theo ATR. - Nhận diện Sweep & Rejection đa lớp: Yêu cầu giá quét qua biên OR kèm khoảng đệm ATR (
0.05 * ATR), đóng cửa quay lại vào trong OR và có râu nến từ chối tối thiểu20%biên độ nến. - Xác nhận nến kế tiếp (Next Candle Confirmation): Chờ nến xác nhận vượt mức
Signal Midpointtrong cửa sổ tối đa4nến, tự động hủy setup nếu đáy/đỉnh quét bị phá vỡ thêm (0.10 * ATR). - Quản trị rủi ro rõ ràng: Cắt lỗ cố định
5.0điểm, chốt lời15.0điểm (tỷ lệ Risk:Reward 1:3), giới hạn tối đa2lệnh/ngày và tự động đóng toàn bộ vị thế trước14:45.
1. CNPS91 Opening Range Failed Break V1 là gì?
CNPS91 Opening Range Failed Break V1 là hệ thống giao dịch tự động theo mô hình Failed Break (Phá vỡ thất bại) dựa trên vùng giá mở cửa Opening Range (OR). Chiến lược vận hành dựa trên 4 trụ cột kỹ thuật chính:
- Opening Range Engine (Xây dựng và khóa vùng mở cửa): Ghi nhận
orHighvàorLowtrong khung giờ mở cửa (mặc định09:00 – 09:15), kiểm tra tính toàn vẹn dữ liệu (completeOR) và khóa vùng giá trước khi cho phép tìm tín hiệu. - Failed Break Sweep Engine (Phát hiện quét thanh khoản & rút chân): Theo dõi các cú quét vượt biên trên/dưới của OR kèm bộ lọc
Fresh Swing, điều kiện giá đóng cửa quay lại trong vùng OR (longReclaim/shortReclaim) và tỷ lệ râu nến từ chối (minimumWickRatio). - Pending Setup & Confirmation Window (Lưu trữ và xác nhận Setup): Thay vì vào lệnh vội vàng ngay tại nến quét, chế độ mặc định
Next Candle Confirmationđưa tín hiệu vào hàng chờ trong tối đa4nến, chỉ kích hoạt khi giá đóng cửa vượt ngưỡng xác nhận và chưa bị vô hiệu hóa cực trị. - Risk & Session Control (Kiểm soát rủi ro và phiên giao dịch): Áp dụng SL/TP cố định theo điểm, giới hạn số lệnh trong ngày, thời gian nghỉ sau thoát lệnh (
cooldownBars), tùy chọn đóng lệnh theo thời gian giữ và tự độngFlattoàn bộ vị thế vào14:45.
Bảng thông số mặc định
| Nhóm thông số | Tham số trong code | Giá trị mặc định | Ý nghĩa |
|---|---|---|---|
| 01. Opening Range | orStartHour / orStartMinute | 9 / 0 | Giờ bắt đầu tính Opening Range (09:00) |
orEndHour / orEndMinute | 9 / 15 | Giờ kết thúc và khóa Opening Range (09:15) | |
atrLength | 14 | Chu kỳ tính ATR | |
useORWidthFilter | false | Bật/tắt lọc độ rộng OR theo ATR (0.20 – 6.00) | |
| 02. Failed Break Detection | maximumSetupMinutes | 300 | Thời gian tối đa tìm setup sau khi khóa OR (phút) |
useSweepBuffer / sweepBufferATR | true / 0.05 | Khoảng đệm quét tối thiểu qua biên OR theo ATR | |
useReclaimBuffer / reclaimBufferATR | false / 0.05 | Yêu cầu đóng cửa sâu vào trong OR theo ATR | |
requireFreshSweep | true | Yêu cầu nến trước đó chưa phá qua biên quét | |
requireWick / minimumWickRatio | true / 0.20 | Yêu cầu tỷ lệ râu nến từ chối tối thiểu 20% | |
useClosePosition | false | Lọc vị trí đóng cửa (Long >= 0.40, Short <= 0.60) | |
| 03. Entry Confirmation | entryMode | "Next Candle Confirmation" | Chế độ vào lệnh (chờ nến xác nhận hoặc đóng nến tín hiệu) |
confirmationWindow | 4 | Số nến tối đa chờ xác nhận sau setup | |
confirmationLevel | "Signal Midpoint" | Mức giá xác nhận ((High + Low) / 2 của nến setup) | |
requireConfirmCandle | true | Yêu cầu nến xác nhận đúng màu (xanh cho Long, đỏ cho Short) | |
cancelOnExtremeBreak / invalidationBufferATR | true / 0.10 | Hủy setup nếu giá phá cực trị quét quá 0.10 * ATR | |
maximumSetupsPerDirection | 3 | Số setup tối đa mỗi chiều trong ngày | |
| 04. EMA Trend | useEMAFilter / emaLength / emaSlopeBars | false / 50 / 3 | Lọc xu hướng theo độ dốc EMA 50 (tắt mặc định) |
| 05. Optional Filters | useVolumeFilter / useADXFilter / useRSIFilter | false / false / false | Các bộ lọc Volume (20), ADX (<= 35), RSI (14) (tắt mặc định) |
| 06. H1 Bias | useH1Bias / h1EMALength | false / 50 | Lọc xu hướng khung H1 theo EMA 50 (tắt mặc định) |
| 07. Risk Management | stopLossPoints / takeProfitPoints | 5.0 / 15.0 | Cắt lỗ 5.0 điểm, chốt lời 15.0 điểm |
useTimeExit / maximumHoldingBars | false / 20 | Đóng lệnh nếu giữ quá 20 nến (tắt mặc định) | |
| 08. Trade Control | tradeDirection | "Long" | Chiều giao dịch mặc định (Long, tùy chọn Short, Both) |
contracts / maximumTradesPerDay / cooldownBars | 3 / 2 / 3 | Tham số hợp đồng (3), tối đa 2 lệnh/ngày, nghỉ 3 nến | |
| 09. Trading Session | useSessionFilter / tz | true / "Asia/Ho_Chi_Minh" | Lọc phiên giao dịch theo múi giờ Việt Nam |
startHour:startMinute – lastHour:lastMinute | 09:15 – 14:15 | Khung giờ cho phép vào lệnh | |
endHour:endMinute | 14:45 | Giờ đóng toàn bộ vị thế cuối phiên (Force Close) |
Source Code CNPS91 Opening Range Failed Break 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="CNPS91 OPENING RANGE FAILED BREAK V1", shorttitle="CNPS91 OR FAILED", 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)
// ============================================================================
// CNPS91 - OPENING RANGE FAILED BREAK
//
// BULLISH FAILED BREAK:
// 1. Opening Range (OR) is completed and frozen.
// 2. Price sweeps below OR Low.
// 3. Candle closes back inside the OR.
// 4. Lower wick supports price rejection.
// 5. Optional next-candle confirmation.
// 6. LONG.
//
// BEARISH FAILED BREAK:
// 1. Price sweeps above OR High.
// 2. Candle closes back inside the OR.
// 3. Upper wick supports rejection.
// 4. Optional confirmation.
// 5. SHORT.
//
// Only confirmed candles generate orders.
// No future-looking pivot calculations.
// Pending setups expire within a fixed window.
// ============================================================================
// ============================================================================
// 01. OPENING RANGE
// ============================================================================
gOR = "01. Opening Range"
orStartHour = input.int(9, "OR Start Hour", minval=0, maxval=23, group=gOR)
orStartMinute = input.int(0, "OR Start Minute", minval=0, maxval=59, group=gOR)
orEndHour = input.int(9, "OR End Hour", minval=0, maxval=23, group=gOR)
orEndMinute = input.int(15, "OR End Minute", minval=0, maxval=59, group=gOR)
atrLength = input.int(14, "ATR Length", minval=1, group=gOR)
useORWidthFilter = input.bool(false, "Use OR Width Filter", group=gOR)
minimumORWidthATR = input.float(0.20, "Minimum OR Width / ATR", minval=0.0, step=0.1, group=gOR)
maximumORWidthATR = input.float(6.00, "Maximum OR Width / ATR", minval=0.1, step=0.1, group=gOR)
// ============================================================================
// 02. FAILED BREAK DETECTION
// ============================================================================
gSweep = "02. Failed Break Detection"
maximumSetupMinutes = input.int(300, "Maximum Minutes After OR", minval=5, maxval=480, step=5, group=gSweep)
useSweepBuffer = input.bool(true, "Require Sweep Buffer", group=gSweep)
sweepBufferATR = input.float(0.05, "Sweep Buffer / ATR", minval=0.0, step=0.05, group=gSweep)
useReclaimBuffer = input.bool(false, "Require Deep Reclaim Into OR", group=gSweep)
reclaimBufferATR = input.float(0.05, "Reclaim Buffer / ATR", minval=0.0, step=0.05, group=gSweep)
requireFreshSweep = input.bool(true, "Require Fresh Swing Across OR", group=gSweep)
requireWick = input.bool(true, "Require Rejection Wick", group=gSweep)
minimumWickRatio = input.float(0.20, "Minimum Wick / Candle Range", minval=0.0, maxval=1.0, step=0.05, group=gSweep)
useClosePosition = input.bool(false, "Filter Signal Close Position", group=gSweep)
minimumLongClosePosition = input.float(0.40, "Minimum Long Close Position", minval=0.0, maxval=1.0, step=0.05, group=gSweep)
maximumShortClosePosition = input.float(0.60, "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("Next Candle Confirmation", "Entry Mode", options=["Signal Candle Close", "Next Candle Confirmation"], group=gConfirm)
confirmationWindow = input.int(4, "Maximum Confirmation Bars", minval=1, maxval=30, group=gConfirm)
confirmationLevel = input.string("Signal Midpoint", "Confirmation Level", options=["Signal Close", "Signal Midpoint", "Signal High/Low"], group=gConfirm)
requireConfirmCandle = input.bool(true, "Require Confirmation Candle Direction", group=gConfirm)
cancelOnExtremeBreak = input.bool(true, "Cancel If Sweep Extreme Breaks", group=gConfirm)
invalidationBufferATR = input.float(0.10, "Invalidation Buffer / ATR", minval=0.0, step=0.05, group=gConfirm)
maximumSetupsPerDirection = input.int(3, "Maximum Setups / Direction / Day", minval=1, maxval=20, 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, maxval=300, group=gTrend)
emaSlopeBars = input.int(3, "EMA Slope Lookback", minval=1, maxval=50, group=gTrend)
requirePriceEMA = input.bool(false, "Require Close Above/Below EMA", group=gTrend)
// ============================================================================
// 05. OPTIONAL FILTERS
// ============================================================================
gFilters = "05. Optional Filters"
useVolumeFilter = input.bool(false, "Use Volume Confirmation", group=gFilters)
volumeLength = input.int(20, "Volume MA Length", minval=2, group=gFilters)
volumeFactor = input.float(1.00, "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)
useRSIFilter = input.bool(false, "Use RSI Filter", group=gFilters)
rsiLength = input.int(14, "RSI Length", minval=2, group=gFilters)
longRSIMax = input.float(65.0, "Maximum RSI For Long", minval=1.0, maxval=100.0, group=gFilters)
shortRSIMin = input.float(35.0, "Minimum RSI For Short", minval=0.0, maxval=99.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 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("Long", "Trade Direction", options=["Long", "Short", "Both"], group=gTrade)
contracts = input.int(3, "Contracts", minval=1, maxval=100, group=gTrade)
maximumTradesPerDay = input.int(2, "Maximum Trades Per Day", minval=1, maxval=20, group=gTrade)
cooldownBars = input.int(3, "Cooldown After Exit (Bars)", minval=0, maxval=100, group=gTrade)
bool allowLong = (tradeDirection == "Long" or tradeDirection == "Both")
bool allowShort = (tradeDirection == "Short" or tradeDirection == "Both")
// ============================================================================
// 09. SESSION
// ============================================================================
gSession = "09. Trading Session"
useSessionFilter = input.bool(true, "Use Entry Session Filter", group=gSession)
tz = input.string("Asia/Ho_Chi_Minh", "Timezone", group=gSession)
startHour = input.int(9, "Entry Start Hour", minval=0, maxval=23, group=gSession)
startMinute = input.int(15, "Entry Start Minute", minval=0, maxval=59, group=gSession)
lastHour = input.int(14, "Last Entry Hour", minval=0, maxval=23, group=gSession)
lastMinute = input.int(15, "Last Entry Minute", minval=0, maxval=59, group=gSession)
endHour = input.int(14, "Force Close Hour", minval=0, maxval=23, group=gSession)
endMinute = input.int(45, "Force Close Minute", minval=0, maxval=59, group=gSession)
// ============================================================================
// 10. ALERTS
// ============================================================================
gAlerts = "10. Alerts"
disableExitAlerts = input.bool(false, "Disable SL/TP Alerts", group=gAlerts)
// ============================================================================
// 11. DISPLAY
// ============================================================================
gDisplay = "11. Display"
showEMA = input.bool(true, "Show EMA", group=gDisplay)
showOpeningRange = input.bool(true, "Show OR High/Low", group=gDisplay)
showORMidpoint = input.bool(false, "Show OR Midpoint", group=gDisplay)
showORBackground = input.bool(false, "Highlight OR Formation", group=gDisplay)
showSweepMarkers = input.bool(false, "Show Raw Sweep Dots", group=gDisplay)
showSetupMarkers = input.bool(false, "Show Failed Break Setup Dots", 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 orStartMinutes = (orStartHour * 60 + orStartMinute)
int orEndMinutes = (orEndHour * 60 + orEndMinute)
int entryStartMinutes = (startHour * 60 + startMinute)
int lastEntryMinutes = (lastHour * 60 + lastMinute)
int forceCloseMinutes = (endHour * 60 + endMinute)
bool intradayOK = timeframe.isintraday
bool validORSettings = (orEndMinutes > orStartMinutes)
bool validChartResolution = (intradayOK and validORSettings and timeframe.in_seconds() <= (orEndMinutes - orStartMinutes) * 60)
bool insideOR = (validChartResolution and openMinutes >= orStartMinutes and closeMinutes <= orEndMinutes)
bool afterOR = (validChartResolution and openMinutes >= orEndMinutes)
bool setupTimeOK = (afterOR and closeMinutes <= orEndMinutes + maximumSetupMinutes)
bool entrySessionOK = (not useSessionFilter or (openMinutes >= entryStartMinutes and closeMinutes <= lastEntryMinutes))
bool beforeForceClose = (closeMinutes < forceCloseMinutes)
bool forceCloseBar = (openMinutes < forceCloseMinutes and closeMinutes >= forceCloseMinutes)
// ============================================================================
// 13. DAILY RESET
// ============================================================================
int dayKey = (year(time, tz) * 10000 + month(time, tz) * 100 + dayofmonth(time, tz))
bool newDay = (na(dayKey[1]) or dayKey != dayKey[1])
var int tradesToday = 0
if newDay
tradesToday := 0
// ============================================================================
// 14. INDICATOR ENGINE
// ============================================================================
float atr = ta.atr(atrLength)
float ema = ta.ema(close, emaLength)
float rsi = ta.rsi(close, rsiLength)
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)
// ============================================================================
// 15. OPENING RANGE VARIABLES
// ============================================================================
var float orHigh = na
var float orLow = na
var float orWidth = na
var float orWidthATR = na
var int orBarCount = 0
var int firstOROpen = na
var int lastORClose = na
var bool orLocked = false
var bool orValid = false
var int totalORDays = 0
var int invalidORDays = 0
var int longSetupsToday = 0
var int shortSetupsToday = 0
if newDay
orHigh := na
orLow := na
orWidth := na
orWidthATR := na
orBarCount := 0
firstOROpen := na
lastORClose := na
orLocked := false
orValid := false
longSetupsToday := 0
shortSetupsToday := 0
// ============================================================================
// 16. BUILD OPENING RANGE
// ============================================================================
if (barstate.isconfirmed and insideOR and not orLocked)
if orBarCount == 0
firstOROpen := openMinutes
orHigh := (na(orHigh) ? high : math.max(orHigh, high))
orLow := (na(orLow) ? low : math.min(orLow, low))
orBarCount += 1
lastORClose := closeMinutes
// ============================================================================
// 17. LOCK OPENING RANGE
// ============================================================================
//
// Require coverage of OR start and end.
// Do not accept an incomplete opening range.
//
// ============================================================================
if (barstate.isconfirmed and afterOR and not orLocked and orBarCount > 0)
orLocked := true
orWidth := orHigh - orLow
orWidthATR := (not na(atr) and atr > 0 ? orWidth / atr : na)
bool completeOR = (firstOROpen == orStartMinutes and lastORClose == orEndMinutes)
bool widthOK = (not useORWidthFilter or (not na(orWidthATR) and orWidthATR >= minimumORWidthATR and orWidthATR <= maximumORWidthATR))
orValid := (completeOR and orWidth > 0 and widthOK)
totalORDays += 1
if not orValid
invalidORDays += 1
// ============================================================================
// 18. FAILED BREAK SWEEP ENGINE
// ============================================================================
//
// LONG:
// Low sweeps below OR Low.
// Close reclaims above OR Low.
// Close remains below OR High.
//
// SHORT:
// High sweeps above OR High.
// Close returns below OR High.
// Close remains above OR Low.
//
// Both setups require an already frozen OR.
//
// ============================================================================
float sweepBuffer = (useSweepBuffer and not na(atr) ? atr * sweepBufferATR : 0.0)
float reclaimBuffer = (useReclaimBuffer and not na(atr) ? atr * reclaimBufferATR : 0.0)
bool rawLongSweep = (barstate.isconfirmed and orLocked and orValid and setupTimeOK and low < orLow - sweepBuffer)
bool rawShortSweep = (barstate.isconfirmed and orLocked and orValid and setupTimeOK and high > orHigh + sweepBuffer)
bool freshLongSweep = (not requireFreshSweep or (not na(orLow) and low[1] >= orLow - sweepBuffer))
bool freshShortSweep = (not requireFreshSweep or (not na(orHigh) and high[1] <= orHigh + sweepBuffer))
bool longReclaim = (not na(orLow) and not na(orHigh) and close > orLow + reclaimBuffer and close < orHigh)
bool shortReclaim = (not na(orHigh) and not na(orLow) and close < orHigh - reclaimBuffer and close > orLow)
// ============================================================================
// 19. REJECTION CANDLE
// ============================================================================
float candleRange = high - low
float candleBody = math.abs(close - open)
float bodyRatio = (candleRange > 0 ? candleBody / candleRange : 0.0)
float upperWick = (high - math.max(open, close))
float lowerWick = (math.min(open, close) - low)
float upperWickRatio = (candleRange > 0 ? upperWick / candleRange : 0.0)
float lowerWickRatio = (candleRange > 0 ? lowerWick / candleRange : 0.0)
float closePosition = (candleRange > 0 ? (close - low) / candleRange : 0.5)
bool bullishCandle = close > open
bool bearishCandle = close < open
bool longWickOK = (not requireWick or lowerWickRatio >= minimumWickRatio)
bool shortWickOK = (not requireWick or upperWickRatio >= minimumWickRatio)
bool longCloseOK = (not useClosePosition or closePosition >= minimumLongClosePosition)
bool shortCloseOK = (not useClosePosition or closePosition <= maximumShortClosePosition)
// ============================================================================
// 20. FAILED BREAK SETUPS
// ============================================================================
bool bullishFailedBreak = (rawLongSweep and freshLongSweep and longReclaim and longWickOK and longCloseOK)
bool bearishFailedBreak = (rawShortSweep and freshShortSweep and shortReclaim and shortWickOK and shortCloseOK)
// ============================================================================
// 21. 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)))
// ============================================================================
// 22. ADX / RSI / VOLUME
// ============================================================================
bool volumeOK = (not useVolumeFilter or (not na(relativeVolume) and relativeVolume >= volumeFactor))
bool adxOK = (not useADXFilter or (not na(adx) and adx <= maximumADX))
bool longRSIOK = (not useRSIFilter or (not na(rsi) and rsi <= longRSIMax))
bool shortRSIOK = (not useRSIFilter or (not na(rsi) and rsi >= shortRSIMin))
// ============================================================================
// 23. CONFIRMED H1 BIAS
// ============================================================================
float h1EMA = request.security(syminfo.tickerid, "60", ta.ema(close, h1EMALength)[1], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
float h1Close = request.security(syminfo.tickerid, "60", close[1], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
bool validH1Chart = (timeframe.isintraday and timeframe.in_seconds() < 3600)
bool longH1OK = (not useH1Bias or (validH1Chart and not na(h1EMA) and not na(h1Close) and h1Close > h1EMA))
bool shortH1OK = (not useH1Bias or (validH1Chart and not na(h1EMA) and not na(h1Close) and h1Close < h1EMA))
// ============================================================================
// 24. 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)
// ============================================================================
// 25. PENDING 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 longSetupHigh = na
var float longSetupLow = na
var float longSetupClose = na
var float shortSetupHigh = na
var float shortSetupLow = na
var float shortSetupClose = na
var int rawLongSweepCount = 0
var int rawShortSweepCount = 0
var int longSetupCount = 0
var int shortSetupCount = 0
var int longConfirmCount = 0
var int shortConfirmCount = 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")
// ============================================================================
// 26. CONFIRMATION WINDOW
// ============================================================================
bool validLongWindow = (pendingLong and not na(longSetupBar) and longSetupDay == dayKey and bar_index > longSetupBar and bar_index - longSetupBar <= confirmationWindow)
bool validShortWindow = (pendingShort and not na(shortSetupBar) and shortSetupDay == dayKey and bar_index > shortSetupBar and bar_index - shortSetupBar <= confirmationWindow)
// ============================================================================
// 27. CONFIRMATION LEVELS
// ============================================================================
float longConfirmationLevel = (confirmationLevel == "Signal High/Low" ? longSetupHigh : confirmationLevel == "Signal Midpoint" ? (longSetupHigh + longSetupLow) / 2.0 : longSetupClose)
float shortConfirmationLevel = (confirmationLevel == "Signal High/Low" ? shortSetupLow : confirmationLevel == "Signal Midpoint" ? (shortSetupHigh + shortSetupLow) / 2.0 : shortSetupClose)
float invalidationBuffer = (not na(atr) ? atr * invalidationBufferATR : 0.0)
bool longExtremeOK = (not cancelOnExtremeBreak or (not na(longSetupLow) and low >= longSetupLow - invalidationBuffer))
bool shortExtremeOK = (not cancelOnExtremeBreak or (not na(shortSetupHigh) and high <= shortSetupHigh + invalidationBuffer))
bool longConfirmCandleOK = (not requireConfirmCandle or bullishCandle)
bool shortConfirmCandleOK = (not requireConfirmCandle or bearishCandle)
bool confirmedLong = (barstate.isconfirmed and validLongWindow and longExtremeOK and longConfirmCandleOK and not na(longConfirmationLevel) and close > longConfirmationLevel)
bool confirmedShort = (barstate.isconfirmed and validShortWindow and shortExtremeOK and shortConfirmCandleOK and not na(shortConfirmationLevel) and close < shortConfirmationLevel)
// ============================================================================
// 28. ENTRY BASE SIGNALS
// ============================================================================
bool longBase = (confirmationMode ? confirmedLong : bullishFailedBreak)
bool shortBase = (confirmationMode ? confirmedShort : bearishFailedBreak)
// ============================================================================
// 29. FILTERED SIGNALS
// ============================================================================
bool rawLong = (longBase and longTrendOK and volumeOK and adxOK and longRSIOK and longH1OK)
bool rawShort = (shortBase and shortTrendOK and volumeOK and adxOK and shortRSIOK and shortH1OK)
// ============================================================================
// 30. ENTRY CONTROL
// ============================================================================
bool canTrade = (barstate.isconfirmed and validChartResolution and orLocked and orValid and flat and strategy.opentrades == 0 and tradesToday < maximumTradesPerDay and cooldownOK and freshEntryBar and entrySessionOK and beforeForceClose and setupTimeOK)
bool ambiguousSignal = rawLong and rawShort
bool enterLong = (canTrade and allowLong and rawLong and not ambiguousSignal)
bool enterShort = (canTrade and allowShort and rawShort and not ambiguousSignal)
// ============================================================================
// 31. SL / TP IN TICKS
// ============================================================================
int slTicks = math.max(1, int(math.round(stopLossPoints / syminfo.mintick)))
int tpTicks = math.max(1, int(math.round(takeProfitPoints / syminfo.mintick)))
float effectiveSL = slTicks * syminfo.mintick
float effectiveTP = tpTicks * syminfo.mintick
// ============================================================================
// 32. LONG ENTRY
// ============================================================================
if enterLong
strategy.entry("Long", strategy.long, comment="OR Failed Break LONG", alert_message="🟢 VÀO VỊ THẾ LONG (CNPS91)\\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
// ============================================================================
// 33. SHORT ENTRY
// ============================================================================
if enterShort
strategy.entry("Short", strategy.short, comment="OR Failed Break SHORT", alert_message="🔴 VÀO VỊ THẾ SHORT (CNPS91)\\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
// ============================================================================
// 34. UPDATE PENDING SETUPS
// ============================================================================
//
// Evaluate entries first.
// Register new setups after signals.
//
// This prevents a setup from confirming
// itself on the same candle.
//
// ============================================================================
if barstate.isconfirmed
if rawLongSweep
rawLongSweepCount += 1
if rawShortSweep
rawShortSweepCount += 1
if longBase
longConfirmCount += 1
if shortBase
shortConfirmCount += 1
if rawLong
filteredLongCount += 1
if rawShort
filteredShortCount += 1
if rawLong and not enterLong
blockedLongCount += 1
if rawShort and not enterShort
blockedShortCount += 1
// --------------------------------------------------------
// RESET OLD PENDING SETUPS
// --------------------------------------------------------
if newDay
pendingLong := false
pendingShort := false
longSetupBar := na
shortSetupBar := na
longSetupDay := na
shortSetupDay := na
longSetupHigh := na
longSetupLow := na
longSetupClose := na
shortSetupHigh := na
shortSetupLow := na
shortSetupClose := na
// --------------------------------------------------------
// LONG EXPIRATION / INVALIDATION
// --------------------------------------------------------
if pendingLong and not na(longSetupBar)
bool longExpired = (longSetupDay != dayKey or bar_index - longSetupBar > confirmationWindow)
bool longInvalid = (cancelOnExtremeBreak and not na(longSetupLow) and low < longSetupLow - invalidationBuffer)
if (longExpired or longInvalid or confirmedLong)
if longExpired or longInvalid
expiredLongCount += 1
pendingLong := false
longSetupBar := na
// --------------------------------------------------------
// SHORT EXPIRATION / INVALIDATION
// --------------------------------------------------------
if pendingShort and not na(shortSetupBar)
bool shortExpired = (shortSetupDay != dayKey or bar_index - shortSetupBar > confirmationWindow)
bool shortInvalid = (cancelOnExtremeBreak and not na(shortSetupHigh) and high > shortSetupHigh + invalidationBuffer)
if (shortExpired or shortInvalid or confirmedShort)
if shortExpired or shortInvalid
expiredShortCount += 1
pendingShort := false
shortSetupBar := na
// --------------------------------------------------------
// REGISTER NEW FAILED BREAK SETUPS
// --------------------------------------------------------
bool canRegister = (confirmationMode and validChartResolution and orLocked and orValid and flat and entrySessionOK and beforeForceClose and setupTimeOK and tradesToday < maximumTradesPerDay and not enterLong and not enterShort)
if (canRegister and bullishFailedBreak and not bearishFailedBreak and not pendingLong and not pendingShort and longSetupsToday < maximumSetupsPerDirection)
pendingLong := true
longSetupBar := bar_index
longSetupDay := dayKey
longSetupHigh := high
longSetupLow := low
longSetupClose := close
longSetupsToday += 1
longSetupCount += 1
if (canRegister and bearishFailedBreak and not bullishFailedBreak and not pendingShort and not pendingLong and shortSetupsToday < maximumSetupsPerDirection)
pendingShort := true
shortSetupBar := bar_index
shortSetupDay := dayKey
shortSetupHigh := high
shortSetupLow := low
shortSetupClose := close
shortSetupsToday += 1
shortSetupCount += 1
// ============================================================================
// 35. LONG EXIT
// ============================================================================
strategy.exit("Long Exit", from_entry="Long", profit=tpTicks, loss=slTicks, comment_profit="TP Long", comment_loss="SL Long", alert_profit="💰 CHỐT LỜI LONG (TP HIT - CNPS91)\\n🎯 Giá chốt: " + str.tostring(close, format.mintick), alert_loss="🛑 CẮT LỖ LONG (SL HIT - CNPS91)\\n🎯 Giá cắt: " + str.tostring(close, format.mintick), disable_alert=disableExitAlerts)
// ============================================================================
// 36. SHORT EXIT
// ============================================================================
strategy.exit("Short Exit", from_entry="Short", profit=tpTicks, loss=slTicks, comment_profit="TP Short", comment_loss="SL Short", alert_profit="💰 CHỐT LỜI SHORT (TP HIT - CNPS91)\\n🎯 Giá chốt: " + str.tostring(close, format.mintick), alert_loss="🛑 CẮT LỖ SHORT (SL HIT - CNPS91)\\n🎯 Giá cắt: " + str.tostring(close, format.mintick), disable_alert=disableExitAlerts)
// ============================================================================
// 37. OPTIONAL TIME EXIT
// ============================================================================
int barsHeld = (strategy.opentrades > 0 ? bar_index - strategy.opentrades.entry_bar_index(0) : 0)
bool timeExit = (useTimeExit and strategy.position_size != 0 and barsHeld >= maximumHoldingBars and barstate.isconfirmed)
if timeExit and not forceCloseBar
strategy.close_all(immediately=true, comment="Time Exit", alert_message="⏱️ ĐÓNG VỊ THẾ QUÁ THỜI GIAN (Time Exit - CNPS91)\\n🎯 Giá đóng: " + str.tostring(close, format.mintick))
// ============================================================================
// 38. FORCE CLOSE
// ============================================================================
if (barstate.isconfirmed and forceCloseBar and strategy.position_size != 0)
strategy.close_all(immediately=true, comment="Session End", alert_message="⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End - CNPS91)\\n🎯 Giá đóng: " + str.tostring(close, format.mintick))
// ============================================================================
// 39. EMA PLOT
// ============================================================================
plot(showEMA ? ema : na, title="EMA Trend", color=color.orange, linewidth=2)
// ============================================================================
// 40. OPENING RANGE PLOTS
// ============================================================================
plot(showOpeningRange ? orHigh : na, title="Opening Range High", color=color.aqua, linewidth=2, style=plot.style_linebr)
plot(showOpeningRange ? orLow : na, title="Opening Range Low", color=color.fuchsia, linewidth=2, style=plot.style_linebr)
float orMidpoint = (not na(orHigh) and not na(orLow) ? (orHigh + orLow) / 2.0 : na)
plot(showORMidpoint ? orMidpoint : na, title="Opening Range Midpoint", color=color.gray, linewidth=1, style=plot.style_linebr)
bgcolor(showORBackground and insideOR ? color.new(color.blue, 92) : na, title="Opening Range Background")
// ============================================================================
// 41. RAW SWEEP MARKERS
// ============================================================================
plotshape(showSweepMarkers and rawLongSweep, title="OR Low Sweep", style=shape.circle, location=location.belowbar, color=color.new(color.green, 20), size=size.tiny, text="SW")
plotshape(showSweepMarkers and rawShortSweep, title="OR High Sweep", style=shape.circle, location=location.abovebar, color=color.new(color.red, 20), size=size.tiny, text="SW")
// ============================================================================
// 42. FAILED BREAK SETUP MARKERS
// ============================================================================
plotshape(showSetupMarkers and bullishFailedBreak, title="Bullish OR Failed Break", style=shape.circle, location=location.belowbar, color=color.aqua, size=size.tiny, text="FB")
plotshape(showSetupMarkers and bearishFailedBreak, title="Bearish OR Failed Break", style=shape.circle, location=location.abovebar, color=color.orange, size=size.tiny, text="FB")
// ============================================================================
// 43. PENDING LEVELS
// ============================================================================
plot(showPendingLevels and pendingLong ? longConfirmationLevel : na, title="Pending Long Trigger", color=color.aqua, linewidth=2, style=plot.style_linebr)
plot(showPendingLevels and pendingShort ? shortConfirmationLevel : na, title="Pending Short Trigger", color=color.fuchsia, linewidth=2, style=plot.style_linebr)
// ============================================================================
// 44. ENTRY MARKERS
// ============================================================================
plotshape(showEntryMarkers and enterLong, title="CNPS91 LONG", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, text="LONG", textcolor=color.white)
plotshape(showEntryMarkers and enterShort, title="CNPS91 SHORT", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small, text="SHORT", textcolor=color.white)
// ============================================================================
// 45. ACTIVE SL / TP
// ============================================================================
float longSL = (inLong ? strategy.position_avg_price - effectiveSL : na)
float longTP = (inLong ? strategy.position_avg_price + effectiveTP : na)
float shortSL = (inShort ? strategy.position_avg_price + effectiveSL : na)
float shortTP = (inShort ? strategy.position_avg_price - effectiveTP : na)
plot(showSLTP ? longSL : na, title="Long SL", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showSLTP ? longTP : na, title="Long TP", color=color.green, linewidth=2, style=plot.style_linebr)
plot(showSLTP ? shortSL : na, title="Short SL", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showSLTP ? shortTP : na, title="Short TP", color=color.green, linewidth=2, style=plot.style_linebr)
// ============================================================================
// 46. DATA WINDOW
// ============================================================================
plot(orWidth, title="OR Width", color=color.blue, display=display.data_window)
plot(orWidthATR, title="OR Width / ATR", color=color.aqua, display=display.data_window)
plot(relativeVolume, title="Relative Volume", color=color.gray, display=display.data_window)
plot(bodyRatio, title="Candle Body Ratio", color=color.orange, display=display.data_window)
plot(lowerWickRatio, title="Lower Wick Ratio", color=color.green, display=display.data_window)
plot(upperWickRatio, title="Upper Wick Ratio", color=color.red, display=display.data_window)
plot(atr, title="ATR", color=color.gray, display=display.data_window)
plot(adx, title="ADX", color=color.purple, display=display.data_window)
// ============================================================================
// 47. DIAGNOSTICS TABLE
// ============================================================================
var table diagnostics = table.new(position.top_right, 2, 23, border_width=1)
if showDiagnostics and barstate.islast
table.cell(diagnostics, 0, 0, "CNPS91 V1")
table.cell(diagnostics, 1, 0, timeframe.period)
table.cell(diagnostics, 0, 1, "OR Locked")
table.cell(diagnostics, 1, 1, orLocked ? "YES" : "NO")
table.cell(diagnostics, 0, 2, "OR Valid")
table.cell(diagnostics, 1, 2, orValid ? "YES" : "NO")
table.cell(diagnostics, 0, 3, "OR Width")
table.cell(diagnostics, 1, 3, str.tostring(orWidth, "#.##"))
table.cell(diagnostics, 0, 4, "OR Days")
table.cell(diagnostics, 1, 4, str.tostring(totalORDays))
table.cell(diagnostics, 0, 5, "Invalid OR Days")
table.cell(diagnostics, 1, 5, str.tostring(invalidORDays))
table.cell(diagnostics, 0, 6, "Long Sweeps")
table.cell(diagnostics, 1, 6, str.tostring(rawLongSweepCount))
table.cell(diagnostics, 0, 7, "Short Sweeps")
table.cell(diagnostics, 1, 7, str.tostring(rawShortSweepCount))
table.cell(diagnostics, 0, 8, "Long Setups")
table.cell(diagnostics, 1, 8, str.tostring(longSetupCount))
table.cell(diagnostics, 0, 9, "Short Setups")
table.cell(diagnostics, 1, 9, str.tostring(shortSetupCount))
table.cell(diagnostics, 0, 10, "Long Confirms")
table.cell(diagnostics, 1, 10, str.tostring(longConfirmCount))
table.cell(diagnostics, 0, 11, "Short Confirms")
table.cell(diagnostics, 1, 11, str.tostring(shortConfirmCount))
table.cell(diagnostics, 0, 12, "Filtered Long")
table.cell(diagnostics, 1, 12, str.tostring(filteredLongCount))
table.cell(diagnostics, 0, 13, "Filtered Short")
table.cell(diagnostics, 1, 13, str.tostring(filteredShortCount))
table.cell(diagnostics, 0, 14, "Blocked Long")
table.cell(diagnostics, 1, 14, str.tostring(blockedLongCount))
table.cell(diagnostics, 0, 15, "Blocked Short")
table.cell(diagnostics, 1, 15, str.tostring(blockedShortCount))
table.cell(diagnostics, 0, 16, "Long Entries")
table.cell(diagnostics, 1, 16, str.tostring(longEntryCount))
table.cell(diagnostics, 0, 17, "Short Entries")
table.cell(diagnostics, 1, 17, str.tostring(shortEntryCount))
table.cell(diagnostics, 0, 18, "Expired Long")
table.cell(diagnostics, 1, 18, str.tostring(expiredLongCount))
table.cell(diagnostics, 0, 19, "Expired Short")
table.cell(diagnostics, 1, 19, str.tostring(expiredShortCount))
table.cell(diagnostics, 0, 20, "Pending Long")
table.cell(diagnostics, 1, 20, pendingLong ? "YES" : "NO")
table.cell(diagnostics, 0, 21, "Trades Today")
table.cell(diagnostics, 1, 21, str.tostring(tradesToday) + "/" + str.tostring(maximumTradesPerDay))
table.cell(diagnostics, 0, 22, "Position")
table.cell(diagnostics, 1, 22, inLong ? "LONG" : inShort ? "SHORT" : "FLAT")
2. Những khái niệm kỹ thuật cốt lõi trong CNPS91
2.1. Xây dựng và xác thực vùng Opening Range (OR)
Hệ thống chỉ hoạt động trên biểu đồ intraday (timeframe.isintraday) có khung thời gian nhỏ hơn hoặc bằng độ rộng vùng OR (timeframe.in_seconds() <= (orEndMinutes - orStartMinutes) * 60). Với cấu hình mặc định 09:00 – 09:15, bạn có thể chạy tốt trên các khung 1m, 3m, 5m hoặc 15m.
Khi phiên giao dịch đi qua 09:15, bot khóa orHigh, orLow và tính:
$$\text{orWidth} = \text{orHigh} - \text{orLow}, \qquad \text{orWidthATR} = \frac{\text{orWidth}}{\text{ATR}(14)}$$
Vùng OR chỉ được đánh dấu hợp lệ (orValid = true) khi thỏa mãn cả 3 điều kiện:
- Dữ liệu bao phủ trọn vẹn từ phút bắt đầu (
firstOROpen == 09:00) đến phút kết thúc (lastORClose == 09:15). - Độ rộng
orWidth > 0. - Nếu bật
useORWidthFilter, tỷ lệorWidthATRphải nằm trong khoảng[0.20, 6.00].
2.2. Động cơ phát hiện Failed Break & nến từ chối (Rejection Candle)
Một cú phá vỡ giả không đơn thuần là giá chạm biên OR, mà phải hội tụ đủ 4 yếu tố trên nến đã đóng (barstate.isconfirmed):
- Quét thanh khoản kèm đệm ATR (
sweepBuffer): Giá thấp nhất phải xuyên thủngorLow - 0.05 * ATR(với Long) hoặc giá cao nhất vượtorHigh + 0.05 * ATR(với Short). - Nhịp quét mới (
requireFreshSweep = true): Nến liền trước (low[1]hoặchigh[1]) chưa nằm ngoài vùng đệm quét, đảm bảo đây là một cú phá vỡ mới. - Đóng cửa quay lại vào trong OR (
Reclaim): Giá đóng cửa phải quay trở lại nằm gọn trong khoảng(orLow, orHigh). Nếu bậtuseReclaimBuffer, giá phải đóng sâu vào trong thêm0.05 * ATR. - Râu nến từ chối (
Rejection Wick):- Long:
lowerWickRatio = (min(open, close) - low) / (high - low) >= 0.20. - Short:
upperWickRatio = (high - max(open, close)) / (high - low) >= 0.20.
- Long:
2.3. Xác nhận nến kế tiếp & bộ lọc tùy chọn
Ở chế độ mặc định Next Candle Confirmation, nến Failed Break đóng vai trò là nến Setup (pendingLong hoặc pendingShort). Bot tính sẵn ngưỡng xác nhận:
Signal Midpoint(mặc định):(setupHigh + setupLow) / 2.0.Signal Close: Giá đóng cửa nến setup.Signal High/Low: Đỉnh nến setup (cho Long) hoặc đáy nến setup (cho Short).
Ngoài ra, CNPS91 tích hợp sẵn 5 bộ lọc tùy chọn (đều mặc định false để giữ nguyên bản chất Price Action):
- EMA Trend (
useEMAFilter): Lọc theo độ dốc EMA50so với3nến trước đó và tùy chọn giá nằm trên/dưới EMA. - Volume (
useVolumeFilter): So sánh khối lượng hiện tại với trung bình20nến trước (relativeVolume >= 1.00). - ADX (
useADXFilter): Giới hạnADX(14, 14) <= 35.0để tránh vào lệnh khi thị trường đang có xu hướng quá mạnh. - RSI (
useRSIFilter): Giới hạnRSI(14) <= 65.0cho Long và>= 35.0cho Short. - H1 Bias (
useH1Bias): Lấy EMA50khung60phút (dữ liệu nến đã đóng[1]) để đồng pha xu hướng lớn.
3. Nguyên lý hoạt động của CNPS91
Quy trình vận hành khép kín của bot diễn ra theo 5 bước tuần tự trên mỗi cây nến đã đóng:
- Bước 1 – Khởi tạo phiên mới (
newDay): Khi sang ngày mới theo múi giờAsia/Ho_Chi_Minh, bot đặt lạitradesToday = 0, xóa các biếnorHigh,orLow,orLocked,orValidvà hủy toàn bộpendingLong/pendingShortcòn tồn đọng. - Bước 2 – Thu thập và khóa Opening Range: Từ
09:00đến09:15, bot cập nhật đỉnh/đáy vùng mở cửa. Ngay cây nến đầu tiên sau09:15, OR được khóa cứng và kiểm tra tính hợp lệ (orValid). - Bước 3 – Quét tín hiệu Failed Break & lưu Setup: Trong vòng
300phút sau khi khóa OR (setupTimeOK), nếu xuất hiện nếnbullishFailedBreakhoặcbearishFailedBreak(không đồng thời cả hai) và đang ở trạng tháiflat, bot ghi nhận Setup vào hàng chờ (tối đa3setup mỗi chiều/ngày). - Bước 4 – Xác nhận, kiểm tra bộ lọc & gửi lệnh: Trong cửa sổ
4nến tiếp theo, nếu giá đóng cửa vượt mức xác nhận, nến đúng chiều và cực trị quét không bị phá vỡ thêm0.10 * ATR, tín hiệu được đưa qua các bộ lọc tùy chọn và điều kiệncanTradetrước khi gọistrategy.entry. - Bước 5 – Quản trị vị thế & đóng lệnh: Ngay khi khớp lệnh,
strategy.exitthiết lập SL5.0điểm và TP15.0điểm. Nếu kích hoạtuseTimeExit, bot đóng lệnh khi giữ đủ20nến; cuối cùng, mọi vị thế còn mở sẽ bị đóng tự động tại cây nến14:45.
4. Điều kiện vào lệnh Long và Short của CNPS91
4.1. Điều kiện vào lệnh Long
Vị thế Long (enterLong) được kích hoạt khi thỏa mãn toàn bộ các điều kiện sau:
tradeDirectioncho phép chiều mua ("Long"mặc định hoặc"Both").- Xuất hiện Bullish Failed Break:
low < orLow - sweepBuffer(0.05 * ATRnếu bậtuseSweepBuffer).- Nếu bật
requireFreshSweep:low[1] >= orLow - sweepBuffer. - Giá đóng cửa quay lại vào trong OR:
close > orLow + reclaimBuffervàclose < orHigh. - Râu nến dưới đạt tối thiểu
20%biên độ nến (lowerWickRatio >= 0.20khi bậtrequireWick). - Vị trí đóng cửa đạt ngưỡng nếu bật
useClosePosition(closePosition >= 0.40).
- Xác nhận (nếu ở chế độ
Next Candle Confirmation):- Đang có
pendingLonghợp lệ trong vòng1đến4nến sau setup cùng ngày. - Đáy nến setup chưa bị phá xuống dưới
longSetupLow - 0.10 * ATR(nếu bậtcancelOnExtremeBreak). - Nến xác nhận là nến tăng (
close > openkhi bậtrequireConfirmCandle) vàclose > longConfirmationLevel.
- Đang có
- Vượt qua các bộ lọc tùy chọn (nếu bật): EMA tăng, Volume đạt chuẩn, ADX
<= 35, RSI<= 65, H1 Close> H1 EMA. - Không xảy ra tín hiệu hai chiều đồng thời (
not ambiguousSignal) và thỏa điều kiệncanTrade.
4.2. Điều kiện vào lệnh Short
Vị thế Short (enterShort) được kích hoạt khi thỏa mãn toàn bộ các điều kiện sau:
tradeDirectioncho phép chiều bán ("Short"hoặc"Both"). Lưu ý: mặc định bot đang để"Long", cần đổi thành"Short"hoặc"Both"nếu muốn giao dịch chiều bán.- Xuất hiện Bearish Failed Break:
high > orHigh + sweepBuffer.- Nếu bật
requireFreshSweep:high[1] <= orHigh + sweepBuffer. - Giá đóng cửa quay lại vào trong OR:
close < orHigh - reclaimBuffervàclose > orLow. - Râu nến trên đạt tối thiểu
20%biên độ nến (upperWickRatio >= 0.20khi bậtrequireWick). - Vị trí đóng cửa đạt ngưỡng nếu bật
useClosePosition(closePosition <= 0.60).
- Xác nhận (nếu ở chế độ
Next Candle Confirmation):- Đang có
pendingShorthợp lệ trong vòng1đến4nến sau setup cùng ngày. - Đỉnh nến setup chưa bị phá lên trên
shortSetupHigh + 0.10 * ATR(nếu bậtcancelOnExtremeBreak). - Nến xác nhận là nến giảm (
close < openkhi bậtrequireConfirmCandle) vàclose < shortConfirmationLevel.
- Đang có
- Vượt qua các bộ lọc tùy chọn (nếu bật): EMA giảm, Volume đạt chuẩn, ADX
<= 35, RSI>= 35, H1 Close< H1 EMA. - Không xảy ra tín hiệu hai chiều đồng thời (
not ambiguousSignal) và thỏa điều kiệncanTrade.
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 kiểm soát canTrade:
- Nến đã đóng & khung hợp lệ:
barstate.isconfirmedvàvalidChartResolution(biểu đồ intraday có timeframe<=độ dài OR). - OR hợp lệ:
orLocked == truevàorValid == true. - Trạng thái tài khoản: Đang
flat(strategy.position_size == 0vàstrategy.opentrades == 0), không có lệnh mở trước đó trên cùng cây nến (freshEntryBar). - Giới hạn tần suất:
tradesToday < 2(maximumTradesPerDay = 2) và đã qua thời gian nghỉ sau lệnh đóng trước đó (bar_index - lastExitBar > 3). - Khung giờ giao dịch: Nằm trong khung
09:15 – 14:15(entrySessionOK), trong thời gian tìm setup<= 300phút sau OR (setupTimeOK), và 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 Ticks
CNPS91 sử dụng mức cắt lỗ cố định theo điểm số thị trường (stopLossPoints = 5.0) và tự động quy đổi sang đơn vị tick của hợp đồng VN30F1M (syminfo.mintick = 0.1):
$$\text{slTicks} = \max\left(1, \text{round}\left(\frac{\text{stopLossPoints}}{\text{syminfo.mintick}}\right)\right)$$
Với giá trị mặc định 5.0 điểm, slTicks = 50 ticks. Bot không sử dụng bộ lọc Min/Max Risk để chặn lệnh, và mức SL thực tế được vẽ trực tiếp trên biểu đồ thông qua biến longSL / shortSL khi đang có vị thế.
5.2. Cơ chế Take Profit và thoát lệnh theo thời gian
Tương tự Stop Loss, mức chốt lời mặc định là takeProfitPoints = 15.0 điểm (tpTicks = 150 ticks), tạo tỷ lệ Risk : Reward = 1 : 3.
- Không dùng Break Even và Trailing Stop: Trong mã nguồn không tích hợp cơ chế dời SL về hòa vốn hay trailing theo giá, giúp lệnh giữ nguyên kỳ vọng lợi nhuận 15 điểm hoặc chạm SL 5 điểm.
- Time Exit (tùy chọn, mặc định tắt): Khi bật
useTimeExit = true, nếu số nến nắm giữbarsHeld >= maximumHoldingBars(20nến), bot sẽ đóng toàn bộ vị thế bằngstrategy.close_all(immediately=true, comment="Time Exit"). - Force Close cuối phiên (luôn bật): Tại cây nến có
openMinutes < 14:45vàcloseMinutes >= 14:45(forceCloseBar), bot tự động đóng toàn bộ vị thế bằngstrategy.close_all(immediately=true, comment="Session End")để tránh rủi ro qua đêm (Overnight Gap).
5.3. Bảng tổng hợp cơ chế bảo vệ vị thế
| Cơ chế thoát lệnh | Trạng thái mặc định | Thông số / Điều kiện kích hoạt | Hành động thực thi |
|---|---|---|---|
| Stop Loss (Cắt lỗ cố định) | Luôn bật | stopLossPoints = 5.0 (50 ticks) | strategy.exit với loss=slTicks |
| Take Profit (Chốt lời cố định) | Luôn bật | takeProfitPoints = 15.0 (150 ticks) | strategy.exit với profit=tpTicks |
| Time Exit (Quá thời gian giữ) | Tắt (false) | barsHeld >= 20 nến và chưa tới 14:45 | strategy.close_all(immediately=true, comment="Time Exit") |
| Force Close (Đóng cuối phiên) | Luôn bật | Cây nến chạm mốc 14:45 (forceCloseBar) | strategy.close_all(immediately=true, comment="Session End") |
6. Hướng dẫn cài đặt và đọc bảng Diagnostics trên TradingView
Các bước cài đặt
- Mở biểu đồ hợp đồng VN30F1M trên TradingView và chọn khung thời gian intraday nhỏ hơn hoặc bằng
15phút (khuyến nghị5mhoặc3m). - Mở tab Pine Editor ở phía dưới màn hình, xóa mã mẫu mặc định.
- Sao chép toàn bộ mã nguồn CNPS91 OPENING RANGE FAILED BREAK V1 ở Mục 1, 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:
- Trong tab Inputs: Chọn
Trade Direction(Long,ShorthoặcBoth) theo nhu cầu. - Trong tab Properties: Kiểm tra lại
Order size(lưu ý hàmstrategy()đặtdefault_qty_value=1trong khi inputcontracts=3chỉ dùng để tham khảo cấu hình).
- Trong tab Inputs: Chọn
Cách đọc bảng chẩn đoán (Diagnostics Table)
Khi bật Show Diagnostics = true trong phần 11. Display, bot hiển thị bảng table.new ở góc trên bên phải (position.top_right) gồm 23 dòng thống kê toàn bộ quá trình vận hành:
- Dòng 0 – 5 (Trạng thái Opening Range): Hiển thị phiên bản (
CNPS91 V1/timeframe.period),OR Locked(YES/NO),OR Valid(YES/NO),OR Width(độ rộng OR bằng điểm),OR Days(tổng số ngày đã ghi nhận OR) vàInvalid OR Days(số ngày OR bị loại do thiếu nến hoặc sai độ rộng). - Dòng 6 – 11 (Thống kê Sweep & Confirm): Đếm số lần quét biên thô (
Long Sweeps,Short Sweeps), số lượng setup Failed Break hợp lệ đã lưu (Long Setups,Short Setups) và số lần đạt ngưỡng xác nhận (Long Confirms,Short Confirms). - Dòng 12 – 17 (Bộ lọc & Vào lệnh): Theo dõi số tín hiệu vượt qua bộ lọc (
Filtered Long/Short), số tín hiệu bị chặn do hết lượt/ngoài giờ/cooldown (Blocked Long/Short) và tổng số lệnh thực tế đã khớp (Long Entries,Short Entries). - Dòng 18 – 22 (Hết hạn & Trạng thái hiện tại): Số setup hết hạn hoặc bị phá cực trị (
Expired Long/Short), trạng thái chờ mua (Pending Long), số lệnh trong ngày (Trades Today, ví dụ1/2) và vị thế hiện tại (Position: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 qua ứng dụng TradingView, Telegram hoặc Webhook khi bot phát sinh tín hiệu:
- Nhấn vào biểu tượng Alert (Đồng hồ báo thức) trên thanh công cụ TradingView.
- Tại mục Condition, chọn CNPS91 OPENING RANGE FAILED BREAK V1.
- Tại mục Message, xóa nội dung cũ và nhập đúng cú pháp:
{{strategy.order.alert_message}}. - Đặt tên Alert và nhấn Create. (Nếu muốn tắt riêng cảnh báo SL/TP, bật tùy chọn
Disable SL/TP Alerts = truetrong Settings).
Bảng thông điệp Alert của CNPS91
| Sự kiện | Thông điệp Alert thực tế trong code |
|---|---|
| Vào lệnh Long | 🟢 VÀO VỊ THẾ LONG (CNPS91)\n🎯 Giá vào: <close>\n🛑 SL dự kiến: <SL>\n🎯 TP dự kiến: <TP> |
| Vào lệnh Short | 🔴 VÀO VỊ THẾ SHORT (CNPS91)\n🎯 Giá vào: <close>\n🛑 SL dự kiến: <SL>\n🎯 TP dự kiến: <TP> |
| Chốt lời Long | 💰 CHỐT LỜI LONG (TP HIT - CNPS91)\n🎯 Giá chốt: <close> |
| Cắt lỗ Long | 🛑 CẮT LỖ LONG (SL HIT - CNPS91)\n🎯 Giá cắt: <close> |
| Chốt lời Short | 💰 CHỐT LỜI SHORT (TP HIT - CNPS91)\n🎯 Giá chốt: <close> |
| Cắt lỗ Short | 🛑 CẮT LỜI SHORT (SL HIT - CNPS91)\n🎯 Giá cắt: <close> |
| Thoát lệnh quá thời gian | ⏱️ ĐÓNG VỊ THẾ QUÁ THỜI GIAN (Time Exit - CNPS91)\n🎯 Giá đóng: <close> |
| Đóng vị thế hết phiên | ⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End - CNPS91)\n🎯 Giá đóng: <close> |
Kết luận
CNPS91 Opening Range Failed Break V1 là hệ thống giao dịch có cấu trúc chặt chẽ, chuyên trị các pha quét thanh khoản giả quanh vùng giá mở cửa 09:00 – 09:15 trên VN30F1M. Chiến lược phát huy hiệu quả cao nhất trong những phiên thị trường có hiện tượng giật hai đầu, tạo bẫy phá vỡ đầu phiên rồi đảo chiều quay lại vùng cân bằng, nhờ bộ lọc râu nến từ chối và cơ chế chờ nến xác nhận giúp hạn chế bắt dao rơi sớm.
Bạn có thể tham khảo thêm các hệ thống giao dịch phái sinh khác như Bot CNPS50 - Trend Analysis V2 và Bot CNPS49 - Daily Open để đa dạng hóa góc nhìn phân tích.
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.





