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

Hướng Dẫn Sử Dụng Bot CNPS86 - OBV Divergence Break V1 cho VN30F1M

Bot CNPS86 phát hiện phân kỳ OBV theo đỉnh/đáy Pivot xác nhận, chờ phá vỡ cấu trúc ngắn hạn kèm bộ lọc xu hướng EMA, H1 Bias, ADX/RSI và quản trị rủi ro cố định cho VN30F1M.

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

Khi giao dịch hợp đồng tương lai VN30F1M trong ngày, một trong những sai lầm phổ biến nhất của nhà giao dịch là bắt đỉnh/đáy quá sớm ngay khi thấy dấu hiệu phân kỳ trên chỉ báo, dẫn đến việc bị quét cắt lỗ liên tục nếu xu hướng cũ vẫn còn quán tính. Ngoài ra, nhiều hệ thống phân kỳ trên TradingView sử dụng hàm Pivot nhưng vào lệnh hồi tố trên nến quá khứ, gây sai lệch kết quả kiểm thử (repaint).

CNPS86 OBV Divergence Break V1 (strategy(title="CNPS86 OBV DIVERGENCE BREAK V1")) được viết bằng Pine Script v6 trên TradingView để giải quyết triệt để hai vấn đề trên. Thay vì vào lệnh ngay tại nến xuất hiện phân kỳ, bot chỉ ghi nhận tín hiệu sau khi Pivot được xác nhận hoàn toàn và kiên nhẫn chờ giá phá vỡ một ngưỡng cấu trúc ngắn hạn thực tế.

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

  • Không repaint Pivot: Chỉ xác nhận đỉnh/đáy sau khi đóng đủ pivotRight nến tương lai và chỉ kích hoạt trạng thái chờ ở các nến xác nhận tiếp theo (barstate.isconfirmed).
  • Kết hợp dòng tiền OBV và phá vỡ cấu trúc: Phân kỳ giữa giá và On-Balance Volume (OBV) được xác nhận lại bằng một cú bứt phá qua structureHigh / structureLow kèm khoảng đệm ATR.
  • Bộ lọc tùy chọn đa tầng: Hỗ trợ lọc theo xu hướng EMA, sức mạnh xu hướng ADX tối đa, ngưỡng RSI và xu hướng khung H1 (Confirmed H1 EMA Bias).
  • Kiểm soát kỷ luật giao dịch chặt chẽ: Giới hạn số lệnh/ngày, thời gian nghỉ (cooldown) sau khi thoát lệnh, khung giờ vào lệnh và tự động đóng toàn bộ vị thế trước giờ ATC (14:45).

1. CNPS86 OBV Divergence Break V1 là gì?

CNPS86 OBV Divergence Break V1 là chiến lược giao dịch theo xu hướng đảo chiều có xác nhận (Confirmed Divergence Breakout) dành cho thị trường phái sinh intraday. Hệ thống vận hành dựa trên 4 trụ cột kỹ thuật chính:

  1. Nhận diện Pivot giá và lấy mẫu OBV: Sử dụng ta.pivotlow và ta.pivothigh để xác định các đỉnh/đáy cục bộ, đồng thời lấy giá trị obv[pivotRight] ngay tại cây nến tạo Pivot đó để so sánh giữa hai nhịp sóng liên tiếp.
  2. Đo lường phân kỳ Bullish / Bearish OBV: So sánh đỉnh/đáy Pivot mới với đỉnh/đáy Pivot cùng loại liền trước trong khoảng cách hợp lệ (minimumPivotGap đến maximumPivotGap), có tùy chọn lọc độ lệch tối thiểu của giá theo ATR và của OBV theo khối lượng trung bình.
  3. Máy trạng thái (State Machine) chờ phá vỡ cấu trúc: Khi phân kỳ hình thành, bot lưu lại ngưỡng kích hoạt (longTrigger / shortTrigger) và ngưỡng vô hiệu (longInvalidLevel / shortInvalidLevel), chờ nến đóng cửa vượt ngưỡng phá vỡ trong giới hạn confirmationWindow nến.
  4. Hệ thống lọc tín hiệu & quản trị rủi ro cố định: Kết hợp bộ lọc EMA, ADX, RSI, H1 EMA Bias cùng Stop Loss / Take Profit cố định theo điểm (quy đổi ra tick), tùy chọn Time Exit và tự động tất toán cuối phiên.

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

Dưới đây là toàn bộ 11 nhóm tham số (input.*) và giá trị mặc định được lập trình trong mã nguồn CNPS86:

Nhóm thông sốTên tham sốGiá trị mặc địnhÝ nghĩa
01. Price / OBV PivotspivotLeft / pivotRight3 / 3Số nến trái/phải để xác nhận Pivot
minimumPivotGap / maximumPivotGap5 / 80Khoảng cách nến tối thiểu/tối đa giữa 2 Pivot
02. Divergence FiltersatrLength / volumeLength14 / 20Chu kỳ tính ATR và khối lượng trung bình
usePriceDifference / minimumPriceDifferenceATRfalse / 0.10Lọc độ lệch giá tối thiểu theo hệ số ATR
useOBVDifference / minimumOBVVolumeUnitsfalse / 1.0Lọc độ lệch OBV tối thiểu theo Avg Volume
03. Breakout ConfirmationstructureLookback / confirmationWindow5 / 8Số nến tìm đỉnh/đáy cấu trúc & cửa sổ chờ xác nhận
useBreakoutBuffer / breakoutBufferATRtrue / 0.05Đệm phá vỡ tính theo hệ số ATR
requireBreakoutCandle / cancelOnNewExtremetrue / trueYêu cầu nến cùng chiều & hủy setup nếu phá cực trị
04. EMA TrenduseEMAFilter / emaLengthfalse / 50Bật/tắt lọc EMA và chu kỳ EMA
emaSlopeBars / requirePriceEMA3 / trueĐộ dốc EMA và yêu cầu giá nằm trên/dưới EMA
05. Optional FiltersuseADXFilter / diLength / adxSmoothing / maximumADXfalse / 14 / 14 / 35.0Lọc ADX tối đa tránh thị trường quá căng
useRSIFilter / rsiLength / longRSIMax / shortRSIMinfalse / 14 / 65.0 / 35.0Giới hạn RSI trần cho Long và sàn cho Short
06. H1 BiasuseH1Bias / h1EMALengthfalse / 50Lọc xu hướng theo EMA khung H1 đã đóng
07. Risk ManagementstopLossPoints / takeProfitPoints5.0 / 15.0Cắt lỗ và chốt lời cố định (điểm)
useTimeExit / maximumHoldingBarsfalse / 20Đóng lệnh nếu giữ quá số nến tối đa
08. Trade ControltradeDirection / contracts"Long" / 3Chiều giao dịch (Long, Short, Both) và số hợp đồng
maximumTradesPerDay / cooldownBars2 / 3Giới hạn lệnh/ngày và số nến nghỉ sau khi đóng lệnh
09. SessionuseSessionFilter / tztrue / "Asia/Ho_Chi_Minh"Lọc phiên giao dịch theo múi giờ Việt Nam
startHour:startMinute / lastHour:lastMinute09:15 / 14:15Khung giờ cho phép mở vị thế mới
endHour:endMinute14:45Giờ bắt buộc đóng toàn bộ vị thế (Force Close)
10. AlertsdisableExitAlertsfalseTắt/bật thông báo khi chạm SL/TP
11. DisplayshowEMA, showDivergenceMarkers, showTriggerLevels, showEntryMarkers, showSLTPtrueHiển thị các đường và nhãn tín hiệu trên biểu đồ
showPivotMarkers, showDiagnosticsfalseHiển thị nhãn PL/PH và bảng thống kê Diagnostics

