Thứ Tư, 02/12/202602/12/2026

Hướng Dẫn Sử Dụng Bot CNPS82 - Outside Bar Reversal V1 cho VN30F1M

Bot CNPS82 Outside Bar Reversal V1 giao dịch đảo chiều từ nến Outside Bar trên VN30F1M, kết hợp lọc biên độ ATR, vị trí đóng cửa, 2 chế độ vào lệnh và quản trị SL/TP cố định.

Hướng dẫn sử dụng Bot CNPS82 cho VN30F1M
Hướng dẫn sử dụng Bot CNPS82 cho VN30F1M
Mục lục
Mục lục

Trong giao dịch hợp đồng tương lai chỉ số VN30F1M, thị trường thường xuyên xuất hiện những nhịp quét thanh khoản hai đầu: giá phá đỉnh hoặc thủng đáy của cây nến liền trước rồi nhanh chóng đảo chiều đóng cửa về phía ngược lại. Mẫu hình nến Outside Bar (nến bao trùm) phản ánh trực tiếp sự giằng co và hấp thụ lực cung/cầu tại các vùng giá nhạy cảm, nhưng nếu giao dịch cảm tính rất dễ rơi vào bẫy nhiễu khi biên độ nến quá hẹp hoặc quá giãn.

Chiến lược CNPS82 OUTSIDE BAR REVERSAL V1 (tên ngắn CNPS82 OB REV), được lập trình bằng Pine Script v6 trên TradingView, chuẩn hóa hoàn toàn quy trình phát hiện Outside Bar đảo chiều và kiểm soát rủi ro trong phiên.

Những điểm nổi bật cốt lõi của Bot CNPS82:

  • Chuẩn hóa mẫu hình Outside Bar theo ATR: Kết hợp kiểm tra nến bao trùm với biên độ hợp lệ (0.80 – 3.00 lần ATR(14)) và vị trí giá đóng cửa (closePosition).
  • 2 chế độ vào lệnh linh hoạt: Hỗ trợ vào lệnh ngay tại giá đóng cửa Outside Bar (Outside Bar Close) hoặc chờ nến xác nhận kế tiếp trong cửa sổ tối đa 3 nến (Next Candle Confirmation).
  • Bộ lọc đa tầng tùy chọn: Tích hợp sẵn lọc xu hướng EMA(50), RSI(14), ADX tối đa (35.0), Volume SMA(20) và xu hướng khung H1 (h1EMALength = 50).
  • Quản trị rủi ro kỷ luật: Cắt lỗ/Chốt lời cố định theo điểm (mặc định SL 5.0 điểm, TP 15.0 điểm), giới hạn tối đa 2 lệnh/ngày, cooldown 3 nến và tự động đóng toàn bộ vị thế lúc 14:45.

1. CNPS82 Outside Bar Reversal là gì?

CNPS82 Outside Bar Reversal là hệ thống giao dịch đảo chiều trong ngày (intraday) dựa trên cấu trúc nến Outside Bar, vận hành theo 4 trụ cột kỹ thuật chính:

  1. Nhận diện Outside Bar & Cấu trúc nến: Kiểm tra điều kiện nến hiện tại bao trùm nến trước đó (chế độ Strict hoặc Loose), đồng thời lọc biên độ nến theo ATR(14), kiểm tra vị trí giá đóng cửa trong biên độ nến (closePosition), hướng nến và tỷ lệ râu nến từ chối (useWickFilter).
  2. Cơ chế xác nhận vào lệnh (Entry Confirmation): Cho phép vào lệnh trực tiếp khi nến Outside Bar đóng cửa hoặc lưu trạng thái chờ (pendingLong / pendingShort) để xác nhận ở các nến tiếp theo với điều kiện hủy lệnh chờ nếu giá phá cực trị ngược lại.
  3. Hệ thống bộ lọc kỹ thuật tùy chọn: Cung cấp các công tắc bật/tắt độc lập cho EMA Trend, RSI, ADX, Volume và Confirmed H1 EMA Bias để thích nghi với từng giai đoạn thị trường.
  4. Kiểm soát phiên & Quản trị lệnh: Giới hạn khung giờ mở vị thế (09:15–14:15), số lệnh tối đa mỗi ngày (2 lệnh), thời gian nghỉ sau khi đóng lệnh (3 nến), tùy chọn thoát lệnh theo thời gian (Time Exit) và đóng vị thế cuối phiên (14:45).

Bảng thông số mặc định

