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

Hướng Dẫn Sử Dụng Bot CNPS87 - MFI Exhaustion Reversal V2 cho VN30F1M

Bot CNPS87 V2 kết hợp chỉ báo MFI thoát vùng quá mua/quá bán với xác nhận phá vỡ cấu trúc giá (Market Structure Breakout) trên VN30F1M, tích hợp bộ lọc đa khung H1 và quản trị rủi ro SL/TP cố định.

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

Khi giao dịch hợp đồng tương lai VN30F1M, một trong những cái bẫy phổ biến nhất của các chiến lược đảo chiều (Mean Reversion) là bắt đáy hoặc bán đỉnh quá sớm chỉ dựa vào việc chỉ báo động lượng đi vào vùng quá bán/quá mua. Khi thị trường có xung lực mạnh, chỉ báo có thể neo ở vùng cực đoan trong nhiều nến liên tiếp, khiến lệnh vào sớm bị quét Stop Loss liên tục.

CNPS87 — tên đầy đủ trong mã nguồn là CNPS87 MFI EXHAUSTION REVERSAL V2 (shorttitle="CNPS87 MFI V2") — được viết bằng Pine Script v6 trên TradingView để giải quyết trực tiếp bài toán này. Thay vì vào lệnh ngay khi Money Flow Index (MFI) đảo chiều, bot tách quy trình thành 2 pha rõ ràng: ghi nhận Setup cạn kiệt dòng tiền từ MFI và chỉ kích hoạt lệnh khi có xác nhận phá vỡ cấu trúc giá (Market Structure Breakout) ở các nến kế tiếp.

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

  • MFI chỉ là Setup, không phải điểm vào lệnh tức thì: Ngăn chặn tình trạng bắt dao rơi bằng cách đóng băng vùng cấu trúc giá tại nến Setup và chờ nến sau xác nhận phá vỡ.
  • Chống xác nhận trên cùng một nến (No Same-Candle Confirmation): Setup mới chỉ được đăng ký sau khi kết thúc đánh giá nến đóng cửa (barstate.isconfirmed), loại bỏ hoàn toàn tín hiệu nhiễu nội nến.
  • Cơ chế hủy Setup thông minh (Timeout & Invalidation): Tự động hủy Setup chờ nếu quá số nến cho phép (confirmationWindow = 8), hết ngày giao dịch, MFI quay ngược lại vùng cực đoan, hoặc giá phá vỡ cực trị của nến Setup.
  • Quản trị rủi ro chặt chẽ: Cắt lỗ/Chốt lời cố định theo điểm quy đổi ra tick (SL = 5.0 điểm, TP = 15.0 điểm), giới hạn số lệnh trong ngày (2 lệnh/ngày), thời gian nghỉ sau thoát lệnh (cooldownBars = 3) và tự động đóng toàn bộ vị thế cuối phiên (14:45).

1. CNPS87 MFI Exhaustion Reversal V2 là gì?

CNPS87 MFI Exhaustion Reversal V2 là hệ thống giao dịch đảo chiều có xác nhận cấu trúc (Structure-Confirmed Reversal) dành cho khung thời gian nội ngày (timeframe.isintraday) trên VN30F1M. Chiến lược được xây dựng dựa trên 4 trụ cột kỹ thuật chính:

  1. Động lượng dòng tiền (Money Flow Index - MFI): Phát hiện trạng thái cạn kiệt lực mua/bán khi MFI tiến vào vùng quá bán (≤ 20.0) hoặc quá mua (≥ 80.0) trong 5 nến gần nhất và cắt ngược trở lại vùng trung tính.
  2. Cấu trúc giá & Phá vỡ xác nhận (Market Structure Breakout): Lưu trữ đỉnh/đáy cấu trúc trong 5 nến gần nhất làm ngưỡng kích hoạt (longTrigger / shortTrigger) kèm khoảng đệm ATR (0.05 * ATR), đòi hỏi các nến tiếp theo phải đóng cửa vượt ngưỡng kèm nến đúng hướng.
  3. Hệ thống bộ lọc đa tầng tùy chọn (Price Exhaustion & Regime Filters): Cho phép bật/tắt linh hoạt bộ lọc râu nến từ chối giá (Wick Filter), vị trí gần đỉnh/đáy Swing (Swing Filter), xu hướng EMA 50, giới hạn sức mạnh xu hướng ADX ≤ 35, xác nhận khối lượng (Volume MA 20) và xu hướng khung H1 đã đóng cửa.
  4. Kiểm soát phiên & Quản trị lệnh chuẩn VN30F1M: Giới hạn khung giờ mở lệnh 09:15 – 14:15 (múi giờ Asia/Ho_Chi_Minh), đóng toàn bộ vị thế tại nến 14:45, giới hạn tối đa 2 lệnh/ngày và khoảng nghỉ 3 nến sau mỗi lần đóng lệnh.

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