Source Code CNPS86 OBV Divergence Break V1

Bạn có thể sao chép toàn bộ mã nguồn Pine Script v6 dưới đây để dán trực tiếp vào Pine Editor trên TradingView:

//@version=6
strategy(title="CNPS86 OBV DIVERGENCE BREAK V1", shorttitle="CNPS86 OBV DIV", 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)

// ============================================================================
// CNPS86 - OBV DIVERGENCE BREAK
//
// BULLISH DIVERGENCE:
// Price pivot low forms a lower low.
// OBV at that pivot forms a higher low.
//
// BEARISH DIVERGENCE:
// Price pivot high forms a higher high.
// OBV at that pivot forms a lower high.
//
// ENTRY:
// Wait for price to break a stored
// short-term structure level.
//
// IMPORTANT:
// Pivots are confirmed after RIGHT bars.
// No orders are placed on the historical
// pivot candle itself.
//
// The strategy uses confirmed bars,
// standard entry/exit orders and
// daily risk controls.
// ============================================================================
// ============================================================================
// 01. PIVOT SETTINGS
// ============================================================================
gPivot = "01. Price / OBV Pivots"
pivotLeft = input.int(3, "Pivot Left Bars", minval=1, maxval=30, group=gPivot)
pivotRight = input.int(3, "Pivot Right Bars", minval=1, maxval=30, group=gPivot)
minimumPivotGap = input.int(5, "Minimum Bars Between Pivots", minval=1, maxval=200, group=gPivot)
maximumPivotGap = input.int(80, "Maximum Bars Between Pivots", minval=2, maxval=500, group=gPivot)

// ============================================================================
// 02. DIVERGENCE FILTERS
// ============================================================================
gDiv = "02. Divergence Filters"
atrLength = input.int(14, "ATR Length", minval=1, group=gDiv)
usePriceDifference = input.bool(false, "Require Minimum Price Divergence", group=gDiv)
minimumPriceDifferenceATR = input.float(0.10, "Minimum Price Difference / ATR", minval=0.0, step=0.05, group=gDiv)
useOBVDifference = input.bool(false, "Require Minimum OBV Difference", group=gDiv)
minimumOBVVolumeUnits = input.float(1.0, "Minimum OBV Difference / Average Volume", minval=0.0, step=0.25, group=gDiv)
volumeLength = input.int(20, "Average Volume Length", minval=2, group=gDiv)

// ============================================================================
// 03. STRUCTURE BREAK
// ============================================================================
gBreak = "03. Breakout Confirmation"
structureLookback = input.int(5, "Structure Lookback", minval=2, maxval=100, group=gBreak)
confirmationWindow = input.int(8, "Maximum Confirmation Bars", minval=1, maxval=50, group=gBreak)
useBreakoutBuffer = input.bool(true, "Require Breakout Buffer", group=gBreak)
breakoutBufferATR = input.float(0.05, "Breakout Buffer / ATR", minval=0.0, step=0.05, group=gBreak)
requireBreakoutCandle = input.bool(true, "Require Breakout Candle Direction", group=gBreak)
cancelOnNewExtreme = input.bool(true, "Cancel If Divergence Extreme Breaks", group=gBreak)

// ============================================================================
// 04. EMA TREND
// ============================================================================
gTrend = "04. 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)

// ============================================================================
// 05. OPTIONAL FILTERS
// ============================================================================
gFilters = "05. Optional Filters"
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)
maximumADX = input.float(35.0, "Maximum ADX", minval=1.0, step=1.0, group=gFilters)
useRSIFilter = input.bool(false, "Use RSI Filter", group=gFilters)
rsiLength = input.int(14, "RSI Length", minval=2, group=gFilters)
longRSIMax = input.float(65.0, "Maximum RSI For Long", minval=1, maxval=100, group=gFilters)
shortRSIMin = input.float(35.0, "Minimum RSI For Short", minval=0, maxval=99, group=gFilters)

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

// ============================================================================
// 07. RISK MANAGEMENT
// ============================================================================
gRisk = "07. Risk Management"
stopLossPoints = input.float(5.0, "Stop Loss (Points)", minval=0.1, step=0.5, group=gRisk)
takeProfitPoints = input.float(15.0, "Take Profit (Points)", minval=0.1, step=0.5, group=gRisk)
useTimeExit = input.bool(false, "Use Maximum Holding Bars", group=gRisk)
maximumHoldingBars = input.int(20, "Maximum Holding Bars", minval=1, maxval=200, group=gRisk)

// ============================================================================
// 08. TRADE CONTROL
// ============================================================================
gTrade = "08. Trade Control"
tradeDirection = input.string("Long", "Trade Direction", options=["Long", "Short", "Both"], group=gTrade)
contracts = input.int(3, "Contracts", minval=1, maxval=100, group=gTrade)
maximumTradesPerDay = input.int(2, "Maximum Trades Per Day", minval=1, maxval=20, group=gTrade)
cooldownBars = input.int(3, "Cooldown Bars After Exit", minval=0, maxval=100, group=gTrade)
bool allowLong = (tradeDirection == "Long" or tradeDirection == "Both")
bool allowShort = (tradeDirection == "Short" or tradeDirection == "Both")