Nhóm thông sốTên tham số trong codeGiá trị mặc địnhMô tả
01. Outside BarstrictOutsidetrueYêu cầu Outside Bar chặt (high > high[1] và low < low[1])
atrLength14Chu kỳ tính ATR
minRangeATR0.80Biên độ nến tối thiểu theo ATR
useMaxRangetrueLoại bỏ nến có biên độ quá lớn
maxRangeATR3.00Biên độ nến tối đa theo ATR
longClosePosition0.65Vị trí đóng cửa tối thiểu cho Long (0.0 – 1.0)
shortClosePosition0.35Vị trí đóng cửa tối đa cho Short (0.0 – 1.0)
requireOutsideDirectiontrueYêu cầu nến Outside Bar tăng cho Long / giảm cho Short
useWickFilterfalseBật bộ lọc tỷ lệ râu nến từ chối
minWickRatio0.20Tỷ lệ râu nến / biên độ nến tối thiểu
02. Entry ConfirmationentryMode"Outside Bar Close"Chế độ vào lệnh (Outside Bar Close / Next Candle Confirmation)
confirmationWindow3Số nến tối đa chờ xác nhận
requireConfirmCandletrueYêu cầu nến xác nhận cùng hướng
requireCloseBeyondSignaltrueYêu cầu đóng cửa vượt giá đóng cửa Outside Bar
requireBreakOutsideExtremefalseYêu cầu đóng cửa vượt High/Low của Outside Bar
cancelOnNewExtremetrueHủy setup chờ nếu giá phá cực trị ngược lại
03. EMA TrenduseEMAFilterfalseBật bộ lọc xu hướng EMA
emaLength50Chu kỳ EMA xu hướng
emaSlopeBars3Số nến so sánh độ dốc EMA
requirePriceEMAtrueYêu cầu giá nằm trên/dưới EMA
04. Optional FiltersuseRSIFilterfalseBật bộ lọc RSI
rsiLength14Chu kỳ RSI
longRSIMax60.0Ngưỡng RSI tối đa cho lệnh Long
shortRSIMin40.0Ngưỡng RSI tối thiểu cho lệnh Short
useADXFilterfalseBật bộ lọc ADX tối đa
diLength / adxSmoothing14 / 14Chu kỳ DI và làm mượt ADX
maxADX35.0Ngưỡng ADX tối đa cho phép vào lệnh
useVolumeFilterfalseBật bộ lọc khối lượng
volumeLength / volumeFactor20 / 1.20Chu kỳ SMA Volume và hệ số nhân tối thiểu
05. H1 TrenduseH1BiasfalseBật bộ lọc xu hướng EMA khung H1
h1EMALength50Chu kỳ EMA trên khung 60 phút
06. Risk ManagementstopLossPoints5.0Cắt lỗ cố định (điểm)
takeProfitPoints15.0Chốt lời cố định (điểm)
useTimeExitfalseBật thoát lệnh theo thời gian giữ lệnh
maxHoldingBars20Số nến giữ lệnh tối đa trước khi đóng
07. Trade ControltradeDirection"Long"Chiều giao dịch (Long, Short, Both)
contracts3Tham số số hợp đồng khai báo (lệnh strategy.entry dùng mặc định default_qty_value=1 của strategy)
maxTradesPerDay2Số lệnh tối đa trong một ngày
cooldownBars3Số nến nghỉ sau khi đóng lệnh
08. SessionuseSessionFiltertrueBật bộ lọc khung giờ giao dịch
tz"Asia/Ho_Chi_Minh"Múi giờ xử lý phiên
startHour : startMinute9 : 15Giờ bắt đầu mở vị thế
lastHour : lastMinute14 : 15Giờ cuối cùng được phép mở vị thế
endHour : endMinute14 : 45Giờ đóng toàn bộ vị thế cuối phiên
09. AlertsdisableExitAlertsfalseTắt cảnh báo SL/TP nếu đặt true
10. DisplayshowEMA, showOutsideBars, showSignalLevels, showEntries, showSLTPtrueHiển thị các đường và nhãn tín hiệu trên biểu đồ
showDiagnosticsfalseHiển thị bảng chẩn đoán góc trên bên phải

Source Code CNPS82 Outside Bar Reversal

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="CNPS82 OUTSIDE BAR REVERSAL V1", shorttitle="CNPS82 OB REV", 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)

// ============================================================
// CNPS82 - OUTSIDE BAR REVERSAL
//
// BULLISH:
// High > previous high
// Low < previous low
// Close in upper portion of outside candle
// Optional bullish candle confirmation
//
// BEARISH:
// High > previous high
// Low < previous low
// Close in lower portion of outside candle
// Optional bearish candle confirmation
//
// Entry modes:
// 1. Outside Bar Close
// 2. Next Candle Confirmation
//
// Exit:
// Fixed SL / TP based on entry fill price.
// ============================================================
// ============================================================
// 01. OUTSIDE BAR
// ============================================================
gOB = "01. Outside Bar"
strictOutside = input.bool(true, "Require Strict Outside Bar", group=gOB)
atrLength = input.int(14, "ATR Length", minval=1, group=gOB)
minRangeATR = input.float(0.80, "Minimum Outside Range / ATR", minval=0.0, step=0.1, group=gOB)
useMaxRange = input.bool(true, "Reject Excessively Large Bars", group=gOB)
maxRangeATR = input.float(3.00, "Maximum Outside Range / ATR", minval=0.1, step=0.1, group=gOB)
longClosePosition = input.float(0.65, "Minimum Long Close Position", minval=0.50, maxval=1.0, step=0.05, group=gOB)
shortClosePosition = input.float(0.35, "Maximum Short Close Position", minval=0.0, maxval=0.50, step=0.05, group=gOB)
requireOutsideDirection = input.bool(true, "Require Bullish/Bearish Outside Candle", group=gOB)
useWickFilter = input.bool(false, "Require Rejection Wick", group=gOB)
minWickRatio = input.float(0.20, "Minimum Wick / Candle Range", minval=0.0, maxval=1.0, step=0.05, group=gOB)

// ============================================================
// 02. ENTRY CONFIRMATION
// ============================================================
gConfirm = "02. Entry Confirmation"
entryMode = input.string("Outside Bar Close", "Entry Mode", options=["Outside Bar Close", "Next Candle Confirmation"], group=gConfirm)
confirmationWindow = input.int(3, "Maximum Confirmation Bars", minval=1, maxval=20, group=gConfirm)
requireConfirmCandle = input.bool(true, "Require Confirmation Candle Direction", group=gConfirm)
requireCloseBeyondSignal = input.bool(true, "Require Close Beyond Outside Bar Close", group=gConfirm)
requireBreakOutsideExtreme = input.bool(false, "Require Break Outside Bar High/Low", group=gConfirm)
cancelOnNewExtreme = input.bool(true, "Cancel When Outside Bar Extreme Is Broken", group=gConfirm)

// ============================================================
// 03. EMA TREND FILTER
// ============================================================
gTrend = "03. EMA Trend"
useEMAFilter = input.bool(false, "Use EMA Trend Filter", group=gTrend)
emaLength = input.int(50, "EMA Length", minval=5, group=gTrend)
emaSlopeBars = input.int(3, "EMA Slope Lookback", minval=1, maxval=50, group=gTrend)
requirePriceEMA = input.bool(true, "Require Price Above/Below EMA", group=gTrend)

// ============================================================
// 04. OPTIONAL FILTERS
// ============================================================
gFilters = "04. Optional Filters"
useRSIFilter = input.bool(false, "Use RSI Filter", group=gFilters)
rsiLength = input.int(14, "RSI Length", minval=2, group=gFilters)
longRSIMax = input.float(60.0, "Maximum RSI For Long", minval=1, maxval=100, group=gFilters)
shortRSIMin = input.float(40.0, "Minimum RSI For Short", minval=1, maxval=100, group=gFilters)
useADXFilter = input.bool(false, "Use Maximum ADX Filter", group=gFilters)
diLength = input.int(14, "DI Length", minval=2, group=gFilters)
adxSmoothing = input.int(14, "ADX Smoothing", minval=2, group=gFilters)
maxADX = input.float(35.0, "Maximum ADX", minval=1.0, step=1.0, group=gFilters)
useVolumeFilter = input.bool(false, "Require Volume Confirmation", group=gFilters)
volumeLength = input.int(20, "Volume MA Length", minval=2, group=gFilters)
volumeFactor = input.float(1.20, "Minimum Volume / Average", minval=0.1, step=0.1, group=gFilters)