Nhóm thông sốTên tham số trong codeGiá trị mặc địnhÝ nghĩa thực tế
01. Money Flow IndexmfiLength14Chu kỳ tính chỉ báo MFI (hlc3)
oversoldLevel / overboughtLevel20.0 / 80.0Ngưỡng quá bán / quá mua của MFI
extremeLookback5Số nến nhìn lại để kiểm tra MFI từng chạm vùng cực đoan
minimumMFIChange0.0Biên độ thay đổi tối thiểu của MFI khi cắt lại vùng trung tính
02. Market StructurestructureLookback5Số nến tính đỉnh/đáy cấu trúc (recentStructureHigh / Low)
confirmationWindow8Số nến tối đa chờ xác nhận phá vỡ kể từ nến Setup
useStructureBreaktrueBắt buộc phá vỡ cấu trúc đa nến thay vì chỉ vượt đỉnh/đáy nến Setup
useBreakoutBuffer / breakoutBufferATRtrue / 0.05Khoảng đệm phá vỡ bằng 0.05 × ATR(14)
requireBreakoutCandletrueBắt buộc nến phá vỡ là nến tăng (Long) hoặc nến giảm (Short)
requireMFIHoldtrueMFI phải duy trì trên 20.0 (Long) hoặc dưới 80.0 (Short) khi xác nhận
cancelOnExtremeBreak / invalidationBufferATRtrue / 0.0Hủy Setup nếu giá phá vỡ cực trị nến Setup
03. Price ExhaustionatrLength14Chu kỳ tính ATR dùng cho buffer và Swing tolerance
useSwingFilter / swingLookback / swingToleranceATRfalse / 10 / 0.50Lọc Setup gần đáy/đỉnh Swing 10 nến (dung sai 0.5 × ATR)
useWickFilter / minimumWickRatiofalse / 0.20Lọc râu nến từ chối tối thiểu 20% biên độ nến
04. EMA TrenduseEMAFilter / emaLength / emaSlopeBarsfalse / 50 / 3Lọc hướng dốc EMA(50) so với 3 nến trước (requirePriceEMA = false)
05. Optional FiltersuseADXFilter / diLength / adxSmoothing / maximumADXfalse / 14 / 14 / 35.0Chỉ giao dịch khi ADX ≤ 35.0 (tránh thị trường có xu hướng quá gắt)
useVolumeFilter / volumeLength / volumeFactorfalse / 20 / 1.0Yêu cầu volume ≥ SMA(volume, 20) × 1.0
06. H1 BiasuseH1Bias / h1EMALengthfalse / 50Lọc theo close[1] so với EMA(50)[1] trên khung H1 đã xác nhận
07. Risk ManagementstopLossPoints / takeProfitPoints5.0 / 15.0Cắt lỗ 5.0 điểm / Chốt lời 15.0 điểm (quy đổi sang tick)
useTimeExit / maximumHoldingBarsfalse / 20Thoát lệnh theo thời gian nếu giữ quá 20 nến
08. Trade ControltradeDirection / contracts"Long" / 3Hướng giao dịch mặc định (Long / Short / Both); số hợp đồng khai báo (3)
maximumTradesPerDay / cooldownBars2 / 3Tối đa 2 lệnh/ngày; nghỉ ít nhất 3 nến sau khi đóng lệnh
09. Trading SessionuseSessionFilter / tztrue / "Asia/Ho_Chi_Minh"Bật lọc phiên theo giờ Việt Nam
startHour:startMinute – lastHour:lastMinute09:15 – 14:15Khung giờ cho phép mở vị thế mới
endHour:endMinute14:45Thời điểm bắt buộc đóng toàn bộ vị thế (Force Session Close)
10. Alerts & 11. DisplaydisableExitAlerts / showDiagnosticsfalse / falseBật/tắt cảnh báo SL/TP và bảng Diagnostics

Source Code CNPS87 MFI Exhaustion 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="CNPS87 MFI EXHAUSTION REVERSAL V2", shorttitle="CNPS87 MFI 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)

// ============================================================================
// CNPS87 V2 - MFI EXHAUSTION + MARKET STRUCTURE
//
// LONG:
// 1. MFI enters oversold.
// 2. MFI crosses back above oversold.
// 3. Store recent structure high and setup low.
// 4. Wait for a later confirmed breakout above structure.
// 5. Confirm optional trend, volume, ADX, H1.
// 6. Enter LONG.
//
// SHORT: Symmetric logic.
//
// Improvements over V1:
// - MFI is a setup, not an immediate trade.
// - Mandatory default structure confirmation.
// - Setup timeout and invalidation.
// - No same-candle setup and confirmation.
// - Confirmed bar entry conditions.
// - Previous confirmed H1 data.
// - Fixed SL / TP in ticks.
// - Daily limits, cooldown and diagnostics.
// ============================================================================
// ============================================================================
// 01. MONEY FLOW INDEX
// ============================================================================
gMFI = "01. Money Flow Index"
mfiLength = input.int(14, "MFI Length", minval=2, maxval=200, group=gMFI)
oversoldLevel = input.float(20.0, "MFI Oversold", minval=1.0, maxval=49.0, step=1.0, group=gMFI)
overboughtLevel = input.float(80.0, "MFI Overbought", minval=51.0, maxval=99.0, step=1.0, group=gMFI)
extremeLookback = input.int(5, "MFI Extreme Lookback", minval=1, maxval=100, group=gMFI)
minimumMFIChange = input.float(0.0, "Minimum MFI Re-entry Change", minval=0.0, step=0.5, group=gMFI)

// ============================================================================
// 02. MARKET STRUCTURE
// ============================================================================
gStructure = "02. Market Structure"
structureLookback = input.int(5, "Structure Lookback", minval=2, maxval=100, group=gStructure)
confirmationWindow = input.int(8, "Maximum Confirmation Bars", minval=1, maxval=50, group=gStructure)
useStructureBreak = input.bool(true, "Require Structure Breakout", group=gStructure)
useBreakoutBuffer = input.bool(true, "Use Breakout Buffer", group=gStructure)
breakoutBufferATR = input.float(0.05, "Breakout Buffer / ATR", minval=0.0, step=0.05, group=gStructure)
requireBreakoutCandle = input.bool(true, "Require Breakout Candle Direction", group=gStructure)
requireMFIHold = input.bool(true, "Require MFI To Hold Re-entry Zone", group=gStructure)
cancelOnExtremeBreak = input.bool(true, "Cancel If Setup Extreme Breaks", group=gStructure)
invalidationBufferATR = input.float(0.0, "Invalidation Buffer / ATR", minval=0.0, step=0.05, group=gStructure)