// ============================================================================
// 09. TRADING SESSION
// ============================================================================
gSession = "09. Session"
useSessionFilter = input.bool(true, "Use Entry Session Filter", group=gSession)
tz = input.string("Asia/Ho_Chi_Minh", "Timezone", group=gSession)
startHour = input.int(9, "Entry Start Hour", minval=0, maxval=23, group=gSession)
startMinute = input.int(15, "Entry Start Minute", minval=0, maxval=59, group=gSession)
lastHour = input.int(14, "Last Entry Hour", minval=0, maxval=23, group=gSession)
lastMinute = input.int(15, "Last Entry Minute", minval=0, maxval=59, group=gSession)
endHour = input.int(14, "Force Close Hour", minval=0, maxval=23, group=gSession)
endMinute = input.int(45, "Force Close Minute", minval=0, maxval=59, group=gSession)

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

// ============================================================================
// 11. DISPLAY
// ============================================================================
gDisplay = "11. Display"
showEMA = input.bool(true, "Show EMA", group=gDisplay)
showPivotMarkers = input.bool(false, "Show Confirmed Pivot Markers", group=gDisplay)
showDivergenceMarkers = input.bool(true, "Show OBV Divergence Markers", group=gDisplay)
showTriggerLevels = input.bool(true, "Show Pending Structure Levels", group=gDisplay)
showEntryMarkers = input.bool(true, "Show Entry Markers", group=gDisplay)
showSLTP = input.bool(true, "Show Active SL/TP", group=gDisplay)
showDiagnostics = input.bool(false, "Show Diagnostics", group=gDisplay)

// ============================================================================
// 12. TIME ENGINE
// ============================================================================
int openMinutes = (hour(time, tz) * 60 + minute(time, tz))
int closeMinutes = (hour(time_close, tz) * 60 + minute(time_close, tz))
int entryStartMinutes = (startHour * 60 + startMinute)
int lastEntryMinutes = (lastHour * 60 + lastMinute)
int forceCloseMinutes = (endHour * 60 + endMinute)
bool intradayOK = timeframe.isintraday
bool entrySessionOK = (not useSessionFilter or (openMinutes >= entryStartMinutes and closeMinutes <= lastEntryMinutes))
bool beforeForceClose = (closeMinutes < forceCloseMinutes)
bool forceCloseBar = (openMinutes < forceCloseMinutes and closeMinutes >= forceCloseMinutes)

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

// ============================================================================
// 14. ON-BALANCE VOLUME
// ============================================================================
//
// OBV:
// If price rises, add volume.
// If price falls, subtract volume.
// If unchanged, OBV remains flat.
//
// ============================================================================
float priceChange = nz(ta.change(close), 0.0)
float obvIncrement = (math.sign(priceChange) * nz(volume, 0.0))
float obv = ta.cum(obvIncrement)
float avgVolume = ta.sma(volume[1], volumeLength)

// ============================================================================
// 15. ATR, EMA, RSI, ADX
// ============================================================================
float atr = ta.atr(atrLength)
float ema = ta.ema(close, emaLength)
float rsi = ta.rsi(close, rsiLength)
[diPlus, diMinus, adx] = ta.dmi(diLength, adxSmoothing)

// ============================================================================
// 16. PRICE PIVOTS
// ============================================================================
//
// ta.pivotlow/high confirm only after
// pivotRight future candles have closed.
//
// The pivot belongs to bar [pivotRight].
// The signal becomes available NOW.
//
// This avoids entering historically at
// an unconfirmed pivot.
//
// ============================================================================
float pivotLow = ta.pivotlow(low, pivotLeft, pivotRight)
float pivotHigh = ta.pivothigh(high, pivotLeft, pivotRight)
bool newPivotLow = (barstate.isconfirmed and not na(pivotLow))
bool newPivotHigh = (barstate.isconfirmed and not na(pivotHigh))
float pivotLowOBV = obv[pivotRight]
float pivotHighOBV = obv[pivotRight]
int pivotBarIndex = bar_index - pivotRight
float pivotATR = atr[pivotRight]
float pivotAvgVolume = avgVolume[pivotRight]

// ============================================================================
// 17. PREVIOUS PIVOT STORAGE
// ============================================================================
var float previousLowPrice = na
var float previousLowOBV = na
var int previousLowBar = na
var float previousHighPrice = na
var float previousHighOBV = na
var int previousHighBar = na
var int pivotLowCount = 0
var int pivotHighCount = 0
var int bullishDivCount = 0
var int bearishDivCount = 0

// ============================================================================
// 18. DIVERGENCE CONDITIONS
// ============================================================================
//
// These events compare the newly confirmed
// price pivot against the previous confirmed
// price pivot of the same type.
//
// OBV values are sampled at those
// corresponding pivot candles.
//
// ============================================================================
bool bullishDivergence = false
bool bearishDivergence = false
if newPivotLow
    pivotLowCount += 1
    int pivotGapLow = (na(previousLowBar) ? 0 : pivotBarIndex - previousLowBar)
    bool gapOK = (not na(previousLowBar) and pivotGapLow >= minimumPivotGap and pivotGapLow <= maximumPivotGap)
    bool priceLowerLow = (not na(previousLowPrice) and pivotLow < previousLowPrice)
    bool obvHigherLow = (not na(previousLowOBV) and not na(pivotLowOBV) and pivotLowOBV > previousLowOBV)
    float priceDifference = (na(previousLowPrice) ? na : previousLowPrice - pivotLow)
    float obvDifference = (na(previousLowOBV) ? na : pivotLowOBV - previousLowOBV)
    bool priceDifferenceOK = (not usePriceDifference or (not na(pivotATR) and pivotATR > 0 and priceDifference >= pivotATR * minimumPriceDifferenceATR))
    bool obvDifferenceOK = (not useOBVDifference or (not na(pivotAvgVolume) and pivotAvgVolume > 0 and obvDifference >= pivotAvgVolume * minimumOBVVolumeUnits))
    bullishDivergence := (gapOK and priceLowerLow and obvHigherLow and priceDifferenceOK and obvDifferenceOK)
    previousLowPrice := pivotLow
    previousLowOBV := pivotLowOBV
    previousLowBar := pivotBarIndex
if newPivotHigh
    pivotHighCount += 1
    int pivotGapHigh = (na(previousHighBar) ? 0 : pivotBarIndex - previousHighBar)
    bool gapOK = (not na(previousHighBar) and pivotGapHigh >= minimumPivotGap and pivotGapHigh <= maximumPivotGap)
    bool priceHigherHigh = (not na(previousHighPrice) and pivotHigh > previousHighPrice)
    bool obvLowerHigh = (not na(previousHighOBV) and not na(pivotHighOBV) and pivotHighOBV < previousHighOBV)
    float priceDifference = (na(previousHighPrice) ? na : pivotHigh - previousHighPrice)
    float obvDifference = (na(previousHighOBV) ? na : previousHighOBV - pivotHighOBV)
    bool priceDifferenceOK = (not usePriceDifference or (not na(pivotATR) and pivotATR > 0 and priceDifference >= pivotATR * minimumPriceDifferenceATR))
    bool obvDifferenceOK = (not useOBVDifference or (not na(pivotAvgVolume) and pivotAvgVolume > 0 and obvDifference >= pivotAvgVolume * minimumOBVVolumeUnits))
    bearishDivergence := (gapOK and priceHigherHigh and obvLowerHigh and priceDifferenceOK and obvDifferenceOK)
    previousHighPrice := pivotHigh
    previousHighOBV := pivotHighOBV
    previousHighBar := pivotBarIndex

