Hướng Dẫn Sử Dụng Bot CNPS90 - Opening Range Breakout V2 cho VN30F1M
TradingviewBot CNPS90 Opening Range Breakout V2 xây dựng vùng giá mở cửa từ nến đã đóng, lọc phá vỡ bằng đệm ATR và độ mạnh thân nến, kết hợp cơ chế Re-arm chỉ nạp lại tín hiệu khi giá đóng cửa quay vào vùng OR cùng SL/TP cố định theo tick.

Mục lục
Khi giao dịch hợp đồng tương lai chỉ số VN30F1M, vùng giá mở cửa đầu phiên (Opening Range) thường đóng vai trò là vùng cân bằng cung – cầu quan trọng trong ngày. Tuy nhiên, nếu áp dụng chiến lược phá vỡ vùng mở cửa (Opening Range Breakout – ORB) truyền thống, trader rất dễ gặp hai vấn đề: hoặc bỏ lỡ các nhịp phá vỡ chất lượng sau khi giá kiểm tra lại vùng cân bằng, hoặc bị nhồi lệnh liên tục khi giá duy trì bên ngoài biên độ mở cửa.
CNPS90 OPENING RANGE BREAKOUT V2 (shorttitle="CNPS90 ORB V2") được viết bằng Pine Script v6 trên nền tảng TradingView để giải quyết triệt để bài toán này. Chiến lược xây dựng vùng Opening Range từ các cây nến đã đóng hoàn chỉnh, sử dụng bộ đệm ATR khi phá vỡ và áp dụng cơ chế Tiêu thụ – Tái nạp đạn (Consume & Re-arm) để chỉ cho phép tìm kiếm điểm vào mới sau khi giá thực sự đóng cửa quay trở lại bên trong vùng OR.
Những điểm nổi bật cốt lõi của Bot CNPS90 V2:
- Không dùng dữ liệu tương lai (No future-looking): Mọi tín hiệu đều tính trên nến đã đóng (
barstate.isconfirmed), kể cả bộ lọc xu hướng khung H1 sử dụng giá và EMA của nến H1 đã hoàn tất ([1]). - Cơ chế Re-arm kỷ luật: Sau một lần phá vỡ, hướng đó sẽ tự động khóa lại (
armedLong = falsehoặcarmedShort = false), không vào lệnh lặp lại khi giá vẫn ở ngoài OR, và chỉ kích hoạt lại khi giá đóng cửa trở lại bên trong OR đủ số nến quy định. - Bộ lọc chất lượng nến & đa lớp: Kiểm soát hướng nến, độ mạnh thân nến (
Body / Range), kết hợp tùy chọn lọc độ rộng OR theo ATR, EMA Trend, Relative Volume, ADX/DI và H1 Bias. - Quản trị rủi ro rõ ràng theo điểm/tick: Cố định Stop Loss (mặc định 5.0 điểm) và Take Profit (mặc định 15.0 điểm), hỗ trợ thoát lệnh theo thời gian nắm giữ và tự động tất toán cuối phiên trước giờ ATC (
14:45).
1. CNPS90 Opening Range Breakout V2 là gì?
CNPS90 Opening Range Breakout V2 là hệ thống giao dịch theo đà phá vỡ vùng giá mở cửa đầu ngày, được thiết kế với 4 trụ cột kỹ thuật chính:
- Xây dựng và khóa vùng Opening Range (
09:00–09:15): Thu thập giá cao nhất (orHigh) và thấp nhất (orLow) từ các nến đã đóng trong khung giờ thiết lập, sau đó khóa cứng biên độ khi bước sang giai đoạnafterORvà kiểm tra tính hợp lệ của độ rộng vùng OR (tùy chọn lọc theo tỷ lệOR Width / ATR). - Xác nhận phá vỡ có đệm & chất lượng nến: Mức phá vỡ được cộng/trừ thêm lớp đệm
breakoutBuffer(mặc định0.05 × ATR(14)) để hạn chế nhiễu quét biên. Nến phá vỡ phải thỏa mãn đồng thời điều kiện đóng cửa vượt ngưỡng, đúng hướng nến (tăng/giảm) và tỷ lệ thân nến tối thiểu (0.35). - Cơ chế Re-entry / Re-arm thông minh: Mỗi hướng giao dịch được phép thử phá vỡ tối đa
maximumAttemptsPerDirectionlần/ngày (mặc định3). Ngay khi xuất hiện sự kiện phá vỡ, trạng thái sẵn sàng của hướng đó bị tiêu thụ và chỉ được nạp lại nếu giá đóng cửa quay vào trong vùng OR đủrearmInsideBarsnến liên tiếp. - Hệ thống lọc đa lớp & kiểm soát rủi ro chặt chẽ: Tích hợp các bộ lọc tùy chọn (EMA Trend, Volume tương đối, ADX/DI, H1 EMA Bias), giới hạn tối đa
3lệnh/ngày, thời gian nghỉ sau khi đóng lệnh (cooldownBars = 1), cùng SL/TP cố định quy đổi sang tick và đóng vị thế bắt buộc lúc14:45.
Bảng thông số mặc định
| Nhóm thông số | Tên tham số trong code | Giá trị mặc định | Ý nghĩa |
|---|---|---|---|
| 01. Opening Range | orStartHour / orStartMinute | 9 / 0 | Giờ bắt đầu xây dựng vùng OR (09:00) |
orEndHour / orEndMinute | 9 / 15 | Giờ kết thúc và khóa vùng OR (09:15) | |
atrLength | 14 | Chu kỳ tính chỉ báo ATR | |
useORWidthFilter | false | Bật/tắt lọc độ rộng vùng OR theo ATR | |
minimumORWidthATR / maximumORWidthATR | 0.20 / 6.00 | Biên độ OR Width / ATR tối thiểu và tối đa | |
| 02. Breakout | maximumBreakoutMinutes | 300 | Thời gian tối đa sau OR cho phép tìm điểm phá vỡ (phút) |
useBreakoutBuffer / breakoutBufferATR | true / 0.05 | Bật đệm phá vỡ theo 0.05 × ATR | |
requireCandleDirection | true | Yêu cầu nến Long là nến tăng, nến Short là nến giảm | |
useBodyFilter / minimumBodyRatio | true / 0.35 | Lọc tỷ lệ thân nến tối thiểu 35% biên độ nến | |
useCloseLocation | false | Bật/tắt lọc vị trí giá đóng cửa gần cực trị nến | |
minimumLongClosePosition / maximumShortClosePosition | 0.65 / 0.35 | Ngưỡng vị trí đóng cửa cho Long (≥ 0.65) và Short (≤ 0.35) | |
| 03. Breakout Re-arm | allowReentry | true | Cho phép nạp lại tín hiệu sau khi giá quay vào vùng OR |
rearmInsideBars | 1 | Số nến đóng cửa liên tiếp trong OR để Re-arm | |
useRearmMargin / rearmMarginATR | false / 0.05 | Yêu cầu giá vào sâu trong OR thêm một khoảng đệm ATR | |
maximumAttemptsPerDirection | 3 | Số lần thử phá vỡ tối đa cho mỗi chiều trong ngày | |
| 04. EMA Trend | useEMAFilter / emaLength / emaSlopeBars | false / 50 / 3 | Bộ lọc xu hướng EMA(50) dốc lên/xuống so với 3 nến trước |
requirePriceEMA | false | Yêu cầu giá đóng cửa nằm trên/dưới EMA | |
| 05. Optional Filters | useVolumeFilter / volumeLength / volumeFactor | false / 20 / 1.0 | Lọc khối lượng tương đối so với SMA(20) của volume[1] |
useADXFilter / diLength / adxSmoothing / minimumADX | false / 14 / 14 / 18.0 | Bộ lọc sức mạnh xu hướng ADX tối thiểu 18.0 | |
requireDIDirection | false | Yêu cầu DI+ > DI- (Long) hoặc DI- > DI+ (Short) | |
| 06. H1 Bias | useH1Bias / h1EMALength | false / 50 | Bộ lọc xu hướng khung H1 (close[1] so với EMA(50)[1]) |
| 07. Risk Management | stopLossPoints / takeProfitPoints | 5.0 / 15.0 | Cắt lỗ 5.0 điểm, chốt lời 15.0 điểm (tỷ lệ R:R 1:3) |
useTimeExit / maximumHoldingBars | false / 20 | Thoát lệnh theo thời gian nếu giữ quá 20 nến | |
| 08. Trade Control | tradeDirection | "Long" | Chiều giao dịch mặc định ("Long", "Short", hoặc "Both") |
contracts | 3 | Số hợp đồng hiển thị cấu hình (lệnh mặc định dùng default_qty_value=1 trong strategy) | |
maximumTradesPerDay | 3 | Tổng số lệnh vào tối đa trong ngày | |
cooldownBars | 1 | Số nến nghỉ tối thiểu sau khi đóng lệnh | |
| 09. Trading Session | useSessionFilter / tz | true / "Asia/Ho_Chi_Minh" | Bật lọc phiên theo múi giờ Việt Nam |
startHour:startMinute – lastHour:lastMinute | 09:15 – 14:15 | Khung giờ cho phép mở vị thế mới | |
endHour:endMinute | 14:45 | Thời điểm bắt buộc đóng toàn bộ vị thế (Force Close) | |
| 10. Alerts | disableExitAlerts | false | Cho phép gửi cảnh báo SL/TP khi khớp lệnh thoát |
| 11. Display | showEMA, showOpeningRange, showEntryMarkers, showSLTP | true | Hiển thị EMA, biên OR, mũi tên vào lệnh và đường SL/TP |
showDiagnostics | false | Bật/tắt bảng thống kê chẩn đoán góc trên bên phải |
Source Code CNPS90 Opening Range Breakout V2
Bạn có thể sao chép toàn bộ mã nguồn Pine Script v6 dưới đây để dán trực tiếp vào Pine Editor trên TradingView:
//@version=6
strategy(title="CNPS90 OPENING RANGE BREAKOUT V2", shorttitle="CNPS90 ORB V2", overlay=true, initial_capital=100000000, default_qty_type=strategy.fixed, default_qty_value=1, pyramiding=0, margin_long=0, margin_short=0, slippage=0, commission_type=strategy.commission.cash_per_contract, commission_value=0, fill_orders_on_standard_ohlc=true, process_orders_on_close=true, calc_on_order_fills=false, max_labels_count=300, max_lines_count=300, max_bars_back=5000)
// ============================================================================
// CNPS90 V2 - OPENING RANGE BREAKOUT RE-ENTRY
//
// 1. Build the opening range from completed candles.
// 2. Freeze OR High / OR Low.
// 3. Enter on a confirmed directional breakout.
// 4. Consume the breakout attempt for that direction.
// 5. Re-arm only after price CLOSES back inside the OR.
// 6. Allow another breakout within the daily limits.
//
// V2 focuses on increasing valid trade opportunities
// without allowing repeated entries while price
// remains continuously outside the range.
//
// No future-looking price data.
// Confirmed-bar entry signals.
// Fixed SL / TP in ticks.
// ============================================================================
// ============================================================================
// 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. BREAKOUT
// ============================================================================
gBreakout = "02. Breakout"
maximumBreakoutMinutes = input.int(300, "Maximum Minutes After OR", minval=5, maxval=480, step=5, group=gBreakout)
useBreakoutBuffer = input.bool(true, "Use Breakout Buffer", group=gBreakout)
breakoutBufferATR = input.float(0.05, "Breakout Buffer / ATR", minval=0.0, step=0.05, group=gBreakout)
requireCandleDirection = input.bool(true, "Require Bullish / Bearish Candle", group=gBreakout)
useBodyFilter = input.bool(true, "Use Body Strength Filter", group=gBreakout)
minimumBodyRatio = input.float(0.35, "Minimum Candle Body / Range", minval=0.0, maxval=1.0, step=0.05, group=gBreakout)
useCloseLocation = input.bool(false, "Require Close Near Candle Extreme", group=gBreakout)
minimumLongClosePosition = input.float(0.65, "Minimum Long Close Position", minval=0.5, maxval=1.0, step=0.05, group=gBreakout)
maximumShortClosePosition = input.float(0.35, "Maximum Short Close Position", minval=0.0, maxval=0.5, step=0.05, group=gBreakout)
// ============================================================================
// 03. RE-ENTRY / RE-ARM
// ============================================================================
gRearm = "03. Breakout Re-arm"
allowReentry = input.bool(true, "Allow New Breakout After OR Re-entry", group=gRearm)
rearmInsideBars = input.int(1, "Consecutive Closes Inside OR", minval=1, maxval=20, group=gRearm)
useRearmMargin = input.bool(false, "Require Distance Inside OR", group=gRearm)
rearmMarginATR = input.float(0.05, "Re-arm Margin / ATR", minval=0.0, step=0.05, group=gRearm)
maximumAttemptsPerDirection = input.int(3, "Maximum Breakout Attempts / Direction / Day", minval=1, maxval=20, group=gRearm)
// ============================================================================
// 04. EMA TREND
// ============================================================================
gTrend = "04. EMA Trend"
useEMAFilter = input.bool(false, "Use EMA Trend Filter", group=gTrend)
emaLength = input.int(50, "EMA Length", minval=2, group=gTrend)
emaSlopeBars = input.int(3, "EMA Slope Lookback", minval=1, maxval=50, group=gTrend)
requirePriceEMA = input.bool(false, "Require Price Above / Below EMA", group=gTrend)
// ============================================================================
// 05. OPTIONAL FILTERS
// ============================================================================
gFilters = "05. Optional Filters"
useVolumeFilter = input.bool(false, "Use Relative Volume Filter", group=gFilters)
volumeLength = input.int(20, "Volume MA Length", minval=2, group=gFilters)
volumeFactor = 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 DI Direction", 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(3, "Maximum Trades Per Day", minval=1, maxval=20, group=gTrade)
cooldownBars = input.int(1, "Cooldown After Exit (Bars)", minval=0, maxval=100, group=gTrade)
bool allowLong = (tradeDirection == "Long" or tradeDirection == "Both")
bool allowShort = (tradeDirection == "Short" or tradeDirection == "Both")
// ============================================================================
// 09. TRADING SESSION
// ============================================================================
gSession = "09. Trading Session"
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 Building", group=gDisplay)
showRawBreakoutMarkers = input.bool(false, "Show Breakout Attempt Dots", group=gDisplay)
showRearmMarkers = input.bool(false, "Show Re-arm Markers", 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 breakoutTimeOK = (afterOR and closeMinutes <= orEndMinutes + maximumBreakoutMinutes)
bool entrySessionOK = (not useSessionFilter or (openMinutes >= entryStartMinutes and closeMinutes <= lastEntryMinutes))
bool beforeForceClose = (closeMinutes < forceCloseMinutes)
bool forceCloseBar = (openMinutes < forceCloseMinutes and closeMinutes >= forceCloseMinutes)
// ============================================================================
// 13. DAILY STATE
// ============================================================================
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. INDICATORS
// ============================================================================
float atr = ta.atr(atrLength)
float ema = ta.ema(close, emaLength)
float avgVolume = ta.sma(volume[1], volumeLength)
float relativeVolume = (not na(volume) and not na(avgVolume) and avgVolume > 0 ? volume / avgVolume : na)
[diPlus, diMinus, adx] = ta.dmi(diLength, adxSmoothing)
// ============================================================================
// 15. OPENING RANGE STATE
// ============================================================================
var float orHigh = na
var float orLow = na
var float orWidth = na
var float orWidthATR = na
var int orBars = 0
var bool orLocked = false
var bool orWidthOK = false
var bool armedLong = false
var bool armedShort = false
var int longAttemptsToday = 0
var int shortAttemptsToday = 0
var int consecutiveInsideBars = 0
var int totalORDays = 0
var int rejectedORDays = 0
var int totalLongAttempts = 0
var int totalShortAttempts = 0
var int totalRearms = 0
if newDay
orHigh := na
orLow := na
orWidth := na
orWidthATR := na
orBars := 0
orLocked := false
orWidthOK := false
armedLong := false
armedShort := false
longAttemptsToday := 0
shortAttemptsToday := 0
consecutiveInsideBars := 0
// ============================================================================
// 16. BUILD OPENING RANGE
// ============================================================================
if (barstate.isconfirmed and insideOR and not orLocked)
orHigh := (na(orHigh) ? high : math.max(orHigh, high))
orLow := (na(orLow) ? low : math.min(orLow, low))
orBars += 1
// ============================================================================
// 17. FREEZE OPENING RANGE
// ============================================================================
if (barstate.isconfirmed and afterOR and not orLocked and orBars > 0)
orLocked := true
orWidth := orHigh - orLow
orWidthATR := (not na(atr) and atr > 0 ? orWidth / atr : na)
orWidthOK := (orWidth > 0 and (not useORWidthFilter or (not na(orWidthATR) and orWidthATR >= minimumORWidthATR and orWidthATR <= maximumORWidthATR)))
armedLong := orWidthOK
armedShort := orWidthOK
totalORDays += 1
if not orWidthOK
rejectedORDays += 1
// ============================================================================
// 18. BREAKOUT LEVELS
// ============================================================================
float breakoutBuffer = (useBreakoutBuffer and not na(atr) ? atr * breakoutBufferATR : 0.0)
float longBreakLevel = (orLocked and not na(orHigh) ? orHigh + breakoutBuffer : na)
float shortBreakLevel = (orLocked and not na(orLow) ? orLow - breakoutBuffer : na)
// ============================================================================
// 19. RAW BREAKOUT EVENT
// ============================================================================
//
// A breakout is counted only if:
// - OR is locked.
// - Its direction is armed.
// - Price crosses beyond the OR boundary.
// - The directional attempt limit is available.
//
// Price cannot repeatedly generate breakouts
// while remaining outside the range.
//
// ============================================================================
bool longBreakoutEvent = (barstate.isconfirmed and orLocked and orWidthOK and breakoutTimeOK and armedLong and longAttemptsToday < maximumAttemptsPerDirection and not na(longBreakLevel) and close > longBreakLevel and close[1] <= longBreakLevel)
bool shortBreakoutEvent = (barstate.isconfirmed and orLocked and orWidthOK and breakoutTimeOK and armedShort and shortAttemptsToday < maximumAttemptsPerDirection and not na(shortBreakLevel) and close < shortBreakLevel and close[1] >= shortBreakLevel)
// ============================================================================
// 20. CANDLE CONFIRMATION
// ============================================================================
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)
// ============================================================================
// 21. EMA TREND
// ============================================================================
bool emaUp = (not na(ema[emaSlopeBars]) and ema > ema[emaSlopeBars])
bool emaDown = (not na(ema[emaSlopeBars]) and ema < ema[emaSlopeBars])
bool longTrendOK = (not useEMAFilter or (emaUp and (not requirePriceEMA or close > ema)))
bool shortTrendOK = (not useEMAFilter or (emaDown and (not requirePriceEMA or close < ema)))
// ============================================================================
// 22. ADX / VOLUME
// ============================================================================
bool volumeOK = (not useVolumeFilter or (not na(relativeVolume) and relativeVolume >= volumeFactor))
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))
// ============================================================================
// 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. BASE AND FILTERED SIGNALS
// ============================================================================
bool longBase = (longBreakoutEvent and longCandleOK and bodyOK and longCloseOK)
bool shortBase = (shortBreakoutEvent and shortCandleOK and bodyOK and shortCloseOK)
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)
// ============================================================================
// 26. ENTRY GATES
// ============================================================================
bool canTrade = (barstate.isconfirmed and validChartResolution and orLocked and orWidthOK and flat and strategy.opentrades == 0 and tradesToday < maximumTradesPerDay and cooldownOK and freshEntryBar and entrySessionOK and beforeForceClose and breakoutTimeOK)
bool enterLong = (canTrade and allowLong and rawLong and not rawShort)
bool enterShort = (canTrade and allowShort and rawShort and not rawLong)
// ============================================================================
// 27. RISK 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
// ============================================================================
// 28. DIAGNOSTICS COUNTERS
// ============================================================================
var int longBaseCount = 0
var int shortBaseCount = 0
var int filteredLongCount = 0
var int filteredShortCount = 0
var int blockedLongCount = 0
var int blockedShortCount = 0
var int longEntryCount = 0
var int shortEntryCount = 0
// ============================================================================
// 29. LONG ENTRY
// ============================================================================
if enterLong
strategy.entry("Long", strategy.long, comment="ORB Re-entry LONG", alert_message="🟢 VÀO VỊ THẾ LONG (CNPS90)\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\n🛑 Cắt lỗ (SL): " + str.tostring(close - effectiveSL, format.mintick) + "\n💰 Chốt lời (TP): " + str.tostring(close + effectiveTP, format.mintick))
tradesToday += 1
longEntryCount += 1
lastEntryBar := bar_index
// ============================================================================
// 30. SHORT ENTRY
// ============================================================================
if enterShort
strategy.entry("Short", strategy.short, comment="ORB Re-entry SHORT", alert_message="🔴 VÀO VỊ THẾ SHORT (CNPS90)\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\n🛑 Cắt lỗ (SL): " + str.tostring(close + effectiveSL, format.mintick) + "\n💰 Chốt lời (TP): " + str.tostring(close - effectiveTP, format.mintick))
tradesToday += 1
shortEntryCount += 1
lastEntryBar := bar_index
// ============================================================================
// 31. CONSUME BREAKOUT ATTEMPTS
// ============================================================================
if barstate.isconfirmed
if longBreakoutEvent
armedLong := false
longAttemptsToday += 1
totalLongAttempts += 1
if shortBreakoutEvent
armedShort := false
shortAttemptsToday += 1
totalShortAttempts += 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
// ============================================================================
// 32. RE-ARM AFTER RETURN INTO OR
// ============================================================================
//
// Price MUST close back inside the OR.
//
// Re-arm never happens on an outside candle.
// Optional margin makes re-arm more conservative.
//
// Both directions may be armed independently.
//
// ============================================================================
float rearmMargin = (useRearmMargin and not na(atr) ? atr * rearmMarginATR : 0.0)
bool priceInsideOR = (orLocked and not na(orHigh) and not na(orLow) and close < orHigh - rearmMargin and close > orLow + rearmMargin)
bool rearmedThisBar = false
if barstate.isconfirmed and orLocked
if priceInsideOR
consecutiveInsideBars += 1
else
consecutiveInsideBars := 0
bool enoughInsideBars = (consecutiveInsideBars >= rearmInsideBars)
if (allowReentry and enoughInsideBars and breakoutTimeOK and orWidthOK)
if (not armedLong and longAttemptsToday < maximumAttemptsPerDirection)
armedLong := true
rearmedThisBar := true
if (not armedShort and shortAttemptsToday < maximumAttemptsPerDirection)
armedShort := true
rearmedThisBar := true
if rearmedThisBar
totalRearms += 1
// ============================================================================
// 33. 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 (CNPS90 - TP HIT)\n🎯 Giá chốt lời: " + str.tostring(strategy.position_avg_price + effectiveTP, format.mintick), alert_loss="🛑 CẮT LỖ LONG (CNPS90 - SL HIT)\n💥 Giá cắt lỗ: " + str.tostring(strategy.position_avg_price - effectiveSL, format.mintick), disable_alert=disableExitAlerts)
// ============================================================================
// 34. 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 (CNPS90 - TP HIT)\n🎯 Giá chốt lời: " + str.tostring(strategy.position_avg_price - effectiveTP, format.mintick), alert_loss="🛑 CẮT LỖ SHORT (CNPS90 - SL HIT)\n💥 Giá cắt lỗ: " + str.tostring(strategy.position_avg_price + effectiveSL, format.mintick), disable_alert=disableExitAlerts)
// ============================================================================
// 35. TIME EXIT
// ============================================================================
int barsHeld = (strategy.opentrades > 0 ? bar_index - strategy.opentrades.entry_bar_index(0) : 0)
bool timeExit = (useTimeExit and strategy.position_size != 0 and barsHeld >= maximumHoldingBars and barstate.isconfirmed)
if timeExit and not forceCloseBar
strategy.close_all(immediately=true, comment="Time Exit", alert_message="⏱️ ĐÓNG VỊ THẾ HẾT THỜI GIAN (CNPS90 - Time Exit)\n📌 Giá đóng: " + str.tostring(close, format.mintick))
// ============================================================================
// 36. SESSION FORCE CLOSE
// ============================================================================
if (barstate.isconfirmed and forceCloseBar and strategy.position_size != 0)
strategy.close_all(immediately=true, comment="Session End", alert_message="⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (CNPS90 - Session End)\n📌 Giá đóng: " + str.tostring(close, format.mintick))
// ============================================================================
// 37. EMA PLOT
// ============================================================================
plot(showEMA ? ema : na, title="EMA Trend", color=color.orange, linewidth=2)
// ============================================================================
// 38. 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")
// ============================================================================
// 39. OPTIONAL MARKERS
// ============================================================================
plotshape(showRawBreakoutMarkers and longBreakoutEvent, title="Long Breakout Attempt", style=shape.circle, location=location.belowbar, color=color.aqua, size=size.tiny, text="BO")
plotshape(showRawBreakoutMarkers and shortBreakoutEvent, title="Short Breakout Attempt", style=shape.circle, location=location.abovebar, color=color.orange, size=size.tiny, text="BO")
plotshape(showRearmMarkers and rearmedThisBar, title="ORB Re-armed", style=shape.circle, location=location.bottom, color=color.gray, size=size.tiny, text="RE")
// ============================================================================
// 40. ENTRY MARKERS
// ============================================================================
plotshape(showEntryMarkers and enterLong, title="CNPS90 V2 LONG", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, text="LONG", textcolor=color.white)
plotshape(showEntryMarkers and enterShort, title="CNPS90 V2 SHORT", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small, text="SHORT", textcolor=color.white)
// ============================================================================
// 41. 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)
// ============================================================================
// 42. DATA WINDOW
// ============================================================================
plot(orWidth, title="OR Width (Points)", 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="Breakout Body Ratio", color=color.orange, display=display.data_window)
plot(atr, title="ATR", color=color.gray, display=display.data_window)
plot(adx, title="ADX", color=color.purple, display=display.data_window)
// ============================================================================
// 43. DIAGNOSTICS
// ============================================================================
var table diagnostics = table.new(position.top_right, 2, 22, border_width=1)
if showDiagnostics and barstate.islast
table.cell(diagnostics, 0, 0, "CNPS90 V2")
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 Bars")
table.cell(diagnostics, 1, 2, str.tostring(orBars))
table.cell(diagnostics, 0, 3, "OR Width")
table.cell(diagnostics, 1, 3, str.tostring(orWidth, "#.##"))
table.cell(diagnostics, 0, 4, "OR Width / ATR")
table.cell(diagnostics, 1, 4, str.tostring(orWidthATR, "#.##"))
table.cell(diagnostics, 0, 5, "OR Valid")
table.cell(diagnostics, 1, 5, orWidthOK ? "YES" : "NO")
table.cell(diagnostics, 0, 6, "OR Days")
table.cell(diagnostics, 1, 6, str.tostring(totalORDays))
table.cell(diagnostics, 0, 7, "Rejected OR")
table.cell(diagnostics, 1, 7, str.tostring(rejectedORDays))
table.cell(diagnostics, 0, 8, "Long Attempts")
table.cell(diagnostics, 1, 8, str.tostring(totalLongAttempts))
table.cell(diagnostics, 0, 9, "Short Attempts")
table.cell(diagnostics, 1, 9, str.tostring(totalShortAttempts))
table.cell(diagnostics, 0, 10, "Re-arms")
table.cell(diagnostics, 1, 10, str.tostring(totalRearms))
table.cell(diagnostics, 0, 11, "Long Bases")
table.cell(diagnostics, 1, 11, str.tostring(longBaseCount))
table.cell(diagnostics, 0, 12, "Short Bases")
table.cell(diagnostics, 1, 12, str.tostring(shortBaseCount))
table.cell(diagnostics, 0, 13, "Filtered Long")
table.cell(diagnostics, 1, 13, str.tostring(filteredLongCount))
table.cell(diagnostics, 0, 14, "Filtered Short")
table.cell(diagnostics, 1, 14, str.tostring(filteredShortCount))
table.cell(diagnostics, 0, 15, "Blocked Long")
table.cell(diagnostics, 1, 15, str.tostring(blockedLongCount))
table.cell(diagnostics, 0, 16, "Blocked Short")
table.cell(diagnostics, 1, 16, str.tostring(blockedShortCount))
table.cell(diagnostics, 0, 17, "Long Entries")
table.cell(diagnostics, 1, 17, str.tostring(longEntryCount))
table.cell(diagnostics, 0, 18, "Short Entries")
table.cell(diagnostics, 1, 18, str.tostring(shortEntryCount))
table.cell(diagnostics, 0, 19, "Armed Long / Short")
table.cell(diagnostics, 1, 19, (armedLong ? "Y" : "N") + " / " + (armedShort ? "Y" : "N"))
table.cell(diagnostics, 0, 20, "Trades Today")
table.cell(diagnostics, 1, 20, str.tostring(tradesToday) + "/" + str.tostring(maximumTradesPerDay))
table.cell(diagnostics, 0, 21, "Position")
table.cell(diagnostics, 1, 21, inLong ? "LONG" : inShort ? "SHORT" : "FLAT")
2. Những khái niệm kỹ thuật cốt lõi trong CNPS90
2.1. Xây dựng vùng Opening Range và kiểm định khung thời gian (Time Engine)
Bot kiểm tra chặt chẽ điều kiện biểu đồ trước khi tính toán vùng OR:
- Biểu đồ phải là khung trong ngày (
timeframe.isintraday), giờ kết thúc OR phải lớn hơn giờ bắt đầu (orEndMinutes > orStartMinutes), và chu kỳ nến của biểu đồ không được lớn hơn độ dài vùng OR (timeframe.in_seconds() <= (orEndMinutes - orStartMinutes) * 60). Với mặc định09:00–09:15, bạn có thể chạy tốt trên các khung1m,3m,5m, hoặc15m. - Trong suốt khoảng
insideOR, các nến đã đóng sẽ liên tục cập nhậtorHigh = math.max(orHigh, high)vàorLow = math.min(orLow, low). Khi nến đầu tiên sau09:15đóng cửa (afterOR), vùng OR được khóa cứng (orLocked := true) và tínhorWidth = orHigh - orLow,orWidthATR = orWidth / ta.atr(14). Nếu bậtuseORWidthFilter,orWidthATRphải nằm trong[0.20, 6.00].
2.2. Mức phá vỡ có đệm ATR và xác nhận chất lượng nến
Thay vì kích hoạt ngay khi giá chạm orHigh hoặc orLow, CNPS90 V2 cộng thêm khoảng đệm biến động breakoutBuffer = atr * breakoutBufferATR (mặc định 0.05 × ATR(14)):
longBreakLevel = orHigh + breakoutBuffershortBreakLevel = orLow - breakoutBuffer
Đồng thời, nến phá vỡ được đánh giá chất lượng qua 3 thước đo:
- Hướng nến: Long yêu cầu
close > open, Short yêu cầuclose < open. - Tỷ lệ thân nến (
bodyRatio):|close - open| / (high - low) ≥ 0.35, đảm bảo lực đẩy dứt khoát thay vì nến Doji râu dài. - Vị trí đóng cửa (
closePosition):(close - low) / (high - low). Nếu bậtuseCloseLocation, nến Long cần đóng ở phần trên (≥ 0.65) và nến Short cần đóng ở phần dưới (≤ 0.35).
2.3. Cơ chế Consume & Re-arm và bộ lọc xu hướng/động lượng
Điểm khác biệt lớn nhất của CNPS90 V2 là vòng đời trạng thái armedLong / armedShort:
- Ngay khi xảy ra
longBreakoutEventhoặcshortBreakoutEvent, hướng tương ứng bị tiêu thụ (armedLong := false/armedShort := false) bất kể lệnh có bị chặn bởi các bộ lọc phụ hay không. - Để được nạp lại (
rearmedThisBar), giá bắt buộc phải đóng cửa quay vào bên trong vùng OR (close < orHigh - rearmMarginvàclose > orLow + rearmMargin) đủrearmInsideBarsnến liên tiếp.
Ngoài ra, bot cung cấp các bộ lọc tùy chọn (mặc định tắt để giữ sự tinh gọn):
- EMA Trend: Kiểm tra độ dốc
ema > ema[3](hoặc<cho Short) vớiEMA(50)và tùy chọn giá nằm trên/dưới EMA. - Relative Volume:
volume / ta.sma(volume[1], 20) ≥ 1.0. - ADX / DI:
ADX(14, 14) ≥ 18.0và tùy chọnDI+ > DI-/DI- > DI+. - Confirmed H1 Bias: Dùng
request.security(..., "60", ...[1], lookahead=barmerge.lookahead_on)để lấyclose[1]vàEMA(50)[1]của nến H1 đã đóng hoàn chỉnh (chỉ áp dụng trên khung nhỏ hơn H1).
3. Nguyên lý hoạt động của CNPS90
Quy trình vận hành khép kín trong mỗi phiên giao dịch của Bot CNPS90 V2 diễn ra theo 5 bước tuần tự:
- Khởi tạo đầu ngày (
newDay): Reset toàn bộ biến trạng thái trong ngày gồmtradesToday = 0,orHigh/orLow = na,orLocked = false,armedLong/armedShort = false,longAttemptsToday/shortAttemptsToday = 0,consecutiveInsideBars = 0. - Xây dựng & Khóa Opening Range: Thu thập biên độ giá trong khung
09:00–09:15. Sau09:15, khóaorHigh/orLow, kiểm traorWidthOK, và kích hoạtarmedLong = true,armedShort = true. - Phát hiện phá vỡ & Tiêu thụ lượt thử: Khi giá đóng cửa cắt qua
longBreakLevel(từ dưới lên) hoặcshortBreakLevel(từ trên xuống) trong thời gianbreakoutTimeOK(≤ 300phút sau OR), sự kiện phá vỡ được ghi nhận và trạng tháiarmedcủa chiều đó lập tức chuyển vềfalse. - Xác nhận bộ lọc & Gửi lệnh: Tín hiệu đi qua lớp xác nhận nến (
longBase/shortBase), các bộ lọc xu hướng/khối lượng (rawLong/rawShort), và cổng kiểm soát giao dịch (canTrade). Nếu thỏa mãn và không xung đột hai chiều, bot gửi lệnhstrategy.entry. - Quản trị & Tái nạp đạn: Trong khi nắm giữ vị thế, lệnh
strategy.exittự động đặt SL/TP theo tick. Song song đó, nếu giá quay đầu đóng cửa vào trong vùng OR đủ số nến quy định và chưa hết lượt thử trong ngày, bot sẽ nạp lại trạng tháiarmedđể sẵn sàng cho nhịp phá vỡ tiếp theo. Cuối phiên lúc14:45, mọi vị thế mở sẽ bị đóng tự động.
4. Điều kiện vào lệnh Long và Short của CNPS90
4.1. Điều kiện vào lệnh Long
Lệnh Long (enterLong) được kích hoạt khi thỏa mãn đồng thời các điều kiện sau trên nến đã đóng (barstate.isconfirmed):
- Biểu đồ cho phép giao dịch chiều Long (
tradeDirectionlà"Long"hoặc"Both"— lưu ý mặc định trong code là"Long"). - Xuất hiện
longBreakoutEvent: Vùng OR đã khóa (orLocked), độ rộng hợp lệ (orWidthOK), còn trong thời gian phá vỡ (breakoutTimeOK), đang ở trạng thái sẵn sàng (armedLong), số lần thử Long trong ngày< maximumAttemptsPerDirection(3), và giá đóng cửa cắt lên mức đệm:close > longBreakLevelvớiclose[1] <= longBreakLevel. - Thỏa mãn xác nhận nến (
longBase): Nến tăng (close > open, nếu bậtrequireCandleDirection), tỷ lệ thân nếnbodyRatio ≥ 0.35(nếu bậtuseBodyFilter), và vị trí đóng cửaclosePosition ≥ 0.65(nếu bậtuseCloseLocation). - Thỏa mãn các bộ lọc tùy chọn đang bật (
rawLong): EMA dốc lên (longTrendOK), khối lượng tương đối đạt chuẩn (volumeOK), ADX đạt ngưỡng (adxOK),DI+ > DI-(longDIOK), và giá H1 trên EMA H1 (longH1OK). - Không đồng thời xuất hiện tín hiệu
rawShort(not rawShort) và vượt qua toàn bộ cổng kiểm soátcanTrade.
4.2. Điều kiện vào lệnh Short
Lệnh Short (enterShort) được kích hoạt khi thỏa mãn đồng thời các điều kiện sau trên nến đã đóng:
- Biểu đồ cho phép giao dịch chiều Short (
tradeDirectionlà"Short"hoặc"Both"). - Xuất hiện
shortBreakoutEvent: Vùng OR đã khóa, độ rộng hợp lệ, còn trongbreakoutTimeOK, đang sẵn sàng (armedShort),shortAttemptsToday < 3, và giá đóng cửa cắt xuống dưới mức đệm:close < shortBreakLevelvớiclose[1] >= shortBreakLevel. - Thỏa mãn xác nhận nến (
shortBase): Nến giảm (close < open, nếu bậtrequireCandleDirection),bodyRatio ≥ 0.35(nếu bậtuseBodyFilter), vàclosePosition ≤ 0.35(nếu bậtuseCloseLocation). - Thỏa mãn các bộ lọc tùy chọn đang bật (
rawShort): EMA dốc xuống (shortTrendOK),volumeOK,adxOK,DI- > DI+(shortDIOK), và giá H1 dưới EMA H1 (shortH1OK). - Không đồng thời xuất hiện tín hiệu
rawLong(not rawLong) và vượt qua cổng kiểm soátcanTrade.
4.3. Điều kiện kiểm soát giao dịch chung (canTrade)
Mọi lệnh vào mới đều phải vượt qua hàng rào kiểm soát canTrade:
- Không nhồi lệnh: Vị thế hiện tại phải phẳng (
strategy.position_size == 0vàstrategy.opentrades == 0), đồng thời không vào 2 lệnh trên cùng một cây nến (freshEntryBar). - Giới hạn tần suất ngày:
tradesToday < maximumTradesPerDay(mặc định tối đa3lệnh/ngày). - Thời gian nghỉ (Cooldown): Số nến kể từ lần thoát lệnh gần nhất phải lớn hơn
cooldownBars(bar_index - lastExitBar > 1). - Khung giờ giao dịch: Nếu bật
useSessionFilter, nến phải nằm trong khung09:15–14:15(entrySessionOK), trước giờ đóng phiên14:45(beforeForceClose), và không vượt quámaximumBreakoutMinutes(300phút sau09:15).
5. Quản trị Stop Loss, Take Profit và Thoát lệnh
5.1. Cơ chế Stop Loss và quy đổi Risk theo Tick
CNPS90 V2 sử dụng mức cắt lỗ và chốt lời cố định theo điểm số, sau đó làm tròn và quy đổi chính xác sang đơn vị tick nhỏ nhất của sản phẩm (syminfo.mintick, với VN30F1M là 0.1 điểm):
slTicks = math.max(1, int(math.round(stopLossPoints / syminfo.mintick)))→ Mặc định5.0 / 0.1 = 50ticks (effectiveSL = 5.0điểm).tpTicks = math.max(1, int(math.round(takeProfitPoints / syminfo.mintick)))→ Mặc định15.0 / 0.1 = 150ticks (effectiveTP = 15.0điểm).
5.2. Cơ chế Take Profit, Time Exit và Session Force Close
Bot không sử dụng cơ chế dời hòa vốn (Break Even) hay Trailing Stop, mà quản trị vị thế bằng 3 cơ chế thoát lệnh độc lập và dứt khoát:
- Chốt lời / Cắt lỗ cố định (
strategy.exit): Đặt ngay lập tức cho lệnh"Long"và"Short"với khoảng cáchtpTicksvàslTickstính từ giá khớp trung bìnhstrategy.position_avg_price. - Thoát lệnh theo thời gian (
Time Exit): Nếu bậtuseTimeExit, khi số nến nắm giữ vị thếbarsHeld >= maximumHoldingBars(mặc định20nến) trên nến đã đóng (và chưa tới nến đóng phiên), bot gọistrategy.close_all(immediately=true)để giải phóng vốn khỏi các nhịp đi ngang kéo dài. - Tất toán cuối phiên (
Session Force Close): Tại cây nến chạm mốc14:45(openMinutes < forceCloseMinutesvàcloseMinutes >= forceCloseMinutes), nếu vẫn còn vị thế mở, bot tự động đóng toàn bộ trước phiên ATC.
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 | Hành động trong code | Tham số mặc định |
|---|---|---|---|
| Stop Loss cố định | Giá chạm mức lỗ slTicks từ giá vào trung bình | strategy.exit(..., loss=slTicks) | 5.0 điểm (50 ticks) |
| Take Profit cố định | Giá chạm mức lời tpTicks từ giá vào trung bình | strategy.exit(..., profit=tpTicks) | 15.0 điểm (150 ticks) |
| Time Exit (tùy chọn) | Bật useTimeExit và giữ lệnh ≥ maximumHoldingBars nến | strategy.close_all(immediately=true) | false / 20 nến |
| Session Force Close | Nến đóng qua mốc 14:45 khi vẫn còn vị thế | strategy.close_all(immediately=true) | 14:45 (Asia/Ho_Chi_Minh) |
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 tương lai VN30F1M trên TradingView, chọn khung thời gian phù hợp (khuyến nghị
1m,3mhoặc5m, bắt buộc≤ 15mđể xây dựng vùng OR09:00–09:15). - Nhấn vào tab Pine Editor ở phía dưới màn hình, xóa code mẫu mặc định.
- Sao chép toàn bộ mã nguồn Pine Script v6 ở Mục 1 và dán vào Pine Editor.
- Nhấn Save để lưu script, sau đó nhấn Add to chart để gắn bot lên biểu đồ.
- Mở phần Settings (Cài đặt) của chiến lược để kiểm tra thông số
Trade Direction(mặc định đang để"Long", hãy chuyển sang"Both"nếu muốn giao dịch cả hai chiều Long và Short) và bậtShow Diagnosticsnếu cần theo dõi thông số thống kê.
Cách đọc bảng chẩn đoán (Diagnostics Table)
Khi bật tùy chọn Show Diagnostics = true, bảng diagnostics gồm 22 dòng sẽ hiển thị ở góc trên bên phải biểu đồ (position.top_right):
| Dòng hiển thị | Ý nghĩa thực tế trong code |
|---|---|
CNPS90 V2 | Tên bot và khung thời gian hiện tại của biểu đồ (timeframe.period). |
OR Locked / OR Bars | Trạng thái vùng OR đã khóa (YES/NO) và số lượng nến hình thành vùng OR. |
OR Width / OR Width / ATR | Độ rộng vùng OR tính bằng điểm và tỷ lệ so với ATR(14). |
OR Valid | Kết quả kiểm tra độ rộng OR có hợp lệ hay không (YES/NO). |
OR Days / Rejected OR | Tổng số ngày có vùng OR và số ngày bị loại do không đạt bộ lọc độ rộng. |
Long Attempts / Short Attempts | Tổng số lần thử phá vỡ lên và xuống trên toàn bộ dữ liệu kiểm thử. |
Re-arms | Tổng số lần bot nạp lại trạng thái sẵn sàng sau khi giá đóng cửa quay vào OR. |
Long Bases / Short Bases | Số tín hiệu đạt điều kiện phá vỡ + xác nhận nến trước khi qua bộ lọc phụ. |
Filtered Long / Filtered Short | Số tín hiệu vượt qua tất cả 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 bởi cổng kiểm soát (canTrade như hết lượt ngày, cooldown, ngoài giờ). |
Long Entries / Short Entries | Tổng số lệnh Long và Short thực tế đã vào. |
Armed Long / Short | Trạng thái sẵn sàng hiện tại của hai chiều (Y hoặc N). |
Trades Today | Số lệnh đã vào trong ngày hiện tại trên tổng giới hạn (tradesToday/maximumTradesPerDay). |
Position | Trạng thái vị thế hiện tại (LONG, SHORT hoặc FLAT). |
7. Cách thiết lập cảnh báo tín hiệu giao dịch (Alert)
Để nhận thông báo tín hiệu giao dịch tự động hoặc kết nối Webhook đặt lệnh, bạn thực hiện theo các bước sau:
- Trên thanh công cụ biểu đồ TradingView, nhấn vào biểu tượng Alert (Đồng hồ báo thức) hoặc nhấn tổ hợp phím
Alt + A. - Ở mục Condition, chọn chiến lược
CNPS90 OPENING RANGE BREAKOUT V2. - Ở phần Message, xóa nội dung mặc định và nhập duy nhất biến:
{{strategy.order.alert_message}}. - Thiết lập kênh nhận thông báo (Ứng dụng TradingView, Email, hoặc Webhook URL) và nhấn Create.
- Nếu muốn tắt riêng cảnh báo khi chạm SL/TP và chỉ nhận cảnh báo vào lệnh / đóng phiên, hãy tick chọn
Disable SL / TP Alerts(disableExitAlerts = true) trong cài đặt bot.
Bảng thông điệp Alert của CNPS90
| Loại sự kiện | Hành động | Nội dung thông điệp (alert_message / alert_profit / alert_loss) |
|---|---|---|
| Vào lệnh Long | strategy.entry("Long", ...) | 🟢 VÀO VỊ THẾ LONG (CNPS90) kèm Giá vào, Cắt lỗ (SL), Chốt lời (TP). |
| Vào lệnh Short | strategy.entry("Short", ...) | 🔴 VÀO VỊ THẾ SHORT (CNPS90) kèm Giá vào, Cắt lỗ (SL), Chốt lời (TP). |
| Chốt lời Long / Short | strategy.exit (alert_profit) | 💰 CHỐT LỜI LONG/SHORT (CNPS90 - TP HIT) kèm Giá chốt lời. |
| Cắt lỗ Long / Short | strategy.exit (alert_loss) | 🛑 CẮT LỖ LONG/SHORT (CNPS90 - SL HIT) kèm Giá cắt lỗ. |
| Hết thời gian giữ lệnh | strategy.close_all (Time Exit) | ⏱️ ĐÓNG VỊ THẾ HẾT THỜI GIAN (CNPS90 - Time Exit) kèm Giá đóng. |
| Đóng vị thế cuối phiên | strategy.close_all (Session End) | ⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (CNPS90 - Session End) kèm Giá đóng. |
Kết luận
CNPS90 Opening Range Breakout V2 là một hệ thống giao dịch ORB hiện đại, giải quyết tốt điểm yếu cố hữu của chiến lược phá vỡ thông thường nhờ cơ chế Consume & Re-arm: hạn chế vào lệnh đuổi khi giá đã đi xa ngoài biên độ mở cửa, đồng thời không bỏ lỡ cơ hội nếu giá quay lại vùng cân bằng và bứt phá lần nữa. Với cấu trúc SL/TP cố định tỷ lệ 1:3 mặc định, lọc nến rõ ràng và đóng lệnh trước ATC lúc 14:45, bot đặc biệt phù hợp với các phiên thị trường có xu hướng rõ ràng sau giai đoạn tích lũy đầu ngày.
Bạn có thể tham khảo thêm các bot giao dịch VN30F1M khác trên hệ thống như Bot CNPS50 - Trend Analysis V2 và Bot CNPS49 - Daily Open.
Thông tin chỉ mang tính tham khảo, không phải khuyến nghị đầu tư. Kết quả kiểm thử quá khứ không đảm bảo lợi nhuận trong tương lai.
Thông tin trong bài chỉ mang tính tham khảo, không phải khuyến nghị mua bán. Giao dịch phái sinh có rủi ro cao do sử dụng đòn bẩy; nhà đầu tư tự chịu trách nhiệm với quyết định của mình.