// ============================================================
// 05. CONFIRMED H1 BIAS
// ============================================================
gH1 = "05. H1 Trend"
useH1Bias = input.bool(false, "Use Confirmed H1 EMA Bias", group=gH1)
h1EMALength = input.int(50, "H1 EMA Length", minval=1, group=gH1)

// ============================================================
// 06. RISK MANAGEMENT
// ============================================================
gRisk = "06. 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)
maxHoldingBars = input.int(20, "Maximum Holding Bars", minval=1, maxval=200, group=gRisk)

// ============================================================
// 07. TRADE CONTROL
// ============================================================
gTrade = "07. 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)
maxTradesPerDay = input.int(2, "Maximum Trades Per Day", minval=1, maxval=20, group=gTrade)
cooldownBars = input.int(3, "Cooldown After Exit (Bars)", minval=0, maxval=100, group=gTrade)
bool allowLong = (tradeDirection == "Long" or tradeDirection == "Both")
bool allowShort = (tradeDirection == "Short" or tradeDirection == "Both")

// ============================================================
// 08. TRADING SESSION
// ============================================================
gSession = "08. 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)

// ============================================================
// 09. ALERTS
// ============================================================
gAlerts = "09. Alerts"
disableExitAlerts = input.bool(false, "Disable SL/TP Alerts", group=gAlerts)

// ============================================================
// 10. DISPLAY
// ============================================================
gDisplay = "10. Display"
showEMA = input.bool(true, "Show EMA", group=gDisplay)
showOutsideBars = input.bool(true, "Show Outside Bar Markers", group=gDisplay)
showSignalLevels = input.bool(true, "Show Active Signal Levels", group=gDisplay)
showEntries = 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)

// ============================================================
// 11. TIME ENGINE
// ============================================================
int openMin = (hour(time, tz) * 60 + minute(time, tz))
int closeMin = (hour(time_close, tz) * 60 + minute(time_close, tz))
int entryStart = (startHour * 60 + startMinute)
int entryLast = (lastHour * 60 + lastMinute)
int forceCloseMin = (endHour * 60 + endMinute)
bool sessionOK = (not useSessionFilter or (openMin >= entryStart and closeMin <= entryLast))
bool beforeClose = (closeMin < forceCloseMin)
bool forceCloseBar = (openMin < forceCloseMin and closeMin >= forceCloseMin)
bool intradayOK = timeframe.isintraday

// ============================================================
// 12. DAILY COUNTER
// ============================================================
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

// ============================================================
// 13. ATR AND CANDLE ANATOMY
// ============================================================
float atr = ta.atr(atrLength)
float barRange = high - low
float body = math.abs(close - open)
float closePosition = (barRange > 0 ? (close - low) / barRange : 0.5)
float lowerWick = (math.min(open, close) - low)
float upperWick = (high - math.max(open, close))
float lowerWickRatio = (barRange > 0 ? lowerWick / barRange : 0.0)
float upperWickRatio = (barRange > 0 ? upperWick / barRange : 0.0)
bool bullishCandle = close > open
bool bearishCandle = close < open

// ============================================================
// 14. OUTSIDE BAR DETECTION
// ============================================================
bool strictOB = (high > high[1] and low < low[1])
bool looseOB = (high >= high[1] and low <= low[1] and (high > high[1] or low < low[1]))
bool outsidePattern = (strictOutside ? strictOB : looseOB)
bool minimumRangeOK = (not na(atr) and atr > 0 and barRange >= minRangeATR * atr)
bool maximumRangeOK = (not useMaxRange or (not na(atr) and barRange <= maxRangeATR * atr))
bool outsideBar = (barstate.isconfirmed and outsidePattern and minimumRangeOK and maximumRangeOK)

// ============================================================
// 15. REVERSAL CONDITIONS
// ============================================================
//
// Close position:
// 0.0 = close at candle low
// 1.0 = close at candle high
//
// LONG: strong close in upper part
// SHORT: weak close in lower part
//
// ============================================================
bool bullishClosePosition = (closePosition >= longClosePosition)
bool bearishClosePosition = (closePosition <= shortClosePosition)
bool bullishDirectionOK = (not requireOutsideDirection or bullishCandle)
bool bearishDirectionOK = (not requireOutsideDirection or bearishCandle)
bool bullishWickOK = (not useWickFilter or lowerWickRatio >= minWickRatio)
bool bearishWickOK = (not useWickFilter or upperWickRatio >= minWickRatio)
bool bullOutside = (outsideBar and bullishClosePosition and bullishDirectionOK and bullishWickOK)
bool bearOutside = (outsideBar and bearishClosePosition and bearishDirectionOK and bearishWickOK)

// ============================================================
// 16. EMA FILTER
// ============================================================
float ema = ta.ema(close, emaLength)
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)))

// ============================================================
// 17. RSI FILTER
// ============================================================
float rsi = ta.rsi(close, rsiLength)
bool longRSIOK = (not useRSIFilter or (not na(rsi) and rsi <= longRSIMax))
bool shortRSIOK = (not useRSIFilter or (not na(rsi) and rsi >= shortRSIMin))

// ============================================================
// 18. ADX FILTER
// ============================================================
[diPlus, diMinus, adx] = ta.dmi(diLength, adxSmoothing)
bool adxOK = (not useADXFilter or (not na(adx) and adx <= maxADX))

// ============================================================
// 19. VOLUME FILTER
// ============================================================
float avgVolume = ta.sma(volume, volumeLength)
bool volumeOK = (not useVolumeFilter or (not na(volume) and not na(avgVolume) and volume >= avgVolume * volumeFactor))

// ============================================================
// 20. 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))

// ============================================================
// 21. POSITION / COOLDOWN
// ============================================================
bool flat = strategy.position_size == 0
bool inLong = strategy.position_size > 0
bool inShort = strategy.position_size < 0
var int lastExitBar = na
bool closedTradeNow = (strategy.closedtrades > nz(strategy.closedtrades[1], 0))
if closedTradeNow
    lastExitBar := bar_index