// ============================================================================
// 19. EMA FILTER
// ============================================================================
bool emaUp = (not na(ema[emaSlopeBars]) and ema > ema[emaSlopeBars])
bool emaDown = (not na(ema[emaSlopeBars]) and ema < ema[emaSlopeBars])
bool longTrendOK = (not useEMAFilter or (emaUp and (not requirePriceEMA or close > ema)))
bool shortTrendOK = (not useEMAFilter or (emaDown and (not requirePriceEMA or close < ema)))

// ============================================================================
// 20. ADX / RSI FILTERS
// ============================================================================
bool adxOK = (not useADXFilter or (not na(adx) and adx <= maximumADX))
bool longRSIOK = (not useRSIFilter or (not na(rsi) and rsi <= longRSIMax))
bool shortRSIOK = (not useRSIFilter or (not na(rsi) and rsi >= shortRSIMin))

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

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

// ============================================================================
// 23. DIVERGENCE STATE MACHINE
// ============================================================================
//
// On a confirmed divergence:
// Save a micro-structure breakout level.
//
// Wait for a LATER confirmed candle
// to close beyond the stored level.
//
// Divergence patterns cannot trigger
// retroactive orders.
//
// ============================================================================
var bool pendingLong = false
var bool pendingShort = false
var int longSignalBar = na
var int shortSignalBar = na
var int longSignalDay = na
var int shortSignalDay = na
var float longTrigger = na
var float shortTrigger = na
var float longInvalidLevel = na
var float shortInvalidLevel = na
var int expiredLongCount = 0
var int expiredShortCount = 0
var int longBaseCount = 0
var int shortBaseCount = 0
var int filteredLongCount = 0
var int filteredShortCount = 0
var int longEntryCount = 0
var int shortEntryCount = 0
float structureHigh = ta.highest(high[1], structureLookback)
float structureLow = ta.lowest(low[1], structureLookback)
float breakoutBuffer = (useBreakoutBuffer and not na(atr) ? atr * breakoutBufferATR : 0.0)

// ============================================================================
// 24. BREAKOUT CONFIRMATION
// ============================================================================
bool longWindowOK = (pendingLong and not na(longSignalBar) and longSignalDay == dayKey and bar_index > longSignalBar and bar_index - longSignalBar <= confirmationWindow)
bool shortWindowOK = (pendingShort and not na(shortSignalBar) and shortSignalDay == dayKey and bar_index > shortSignalBar and bar_index - shortSignalBar <= confirmationWindow)
bool longExtremeOK = (not cancelOnNewExtreme or (not na(longInvalidLevel) and low >= longInvalidLevel))
bool shortExtremeOK = (not cancelOnNewExtreme or (not na(shortInvalidLevel) and high <= shortInvalidLevel))
bool longCandleOK = (not requireBreakoutCandle or close > open)
bool shortCandleOK = (not requireBreakoutCandle or close < open)
bool longBase = (barstate.isconfirmed and longWindowOK and longExtremeOK and longCandleOK and not na(longTrigger) and close > longTrigger + breakoutBuffer)
bool shortBase = (barstate.isconfirmed and shortWindowOK and shortExtremeOK and shortCandleOK and not na(shortTrigger) and close < shortTrigger - breakoutBuffer)

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

// ============================================================================
// 26. ENTRY GATES
// ============================================================================
bool canTrade = (barstate.isconfirmed and intradayOK and flat and strategy.opentrades == 0 and tradesToday < maximumTradesPerDay and cooldownOK and freshEntryBar and entrySessionOK and beforeForceClose)
bool ambiguousSignal = (rawLong and rawShort)
bool enterLong = (canTrade and allowLong and rawLong and not ambiguousSignal)
bool enterShort = (canTrade and allowShort and rawShort and not ambiguousSignal)

// ============================================================================
// 27. RISK MANAGEMENT IN TICKS
// ============================================================================
int slTicks = math.max(1, int(math.round(stopLossPoints / syminfo.mintick)))
int tpTicks = math.max(1, int(math.round(takeProfitPoints / syminfo.mintick)))
float effectiveSL = (slTicks * syminfo.mintick)
float effectiveTP = (tpTicks * syminfo.mintick)

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

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

// ============================================================================
// 30. UPDATE DIVERGENCE STATE
// ============================================================================
//
// New divergence registration happens
// AFTER entry signals are evaluated.
//
// This guarantees a divergence cannot
// break its stored level on the same bar.
//
// ============================================================================
if barstate.isconfirmed
    if bullishDivergence
        bullishDivCount += 1
    if bearishDivergence
        bearishDivCount += 1
    if longBase
        longBaseCount += 1
    if shortBase
        shortBaseCount += 1
    if rawLong
        filteredLongCount += 1
    if rawShort
        filteredShortCount += 1

    // --------------------------------------------------------
    // RESET DAILY PENDING SETUPS
    // --------------------------------------------------------
    if newDay
        pendingLong := false
        pendingShort := false
        longSignalBar := na
        shortSignalBar := na
        longSignalDay := na
        shortSignalDay := na
        longTrigger := na
        shortTrigger := na
        longInvalidLevel := na
        shortInvalidLevel := na

    // --------------------------------------------------------
    // LONG EXPIRATION / INVALIDATION
    // --------------------------------------------------------
    if pendingLong and not na(longSignalBar)
        bool longExpired = (bar_index - longSignalBar > confirmationWindow)
        bool longInvalid = (cancelOnNewExtreme and not na(longInvalidLevel) and low < longInvalidLevel)
        if longExpired or longInvalid
            pendingLong := false
            longSignalBar := na
            expiredLongCount += 1

    // --------------------------------------------------------
    // SHORT EXPIRATION / INVALIDATION
    // --------------------------------------------------------
    if pendingShort and not na(shortSignalBar)
        bool shortExpired = (bar_index - shortSignalBar > confirmationWindow)
        bool shortInvalid = (cancelOnNewExtreme and not na(shortInvalidLevel) and high > shortInvalidLevel)
        if shortExpired or shortInvalid
            pendingShort := false
            shortSignalBar := na
            expiredShortCount += 1

    // --------------------------------------------------------
    // CONSUME SETUP AFTER ENTRY
    // --------------------------------------------------------
    if enterLong
        pendingLong := false
        longSignalBar := na
    if enterShort
        pendingShort := false
        shortSignalBar := na

    // --------------------------------------------------------
    // REGISTER NEW CONFIRMED DIVERGENCE
    // --------------------------------------------------------
    bool canRegister = (intradayOK and flat and entrySessionOK and beforeForceClose and not enterLong and not enterShort)
    if (canRegister and bullishDivergence and not pendingLong and not na(structureHigh))
        pendingLong := true
        longSignalBar := bar_index
        longSignalDay := dayKey
        longTrigger := structureHigh
        longInvalidLevel := pivotLow
        pendingShort := false
        shortSignalBar := na
    if (canRegister and bearishDivergence and not pendingShort and not na(structureLow))
        pendingShort := true
        shortSignalBar := bar_index
        shortSignalDay := dayKey
        shortTrigger := structureLow
        shortInvalidLevel := pivotHigh
        pendingLong := false
        longSignalBar := na

