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

Hướng Dẫn Sử Dụng Bot CNPS83 - Three-Bar Reversal V2 cho VN30F1M

Bot CNPS83 (Three-Bar Reversal V2) kết hợp mô hình đảo chiều 3 nến, xác nhận phá vỡ ở nến kế tiếp, cấu trúc thị trường ngắn hạn và bộ lọc xu hướng EMA cùng quản trị SL/TP cố định theo điểm cho VN30F1M.

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

Trong giao dịch hợp đồng tương lai VN30F1M, các nhịp đảo chiều giả (fake reversal) hoặc bắt đáy/đỉnh ngược xu hướng chính thường khiến nhà đầu tư gặp rủi ro quét dừng lỗ liên tục. Nếu chỉ dựa vào một cây nến đảo chiều đơn lẻ mà thiếu xác nhận cấu trúc giá và bối cảnh xu hướng, tín hiệu rất dễ bị nhiễu trong các phiên biến động mạnh.

CNPS83 THREE-BAR REVERSAL V2 (tên rút gọn: CNPS83 3BAR V2) là chiến lược giao dịch định lượng viết bằng Pine Script v6 trên TradingView, được thiết kế để giải quyết bài toán này thông qua quy trình lọc đa tầng trước khi kích hoạt lệnh.

Các điểm nổi bật cốt lõi của Bot CNPS83:

  • Mô hình đảo chiều 3 nến chuẩn hóa: Kiểm tra chặt chẽ cấu trúc nến 1–2–3, biên độ mẫu hình theo ATR (0.50 – 5.00 ATR), giữ cực trị nến 2 và khả năng giành lại điểm giữa nến 1 (firstMidpoint).
  • Xác nhận phá vỡ ở nến kế tiếp (Next Bar Breakout): Thay vì vào lệnh ngay khi hoàn tất mô hình, bot mặc định đưa thiết lập vào trạng thái chờ (Pending) và chỉ kích hoạt khi giá đóng cửa phá vỡ patternHigh/patternLow trong tối đa 5 nến.
  • Kết hợp cấu trúc thị trường & xu hướng EMA: Yêu cầu giá phá vỡ đỉnh/đáy ngắn hạn (structureLookback = 3) đồng thuận với độ dốc và vị trí đường EMA 50.
  • Quản trị rủi ro kỷ luật: Tính SL/TP cố định theo điểm chuyển đổi sang tick từ giá khớp lệnh thực tế, giới hạn tối đa 2 lệnh/ngày, thời gian nghỉ 3 nến sau thoát lệnh và tự động đóng toàn bộ vị thế cuối phiên lúc 14:45.

1. CNPS83 Three-Bar Reversal V2 là gì?

CNPS83 Three-Bar Reversal V2 là hệ thống giao dịch theo mô hình hành động giá 3 nến đảo chiều kết hợp phá vỡ cấu trúc ngắn hạn và bộ lọc xu hướng. Chiến lược vận hành trên biểu đồ nội ngày (timeframe.isintraday) và chỉ xử lý tín hiệu khi nến đã đóng cửa (barstate.isconfirmed) để đảm bảo không bị repaint.

Hệ thống được xây dựng trên 4 trụ cột kỹ thuật chính:

  1. Nhận diện mẫu hình 3 nến (Three-Bar Pattern): Đánh giá chuỗi 3 nến liên tiếp về hướng nến, cực trị cao hơn/thấp hơn, mức độ đóng cửa mạnh và độ rộng mẫu hình so với ATR(14).
  2. Cơ chế chờ xác nhận (Next Bar Confirmation): Lưu trữ vùng kích hoạt (longTrigger / shortTrigger) và vùng vô hiệu hóa (longInvalidLevel / shortInvalidLevel) để lọc bỏ các cú đảo chiều thiếu lực tiếp diễn.
  3. Bộ lọc cấu trúc & xu hướng (Market Structure & EMA Trend): Đảm bảo điểm vào lệnh đồng thời phá vỡ đỉnh/đáy gần nhất và thuận chiều xu hướng EMA(50) (cộng thêm các bộ lọc tùy chọn ADX, Volume, RSI và H1 EMA Bias).
  4. Kiểm soát phiên & quản trị vị thế (Session & Risk Engine): Ràng buộc khung giờ vào lệnh (09:15 – 14:15), đóng cưỡng bức cuối phiên (14:45), cùng SL/TP cố định (5.0 điểm / 10.0 điểm) và tùy chọn thoát lệnh theo thời gian.

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