bool cooldownOK = (na(lastExitBar) or bar_index - lastExitBar > cooldownBars)

// ============================================================
// 22. OUTSIDE BAR STATE
// ============================================================
//
// For confirmation mode, store the signal candle.
//
// The signal is valid only on future bars.
// Pending signals expire or invalidate.
//
// ============================================================
var bool pendingLong = false
var bool pendingShort = false
var int longSignalBar = na
var int shortSignalBar = na
var float longSignalHigh = na
var float longSignalLow = na
var float longSignalClose = na
var float shortSignalHigh = na
var float shortSignalLow = na
var float shortSignalClose = na
var int outsideCount = 0
var int bullOutsideCount = 0
var int bearOutsideCount = 0
var int longExpiredCount = 0
var int shortExpiredCount = 0

// ============================================================
// 23. CONFIRMATION WINDOW
// ============================================================
bool confirmationMode = (entryMode == "Next Candle Confirmation")
bool validLongWindow = (pendingLong and not na(longSignalBar) and bar_index > longSignalBar and bar_index - longSignalBar <= confirmationWindow)
bool validShortWindow = (pendingShort and not na(shortSignalBar) and bar_index > shortSignalBar and bar_index - shortSignalBar <= confirmationWindow)

// ============================================================
// 24. PRICE CONFIRMATION
// ============================================================
bool longConfirmCandleOK = (not requireConfirmCandle or bullishCandle)
bool shortConfirmCandleOK = (not requireConfirmCandle or bearishCandle)
bool longConfirmCloseOK = (not requireCloseBeyondSignal or (not na(longSignalClose) and close > longSignalClose))
bool shortConfirmCloseOK = (not requireCloseBeyondSignal or (not na(shortSignalClose) and close < shortSignalClose))
bool longConfirmExtremeOK = (not requireBreakOutsideExtreme or (not na(longSignalHigh) and close > longSignalHigh))
bool shortConfirmExtremeOK = (not requireBreakOutsideExtreme or (not na(shortSignalLow) and close < shortSignalLow))
bool longConfirmNotInvalid = (not cancelOnNewExtreme or (not na(longSignalLow) and low >= longSignalLow))
bool shortConfirmNotInvalid = (not cancelOnNewExtreme or (not na(shortSignalHigh) and high <= shortSignalHigh))
bool confirmedLong = (validLongWindow and longConfirmCandleOK and longConfirmCloseOK and longConfirmExtremeOK and longConfirmNotInvalid)
bool confirmedShort = (validShortWindow and shortConfirmCandleOK and shortConfirmCloseOK and shortConfirmExtremeOK and shortConfirmNotInvalid)

// ============================================================
// 25. ENTRY BASES
// ============================================================
bool longBase = (confirmationMode ? confirmedLong : bullOutside)
bool shortBase = (confirmationMode ? confirmedShort : bearOutside)

// ============================================================
// 26. FILTERED SIGNALS
// ============================================================
bool rawLong = (longBase and longTrendOK and longRSIOK and adxOK and volumeOK and longH1OK)
bool rawShort = (shortBase and shortTrendOK and shortRSIOK and adxOK and volumeOK and shortH1OK)

// ============================================================
// 27. ENTRY GATES
// ============================================================
var int lastEntryBar = na
bool freshEntryBar = (na(lastEntryBar) or lastEntryBar != bar_index)
bool canTrade = (barstate.isconfirmed and intradayOK and flat and strategy.opentrades == 0 and tradesToday < maxTradesPerDay and cooldownOK and sessionOK and beforeClose and freshEntryBar)
bool ambiguous = rawLong and rawShort
bool enterLong = (canTrade and allowLong and rawLong and not ambiguous)
bool enterShort = (canTrade and allowShort and rawShort and not ambiguous)

// ============================================================
// 28. DIAGNOSTIC COUNTERS
// ============================================================
var int longBaseCount = 0
var int shortBaseCount = 0
var int longFilteredCount = 0
var int shortFilteredCount = 0
var int longEntryCount = 0
var int shortEntryCount = 0

// ============================================================
// 29. SL / TP IN TICKS
// ============================================================
int slTicks = math.max(1, int(math.round(stopLossPoints / syminfo.mintick)))
int tpTicks = math.max(1, int(math.round(takeProfitPoints / syminfo.mintick)))
float effectiveSL = slTicks * syminfo.mintick
float effectiveTP = tpTicks * syminfo.mintick