// ============================================================================
// 31. LONG EXIT
// ============================================================================
strategy.exit("Long Exit", from_entry="Long", profit=tpTicks, loss=slTicks, comment_profit="TP Long", comment_loss="SL Long", alert_profit="💰 CHỐT LỜI LONG (CNPS86 - TP HIT)\n🎯 Giá chốt lời: " + str.tostring(strategy.position_avg_price + effectiveTP, format.mintick), alert_loss="🛑 CẮT LỖ LONG (CNPS86 - SL HIT)\n💥 Giá cắt lỗ: " + str.tostring(strategy.position_avg_price - effectiveSL, format.mintick), disable_alert=disableExitAlerts)

// ============================================================================
// 32. SHORT EXIT
// ============================================================================
strategy.exit("Short Exit", from_entry="Short", profit=tpTicks, loss=slTicks, comment_profit="TP Short", comment_loss="SL Short", alert_profit="💰 CHỐT LỜI SHORT (CNPS86 - TP HIT)\n🎯 Giá chốt lời: " + str.tostring(strategy.position_avg_price - effectiveTP, format.mintick), alert_loss="🛑 CẮT LỖ SHORT (CNPS86 - SL HIT)\n💥 Giá cắt lỗ: " + str.tostring(strategy.position_avg_price + effectiveSL, format.mintick), disable_alert=disableExitAlerts)

// ============================================================================
// 33. OPTIONAL TIME EXIT
// ============================================================================
int barsHeld = (strategy.opentrades > 0 ? bar_index - strategy.opentrades.entry_bar_index(0) : 0)
bool timeExit = (useTimeExit and strategy.position_size != 0 and barsHeld >= maximumHoldingBars and barstate.isconfirmed)
if timeExit and not forceCloseBar
    strategy.close_all(immediately=true, comment="Time Exit", alert_message="⏱️ ĐÓNG VỊ THẾ HẾT THỜI GIAN (CNPS86 - Time Exit)\n📌 Giá đóng: " + str.tostring(close, format.mintick))

// ============================================================================
// 34. FORCE CLOSE
// ============================================================================
if (barstate.isconfirmed and forceCloseBar and strategy.position_size != 0)
    strategy.close_all(immediately=true, comment="Session End", alert_message="⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (CNPS86 - Session End)\n📌 Giá đóng: " + str.tostring(close, format.mintick))

// ============================================================================
// 35. EMA PLOT
// ============================================================================
plot(showEMA ? ema : na, title="EMA Trend", color=color.orange, linewidth=2)

// ============================================================================
// 36. CONFIRMED PIVOT MARKERS
// ============================================================================
//
// Markers appear on the CONFIRMATION bar,
// not retroactively on the pivot bar.
//
// ============================================================================
plotshape(showPivotMarkers and newPivotLow, title="Confirmed Price Pivot Low", style=shape.circle, location=location.belowbar, color=color.new(color.green, 30), size=size.tiny, text="PL")
plotshape(showPivotMarkers and newPivotHigh, title="Confirmed Price Pivot High", style=shape.circle, location=location.abovebar, color=color.new(color.red, 30), size=size.tiny, text="PH")

// ============================================================================
// 37. DIVERGENCE MARKERS
// ============================================================================
plotshape(showDivergenceMarkers and bullishDivergence, title="Bullish OBV Divergence Confirmed", style=shape.labelup, location=location.belowbar, color=color.aqua, size=size.tiny, text="OBV+", textcolor=color.black)
plotshape(showDivergenceMarkers and bearishDivergence, title="Bearish OBV Divergence Confirmed", style=shape.labeldown, location=location.abovebar, color=color.orange, size=size.tiny, text="OBV-", textcolor=color.black)

// ============================================================================
// 38. PENDING STRUCTURE LEVELS
// ============================================================================
plot(showTriggerLevels and pendingLong ? longTrigger : na, title="Pending Long Breakout Level", color=color.aqua, linewidth=2, style=plot.style_linebr)
plot(showTriggerLevels and pendingShort ? shortTrigger : na, title="Pending Short Breakout Level", color=color.fuchsia, linewidth=2, style=plot.style_linebr)

// ============================================================================
// 39. ENTRY MARKERS
// ============================================================================
plotshape(showEntryMarkers and enterLong, title="CNPS86 LONG", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, text="LONG", textcolor=color.white)
plotshape(showEntryMarkers and enterShort, title="CNPS86 SHORT", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small, text="SHORT", textcolor=color.white)

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

// ============================================================================
// 41. DATA WINDOW
// ============================================================================
plot(obv, title="OBV", color=color.blue, display=display.data_window)
plot(rsi, title="RSI", color=color.purple, display=display.data_window)
plot(adx, title="ADX", color=color.gray, display=display.data_window)
plot(atr, title="ATR", color=color.orange, display=display.data_window)
plot(longTrigger, title="Saved Long Trigger", color=color.aqua, display=display.data_window)
plot(shortTrigger, title="Saved Short Trigger", color=color.fuchsia, display=display.data_window)

