Hướng Dẫn Sử Dụng Bot CNPS68 - Supertrend Flip cho VN30F1M
TradingviewBot CNPS68 bắt điểm đảo chiều Supertrend (Flip) trên VN30F1M, kết hợp bộ lọc nến, ATR, Volume, H1 EMA và quản trị SL/TP cố định cùng đóng lệnh cuối phiên.

Mục lục
Trong giao dịch phái sinh VN30F1M, việc bắt đúng thời điểm xu hướng đảo chiều (Trend Reversal) mà không bị nhiễu bởi các nhịp rung lắc ngắn hạn là thách thức lớn đối với nhà giao dịch. Nếu vào lệnh quá sớm khi xu hướng chưa xác nhận, tài khoản dễ bị quét dừng lỗ liên tục; ngược lại, nếu vào quá muộn thì tỷ lệ Risk:Reward không còn hấp dẫn.
CNPS68 — với tên đầy đủ trong mã nguồn là CNPS68 SUPERTREND-FLIP (shorttitle="CNPS68 SUPERTREND") — được viết bằng Pine Script v6 trên TradingView nhằm giải quyết bài toán trên thông qua cơ chế phát hiện điểm đảo chiều Supertrend Flip kết hợp hệ thống bộ lọc đa lớp tùy chọn và quản trị rủi ro chặt chẽ trong phiên.
Các điểm nổi bật cốt lõi của Bot CNPS68:
- Bắt điểm đảo chiều Supertrend Flip chuẩn xác: Chỉ kích hoạt tín hiệu khi chỉ báo Supertrend đổi chiều (
crossunderhoặccrossoverqua ngưỡng 0) hoặc duy trì xu hướng theo cấu hình. - Hệ thống bộ lọc 4 lớp tùy chọn: Cho phép kết hợp lọc hướng/thân nến (
Candle Direction&Minimum Body), mở rộng biến động (ATR Expansion), đột biến khối lượng (Volume Spike) và xu hướng khung lớn (Confirmed H1 EMA Bias). - Quản trị rủi ro rõ ràng: Thiết lập sẵn Stop Loss (
5.0điểm) và Take Profit (15.0điểm) theo tỷ lệ 1:3 mặc định, giới hạn tối đa2lệnh/ngày và tự động đóng toàn bộ vị thế cuối phiên lúc14:45. - Chống tín hiệu mơ hồ & bảng Diagnostics trực quan: Tích hợp cơ chế loại trừ khi tín hiệu Long/Short xuất hiện đồng thời và bảng thống kê 16 dòng theo thời gian thực ngay trên biểu đồ.
1. CNPS68 Supertrend Flip là gì?
CNPS68 Supertrend Flip là một chiến lược giao dịch theo xu hướng đảo chiều (TREND REVERSAL -> FLIP -> ENTRY), vận hành dựa trên 4 trụ cột kỹ thuật chính:
- Động cơ Supertrend & Phát hiện Flip: Sử dụng
ta.supertrend(supertrendFactor, supertrendATRLength)để xác định trạng thái xu hướng (UPTRENDkhidirection < 0,DOWNTRENDkhidirection > 0) và bắt chính xác thời điểm chuyển trạng thái (bullishFlip/bearishFlip). - Bộ lọc xác nhận chất lượng tín hiệu: Cho phép bật/tắt linh hoạt các điều kiện lọc gồm màu nến, kích thước thân nến tối thiểu theo ATR, độ mở rộng ATR so với trung bình, đột biến Volume và xu hướng H1 EMA đã đóng nến.
- Kiểm soát phiên & Tần suất giao dịch: Giới hạn số lệnh tối đa trong ngày (
tradesToday < maximumTradesPerDay), tùy chọn hướng giao dịch (Long,Short,Both), lọc khung giờ vào lệnh (09:00–14:30) và ép đóng vị thế cuối phiên (14:45) theo múi giờAsia/Ho_Chi_Minh. - Quản trị rủi ro & Cảnh báo tự động: Tính toán SL/TP cố định theo điểm từ giá khớp lệnh trung bình (
strategy.position_avg_price), vẽ đường SL/TP trực tiếp trên biểu đồ và gửi thông điệp Alert chi tiết qua webhook/TradingView.
Bảng thông số mặc định
| Nhóm thông số | Tên tham số trong code | Giá trị mặc định | Mô tả |
|---|---|---|---|
| Supertrend | supertrendATRLength | 10 | Chu kỳ ATR tính Supertrend |
supertrendFactor | 3.0 | Hệ số nhân ATR của Supertrend | |
requireFreshFlip | true | Yêu cầu tín hiệu Flip mới xảy ra | |
| Flip Confirmation | requireCandleDirection | false | Yêu cầu nến tín hiệu cùng chiều (xanh/đỏ) |
requireMinimumBody | false | Yêu cầu thân nến tối thiểu theo ATR | |
minimumBodyATR | 0.20 | Tỷ lệ thân nến tối thiểu / ATR | |
| ATR Filter | atrLength | 14 | Chu kỳ tính ATR |
requireATRExpansion | false | Bật bộ lọc mở rộng biến động ATR | |
atrAverageLength | 20 | Chu kỳ SMA của ATR | |
atrExpansionFactor | 1.0 | Hệ số ATR tối thiểu / ATR trung bình | |
| Volume | requireVolumeSpike | false | Bật bộ lọc đột biến khối lượng |
volumeAverageLength | 20 | Chu kỳ SMA của Volume | |
volumeSpikeFactor | 1.20 | Hệ số Volume tối thiểu / Volume trung bình | |
| H1 Trend | useH1EMABias | false | Bật bộ lọc xu hướng theo H1 EMA |
h1EMALength | 50 | Chu kỳ EMA trên khung H1 (60 phút) | |
| Risk Management | stopLossPoints | 5.0 | Cắt lỗ cố định (điểm) |
takeProfitPoints | 15.0 | Chốt lời cố định (điểm) | |
| Trade Control | maximumTradesPerDay | 2 | Số lệnh tối đa mỗi ngày |
tradeDirection | "Long" | Hướng giao dịch (Long, Short, Both) | |
| Session | useSessionFilter | false | Bật bộ lọc khung giờ vào lệnh |
strategyTimezone | "Asia/Ho_Chi_Minh" | Múi giờ tính phiên giao dịch | |
sessionStartHour / Minute | 09:00 | Giờ bắt đầu phiên | |
lastEntryHour / Minute | 14:30 | Giờ giới hạn vào lệnh cuối | |
sessionEndHour / Minute | 14:45 | Giờ cưỡng bức đóng toàn bộ vị thế | |
| Alerts & Display | disableSLTPAlerts | false | Tắt cảnh báo SL / TP |
showSupertrend / showActiveSLTP | true | Hiển thị Supertrend và đường SL/TP | |
showH1EMA / showSignalMarkers / showDiagnostics | false | Hiển thị H1 EMA, mũi tên setup, bảng chẩn đoán |
Source Code CNPS68 Supertrend Flip
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="CNPS68 SUPERTREND-FLIP", shorttitle="CNPS68 SUPERTREND", 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=true, max_labels_count=300, max_lines_count=300, max_bars_back=5000)
// ╔══════════════════════════════════════════════════════════════════════╗
// ║ CNPS68 SUPERTREND FLIP ║
// ║ TREND REVERSAL -> FLIP -> ENTRY ║
// ╠══════════════════════════════════════════════════════════════════════╣
// ║ TIMEFRAME : CURRENT CHART TIMEFRAME ║
// ║ POSITION : 3 CONTRACTS ║
// ║ COMMISSION : VND 10,000 / CONTRACT ║
// ║ SLIPPAGE : 3 TICKS ║
// ║ ║
// ║ LONG ║
// ║ Supertrend changes from DOWN to UP ║
// ║ -> Confirmed bullish flip ║
// ║ -> Optional ATR / Volume / H1 / Candle filters ║
// ║ -> LONG ║
// ║ ║
// ║ SHORT ║
// ║ Supertrend changes from UP to DOWN ║
// ║ -> Confirmed bearish flip ║
// ║ -> Optional ATR / Volume / H1 / Candle filters ║
// ║ -> SHORT ║
// ║ ║
// ║ DEFAULT EXIT ║
// ║ SL = 5 POINTS ║
// ║ TP = 15 POINTS ║
// ╚══════════════════════════════════════════════════════════════════════╝
// ============================================================================
// SECTION 1: SUPERTREND SETTINGS
// ============================================================================
supertrendATRLength = input.int(10, title="Supertrend ATR Period", minval=1, maxval=500, group="Supertrend")
supertrendFactor = input.float(3.0, title="Supertrend Factor", minval=0.1, step=0.1, group="Supertrend")
requireFreshFlip = input.bool(true, title="Require Fresh Supertrend Flip?", group="Supertrend")
// ============================================================================
// SECTION 2: FLIP CONFIRMATION
// ============================================================================
requireCandleDirection = input.bool(false, title="Require Bullish / Bearish Candle?", group="Flip Confirmation")
requireMinimumBody = input.bool(false, title="Require Minimum Candle Body?", group="Flip Confirmation")
minimumBodyATR = input.float(0.20, title="Minimum Candle Body / ATR", minval=0.0, step=0.05, group="Flip Confirmation")
// ============================================================================
// SECTION 3: ATR FILTER
// ============================================================================
atrLength = input.int(14, title="ATR Length", minval=1, group="ATR Filter")
requireATRExpansion = input.bool(false, title="Require ATR Expansion?", group="ATR Filter")
atrAverageLength = input.int(20, title="ATR Average Length", minval=2, group="ATR Filter")
atrExpansionFactor = input.float(1.0, title="Minimum ATR / Average ATR", minval=0.1, step=0.05, group="ATR Filter")
// ============================================================================
// SECTION 4: VOLUME FILTER
// ============================================================================
requireVolumeSpike = input.bool(false, title="Require Volume Spike?", group="Volume")
volumeAverageLength = input.int(20, title="Volume Average Length", minval=2, group="Volume")
volumeSpikeFactor = input.float(1.20, title="Volume Spike Factor", minval=0.1, step=0.1, group="Volume")
// ============================================================================
// SECTION 5: H1 TREND FILTER
// ============================================================================
useH1EMABias = input.bool(false, title="Use Confirmed H1 EMA Bias?", group="H1 Trend")
h1EMALength = input.int(50, title="H1 EMA Length", minval=1, group="H1 Trend")
// ============================================================================
// SECTION 6: RISK MANAGEMENT
// ============================================================================
stopLossPoints = input.float(5.0, title="Stop Loss (Points)", minval=0.1, step=0.5, group="Risk Management")
takeProfitPoints = input.float(15.0, title="Take Profit (Points)", minval=0.1, step=0.5, group="Risk Management")
// ============================================================================
// SECTION 7: TRADE CONTROL
// ============================================================================
maximumTradesPerDay = input.int(2, title="Maximum Trades Per Day", minval=1, maxval=20, group="Trade Control")
tradeDirection = input.string("Long", title="Trade Direction", options=["Long", "Short", "Both"], group="Trade Control")
bool allowLong = (tradeDirection == "Long" or tradeDirection == "Both")
bool allowShort = (tradeDirection == "Short" or tradeDirection == "Both")
// ============================================================================
// SECTION 8: SESSION
// ============================================================================
useSessionFilter = input.bool(false, title="Use Entry Session Filter?", group="Session")
strategyTimezone = input.string("Asia/Ho_Chi_Minh", title="Strategy Timezone", group="Session")
sessionStartHour = input.int(9, title="Session Start Hour", minval=0, maxval=23, group="Session")
sessionStartMinute = input.int(0, title="Session Start Minute", minval=0, maxval=59, group="Session")
lastEntryHour = input.int(14, title="Last Entry Hour", minval=0, maxval=23, group="Session")
lastEntryMinute = input.int(30, title="Last Entry Minute", minval=0, maxval=59, group="Session")
sessionEndHour = input.int(14, title="Force Close Hour", minval=0, maxval=23, group="Session")
sessionEndMinute = input.int(45, title="Force Close Minute", minval=0, maxval=59, group="Session")
// ============================================================================
// SECTION 9: ALERT CONTROL
// ============================================================================
disableSLTPAlerts = input.bool(false, title="Disable SL / TP Alerts?", group="Alerts")
// ============================================================================
// SECTION 10: DISPLAY
// ============================================================================
showSupertrend = input.bool(true, title="Show Supertrend?", group="Display")
showH1EMA = input.bool(false, title="Show H1 EMA?", group="Display")
showSignalMarkers = input.bool(false, title="Show Setup Markers?", group="Display")
showActiveSLTP = input.bool(true, title="Show Active SL / TP?", group="Display")
showDiagnostics = input.bool(false, title="Show Diagnostics?", group="Display")
// ============================================================================
// SECTION 11: TIME ENGINE
// ============================================================================
int currentMinute = (hour(time, strategyTimezone) * 60 + minute(time, strategyTimezone))
int currentCloseMinute = (hour(time_close, strategyTimezone) * 60 + minute(time_close, strategyTimezone))
int sessionStartTotal = (sessionStartHour * 60 + sessionStartMinute)
int lastEntryTotal = (lastEntryHour * 60 + lastEntryMinute)
int sessionEndTotal = (sessionEndHour * 60 + sessionEndMinute)
bool entrySession = (currentMinute >= sessionStartTotal and currentMinute <= lastEntryTotal)
bool sessionOK = (not useSessionFilter or entrySession)
// ============================================================================
// SECTION 12: TRADING DAY
// ============================================================================
int tradingDayKey = (year(time, strategyTimezone) * 10000 + month(time, strategyTimezone) * 100 + dayofmonth(time, strategyTimezone))
bool newTradingDay = (bar_index == 0 or tradingDayKey != tradingDayKey[1])
var int tradesToday = 0
if newTradingDay
tradesToday := 0
// ============================================================================
// SECTION 13: SUPERTREND ENGINE
// ============================================================================
//
// TradingView ta.supertrend direction:
//
// direction < 0 = UPTREND
// direction > 0 = DOWNTREND
//
// ============================================================================
[supertrendValue, supertrendDirection] = ta.supertrend(supertrendFactor, supertrendATRLength)
bool supertrendBullish = (supertrendDirection < 0)
bool supertrendBearish = (supertrendDirection > 0)
// ============================================================================
// SECTION 14: SUPERTREND FLIP DETECTION
// ============================================================================
//
// LONG:
// Previous direction = DOWN
// Current direction = UP
//
// SHORT:
// Previous direction = UP
// Current direction = DOWN
//
// ============================================================================
bool bullishFlip = ta.crossunder(supertrendDirection, 0)
bool bearishFlip = ta.crossover(supertrendDirection, 0)
// ============================================================================
// SECTION 15: FRESH FLIP CONTROL
// ============================================================================
//
// Default requires a new flip event.
//
// When disabled, the strategy can enter while
// Supertrend maintains the selected direction.
//
// ============================================================================
bool longTrendSetup = (requireFreshFlip ? bullishFlip : supertrendBullish)
bool shortTrendSetup = (requireFreshFlip ? bearishFlip : supertrendBearish)
// ============================================================================
// SECTION 16: ATR CALCULATION
// ============================================================================
float atr = ta.atr(atrLength)
float averageATR = ta.sma(atr, atrAverageLength)
bool atrExpansion = (not na(averageATR) and atr >= averageATR * atrExpansionFactor)
bool atrFilterOK = (not requireATRExpansion or atrExpansion)
// ============================================================================
// SECTION 17: VOLUME CALCULATION
// ============================================================================
float averageVolume = ta.sma(volume, volumeAverageLength)
bool volumeSpike = (not na(averageVolume) and volume >= averageVolume * volumeSpikeFactor)
bool volumeFilterOK = (not requireVolumeSpike or volumeSpike)
// ============================================================================
// SECTION 18: CANDLE METRICS
// ============================================================================
float candleBody = math.abs(close - open)
bool bullishCandle = (close > open)
bool bearishCandle = (close < open)
bool minimumBodyOK = (not requireMinimumBody or (not na(atr) and candleBody >= atr * minimumBodyATR))
bool longCandleOK = (not requireCandleDirection or bullishCandle)
bool shortCandleOK = (not requireCandleDirection or bearishCandle)
// ============================================================================
// SECTION 19: CONFIRMED H1 EMA
// ============================================================================
//
// Uses the previous completed H1 bar.
//
// Intended for chart timeframes below 60 minutes.
//
// ============================================================================
float h1ConfirmedEMA = request.security(syminfo.tickerid, "60", ta.ema(close, h1EMALength)[1], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
float h1ConfirmedClose = request.security(syminfo.tickerid, "60", close[1], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
bool longBiasOK = (not useH1EMABias or (not na(h1ConfirmedEMA) and not na(h1ConfirmedClose) and h1ConfirmedClose > h1ConfirmedEMA))
bool shortBiasOK = (not useH1EMABias or (not na(h1ConfirmedEMA) and not na(h1ConfirmedClose) and h1ConfirmedClose < h1ConfirmedEMA))
// ============================================================================
// SECTION 20: RAW LONG SIGNAL
// ============================================================================
bool rawLongSignal = (longTrendSetup and longCandleOK and minimumBodyOK and atrFilterOK and volumeFilterOK and longBiasOK)
// ============================================================================
// SECTION 21: RAW SHORT SIGNAL
// ============================================================================
bool rawShortSignal = (shortTrendSetup and shortCandleOK and minimumBodyOK and atrFilterOK and volumeFilterOK and shortBiasOK)
// ============================================================================
// SECTION 22: POSITION STATE
// ============================================================================
bool positionFlat = (strategy.position_size == 0)
bool positionLong = (strategy.position_size > 0)
bool positionShort = (strategy.position_size < 0)
bool positionJustClosed = (strategy.position_size == 0 and strategy.position_size[1] != 0)
// ============================================================================
// SECTION 23: CAN TRADE
// ============================================================================
bool dailyTradeLimitOK = (tradesToday < maximumTradesPerDay)
bool canTrade = (positionFlat and dailyTradeLimitOK and sessionOK and currentCloseMinute < sessionEndTotal and barstate.isconfirmed)
// ============================================================================
// SECTION 24: AMBIGUOUS SIGNAL PROTECTION
// ============================================================================
bool ambiguousSignal = (rawLongSignal and rawShortSignal)
bool finalLongSignal = (canTrade and allowLong and rawLongSignal and not ambiguousSignal)
bool finalShortSignal = (canTrade and allowShort and rawShortSignal and not ambiguousSignal)
// ============================================================================
// SECTION 25: LONG ENTRY
// ============================================================================
if finalLongSignal
strategy.entry("Long", strategy.long, comment="Supertrend Flip Long", alert_message="🟢 VÀO VỊ THẾ LONG (Supertrend Flip)\\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\\n🛑 SL dự kiến: " + str.tostring(close - stopLossPoints, format.mintick) + "\\n🎯 TP dự kiến: " + str.tostring(close + takeProfitPoints, format.mintick))
tradesToday += 1
// ============================================================================
// SECTION 26: SHORT ENTRY
// ============================================================================
if finalShortSignal
strategy.entry("Short", strategy.short, comment="Supertrend Flip Short", alert_message="🔴 VÀO VỊ THẾ SHORT (Supertrend Flip)\\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\\n🛑 SL dự kiến: " + str.tostring(close + stopLossPoints, format.mintick) + "\\n🎯 TP dự kiến: " + str.tostring(close - takeProfitPoints, format.mintick))
tradesToday += 1
// ============================================================================
// SECTION 27: ACTIVE RISK LEVELS
// ============================================================================
var float activeLongSL = na
var float activeLongTP = na
var float activeShortSL = na
var float activeShortTP = na
// ============================================================================
// SECTION 28: LONG SL / TP
// ============================================================================
if positionLong
float entryPrice = (strategy.position_avg_price)
activeLongSL := (entryPrice - stopLossPoints)
activeLongTP := (entryPrice + takeProfitPoints)
strategy.exit("Long Exit", from_entry="Long", stop=activeLongSL, limit=activeLongTP, comment_profit="TP Long", comment_loss="SL Long", alert_profit="💰 CHỐT LỜI LONG (TP HIT)\\n🎯 Giá chốt: " + str.tostring(activeLongTP, format.mintick), alert_loss="🛑 CẮT LỖ LONG (SL HIT)\\n🎯 Giá cắt: " + str.tostring(activeLongSL, format.mintick), disable_alert=disableSLTPAlerts)
// ============================================================================
// SECTION 29: SHORT SL / TP
// ============================================================================
if positionShort
float entryPrice = (strategy.position_avg_price)
activeShortSL := (entryPrice + stopLossPoints)
activeShortTP := (entryPrice - takeProfitPoints)
strategy.exit("Short Exit", from_entry="Short", stop=activeShortSL, limit=activeShortTP, comment_profit="TP Short", comment_loss="SL Short", alert_profit="💰 CHỐT LỜI SHORT (TP HIT)\\n🎯 Giá chốt: " + str.tostring(activeShortTP, format.mintick), alert_loss="🛑 CẮT LỖ SHORT (SL HIT)\\n🎯 Giá cắt: " + str.tostring(activeShortSL, format.mintick), disable_alert=disableSLTPAlerts)
// ============================================================================
// SECTION 30: POSITION CLEANUP
// ============================================================================
if positionJustClosed
activeLongSL := na
activeLongTP := na
activeShortSL := na
activeShortTP := na
// ============================================================================
// SECTION 31: SESSION END
// ============================================================================
//
// Force Close at 14:45.
//
// Actual execution depends on chart bar boundaries.
//
// ============================================================================
bool finalSessionBar = (currentMinute < sessionEndTotal and currentCloseMinute >= sessionEndTotal)
if finalSessionBar
if 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))
// ============================================================================
// SECTION 32: SUPERTREND DISPLAY
// ============================================================================
plot(showSupertrend and supertrendBullish ? supertrendValue : na, title="Supertrend Up", color=color.green, linewidth=2, style=plot.style_linebr)
plot(showSupertrend and supertrendBearish ? supertrendValue : na, title="Supertrend Down", color=color.red, linewidth=2, style=plot.style_linebr)
// ============================================================================
// SECTION 33: H1 EMA DISPLAY
// ============================================================================
plot(showH1EMA and useH1EMABias ? h1ConfirmedEMA : na, title="Confirmed H1 EMA", color=color.blue, linewidth=1)
// ============================================================================
// SECTION 34: ACTIVE LONG SL / TP DISPLAY
// ============================================================================
plot(showActiveSLTP and positionLong ? activeLongSL : na, title="Long SL", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showActiveSLTP and positionLong ? activeLongTP : na, title="Long TP", color=color.green, linewidth=2, style=plot.style_linebr)
// ============================================================================
// SECTION 35: ACTIVE SHORT SL / TP DISPLAY
// ============================================================================
plot(showActiveSLTP and positionShort ? activeShortSL : na, title="Short SL", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showActiveSLTP and positionShort ? activeShortTP : na, title="Short TP", color=color.green, linewidth=2, style=plot.style_linebr)
// ============================================================================
// SECTION 36: OPTIONAL SETUP MARKERS
// ============================================================================
plotshape(showSignalMarkers and rawLongSignal, title="Supertrend Long Setup", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.tiny, text="L", textcolor=color.white)
plotshape(showSignalMarkers and rawShortSignal, title="Supertrend Short Setup", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.tiny, text="S", textcolor=color.white)
// ============================================================================
// SECTION 37: DIAGNOSTIC COUNTERS
// ============================================================================
var int bullFlipCount = 0
var int bearFlipCount = 0
var int longSetupCount = 0
var int shortSetupCount = 0
var int longEntryCount = 0
var int shortEntryCount = 0
var int lastCountedBar = na
if (barstate.isconfirmed and (na(lastCountedBar) or lastCountedBar != bar_index))
lastCountedBar := bar_index
if bullishFlip
bullFlipCount += 1
if bearishFlip
bearFlipCount += 1
if rawLongSignal and not rawLongSignal[1]
longSetupCount += 1
if rawShortSignal and not rawShortSignal[1]
shortSetupCount += 1
if finalLongSignal
longEntryCount += 1
if finalShortSignal
shortEntryCount += 1
// ============================================================================
// SECTION 38: DIAGNOSTICS
// ============================================================================
var table diagnostics = table.new(position.top_right, 2, 16, border_width=1)
if showDiagnostics and barstate.islast
string positionText = "FLAT"
if positionLong
positionText := "LONG"
if positionShort
positionText := "SHORT"
table.cell(diagnostics, 0, 0, "CNPS68")
table.cell(diagnostics, 1, 0, timeframe.period)
table.cell(diagnostics, 0, 1, "Supertrend")
table.cell(diagnostics, 1, 1, str.tostring(supertrendValue, format.mintick))
table.cell(diagnostics, 0, 2, "Trend")
table.cell(diagnostics, 1, 2, supertrendBullish ? "UP" : "DOWN")
table.cell(diagnostics, 0, 3, "Bull Flips")
table.cell(diagnostics, 1, 3, str.tostring(bullFlipCount))
table.cell(diagnostics, 0, 4, "Bear Flips")
table.cell(diagnostics, 1, 4, str.tostring(bearFlipCount))
table.cell(diagnostics, 0, 5, "Long Setups")
table.cell(diagnostics, 1, 5, str.tostring(longSetupCount))
table.cell(diagnostics, 0, 6, "Short Setups")
table.cell(diagnostics, 1, 6, str.tostring(shortSetupCount))
table.cell(diagnostics, 0, 7, "ATR")
table.cell(diagnostics, 1, 7, str.tostring(atr, format.mintick))
table.cell(diagnostics, 0, 8, "ATR Expansion")
table.cell(diagnostics, 1, 8, atrFilterOK ? "YES" : "NO")
table.cell(diagnostics, 0, 9, "Volume OK")
table.cell(diagnostics, 1, 9, volumeFilterOK ? "YES" : "NO")
table.cell(diagnostics, 0, 10, "Long H1 Bias")
table.cell(diagnostics, 1, 10, longBiasOK ? "YES" : "NO")
table.cell(diagnostics, 0, 11, "Short H1 Bias")
table.cell(diagnostics, 1, 11, shortBiasOK ? "YES" : "NO")
table.cell(diagnostics, 0, 12, "Long Entries")
table.cell(diagnostics, 1, 12, str.tostring(longEntryCount))
table.cell(diagnostics, 0, 13, "Short Entries")
table.cell(diagnostics, 1, 13, str.tostring(shortEntryCount))
table.cell(diagnostics, 0, 14, "Trades Today")
table.cell(diagnostics, 1, 14, str.tostring(tradesToday) + " / " + str.tostring(maximumTradesPerDay))
table.cell(diagnostics, 0, 15, "Position")
table.cell(diagnostics, 1, 15, positionText)
2. Những khái niệm kỹ thuật cốt lõi trong CNPS68
2.1. Động cơ Supertrend và cơ chế Fresh Flip
Bot sử dụng hàm chuẩn ta.supertrend(supertrendFactor, supertrendATRLength) với giá trị mặc định Factor = 3.0 và ATR Period = 10. Trong Pine Script, biến supertrendDirection quy ước:
supertrendDirection < 0: Xu hướng tăng (UPTREND).supertrendDirection > 0: Xu hướng giảm (DOWNTREND).
Điểm đảo chiều được xác định qua bullishFlip = ta.crossunder(supertrendDirection, 0) (đảo từ giảm sang tăng) và bearishFlip = ta.crossover(supertrendDirection, 0) (đảo từ tăng sang giảm). Khi requireFreshFlip = true (mặc định), bot chỉ chấp nhận tín hiệu tại đúng cây nến xảy ra Flip; nếu tắt (false), bot có thể vào lệnh bất cứ khi nào Supertrend đang duy trì hướng tương ứng (supertrendBullish hoặc supertrendBearish).
2.2. Bộ lọc xác nhận nến, ATR Expansion và Volume Spike
Để tránh các cú Flip giả trong vùng sideway thanh khoản yếu, mã nguồn cung cấp 3 bộ lọc tùy chọn (mặc định tắt để giữ nguyên tín hiệu gốc, có thể bật khi tối ưu):
- Candle Metrics: Kiểm tra hướng nến (
close > opencho Long,close < opencho Short) và độ lớn thân nếncandleBody = math.abs(close - open) >= atr * minimumBodyATR(mặc định0.20). - ATR Expansion: So sánh
atr = ta.atr(14)vớiaverageATR = ta.sma(atr, 20). Điều kiện đạt khiatr >= averageATR * atrExpansionFactor(mặc định1.0), đảm bảo thị trường đang có đủ biên độ biến động. - Volume Spike: So sánh khối lượng hiện tại với
averageVolume = ta.sma(volume, 20). Điều kiện đạt khivolume >= averageVolume * volumeSpikeFactor(mặc định1.20), xác nhận dòng tiền tham gia tại điểm đảo chiều.
2.3. Bộ lọc xu hướng khung lớn Confirmed H1 EMA Bias
Khi bật useH1EMABias, bot lấy dữ liệu từ khung 60 phút thông qua request.security(syminfo.tickerid, "60", ...[1], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on). Việc sử dụng chỉ số [1] của nến H1 đã đóng cửa hoàn toàn giúp loại bỏ hoàn toàn lỗi repaint trên dữ liệu lịch sử và thực chiến:
- Long Bias: Yêu cầu
h1ConfirmedClose > h1ConfirmedEMA(EMA mặc định50). - Short Bias: Yêu cầu
h1ConfirmedClose < h1ConfirmedEMA.
3. Nguyên lý hoạt động của CNPS68
Quy trình vận hành của CNPS68 trên mỗi thanh nến diễn ra tuần tự qua 5 bước:
- Khởi tạo phiên và đếm ngày giao dịch: Hệ thống chuyển đổi thời gian về múi giờ
Asia/Ho_Chi_Minh, xác địnhtradingDayKeytheo định dạngYYYYMMDD. Khi bước sang ngày mới (newTradingDay), biến đếmtradesTodayđược reset về0. - Đo lường Supertrend và các bộ lọc: Tính toán giá trị Supertrend, phát hiện
bullishFlip/bearishFlip, đồng thời cập nhật trạng thái của các bộ lọc Nến, ATR, Volume và H1 EMA. - Tổng hợp tín hiệu thô (Raw Signal): Kết hợp trạng thái xu hướng (
longTrendSetup/shortTrendSetup) với toàn bộ các bộ lọc để tạorawLongSignalvàrawShortSignal. - Kiểm tra điều kiện giao dịch & Chống mơ hồ: Kiểm tra biến
canTrade(đang phẳng vị thế, chưa vượtmaximumTradesPerDay, trong khung giờ cho phép và nến đã đóng cửabarstate.isconfirmed), đồng thời loại trừ trường hợpambiguousSignal(cả Long và Short cùng thỏa mãn). - Gửi lệnh và quản trị thoát lệnh: Gửi lệnh vào vị thế kèm
alert_message, tăngtradesToday, thiết lập ngaystrategy.exitvới mức SL/TP cố định và theo dõi mốc14:45để đóng cưỡng bức nếu còn vị thế mở.
4. Điều kiện vào lệnh Long và Short của CNPS68
4.1. Điều kiện vào lệnh Long
Lệnh Long (finalLongSignal) được thực thi khi thỏa mãn đồng thời tất cả các điều kiện sau:
- Hướng giao dịch
tradeDirectioncho phép Long ("Long"hoặc"Both"). longTrendSetupđúng: cóbullishFlip(nếurequireFreshFlip = true) hoặcsupertrendBullish(nếurequireFreshFlip = false).longCandleOKđúng: nến tăngclose > open(nếurequireCandleDirection = true).minimumBodyOKđúng:candleBody >= atr * minimumBodyATR(nếurequireMinimumBody = true).atrFilterOKđúng:atr >= averageATR * atrExpansionFactor(nếurequireATRExpansion = true).volumeFilterOKđúng:volume >= averageVolume * volumeSpikeFactor(nếurequireVolumeSpike = true).longBiasOKđúng:h1ConfirmedClose > h1ConfirmedEMA(nếuuseH1EMABias = true).- Thỏa mãn điều kiện
canTradevà không bị dínhambiguousSignal.
4.2. Điều kiện vào lệnh Short
Lệnh Short (finalShortSignal) được thực thi khi thỏa mãn đồng thời tất cả các điều kiện sau:
- Hướng giao dịch
tradeDirectioncho phép Short ("Short"hoặc"Both"). shortTrendSetupđúng: cóbearishFlip(nếurequireFreshFlip = true) hoặcsupertrendBearish(nếurequireFreshFlip = false).shortCandleOKđúng: nến giảmclose < open(nếurequireCandleDirection = true).minimumBodyOKđúng:candleBody >= atr * minimumBodyATR(nếurequireMinimumBody = true).atrFilterOKđúng:atr >= averageATR * atrExpansionFactor(nếurequireATRExpansion = true).volumeFilterOKđúng:volume >= averageVolume * volumeSpikeFactor(nếurequireVolumeSpike = true).shortBiasOKđúng:h1ConfirmedClose < h1ConfirmedEMA(nếuuseH1EMABias = true).- Thỏa mãn điều kiện
canTradevà không bị dínhambiguousSignal.
4.3. Điều kiện kiểm soát giao dịch chung
Biến canTrade đóng vai trò cổng gác cuối cùng trước khi gửi lệnh:
- Trạng thái phẳng (
positionFlat):strategy.position_size == 0(vìpyramiding = 0, bot không nhồi lệnh khi đang giữ vị thế). - Giới hạn lệnh ngày (
dailyTradeLimitOK):tradesToday < maximumTradesPerDay(mặc định tối đa2lệnh/ngày). - Bộ lọc phiên (
sessionOK): NếuuseSessionFilter = true, thời gian mở nếncurrentMinutephải nằm trong khoảng09:00đến14:30. - Chặn sát giờ đóng phiên: Thời điểm đóng nến
currentCloseMinutephải nhỏ hơn14:45(sessionEndTotal). - Xác nhận đóng nến: Bắt buộc
barstate.isconfirmedđể tránh vào lệnh sớm khi nến đang chạy.
5. Quản trị Stop Loss, Take Profit và Thoát lệnh
5.1. Cơ chế Stop Loss và bộ lọc Risk
Ngay khi vị thế được mở (positionLong hoặc positionShort), bot lấy giá khớp lệnh trung bình entryPrice = strategy.position_avg_price để tính mức Stop Loss cố định theo điểm (stopLossPoints, mặc định 5.0 điểm):
- Lệnh Long:
activeLongSL = entryPrice - stopLossPoints - Lệnh Short:
activeShortSL = entryPrice + stopLossPoints
Bot không sử dụng khoảng đệm ATR hay bộ lọc Min–Max Risk cho SL; rủi ro trên mỗi hợp đồng được cố định chính xác bằng stopLossPoints.
5.2. Cơ chế Take Profit, Break Even và Trailing
Mức chốt lời được tính cố định dựa trên takeProfitPoints (mặc định 15.0 điểm, tương ứng tỷ lệ Risk:Reward = 1:3):
- Lệnh Long:
activeLongTP = entryPrice + takeProfitPoints - Lệnh Short:
activeShortTP = entryPrice - takeProfitPoints
Mã nguồn CNPS68 không sử dụng cơ chế dời hòa vốn (Break Even) hay Trailing Stop. Thay vào đó, ngoài strategy.exit cho SL/TP cố định, bot áp dụng cơ chế đóng cưỡng bức cuối phiên (Session End): khi finalSessionBar kích hoạt (currentMinute < 14:45 và currentCloseMinute >= 14:45), nếu strategy.position_size != 0, bot gọi strategy.close_all(immediately=true) để đóng toàn bộ vị thế trước giờ ATC. Khi vị thế đóng (positionJustClosed), toàn bộ biến activeLongSL/TP và activeShortSL/TP được xóa về na.
5.3. Bảng tổng hợp cơ chế bảo vệ vị thế
| Cơ chế bảo vệ | Tham số / Điều kiện | Giá trị mặc định | Hành động thực thi |
|---|---|---|---|
| Stop Loss cố định | stopLossPoints | 5.0 điểm | Cắt lỗ tại entryPrice ± 5.0 |
| Take Profit cố định | takeProfitPoints | 15.0 điểm | Chốt lời tại entryPrice ± 15.0 |
| Break Even / Trailing | Không áp dụng | — | Giữ nguyên SL/TP cố định đến khi chạm hoặc hết phiên |
| Đóng vị thế cuối phiên | sessionEndHour / Minute | 14:45 | strategy.close_all(immediately=true) |
| Giới hạn lệnh/ngày | maximumTradesPerDay | 2 lệnh | Ngừng mở vị thế mới khi đạt giới hạn |
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 đồ hợp đồng tương lai VN30F1M trên TradingView và chọn khung thời gian giao dịch mong muốn (khuyến nghị khung dưới 60 phút như M5, M15 nếu sử dụng bộ lọc H1 EMA).
- Nhấn vào tab Pine Editor ở thanh công cụ phía dưới màn hình.
- Xóa toàn bộ mã mẫu mặc định, sao chép toàn bộ Source Code CNPS68 ở Mục 1 và dán vào Pine Editor.
- Nhấn Save để lưu chiến lược, sau đó nhấn Add to chart để đưa bot lên biểu đồ.
- 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 (
tradeDirection), các bộ lọc tùy chọn hoặc bậtShow Diagnostics?nếu muốn theo dõi bảng thống kê.
Cách đọc bảng chẩn đoán (Diagnostics Table)
Khi bật showDiagnostics = true, bot sẽ vẽ một bảng gồm 16 dòng ở góc trên bên phải (position.top_right) tại thanh nến cuối cùng (barstate.islast):
| Dòng | Nhãn hiển thị | Ý nghĩa thực tế trong code |
|---|---|---|
| 0 | CNPS68 | Khung thời gian hiện tại của biểu đồ (timeframe.period) |
| 1 | Supertrend | Giá trị đường Supertrend hiện tại |
| 2 | Trend | Trạng thái xu hướng Supertrend (UP hoặc DOWN) |
| 3–4 | Bull Flips / Bear Flips | Tổng số lần Supertrend đảo chiều tăng / giảm đã đếm |
| 5–6 | Long Setups / Short Setups | Tổng số lần tín hiệu thô rawLongSignal / rawShortSignal xuất hiện |
| 7 | ATR | Giá trị ATR hiện tại (ta.atr(14)) |
| 8 | ATR Expansion | Trạng thái bộ lọc ATR (YES / NO) |
| 9 | Volume OK | Trạng thái bộ lọc Volume (YES / NO) |
| 10–11 | Long H1 Bias / Short H1 Bias | Trạng thái cho phép theo H1 EMA (YES / NO) |
| 12–13 | Long Entries / Short Entries | Tổng số lệnh Long / Short thực tế đã kích hoạt |
| 14 | Trades Today | Số lệnh đã vào trong ngày / Giới hạn tối đa (tradesToday / maximumTradesPerDay) |
| 15 | Position | Trạng thái vị thế hiện tại (FLAT, LONG hoặc SHORT) |
7. Cách thiết lập cảnh báo tín hiệu giao dịch (Alert)
Để nhận thông báo tự động qua ứng dụng TradingView, Telegram hoặc Webhook khi bot phát sinh tín hiệu:
- Nhấn vào biểu tượng Alert (hình đồng hồ báo thức) trên thanh công cụ bên phải hoặc phím tắt
Alt + A. - Tại mục Condition, chọn đúng tên chiến lược CNPS68 SUPERTREND-FLIP.
- Tại mục Message, xóa nội dung mặc định và điền chính xác cú pháp:
{{strategy.order.alert_message}}. - Nếu không muốn nhận thông báo khi chạm SL/TP (chỉ nhận thông báo vào lệnh và hết phiên), bạn có thể bật tùy chọn
Disable SL / TP Alerts?(disableSLTPAlerts = true) trong phần cài đặt bot.
Bảng thông điệp Alert của CNPS68
| Loại sự kiện | Điều kiện kích hoạt | Nội dung thông điệp (alert_message / alert_profit / alert_loss) |
|---|---|---|
| Vào lệnh Long | finalLongSignal | 🟢 VÀO VỊ THẾ LONG (Supertrend Flip) kèm Giá vào, SL dự kiến, TP dự kiến |
| Vào lệnh Short | finalShortSignal | 🔴 VÀO VỊ THẾ SHORT (Supertrend Flip) kèm Giá vào, SL dự kiến, TP dự kiến |
| Chốt lời Long | Chạm activeLongTP | 💰 CHỐT LỜI LONG (TP HIT) kèm Giá chốt |
| Cắt lỗ Long | Chạm activeLongSL | 🛑 CẮT LỖ LONG (SL HIT) kèm Giá cắt |
| Chốt lời Short | Chạm activeShortTP | 💰 CHỐT LỜI SHORT (TP HIT) kèm Giá chốt |
| Cắt lỗ Short | Chạm activeShortSL | 🛑 CẮT LỖ SHORT (SL HIT) kèm Giá cắt |
| Đóng hết phiên | finalSessionBar (14:45) | ⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End) kèm Giá đóng |
Kết luận
CNPS68 Supertrend Flip là một hệ thống giao dịch phái sinh VN30F1M gọn nhẹ, minh bạch và dễ tùy biến, đặc biệt phù hợp với các giai đoạn thị trường có xu hướng rõ ràng sau khi phá vỡ cấu trúc ngắn hạn. Nhờ khả năng bật/tắt linh hoạt các bộ lọc Nến, ATR, Volume và H1 EMA cùng cơ chế SL/TP cố định 5/15 điểm và đóng lệnh cuối phiên lúc 14:45, nhà giao dịch có thể dễ dàng kiểm soát rủi ro và tránh giữ vị thế qua đêm.
Bạn có thể tham khảo thêm các chiến lược khác 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.