// ============================================================
// 30. LONG ENTRY
// ============================================================
if enterLong
    strategy.entry("Long", strategy.long, comment="Bullish Outside Bar", alert_message="🟢 VÀO VỊ THẾ LONG (CNPS82)\\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

// ============================================================
// 31. SHORT ENTRY
// ============================================================
if enterShort
    strategy.entry("Short", strategy.short, comment="Bearish Outside Bar", alert_message="🔴 VÀO VỊ THẾ SHORT (CNPS82)\\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

// ============================================================
// 32. UPDATE SIGNAL STATE
// ============================================================
//
// Update AFTER evaluating current entry signals.
//
// A new Outside Bar cannot confirm itself
// in Next Candle Confirmation mode.
//
// ============================================================
if barstate.isconfirmed
    if outsideBar
        outsideCount += 1
    if bullOutside
        bullOutsideCount += 1
    if bearOutside
        bearOutsideCount += 1
    if longBase
        longBaseCount += 1
    if shortBase
        shortBaseCount += 1
    if rawLong
        longFilteredCount += 1
    if rawShort
        shortFilteredCount += 1

    // Reset pending signals on new day.
    if newDay
        pendingLong := false
        pendingShort := false
        longSignalBar := na
        shortSignalBar := na
        longSignalHigh := na
        longSignalLow := na
        longSignalClose := na
        shortSignalHigh := na
        shortSignalLow := na
        shortSignalClose := na

    // Expire or invalidate pending LONG.
    if pendingLong and not na(longSignalBar)
        bool longExpired = (bar_index - longSignalBar > confirmationWindow)
        bool longInvalid = (cancelOnNewExtreme and not na(longSignalLow) and low < longSignalLow)
        if longExpired or longInvalid
            pendingLong := false
            longSignalBar := na
            longExpiredCount += 1

    // Expire or invalidate pending SHORT.
    if pendingShort and not na(shortSignalBar)
        bool shortExpired = (bar_index - shortSignalBar > confirmationWindow)
        bool shortInvalid = (cancelOnNewExtreme and not na(shortSignalHigh) and high > shortSignalHigh)
        if shortExpired or shortInvalid
            pendingShort := false
            shortSignalBar := na
            shortExpiredCount += 1

    // Consumed setup.
    if enterLong
        pendingLong := false
        longSignalBar := na
    if enterShort
        pendingShort := false
        shortSignalBar := na

    // Register new confirmed Outside Bar
    // only in confirmation mode.
    //
    // A setup must not overwrite an active setup.
    bool canRegister = (confirmationMode and intradayOK and beforeClose and flat and not enterLong and not enterShort)
    if canRegister and bullOutside and not pendingLong
        pendingLong := true
        longSignalBar := bar_index
        longSignalHigh := high
        longSignalLow := low
        longSignalClose := close
        pendingShort := false
        shortSignalBar := na
    if canRegister and bearOutside and not pendingShort
        pendingShort := true
        shortSignalBar := bar_index
        shortSignalHigh := high
        shortSignalLow := low
        shortSignalClose := close
        pendingLong := false
        longSignalBar := na

// ============================================================
// 33. LONG SL / TP
// ============================================================
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 (CNPS82 - TP HIT)\\n🎯 Giá chốt lời: " + str.tostring(strategy.position_avg_price + effectiveTP, format.mintick), alert_loss="🛑 CẮT LỖ LONG (CNPS82 - SL HIT)\\n💥 Giá cắt lỗ: " + str.tostring(strategy.position_avg_price - effectiveSL, format.mintick), disable_alert=disableExitAlerts)

// ============================================================
// 34. SHORT SL / TP
// ============================================================
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 (CNPS82 - TP HIT)\\n🎯 Giá chốt lời: " + str.tostring(strategy.position_avg_price - effectiveTP, format.mintick), alert_loss="🛑 CẮT LỖ SHORT (CNPS82 - SL HIT)\\n💥 Giá cắt lỗ: " + str.tostring(strategy.position_avg_price + effectiveSL, format.mintick), disable_alert=disableExitAlerts)

// ============================================================
// 35. OPTIONAL TIME EXIT
// ============================================================
int barsHeld = (strategy.opentrades > 0 ? bar_index - strategy.opentrades.entry_bar_index(0) : 0)
bool timeExit = (useTimeExit and strategy.position_size != 0 and barsHeld >= maxHoldingBars 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 (CNPS82 - Time Exit)\\n📌 Giá đóng: " + str.tostring(close, format.mintick))

// ============================================================
// 36. SESSION END
// ============================================================
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 (CNPS82 - 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. OUTSIDE BAR MARKERS
// ============================================================
plotshape(showOutsideBars and bullOutside, title="Bullish Outside Bar", style=shape.circle, location=location.belowbar, color=color.aqua, size=size.tiny, text="OB")
plotshape(showOutsideBars and bearOutside, title="Bearish Outside Bar", style=shape.circle, location=location.abovebar, color=color.orange, size=size.tiny, text="OB")

// ============================================================
// 39. ACTIVE SIGNAL LEVELS
// ============================================================
plot(showSignalLevels and pendingLong ? longSignalHigh : na, title="Pending Long Signal High", color=color.aqua, linewidth=2, style=plot.style_linebr)
plot(showSignalLevels and pendingLong ? longSignalLow : na, title="Pending Long Signal Low", color=color.green, linewidth=1, style=plot.style_linebr)
plot(showSignalLevels and pendingShort ? shortSignalHigh : na, title="Pending Short Signal High", color=color.orange, linewidth=1, style=plot.style_linebr)
plot(showSignalLevels and pendingShort ? shortSignalLow : na, title="Pending Short Signal Low", color=color.red, linewidth=2, style=plot.style_linebr)

// ============================================================
// 40. ENTRY MARKERS
// ============================================================
plotshape(showEntries and enterLong, title="CNPS82 LONG", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, text="LONG", textcolor=color.white)
plotshape(showEntries and enterShort, title="CNPS82 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(atr, title="ATR", color=color.gray, display=display.data_window)
plot(closePosition, title="Outside Bar Close Position", color=color.blue, display=display.data_window)
plot(lowerWickRatio, title="Lower Wick Ratio", color=color.green, display=display.data_window)
plot(upperWickRatio, title="Upper Wick Ratio", color=color.red, display=display.data_window)
plot(rsi, title="RSI", color=color.purple, display=display.data_window)
plot(adx, title="ADX", color=color.orange, display=display.data_window)

// ============================================================
// 43. DIAGNOSTICS
// ============================================================
var table diagnostics = table.new(position.top_right, 2, 19, border_width=1)
if showDiagnostics and barstate.islast
    table.cell(diagnostics, 0, 0, "CNPS82 V1")
    table.cell(diagnostics, 1, 0, timeframe.period)
    table.cell(diagnostics, 0, 1, "Outside Bars")
    table.cell(diagnostics, 1, 1, str.tostring(outsideCount))
    table.cell(diagnostics, 0, 2, "Bull Outside")
    table.cell(diagnostics, 1, 2, str.tostring(bullOutsideCount))
    table.cell(diagnostics, 0, 3, "Bear Outside")
    table.cell(diagnostics, 1, 3, str.tostring(bearOutsideCount))
    table.cell(diagnostics, 0, 4, "Long Bases")
    table.cell(diagnostics, 1, 4, str.tostring(longBaseCount))
    table.cell(diagnostics, 0, 5, "Short Bases")
    table.cell(diagnostics, 1, 5, str.tostring(shortBaseCount))
    table.cell(diagnostics, 0, 6, "Filtered Long")
    table.cell(diagnostics, 1, 6, str.tostring(longFilteredCount))
    table.cell(diagnostics, 0, 7, "Filtered Short")
    table.cell(diagnostics, 1, 7, str.tostring(shortFilteredCount))
    table.cell(diagnostics, 0, 8, "Long Entries")
    table.cell(diagnostics, 1, 8, str.tostring(longEntryCount))
    table.cell(diagnostics, 0, 9, "Short Entries")
    table.cell(diagnostics, 1, 9, str.tostring(shortEntryCount))
    table.cell(diagnostics, 0, 10, "Pending Long")
    table.cell(diagnostics, 1, 10, pendingLong ? "YES" : "NO")
    table.cell(diagnostics, 0, 11, "Pending Short")
    table.cell(diagnostics, 1, 11, pendingShort ? "YES" : "NO")
    table.cell(diagnostics, 0, 12, "Expired Long")
    table.cell(diagnostics, 1, 12, str.tostring(longExpiredCount))
    table.cell(diagnostics, 0, 13, "Expired Short")
    table.cell(diagnostics, 1, 13, str.tostring(shortExpiredCount))
    table.cell(diagnostics, 0, 14, "EMA Up")
    table.cell(diagnostics, 1, 14, emaUp ? "YES" : "NO")
    table.cell(diagnostics, 0, 15, "EMA Down")
    table.cell(diagnostics, 1, 15, emaDown ? "YES" : "NO")
    table.cell(diagnostics, 0, 16, "RSI")
    table.cell(diagnostics, 1, 16, str.tostring(rsi, "#.##"))
    table.cell(diagnostics, 0, 17, "Trades Today")
    table.cell(diagnostics, 1, 17, str.tostring(tradesToday) + "/" + str.tostring(maxTradesPerDay))
    table.cell(diagnostics, 0, 18, "Position")
    table.cell(diagnostics, 1, 18, inLong ? "LONG" : inShort ? "SHORT" : "FLAT")

2. Những khái niệm kỹ thuật cốt lõi trong CNPS82

2.1. Cấu trúc Outside Bar, ATR và Vị trí đóng cửa

Bot kiểm tra nến hiện tại (khi đã đóng nến barstate.isconfirmed) có tạo thành mẫu hình Outside Bar hay không qua 2 chế độ:

  • Strict Outside Bar (strictOutside = true): high > high[1] và low < low[1].
  • Loose Outside Bar (strictOutside = false): high >= high[1] và low <= low[1] đồng thời có ít nhất một cực trị vượt hẳn (high > high[1] hoặc low < low[1]).

Biên độ nến barRange = high - low phải nằm trong dải hợp lệ so với atr = ta.atr(14):

  • barRange >= 0.80 * atr (tránh nến quá nhỏ, nhiễu).
  • Nếu useMaxRange = true: barRange <= 3.00 * atr (loại bỏ các cây nến biến động quá bất thường).

Để đo lực đảo chiều thực sự của Outside Bar, bot tính vị trí giá đóng cửa: closePosition = (close - low) / barRange (bằng 0.5 nếu barRange == 0).

  • Bullish Outside Bar (bullOutside): closePosition >= 0.65 (đóng cửa ở vùng trên), nến tăng close > open (nếu requireOutsideDirection = true), và tùy chọn râu dưới lowerWick / barRange >= 0.20 (nếu useWickFilter = true).
  • Bearish Outside Bar (bearOutside): closePosition <= 0.35 (đóng cửa ở vùng dưới), nến giảm close < open (nếu requireOutsideDirection = true), và tùy chọn râu trên upperWick / barRange >= 0.20 (nếu useWickFilter = true).

2.2. Hai chế độ vào lệnh và Cửa sổ xác nhận

  • Chế độ Outside Bar Close (mặc định): Khi xuất hiện bullOutside hoặc bearOutside đạt chuẩn, tín hiệu gốc (longBase / shortBase) được kích hoạt ngay tại giá đóng cửa của chính nến Outside Bar đó.
  • Chế độ Next Candle Confirmation: Nến Outside Bar chỉ đóng vai trò thiết lập setup chờ (pendingLong / pendingShort) và lưu lại High, Low, Close, bar_index. Trong tối đa confirmationWindow nến tiếp theo (mặc định 3 nến), bot chờ một nến xác nhận thỏa mãn: cùng hướng nến (requireConfirmCandle), đóng cửa vượt giá đóng cửa Outside Bar (requireCloseBeyondSignal), tùy chọn vượt High/Low của Outside Bar (requireBreakOutsideExtreme), và không vi phạm cực trị ngược lại (cancelOnNewExtreme).

2.3. Hệ thống bộ lọc kỹ thuật tùy chọn

Ngoài mẫu hình nến, CNPS82 tích hợp 5 bộ lọc (mặc định đang tắt để giữ tín hiệu nguyên bản, có thể bật từng phần):

  • EMA Trend (useEMAFilter): ema = ta.ema(close, 50). Long yêu cầu ema > ema[3] (EMA dốc lên) và close > ema; Short yêu cầu ema < ema[3] và close < ema.
  • RSI Filter (useRSIFilter): rsi = ta.rsi(close, 14). Long yêu cầu rsi <= 60.0 (tránh mua đuổi vùng quá mua), Short yêu cầu rsi >= 40.0 (tránh bán đuổi vùng quá bán).
  • ADX Filter (useADXFilter): Sử dụng ta.dmi(14, 14), chỉ cho phép giao dịch khi adx <= 35.0.
  • Volume Filter (useVolumeFilter): Yêu cầu volume >= ta.sma(volume, 20) * 1.20.
  • Confirmed H1 Bias (useH1Bias): Lấy ta.ema(close, 50)[1] và close[1] từ khung "60" (chỉ hợp lệ trên biểu đồ intraday nhỏ hơn 1 giờ), Long khi h1Close > h1EMA và Short khi h1Close < h1EMA.

3. Nguyên lý hoạt động của CNPS82

Quy trình vận hành của CNPS82 trên mỗi nến được thực thi tuần tự theo 5 bước:

  1. Khởi tạo phiên và bộ đếm ngày: Xác định dayKey theo múi giờ Asia/Ho_Chi_Minh. Khi sang ngày mới (newDay), bot reset tradesToday := 0 và xóa toàn bộ trạng thái pendingLong / pendingShort của ngày hôm trước.
  2. Đo lường nến và nhận diện Outside Bar: Trên mỗi nến đã đóng (barstate.isconfirmed), bot tính atr(14), barRange, closePosition, tỷ lệ râu nến và kiểm tra điều kiện bullOutside / bearOutside.
  3. Xác nhận tín hiệu gốc (longBase / shortBase): Nếu dùng Outside Bar Close, tín hiệu gốc lấy trực tiếp từ bullOutside / bearOutside. Nếu dùng Next Candle Confirmation, tín hiệu gốc lấy từ confirmedLong / confirmedShort dựa trên setup pending đã lưu ở các nến trước.
  4. Lọc điều kiện và gửi lệnh: Kết hợp tín hiệu gốc với các bộ lọc (EMA, RSI, ADX, Volume, H1 Bias) thành rawLong / rawShort. Nếu cổng giao dịch canTrade mở và không xảy ra xung đột ambiguous (rawLong and rawShort), bot gửi lệnh strategy.entry, tăng tradesToday và ghi nhận lastEntryBar.
  5. Cập nhật trạng thái & Quản trị thoát lệnh: Sau khi đánh giá vào lệnh, bot cập nhật các bộ đếm thống kê, hủy các setup pending hết hạn hoặc bị phá cực trị, đăng ký setup Outside Bar mới (nếu ở chế độ chờ xác nhận), đồng thời theo dõi strategy.exit (SL/TP), Time Exit và Session End.

4. Điều kiện vào lệnh Long và Short của CNPS82

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:

  1. Cổng giao dịch canTrade hợp lệ và chiều giao dịch cho phép Long (tradeDirection là "Long" hoặc "Both").
  2. Không xảy ra trạng thái xung đột ambiguous (not (rawLong and rawShort)).
  3. Tín hiệu gốc longBase hợp lệ:
    • Nếu entryMode == "Outside Bar Close": nến hiện tại là bullOutside (bao trùm nến trước, biên độ trong [0.80 * ATR, 3.00 * ATR], closePosition >= 0.65, nến tăng nếu bật requireOutsideDirection, râu dưới >= 0.20 nếu bật useWickFilter).
    • Nếu entryMode == "Next Candle Confirmation": có pendingLong còn hiệu lực trong confirmationWindow nến và nến hiện tại xác nhận tăng, đóng cửa trên longSignalClose (nếu bật), phá longSignalHigh (nếu bật) và low >= longSignalLow (nếu bật cancelOnNewExtreme).
  4. Thỏa mãn các bộ lọc đang bật: longTrendOK, longRSIOK, adxOK, volumeOK, longH1OK.

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:

  1. Cổng giao dịch canTrade hợp lệ và chiều giao dịch cho phép Short (tradeDirection là "Short" hoặc "Both").
  2. Không xảy ra trạng thái xung đột ambiguous.
  3. Tín hiệu gốc shortBase hợp lệ:
    • Nếu entryMode == "Outside Bar Close": nến hiện tại là bearOutside (bao trùm nến trước, biên độ trong [0.80 * ATR, 3.00 * ATR], closePosition <= 0.35, nến giảm nếu bật requireOutsideDirection, râu trên >= 0.20 nếu bật useWickFilter).
    • Nếu entryMode == "Next Candle Confirmation": có pendingShort còn hiệu lực trong confirmationWindow nến và nến hiện tại xác nhận giảm, đóng cửa dưới shortSignalClose (nếu bật), phá shortSignalLow (nếu bật) và high <= shortSignalHigh (nếu bật cancelOnNewExtreme).
  4. Thỏa mãn các bộ lọc đang bật: shortTrendOK, shortRSIOK, adxOK, volumeOK, shortH1OK.

4.3. Điều kiện kiểm soát giao dịch chung

Biến canTrade kiểm soát toàn bộ việc mở vị thế mới:

  • Nến đã đóng & Intraday: barstate.isconfirmed và timeframe.isintraday.
  • Không đang giữ lệnh: strategy.position_size == 0 (flat) và strategy.opentrades == 0, đồng thời freshEntryBar đảm bảo không vào lại trên cùng nến.
  • Giới hạn số lệnh/ngày: tradesToday < maxTradesPerDay (mặc định tối đa 2 lệnh/ngày).
  • Thời gian nghỉ (Cooldown): bar_index - lastExitBar > cooldownBars (mặc định nghỉ ít nhất 3 nến sau khi đóng lệnh trước).
  • Khung giờ phiên: sessionOK (09:15 đến 14:15 theo Asia/Ho_Chi_Minh) và beforeClose (thời gian đóng nến < 14:45).

5. Quản trị Stop Loss, Take Profit và Thoát lệnh

5.1. Cơ chế Stop Loss và quy đổi Tick

Bot không sử dụng bộ lọc Min–Max Risk theo biên độ nến mà áp dụng Stop Loss cố định theo điểm (stopLossPoints, mặc định 5.0 điểm):

  • Số tick cắt lỗ được tính bằng: slTicks = math.max(1, int(math.round(stopLossPoints / syminfo.mintick))).
  • Khoảng cắt lỗ thực tế: effectiveSL = slTicks * syminfo.mintick.
  • Với lệnh Long, SL đặt tại strategy.position_avg_price - effectiveSL. Với lệnh Short, SL đặt tại strategy.position_avg_price + effectiveSL.

5.2. Cơ chế Take Profit, Time Exit và Đóng lệnh cuối phiên

  • Take Profit cố định: Tính từ takeProfitPoints (mặc định 15.0 điểm, tương ứng tỷ lệ Risk:Reward mặc định 1:3), quy đổi sang tick qua tpTicks và effectiveTP. Bot không sử dụng Break Even hay Trailing Stop.
  • Thoát lệnh theo thời gian (Time Exit): Khi bật useTimeExit = true, nếu số nến giữ lệnh barsHeld >= maxHoldingBars (mặc định 20 nến) khi nến đóng và chưa đến giờ đóng phiên, bot gọi strategy.close_all để đóng vị thế.
  • Đóng lệnh cuối phiên (Session End): Tại nến thỏa forceCloseBar (openMin < 14:45 và closeMin >= 14:45), nếu đang có vị thế (strategy.position_size != 0), bot bắt buộc đóng toàn bộ lệnh để không giữ qua đêm.

5.3. Bảng tổng hợp cơ chế bảo vệ vị thế

Cơ chế thoát lệnhĐiều kiện kích hoạtHành động thực thiTrạng thái mặc định
Stop Loss (SL)Giá chạm avg_price - effectiveSL (Long) hoặc avg_price + effectiveSL (Short)strategy.exit đóng vị thế (SL Long / SL Short)Bật (5.0 điểm)
Take Profit (TP)Giá chạm avg_price + effectiveTP (Long) hoặc avg_price - effectiveTP (Short)strategy.exit chốt lời (TP Long / TP Short)Bật (15.0 điểm)
Time ExitbarsHeld >= maxHoldingBars tại nến đóng (not forceCloseBar)strategy.close_all(immediately=true) (Time Exit)Tắt (useTimeExit = false)
Session EndNến chạm mốc 14:45 (forceCloseBar) khi đang có vị thếstrategy.close_all(immediately=true) (Session End)Luôn bật

6. Hướng dẫn cài đặt và đọc bảng Diagnostics trên TradingView

Các bước cài đặt

  1. Mở biểu đồ hợp đồng phái sinh VN30F1M trên TradingView (khung thời gian intraday như M5 hoặc M15; lưu ý nếu bật useH1Bias thì khung biểu đồ phải nhỏ hơn 60 phút).
  2. Nhấp vào tab Pine Editor ở phía dưới màn hình.
  3. Xóa code mẫu mặc định, dán toàn bộ mã nguồn Pine Script v6 của CNPS82 ở Mục 1 vào trình soạn thảo.
  4. Nhấn Save để lưu script, sau đó nhấn Add to chart để gắn bot lên biểu đồ.
  5. Mở biểu tượng bánh răng (Settings) của chiến lược để tùy chỉnh tradeDirection (Long, Short, hoặc Both), entryMode và các bộ lọc theo nhu cầu.

Cách đọc bảng chẩn đoán (Diagnostics Table)

Khi bật showDiagnostics = true trong phần 10. Display, bot hiển thị bảng table.new gồm 19 dòng ở góc trên bên phải biểu đồ (position.top_right):

  • CNPS82 V1: Hiển thị khung thời gian hiện tại của biểu đồ (timeframe.period).
  • Outside Bars / Bull Outside / Bear Outside: Tổng số nến Outside Bar hợp lệ, số nến tăng và số nến giảm được phát hiện.
  • Long Bases / Short Bases: Số lượng tín hiệu gốc đạt chuẩn trước khi qua bộ lọc.
  • Filtered Long / Filtered Short: Số tín hiệu vượt qua toàn bộ các bộ lọc (EMA, RSI, ADX, Volume, H1 Bias).
  • Long Entries / Short Entries: Số lệnh Long và Short thực tế đã khớp.
  • Pending Long / Pending Short: Trạng thái có đang chờ nến xác nhận (YES / NO) trong chế độ Next Candle Confirmation hay không.
  • Expired Long / Expired Short: Số lượng setup chờ bị hết hạn hoặc bị hủy do giá phá cực trị ngược lại.
  • EMA Up / EMA Down: Trạng thái độ dốc EMA hiện tại (YES / NO).
  • RSI: Giá trị RSI(14) hiện tại.
  • Trades Today: Số lệnh đã giao dịch trong ngày trên tổng giới hạn (tradesToday / maxTradesPerDay).
  • 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 thời gian thực qua ứng dụng TradingView, Telegram hoặc Webhook:

  1. Nhấp vào biểu tượng Alert (hình đồng hồ) trên thanh công cụ TradingView.
  2. Tại mục Condition, chọn chiến lược CNPS82 OUTSIDE BAR REVERSAL V1.
  3. Tại mục Message, xóa nội dung mặc định và nhập chính xác: {{strategy.order.alert_message}}.
  4. Đặt tên cảnh báo và nhấn Create. (Lưu ý: nếu muốn tắt thông báo khi chạm SL/TP và chỉ giữ thông báo vào lệnh/đóng phiên, hãy bật disableExitAlerts = true trong cài đặt bot).

Bảng thông điệp Alert của CNPS82

Sự kiệnThông điệp Alert thực tế trong code
Vào lệnh Long🟢 VÀO VỊ THẾ LONG (CNPS82) kèm 🎯 Giá vào, 🛑 Cắt lỗ (SL), 💰 Chốt lời (TP)
Vào lệnh Short🔴 VÀO VỊ THẾ SHORT (CNPS82) kèm 🎯 Giá vào, 🛑 Cắt lỗ (SL), 💰 Chốt lời (TP)
Chốt lời Long (TP)💰 CHỐT LỜI LONG (CNPS82 - TP HIT) kèm 🎯 Giá chốt lời
Cắt lỗ Long (SL)🛑 CẮT LỖ LONG (CNPS82 - SL HIT) kèm 💥 Giá cắt lỗ
Chốt lời Short (TP)💰 CHỐT LỜI SHORT (CNPS82 - TP HIT) kèm 🎯 Giá chốt lời
Cắt lỗ Short (SL)🛑 CẮT LỖ SHORT (CNPS82 - SL HIT) kèm 💥 Giá cắt lỗ
Đóng hết thời gian⏱️ ĐÓNG VỊ THẾ HẾT THỜI GIAN (CNPS82 - Time Exit) kèm 📌 Giá đóng
Đóng hết phiên⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (CNPS82 - Session End) kèm 📌 Giá đóng

Kết luận

CNPS82 Outside Bar Reversal V1 là hệ thống giao dịch đảo chiều có tính kỷ luật cao cho VN30F1M, nổi bật nhờ khả năng lọc nhiễu biên độ nến bằng ATR, kiểm soát vị trí đóng cửa, hỗ trợ xác nhận nến kế tiếp và quản trị SL/TP cố định rõ ràng. Chiến lược phát huy hiệu quả tốt nhất khi thị trường có các nhịp quét thanh khoản rõ nét hoặc dao động trong biên độ ổn định, đồng thời hạn chế rủi ro giữ lệnh qua đêm nhờ cơ chế tự động đóng vị thế lúc 14:45.

Bạn có thể tham khảo thêm các hệ thống giao dịch khác trên VN30F1M 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.

Đinh Mạnh Đạt

Nhà nghiên cứu định lượng, chuyên sâu về dữ liệu Open Interest và quản trị vị thế.

Bản tin phái sinh mỗi phiên
Nhận bản tin mỗi phiên + Dự báo Nhịp đập phái sinh

Giao dịch & cuộc sống

Xem tất cả →
Cộng đồng