// ============================================================================
// 42. DIAGNOSTICS
// ============================================================================
var table diagnostics = table.new(position.top_right, 2, 20, border_width=1)
if showDiagnostics and barstate.islast
    table.cell(diagnostics, 0, 0, "CNPS86 V1")
    table.cell(diagnostics, 1, 0, timeframe.period)
    table.cell(diagnostics, 0, 1, "OBV")
    table.cell(diagnostics, 1, 1, str.tostring(obv, "#.##"))
    table.cell(diagnostics, 0, 2, "Pivot Lows")
    table.cell(diagnostics, 1, 2, str.tostring(pivotLowCount))
    table.cell(diagnostics, 0, 3, "Pivot Highs")
    table.cell(diagnostics, 1, 3, str.tostring(pivotHighCount))
    table.cell(diagnostics, 0, 4, "Bull Divergences")
    table.cell(diagnostics, 1, 4, str.tostring(bullishDivCount))
    table.cell(diagnostics, 0, 5, "Bear Divergences")
    table.cell(diagnostics, 1, 5, str.tostring(bearishDivCount))
    table.cell(diagnostics, 0, 6, "Long Bases")
    table.cell(diagnostics, 1, 6, str.tostring(longBaseCount))
    table.cell(diagnostics, 0, 7, "Short Bases")
    table.cell(diagnostics, 1, 7, str.tostring(shortBaseCount))
    table.cell(diagnostics, 0, 8, "Filtered Long")
    table.cell(diagnostics, 1, 8, str.tostring(filteredLongCount))
    table.cell(diagnostics, 0, 9, "Filtered Short")
    table.cell(diagnostics, 1, 9, str.tostring(filteredShortCount))
    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(expiredLongCount))
    table.cell(diagnostics, 0, 13, "Expired Short")
    table.cell(diagnostics, 1, 13, str.tostring(expiredShortCount))
    table.cell(diagnostics, 0, 14, "Long Entries")
    table.cell(diagnostics, 1, 14, str.tostring(longEntryCount))
    table.cell(diagnostics, 0, 15, "Short Entries")
    table.cell(diagnostics, 1, 15, str.tostring(shortEntryCount))
    table.cell(diagnostics, 0, 16, "EMA Up")
    table.cell(diagnostics, 1, 16, emaUp ? "YES" : "NO")
    table.cell(diagnostics, 0, 17, "EMA Down")
    table.cell(diagnostics, 1, 17, emaDown ? "YES" : "NO")
    table.cell(diagnostics, 0, 18, "Trades Today")
    table.cell(diagnostics, 1, 18, str.tostring(tradesToday) + "/" + str.tostring(maximumTradesPerDay))
    table.cell(diagnostics, 0, 19, "Position")
    table.cell(diagnostics, 1, 19, inLong ? "LONG" : inShort ? "SHORT" : "FLAT")

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

2.1. Chỉ báo On-Balance Volume (OBV) và cơ chế Pivot xác nhận

Bot tự tính OBV bằng công thức tích lũy dòng tiền theo biến động giá đóng cửa:

  • priceChange = nz(ta.change(close), 0.0)
  • obvIncrement = math.sign(priceChange) * nz(volume, 0.0)
  • obv = ta.cum(obvIncrement)

Khi giá đóng cửa tăng so với nến trước, khối lượng được cộng vào OBV; khi giá giảm, khối lượng bị trừ đi; nếu đi ngang, OBV giữ nguyên. Ngoài ra, khối lượng trung bình tham chiếu được tính trên nến đã đóng trước đó (avgVolume = ta.sma(volume[1], volumeLength)).

Điểm quan trọng là cách bot xử lý Pivot qua ta.pivotlow(low, pivotLeft, pivotRight) và ta.pivothigh(high, pivotLeft, pivotRight). Một đỉnh hoặc đáy Pivot chỉ được xác nhận tại thời điểm hiện tại (newPivotLow / newPivotHigh) khi nến hiện tại đã đóng (barstate.isconfirmed) và đủ pivotRight nến phía sau đã hình thành. Lúc này, giá trị OBV, ATR và Avg Volume tương ứng được lấy tại đúng cây nến tạo Pivot (obv[pivotRight], atr[pivotRight], avgVolume[pivotRight]), với chỉ số nến là pivotBarIndex = bar_index - pivotRight. Cách làm này giúp loại bỏ hoàn toàn tình trạng đặt lệnh hồi tố trên nến Pivot trong quá khứ.

2.2. Phân kỳ tăng/giảm OBV (Bullish & Bearish Divergence)

Mỗi khi có Pivot mới được xác nhận, bot so sánh nó với Pivot cùng loại liền trước đã lưu (previousLowPrice/previousLowOBV/previousLowBar hoặc previousHighPrice/previousHighOBV/previousHighBar):

  • Bullish Divergence (Phân kỳ tăng):
    • Khoảng cách giữa 2 đáy Pivot (pivotGapLow) nằm trong đoạn [minimumPivotGap, maximumPivotGap] (mặc định 5–80 nến).
    • Giá tạo đáy thấp hơn: pivotLow < previousLowPrice.
    • OBV tại đáy mới tạo đáy cao hơn: pivotLowOBV > previousLowOBV (lực bán suy yếu, dòng tiền âm không còn xác nhận đà giảm).
    • Tùy chọn lọc biên độ: nếu bật usePriceDifference, độ chênh giá phải đạt ít nhất pivotATR * minimumPriceDifferenceATR; nếu bật useOBVDifference, độ chênh OBV phải đạt ít nhất pivotAvgVolume * minimumOBVVolumeUnits.
  • Bearish Divergence (Phân kỳ giảm):
    • Khoảng cách giữa 2 đỉnh Pivot (pivotGapHigh) nằm trong đoạn [minimumPivotGap, maximumPivotGap].
    • Giá tạo đỉnh cao hơn: pivotHigh > previousHighPrice.
    • OBV tại đỉnh mới tạo đỉnh thấp hơn: pivotHighOBV < previousHighOBV (lực mua suy yếu dù giá rướn đỉnh mới).
    • Tùy chọn lọc biên độ giá theo ATR và biên độ OBV theo Avg Volume tương tự chiều tăng.

2.3. State Machine phá vỡ cấu trúc và bộ lọc đa tầng

Khi phát hiện phân kỳ, bot không vào lệnh ngay mà chuyển sang trạng thái chờ (pendingLong hoặc pendingShort) và lưu ngưỡng cấu trúc ngắn hạn trước đó (structureHigh = ta.highest(high[1], structureLookback) cho Long, structureLow = ta.lowest(low[1], structureLookback) cho Short). Nến xác nhận phá vỡ phải đóng vượt ngưỡng này cộng/trừ thêm breakoutBuffer (mặc định 0.05 * ATR).

Để tăng chất lượng tín hiệu, hệ thống cung cấp 4 lớp lọc tùy chọn:

  • EMA Trend Filter: Kiểm tra độ dốc EMA (ema > ema[emaSlopeBars] với Long, ngược lại với Short) và vị trí giá so với EMA (requirePriceEMA).
  • Maximum ADX Filter: Yêu cầu adx <= maximumADX (mặc định 35.0) nhằm tránh vào lệnh đảo chiều khi xu hướng cũ đang quá mạnh.
  • RSI Filter: Giới hạn rsi <= longRSIMax (mặc định 65.0) cho Long và rsi >= shortRSIMin (mặc định 35.0) cho Short để tránh mua quá cao hoặc bán quá thấp.
  • Confirmed H1 EMA Bias: Dùng request.security(..., "60", ...[1], lookahead=barmerge.lookahead_on) để lấy h1Close và h1EMA của cây nến H1 đã đóng hoàn toàn gần nhất (chỉ áp dụng trên biểu đồ intraday nhỏ hơn 1 giờ).

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