Nhóm thông sốTham số trong codeGiá trị mặc địnhÝ nghĩa thực tế
01. Three-Bar PatternatrLength14Chu kỳ tính chỉ báo ATR
requireMiddleDirectiontrueNến 2 cùng hướng với nến 1
requireThirdExtremetrueNến 3 giữ được cực trị của nến 2 (low >= low[1] / high <= high[1])
useStrongClosetrueNến 3 đóng vượt high[1] (Long) / dưới low[1] (Short)
useFirstMidpointtrueNến 3 đóng vượt điểm giữa nến 1 (firstMidpoint)
usePatternRangetrueBật lọc biên độ mẫu hình theo ATR
minimumRangeATR / maximumRangeATR0.50 / 5.00Biên độ 3 nến phải nằm trong [0.5 * ATR, 5.0 * ATR]
useThirdBodyFilter / minimumThirdBodyRatiofalse / 0.40Tùy chọn lọc tỷ lệ thân nến 3 tối thiểu 40% biên độ nến
02. Entry ConfirmationentryMode"Next Bar Breakout"Chế độ vào lệnh (hoặc "Signal Candle Close")
confirmationBars5Số nến tối đa chờ xác nhận phá vỡ
requireConfirmCandletrueNến xác nhận phải là nến tăng (Long) / giảm (Short)
cancelOnNewExtremetrueHủy thiết lập chờ nếu giá phá cực trị mẫu hình
03. Market StructureuseStructureFiltertrueBật lọc phá vỡ cấu trúc ngắn hạn
structureLookback3Số nến nhìn lại (high[1], low[1]) để lấy đỉnh/đáy cấu trúc
useStructureBuffer / structureBufferATRfalse / 0.05Tùy chọn cộng thêm khoảng đệm theo ATR
04. EMA TrenduseEMAFiltertrueBật bộ lọc xu hướng EMA
emaLength / emaSlopeBars50 / 3Chu kỳ EMA 50, so sánh độ dốc với 3 nến trước
requirePriceEMAtrueYêu cầu giá đóng cửa nằm trên/dưới EMA
05. Optional FiltersuseADXFilter / maximumADXfalse / 35.0Tùy chọn giới hạn ADX(14, 14) <= 35.0
useVolumeFilter / volumeFactorfalse / 1.0Tùy chọn lọc khối lượng >= SMA(20) * 1.0
useRSIFilter / longRSIMax / shortRSIMinfalse / 65.0 / 35.0Tùy chọn giới hạn RSI(14) cho Long/Short
06. H1 BiasuseH1Bias / h1EMALengthfalse / 50Tùy chọn lọc xu hướng theo nến H1 đã đóng (close[1] vs EMA 50)
07. Risk ManagementstopLossPoints / takeProfitPoints5.0 / 10.0Mức SL 5.0 điểm và TP 10.0 điểm
useTimeExit / maxHoldingBarsfalse / 20Tùy chọn đóng lệnh nếu giữ quá 20 nến
08. Trade ControltradeDirection"Long"Hướng giao dịch (Long, Short, Both)
contracts3Tham số số hợp đồng khai báo trong Trade Control
maxTradesPerDay / cooldownBars2 / 3Tối đa 2 lệnh/ngày, nghỉ 3 nến sau khi đóng lệnh
09. SessionuseSessionFilter / tztrue / "Asia/Ho_Chi_Minh"Lọc khung giờ 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ờ đóng cưỡng bức toàn bộ vị thế đang mở
10. Alerts & 11. DisplaydisableExitAlerts / showDiagnosticsfalse / falseTắt cảnh báo SL/TP; bật bảng thống kê góc trên phải

Source Code CNPS83 Three-Bar Reversal V2

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

//@version=6
strategy(title="CNPS83 THREE-BAR REVERSAL V2", shorttitle="CNPS83 3BAR V2", overlay=true, initial_capital=100000000, default_qty_type=strategy.fixed, default_qty_value=1, pyramiding=0, margin_long=0, margin_short=0, slippage=0, commission_type=strategy.commission.cash_per_contract, commission_value=0, fill_orders_on_standard_ohlc=true, process_orders_on_close=true, calc_on_order_fills=false, max_labels_count=300, max_lines_count=300, max_bars_back=5000)

// ============================================================================
// CNPS83 V2 - THREE-BAR REVERSAL + MARKET STRUCTURE
//
// BULLISH PATTERN
// Bar 1: Bearish candle.
// Bar 2: Lower low, continuation of pressure.
// Bar 3: Bullish reversal with improved close.
//
// BEARISH PATTERN
// Bar 1: Bullish candle.
// Bar 2: Higher high.
// Bar 3: Bearish reversal with improved close.
//
// V2 IMPROVEMENTS
// - Optional structure breakout confirmation
// - Optional next-bar breakout
// - EMA direction and price-location filters
// - Pattern range and rejection validation
// - Non-repainting confirmed-bar signals
// - Fixed SL/TP from actual fill price
// - Daily entry limits and cooldown
// - Optional end-of-session force close
// - Diagnostics
//
// IMPORTANT
// This is a backtestable strategy, not a
// validated profitable trading system.
// ============================================================================
// ============================================================================
// 01. THREE-BAR PATTERN
// ============================================================================
gPattern = "01. Three-Bar Pattern"
atrLength = input.int(14, "ATR Length", minval=1, group=gPattern)
requireMiddleDirection = input.bool(true, "Require Bar 2 Same Direction As Bar 1", group=gPattern)
requireThirdExtreme = input.bool(true, "Require Bar 3 To Hold Bar 2 Extreme", group=gPattern)
useStrongClose = input.bool(true, "Require Bar 3 Close Beyond Bar 2 High/Low", group=gPattern)
useFirstMidpoint = input.bool(true, "Require Reclaim Of Bar 1 Midpoint", group=gPattern)
usePatternRange = input.bool(true, "Use Pattern Range Filter", group=gPattern)
minimumRangeATR = input.float(0.50, "Minimum Pattern Range / ATR", minval=0.0, step=0.1, group=gPattern)
maximumRangeATR = input.float(5.00, "Maximum Pattern Range / ATR", minval=0.1, step=0.1, group=gPattern)
useThirdBodyFilter = input.bool(false, "Require Minimum Bar 3 Body", group=gPattern)
minimumThirdBodyRatio = input.float(0.40, "Minimum Bar 3 Body / Range", minval=0.0, maxval=1.0, step=0.05, group=gPattern)

// ============================================================================
// 02. ENTRY CONFIRMATION
// ============================================================================
gConfirm = "02. Entry Confirmation"
entryMode = input.string("Next Bar Breakout", "Entry Mode", options=["Signal Candle Close", "Next Bar Breakout"], group=gConfirm)
confirmationBars = input.int(5, "Maximum Confirmation Bars", minval=1, maxval=30, group=gConfirm)
requireConfirmCandle = input.bool(true, "Require Confirmation Candle Direction", group=gConfirm)
cancelOnNewExtreme = input.bool(true, "Cancel If Pattern Extreme Breaks", group=gConfirm)

// ============================================================================
// 03. MARKET STRUCTURE
// ============================================================================
gStructure = "03. Market Structure"
useStructureFilter = input.bool(true, "Require Short-Term Structure Break", group=gStructure)
structureLookback = input.int(3, "Structure Lookback", minval=2, maxval=50, group=gStructure)
useStructureBuffer = input.bool(false, "Require Structure Break Buffer", group=gStructure)
structureBufferATR = input.float(0.05, "Structure Break Buffer / ATR", minval=0.0, step=0.05, group=gStructure)