// ============================================================================
// 03. PRICE EXHAUSTION
// ============================================================================
gPrice = "03. Price Exhaustion"
atrLength = input.int(14, "ATR Length", minval=1, group=gPrice)
useSwingFilter = input.bool(false, "Require Setup Near Swing Extreme", group=gPrice)
swingLookback = input.int(10, "Swing Lookback", minval=3, maxval=200, group=gPrice)
swingToleranceATR = input.float(0.50, "Swing Tolerance / ATR", minval=0.0, step=0.1, group=gPrice)
useWickFilter = input.bool(false, "Require Setup Rejection Wick", group=gPrice)
minimumWickRatio = input.float(0.20, "Minimum Wick / Candle Range", minval=0.0, maxval=1.0, step=0.05, group=gPrice)

// ============================================================================
// 04. EMA TREND FILTER
// ============================================================================
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(false, "Require Price Above/Below EMA", group=gTrend)

// ============================================================================
// 05. OPTIONAL FILTERS
// ============================================================================
gFilters = "05. Optional Filters"
useADXFilter = input.bool(false, "Use Maximum ADX", 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)
useVolumeFilter = input.bool(false, "Use Volume Confirmation", group=gFilters)
volumeLength = input.int(20, "Volume MA Length", minval=2, group=gFilters)
volumeFactor = input.float(1.0, "Minimum Volume Factor", minval=0.1, step=0.1, group=gFilters)

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

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

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

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

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