Quy trình vận hành trên mỗi cây nến của CNPS86 diễn ra tuần tự qua 5 bước:

  1. Khởi tạo ngày mới & kiểm tra phiên: Khi newDay xuất hiện, bộ đếm tradesToday được đưa về 0 và toàn bộ setup đang chờ (pendingLong, pendingShort) của ngày hôm trước bị xóa sạch. Bộ đếm thời gian quy đổi giờ theo múi giờ Asia/Ho_Chi_Minh để kiểm soát entrySessionOK (09:15–14:15) và forceCloseBar (14:45).
  2. Đánh giá tín hiệu phá vỡ từ setup đang chờ: Nếu đang có pendingLong hoặc pendingShort từ các nến trước (cùng ngày dayKey, chưa quá confirmationWindow nến và chưa phá cực trị hủy kèo), bot kiểm tra nến hiện tại có đóng cửa vượt longTrigger + breakoutBuffer hoặc dưới shortTrigger - breakoutBuffer hay không.
  3. Lọc điều kiện & gửi lệnh vào thị trường: Nếu thỏa mãn tín hiệu rawLong / rawShort, không bị xung đột hai chiều (not ambiguousSignal) và vượt qua cổng canTrade, bot gửi lệnh strategy.entry, tăng tradesToday và ghi nhận lastEntryBar.
  4. Cập nhật State Machine & đăng ký phân kỳ mới: Thực hiện sau bước đánh giá vào lệnh (section 30) để đảm bảo một phân kỳ mới xuất hiện không thể tự kích hoạt vào lệnh ngay trên chính cây nến xác nhận nó. Bot cũng dọn dẹp các setup hết hạn hoặc bị vô hiệu hóa (expiredLongCount / expiredShortCount), sau đó mới đăng ký bullishDivergence / bearishDivergence mới nếu đang flat.
  5. Quản trị vị thế & thoát lệnh: Ngay khi có vị thế mở, strategy.exit đặt sẵn chốt lời/cắt lỗ cố định; đồng thời kiểm tra điều kiện timeExit (nếu bật) và forceCloseBar để đóng toàn bộ vị thế trước giờ đóng cửa.

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

4.1. Điều kiện vào lệnh Long

Lệnh Long (enterLong) được kích hoạt khi hội tụ đủ các điều kiện sau:

  1. Cho phép chiều Long: tradeDirection là "Long" hoặc "Both".
  2. Đang có setup chờ Long hợp lệ: pendingLong == true, cùng ngày giao dịch (longSignalDay == dayKey), số nến trôi qua kể từ lúc xác nhận phân kỳ nằm trong khoảng 1 đến confirmationWindow (mặc định 8 nến).
  3. Không bị phá đáy hủy kèo: Nếu bật cancelOnNewExtreme, giá thấp nhất low không được rơi xuống dưới longInvalidLevel (mức pivotLow tạo phân kỳ).
  4. Phá vỡ cấu trúc tăng: Nến hiện tại là nến xanh (close > open nếu bật requireBreakoutCandle) và đóng cửa vượt ngưỡng close > longTrigger + breakoutBuffer.
  5. Thỏa mãn bộ lọc (nếu bật): longTrendOK (EMA dốc lên và close > ema), adxOK (adx <= maximumADX), longRSIOK (rsi <= longRSIMax), và longH1OK (h1Close > h1EMA).
  6. Không xung đột tín hiệu & đạt cổng giao dịch: not ambiguousSignal và canTrade == true.

4.2. Điều kiện vào lệnh Short

Lệnh Short (enterShort) được kích hoạt khi hội tụ đủ các điều kiện sau:

  1. Cho phép chiều Short: tradeDirection là "Short" hoặc "Both" (lưu ý mặc định trong code đang để "Long", bạn cần chuyển sang "Short" hoặc "Both" nếu muốn bot đánh chiều bán).
  2. Đang có setup chờ Short hợp lệ: pendingShort == true, cùng ngày giao dịch (shortSignalDay == dayKey), số nến trôi qua nằm trong khoảng 1 đến confirmationWindow.
  3. Không bị phá đỉnh hủy kèo: Nếu bật cancelOnNewExtreme, giá cao nhất high không được vượt lên trên shortInvalidLevel (mức pivotHigh tạo phân kỳ).
  4. Phá vỡ cấu trúc giảm: Nến hiện tại là nến đỏ (close < open nếu bật requireBreakoutCandle) và đóng cửa dưới ngưỡng close < shortTrigger - breakoutBuffer.
  5. Thỏa mãn bộ lọc (nếu bật): shortTrendOK (EMA dốc xuống và close < ema), adxOK (adx <= maximumADX), shortRSIOK (rsi >= shortRSIMin), và shortH1OK (h1Close < h1EMA).
  6. Không xung đột tín hiệu & đạt cổng giao dịch: not ambiguousSignal và canTrade == true.

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

Biến canTrade bắt buộc toàn bộ các điều kiện sau phải đồng thời đúng:

  • Nến đã đóng hoàn toàn (barstate.isconfirmed) và đang chạy trên khung thời gian trong ngày (timeframe.isintraday).
  • Tài khoản đang không có vị thế (flat, strategy.opentrades == 0).
  • Số lệnh trong ngày chưa vượt trần (tradesToday < maximumTradesPerDay, mặc định 2 lệnh/ngày).
  • Đã qua thời gian nghỉ sau lệnh đóng gần nhất (bar_index - lastExitBar > cooldownBars, mặc định 3 nến) và chưa vào lệnh trên chính nến hiện tại (freshEntryBar).
  • Nằm trong khung giờ cho phép mở lệnh (09:15 đến 14:15 nếu bật useSessionFilter) và trước giờ đóng bắt buộc (closeMinutes < 14:45).

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

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

CNPS86 sử dụng mức cắt lỗ cố định theo điểm (stopLossPoints, mặc định 5.0 điểm) và quy đổi sang đơn vị tick nhỏ nhất của hợp đồng (syminfo.mintick) để đảm bảo tính chính xác khi khớp lệnh:

  • slTicks = math.max(1, int(math.round(stopLossPoints / syminfo.mintick)))
  • effectiveSL = slTicks * syminfo.mintick

