Hướng Dẫn Sử Dụng Bot CNPS60 - Opening Range Acceptance V2 cho VN30F1M
TradingviewBot CNPS60 giao dịch VN30F1M theo mô hình Opening Range Acceptance V2: xác định vùng mở cửa 09:00, lọc Breakout chất lượng, chờ Retest và xác nhận cấu trúc nến kèm quản trị SL/TP chặt chẽ.

Mục lục
Trong giao dịch hợp đồng tương lai VN30F1M, 15 phút đầu phiên sáng (09:00–09:15) thường tập trung dòng tiền thăm dò và tạo ra vùng biên độ giá quan trọng trong ngày. Tuy nhiên, nếu mua đuổi ngay khi giá vừa vượt đỉnh/đáy vùng mở cửa, nhà đầu tư rất dễ dính bẫy phá vỡ giả (False Breakout) hoặc vào lệnh tại vùng có tỷ lệ Rủi ro/Lợi nhuận (R:R) kém.
Để giải quyết bài toán này, Bot CNPS60 (strategy(title="CNPS60 OPENING RANGE ACCEPTANCE V2 - CLEAN - VN30F1M")) được lập trình trên nền tảng Pine Script v6 của TradingView. Chiến lược tập trung vào cơ chế Opening Range Acceptance (Chấp nhận vùng mở cửa): chỉ giao dịch khi giá phá vỡ dứt khoát, sau đó kiểm tra lại (Retest) thành công và có nến xác nhận tiếp diễn.
Điểm nổi bật cốt lõi của Bot CNPS60:
- Máy trạng thái 5 bước chặt chẽ: Tách biệt rõ giai đoạn hình thành Opening Range, Breakout chất lượng, Retest giữ biên và nến Xác nhận (Confirmation), loại bỏ các pha phá vỡ thiếu lực.
- Lọc đa lớp theo cấu trúc thị trường: Kết hợp EMA 34 (hướng và độ dốc chuẩn hóa theo ATR), DMI (
pDI/mDI), Session VWAP phiên liên tục và tùy chọn ADX14 / Relative Volume. - Định cỡ rủi ro theo cấu trúc (Structural Stop): Đặt Stop Loss ngay dưới/trên vùng neo cấu trúc (
stopAnchor) cộng đệm0.15 × ATR, chỉ vào lệnh khi rủi ro nằm trong khoảng1.5 – 9.0điểm và mục tiêu tối thiểu đạt3.0điểm. - Quản trị thoát lệnh đa tầng: Bảo vệ vị thế bằng cơ chế thoát sớm khi giá quay lại bên trong Opening Range (
Acceptance Failure Exit), giới hạn thời gian giữ lệnh tối đa (55 phút), kiểm tra rủi ro khớp lệnh thực tế (Invalid Gap) và tự động đóng vị thế trước giờ nghỉ trưa (11:25) cũng như cuối phiên (14:25).
1. CNPS60 Opening Range Acceptance V2 là gì?
CNPS60 Opening Range Acceptance V2 là hệ thống giao dịch trong ngày (Intraday) độc lập dành riêng cho VN30F1M, vận hành dựa trên 4 trụ cột kỹ thuật chính:
- Xây dựng và khóa vùng Opening Range (OR): Tự động ghi nhận mức cao nhất (
openingHigh) và thấp nhất (openingLow) trong khung thời gian mở cửa phiên sáng từ09:00(mặc định15 phút, đến09:15), đồng thời kiểm tra điều kiện số nến tối thiểu (>= 3) và độ rộng vùng mở cửa hợp lệ (4.0 – 55.0điểm). - Đánh giá chất lượng Breakout: Không chỉ xét giá đóng cửa vượt biên OR, bot còn kiểm tra thân nến, vị trí đóng cửa (
closeLocation), biên độ nến so vớiATR(14)và tùy chọn khối lượng đột biến. - Cơ chế Retest & Confirmation (hoặc Strong Follow-Through): Chờ giá hồi về kiểm tra lại ranh giới Opening Range với biên độ xuyên thủng tối đa được kiểm soát theo
ATR, sau đó mới kích hoạt lệnh khi có nến xác nhận hướng đi. - Kiểm soát phiên & bảo vệ tài khoản: Giới hạn tối đa
2 lệnh/ngày, tối đa1 lệnh mỗi chiều (Long/Short), giãn cách8 nếnsau khi đóng lệnh, chặn giao dịch mới khi lỗ đã thực hiện trong ngày chạm ngưỡng2.400.000 VNĐvà bắt buộc phẳng vị thế (Flat) trước giờ nghỉ trưa/kết phiên.
Bảng thông số mặc định
| Nhóm thông số | Tham số (input) | Giá trị mặc định | Ý nghĩa |
|---|---|---|---|
| 01 - Trade Control | tradeDirection | "Both" | Hướng giao dịch (Both, Long, Short) |
contracts | 3 | Số hợp đồng tham chiếu mỗi lệnh | |
maximumTradesPerDay | 2 | Số lệnh tối đa mỗi ngày | |
oneEntryPerSide | true | Tối đa 1 lệnh mỗi chiều Long/Short/ngày | |
cooldownBars | 8 | Số nến nghỉ sau khi đóng lệnh | |
| 02 - Opening Range | openingRangeMinutes | 15 | Thời gian hình thành OR từ 09:00 (10, 15, 20, 30 phút) |
minimumORWidth / maximumORWidth | 4.0 / 55.0 | Biên độ OR hợp lệ (điểm) | |
| 03 - Breakout | minimumBreakoutPoints | 0.60 | Điểm đóng cửa vượt biên OR tối thiểu |
minimumBreakRangeATR / maximumBreakRangeATR | 0.65 / 2.20 | Biên độ nến Breakout cho phép (theo ATR14) | |
minimumBreakBodyRatio | 0.40 | Tỷ lệ thân nến / tổng biên độ tối thiểu | |
minimumBreakCloseLocation | 0.65 | Vị trí giá đóng cửa về phía Breakout | |
useBreakoutVolume / volumeLookback / minimumBreakoutVolume | false / 25 / 1.10 | Lọc khối lượng Breakout so với SMA(25) trước đó | |
| 04 - Retest | entryMode | "Retest + Confirmation" | Chế độ vào lệnh (Retest + Confirmation, Retest Close, Retest / Strong Follow-Through) |
maximumRetestBars | 12 | Số nến tối đa chờ Retest sau Breakout | |
retestTouchATR / maximumRetestPierceATR | 0.45 / 0.40 | Bán kính chạm biên ngoài và mức xuyên tối đa vào trong OR (× ATR) | |
retestHoldBuffer / minimumRetestLocation | 0.20 / 0.60 | Đóng cửa giữ ngoài biên (điểm) và vị trí đóng cửa nến Retest | |
confirmationWindow / confirmationBuffer / minimumConfirmBody | 4 / 0.20 / 0.30 | Cửa sổ chờ xác nhận (nến), mức vượt đỉnh/đáy Retest và thân nến xác nhận | |
invalidInsideClose | 0.40 | Ngưỡng đóng cửa ngược vào trong OR làm hủy setup (điểm) | |
| 05 - Continuation | followThroughBars / followThroughDistanceATR | 3 / 0.50 | Điều kiện vào lệnh tiếp diễn mạnh (khi chọn mode Follow-Through) |
| 06 - Regime | useTrendFilter / trendEMALength / trendSlopeBars / minimumSlopeATR | true / 34 / 5 / 0.00 | Bộ lọc xu hướng EMA34, độ dốc theo ATR và DMI |
useVWAPFilter | true | Yêu cầu giá nằm đúng phía Session VWAP | |
useADXFilter / minimumADX | false / 18.0 | Bộ lọc ADX(14) tối thiểu | |
| 07 - Risk Management | stopBufferATR | 0.15 | Khoảng đệm Stop Loss theo ATR14 |
minimumRiskPoints / maximumRiskPoints | 1.50 / 9.0 | Khoảng cách SL hợp lệ (điểm) | |
takeProfitR / minimumGrossTarget | 1.70 / 3.0 | Tỷ lệ Take Profit (1.7R) và mục tiêu tối thiểu (3.0 điểm) | |
| 08 - Exit Management | useAcceptanceFailureExit / failureCloses | true / 2 | Thoát lệnh nếu giá đóng cửa lại vào trong OR 2 nến liên tiếp |
useBreakEven / breakEvenAtR / breakEvenOffset | false / 1.0 / 0.2 | Dời SL về hòa vốn khi đạt mức R | |
useTimeExit / maximumHoldMinutes | true / 55 | Đóng lệnh nếu giữ quá 55 phút | |
| 09 - Daily Protection | useDailyLossGuard / maximumDailyLossVND | true / 2400000 | Ngừng mở lệnh mới khi lỗ đã chốt trong ngày đạt 2.400.000 VNĐ |
| 10 - Session | morningEntrySession / afternoonEntrySession | "0920-1110" / "1305-1405" | Khung giờ tìm điểm vào lệnh sáng và chiều |
closeBeforeLunch / lunchFlatMinute | true / 25 | Đóng toàn bộ vị thế trước giờ nghỉ trưa (11:25) | |
endFlatHour / endFlatMinute | 14 / 25 | Đóng toàn bộ vị thế cuối ngày (14:25) |
Source Code CNPS60 Opening Range Acceptance 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
// CNPS60 V2 - Independent VN30F1M intraday strategy.
// Opening Range Acceptance -> Quality Breakout -> Retest -> Confirmation.
// No dashboard / table / on-chart diagnostic box.
strategy(title="CNPS60 OPENING RANGE ACCEPTANCE V2 - CLEAN - VN30F1M", shorttitle="CNPS60 ORA V2", overlay=true, initial_capital=100000000, currency=currency.VND, 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, process_orders_on_close=false, calc_on_order_fills=false, calc_on_every_tick=false, fill_orders_on_standard_ohlc=true, max_bars_back=5000, max_labels_count=100)
// ============================================================================
// SECTION 1: TRADE CONTROL
// ============================================================================
tradeDirection = input.string("Both", title="Trade Direction", options=["Both", "Long", "Short"], group="01 - Trade Control")
contracts = input.int(3, title="Contracts Per Entry", minval=1, maxval=20, group="01 - Trade Control")
maximumTradesPerDay = input.int(2, title="Maximum Trades Per Day", minval=1, maxval=10, group="01 - Trade Control")
oneEntryPerSide = input.bool(true, title="At Most One Trade Per Side / Day?", group="01 - Trade Control")
cooldownBars = input.int(8, title="Cooldown Bars After Closed Trade", minval=0, maxval=100, group="01 - Trade Control")
// ============================================================================
// SECTION 2: OPENING RANGE (09:00 CONTINUOUS SESSION)
// ============================================================================
openingRangeMinutes = input.int(15, title="Opening Range Minutes", options=[10, 15, 20, 30], group="02 - Opening Range")
minimumORWidth = input.float(4.0, title="Minimum Opening Range Width (points)", minval=0.5, step=0.5, group="02 - Opening Range")
maximumORWidth = input.float(55.0, title="Maximum Opening Range Width (points)", minval=5.0, step=1.0, group="02 - Opening Range")
// ============================================================================
// SECTION 3: BREAKOUT QUALITY
// ============================================================================
minimumBreakoutPoints = input.float(0.60, title="Minimum Close Beyond Opening Range (points)", minval=0.0, step=0.1, group="03 - Breakout")
minimumBreakRangeATR = input.float(0.65, title="Minimum Breakout Candle Range / ATR", minval=0.1, maxval=5.0, step=0.05, group="03 - Breakout")
maximumBreakRangeATR = input.float(2.20, title="Maximum Breakout Candle Range / ATR", minval=0.5, maxval=10.0, step=0.1, group="03 - Breakout")
minimumBreakBodyRatio = input.float(0.40, title="Minimum Breakout Body / Range", minval=0.0, maxval=1.0, step=0.05, group="03 - Breakout")
minimumBreakCloseLocation = input.float(0.65, title="Close Location Toward Breakout (0-1)", minval=0.5, maxval=0.95, step=0.05, group="03 - Breakout")
useBreakoutVolume = input.bool(false, title="Require Relative Breakout Volume?", group="03 - Breakout")
volumeLookback = input.int(25, title="Volume Average Length", minval=5, maxval=200, group="03 - Breakout")
minimumBreakoutVolume = input.float(1.10, title="Breakout Volume / Previous Average", minval=0.2, maxval=5.0, step=0.05, group="03 - Breakout")
// ============================================================================
// SECTION 4: RETEST / CONFIRMATION
// ============================================================================
entryMode = input.string("Retest + Confirmation", title="Entry Mode", options=["Retest + Confirmation", "Retest Close", "Retest / Strong Follow-Through"], group="04 - Retest")
maximumRetestBars = input.int(12, title="Maximum Bars Waiting For Retest", minval=2, maxval=60, group="04 - Retest")
retestTouchATR = input.float(0.45, title="Retest Touch Radius Outside Range x ATR", minval=0.05, maxval=3.0, step=0.05, group="04 - Retest")
maximumRetestPierceATR = input.float(0.40, title="Maximum Retest Wick Inside Range x ATR", minval=0.05, maxval=3.0, step=0.05, group="04 - Retest")
retestHoldBuffer = input.float(0.20, title="Minimum Retest Close Beyond Boundary (points)", minval=0.0, step=0.1, group="04 - Retest")
minimumRetestLocation = input.float(0.60, title="Retest Close Location", minval=0.5, maxval=0.95, step=0.05, group="04 - Retest")
confirmationWindow = input.int(4, title="Bars To Confirm After Retest", minval=1, maxval=15, group="04 - Retest")
confirmationBuffer = input.float(0.20, title="Confirmation Close Beyond Retest High / Low", minval=0.0, step=0.1, group="04 - Retest")
minimumConfirmBody = input.float(0.30, title="Confirmation Body / Range", minval=0.0, maxval=1.0, step=0.05, group="04 - Retest")
invalidInsideClose = input.float(0.40, title="Invalidate On Close Inside OR By (points)", minval=0.0, step=0.1, group="04 - Retest")
// ============================================================================
// SECTION 5: OPTIONAL CONTINUATION ENTRY
// ============================================================================
followThroughBars = input.int(3, title="Maximum Bars For Strong Follow-Through", minval=1, maxval=15, group="05 - Continuation")
followThroughDistanceATR = input.float(0.50, title="Close Beyond Breakout Extreme x ATR", minval=0.0, maxval=3.0, step=0.05, group="05 - Continuation")
// ============================================================================
// SECTION 6: TREND / REGIME QUALITY
// ============================================================================
useTrendFilter = input.bool(true, title="Require Trend Alignment?", group="06 - Regime")
trendEMALength = input.int(34, title="Futures EMA Length", minval=5, maxval=200, group="06 - Regime")
trendSlopeBars = input.int(5, title="EMA Slope Lookback", minval=1, maxval=40, group="06 - Regime")
minimumSlopeATR = input.float(0.00, title="Minimum Directional EMA Slope / ATR", minval=-1.0, maxval=3.0, step=0.05, group="06 - Regime")
useVWAPFilter = input.bool(true, title="Require Entry On Trend Side Of Session VWAP?", group="06 - Regime")
useADXFilter = input.bool(false, title="Require Minimum ADX?", group="06 - Regime")
minimumADX = input.float(18.0, title="Minimum ADX14", minval=5.0, maxval=50.0, step=1.0, group="06 - Regime")
// ============================================================================
// SECTION 7: STRUCTURAL STOP / TARGET
// ============================================================================
stopBufferATR = input.float(0.15, title="Stop Buffer Beyond Retest / Range x ATR", minval=0.0, maxval=2.0, step=0.05, group="07 - Risk Management")
minimumRiskPoints = input.float(1.50, title="Minimum Stop Distance (points)", minval=0.1, step=0.5, group="07 - Risk Management")
maximumRiskPoints = input.float(9.0, title="Maximum Stop Distance (points)", minval=0.5, step=0.5, group="07 - Risk Management")
takeProfitR = input.float(1.70, title="Take Profit (R)", minval=0.25, maxval=6.0, step=0.1, group="07 - Risk Management")
minimumGrossTarget = input.float(3.0, title="Minimum Gross Target Distance (points)", minval=0.0, step=0.5, group="07 - Risk Management")
// ============================================================================
// SECTION 8: POSITION MANAGEMENT
// ============================================================================
useAcceptanceFailureExit = input.bool(true, title="Exit If Price Re-Accepts Inside OR?", group="08 - Exit Management")
failureCloses = input.int(2, title="Consecutive Closes Inside OR", minval=1, maxval=5, group="08 - Exit Management")
useBreakEven = input.bool(false, title="Use Break Even?", group="08 - Exit Management")
breakEvenAtR = input.float(1.0, title="Break Even Trigger (R)", minval=0.25, maxval=5.0, step=0.25, group="08 - Exit Management")
breakEvenOffset = input.float(0.2, title="Break Even Offset (points)", minval=0.0, step=0.1, group="08 - Exit Management")
useTimeExit = input.bool(true, title="Use Maximum Hold Minutes?", group="08 - Exit Management")
maximumHoldMinutes = input.int(55, title="Maximum Hold (minutes)", minval=5, maxval=240, group="08 - Exit Management")
// ============================================================================
// SECTION 9: DAILY RISK GUARD
// ============================================================================
useDailyLossGuard = input.bool(true, title="Block New Entries After Daily Realized Loss?", group="09 - Daily Protection")
maximumDailyLossVND = input.float(2400000, title="Daily Realized Loss Guard (VND)", minval=100000, step=100000, group="09 - Daily Protection")
// ============================================================================
// SECTION 10: VN30F1M SESSION
// ============================================================================
string timezoneVN = "Asia/Ho_Chi_Minh"
morningEntrySession = input.session("0920-1110", title="Morning Entry Window", group="10 - Session")
afternoonEntrySession = input.session("1305-1405", title="Afternoon Entry Window", group="10 - Session")
closeBeforeLunch = input.bool(true, title="Force Flat Before Lunch?", group="10 - Session")
lunchFlatMinute = input.int(25, title="Lunch Flat Minute (11:xx)", minval=15, maxval=30, group="10 - Session")
endFlatHour = input.int(14, title="Final Flat Hour", minval=0, maxval=23, group="10 - Session")
endFlatMinute = input.int(25, title="Final Flat Minute", minval=0, maxval=59, group="10 - Session")
// ============================================================================
// SECTION 11: DISPLAY - NO TABLE
// ============================================================================
showOpeningRange = input.bool(true, title="Show Opening Range High / Low?", group="11 - Display")
showVWAP = input.bool(false, title="Show Session VWAP?", group="11 - Display")
showBreakouts = input.bool(false, title="Show Breakout Markers?", group="11 - Display")
showRetests = input.bool(false, title="Show Accepted Retest Markers?", group="11 - Display")
showEntrySignals = input.bool(true, title="Show Entry Signals?", group="11 - Display")
showTradeLevels = input.bool(true, title="Show Active SL / TP?", group="11 - Display")
// ============================================================================
// SECTION 12: TIME ENGINE
// ============================================================================
int minuteOpen = hour(time, timezoneVN) * 60 + minute(time, timezoneVN)
int minuteClose = hour(time_close, timezoneVN) * 60 + minute(time_close, timezoneVN)
int openingEndMinute = 540 + openingRangeMinutes
int lunchCutoff = 660 + lunchFlatMinute
int finalCutoff = endFlatHour * 60 + endFlatMinute
bool continuousMorning = minuteOpen >= 540 and minuteOpen < 690
bool continuousAfternoon = minuteOpen >= 780 and minuteOpen < 870
bool inContinuousSession = continuousMorning or continuousAfternoon
bool openingObservation = (continuousMorning and minuteOpen >= 540 and minuteOpen < openingEndMinute and minuteClose <= openingEndMinute)
bool openingTimeComplete = minuteOpen >= openingEndMinute
bool entryMorning = not na(time(timeframe.period, morningEntrySession + ":23456", timezoneVN))
bool entryAfternoon = not na(time(timeframe.period, afternoonEntrySession + ":23456", timezoneVN))
bool entrySession = entryMorning or entryAfternoon
bool afternoonBegins = entryAfternoon and not entryAfternoon[1]
int dayKey = (year(time, timezoneVN) * 10000 + month(time, timezoneVN) * 100 + dayofmonth(time, timezoneVN))
bool newTradingDay = bar_index == 0 or dayKey != nz(dayKey[1], dayKey)
bool beforeCutoffs = (not na(time_close) and minuteClose < finalCutoff and (not closeBeforeLunch or not continuousMorning or minuteClose < lunchCutoff))
bool lunchFlatBar = (closeBeforeLunch and barstate.isconfirmed and continuousMorning and minuteOpen < lunchCutoff and minuteClose >= lunchCutoff)
bool endFlatBar = (barstate.isconfirmed and continuousAfternoon and minuteOpen < finalCutoff and minuteClose >= finalCutoff)
// ============================================================================
// SECTION 13: BUILD AND FREEZE OPENING RANGE
// ============================================================================
var float openingHigh = na
var float openingLow = na
var int openingBars = 0
if newTradingDay
openingHigh := na
openingLow := na
openingBars := 0
if openingObservation and barstate.isconfirmed
openingHigh := math.max(nz(openingHigh, high), high)
openingLow := math.min(nz(openingLow, low), low)
openingBars += 1
float openingWidth = openingHigh - openingLow
bool openingReady = (openingTimeComplete and openingBars >= 3 and not na(openingHigh) and not na(openingLow) and openingWidth >= minimumORWidth and openingWidth <= maximumORWidth)
// ============================================================================
// SECTION 14: VOLATILITY / TREND METRICS
// ============================================================================
float atr = ta.atr(14)
float trendEMA = ta.ema(close, trendEMALength)
float emaSlope = not na(atr) and atr > 0 ? (trendEMA - trendEMA[trendSlopeBars]) / atr : 0.0
float candleRange = math.max(high - low, syminfo.mintick)
float candleBodyRatio = math.abs(close - open) / candleRange
float closeLocation = (close - low) / candleRange
float avgVolumePrevious = ta.sma(volume, volumeLookback)[1]
[pDI, mDI, adx] = ta.dmi(14, 14)
bool bullishBreakCandle = (close > open and candleBodyRatio >= minimumBreakBodyRatio and closeLocation >= minimumBreakCloseLocation and not na(atr) and atr > 0 and candleRange >= minimumBreakRangeATR * atr and candleRange <= maximumBreakRangeATR * atr)
bool bearishBreakCandle = (close < open and candleBodyRatio >= minimumBreakBodyRatio and closeLocation <= 1.0 - minimumBreakCloseLocation and not na(atr) and atr > 0 and candleRange >= minimumBreakRangeATR * atr and candleRange <= maximumBreakRangeATR * atr)
bool bullishConfirmCandle = (close > open and candleBodyRatio >= minimumConfirmBody and closeLocation >= 0.55)
bool bearishConfirmCandle = (close < open and candleBodyRatio >= minimumConfirmBody and closeLocation <= 0.45)
bool breakoutVolumeOK = (not useBreakoutVolume or (not na(avgVolumePrevious) and avgVolumePrevious > 0 and volume >= avgVolumePrevious * minimumBreakoutVolume))
// ============================================================================
// SECTION 15: CONTINUOUS-SESSION VWAP
// ============================================================================
var float accumulatedPV = 0.0
var float accumulatedVolume = 0.0
if newTradingDay
accumulatedPV := 0.0
accumulatedVolume := 0.0
if inContinuousSession and barstate.isconfirmed and not na(volume) and volume > 0
accumulatedPV += hlc3 * volume
accumulatedVolume += volume
float sessionVWAP = accumulatedVolume > 0 ? accumulatedPV / accumulatedVolume : na
bool longTrendOK = (not useTrendFilter or (close > trendEMA and emaSlope >= minimumSlopeATR and pDI >= mDI))
bool shortTrendOK = (not useTrendFilter or (close < trendEMA and emaSlope <= -minimumSlopeATR and mDI >= pDI))
bool longVWAPOK = not useVWAPFilter or (not na(sessionVWAP) and close > sessionVWAP)
bool shortVWAPOK = not useVWAPFilter or (not na(sessionVWAP) and close < sessionVWAP)
bool adxOK = not useADXFilter or (not na(adx) and adx >= minimumADX)
// ============================================================================
// SECTION 16: DAILY TRADE CONTROL
// ============================================================================
var int tradesToday = 0
var int closedTradesSeen = 0
var int lastExitBar = na
var int lastOrderBar = na
var float dayStartNetProfit = na
var bool tradedLongToday = false
var bool tradedShortToday = false
if newTradingDay
tradesToday := 0
dayStartNetProfit := strategy.netprofit
tradedLongToday := false
tradedShortToday := false
if strategy.closedtrades > closedTradesSeen
closedTradesSeen := strategy.closedtrades
lastExitBar := bar_index
bool flat = strategy.position_size == 0
bool inLong = strategy.position_size > 0
bool inShort = strategy.position_size < 0
bool allowLong = tradeDirection != "Short"
bool allowShort = tradeDirection != "Long"
bool longSideAvailable = allowLong and (not oneEntryPerSide or not tradedLongToday)
bool shortSideAvailable = allowShort and (not oneEntryPerSide or not tradedShortToday)
float dailyClosedPnL = strategy.netprofit - nz(dayStartNetProfit, strategy.netprofit)
bool dailyControlOK = (tradesToday < maximumTradesPerDay and (not useDailyLossGuard or dailyClosedPnL > -maximumDailyLossVND))
bool cooldownOK = na(lastExitBar) or bar_index - lastExitBar > cooldownBars
bool oncePerBar = na(lastOrderBar) or lastOrderBar != bar_index
bool commonEntryOK = (flat and openingReady and entrySession and inContinuousSession and beforeCutoffs and dailyControlOK and cooldownOK and oncePerBar and barstate.isconfirmed)
// ============================================================================
// SECTION 17: BREAKOUT / RETEST STATE
// ============================================================================
// 0: Wait for fresh, quality breakout.
// 1: Above OR High, waiting for accepted retest.
// -1: Below OR Low, waiting for accepted retest.
// 2: Upper retest accepted; wait for upside confirmation.
// -2: Lower retest accepted; wait for downside confirmation.
// ============================================================================
var int setupState = 0
var int breakoutBar = na
var float breakoutHigh = na
var float breakoutLow = na
var int retestBar = na
var float retestHigh = na
var float retestLow = na
bool breakoutLongMark = false
bool breakoutShortMark = false
bool retestLongMark = false
bool retestShortMark = false
bool rawLong = false
bool rawShort = false
float stopAnchor = na
if newTradingDay or afternoonBegins or lunchFlatBar or endFlatBar
setupState := 0
breakoutBar := na
retestBar := na
// ============================================================================
// SECTION 18: EXISTING LONG BREAKOUT -> RETEST OR CONTINUATION
// ============================================================================
if barstate.isconfirmed and openingReady and setupState == 1
bool expired = bar_index - breakoutBar > maximumRetestBars
bool failed = close < openingHigh - invalidInsideClose
if expired or failed or not entrySession
setupState := 0
else if bar_index > breakoutBar
bool retestTouched = (not na(atr) and low <= openingHigh + atr * retestTouchATR and low >= openingHigh - atr * maximumRetestPierceATR)
bool heldOutside = (close > openingHigh + retestHoldBuffer and closeLocation >= minimumRetestLocation)
if retestTouched and heldOutside and bullishConfirmCandle
retestLongMark := true
retestBar := bar_index
retestHigh := high
retestLow := low
if entryMode == "Retest Close"
rawLong := true
stopAnchor := math.min(retestLow, openingHigh)
setupState := 0
else
setupState := 2
else if entryMode == "Retest / Strong Follow-Through"
bool strongFollow = (bar_index - breakoutBar <= followThroughBars and close > breakoutHigh + atr * followThroughDistanceATR and bullishConfirmCandle and longTrendOK and longVWAPOK)
if strongFollow
rawLong := true
stopAnchor := openingHigh
setupState := 0
// ============================================================================
// SECTION 19: EXISTING SHORT BREAKOUT -> RETEST OR CONTINUATION
// ============================================================================
if barstate.isconfirmed and openingReady and setupState == -1
bool expired = bar_index - breakoutBar > maximumRetestBars
bool failed = close > openingLow + invalidInsideClose
if expired or failed or not entrySession
setupState := 0
else if bar_index > breakoutBar
bool retestTouched = (not na(atr) and high >= openingLow - atr * retestTouchATR and high <= openingLow + atr * maximumRetestPierceATR)
bool heldOutside = (close < openingLow - retestHoldBuffer and closeLocation <= 1.0 - minimumRetestLocation)
if retestTouched and heldOutside and bearishConfirmCandle
retestShortMark := true
retestBar := bar_index
retestHigh := high
retestLow := low
if entryMode == "Retest Close"
rawShort := true
stopAnchor := math.max(retestHigh, openingLow)
setupState := 0
else
setupState := -2
else if entryMode == "Retest / Strong Follow-Through"
bool strongFollow = (bar_index - breakoutBar <= followThroughBars and close < breakoutLow - atr * followThroughDistanceATR and bearishConfirmCandle and shortTrendOK and shortVWAPOK)
if strongFollow
rawShort := true
stopAnchor := openingLow
setupState := 0
// ============================================================================
// SECTION 20: LONG RETEST -> CONFIRMED ACCEPTANCE
// ============================================================================
if barstate.isconfirmed and openingReady and setupState == 2
bool expired = bar_index - retestBar > confirmationWindow
bool failed = (close < openingHigh - invalidInsideClose or low < retestLow - atr * maximumRetestPierceATR)
if expired or failed or not entrySession
setupState := 0
else if bar_index > retestBar
bool accepted = (close > retestHigh + confirmationBuffer and close > openingHigh + retestHoldBuffer and bullishConfirmCandle)
if accepted
rawLong := true
stopAnchor := math.min(retestLow, openingHigh)
setupState := 0
// ============================================================================
// SECTION 21: SHORT RETEST -> CONFIRMED ACCEPTANCE
// ============================================================================
if barstate.isconfirmed and openingReady and setupState == -2
bool expired = bar_index - retestBar > confirmationWindow
bool failed = (close > openingLow + invalidInsideClose or high > retestHigh + atr * maximumRetestPierceATR)
if expired or failed or not entrySession
setupState := 0
else if bar_index > retestBar
bool accepted = (close < retestLow - confirmationBuffer and close < openingLow - retestHoldBuffer and bearishConfirmCandle)
if accepted
rawShort := true
stopAnchor := math.max(retestHigh, openingLow)
setupState := 0
// ============================================================================
// SECTION 22: START ONLY FRESH BREAKOUTS FROM THE RANGE INTERIOR
// ============================================================================
bool freshLongBreakout = (openingReady and close[1] <= openingHigh + minimumBreakoutPoints and close > openingHigh + minimumBreakoutPoints and bullishBreakCandle and breakoutVolumeOK and longTrendOK and longVWAPOK and adxOK)
bool freshShortBreakout = (openingReady and close[1] >= openingLow - minimumBreakoutPoints and close < openingLow - minimumBreakoutPoints and bearishBreakCandle and breakoutVolumeOK and shortTrendOK and shortVWAPOK and adxOK)
if (barstate.isconfirmed and setupState == 0 and not rawLong and not rawShort and commonEntryOK)
if freshLongBreakout and longSideAvailable
setupState := 1
breakoutBar := bar_index
breakoutHigh := high
breakoutLow := low
breakoutLongMark := true
else if freshShortBreakout and shortSideAvailable
setupState := -1
breakoutBar := bar_index
breakoutHigh := high
breakoutLow := low
breakoutShortMark := true
// ============================================================================
// SECTION 23: STRUCTURAL STOP / REWARD VALIDATION
// ============================================================================
float candidateLongStop = not na(stopAnchor) and not na(atr) ? math.round_to_mintick(stopAnchor - atr * stopBufferATR) : na
float candidateShortStop = not na(stopAnchor) and not na(atr) ? math.round_to_mintick(stopAnchor + atr * stopBufferATR) : na
float riskLong = close - candidateLongStop
float riskShort = candidateShortStop - close
bool riskLongOK = (not na(riskLong) and riskLong >= minimumRiskPoints and riskLong <= maximumRiskPoints and riskLong * takeProfitR >= minimumGrossTarget)
bool riskShortOK = (not na(riskShort) and riskShort >= minimumRiskPoints and riskShort <= maximumRiskPoints and riskShort * takeProfitR >= minimumGrossTarget)
float targetLong = not na(riskLong) ? math.round_to_mintick(close + riskLong * takeProfitR) : na
float targetShort = not na(riskShort) ? math.round_to_mintick(close - riskShort * takeProfitR) : na
bool finalLong = rawLong and longSideAvailable and longTrendOK and longVWAPOK and adxOK and riskLongOK and commonEntryOK
bool finalShort = rawShort and shortSideAvailable and shortTrendOK and shortVWAPOK and adxOK and riskShortOK and commonEntryOK and not finalLong
// ============================================================================
// SECTION 24: ORDER LEVEL STATE
// ============================================================================
var float activeStop = na
var float activeTarget = na
var float initialFillRisk = na
var float actualFillPrice = na
var int actualFillBar = na
var int acceptanceFailureCount = 0
var bool breakEvenActivated = false
// ============================================================================
// SECTION 25: LONG ENTRY + INITIAL PROTECTIVE BRACKET
// ============================================================================
if finalLong
activeStop := candidateLongStop
activeTarget := targetLong
initialFillRisk := na
actualFillPrice := na
actualFillBar := na
acceptanceFailureCount := 0
breakEvenActivated := false
strategy.entry("CNPS60-L", strategy.long, comment="OPENING RANGE LONG ACCEPTED", alert_message="🟢 VÀO VỊ THẾ LONG (CNPS60)\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\n🛑 Cắt lỗ (SL): " + str.tostring(activeStop, format.mintick) + "\n🎯 Chốt lời (TP): " + str.tostring(activeTarget, format.mintick))
strategy.exit("CNPS60-L-X", from_entry="CNPS60-L", stop=activeStop, limit=activeTarget, comment_profit="TP Long", comment_loss="SL Long", alert_profit="💰 CHỐT LỜI LONG (TP HIT)\n🎯 Giá chốt lời: " + str.tostring(activeTarget, format.mintick), alert_loss="🛑 CẮT LỖ LONG (SL HIT)\nGiá cắt lỗ: " + str.tostring(activeStop, format.mintick))
tradesToday += 1
tradedLongToday := true
lastOrderBar := bar_index
setupState := 0
// ============================================================================
// SECTION 26: SHORT ENTRY + INITIAL PROTECTIVE BRACKET
// ============================================================================
else if finalShort
activeStop := candidateShortStop
activeTarget := targetShort
initialFillRisk := na
actualFillPrice := na
actualFillBar := na
acceptanceFailureCount := 0
breakEvenActivated := false
strategy.entry("CNPS60-S", strategy.short, comment="OPENING RANGE SHORT ACCEPTED", alert_message="🔴 VÀO VỊ THẾ SHORT (CNPS60)\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\n🛑 Cắt lỗ (SL): " + str.tostring(activeStop, format.mintick) + "\n🎯 Chốt lời (TP): " + str.tostring(activeTarget, format.mintick))
strategy.exit("CNPS60-S-X", from_entry="CNPS60-S", stop=activeStop, limit=activeTarget, comment_profit="TP Short", comment_loss="SL Short", alert_profit="💰 CHỐT LỜI SHORT (TP HIT)\n🎯 Giá chốt lời: " + str.tostring(activeTarget, format.mintick), alert_loss="🛑 CẮT LỖ SHORT (SL HIT)\nGiá cắt lỗ: " + str.tostring(activeStop, format.mintick))
tradesToday += 1
tradedShortToday := true
lastOrderBar := bar_index
setupState := 0
// ============================================================================
// SECTION 27: FILL VALIDATION + OPTIONAL BREAK EVEN
// ============================================================================
if strategy.position_size != 0 and strategy.opentrades > 0 and barstate.isconfirmed
int positionEntryBar = strategy.opentrades.entry_bar_index(0)
float positionEntryPrice = strategy.position_avg_price
if na(actualFillBar) or positionEntryBar != actualFillBar
actualFillBar := positionEntryBar
actualFillPrice := positionEntryPrice
initialFillRisk := inLong ? actualFillPrice - activeStop : activeStop - actualFillPrice
bool validFill = (not na(initialFillRisk) and initialFillRisk > syminfo.mintick and (inLong ? activeTarget > actualFillPrice : activeTarget < actualFillPrice))
if not validFill
strategy.close(inLong ? "CNPS60-L" : "CNPS60-S", immediately=true, comment="INVALID FILLED RISK", alert_message="⚠️ ĐÓNG VỊ THẾ DO GAP/RỦI RO KHÔNG HỢP LỆ (Invalid Gap)")
else
float closeInR = (inLong ? close - actualFillPrice : actualFillPrice - close) / initialFillRisk
if useBreakEven and closeInR >= breakEvenAtR
float proposedBE = math.round_to_mintick(inLong ? actualFillPrice + breakEvenOffset : actualFillPrice - breakEvenOffset)
activeStop := inLong ? math.max(activeStop, proposedBE) : math.min(activeStop, proposedBE)
breakEvenActivated := true
if inLong
strategy.exit("CNPS60-L-X", from_entry="CNPS60-L", stop=activeStop, limit=activeTarget, comment_profit="TP Long", comment_loss=breakEvenActivated ? "BE Long" : "SL Long", alert_profit="💰 CHỐT LỜI LONG (TP HIT)\n🎯 Giá chốt lời: " + str.tostring(activeTarget, format.mintick), alert_loss=breakEvenActivated ? "🛡️ HÒA VỐN LONG (BE HIT)\nGiá hòa vốn: " + str.tostring(activeStop, format.mintick) : "🛑 CẮT LỖ LONG (SL HIT)\nGiá cắt lỗ: " + str.tostring(activeStop, format.mintick))
else
strategy.exit("CNPS60-S-X", from_entry="CNPS60-S", stop=activeStop, limit=activeTarget, comment_profit="TP Short", comment_loss=breakEvenActivated ? "BE Short" : "SL Short", alert_profit="💰 CHỐT LỜI SHORT (TP HIT)\n🎯 Giá chốt lời: " + str.tostring(activeTarget, format.mintick), alert_loss=breakEvenActivated ? "🛡️ HÒA VỐN SHORT (BE HIT)\nGiá hòa vốn: " + str.tostring(activeStop, format.mintick) : "🛑 CẮT LỖ SHORT (SL HIT)\nGiá cắt lỗ: " + str.tostring(activeStop, format.mintick))
// ============================================================================
// SECTION 28: ACCEPTANCE FAILURE / MAXIMUM HOLD EXITS
// ============================================================================
if strategy.position_size != 0 and strategy.opentrades > 0 and barstate.isconfirmed
bool returnedIntoRange = inLong ? close < openingHigh - invalidInsideClose : close > openingLow + invalidInsideClose
acceptanceFailureCount := returnedIntoRange ? acceptanceFailureCount + 1 : 0
if useAcceptanceFailureExit and acceptanceFailureCount >= failureCloses
strategy.close(inLong ? "CNPS60-L" : "CNPS60-S", comment="OPENING RANGE ACCEPTANCE FAILED", alert_message="⚡ ĐÓNG VỊ THẾ DO CHẤP NHẬN VÙNG MỞ CỬA THẤT BẠI (Acceptance Failed)")
int tradeEntryTime = strategy.opentrades.entry_time(0)
if useTimeExit and not na(time_close) and time_close >= tradeEntryTime + maximumHoldMinutes * 60000
strategy.close(inLong ? "CNPS60-L" : "CNPS60-S", comment="MAXIMUM HOLD EXIT", alert_message="⏱️ ĐÓNG VỊ THẾ HẾT THỜI GIAN GIỮ LỆNH (Time Exit)")
// ============================================================================
// SECTION 29: LUNCH / END OF DAY FORCE FLAT
// ============================================================================
if (lunchFlatBar or endFlatBar) and strategy.position_size != 0
strategy.close_all(immediately=true, comment="VN30F1M SESSION FLAT", alert_message="⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End)")
// ============================================================================
// SECTION 30: CLEAR STATE AFTER EXIT
// ============================================================================
if flat and not finalLong and not finalShort
activeStop := na
activeTarget := na
initialFillRisk := na
actualFillPrice := na
actualFillBar := na
acceptanceFailureCount := 0
breakEvenActivated := false
// ============================================================================
// SECTION 31: CLEAN CHART PLOTS ONLY
// ============================================================================
plot(showOpeningRange and openingReady ? openingHigh : na, title="Opening Range High", color=color.new(color.teal, 20), linewidth=2, style=plot.style_linebr)
plot(showOpeningRange and openingReady ? openingLow : na, title="Opening Range Low", color=color.new(color.red, 20), linewidth=2, style=plot.style_linebr)
plot(showVWAP ? sessionVWAP : na, title="Session VWAP", color=color.orange, linewidth=1, style=plot.style_linebr)
plot(showTradeLevels and strategy.position_size != 0 ? activeStop : na, title="Active Stop Loss", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showTradeLevels and strategy.position_size != 0 ? activeTarget : na, title="Active Take Profit", color=color.green, linewidth=2, style=plot.style_linebr)
// ============================================================================
// SECTION 32: CLEAN SIGNAL MARKERS - NO DASHBOARD
// ============================================================================
plotshape(showBreakouts and breakoutLongMark, title="Quality Long Breakout", style=shape.circle, location=location.belowbar, color=color.new(color.teal, 55), size=size.tiny)
plotshape(showBreakouts and breakoutShortMark, title="Quality Short Breakout", style=shape.circle, location=location.abovebar, color=color.new(color.red, 55), size=size.tiny)
plotshape(showRetests and retestLongMark, title="Accepted Long Retest", style=shape.circle, location=location.belowbar, color=color.teal, size=size.tiny)
plotshape(showRetests and retestShortMark, title="Accepted Short Retest", style=shape.circle, location=location.abovebar, color=color.red, size=size.tiny)
plotshape(showEntrySignals and finalLong, title="CNPS60 V2 LONG", style=shape.triangleup, location=location.belowbar, text="L", textcolor=color.white, color=color.teal, size=size.small)
plotshape(showEntrySignals and finalShort, title="CNPS60 V2 SHORT", style=shape.triangledown, location=location.abovebar, text="S", textcolor=color.white, color=color.red, size=size.small)
// ============================================================================
// RESEARCH NOTES
// ============================================================================
// - No diagnostic overlay or floating dashboard.
// - V2 tests stricter breakout acceptance, NOT a proven profitable setup.
// - Orders are emitted on confirmed bars and normally fill next bar.
// - Structural SL / fixed target are frozen at the signal bar.
// - No intrabar order-flow data or future candles are used.
// - Daily realized-loss guard only blocks additional entries.
// - Use realistic exchange margin and additional costs for live decisions.
// ============================================================================
2. Những khái niệm kỹ thuật cốt lõi trong CNPS60
2.1. Vùng mở cửa (Opening Range) phiên 09:00
Bot chia phiên giao dịch VN30F1M theo múi giờ Asia/Ho_Chi_Minh thành hai khung liên tục: phiên sáng (09:00–11:30, tức phút 540 đến < 690) và phiên chiều (13:00–14:30, tức phút 780 đến < 870).
Trong khoảng thời gian quan sát đầu phiên (openingObservation: từ 09:00 đến 09:00 + openingRangeMinutes, mặc định 09:15), bot liên tục cập nhật openingHigh và openingLow trên mỗi nến đã đóng (barstate.isconfirmed). Sau 09:15, vùng mở cửa chỉ được kích hoạt (openingReady = true) khi:
- Đã ghi nhận ít nhất
3nến trong vùng mở cửa (openingBars >= 3). - Độ rộng
openingWidth = openingHigh - openingLownằm trong biên[4.0, 55.0]điểm.
2.2. Đo lường chất lượng nến Breakout, Retest và Confirmation
Mọi cây nến đều được chuẩn hóa qua ATR(14) và cấu trúc thân nến:
- Biên độ nến:
candleRange = math.max(high - low, syminfo.mintick). - Tỷ lệ thân nến:
candleBodyRatio = |close - open| / candleRange. - Vị trí đóng cửa:
closeLocation = (close - low) / candleRange(từ0ở đáy nến đến1ở đỉnh nến).
Một nến Breakout tăng (bullishBreakCandle) phải là nến xanh (close > open), thân nến chiếm tối thiểu 40% biên độ (>= 0.40), đóng cửa ở top 35% trên cùng (closeLocation >= 0.65) và biên độ nến nằm trong 0.65 × ATR đến 2.20 × ATR. Ngược lại, Breakout giảm (bearishBreakCandle) yêu cầu nến đỏ, thân >= 40%, closeLocation <= 0.35 và biên độ tương tự. Nếu bật useBreakoutVolume, khối lượng nến Breakout phải đạt tối thiểu 1.10 lần trung bình 25 nến trước đó (ta.sma(volume, 25)[1]).
2.3. Bộ lọc xu hướng & cấu trúc phiên (EMA, DMI/ADX, Session VWAP)
- Xu hướng EMA & DMI: Sử dụng
EMA(34)kết hợp độ dốc chuẩn hóaemaSlope = (trendEMA - trendEMA[5]) / atrvà chỉ báota.dmi(14, 14). Chiều Long yêu cầuclose > trendEMA,emaSlope >= 0.00vàpDI >= mDI; chiều Short yêu cầu ngược lại (close < trendEMA,emaSlope <= 0.00,mDI >= pDI). - Session VWAP phiên liên tục: Bot tự tính
sessionVWAP = accumulatedPV / accumulatedVolumetừhlc3 * volumetrong giờ giao dịch liên tục và reset mỗi ngày mới. Mặc định (useVWAPFilter = true), lệnh Long phải nằm trênsessionVWAP, lệnh Short phải nằm dướisessionVWAP. - Bộ lọc ADX (tùy chọn): Khi bật
useADXFilter, yêu cầuadx >= 18.0.
3. Nguyên lý hoạt động của CNPS60
Bot vận hành theo máy trạng thái (setupState) trên từng nến đã đóng (barstate.isconfirmed):
- Bước 1 — Khởi tạo phiên & Khóa Opening Range: Sang ngày mới (
newTradingDay), toàn bộ biến đếm vàsessionVWAPđược reset. Sau09:15, nếuopeningWidthhợp lệ, trạng tháiopeningReadybật lên để sẵn sàng tìm tín hiệu. - Bước 2 — Chờ Breakout chất lượng (
setupState = 0): Khi chưa có vị thế và đang trong khung giờ vào lệnh (09:20–11:10hoặc13:05–14:05), nếu giá từ bên trong vùng OR bứt phá qua biên với nến đạt chuẩn Breakout, bot ghi nhậnbreakoutBar,breakoutHigh,breakoutLowvà chuyểnsetupStatesang1(Long) hoặc-1(Short). - Bước 3 — Kiểm tra Retest (
setupState = 1hoặc-1): Trong tối đa12 nến(maximumRetestBars), bot chờ giá hồi về chạm vùng biên OR (sai số ngoài biên0.45 × ATR, rút râu vào trong tối đa0.40 × ATR), nhưng vẫn đóng cửa giữ ngoài biên tối thiểu0.20điểm kèm nến xác nhận (bullishConfirmCandle/bearishConfirmCandle). Nếu chọnentryMode = "Retest Close", bot vào lệnh ngay; nếu chọn"Retest + Confirmation", bot chuyển sangsetupState = 2hoặc-2. (Với mode"Retest / Strong Follow-Through", nếu trong3 nếngiá phóng mạnh vượt đỉnh/đáy Breakout0.50 × ATRkèm đủ bộ lọc Trend & VWAP, bot vào lệnh tiếp diễn ngay). - Bước 4 — Xác nhận điểm vào lệnh (
setupState = 2hoặc-2): Trong tối đa4 nến(confirmationWindow), giá phải đóng cửa vượt đỉnh/đáy nến Retest tối thiểu0.20điểm và duy trì ngoài vùng OR để phát sinh tín hiệurawLong/rawShort. - Bước 5 — Kiểm tra Risk & Gửi lệnh: Bot tính Stop Loss cấu trúc từ
stopAnchor, kiểm trarisknằm trong[1.50, 9.0]điểm và mục tiêu tối thiểu3.0điểm. Đạt chuẩn mới gửi lệnhstrategy.entrykèmstrategy.exitbảo vệ ngay lập tức. Lưu ýsetupStatesẽ bị reset về0khi hết giờ giao dịch phiên sáng/chiều hoặc khi đến mốc đóng lệnh11:25/14:25.
4. Điều kiện vào lệnh Long và Short của CNPS60
4.1. Điều kiện vào lệnh Long
Tín hiệu finalLong được kích hoạt khi thỏa mãn đồng thời:
- Fresh Long Breakout (tại bước 1):
close[1] <= openingHigh + 0.60vàclose > openingHigh + 0.60, thỏabullishBreakCandle,breakoutVolumeOK,longTrendOK,longVWAPOK,adxOK. - Retest & Confirmation (theo
entryMode):- Nến Retest chạm vùng
openingHightrong phạm vi[openingHigh - 0.40 × ATR, openingHigh + 0.45 × ATR], đóng cửa> openingHigh + 0.20,closeLocation >= 0.60và thỏabullishConfirmCandle(close > open, thân>= 30%,closeLocation >= 0.55). - Nếu ở chế độ
Retest + Confirmation: trong vòng4 nếntiếp theo có nến đóng cửa> retestHigh + 0.20,> openingHigh + 0.20và thỏabullishConfirmCandle(không vi phạmclose < openingHigh - 0.40hoặclow < retestLow - 0.40 × ATR).
- Nến Retest chạm vùng
- Xác nhận cuối (
finalLong):longSideAvailable(cho phép Long và chưa vào lệnh Long trong ngày nếu bậtoneEntryPerSide),longTrendOK,longVWAPOK,adxOK,riskLongOKvàcommonEntryOK.
4.2. Điều kiện vào lệnh Short
Tín hiệu finalShort được kích hoạt đối xứng với chiều Long:
- Fresh Short Breakout:
close[1] >= openingLow - 0.60vàclose < openingLow - 0.60, thỏabearishBreakCandle,breakoutVolumeOK,shortTrendOK,shortVWAPOK,adxOK. - Retest & Confirmation:
- Nến Retest hồi lên chạm vùng
openingLowtrong phạm vi[openingLow - 0.45 × ATR, openingLow + 0.40 × ATR], đóng cửa< openingLow - 0.20,closeLocation <= 0.40và thỏabearishConfirmCandle(close < open, thân>= 30%,closeLocation <= 0.45). - Ở chế độ
Retest + Confirmation: trong4 nếntiếp theo có nến đóng cửa< retestLow - 0.20,< openingLow - 0.20và thỏabearishConfirmCandle(không vi phạmclose > openingLow + 0.40hoặchigh > retestHigh + 0.40 × ATR).
- Nến Retest hồi lên chạm vùng
- Xác nhận cuối (
finalShort):shortSideAvailable,shortTrendOK,shortVWAPOK,adxOK,riskShortOK,commonEntryOKvànot finalLong.
4.3. Điều kiện kiểm soát giao dịch chung (commonEntryOK)
- Trạng thái phẳng (
flat):strategy.position_size == 0(không nhồi lệnh,pyramiding=0). - Khung giờ giao dịch: Phiên sáng
09:20–11:10hoặc phiên chiều13:05–14:05, nằm trong phiên liên tục và trước giờ cắt lệnh (11:25buổi sáng,14:25buổi chiều). - Giới hạn tần suất:
tradesToday < 2, tối đa1lệnh mỗi chiều trong ngày (oneEntryPerSide = true), và đã qua8 nếnkể từ lần thoát lệnh gần nhất (cooldownBars = 8). - Bảo vệ lỗ ngày (
useDailyLossGuard = true): Tổng lãi/lỗ đã đóng trong ngày (dailyClosedPnL) phải lớn hơn-2.400.000 VNĐ.
5. Quản trị Stop Loss, Take Profit và Thoát lệnh
5.1. Cơ chế Stop Loss và bộ lọc Risk
- Điểm neo cấu trúc (
stopAnchor):- Với chế độ Retest:
stopAnchor = math.min(retestLow, openingHigh)cho Long vàmath.max(retestHigh, openingLow)cho Short. - Với chế độ Strong Follow-Through:
stopAnchor = openingHigh(Long) hoặcopeningLow(Short).
- Với chế độ Retest:
- Công thức SL:
candidateLongStop = math.round_to_mintick(stopAnchor - atr * 0.15)candidateShortStop = math.round_to_mintick(stopAnchor + atr * 0.15)
- Bộ lọc Risk hợp lệ: Khoảng cách
risk = |close - candidateStop|bắt buộc nằm trong[1.50, 9.0]điểm và mục tiêu thôrisk * 1.70 >= 3.0điểm.
5.2. Cơ chế Take Profit, Break Even và Thoát lệnh sớm
- Take Profit cố định theo R:
targetLong = close + riskLong * 1.70,targetShort = close - riskShort * 1.70(làm tròn theomintick). - Kiểm tra khớp lệnh thực tế (Fill Validation): Khi lệnh đã khớp, bot tính
initialFillRiskdựa trênstrategy.position_avg_price. Nếu do Gap khiếninitialFillRisk <= syminfo.mintickhoặcactiveTargetbị ngược phía giá khớp, bot đóng lệnh ngay lập tức (INVALID FILLED RISK). - Dời hòa vốn (Break Even - mặc định tắt): Khi bật
useBreakEven, nếu lợi nhuận đóng nến đạt>= 1.0R, SL được dời vềactualFillPrice ± 0.2điểm. - Thoát khi chấp nhận thất bại (
useAcceptanceFailureExit = true): Nếu giá đóng cửa quay lại bên trong Opening Range vượt quá0.40điểm trong2 nếnliên tiếp (failureCloses = 2), bot đóng lệnh sớm. - Thoát theo thời gian (
useTimeExit = true): Nếu thời gian giữ lệnh đạt hoặc vượt55 phút(maximumHoldMinutes), bot chủ động đóng vị thế. - Ép phẳng cuối phiên: Đóng toàn bộ vị thế bằng
strategy.close_all(immediately=true)tại mốc11:25(trước nghỉ trưa) và14:25(cuối ngày).
5.3. Bảng tổng hợp cơ chế bảo vệ vị thế
| Cơ chế bảo vệ | Điều kiện kích hoạt mặc định | Hành động của Bot |
|---|---|---|
| Stop Loss cấu trúc | Giá chạm stopAnchor ∓ 0.15 × ATR | Cắt lỗ qua lệnh strategy.exit (SL Long / SL Short) |
| Take Profit theo R | Giá chạm mức 1.70R (tối thiểu 3.0 điểm) | Chốt lời qua lệnh strategy.exit (TP Long / TP Short) |
| Invalid Gap Guard | initialFillRisk <= mintick hoặc TP sai phía | Đóng khẩn cấp ngay lập tức (INVALID FILLED RISK) |
| Break Even | Đang tắt (false); nếu bật: lãi đóng nến >= 1.0R | Dời SL về giá khớp ± 0.2 điểm (BE Long / BE Short) |
| Acceptance Failure Exit | Giá đóng cửa vào lại trong OR > 0.40 điểm trong 2 nến liên tiếp | Đóng lệnh sớm (OPENING RANGE ACCEPTANCE FAILED) |
| Maximum Hold Time | Thời gian giữ lệnh >= 55 phút | Đóng lệnh hết thời gian (MAXIMUM HOLD EXIT) |
| Session Force Flat | Nến chạm mốc 11:25 (sáng) hoặc 14:25 (chiều) | Đóng toàn bộ vị thế (VN30F1M SESSION FLAT) |
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 (khuyến nghị khung thời gian intraday như
1m,3mhoặc5mđể quan sát rõ vùng Opening Range 15 phút). - Nhấn vào tab Pine Editor ở thanh công cụ phía dưới màn hình.
- Xóa toàn bộ code mặc định, sao chép nguyên văn đoạn mã Pine Script v6 ở Mục 1 và dán vào Pine Editor.
- Nhấn Save (Lưu), đặt tên tùy chọn (ví dụ
CNPS60 ORA V2) rồi nhấn Add to chart để chạy chiến lược và kiểm tra kết quả trên Strategy Tester.
Cách đọc tín hiệu hiển thị trên biểu đồ (Không dùng bảng Diagnostics)
Phiên bản CNPS60 V2 - CLEAN chủ đích không vẽ bảng thống kê nổi (table.new / Dashboard) nhằm giữ biểu đồ tối giản, không che khuất hành động giá. Thay vào đó, toàn bộ trạng thái được trực quan hóa trực tiếp trên chart qua các lớp hiển thị (Section 11):
- Đường Opening Range High / Low (
showOpeningRange = true): Hai đường ngang màu xanh ngọc (High) và đỏ (Low) xuất hiện sau09:15khi biên độ vùng mở cửa hợp lệ. - Đường Active Stop Loss / Take Profit (
showTradeLevels = true): Đường ngang màu đỏ (SL) và xanh lá (TP) hiển thị trực tiếp khi đang có vị thế mở, giúp bạn theo dõi khoảng cách rủi ro theo thời gian thực. - Mũi tên vào lệnh (
showEntrySignals = true): Tam giác xanh hướng lên kèm chữLdưới chân nến (Long) và tam giác đỏ hướng xuống kèm chữStrên đầu nến (Short). - Các lớp tùy chọn (mặc định tắt): Bạn có thể bật thêm
showVWAP(đường cam Session VWAP),showBreakouts(chấm tròn mờ đánh dấu nến Breakout đạt chuẩn) vàshowRetests(chấm tròn đậm đánh dấu nến Retest được chấp nhận) trong phần Cài đặt của chỉ báo.
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 CNPS60 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 (hoặc phím tắt
Alt + A). - Tại mục Condition, chọn tên chiến lược
CNPS60 OPENING RANGE ACCEPTANCE V2 - CLEAN - VN30F1M. - Tại ô Message, xóa nội dung mặc định và nhập đúng cú pháp:
{{strategy.order.alert_message}} - Chọn kênh nhận thông báo (Notify in app, Webhook URL, Email…) và nhấn Create.
Bảng thông điệp Alert của CNPS60
| Sự kiện | Nội dung alert_message / alert_profit / alert_loss phát ra |
|---|---|
| Vào lệnh Long | 🟢 VÀO VỊ THẾ LONG (CNPS60)\n🎯 Giá vào: <close>\n🛑 Cắt lỗ (SL): <activeStop>\n🎯 Chốt lời (TP): <activeTarget> |
| Vào lệnh Short | 🔴 VÀO VỊ THẾ SHORT (CNPS60)\n🎯 Giá vào: <close>\n🛑 Cắt lỗ (SL): <activeStop>\n🎯 Chốt lời (TP): <activeTarget> |
| Chốt lời (TP Hit) | 💰 CHỐT LỜI LONG (TP HIT)\n🎯 Giá chốt lời: <activeTarget> (hoặc SHORT) |
| Cắt lỗ (SL Hit) | 🛑 CẮT LỖ LONG (SL HIT)\nGiá cắt lỗ: <activeStop> (hoặc SHORT) |
| Hòa vốn (BE Hit) | 🛡️ HÒA VỐN LONG (BE HIT)\nGiá hòa vốn: <activeStop> (hoặc SHORT, khi bật useBreakEven) |
| Lỗi Gap/Rủi ro | ⚠️ ĐÓNG VỊ THẾ DO GAP/RỦI RO KHÔNG HỢP LỆ (Invalid Gap) |
| Chấp nhận OR thất bại | ⚡ ĐÓNG VỊ THẾ DO CHẤP NHẬN VÙNG MỞ CỬA THẤT BẠI (Acceptance Failed) |
| Hết thời gian giữ lệnh | ⏱️ ĐÓNG VỊ THẾ HẾT THỜI GIAN GIỮ LỆNH (Time Exit) |
| Đóng vị thế hết phiên | ⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End) |
Kết luận
Bot CNPS60 (Opening Range Acceptance V2) là một hệ thống giao dịch VN30F1M có tính kỷ luật cao, phù hợp với những phiên thị trường có xu hướng rõ ràng sau 15 phút mở cửa và tôn trọng các mốc hỗ trợ/kháng cự đầu ngày. Nhờ cơ chế chỉ vào lệnh sau khi giá đã Breakout, Retest và xác nhận cấu trúc nến kết hợp quản trị rủi ro chặt chẽ theo ATR và giới hạn lỗ ngày, bot giúp hạn chế đáng kể rủi ro mua/bán đuổi trong các pha nhiễu đầu phiên.
Bạn có thể tham khảo thêm các hệ thống 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.





