Hướng Dẫn Sử Dụng Bot CNPS78 - Bollinger Squeeze Fakeout V3 cho VN30F1M
TradingviewBot CNPS78 Bollinger Squeeze Fakeout V3 phát hiện vùng nén Bollinger Bands, bắt nhịp phá vỡ giả (Fakeout) quay đầu vào trong dải với quản trị SL/TP cố định theo điểm, Time Exit và tự động đóng phiên.

Mục lục
Khi giao dịch hợp đồng tương lai VN30F1M, thị trường thường xuyên trải qua các giai đoạn đi ngang tích lũy với biên độ thu hẹp (nén biến động) trước khi xuất hiện một nhịp bứt phá. Tuy nhiên, rất nhiều cú phá vỡ ban đầu lại là phá vỡ giả (Fakeout / Bull Trap / Bear Trap): giá xuyên thủng biên trên hoặc biên dưới trong thời gian ngắn rồi lập tức quay đầu trở lại vùng cân bằng, khiến các chiến lược đánh theo breakout truyền thống dễ bị quét cắt lỗ.
Để giải quyết bài toán này, CNPS78 BOLLINGER SQUEEZE FAKEOUT V3 (tên rút gọn CNPS78 BB V3) được phát triển bằng Pine Script v6 trên nền tảng TradingView. Thay vì đuổi theo nhịp phá vỡ, bot tập trung nhận diện trạng thái nén của dải Bollinger Bands, theo dõi cú phá vỡ ra ngoài dải và chỉ kích hoạt lệnh đảo chiều khi giá thực sự quay trở lại bên trong dải kèm xác nhận hành động giá.
Những điểm nổi bật cốt lõi của CNPS78 Bollinger Squeeze Fakeout V3:
- Đo lường độ nén Bollinger chuẩn hóa (
BB Width %): So sánh độ rộng dải hiện tại với trung bình độ rộng trong100nến để phát hiện vùng nén biến động trước khi breakout xảy ra. - Máy trạng thái Fakeout có giới hạn cửa sổ: Theo dõi nhịp phá vỡ qua
pendingLong/pendingShorttrongfakeoutWindownến, tự động hủy kèo nếu hết hạn hoặc nếu giá đi quá xa (useMaximumExtension). - Hệ thống bộ lọc tùy chọn đa lớp: Hỗ trợ lọc theo ADX (tránh xu hướng quá mạnh), Volume Spike, RSI và Confirmed H1 EMA Bias (dữ liệu khung H1 đã đóng nến, không repaint).
- Quản trị rủi ro và phiên giao dịch chặt chẽ: Cài đặt SL/TP theo điểm quy đổi sang tick từ giá khớp thực tế, hỗ trợ thoát lệnh theo thời gian nắm giữ (
Time Exit), giới hạn số lệnh/ngày, thời gian nghỉ (Cooldown) và tự động đóng toàn bộ vị thế cuối phiên.
1. CNPS78 Bollinger Squeeze Fakeout V3 là gì?
CNPS78 Bollinger Squeeze Fakeout V3 là hệ thống giao dịch đảo chiều ngắn hạn (Mean Reversion sau Squeeze) được thiết kế cho VN30F1M. Chiến lược vận hành dựa trên 4 trụ cột kỹ thuật chính:
- Đo lường độ nén Bollinger Bands (Squeeze Engine): Tính toán dải trên, dải giữa, dải dưới của Bollinger Bands và theo dõi tỷ lệ phần trăm độ rộng dải (
bbWidthPercent). Khi độ rộng dải giảm xuống dưới mức trung bình nhân với hệ số nén trong nhóm nến liền trước, hệ thống ghi nhận thị trường đang ở trạng thái tích lũy nén. - Theo dõi phá vỡ giả (Fakeout State Machine): Khi giá đóng cửa vượt ra ngoài dải trên hoặc dải dưới sau một vùng nén, bot không vào lệnh ngay mà đưa tín hiệu vào trạng thái chờ (
pendingShorthoặcpendingLong) trong tối đafakeoutWindownến. - Xác nhận quay đầu & Bộ lọc đa điều kiện: Tín hiệu chỉ được hình thành khi giá đóng cửa quay trở lại vào bên trong dải Bollinger (
bbLower <= close <= bbUpper), thỏa mãn điều kiện nến đảo chiều và vượt qua các bộ lọc tùy chọn như ADX, Volume, RSI hoặc xu hướng H1 EMA. - Quản trị vị thế & Kiểm soát phiên: Mọi lệnh vào đều được gắn Stop Loss và Take Profit tính bằng tick từ
strategy.position_avg_price, kết hợp cơ chếTime Exit(nếu bật) và lệnh đóng toàn bộ vị thế trước giờ kết phiên (forceCloseBar).
Bảng thông số mặc định
| Nhóm | Thông số trong code | Giá trị mặc định | Ý nghĩa thực tế |
|---|---|---|---|
| 01. Bollinger Bands | bbLength / bbMultiplier / bbSource | 20 / 2.0 / close | Chu kỳ SMA 20, độ lệch chuẩn 2.0, nguồn giá đóng cửa |
| 02. Squeeze | squeezeLookback / squeezeFactor / recentSqueezeBars | 100 / 0.85 / 10 | So sánh BB Width với SMA 100 nến (<= 0.85x), kiểm tra trong 10 nến trước |
| 03. Fakeout | fakeoutWindow / atrLength | 5 / 14 | Cửa sổ chờ giá quay lại dải tối đa 5 nến; chu kỳ ATR 14 |
| 03. Fakeout | requireFreshBreakout / requireCandleDirection / requirePreviousCloseBreak | true / true / false | Yêu cầu nến phá vỡ mới; yêu cầu nến đảo chiều (close > open / close < open); không bắt buộc vượt close[1] |
| 03. Fakeout | useMinimumBreakDistance (minimumBreakATR) / useMaximumExtension (maximumExtensionATR) | false (0.10) / false (2.0) | Tắt mặc định bộ lọc khoảng cách phá vỡ tối thiểu và hủy kèo khi đi quá xa theo ATR |
| 04. Filters | useADXFilter (diLength, adxSmoothing, maximumADX) | false (14, 14, 35.0) | Tắt mặc định; khi bật yêu cầu adx <= 35.0 |
| 04. Filters | useVolumeFilter (volumeLength, volumeFactor) | false (20, 1.20) | Tắt mặc định; khi bật yêu cầu volume >= 1.20x SMA(20) |
| 04. Filters | useRSIFilter (rsiLength, longRSIMax, shortRSIMin) | false (14, 55.0, 45.0) | Tắt mặc định; khi bật Long cần rsi <= 55, Short cần rsi >= 45 |
| 05. H1 Bias | useH1EMABias / h1EMALength | false / 50 | Tắt mặc định; lọc theo giá đóng cửa H1 so với EMA(50) H1 đã xác nhận |
| 06. Risk Management | stopLossPoints / takeProfitPoints | 5.0 / 15.0 | Cắt lỗ 5.0 điểm, chốt lời 15.0 điểm (tỉ lệ R:R 1:3) |
| 06. Risk Management | useTimeExit / maximumHoldingBars | false / 20 | Tắt mặc định; khi bật sẽ đóng lệnh sau 20 nến nắm giữ |
| 07. Trade Control | tradeDirection / contracts | "Long" / 3 | Mặc định chỉ đánh chiều Long, khối lượng 3 hợp đồng |
| 07. Trade Control | maximumTradesPerDay / cooldownBars | 2 / 3 | Tối đa 2 lệnh/ngày, nghỉ ít nhất 3 nến sau khi đóng lệnh |
| 08. Session | useSessionFilter / strategyTimezone | false / "Asia/Ho_Chi_Minh" | Tắt bộ lọc giờ vào lệnh mặc định; múi giờ Việt Nam |
| 08. Session | startHour:startMinute / lastEntryHour:lastEntryMinute / endHour:endMinute | 09:00 / 14:30 / 14:45 | Khung giờ vào lệnh và giờ bắt buộc đóng vị thế (14:45) |
| 09. Alerts | disableExitAlerts | false | Cho phép gửi cảnh báo khi chạm SL/TP |
| 10. Display | showBands / showFakeoutMarkers / showSLTP / showDiagnostics | true / true / true / false | Hiển thị dải BB, mũi tên Long/Short, đường SL/TP; ẩn bảng chẩn đoán mặc định |
Source Code CNPS78 Bollinger Squeeze Fakeout V3
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="CNPS78 BOLLINGER SQUEEZE FAKEOUT V3", shorttitle="CNPS78 BB V3", 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)
// ============================================================================
// CNPS78 V3 - BOLLINGER SQUEEZE FAKEOUT
//
// LONG:
// 1. Recent Bollinger squeeze.
// 2. Close breaks below lower band.
// 3. Close returns inside bands within N bars.
// 4. Bullish confirmation.
// 5. LONG.
//
// SHORT:
// 1. Recent Bollinger squeeze.
// 2. Close breaks above upper band.
// 3. Close returns inside bands within N bars.
// 4. Bearish confirmation.
// 5. SHORT.
//
// Exits use ticks from actual entry fill.
// ============================================================================
// ============================================================================
// 01. BOLLINGER BANDS
// ============================================================================
groupBB = "01. Bollinger Bands"
bbLength = input.int(20, "Bollinger Length", minval=2, maxval=500, group=groupBB)
bbMultiplier = input.float(2.0, "Standard Deviation", minval=0.1, step=0.1, group=groupBB)
bbSource = input.source(close, "Bollinger Source", group=groupBB)
// ============================================================================
// 02. SQUEEZE DETECTION
// ============================================================================
groupSqueeze = "02. Squeeze"
squeezeLookback = input.int(100, "Average Width Lookback", minval=10, maxval=500, group=groupSqueeze)
squeezeFactor = input.float(0.85, "Maximum Width / Average Width", minval=0.1, maxval=2.0, step=0.05, group=groupSqueeze)
recentSqueezeBars = input.int(10, "Recent Squeeze Window", minval=1, maxval=100, group=groupSqueeze)
// ============================================================================
// 03. FAKEOUT
// ============================================================================
groupFakeout = "03. Fakeout"
fakeoutWindow = input.int(5, "Fakeout Window (Bars)", minval=1, maxval=30, group=groupFakeout)
requireFreshBreakout = input.bool(true, "Require Fresh Breakout", group=groupFakeout)
requireCandleDirection = input.bool(true, "Require Reversal Candle", group=groupFakeout)
requirePreviousCloseBreak = input.bool(false, "Require Previous Close Break", group=groupFakeout)
useMinimumBreakDistance = input.bool(false, "Use Minimum Break Distance", group=groupFakeout)
minimumBreakATR = input.float(0.10, "Minimum Break Distance / ATR", minval=0.0, step=0.05, group=groupFakeout)
useMaximumExtension = input.bool(false, "Cancel Excessive Extension", group=groupFakeout)
maximumExtensionATR = input.float(2.0, "Maximum Extension / ATR", minval=0.1, step=0.1, group=groupFakeout)
atrLength = input.int(14, "ATR Length", minval=1, group=groupFakeout)
// ============================================================================
// 04. OPTIONAL FILTERS
// ============================================================================
groupFilters = "04. Filters"
useADXFilter = input.bool(false, "Use ADX Filter", group=groupFilters)
diLength = input.int(14, "DI Length", minval=2, group=groupFilters)
adxSmoothing = input.int(14, "ADX Smoothing", minval=2, group=groupFilters)
maximumADX = input.float(35.0, "Maximum ADX", minval=1.0, step=1.0, group=groupFilters)
useVolumeFilter = input.bool(false, "Require Volume Spike", group=groupFilters)
volumeLength = input.int(20, "Volume MA Length", minval=2, group=groupFilters)
volumeFactor = input.float(1.20, "Volume Factor", minval=0.1, step=0.1, group=groupFilters)
useRSIFilter = input.bool(false, "Use RSI Filter", group=groupFilters)
rsiLength = input.int(14, "RSI Length", minval=2, group=groupFilters)
longRSIMax = input.float(55.0, "Maximum RSI For Long", minval=1, maxval=100, group=groupFilters)
shortRSIMin = input.float(45.0, "Minimum RSI For Short", minval=1, maxval=100, group=groupFilters)
// ============================================================================
// 05. H1 FILTER
// ============================================================================
groupH1 = "05. H1 Bias"
useH1EMABias = input.bool(false, "Use Confirmed H1 EMA Bias", group=groupH1)
h1EMALength = input.int(50, "H1 EMA Length", minval=1, group=groupH1)
// ============================================================================
// 06. RISK MANAGEMENT
// ============================================================================
groupRisk = "06. Risk Management"
stopLossPoints = input.float(5.0, "Stop Loss (Points)", minval=0.1, step=0.5, group=groupRisk)
takeProfitPoints = input.float(15.0, "Take Profit (Points)", minval=0.1, step=0.5, group=groupRisk)
useTimeExit = input.bool(false, "Use Time Exit", group=groupRisk)
maximumHoldingBars = input.int(20, "Maximum Holding Bars", minval=1, maxval=200, group=groupRisk)
// ============================================================================
// 07. TRADE CONTROL
// ============================================================================
groupTrade = "07. Trade Control"
tradeDirection = input.string("Long", "Trade Direction", options=["Long", "Short", "Both"], group=groupTrade)
contracts = input.int(3, "Contracts", minval=1, maxval=100, group=groupTrade)
maximumTradesPerDay = input.int(2, "Maximum Trades Per Day", minval=1, maxval=20, group=groupTrade)
cooldownBars = input.int(3, "Cooldown Bars After Exit", minval=0, maxval=100, group=groupTrade)
bool allowLong = (tradeDirection == "Long" or tradeDirection == "Both")
bool allowShort = (tradeDirection == "Short" or tradeDirection == "Both")
// ============================================================================
// 08. SESSION
// ============================================================================
groupSession = "08. Session"
useSessionFilter = input.bool(false, "Use Entry Session Filter", group=groupSession)
strategyTimezone = input.string("Asia/Ho_Chi_Minh", "Timezone", group=groupSession)
startHour = input.int(9, "Entry Start Hour", minval=0, maxval=23, group=groupSession)
startMinute = input.int(0, "Entry Start Minute", minval=0, maxval=59, group=groupSession)
lastEntryHour = input.int(14, "Last Entry Hour", minval=0, maxval=23, group=groupSession)
lastEntryMinute = input.int(30, "Last Entry Minute", minval=0, maxval=59, group=groupSession)
endHour = input.int(14, "Force Close Hour", minval=0, maxval=23, group=groupSession)
endMinute = input.int(45, "Force Close Minute", minval=0, maxval=59, group=groupSession)
// ============================================================================
// 09. ALERTS
// ============================================================================
groupAlerts = "09. Alerts"
disableExitAlerts = input.bool(false, "Disable SL/TP Alerts", group=groupAlerts)
// ============================================================================
// 10. DISPLAY
// ============================================================================
groupDisplay = "10. Display"
showBands = input.bool(true, "Show Bollinger Bands", group=groupDisplay)
showSqueezeMarkers = input.bool(false, "Show Squeeze Markers", group=groupDisplay)
showBreakoutMarkers = input.bool(false, "Show Breakout Markers", group=groupDisplay)
showFakeoutMarkers = input.bool(true, "Show Fakeout Markers", group=groupDisplay)
showSLTP = input.bool(true, "Show SL/TP", group=groupDisplay)
showDiagnostics = input.bool(false, "Show Diagnostics", group=groupDisplay)
// ============================================================================
// 11. TIME ENGINE
// ============================================================================
int barOpenMinutes = (hour(time, strategyTimezone) * 60 + minute(time, strategyTimezone))
int barCloseMinutes = (hour(time_close, strategyTimezone) * 60 + minute(time_close, strategyTimezone))
int entryStartMinutes = (startHour * 60 + startMinute)
int lastEntryMinutes = (lastEntryHour * 60 + lastEntryMinute)
int forceCloseMinutes = (endHour * 60 + endMinute)
bool entrySessionOK = (not useSessionFilter or (barOpenMinutes >= entryStartMinutes and barCloseMinutes <= lastEntryMinutes))
bool beforeForceClose = (barCloseMinutes < forceCloseMinutes)
bool forceCloseBar = (barOpenMinutes < forceCloseMinutes and barCloseMinutes >= forceCloseMinutes)
// ============================================================================
// 12. TRADING DAY
// ============================================================================
int dayKey = (year(time, strategyTimezone) * 10000 + month(time, strategyTimezone) * 100 + dayofmonth(time, strategyTimezone))
bool newTradingDay = (na(dayKey[1]) or dayKey != dayKey[1])
var int tradesToday = 0
if newTradingDay
tradesToday := 0
// ============================================================================
// 13. BOLLINGER ENGINE
// ============================================================================
float bbMiddle = ta.sma(bbSource, bbLength)
float bbDeviation = (bbMultiplier * ta.stdev(bbSource, bbLength))
float bbUpper = bbMiddle + bbDeviation
float bbLower = bbMiddle - bbDeviation
bool bandsReady = (not na(bbUpper) and not na(bbLower))
// ============================================================================
// 14. BANDWIDTH
// ============================================================================
float bbWidthPercent = (bandsReady and bbMiddle != 0 ? 100.0 * (bbUpper - bbLower) / math.abs(bbMiddle) : na)
float averageWidth = ta.sma(bbWidthPercent, squeezeLookback)
bool squeezeNow = (not na(bbWidthPercent) and not na(averageWidth) and bbWidthPercent <= averageWidth * squeezeFactor)
// ============================================================================
// 15. RECENT SQUEEZE - FIXED
// ============================================================================
//
// math.sum() is the correct Pine v6 function.
//
// Count ONLY previous bars so the squeeze
// must exist before breakout.
//
// ============================================================================
float squeezeRecentCount = math.sum(squeezeNow[1] ? 1.0 : 0.0, recentSqueezeBars)
bool squeezeRecently = (not na(squeezeRecentCount) and squeezeRecentCount > 0)
// ============================================================================
// 16. ATR AND BREAKOUT ENGINE
// ============================================================================
float atr = ta.atr(atrLength)
bool aboveUpper = (bandsReady and close > bbUpper)
bool belowLower = (bandsReady and close < bbLower)
bool freshUpperBreak = (aboveUpper and not aboveUpper[1])
bool freshLowerBreak = (belowLower and not belowLower[1])
bool upperBreakCandidate = (requireFreshBreakout ? freshUpperBreak : aboveUpper)
bool lowerBreakCandidate = (requireFreshBreakout ? freshLowerBreak : belowLower)
float upperBreakDistance = close - bbUpper
float lowerBreakDistance = bbLower - close
bool upperDistanceOK = (not useMinimumBreakDistance or (not na(atr) and upperBreakDistance >= minimumBreakATR * atr))
bool lowerDistanceOK = (not useMinimumBreakDistance or (not na(atr) and lowerBreakDistance >= minimumBreakATR * atr))
bool upperBreakoutEvent = (squeezeRecently and upperBreakCandidate and upperDistanceOK)
bool lowerBreakoutEvent = (squeezeRecently and lowerBreakCandidate and lowerDistanceOK)
// ============================================================================
// 17. OPTIONAL FILTERS
// ============================================================================
[diPlus, diMinus, adx] = ta.dmi(diLength, adxSmoothing)
bool adxOK = (not useADXFilter or (not na(adx) and adx <= maximumADX))
float averageVolume = ta.sma(volume, volumeLength)
bool volumeOK = (not useVolumeFilter or (not na(averageVolume) and volume >= averageVolume * volumeFactor))
float rsi = ta.rsi(close, rsiLength)
bool longRSIOK = (not useRSIFilter or (not na(rsi) and rsi <= longRSIMax))
bool shortRSIOK = (not useRSIFilter or (not na(rsi) and rsi >= shortRSIMin))
// ============================================================================
// 18. 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 useH1EMABias or (validH1Chart and not na(h1EMA) and not na(h1Close) and h1Close > h1EMA))
bool shortH1OK = (not useH1EMABias or (validH1Chart and not na(h1EMA) and not na(h1Close) and h1Close < h1EMA))
// ============================================================================
// 19. FAKEOUT STATE
// ============================================================================
var bool pendingLong = false
var bool pendingShort = false
var int lowerBreakBar = na
var int upperBreakBar = na
var float lowerBreakPrice = na
var float upperBreakPrice = na
var int squeezeCount = 0
var int lowerBreakCount = 0
var int upperBreakCount = 0
var int expiredLongCount = 0
var int expiredShortCount = 0
var int lastProcessedBar = na
bool processState = (barstate.isconfirmed and (na(lastProcessedBar) or lastProcessedBar != bar_index))
// ============================================================================
// 20. PROCESS BREAKOUT STATE
// ============================================================================
if processState
lastProcessedBar := bar_index
if newTradingDay
pendingLong := false
pendingShort := false
lowerBreakBar := na
upperBreakBar := na
lowerBreakPrice := na
upperBreakPrice := na
if squeezeNow and not squeezeNow[1]
squeezeCount += 1
// Expire old lower breakout.
if pendingLong and not na(lowerBreakBar)
if bar_index - lowerBreakBar > fakeoutWindow
pendingLong := false
lowerBreakBar := na
lowerBreakPrice := na
expiredLongCount += 1
// Expire old upper breakout.
if pendingShort and not na(upperBreakBar)
if bar_index - upperBreakBar > fakeoutWindow
pendingShort := false
upperBreakBar := na
upperBreakPrice := na
expiredShortCount += 1
// Cancel excessive extension.
if useMaximumExtension and not na(atr)
if pendingLong and not na(lowerBreakPrice)
if close < lowerBreakPrice - maximumExtensionATR * atr
pendingLong := false
lowerBreakBar := na
lowerBreakPrice := na
if pendingShort and not na(upperBreakPrice)
if close > upperBreakPrice + maximumExtensionATR * atr
pendingShort := false
upperBreakBar := na
upperBreakPrice := na
// Register lower-band breakout.
if lowerBreakoutEvent and not pendingLong
pendingLong := true
lowerBreakBar := bar_index
lowerBreakPrice := close
pendingShort := false
upperBreakBar := na
upperBreakPrice := na
lowerBreakCount += 1
// Register upper-band breakout.
if upperBreakoutEvent and not pendingShort
pendingShort := true
upperBreakBar := bar_index
upperBreakPrice := close
pendingLong := false
lowerBreakBar := na
lowerBreakPrice := na
upperBreakCount += 1
// ============================================================================
// 21. VALID FAKEOUT WINDOWS
// ============================================================================
bool validLongWindow = (pendingLong and not na(lowerBreakBar) and bar_index > lowerBreakBar and bar_index - lowerBreakBar <= fakeoutWindow)
bool validShortWindow = (pendingShort and not na(upperBreakBar) and bar_index > upperBreakBar and bar_index - upperBreakBar <= fakeoutWindow)
// ============================================================================
// 22. RETURN INSIDE BOLLINGER
// ============================================================================
bool longReturnedInside = (validLongWindow and bandsReady and close >= bbLower and close <= bbUpper)
bool shortReturnedInside = (validShortWindow and bandsReady and close >= bbLower and close <= bbUpper)
// ============================================================================
// 23. PRICE CONFIRMATION
// ============================================================================
bool longCandleOK = (not requireCandleDirection or close > open)
bool shortCandleOK = (not requireCandleDirection or close < open)
bool longPreviousCloseOK = (not requirePreviousCloseBreak or close > close[1])
bool shortPreviousCloseOK = (not requirePreviousCloseBreak or close < close[1])
bool longBase = (longReturnedInside and longCandleOK and longPreviousCloseOK)
bool shortBase = (shortReturnedInside and shortCandleOK and shortPreviousCloseOK)
// ============================================================================
// 24. FINAL SIGNALS
// ============================================================================
bool rawLongSignal = (longBase and adxOK and volumeOK and longRSIOK and longH1OK)
bool rawShortSignal = (shortBase and adxOK and volumeOK and shortRSIOK and shortH1OK)
// ============================================================================
// 25. POSITION / COOLDOWN
// ============================================================================
bool flat = strategy.position_size == 0
bool inLong = strategy.position_size > 0
bool inShort = strategy.position_size < 0
var int lastExitBar = na
bool newClosedTrade = (strategy.closedtrades > nz(strategy.closedtrades[1], 0))
if newClosedTrade
lastExitBar := bar_index
bool cooldownOK = (na(lastExitBar) or bar_index - lastExitBar > cooldownBars)
// ============================================================================
// 26. ENTRY GATES
// ============================================================================
var int lastEntryBar = na
bool freshEntryBar = (na(lastEntryBar) or lastEntryBar != bar_index)
bool canTrade = (flat and strategy.opentrades == 0 and tradesToday < maximumTradesPerDay and cooldownOK and entrySessionOK and beforeForceClose and freshEntryBar and barstate.isconfirmed)
bool ambiguousSignal = (rawLongSignal and rawShortSignal)
bool enterLong = (canTrade and allowLong and rawLongSignal and not ambiguousSignal)
bool enterShort = (canTrade and allowShort and rawShortSignal and not ambiguousSignal)
// ============================================================================
// 27. DIAGNOSTIC COUNTERS
// ============================================================================
var int longBaseCount = 0
var int shortBaseCount = 0
var int filteredLongCount = 0
var int filteredShortCount = 0
var int longEntryCount = 0
var int shortEntryCount = 0
if processState
if longBase
longBaseCount += 1
if shortBase
shortBaseCount += 1
if rawLongSignal
filteredLongCount += 1
if rawShortSignal
filteredShortCount += 1
// ============================================================================
// 28. SL / TP 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="Failed Breakdown LONG", alert_message="🟢 VÀO VỊ THẾ LONG (CNPS78 Failed Breakdown/Breakout V3)\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
pendingLong := false
lowerBreakBar := na
lowerBreakPrice := na
// ============================================================================
// 30. SHORT ENTRY
// ============================================================================
if enterShort
strategy.entry("Short", strategy.short, comment="Failed Breakout SHORT", alert_message="🔴 VÀO VỊ THẾ SHORT (CNPS78 Failed Breakdown/Breakout V3)\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
pendingShort := false
upperBreakBar := na
upperBreakPrice := na
// ============================================================================
// 31. LONG EXIT
// ============================================================================
strategy.exit("Long Exit", from_entry="Long", profit=tpTicks, loss=slTicks, comment_profit="TP Long", comment_loss="SL Long", alert_profit="💰 CHỐT LỜI LONG (TP HIT)\n🎯 Giá chốt: " + str.tostring(strategy.position_avg_price + effectiveTP, format.mintick), alert_loss="🛑 CẮT LỖ LONG (SL HIT)\n🎯 Giá cắt: " + str.tostring(strategy.position_avg_price - effectiveSL, format.mintick), disable_alert=disableExitAlerts)
// ============================================================================
// 32. SHORT EXIT
// ============================================================================
strategy.exit("Short Exit", from_entry="Short", profit=tpTicks, loss=slTicks, comment_profit="TP Short", comment_loss="SL Short", alert_profit="💰 CHỐT LỜI SHORT (TP HIT)\n🎯 Giá chốt: " + str.tostring(strategy.position_avg_price - effectiveTP, format.mintick), alert_loss="🛑 CẮT LỖ SHORT (SL HIT)\n🎯 Giá cắt: " + str.tostring(strategy.position_avg_price + effectiveSL, format.mintick), disable_alert=disableExitAlerts)
// ============================================================================
// 33. OPTIONAL TIME EXIT
// ============================================================================
int barsHeld = (strategy.opentrades > 0 ? bar_index - strategy.opentrades.entry_bar_index(0) : 0)
bool timeExitSignal = (useTimeExit and strategy.position_size != 0 and barsHeld >= maximumHoldingBars and barstate.isconfirmed)
if timeExitSignal and not forceCloseBar
strategy.close_all(immediately=true, comment="Time Exit", alert_message="⏱️ ĐÓNG VỊ THẾ HẾT THỜI GIAN GIỮ (Time Exit)\n🎯 Giá đóng: " + str.tostring(close, format.mintick))
// ============================================================================
// 34. SESSION END
// ============================================================================
if forceCloseBar and strategy.position_size != 0
strategy.close_all(immediately=true, comment="Session End", alert_message="⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End)\n🎯 Giá đóng: " + str.tostring(close, format.mintick))
// ============================================================================
// 35. BOLLINGER PLOTS
// ============================================================================
plot(showBands ? bbUpper : na, title="Upper Bollinger", color=color.red, linewidth=2)
plot(showBands ? bbMiddle : na, title="Middle Bollinger", color=color.orange, linewidth=2)
plot(showBands ? bbLower : na, title="Lower Bollinger", color=color.green, linewidth=2)
// ============================================================================
// 36. SETUP MARKERS
// ============================================================================
plotshape(showSqueezeMarkers and squeezeNow and not squeezeNow[1], title="Squeeze", style=shape.circle, location=location.bottom, color=color.gray, size=size.tiny, text="SQ")
plotshape(showBreakoutMarkers and lowerBreakoutEvent, title="Lower Breakout", style=shape.circle, location=location.belowbar, color=color.aqua, size=size.tiny, text="BO")
plotshape(showBreakoutMarkers and upperBreakoutEvent, title="Upper Breakout", style=shape.circle, location=location.abovebar, color=color.orange, size=size.tiny, text="BO")
// ============================================================================
// 37. ENTRY MARKERS
// ============================================================================
plotshape(showFakeoutMarkers and enterLong, title="Fakeout LONG", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, text="LONG", textcolor=color.white)
plotshape(showFakeoutMarkers and enterShort, title="Fakeout SHORT", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small, text="SHORT", textcolor=color.white)
// ============================================================================
// 38. 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)
// ============================================================================
// 39. DATA WINDOW
// ============================================================================
plot(bbWidthPercent, title="BB Width %", color=color.gray, display=display.data_window)
plot(averageWidth, title="Average BB Width", color=color.orange, display=display.data_window)
plot(squeezeRecentCount, title="Recent Squeeze Count", color=color.blue, display=display.data_window)
plot(adx, title="ADX", color=color.purple, display=display.data_window)
// ============================================================================
// 40. DIAGNOSTICS
// ============================================================================
var table diagnostics = table.new(position.top_right, 2, 19, border_width=1)
if showDiagnostics and barstate.islast
string positionText = (inLong ? "LONG" : inShort ? "SHORT" : "FLAT")
table.cell(diagnostics, 0, 0, "CNPS78 V3")
table.cell(diagnostics, 1, 0, timeframe.period)
table.cell(diagnostics, 0, 1, "BB Width %")
table.cell(diagnostics, 1, 1, str.tostring(bbWidthPercent, "#.###"))
table.cell(diagnostics, 0, 2, "Avg Width")
table.cell(diagnostics, 1, 2, str.tostring(averageWidth, "#.###"))
table.cell(diagnostics, 0, 3, "Squeeze Now")
table.cell(diagnostics, 1, 3, squeezeNow ? "YES" : "NO")
table.cell(diagnostics, 0, 4, "Squeeze Events")
table.cell(diagnostics, 1, 4, str.tostring(squeezeCount))
table.cell(diagnostics, 0, 5, "Lower Breakouts")
table.cell(diagnostics, 1, 5, str.tostring(lowerBreakCount))
table.cell(diagnostics, 0, 6, "Upper Breakouts")
table.cell(diagnostics, 1, 6, str.tostring(upperBreakCount))
table.cell(diagnostics, 0, 7, "Long Bases")
table.cell(diagnostics, 1, 7, str.tostring(longBaseCount))
table.cell(diagnostics, 0, 8, "Short Bases")
table.cell(diagnostics, 1, 8, str.tostring(shortBaseCount))
table.cell(diagnostics, 0, 9, "Filtered Long")
table.cell(diagnostics, 1, 9, str.tostring(filteredLongCount))
table.cell(diagnostics, 0, 10, "Filtered Short")
table.cell(diagnostics, 1, 10, str.tostring(filteredShortCount))
table.cell(diagnostics, 0, 11, "Pending Long")
table.cell(diagnostics, 1, 11, pendingLong ? "YES" : "NO")
table.cell(diagnostics, 0, 12, "Pending Short")
table.cell(diagnostics, 1, 12, pendingShort ? "YES" : "NO")
table.cell(diagnostics, 0, 13, "Expired Long")
table.cell(diagnostics, 1, 13, str.tostring(expiredLongCount))
table.cell(diagnostics, 0, 14, "Expired Short")
table.cell(diagnostics, 1, 14, str.tostring(expiredShortCount))
table.cell(diagnostics, 0, 15, "ADX OK")
table.cell(diagnostics, 1, 15, adxOK ? "YES" : "NO")
table.cell(diagnostics, 0, 16, "Long Entries")
table.cell(diagnostics, 1, 16, str.tostring(longEntryCount))
table.cell(diagnostics, 0, 17, "Short Entries")
table.cell(diagnostics, 1, 17, str.tostring(shortEntryCount))
table.cell(diagnostics, 0, 18, "Trades Today")
table.cell(diagnostics, 1, 18, str.tostring(tradesToday) + "/" + str.tostring(maximumTradesPerDay))
2. Những khái niệm kỹ thuật cốt lõi trong CNPS78
2.1. Bollinger Bandwidth & Cơ chế nhận diện vùng nén (Squeeze)
Bot sử dụng dải Bollinger Bands chuẩn gồm bbMiddle = ta.sma(bbSource, bbLength) và bbDeviation = bbMultiplier * ta.stdev(bbSource, bbLength) để tạo thành bbUpper và bbLower.
Để đánh giá độ hẹp của dải theo tỷ lệ phần trăm, code tính:
bbWidthPercent = 100.0 * (bbUpper - bbLower) / math.abs(bbMiddle)(khibandsReadyvàbbMiddle != 0).averageWidth = ta.sma(bbWidthPercent, squeezeLookback)(trung bình100nến).- Trạng thái nén tại nến hiện tại
squeezeNowđược xác định khibbWidthPercent <= averageWidth * squeezeFactor(mặc định0.85).
Điểm quan trọng trong CNPS78 V3 là biến squeezeRecently: bot dùng math.sum(squeezeNow[1] ? 1.0 : 0.0, recentSqueezeBars) để chỉ đếm các nến trước đó (squeezeNow[1]) trong cửa sổ recentSqueezeBars (10 nến). Điều này đảm bảo vùng nén phải tồn tại trước khi nến phá vỡ xuất hiện.
2.2. Máy trạng thái Fakeout (Fakeout State Machine) và Bộ lọc ATR
Sau khi có squeezeRecently, bot theo dõi sự kiện phá vỡ biên:
aboveUpper = close > bbUppervàbelowLower = close < bbLower. NếurequireFreshBreakout = true, chỉ nhận nến mới vượt biên (aboveUpper and not aboveUpper[1]hoặcbelowLower and not belowLower[1]).- Nếu bật
useMinimumBreakDistance, khoảng cách vượt dải (close - bbUpperhoặcbbLower - close) phải lớn hơn hoặc bằngminimumBreakATR * atr(atr = ta.atr(14)).
Khi lowerBreakoutEvent hoặc upperBreakoutEvent xảy ra, hệ thống cập nhật biến trạng thái tại nến đã đóng (processState):
- Bật
pendingLong = true(hoặcpendingShort = true), ghi nhậnlowerBreakBar = bar_indexvàlowerBreakPrice = close(đồng thời xóa trạng thái chờ ngược chiều). - Trạng thái chờ sẽ tự động hết hạn nếu số nến trôi qua vượt quá
fakeoutWindow(bar_index - lowerBreakBar > fakeoutWindow), hoặc bị hủy nếu bậtuseMaximumExtensionvà giá đi quá xa điểm phá vỡ hơnmaximumExtensionATR * atr.
2.3. Hệ thống bộ lọc xác nhận tùy chọn (ADX, Volume, RSI, H1 EMA)
Để giảm nhiễu trong những pha thị trường có xu hướng quá mạnh hoặc thiếu thanh khoản, CNPS78 trang bị 4 bộ lọc độc lập (mặc định đang tắt false để dễ tùy biến):
- ADX Filter (
useADXFilter): Tính[diPlus, diMinus, adx] = ta.dmi(diLength, adxSmoothing)và yêu cầuadx <= maximumADX(35.0), giúp tránh bắt đảo chiều khi xu hướng đang chạy quá mạnh. - Volume Filter (
useVolumeFilter): Yêu cầu khối lượng nến xác nhậnvolume >= ta.sma(volume, volumeLength) * volumeFactor(1.20lần trung bình20nến). - RSI Filter (
useRSIFilter): Tínhrsi = ta.rsi(close, rsiLength)(14), yêu cầursi <= longRSIMax(55.0) cho lệnh Long vàrsi >= shortRSIMin(45.0) cho lệnh Short. - Confirmed H1 EMA Bias (
useH1EMABias): Lấy giá đóng cửa và EMA(50) của nến H1 đã hoàn tất ([1]kết hợplookahead=barmerge.lookahead_on). Bộ lọc này chỉ hợp lệ trên biểu đồ intraday dưới 1 giờ (timeframe.in_seconds() < 3600), yêu cầuh1Close > h1EMAcho Long vàh1Close < h1EMAcho Short.
3. Nguyên lý hoạt động của CNPS78
Trên mỗi nến đã đóng hoàn chỉnh (barstate.isconfirmed và processState), CNPS78 thực hiện tuần tự 5 bước:
- Khởi tạo ngày giao dịch mới (
newTradingDay): Khi sang ngày mới theo múi giờAsia/Ho_Chi_Minh, bot đặt lạitradesToday := 0và xóa sạch các trạng tháipendingLong,pendingShort, tọa độ breakout cũ. - Cập nhật Bollinger & Trạng thái Breakout: Tính
bbUpper,bbLower,squeezeRecently, kiểm tra hết hạnfakeoutWindow, kiểm trauseMaximumExtensionvà ghi nhận nếu cólowerBreakoutEventhoặcupperBreakoutEventmới. - Kiểm tra giá quay đầu vào trong dải (
Return Inside Bollinger): Trong cửa sổ hợp lệ (bar_index > breakBarvà<= fakeoutWindow), nếu giá đóng cửa quay lại nằm gọn trong[bbLower, bbUpper]kèm xác nhận nến (longCandleOK/shortCandleOK,longPreviousCloseOK/shortPreviousCloseOK), bot ghi nhận tín hiệu nềnlongBase/shortBase. - Đánh giá bộ lọc & Cổng vào lệnh: Kết hợp
longBase/shortBasevới 4 bộ lọc tùy chọn thànhrawLongSignal/rawShortSignal. Nếu cổngcanTrademở và không xảy ra tín hiệu mơ hồ (not ambiguousSignal), bot gửi lệnhstrategy.entry(đồng thời xóa trạng thái pending). - Quản trị & Thoát lệnh: Sau khi khớp lệnh,
strategy.exittự động đặt SL/TP theo tick; nếu bậtuseTimeExithoặc đến giờ đóng phiênforceCloseBar, bot sẽ gọistrategy.close_all(immediately=true).
4. Điều kiện vào lệnh Long và Short của CNPS78
4.1. Điều kiện vào lệnh Long
Lệnh Long (enterLong) được kích hoạt khi thỏa mãn đồng thời các điều kiện sau:
- Cổng giao dịch & Chiều đánh:
canTrade == truevàallowLong == true(tradeDirectionlà"Long"hoặc"Both"). - Trạng thái chờ hợp lệ (
validLongWindow): Đang cópendingLong == truetừ một cú phá vỡ xuống dướibbLowersau vùng nén (squeezeRecently), và nến hiện tại nằm trong khoảng1đếnfakeoutWindownến saulowerBreakBar. - Giá quay lại vào trong dải (
longReturnedInside): Dải Bollinger đã sẵn sàng (bandsReady) vàbbLower <= close <= bbUpper. - Xác nhận hành động giá (
longBase):- Nếu
requireCandleDirection = true: nến hiện tại là nến tăng (close > open). - Nếu
requirePreviousCloseBreak = true: giá đóng cửa cao hơn nến trước (close > close[1]).
- Nếu
- Bộ lọc tùy chọn (
rawLongSignal): Thỏa mãnadxOK,volumeOK,longRSIOKvàlongH1OK. - Không xung đột chiều (
not ambiguousSignal): Không đồng thời xuất hiệnrawShortSignaltrên cùng một nến.
4.2. Điều kiện vào lệnh Short
Lệnh Short (enterShort) được kích hoạt khi thỏa mãn đồng thời các điều kiện sau:
- Cổng giao dịch & Chiều đánh:
canTrade == truevàallowShort == true(tradeDirectionlà"Short"hoặc"Both"). - Trạng thái chờ hợp lệ (
validShortWindow): Đang cópendingShort == truetừ một cú phá vỡ lên trênbbUppersau vùng nén (squeezeRecently), và nến hiện tại nằm trong khoảng1đếnfakeoutWindownến sauupperBreakBar. - Giá quay lại vào trong dải (
shortReturnedInside):bandsReady == truevàbbLower <= close <= bbUpper. - Xác nhận hành động giá (
shortBase):- Nếu
requireCandleDirection = true: nến hiện tại là nến giảm (close < open). - Nếu
requirePreviousCloseBreak = true: giá đóng cửa thấp hơn nến trước (close < close[1]).
- Nếu
- Bộ lọc tùy chọn (
rawShortSignal): Thỏa mãnadxOK,volumeOK,shortRSIOKvàshortH1OK. - Không xung đột chiều (
not ambiguousSignal): Không đồng thời xuất hiệnrawLongSignaltrên cùng một nến.
4.3. Điều kiện kiểm soát giao dịch chung
Biến canTrade đóng vai trò chốt chặn an toàn trước khi gửi bất kỳ lệnh nào:
- Không có vị thế mở:
strategy.position_size == 0(flat) vàstrategy.opentrades == 0(bot cấu hìnhpyramiding = 0). - Giới hạn số lệnh/ngày:
tradesToday < maximumTradesPerDay(mặc định tối đa2lệnh/ngày). - Thời gian nghỉ sau thoát lệnh (
cooldownOK): Khi có lệnh đóng mới,lastExitBarđược cập nhật; lệnh mới chỉ được phép mở khibar_index - lastExitBar > cooldownBars(mặc định3nến). - Kiểm soát phiên (
entrySessionOK&beforeForceClose): Nếu bậtuseSessionFilter, nến phải nằm trong khung[09:00, 14:30](barOpenMinutes >= entryStartMinutesvàbarCloseMinutes <= lastEntryMinutes). Ngoài ra, luôn bắt buộcbarCloseMinutes < forceCloseMinutes(14:45). - Chống trùng lặp nến:
freshEntryBar(lastEntryBar != bar_index) vàbarstate.isconfirmed == true.
5. Quản trị Stop Loss, Take Profit và Thoát lệnh
5.1. Cơ chế Stop Loss và Take Profit cố định theo điểm
CNPS78 sử dụng cơ chế SL/TP cố định theo số điểm, được quy đổi chính xác sang đơn vị tick của hợp đồng VN30F1M (syminfo.mintick):
slTicks = math.max(1, int(math.round(stopLossPoints / syminfo.mintick)))(mặc địnhstopLossPoints = 5.0).tpTicks = math.max(1, int(math.round(takeProfitPoints / syminfo.mintick)))(mặc địnhtakeProfitPoints = 15.0).effectiveSL = slTicks * syminfo.mintickvàeffectiveTP = tpTicks * syminfo.mintick.
Lệnh thoát strategy.exit("Long Exit", ...) và strategy.exit("Short Exit", ...) được đặt trực tiếp theo profit=tpTicks và loss=slTicks, tính từ giá khớp thực tế strategy.position_avg_price (và vẽ đường SL/TP lên biểu đồ khi showSLTP = true).
5.2. Cơ chế Time Exit và Đóng vị thế cuối phiên (Session End)
Mã nguồn của CNPS78 không sử dụng Break Even hay Trailing Stop, mà bảo vệ vị thế bằng hai cơ chế đóng lệnh chủ động:
- Time Exit (
useTimeExit): Mặc định tắt (false). Khi bật, bot đếm số nến đã giữ lệnhbarsHeld = bar_index - strategy.opentrades.entry_bar_index(0). NếubarsHeld >= maximumHoldingBars(20nến) tại thời điểm nến đóng (barstate.isconfirmed) và chưa đến nến đóng phiên (not forceCloseBar), bot gọistrategy.close_all(immediately=true, comment="Time Exit"). - Session End (
forceCloseBar): Luôn hoạt động. Tại cây nến cóbarOpenMinutes < forceCloseMinutesvàbarCloseMinutes >= forceCloseMinutes(mặc định14:45giờ Việt Nam), nếu đang còn vị thế mở (strategy.position_size != 0), bot lập tức đóng toàn bộ bằngstrategy.close_all(immediately=true, comment="Session End")để không giữ vị thế qua đêm (tránh rủi ro gap ATC/ATO).
5.3. Bảng tổng hợp cơ chế bảo vệ vị thế
| Cơ chế thoát lệnh | Điều kiện kích hoạt | Thông số mặc định | Ghi chú thực tế trong code |
|---|---|---|---|
| Take Profit (TP) | Giá đạt strategy.position_avg_price ± effectiveTP | takeProfitPoints = 15.0 | Đặt qua strategy.exit bằng tpTicks |
| Stop Loss (SL) | Giá chạm strategy.position_avg_price ∓ effectiveSL | stopLossPoints = 5.0 | Đặt qua strategy.exit bằng slTicks |
| Time Exit | useTimeExit = true và barsHeld >= maximumHoldingBars | useTimeExit = false, 20 nến | Đóng tại nến xác nhận (not forceCloseBar) |
| Session End | Nến chạm mốc forceCloseMinutes và còn vị thế mở | endHour = 14, endMinute = 45 | strategy.close_all(immediately=true) |
6. Hướng dẫn cài đặt và đọc bảng Diagnostics trên TradingView
Các bước cài đặt
- Mở biểu đồ VN30F1M trên TradingView (khuyến nghị khung thời gian intraday như M5 hoặc M15; nếu bật
useH1EMABiasbắt buộc dùng khung nhỏ hơn H1). - Nhấn vào tab Pine Editor ở thanh công cụ phía dưới, xóa code mẫu 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.
- Nhấn Save để lưu script, sau đó nhấn Add to chart để gắn bot lên biểu đồ.
- Mở phần Settings (Cài đặt) của chiến lược để điều chỉnh
Trade Direction(Long,ShorthoặcBoth),Contracts, mứcStop Loss / Take Profitvà bật các bộ lọc tùy chọn nếu cần.
Cách đọc bảng chẩn đoán (Diagnostics Table)
Khi bật tùy chọn Show Diagnostics (showDiagnostics = true) trong nhóm 10. Display, bot sẽ vẽ một bảng gồm 2 cột, 19 dòng ở góc trên bên phải (position.top_right) tại nến cuối cùng (barstate.islast):
| Dòng | Nhãn hiển thị | Ý nghĩa thực tế |
|---|---|---|
| 0 | CNPS78 V3 / timeframe.period | Tên phiên bản bot và khung thời gian biểu đồ đang chạy |
| 1 | BB Width % | Độ rộng dải Bollinger hiện tại (%) |
| 2 | Avg Width | Trung bình độ rộng dải trong squeezeLookback nến |
| 3 | Squeeze Now | Trạng thái nén tại nến hiện tại (YES / NO) |
| 4 | Squeeze Events | Tổng số lần bắt đầu chu kỳ nén (squeezeCount) |
| 5–6 | Lower Breakouts / Upper Breakouts | Tổng số sự kiện phá vỡ biên dưới / biên trên sau vùng nén |
| 7–8 | Long Bases / Short Bases | Số tín hiệu nền quay lại trong dải + đạt xác nhận nến |
| 9–10 | Filtered Long / Filtered Short | Số tín hiệu vượt qua toàn bộ bộ lọc tùy chọn (rawLongSignal / rawShortSignal) |
| 11–12 | Pending Long / Pending Short | Trạng thái đang chờ giá quay đầu vào trong dải (YES / NO) |
| 13–14 | Expired Long / Expired Short | Số kèo chờ bị hủy do quá hạn fakeoutWindow |
| 15 | ADX OK | Trạng thái bộ lọc ADX hiện tại (YES / NO) |
| 16–17 | Long Entries / Short Entries | Tổng số lệnh Long / Short đã khớp từ đầu lịch sử backtest |
| 18 | Trades Today | Số lệnh đã vào trong ngày / Giới hạn maximumTradesPerDay |
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 TradingView App, Email hoặc Webhook kết nối bot thực thi lệnh, bạn thực hiện theo các bước sau:
- Nhấn vào biểu tượng Alert (Đồng hồ báo thức) trên thanh công cụ TradingView (hoặc phím tắt
Alt + A). - Ở mục Condition, chọn đúng chiến lược
CNPS78 BOLLINGER SQUEEZE FAKEOUT V3. - Ở ô Message, xóa toàn bộ nội dung mặc định và thay bằng cú pháp duy nhất:
{{strategy.order.alert_message}}. - Kiểm tra thông số
Disable SL/TP Alerts(disableExitAlerts): giữfalsenếu muốn nhận cả thông báo chốt lời/cắt lỗ từstrategy.exit.
Bảng thông điệp Alert của CNPS78
| Sự kiện | Lệnh trong code | Nội dung thông điệp (alert_message / alert_profit / alert_loss) |
|---|---|---|
| Vào lệnh Long | strategy.entry("Long", ...) | 🟢 VÀO VỊ THẾ LONG (CNPS78 Failed Breakdown/Breakout V3) + Giá vào, SL, TP |
| Vào lệnh Short | strategy.entry("Short", ...) | 🔴 VÀO VỊ THẾ SHORT (CNPS78 Failed Breakdown/Breakout V3) + Giá vào, SL, TP |
| Chốt lời Long | strategy.exit("Long Exit", ...) (alert_profit) | 💰 CHỐT LỜI LONG (TP HIT) + Giá chốt (position_avg_price + effectiveTP) |
| Cắt lỗ Long | strategy.exit("Long Exit", ...) (alert_loss) | 🛑 CẮT LỖ LONG (SL HIT) + Giá cắt (position_avg_price - effectiveSL) |
| Chốt lời Short | strategy.exit("Short Exit", ...) (alert_profit) | 💰 CHỐT LỜI SHORT (TP HIT) + Giá chốt (position_avg_price - effectiveTP) |
| Cắt lỗ Short | strategy.exit("Short Exit", ...) (alert_loss) | 🛑 CẮT LỖ SHORT (SL HIT) + Giá cắt (position_avg_price + effectiveSL) |
| Hết thời gian giữ | strategy.close_all(..., comment="Time Exit") | ⏱️ ĐÓNG VỊ THẾ HẾT THỜI GIAN GIỮ (Time Exit) + Giá đóng (close) |
| Đóng hết phiên | strategy.close_all(..., comment="Session End") | ⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End) + Giá đóng (close) |
Kết luận
CNPS78 Bollinger Squeeze Fakeout V3 là một hệ thống giao dịch phái sinh VN30F1M có cấu trúc logic rõ ràng, chuyên biệt cho kịch bản thị trường tích lũy biên độ hẹp và xuất hiện các nhịp phá vỡ giả trước khi quay đầu. Nhờ sự kết hợp giữa máy trạng thái Fakeout có giới hạn thời gian, bộ lọc đa lớp tùy chọn (ADX, Volume, RSI, H1 EMA) cùng cơ chế quản trị SL/TP theo tick và đóng vị thế cuối phiên, bot giúp kiểm soát rủi ro kỷ luật và hạn chế tối đa việc giữ lệnh qua đêm.
Bạn có thể tham khảo thêm các chiến lược giao dịch VN30F1M khác trong cùng hệ sinh thái như Bot CNPS50 - Trend Analysis V2 và Bot CNPS49 - Daily Open.
Thông tin chỉ mang tính tham khảo, không phải khuyến nghị đầu tư. Kết quả kiểm thử quá khứ không đảm bảo lợi nhuận trong tương lai.
Thông tin trong bài chỉ mang tính tham khảo, không phải khuyến nghị mua bán. Giao dịch phái sinh có rủi ro cao do sử dụng đòn bẩy; nhà đầu tư tự chịu trách nhiệm với quyết định của mình.