Với vị thế Long, mức cắt lỗ hiển thị và thực thi tại strategy.position_avg_price - effectiveSL. Với vị thế Short, mức cắt lỗ đặt tại strategy.position_avg_price + effectiveSL. Bot không sử dụng bộ lọc Min–Max Risk theo ATR như một số chiến lược khác mà giữ khoảng cách rủi ro cố định.

5.2. Cơ chế Take Profit, Time Exit và Force Close cuối phiên

  • Take Profit cố định: Tương tự Stop Loss, mục tiêu lợi nhuận (takeProfitPoints, mặc định 15.0 điểm — tỷ lệ Risk:Reward 1:3) được quy đổi sang tpTicks và effectiveTP. Bot không dùng cơ chế dời hòa vốn (Break Even) hay Trailing Stop.
  • Thoát lệnh theo thời gian (useTimeExit): Mặc định tắt (false). Nếu bật, khi số nến nắm giữ vị thế barsHeld >= maximumHoldingBars (mặc định 20 nến) tại thời điểm đóng nến xác nhận (và chưa phải nến Force Close), bot gọi strategy.close_all(immediately=true) với ghi chú "Time Exit".
  • Đóng vị thế cuối phiên (Force Close): Khi nến hiện tại vắt qua hoặc chạm mốc 14:45 (openMinutes < forceCloseMinutes and closeMinutes >= forceCloseMinutes) và đang còn vị thế mở, bot tự động đóng toàn bộ lệnh với ghi chú "Session End" để tránh rủi ro qua đêm hoặc kẹt lệnh ATC.

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

Cơ chế thoát lệnhĐiều kiện kích hoạtHành động thực thiTrạng thái mặc định
Stop Loss cố địnhGiá chạm avg_price ∓ effectiveSLThoát lệnh qua strategy.exit (SL Long / SL Short)Bật (5.0 điểm)
Take Profit cố địnhGiá chạm avg_price ± effectiveTPThoát lệnh qua strategy.exit (TP Long / TP Short)Bật (15.0 điểm)
Time ExitbarsHeld >= maximumHoldingBarsstrategy.close_all (Time Exit)Tắt (20 nến)
Force Close cuối phiênNến chạm mốc 14:45strategy.close_all (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 tương lai VN30F1M trên TradingView, chọn khung thời gian intraday (ví dụ 1m, 3m, 5m hoặc 15m; lưu ý nếu bật useH1Bias thì khung biểu đồ phải nhỏ hơn 60m).
  2. Nhấn vào tab Pine Editor ở thanh công cụ phía dưới màn hình.
  3. Xóa toàn bộ đoạn code mẫu mặc định trong trình soạn thảo, sau đó dán toàn bộ mã nguồn Pine Script v6 từ Mục 1 vào.
  4. Nhấn Save (Lưu) để đặt tên cho chiến lược, sau đó nhấn Add to chart (Thêm vào biểu đồ).
  5. Mở biểu tượng bánh răng Settings của chiến lược để điều chỉnh chiều giao dịch (tradeDirection), số hợp đồng (contracts), hoặc bật các bộ lọc EMA/ADX/RSI/H1 Bias và bảng Show Diagnostics theo nhu cầu.

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

Khi bật tùy chọn Show Diagnostics trong mục 11. Display, bot sẽ vẽ một bảng gồm 2 cột, 20 dòng ở góc trên bên phải biểu đồ (position.top_right) tại cây nến cuối cùng (barstate.islast) với các thông số thực tế sau:

DòngNhãn hiển thịÝ nghĩa dữ liệu thực tế
0CNPS86 V1Tên phiên bản bot và khung thời gian hiện tại (timeframe.period)
1OBVGiá trị chỉ báo On-Balance Volume tích lũy hiện tại
2–3Pivot Lows / Pivot HighsTổng số đáy/đỉnh Pivot đã được xác nhận
4–5Bull Divergences / Bear DivergencesTổng số lần phát hiện phân kỳ tăng/giảm OBV
6–7Long Bases / Short BasesSố lần giá phá vỡ cấu trúc hợp lệ (trước khi qua bộ lọc xu hướng)
8–9Filtered Long / Filtered ShortSố tín hiệu Long/Short vượt qua toàn bộ bộ lọc EMA, ADX, RSI, H1
10–11Pending Long / Pending ShortTrạng thái đang chờ phá vỡ cấu trúc (YES hoặc NO)
12–13Expired Long / Expired ShortSố setup bị hết hạn thời gian chờ hoặc bị phá cực trị hủy kèo
14–15Long Entries / Short EntriesTổng số lệnh Long/Short thực tế đã vào
16–17EMA Up / EMA DownTrạng thái độ dốc đường EMA hiện tại (YES / NO)
18Trades TodaySố lệnh đã giao dịch trong ngày so với giới hạn (tradesToday/maximumTradesPerDay)
19PositionTrạ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ự động qua ứng dụng TradingView, Telegram hoặc Webhook khi bot phát lệnh, bạn thực hiện theo các bước sau:

  1. Nhấn vào nút Alert (biểu tượng đồng hồ báo thức) trên thanh công cụ TradingView.
  2. Tại mục Condition, chọn đúng tên chiến lược CNPS86 OBV DIVERGENCE BREAK V1.
  3. Tại ô Message, xóa nội dung mặc định và điền chính xác cú pháp: {{strategy.order.alert_message}}
  4. Đặt tên cảnh báo và chọn phương thức thông báo (Popup, Email, Webhook URL), sau đó nhấn Create.

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

Dưới đây là toàn bộ 8 thông điệp cảnh báo được lập trình sẵn trong mã nguồn CNPS86 (nếu muốn tắt riêng thông báo chốt lời/cắt lỗ của strategy.exit, bạn có thể bật Disable SL/TP Alerts trong mục 10. Alerts):

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

Kết luận

CNPS86 OBV Divergence Break V1 là một hệ thống giao dịch phân kỳ có tính kỷ luật cao nhờ kết hợp xác nhận Pivot không repaint, dòng tiền OBV và cơ chế chờ phá vỡ cấu trúc ngắn hạn. Chiến lược phát huy hiệu quả tốt nhất trong các phiên thị trường có nhịp rũ bỏ (shakeout) hoặc suy yếu động lượng cuối sóng, nơi dòng tiền OBV sớm bộc lộ sự phân kỳ trước khi giá thực sự đảo chiều qua vùng cấu trúc.

Bạn có thể tham khảo thêm các hệ thống giao dịch tự động khác trên VN30F1M như Bot CNPS50 - Trend Analysis V2 và Bot CNPS49 - Daily Open để đa dạng hóa danh mục chiến lược.

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