// ============================================================================
// 11. DISPLAY
// ============================================================================
gDisplay = "11. Display"
showEMA = input.bool(true, "Show EMA", group=gDisplay)
showMFIMarkers = input.bool(false, "Show MFI Setup Dots", group=gDisplay)
showPendingLevels = input.bool(true, "Show Pending Structure Levels", group=gDisplay)
showEntryMarkers = input.bool(true, "Show Entry Markers", 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 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. INDICATOR ENGINE
// ============================================================================
float mfi = ta.mfi(hlc3, mfiLength)
float atr = ta.atr(atrLength)
float ema = ta.ema(close, emaLength)
[diPlus, diMinus, adx] = ta.dmi(diLength, adxSmoothing)
float averageVolume = ta.sma(volume, volumeLength)

// ============================================================================
// 15. MFI RE-ENTRY CONDITIONS
// ============================================================================
float previousLowestMFI = ta.lowest(mfi[1], extremeLookback)
float previousHighestMFI = ta.highest(mfi[1], extremeLookback)
bool recentOversold = (not na(previousLowestMFI) and previousLowestMFI <= oversoldLevel)
bool recentOverbought = (not na(previousHighestMFI) and previousHighestMFI >= overboughtLevel)
bool mfiCrossUp = ta.crossover(mfi, oversoldLevel)
bool mfiCrossDown = ta.crossunder(mfi, overboughtLevel)
bool bullishMFIReentry = (barstate.isconfirmed and recentOversold and mfiCrossUp and not na(mfi[1]) and mfi - mfi[1] >= minimumMFIChange)
bool bearishMFIReentry = (barstate.isconfirmed and recentOverbought and mfiCrossDown and not na(mfi[1]) and mfi[1] - mfi >= minimumMFIChange)

// ============================================================================
// 16. PRICE STRUCTURE
// ============================================================================
//
// Structure is calculated from prior bars.
// On a setup candle, the trigger is frozen.
// Subsequent candles must break that trigger.
//
// ============================================================================
float recentStructureHigh = ta.highest(high, structureLookback)
float recentStructureLow = ta.lowest(low, structureLookback)
float previousSwingHigh = ta.highest(high[1], swingLookback)
float previousSwingLow = ta.lowest(low[1], swingLookback)
float swingTolerance = (not na(atr) ? atr * swingToleranceATR : 0.0)
bool longSwingOK = (not useSwingFilter or (not na(previousSwingLow) and low <= previousSwingLow + swingTolerance))
bool shortSwingOK = (not useSwingFilter or (not na(previousSwingHigh) and high >= previousSwingHigh - swingTolerance))

// ============================================================================
// 17. CANDLE ANATOMY
// ============================================================================
float candleRange = (high - low)
float lowerWick = (math.min(open, close) - low)
float upperWick = (high - math.max(open, close))
float lowerWickRatio = (candleRange > 0 ? lowerWick / candleRange : 0.0)
float upperWickRatio = (candleRange > 0 ? upperWick / candleRange : 0.0)
bool bullishCandle = close > open
bool bearishCandle = close < open
bool longWickOK = (not useWickFilter or lowerWickRatio >= minimumWickRatio)
bool shortWickOK = (not useWickFilter or upperWickRatio >= minimumWickRatio)

// ============================================================================
// 18. SETUP QUALIFICATION
// ============================================================================
bool bullishSetup = (bullishMFIReentry and longSwingOK and longWickOK)
bool bearishSetup = (bearishMFIReentry and shortSwingOK and shortWickOK)

// ============================================================================
// 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 AND VOLUME FILTERS
// ============================================================================
bool adxOK = (not useADXFilter or (not na(adx) and adx <= maximumADX))
bool volumeOK = (not useVolumeFilter or (not na(volume) and not na(averageVolume) and averageVolume > 0 and volume >= averageVolume * volumeFactor))

// ============================================================================
// 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. STATE VARIABLES
// ============================================================================
var bool pendingLong = false
var bool pendingShort = false
var int longSetupBar = na
var int shortSetupBar = na
var int longSetupDay = na
var int shortSetupDay = na
var float longTrigger = na
var float shortTrigger = na
var float longInvalidLevel = na
var float shortInvalidLevel = na
var int bullReentryCount = 0
var int bearReentryCount = 0
var int bullSetupCount = 0
var int bearSetupCount = 0
var int longBreakCount = 0
var int shortBreakCount = 0
var int longFilterCount = 0
var int shortFilterCount = 0
var int expiredLongCount = 0
var int expiredShortCount = 0
var int longEntryCount = 0
var int shortEntryCount = 0

// ============================================================================
// 24. SETUP VALIDITY
// ============================================================================
bool validLongWindow = (pendingLong and not na(longSetupBar) and longSetupDay == dayKey and bar_index > longSetupBar and bar_index - longSetupBar <= confirmationWindow)
bool validShortWindow = (pendingShort and not na(shortSetupBar) and shortSetupDay == dayKey and bar_index > shortSetupBar and bar_index - shortSetupBar <= confirmationWindow)
float breakoutBuffer = (useBreakoutBuffer and not na(atr) ? atr * breakoutBufferATR : 0.0)
float invalidationBuffer = (not na(atr) ? atr * invalidationBufferATR : 0.0)
bool longInvalid = (validLongWindow and cancelOnExtremeBreak and not na(longInvalidLevel) and low < longInvalidLevel - invalidationBuffer)
bool shortInvalid = (validShortWindow and cancelOnExtremeBreak and not na(shortInvalidLevel) and high > shortInvalidLevel + invalidationBuffer)
bool longMFIHoldOK = (not requireMFIHold or (not na(mfi) and mfi > oversoldLevel))
bool shortMFIHoldOK = (not requireMFIHold or (not na(mfi) and mfi < overboughtLevel))

// ============================================================================
// 25. STRUCTURE CONFIRMATION
// ============================================================================
//
// If structure breakout is enabled:
// LONG must close above frozen structure high.
// SHORT must close below frozen structure low.
//
// If disabled:
// LONG/SHORT still require directional candle
// and an improvement over the setup candle's
// extreme, but not the multi-bar structure.
//
// ============================================================================
bool longBreakOK = (validLongWindow and not na(longTrigger) and close > longTrigger + breakoutBuffer)
bool shortBreakOK = (validShortWindow and not na(shortTrigger) and close < shortTrigger - breakoutBuffer)
bool longPriceOK = (useStructureBreak ? longBreakOK : (validLongWindow and not na(longTrigger) and close > longTrigger - breakoutBuffer))
bool shortPriceOK = (useStructureBreak ? shortBreakOK : (validShortWindow and not na(shortTrigger) and close < shortTrigger + breakoutBuffer))
bool longCandleOK = (not requireBreakoutCandle or bullishCandle)
bool shortCandleOK = (not requireBreakoutCandle or bearishCandle)
bool longBase = (barstate.isconfirmed and longPriceOK and not longInvalid and longMFIHoldOK and longCandleOK)
bool shortBase = (barstate.isconfirmed and shortPriceOK and not shortInvalid and shortMFIHoldOK and shortCandleOK)

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

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

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

// ============================================================================
// 29. LONG ENTRY
// ============================================================================
if enterLong
    strategy.entry("Long", strategy.long, comment="MFI Structure LONG", alert_message="🟢 VÀO VỊ THẾ LONG (CNPS87)\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="MFI Structure SHORT", alert_message="🔴 VÀO VỊ THẾ SHORT (CNPS87)\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 STATE
// ============================================================================
//
// Entries above use previously saved setups.
//
// New setups are registered after evaluation.
// This prevents same-candle confirmation.
//
// ============================================================================
if barstate.isconfirmed
    if bullishMFIReentry
        bullReentryCount += 1
    if bearishMFIReentry
        bearReentryCount += 1
    if bullishSetup
        bullSetupCount += 1
    if bearishSetup
        bearSetupCount += 1
    if longBase
        longBreakCount += 1
    if shortBase
        shortBreakCount += 1
    if rawLong
        longFilterCount += 1
    if rawShort
        shortFilterCount += 1

    // --------------------------------------------------------
    // CANCEL PREVIOUS-DAY SETUPS
    // --------------------------------------------------------
    if newDay
        pendingLong := false
        pendingShort := false
        longSetupBar := na
        shortSetupBar := na
        longSetupDay := na
        shortSetupDay := na
        longTrigger := na
        shortTrigger := na
        longInvalidLevel := na
        shortInvalidLevel := na

    // --------------------------------------------------------
    // LONG EXPIRATION
    // --------------------------------------------------------
    if pendingLong and not na(longSetupBar)
        bool expiredLong = (longSetupDay != dayKey or bar_index - longSetupBar > confirmationWindow)
        bool invalidLong = ((cancelOnExtremeBreak and not na(longInvalidLevel) and low < longInvalidLevel - invalidationBuffer) or (requireMFIHold and not na(mfi) and mfi <= oversoldLevel))
        if expiredLong or invalidLong or enterLong
            if expiredLong or invalidLong
                expiredLongCount += 1
            pendingLong := false
            longSetupBar := na

    // --------------------------------------------------------
    // SHORT EXPIRATION
    // --------------------------------------------------------
    if pendingShort and not na(shortSetupBar)
        bool expiredShort = (shortSetupDay != dayKey or bar_index - shortSetupBar > confirmationWindow)
        bool invalidShort = ((cancelOnExtremeBreak and not na(shortInvalidLevel) and high > shortInvalidLevel + invalidationBuffer) or (requireMFIHold and not na(mfi) and mfi >= overboughtLevel))
        if expiredShort or invalidShort or enterShort
            if expiredShort or invalidShort
                expiredShortCount += 1
            pendingShort := false
            shortSetupBar := na

    // --------------------------------------------------------
    // REGISTER NEW SETUP
    // --------------------------------------------------------
    bool canRegister = (intradayOK and flat and entrySessionOK and beforeForceClose and tradesToday < maximumTradesPerDay and not enterLong and not enterShort)
    if (canRegister and bullishSetup and not pendingLong and not pendingShort and not na(recentStructureHigh))
        pendingLong := true
        longSetupBar := bar_index
        longSetupDay := dayKey
        longTrigger := (useStructureBreak ? recentStructureHigh : high)
        longInvalidLevel := low
    if (canRegister and bearishSetup and not pendingShort and not pendingLong and not na(recentStructureLow))
        pendingShort := true
        shortSetupBar := bar_index
        shortSetupDay := dayKey
        shortTrigger := (useStructureBreak ? recentStructureLow : low)
        shortInvalidLevel := high

// ============================================================================
// 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 (CNPS87 - TP HIT)\n🎯 Giá chốt lời: " + str.tostring(strategy.position_avg_price + effectiveTP, format.mintick), alert_loss="🛑 CẮT LỖ LONG (CNPS87 - 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 (CNPS87 - TP HIT)\n🎯 Giá chốt lời: " + str.tostring(strategy.position_avg_price - effectiveTP, format.mintick), alert_loss="🛑 CẮT LỖ SHORT (CNPS87 - 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 >= 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 (CNPS87 - Time Exit)\n📌 Giá đóng: " + str.tostring(close, format.mintick))

// ============================================================================
// 35. FORCE SESSION 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 (CNPS87 - 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. MFI SETUP MARKERS
// ============================================================================
plotshape(showMFIMarkers and bullishSetup, title="Bullish MFI Re-entry Setup", style=shape.circle, location=location.belowbar, color=color.aqua, size=size.tiny, text="MFI")
plotshape(showMFIMarkers and bearishSetup, title="Bearish MFI Re-entry Setup", style=shape.circle, location=location.abovebar, color=color.orange, size=size.tiny, text="MFI")

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

// ============================================================================
// 39. ENTRY MARKERS
// ============================================================================
plotshape(showEntryMarkers and enterLong, title="CNPS87 V2 LONG", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, text="LONG", textcolor=color.white)
plotshape(showEntryMarkers and enterShort, title="CNPS87 V2 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(mfi, title="Money Flow Index", color=color.blue, display=display.data_window)
plot(atr, title="ATR", color=color.gray, display=display.data_window)
plot(adx, title="ADX", color=color.purple, display=display.data_window)
plot(longTrigger, title="Stored Long Trigger", color=color.aqua, display=display.data_window)
plot(shortTrigger, title="Stored Short Trigger", color=color.fuchsia, display=display.data_window)

// ============================================================================
// 42. DIAGNOSTICS
// ============================================================================
var table diagnostics = table.new(position.top_right, 2, 19, border_width=1)
if showDiagnostics and barstate.islast
    table.cell(diagnostics, 0, 0, "CNPS87 V2")
    table.cell(diagnostics, 1, 0, timeframe.period)
    table.cell(diagnostics, 0, 1, "MFI")
    table.cell(diagnostics, 1, 1, str.tostring(mfi, "#.##"))
    table.cell(diagnostics, 0, 2, "Bull Re-entry")
    table.cell(diagnostics, 1, 2, str.tostring(bullReentryCount))
    table.cell(diagnostics, 0, 3, "Bear Re-entry")
    table.cell(diagnostics, 1, 3, str.tostring(bearReentryCount))
    table.cell(diagnostics, 0, 4, "Bull Setups")
    table.cell(diagnostics, 1, 4, str.tostring(bullSetupCount))
    table.cell(diagnostics, 0, 5, "Bear Setups")
    table.cell(diagnostics, 1, 5, str.tostring(bearSetupCount))
    table.cell(diagnostics, 0, 6, "Long Breaks")
    table.cell(diagnostics, 1, 6, str.tostring(longBreakCount))
    table.cell(diagnostics, 0, 7, "Short Breaks")
    table.cell(diagnostics, 1, 7, str.tostring(shortBreakCount))
    table.cell(diagnostics, 0, 8, "Filtered Long")
    table.cell(diagnostics, 1, 8, str.tostring(longFilterCount))
    table.cell(diagnostics, 0, 9, "Filtered Short")
    table.cell(diagnostics, 1, 9, str.tostring(shortFilterCount))
    table.cell(diagnostics, 0, 10, "Long Entries")
    table.cell(diagnostics, 1, 10, str.tostring(longEntryCount))
    table.cell(diagnostics, 0, 11, "Short Entries")
    table.cell(diagnostics, 1, 11, str.tostring(shortEntryCount))
    table.cell(diagnostics, 0, 12, "Pending Long")
    table.cell(diagnostics, 1, 12, pendingLong ? "YES" : "NO")
    table.cell(diagnostics, 0, 13, "Pending Short")
    table.cell(diagnostics, 1, 13, pendingShort ? "YES" : "NO")
    table.cell(diagnostics, 0, 14, "Expired Long")
    table.cell(diagnostics, 1, 14, str.tostring(expiredLongCount))
    table.cell(diagnostics, 0, 15, "Expired Short")
    table.cell(diagnostics, 1, 15, str.tostring(expiredShortCount))
    table.cell(diagnostics, 0, 16, "EMA Up")
    table.cell(diagnostics, 1, 16, emaUp ? "YES" : "NO")
    table.cell(diagnostics, 0, 17, "Trades Today")
    table.cell(diagnostics, 1, 17, str.tostring(tradesToday) + "/" + str.tostring(maximumTradesPerDay))
    table.cell(diagnostics, 0, 18, "Position")
    table.cell(diagnostics, 1, 18, inLong ? "LONG" : inShort ? "SHORT" : "FLAT")

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

2.1. Tín hiệu cạn kiệt và tái nhập MFI (MFI Re-entry Setup)

Bot sử dụng ta.mfi(hlc3, 14) — chỉ báo kết hợp giữa giá trung bình (High + Low + Close) / 3 và khối lượng giao dịch. Thay vì bắt điểm cắt thông thường, CNPS87 kiểm tra tính liên tục của trạng thái quá bán/quá mua:

  • previousLowestMFI = ta.lowest(mfi[1], 5) phải nhỏ hơn hoặc bằng 20.0 (cho Long) hoặc previousHighestMFI = ta.highest(mfi[1], 5) phải lớn hơn hoặc bằng 80.0 (cho Short).
  • Tại nến đóng cửa xác nhận (barstate.isconfirmed), MFI phải cắt lên trên 20.0 (ta.crossover) hoặc cắt xuống dưới 80.0 (ta.crossunder), với độ dốc |mfi - mfi[1]| >= minimumMFIChange.

2.2. Đóng băng cấu trúc giá & Bộ lọc giải phẫu nến (Frozen Structure & Candle Anatomy)

Tại thời điểm nến Setup được đăng ký:

  • Ngưỡng kích hoạt (longTrigger / shortTrigger): Khi useStructureBreak = true (mặc định), bot đóng băng đỉnh cao nhất ta.highest(high, 5) cho Setup Long hoặc đáy thấp nhất ta.lowest(low, 5) cho Setup Short. Nếu tắt useStructureBreak, ngưỡng kích hoạt sẽ là high hoặc low của chính nến Setup.
  • Mức vô hiệu (longInvalidLevel / shortInvalidLevel): Lưu lại low của nến Setup Long (hoặc high của nến Setup Short).
  • Lọc Swing & Râu nến (tùy chọn): useSwingFilter kiểm tra xem nến Setup có nằm sát vùng đáy/đỉnh 10 nến trước đó trong biên độ 0.5 × ATR(14) hay không; useWickFilter đo tỷ lệ râu nến rút chân lowerWick / candleRange hoặc râu trên upperWick / candleRange tối thiểu 0.20.

2.3. Hệ thống bộ lọc xu hướng, ADX, Volume và H1 Bias

Để tránh giao dịch ngược dòng chảy chính của thị trường, bot cung cấp 4 lớp lọc tùy chọn (mặc định đều ở trạng thái false để ưu tiên độ tinh khiết của tín hiệu cấu trúc):

  • EMA Trend (useEMAFilter): Kiểm tra độ dốc ema > ema[3] (Long) hoặc ema < ema[3] (Short) trên EMA(50), có thể kết hợp requirePriceEMA để ép giá nằm trên/dưới EMA.
  • Maximum ADX (useADXFilter): Sử dụng ta.dmi(14, 14) và chỉ cho phép giao dịch khi adx <= 35.0, loại bỏ giai đoạn thị trường đang có xu hướng một chiều quá mạnh khiến nhịp hồi dễ thất bại.
  • Volume Confirmation (useVolumeFilter): Yêu cầu volume >= SMA(volume, 20) * 1.0 tại nến phá vỡ.
  • Confirmed H1 Bias (useH1Bias): Gọi request.security(..., "60", ...[1], lookahead=barmerge.lookahead_on) lấy giá đóng cửa và EMA(50) của nến H1 đã đóng liền trước (tránh repaint), yêu cầu khung biểu đồ hiện tại nhỏ hơn 60 phút (timeframe.in_seconds() < 3600).

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

Bot vận hành theo chu trình khép kín trên mỗi nến đóng cửa (barstate.isconfirmed):

  1. Khởi tạo phiên & Bộ đếm ngày: Xác định dayKey theo múi giờ Asia/Ho_Chi_Minh. Khi sang ngày mới (newDay), bot reset tradesToday := 0 và xóa sạch mọi Setup đang chờ (pendingLong, pendingShort) từ phiên trước.
  2. Đánh giá Setup đang chờ để vào lệnh: Nếu đang có pendingLong hoặc pendingShort hợp lệ (trong cửa sổ 1 đến 8 nến sau nến Setup, cùng ngày giao dịch), bot kiểm tra giá đóng cửa phá vỡ ngưỡng Trigger ± breakoutBuffer, nến cùng chiều, MFI giữ vùng tái nhập và không vi phạm mức vô hiệu.
  3. Kiểm tra cổng vào lệnh & Gửi lệnh: Nếu vượt qua các bộ lọc tùy chọn và thỏa mãn canTrade (chưa có vị thế, đủ cooldown, trong khung giờ 09:15 – 14:15, chưa chạm 2 lệnh/ngày), bot thực thi strategy.entry và tăng bộ đếm.
  4. Cập nhật trạng thái & Đăng ký Setup mới: Sau phần vào lệnh, bot kiểm tra điều kiện hết hạn/vô hiệu của Setup cũ, rồi mới đăng ký Setup mới nếu nến hiện tại thỏa mãn bullishSetup hoặc bearishSetup (đảm bảo không bao giờ vào lệnh trên cùng nến phát sinh Setup).
  5. Quản trị & Đóng vị thế: Theo dõi SL/TP cố định theo tick, kiểm tra Time Exit (nếu bật) và tự động strategy.close_all tại nến 14:45 (forceCloseBar).

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

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

Lệnh Long (enterLong) được kích hoạt khi allowLong bật (tradeDirection là "Long" hoặc "Both") và thỏa mãn đồng thời:

  • Setup Long đã được đăng ký trước đó (pendingLong == true): Tại nến Setup trước đó, MFI(14) từng ở mức ≤ 20.0 trong 5 nến liền trước, cắt lên trên 20.0 với biên độ mfi - mfi[1] >= minimumMFIChange, đồng thời thỏa mãn longSwingOK và longWickOK (nếu bật).
  • Cửa sổ thời gian hợp lệ (validLongWindow): Nến hiện tại cùng ngày với nến Setup (longSetupDay == dayKey) và nằm trong khoảng 1 đến 8 nến sau longSetupBar.
  • Phá vỡ cấu trúc (longPriceOK): Khi useStructureBreak = true, giá đóng cửa close > longTrigger + breakoutBuffer (với breakoutBuffer = ATR(14) * 0.05).
  • Không bị vô hiệu (not longInvalid): Giá thấp nhất không thủng longInvalidLevel - invalidationBuffer.
  • Giữ vùng MFI & Nến tăng: mfi > 20.0 (requireMFIHold = true) và close > open (requireBreakoutCandle = true).
  • Bộ lọc bổ sung (nếu bật): longTrendOK, adxOK, volumeOK, longH1OK đều đạt và không trùng tín hiệu Short (not ambiguousSignal).

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

Lệnh Short (enterShort) hoạt động đối xứng khi allowShort bật (tradeDirection là "Short" hoặc "Both"):

  • Setup Short đã được đăng ký (pendingShort == true): MFI(14) từng đạt ≥ 80.0 trong 5 nến liền trước, cắt xuống dưới 80.0 với mfi[1] - mfi >= minimumMFIChange, thỏa mãn shortSwingOK và shortWickOK (nếu bật).
  • Cửa sổ hợp lệ (validShortWindow): Cùng ngày giao dịch và trong vòng 1 đến 8 nến sau shortSetupBar.
  • Phá vỡ cấu trúc (shortPriceOK): Giá đóng cửa close < shortTrigger - breakoutBuffer.
  • Không bị vô hiệu (not shortInvalid): Giá cao nhất không vượt shortInvalidLevel + invalidationBuffer.
  • Giữ vùng MFI & Nến giảm: mfi < 80.0 và close < open.
  • Bộ lọc bổ sung (nếu bật): shortTrendOK, adxOK, volumeOK, shortH1OK đều đạt và not ambiguousSignal.

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

Mọi lệnh vào mới đều phải vượt qua hàng rào kiểm soát canTrade:

  • Nến nội ngày đã đóng: barstate.isconfirmed và timeframe.isintraday.
  • Trạng thái Flat: strategy.position_size == 0 và strategy.opentrades == 0 (chiến lược đặt pyramiding=0, không nhồi lệnh).
  • Giới hạn lệnh ngày: tradesToday < 2 (maximumTradesPerDay).
  • Thời gian nghỉ (Cooldown) & Nến mới: bar_index - lastExitBar > 3 (cooldownBars = 3, tức phải qua ít nhất 3 nến sau nến đóng lệnh gần nhất) và lastEntryBar != bar_index.
  • Khung giờ giao dịch: openMinutes >= 09:15 và closeMinutes <= 14:15 (entrySessionOK), đồng thời closeMinutes < 14:45 (beforeForceClose).

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

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

Bot sử dụng mức cắt lỗ cố định theo điểm số (stopLossPoints = 5.0), được quy đổi sang đơn vị tick của hợp đồng để truyền vào strategy.exit:

  • slTicks = math.max(1, int(math.round(stopLossPoints / syminfo.mintick)))
  • effectiveSL = slTicks * syminfo.mintick
  • Với VN30F1M (syminfo.mintick = 0.1), 5.0 điểm tương ứng 50 ticks. Giá SL được vẽ trực tiếp trên biểu đồ tại strategy.position_avg_price - effectiveSL (Long) hoặc + effectiveSL (Short).

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

  • Take Profit cố định: Tính tương tự theo takeProfitPoints = 15.0 (150 ticks trên VN30F1M), tạo tỷ lệ Risk:Reward mặc định là 1:3. Bot không sử dụng Break Even hay Trailing Stop trong phiên bản này.
  • Thoát lệnh theo thời gian (useTimeExit): Mặc định tắt (false). Khi bật, nếu số nến nắm giữ barsHeld >= 20 (maximumHoldingBars) và không trùng nến Force Close, bot gọi strategy.close_all đóng lệnh ở giá đóng cửa.
  • Đóng vị thế bắt buộc cuối phiên (Force Session Close): Tại nến có openMinutes < 14:45 và closeMinutes >= 14:45, nếu vẫn còn vị thế mở, bot tự động đóng toàn bộ với comment "Session End" để tránh giữ lệnh qua đêm.

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

Cơ chế bảo vệĐiều kiện kích hoạtHành động thực thiThông số mặc định
Stop Loss (SL)Giá chạm mức avg_price ∓ effectiveSLstrategy.exit (SL Long / SL Short)5.0 điểm (50 ticks)
Take Profit (TP)Giá chạm mức avg_price ± effectiveTPstrategy.exit (TP Long / TP Short)15.0 điểm (150 ticks)
Time ExituseTimeExit = true và barsHeld >= 20strategy.close_all (Time Exit)Tắt (false), 20 nến
Force Session CloseNến chạm mốc 14:45 (Asia/Ho_Chi_Minh)strategy.close_all (Session End)Bắt buộc (14:45)

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 nội ngày (ví dụ: M5 hoặc M15; lưu ý nếu bật useH1Bias thì khung biểu đồ bắt buộc phải nhỏ hơn 1H).
  2. Mở tab Pine Editor ở phía dưới màn hình, xóa toàn bộ code mẫu mặc định.
  3. 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), đặt tên tùy chọn (ví dụ CNPS87 MFI V2), 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 hướng giao dịch (Long, Short hoặc Both — lưu ý mặc định chỉ đang bật "Long"), mức SL/TP hoặc bật Show Diagnostics để theo dõi số liệu.

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

Khi bật showDiagnostics = true trong phần 11. Display, bot hiển thị bảng 2 × 19 ở góc trên bên phải (position.top_right) trên nến cuối cùng:

  • CNPS87 V2 / MFI: Khung thời gian đang chạy (timeframe.period) và giá trị MFI hiện tại.
  • Bull/Bear Re-entry & Bull/Bear Setups: Tổng số lần MFI cắt lại vùng trung tính và số lần thỏa điều kiện Setup (sau khi qua Swing/Wick filter).
  • Long/Short Breaks & Filtered Long/Short: Số lần phá vỡ cấu trúc thành công và số tín hiệu còn lại sau khi qua các bộ lọc EMA/ADX/Volume/H1.
  • Long/Short Entries: Tổng số lệnh Long và Short thực tế đã vào.
  • Pending Long / Pending Short: Trạng thái hiện tại có đang chờ phá vỡ cấu trúc hay không (YES / NO).
  • Expired Long / Expired Short: Số lượng Setup bị hủy do quá hạn 8 nến, sang ngày mới hoặc bị phá vỡ cực trị.
  • EMA Up / Trades Today / Position: Hướng dốc của EMA(50) (YES / NO), số lệnh đã mở trong ngày trên giới hạn (x/2) và trạng thái vị thế (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 Telegram, Webhook hoặc ứng dụng TradingView khi bot phát sinh lệnh:

  1. Nhấn biểu tượng Alert (đồng hồ báo thức) trên thanh công cụ TradingView.
  2. Ở mục Condition, chọn đúng tên chiến lược CNPS87 MFI EXHAUSTION REVERSAL V2.
  3. Ở ô Message, xóa nội dung mặc định và điền duy nhất biến: {{strategy.order.alert_message}}.
  4. Đặt tên Alert và nhấn Create. (Nếu không muốn nhận thông báo khi chạm SL/TP, hãy tích chọn Disable SL/TP Alerts trong cài đặt bot).

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

Sự kiệnĐiều kiện kích hoạtNội dung thông điệp (alert_message / alert_profit / alert_loss)
Vào lệnh LongenterLong🟢 VÀO VỊ THẾ LONG (CNPS87) kèm Giá vào, SL (close - effectiveSL) và TP (close + effectiveTP)
Vào lệnh ShortenterShort🔴 VÀO VỊ THẾ SHORT (CNPS87) kèm Giá vào, SL (close + effectiveSL) và TP (close - effectiveTP)
Chốt lời (TP)Chạm mức tpTicks💰 CHỐT LỜI LONG/SHORT (CNPS87 - TP HIT) kèm Giá chốt lời
Cắt lỗ (SL)Chạm mức slTicks🛑 CẮT LỖ LONG/SHORT (CNPS87 - SL HIT) kèm Giá cắt lỗ
Hết thời gianuseTimeExit đạt 20 nến⏱️ ĐÓNG VỊ THẾ HẾT THỜI GIAN (CNPS87 - Time Exit) kèm Giá đóng
Đóng cuối phiênChạm nến 14:45⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (CNPS87 - Session End) kèm Giá đóng

Kết luận

CNPS87 MFI Exhaustion Reversal V2 là một bước nâng cấp toàn diện cho chiến lược giao dịch đảo chiều trên VN30F1M nhờ việc tách bạch rõ giữa tín hiệu cạn kiệt dòng tiền (MFI Setup) và xác nhận phá vỡ cấu trúc giá (Market Structure Breakout). Hệ thống đặc biệt phù hợp với các nhịp thị trường có biên độ dao động rõ ràng hoặc điều chỉnh kỹ thuật trong phiên, nơi việc chờ nến xác nhận giúp cải thiện đáng kể tỷ lệ thắng và duy trì tỷ lệ Risk:Reward mục tiêu 1:3.

Bạn có thể tham khảo thêm các hệ thống giao dịch khác trên phaisinh.online như Bot CNPS50 - Trend Analysis V2 và Bot CNPS49 - Daily Open để đa dạng hóa góc nhìn và lựa chọn chiến lược phù hợp với phong cách giao dịch của mình.

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