// ============================================================================
// 04. EMA TREND
// ============================================================================
gTrend = "04. EMA Trend"
useEMAFilter = input.bool(true, "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 Close Above/Below EMA", group=gTrend)

// ============================================================================
// 05. OPTIONAL INDICATOR 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, step=1, group=gFilters)
useVolumeFilter = input.bool(false, "Use Volume Filter", group=gFilters)
volumeLength = input.int(20, "Volume Average Length", minval=2, group=gFilters)
volumeFactor = input.float(1.0, "Volume Factor", minval=0.1, step=0.1, 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=1, maxval=100, 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(10.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)

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

// ============================================================================
// 09. 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)
showPatternMarkers = input.bool(false, "Show Three-Bar Pattern Markers", group=gDisplay)
showEntryMarkers = input.bool(true, "Show Entry Markers", group=gDisplay)
showStructureLevels = input.bool(false, "Show Structure Levels", group=gDisplay)
showPendingLevels = input.bool(false, "Show Pending Trigger Levels", group=gDisplay)
showSLTP = input.bool(true, "Show 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 sessionOK = (not useSessionFilter or (openMinutes >= entryStartMinutes and closeMinutes <= lastEntryMinutes))
bool beforeForceClose = (closeMinutes < forceCloseMinutes)
bool forceCloseBar = (openMinutes < forceCloseMinutes and closeMinutes >= forceCloseMinutes)
bool intradayOK = timeframe.isintraday

// ============================================================================
// 13. DAILY TRADE LIMIT
// ============================================================================
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. ATR AND CANDLE ANATOMY
// ============================================================================
float atr = ta.atr(atrLength)
float barRange = high - low
float candleBody = math.abs(close - open)
float bodyRatio = (barRange > 0 ? candleBody / barRange : 0.0)
bool firstBearish = (close[2] < open[2])
bool firstBullish = (close[2] > open[2])
bool middleBearish = (close[1] < open[1])
bool middleBullish = (close[1] > open[1])
bool thirdBullish = (close > open)
bool thirdBearish = (close < open)
float firstMidpoint = (high[2] + low[2]) / 2.0

// ============================================================================
// 15. THREE-BAR PRICE STRUCTURE
// ============================================================================
bool middleLowerLow = (low[1] < low[2])
bool middleHigherHigh = (high[1] > high[2])
float patternHigh = math.max(high, math.max(high[1], high[2]))
float patternLow = math.min(low, math.min(low[1], low[2]))
float patternRange = (patternHigh - patternLow)
bool patternRangeOK = (not usePatternRange or (not na(atr) and atr > 0 and patternRange >= minimumRangeATR * atr and patternRange <= maximumRangeATR * atr))
bool thirdBodyOK = (not useThirdBodyFilter or bodyRatio >= minimumThirdBodyRatio)

// ============================================================================
// 16. BULLISH PATTERN
// ============================================================================
bool bullMiddleDirectionOK = (not requireMiddleDirection or middleBearish)
bool bullThirdExtremeOK = (not requireThirdExtreme or low >= low[1])
bool bullStrongCloseOK = (not useStrongClose or close > high[1])
bool bullMidpointOK = (not useFirstMidpoint or close > firstMidpoint)
bool bullishPattern = (barstate.isconfirmed and firstBearish and middleLowerLow and thirdBullish and close > close[1] and bullMiddleDirectionOK and bullThirdExtremeOK and bullStrongCloseOK and bullMidpointOK and patternRangeOK and thirdBodyOK)

// ============================================================================
// 17. BEARISH PATTERN
// ============================================================================
bool bearMiddleDirectionOK = (not requireMiddleDirection or middleBullish)
bool bearThirdExtremeOK = (not requireThirdExtreme or high <= high[1])
bool bearStrongCloseOK = (not useStrongClose or close < low[1])
bool bearMidpointOK = (not useFirstMidpoint or close < firstMidpoint)
bool bearishPattern = (barstate.isconfirmed and firstBullish and middleHigherHigh and thirdBearish and close < close[1] and bearMiddleDirectionOK and bearThirdExtremeOK and bearStrongCloseOK and bearMidpointOK and patternRangeOK and thirdBodyOK)

// ============================================================================
// 18. EMA TREND 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)))

// ============================================================================
// 19. MARKET STRUCTURE BREAK
// ============================================================================
//
// The current bar is excluded.
// No future pivot candles are used.
//
// ============================================================================
float structureHigh = ta.highest(high[1], structureLookback)
float structureLow = ta.lowest(low[1], structureLookback)
float structureBuffer = (useStructureBuffer ? atr * structureBufferATR : 0.0)
bool longStructureOK = (not useStructureFilter or (not na(structureHigh) and close > structureHigh + structureBuffer))
bool shortStructureOK = (not useStructureFilter or (not na(structureLow) and close < structureLow - structureBuffer))

// ============================================================================
// 20. ADX, RSI AND VOLUME
// ============================================================================
[diPlus, diMinus, adx] = ta.dmi(diLength, adxSmoothing)
float rsi = ta.rsi(close, rsiLength)
float averageVolume = ta.sma(volume, volumeLength)
bool adxOK = (not useADXFilter or (not na(adx) and adx <= maximumADX))
bool volumeOK = (not useVolumeFilter or (not na(volume) and not na(averageVolume) and volume >= averageVolume * volumeFactor))
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 FILTER
// ============================================================================
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 AND 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 closedTradeNow = (strategy.closedtrades > nz(strategy.closedtrades[1], 0))
if closedTradeNow
    lastExitBar := bar_index
bool cooldownOK = (na(lastExitBar) or bar_index - lastExitBar > cooldownBars)
bool freshEntryBar = (na(lastEntryBar) or lastEntryBar != bar_index)

// ============================================================================
// 23. PENDING PATTERN STATE
// ============================================================================
var bool pendingLong = false
var bool pendingShort = false
var int longPatternBar = na
var int shortPatternBar = na
var int longPatternDay = na
var int shortPatternDay = na
var float longTrigger = na
var float shortTrigger = na
var float longInvalidLevel = na
var float shortInvalidLevel = na
var int bullPatternCount = 0
var int bearPatternCount = 0
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

// ============================================================================
// 24. NEXT BAR CONFIRMATION
// ============================================================================
bool nextBarMode = (entryMode == "Next Bar Breakout")
bool validLongWindow = (pendingLong and not na(longPatternBar) and longPatternDay == dayKey and bar_index > longPatternBar and bar_index - longPatternBar <= confirmationBars)
bool validShortWindow = (pendingShort and not na(shortPatternBar) and shortPatternDay == dayKey and bar_index > shortPatternBar and bar_index - shortPatternBar <= confirmationBars)
bool longExtremeOK = (not cancelOnNewExtreme or (not na(longInvalidLevel) and low >= longInvalidLevel))
bool shortExtremeOK = (not cancelOnNewExtreme or (not na(shortInvalidLevel) and high <= shortInvalidLevel))
bool longConfirmCandleOK = (not requireConfirmCandle or close > open)
bool shortConfirmCandleOK = (not requireConfirmCandle or close < open)
bool confirmedLong = (barstate.isconfirmed and validLongWindow and longExtremeOK and longConfirmCandleOK and not na(longTrigger) and close > longTrigger)
bool confirmedShort = (barstate.isconfirmed and validShortWindow and shortExtremeOK and shortConfirmCandleOK and not na(shortTrigger) and close < shortTrigger)

// ============================================================================
// 25. ENTRY BASES
// ============================================================================
bool longBase = (nextBarMode ? confirmedLong : bullishPattern)
bool shortBase = (nextBarMode ? confirmedShort : bearishPattern)

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

// ============================================================================
// 27. ENTRY GATES
// ============================================================================
bool canTrade = (barstate.isconfirmed and intradayOK and flat and strategy.opentrades == 0 and tradesToday < maxTradesPerDay and cooldownOK and freshEntryBar and sessionOK 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)

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

// ============================================================================
// 29. LONG ENTRY
// ============================================================================
if enterLong
    strategy.entry("Long", strategy.long, comment="3-Bar Structure LONG", alert_message="🟢 VÀO VỊ THẾ LONG (CNPS83)\\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\\n🛑 Cắt lỗ (SL): " + str.tostring(close - effectiveSL, format.mintick) + "\\n💰 Chốt lời (TP): " + str.tostring(close + effectiveTP, format.mintick))
    tradesToday += 1
    longEntryCount += 1
    lastEntryBar := bar_index

// ============================================================================
// 30. SHORT ENTRY
// ============================================================================
if enterShort
    strategy.entry("Short", strategy.short, comment="3-Bar Structure SHORT", alert_message="🔴 VÀO VỊ THẾ SHORT (CNPS83)\\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\\n🛑 Cắt lỗ (SL): " + str.tostring(close + effectiveSL, format.mintick) + "\\n💰 Chốt lời (TP): " + str.tostring(close - effectiveTP, format.mintick))
    tradesToday += 1
    shortEntryCount += 1
    lastEntryBar := bar_index

// ============================================================================
// 31. UPDATE PATTERN STATE
// ============================================================================
//
// State is updated AFTER signals are evaluated.
//
// This prevents a new pattern from confirming
// itself on the same bar in breakout mode.
//
// ============================================================================
if barstate.isconfirmed
    if bullishPattern
        bullPatternCount += 1
    if bearishPattern
        bearPatternCount += 1
    if longBase
        longBaseCount += 1
    if shortBase
        shortBaseCount += 1
    if rawLong
        filteredLongCount += 1
    if rawShort
        filteredShortCount += 1

    // --------------------------------------------------------
    // RESET AT NEW DAY
    // --------------------------------------------------------
    if newDay
        pendingLong := false
        pendingShort := false
        longPatternBar := na
        shortPatternBar := na
        longPatternDay := na
        shortPatternDay := na
        longTrigger := na
        shortTrigger := na
        longInvalidLevel := na
        shortInvalidLevel := na

    // --------------------------------------------------------
    // EXPIRE OR INVALIDATE LONG
    // --------------------------------------------------------
    if pendingLong and not na(longPatternBar)
        bool expiredLong = (bar_index - longPatternBar > confirmationBars)
        bool invalidLong = (cancelOnNewExtreme and not na(longInvalidLevel) and low < longInvalidLevel)
        if expiredLong or invalidLong
            pendingLong := false
            longPatternBar := na
            expiredLongCount += 1

    // --------------------------------------------------------
    // EXPIRE OR INVALIDATE SHORT
    // --------------------------------------------------------
    if pendingShort and not na(shortPatternBar)
        bool expiredShort = (bar_index - shortPatternBar > confirmationBars)
        bool invalidShort = (cancelOnNewExtreme and not na(shortInvalidLevel) and high > shortInvalidLevel)
        if expiredShort or invalidShort
            pendingShort := false
            shortPatternBar := na
            expiredShortCount += 1

    // --------------------------------------------------------
    // CONSUME PENDING SETUP AFTER ENTRY
    // --------------------------------------------------------
    if enterLong
        pendingLong := false
        longPatternBar := na
    if enterShort
        pendingShort := false
        shortPatternBar := na

    // --------------------------------------------------------
    // REGISTER NEW PATTERN
    // --------------------------------------------------------
    bool registerOK = (nextBarMode and intradayOK and flat and sessionOK and beforeForceClose and not enterLong and not enterShort)
    if registerOK and bullishPattern and not pendingLong
        pendingLong := true
        longPatternBar := bar_index
        longPatternDay := dayKey
        longTrigger := patternHigh
        longInvalidLevel := patternLow
        pendingShort := false
        shortPatternBar := na
    if registerOK and bearishPattern and not pendingShort
        pendingShort := true
        shortPatternBar := bar_index
        shortPatternDay := dayKey
        shortTrigger := patternLow
        shortInvalidLevel := patternHigh
        pendingLong := false
        longPatternBar := na

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

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

// ============================================================================
// 34. 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 (CNPS83 - Time Exit)\\n📌 Giá đóng: " + str.tostring(close, format.mintick))

// ============================================================================
// 35. 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 (CNPS83 - Session End)\\n📌 Giá đóng: " + str.tostring(close, format.mintick))

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

// ============================================================================
// 37. MARKET STRUCTURE PLOTS
// ============================================================================
plot(showStructureLevels ? structureHigh : na, title="Structure High", color=color.new(color.red, 40), linewidth=1, style=plot.style_stepline)
plot(showStructureLevels ? structureLow : na, title="Structure Low", color=color.new(color.green, 40), linewidth=1, style=plot.style_stepline)

// ============================================================================
// 38. PATTERN MARKERS
// ============================================================================
//
// OFF by default to avoid visual clutter.
//
// ============================================================================
plotshape(showPatternMarkers and bullishPattern, title="Bullish Three-Bar Pattern", style=shape.circle, location=location.belowbar, color=color.aqua, size=size.tiny, text="3B")
plotshape(showPatternMarkers and bearishPattern, title="Bearish Three-Bar Pattern", style=shape.circle, location=location.abovebar, color=color.orange, size=size.tiny, text="3B")

// ============================================================================
// 39. PENDING TRIGGER LEVELS
// ============================================================================
plot(showPendingLevels and pendingLong ? longTrigger : na, title="Pending Long Trigger", color=color.aqua, linewidth=2, style=plot.style_linebr)
plot(showPendingLevels and pendingShort ? shortTrigger : na, title="Pending Short Trigger", color=color.fuchsia, linewidth=2, style=plot.style_linebr)

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

// ============================================================================
// 41. ACTIVE SL / TP
// ============================================================================
float longSL = (inLong ? strategy.position_avg_price - effectiveSL : na)
float longTP = (inLong ? strategy.position_avg_price + effectiveTP : na)
float shortSL = (inShort ? strategy.position_avg_price + effectiveSL : na)
float shortTP = (inShort ? strategy.position_avg_price - effectiveTP : na)
plot(showSLTP ? longSL : na, title="Long SL", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showSLTP ? longTP : na, title="Long TP", color=color.green, linewidth=2, style=plot.style_linebr)
plot(showSLTP ? shortSL : na, title="Short SL", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showSLTP ? shortTP : na, title="Short TP", color=color.green, linewidth=2, style=plot.style_linebr)

// ============================================================================
// 42. DATA WINDOW
// ============================================================================
plot(atr, title="ATR", color=color.gray, display=display.data_window)
plot(adx, title="ADX", color=color.purple, display=display.data_window)
plot(rsi, title="RSI", color=color.blue, display=display.data_window)
plot(patternRange, title="Three-Bar Pattern Range", color=color.orange, display=display.data_window)

// ============================================================================
// 43. DIAGNOSTICS
// ============================================================================
var table diagnostics = table.new(position.top_right, 2, 17, border_width=1)
if showDiagnostics and barstate.islast
    table.cell(diagnostics, 0, 0, "CNPS83 V2")
    table.cell(diagnostics, 1, 0, timeframe.period)
    table.cell(diagnostics, 0, 1, "Bull Patterns")
    table.cell(diagnostics, 1, 1, str.tostring(bullPatternCount))
    table.cell(diagnostics, 0, 2, "Bear Patterns")
    table.cell(diagnostics, 1, 2, str.tostring(bearPatternCount))
    table.cell(diagnostics, 0, 3, "Long Bases")
    table.cell(diagnostics, 1, 3, str.tostring(longBaseCount))
    table.cell(diagnostics, 0, 4, "Short Bases")
    table.cell(diagnostics, 1, 4, str.tostring(shortBaseCount))
    table.cell(diagnostics, 0, 5, "Filtered Long")
    table.cell(diagnostics, 1, 5, str.tostring(filteredLongCount))
    table.cell(diagnostics, 0, 6, "Filtered Short")
    table.cell(diagnostics, 1, 6, str.tostring(filteredShortCount))
    table.cell(diagnostics, 0, 7, "Long Entries")
    table.cell(diagnostics, 1, 7, str.tostring(longEntryCount))
    table.cell(diagnostics, 0, 8, "Short Entries")
    table.cell(diagnostics, 1, 8, str.tostring(shortEntryCount))
    table.cell(diagnostics, 0, 9, "Pending Long")
    table.cell(diagnostics, 1, 9, pendingLong ? "YES" : "NO")
    table.cell(diagnostics, 0, 10, "Pending Short")
    table.cell(diagnostics, 1, 10, pendingShort ? "YES" : "NO")
    table.cell(diagnostics, 0, 11, "Expired Long")
    table.cell(diagnostics, 1, 11, str.tostring(expiredLongCount))
    table.cell(diagnostics, 0, 12, "Expired Short")
    table.cell(diagnostics, 1, 12, str.tostring(expiredShortCount))
    table.cell(diagnostics, 0, 13, "EMA Up")
    table.cell(diagnostics, 1, 13, emaUp ? "YES" : "NO")
    table.cell(diagnostics, 0, 14, "EMA Down")
    table.cell(diagnostics, 1, 14, emaDown ? "YES" : "NO")
    table.cell(diagnostics, 0, 15, "Trades Today")
    table.cell(diagnostics, 1, 15, str.tostring(tradesToday) + "/" + str.tostring(maxTradesPerDay))
    table.cell(diagnostics, 0, 16, "Position")
    table.cell(diagnostics, 1, 16, inLong ? "LONG" : inShort ? "SHORT" : "FLAT")

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

2.1. Giải phẫu mẫu hình 3 nến (Three-Bar Price Structure) & Lọc biên độ ATR

Bot đánh giá 3 nến gần nhất gồm nến 1 ([2]), nến 2 ([1]) và nến 3 (nến hiện tại vừa đóng cửa):

  • Biên độ mẫu hình (patternRange):
    • patternHigh = max(high, high[1], high[2])
    • patternLow = min(low, low[1], low[2])
    • patternRange = patternHigh - patternLow
  • Bộ lọc biên độ (patternRangeOK): Khi usePatternRange = true, biên độ 3 nến phải thỏa mãn 0.50 * ATR <= patternRange <= 5.00 * ATR (với ATR(14)), giúp loại bỏ các cụm nến quá hẹp (nhiễu đi ngang) hoặc quá giãn (biến động bất thường).
  • Điểm giữa nến 1 (firstMidpoint): Được tính bằng (high[2] + low[2]) / 2.0. Nến 3 phải đóng cửa vượt qua mốc này để chứng minh phe đảo chiều đã giành lại ít nhất 50% vùng giá nến khởi đầu.
  • Tỷ lệ thân nến 3 (bodyRatio): Nếu bật useThirdBodyFilter, thân nến 3 (|close - open| / (high - low)) phải đạt tối thiểu 0.40.

2.2. Xác nhận phá vỡ ở nến kế tiếp (Next Bar Breakout)

Mặc định entryMode = "Next Bar Breakout" không vào lệnh ngay tại nến 3 của mẫu hình. Thay vào đó:

  • Khi xuất hiện bullishPattern (hoặc bearishPattern), bot ghi nhận trạng thái chờ (pendingLong / pendingShort) với mức kích hoạt longTrigger = patternHigh (hoặc shortTrigger = patternLow) và mức vô hiệu hóa longInvalidLevel = patternLow (hoặc shortInvalidLevel = patternHigh).
  • Trạng thái chờ chỉ có hiệu lực trong cùng ngày (longPatternDay == dayKey) và trong tối đa confirmationBars = 5 nến sau nến mẫu hình.
  • Đặc biệt, trạng thái mẫu hình được cập nhật sau khi đánh giá tín hiệu (Update Pattern State ở mục 31), giúp ngăn chặn tuyệt đối việc một mẫu hình tự xác nhận chính nó ngay trên cùng một cây nến.

2.3. Phá vỡ cấu trúc ngắn hạn (Market Structure Break) & Bộ lọc xu hướng

  • Cấu trúc ngắn hạn: Bot tính đỉnh cấu trúc structureHigh = ta.highest(high[1], structureLookback) và đáy cấu trúc structureLow = ta.lowest(low[1], structureLookback) với structureLookback = 3 (loại trừ nến hiện tại, không dùng pivot tương lai). Tín hiệu Long yêu cầu close > structureHigh + structureBuffer, tín hiệu Short yêu cầu close < structureLow - structureBuffer.
  • Xu hướng EMA (EMA 50): Độ dốc tăng emaUp khi ema > ema[3] và giảm emaDown khi ema < ema[3]. Khi requirePriceEMA = true, giá đóng cửa phải nằm cùng phía với EMA (close > ema cho Long, close < ema cho Short).
  • Bộ lọc tùy chọn (mặc định tắt): Hỗ trợ giới hạn ADX(14, 14) <= 35.0, khối lượng volume >= SMA(20) * 1.0, vùng RSI(14) (<= 65.0 cho Long, >= 35.0 cho Short) và xu hướng khung H1 (useH1Bias dùng close[1] so với EMA 50 của khung 60 phút với lookahead=barmerge.lookahead_on trên dữ liệu đã đóng).

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

Quy trình vận hành khép kín của CNPS83 trên mỗi cây nến đóng cửa (barstate.isconfirmed) diễn ra theo 5 bước:

  1. Khởi tạo phiên & làm mới bộ đếm: Khi sang ngày mới (newDay), bot đặt lại tradesToday = 0 và xóa toàn bộ trạng thái chờ (pendingLong, pendingShort, các mức trigger/invalid). Đồng thời kiểm tra khung giờ phiên (09:15 – 14:15) và mốc đóng cưỡng bức (14:45).
  2. Quét mẫu hình 3 nến & xác nhận: Kiểm tra nến hiện tại có hình thành bullishPattern hoặc bearishPattern hay không. Nếu đang ở chế độ "Next Bar Breakout", bot kiểm tra xem giá có đóng cửa vượt longTrigger/shortTrigger trong cửa sổ 5 nến hay không để tạo tín hiệu gốc longBase/shortBase.
  3. Sàng lọc qua bộ lọc kỹ thuật: Kết hợp longBase/shortBase với phá vỡ cấu trúc (longStructureOK/shortStructureOK), xu hướng EMA (longTrendOK/shortTrendOK) và các bộ lọc tùy chọn (ADX, Volume, RSI, H1 Bias) để ra tín hiệu rawLong/rawShort.
  4. Kiểm tra cổng vào lệnh (canTrade) & gửi lệnh: Đảm bảo không có vị thế mở (flat), chưa chạm giới hạn 2 lệnh/ngày, đã hết thời gian nghỉ 3 nến (cooldownOK) và không xuất hiện tín hiệu mâu thuẫn hai chiều (ambiguousSignal). Nếu hợp lệ, gọi strategy.entry và tăng tradesToday.
  5. Cập nhật trạng thái chờ & quản trị thoát lệnh: Hủy các setup chờ quá hạn hoặc bị phá cực trị, tiêu thụ setup vừa vào lệnh, đăng ký setup mới nếu đủ điều kiện, đồng thời theo dõi thoát lệnh qua SL/TP cố định, Time Exit (nếu bật) hoặc Force Close lúc 14:45.

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

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

Lệnh Long (enterLong) chỉ được kích hoạt khi allowLong = true (mặc định tradeDirection = "Long"), canTrade = true, không bị ambiguousSignal và thỏa mãn đồng thời:

  1. Mẫu hình 3 nến tăng (bullishPattern):
    • Nến 1 giảm (close[2] < open[2]).
    • Nến 2 tạo đáy thấp hơn (low[1] < low[2]) và là nến giảm (close[1] < open[1] khi requireMiddleDirection = true).
    • Nến 3 tăng (close > open), đóng cửa cao hơn nến 2 (close > close[1]), giữ được đáy nến 2 (low >= low[1]), đóng cửa vượt đỉnh nến 2 (close > high[1]) và vượt điểm giữa nến 1 (close > firstMidpoint).
    • Biên độ 3 nến nằm trong [0.50 * ATR, 5.00 * ATR].
  2. Xác nhận phá vỡ (longBase): Ở chế độ mặc định "Next Bar Breakout", trong vòng 1 đến 5 nến sau nến mẫu hình (cùng ngày), không có nến nào phá xuống dưới longInvalidLevel (patternLow), nến xác nhận là nến tăng (close > open) và đóng cửa vượt longTrigger (patternHigh). (Nếu chọn "Signal Candle Close", longBase lấy trực tiếp bullishPattern).
  3. Phá vỡ cấu trúc & xu hướng: close > ta.highest(high[1], 3) + structureBuffer, ema > ema[3] và close > ema.
  4. Bộ lọc tùy chọn (nếu bật): adx <= 35.0, volume >= averageVolume * 1.0, rsi <= 65.0, và trên khung < 1H có h1Close > h1EMA.

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

Lệnh Short (enterShort) chỉ được kích hoạt khi allowShort = true (cần chuyển tradeDirection sang "Short" hoặc "Both"), canTrade = true, không bị ambiguousSignal và thỏa mãn đồng thời:

  1. Mẫu hình 3 nến giảm (bearishPattern):
    • Nến 1 tăng (close[2] > open[2]).
    • Nến 2 tạo đỉnh cao hơn (high[1] > high[2]) và là nến tăng (close[1] > open[1] khi requireMiddleDirection = true).
    • Nến 3 giảm (close < open), đóng cửa thấp hơn nến 2 (close < close[1]), giữ được đỉnh nến 2 (high <= high[1]), đóng cửa dưới đáy nến 2 (close < low[1]) và dưới điểm giữa nến 1 (close < firstMidpoint).
    • Biên độ 3 nến nằm trong [0.50 * ATR, 5.00 * ATR].
  2. Xác nhận phá vỡ (shortBase): Ở chế độ "Next Bar Breakout", trong vòng 1 đến 5 nến sau nến mẫu hình (cùng ngày), giá không vượt lên trên shortInvalidLevel (patternHigh), nến xác nhận là nến giảm (close < open) và đóng cửa dưới shortTrigger (patternLow).
  3. Phá vỡ cấu trúc & xu hướng: close < ta.lowest(low[1], 3) - structureBuffer, ema < ema[3] và close < ema.
  4. Bộ lọc tùy chọn (nếu bật): adx <= 35.0, volume >= averageVolume * 1.0, rsi >= 35.0, và trên khung < 1H có h1Close < h1EMA.

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

Mọi lệnh vào đều phải vượt qua cổng canTrade:

  • Nến đã đóng cửa (barstate.isconfirmed) trên biểu đồ nội ngày (timeframe.isintraday).
  • Trạng thái tài khoản đang flat (strategy.position_size == 0 và strategy.opentrades == 0), không có giao dịch nào vừa mở trên cùng một nến (freshEntryBar).
  • Số lệnh trong ngày nhỏ hơn giới hạn (tradesToday < maxTradesPerDay, mặc định tối đa 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).
  • Nằm trong khung giờ vào lệnh (09:15 ≤ thời gian mở nến và thời gian đóng nến ≤ 14:15 theo giờ Asia/Ho_Chi_Minh) và trước giờ đóng cưỡng bứ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 sang Tick

CNPS83 sử dụng mức cắt lỗ cố định theo điểm và tự động quy đổi sang số tick chuẩn của hợp đồng VN30F1M:

  • slTicks = math.max(1, int(math.round(stopLossPoints / syminfo.mintick))) (mặc định stopLossPoints = 5.0 điểm).
  • effectiveSL = slTicks * syminfo.mintick.
  • Mức SL được gắn trực tiếp vào strategy.exit tính từ giá khớp lệnh trung bình thực tế (strategy.position_avg_price - effectiveSL cho Long và + effectiveSL cho Short).

5.2. Cơ chế Take Profit, Time Exit và Force Close

Bot không sử dụng Break Even hay Trailing Stop, thay vào đó tập trung vào 3 cơ chế thoát lệnh rõ ràng:

  • Take Profit cố định: tpTicks = math.max(1, int(math.round(takeProfitPoints / syminfo.mintick))) (mặc định 10.0 điểm, tỷ lệ R:R 1:2 so với SL 5.0 điểm).
  • Time Exit (Tùy chọn, mặc định tắt): Khi useTimeExit = true, nếu số nến nắm giữ barsHeld >= maxHoldingBars (20 nến) tại nến đóng cửa (và không trùng nến đóng phiên), bot gọi strategy.close_all(immediately=true) với ghi chú "Time Exit".
  • Force Close cuối phiên: Tại cây nến đóng cửa cắt qua mốc 14:45 (openMinutes < 14:45 và closeMinutes >= 14:45), nếu còn vị thế mở, bot lập tức đóng toàn bộ bằng strategy.close_all(immediately=true, comment="Session End") để tránh rủi ro qua đêm (overnight/ATO).

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

Cơ chế thoát lệnhTrạng thái mặc địnhThông sốHành vi thực tế trong code
Stop Loss (Cắt lỗ)Luôn bật5.0 điểm (slTicks)Đóng vị thế qua strategy.exit từ giá khớp thực tế
Take Profit (Chốt lời)Luôn bật10.0 điểm (tpTicks)Đóng vị thế qua strategy.exit khi đạt mục tiêu lợi nhuận
Time Exit (Thoát theo thời gian)Tắt (false)20 nến (maxHoldingBars)Đóng toàn bộ vị thế bằng strategy.close_all nếu giữ quá số nến
Session End (Đóng cuối phiên)Luôn bật14:45 (Asia/Ho_Chi_Minh)Đóng toàn bộ vị thế tại nến kết phiên trước ATC

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 (chọn khung thời gian nội ngày phù hợp như 5m hoặc 15m).
  2. Nhấn vào tab Pine Editor ở thanh công cụ phía dưới màn hình.
  3. Xóa mã mặc định, sao chép toàn bộ mã nguồn Pine Script v6 ở Mục 1 và dán vào Pine Editor.
  4. Nhấn Save để lưu chiến lược, sau đó nhấn Add to chart để đưa CNPS83 THREE-BAR REVERSAL V2 lên biểu đồ.
  5. Mở biểu tượng bánh răng Settings của chiến lược để điều chỉnh hướng giao dịch (Long, Short, Both), khối lượng hợp đồng (Properties -> Order size), hoặc bật Show Diagnostics để theo dõi thông số.

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

Khi bật showDiagnostics = true, bot hiển thị bảng 17 dòng ở góc trên bên phải (position.top_right) giúp bạn kiểm tra sức khỏe và tỷ lệ lọc của chiến lược:

  • CNPS83 V2 | <timeframe>: Tên phiên bản và khung thời gian biểu đồ đang chạy.
  • Bull Patterns / Bear Patterns: Tổng số mẫu hình 3 nến tăng/giảm đạt chuẩn được phát hiện.
  • Long Bases / Short Bases: Số tín hiệu đã vượt qua bước xác nhận (hoặc nến mẫu hình nếu dùng Signal Candle Close).
  • Filtered Long / Filtered Short: Số tín hiệu sống sót sau khi đi qua bộ lọc cấu trúc, EMA và các bộ lọc tùy chọn.
  • Long Entries / Short Entries: Số lệnh Long/Short thực tế đã được gửi vào thị trường.
  • Pending Long / Pending Short (YES/NO): Trạng thái hiện tại có đang chờ nến phá vỡ xác nhận hay không.
  • Expired Long / Expired Short: Số lượng thiết lập chờ bị hủy do quá 5 nến hoặc bị phá vỡ cực trị mẫu hình.
  • EMA Up / EMA Down (YES/NO): Trạng thái độ dốc của đường EMA 50 tại nến hiện tại.
  • Trades Today: Số lệnh đã giao dịch trong ngày trên tổng giới hạn (ví dụ 1/2).
  • 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ự động qua ứng dụng TradingView, Telegram hoặc Webhook khi Bot CNPS83 phát sinh lệnh, bạn thực hiện:

  1. Nhấn vào biểu tượng đồng hồ Create Alert (hoặc phím tắt Alt + A).
  2. Ở mục Condition, chọn chiến lược CNPS83 THREE-BAR REVERSAL V2.
  3. Ở mục Message, xóa nội dung mặc định và nhập chính xác biến: {{strategy.order.alert_message}}
  4. Nếu không muốn nhận thông báo khi chạm SL/TP (chỉ nhận thông báo vào lệnh và đóng phiên), bạn có thể tick chọn Disable SL/TP Alerts (disableExitAlerts = true) trong phần cài đặt của bot.
  5. Nhấn Create để kích hoạt cảnh báo.

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

Sự kiệnNội dung thông điệp (alert_message / alert_profit / alert_loss)
Vào lệnh Long🟢 VÀO VỊ THẾ LONG (CNPS83) + Giá vào (close), SL (close - effectiveSL), TP (close + effectiveTP)
Vào lệnh Short🔴 VÀO VỊ THẾ SHORT (CNPS83) + Giá vào (close), SL (close + effectiveSL), TP (close - effectiveTP)
Chốt lời Long (TP)💰 CHỐT LỜI LONG (CNPS83 - TP HIT) + Giá chốt lời (strategy.position_avg_price + effectiveTP)
Cắt lỗ Long (SL)🛑 CẮT LỖ LONG (CNPS83 - SL HIT) + Giá cắt lỗ (strategy.position_avg_price - effectiveSL)
Chốt lời Short (TP)💰 CHỐT LỜI SHORT (CNPS83 - TP HIT) + Giá chốt lời (strategy.position_avg_price - effectiveTP)
Cắt lỗ Short (SL)🛑 CẮT LỜI SHORT (CNPS83 - SL HIT) (nguyên văn trong code: 🛑 CẮT LỖ SHORT (CNPS83 - SL HIT)) + Giá cắt lỗ (strategy.position_avg_price + effectiveSL)
Thoát lệnh hết thời gian⏱️ ĐÓNG VỊ THẾ HẾT THỜI GIAN (CNPS83 - Time Exit) + Giá đóng (close)
Đóng vị thế cuối phiên⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (CNPS83 - Session End) + Giá đóng (close)

Kết luận

Bot CNPS83 (Three-Bar Reversal V2) là một hệ thống giao dịch có cấu trúc chặt chẽ, kết hợp giữa hành động giá đảo chiều 3 nến, xác nhận phá vỡ ở nến kế tiếp, phá vỡ cấu trúc ngắn hạn và xu hướng EMA 50. Chiến lược phát huy hiệu quả tốt nhất trong các phiên thị trường VN30F1M có xu hướng rõ ràng với những nhịp điều chỉnh ngắn hạn trước khi tiếp diễn xu hướng chính, đồng thời vẫn đảm bảo kỷ luật nhờ SL/TP cố định, giới hạn số lệnh/ngày và tự động đóng vị thế trước ATC.

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

Thông tin chỉ mang tính tham khảo, không phải khuyến nghị đầu tư. Kết quả kiểm thử quá khứ không đảm bảo lợi nhuận trong tương lai.

Thông tin trong bài chỉ mang tính tham khảo, không phải khuyến nghị mua bán. Giao dịch phái sinh có rủi ro cao do sử dụng đòn bẩy; nhà đầu tư tự chịu trách nhiệm với quyết định của mình.

Đ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