Hướng Dẫn Sử Dụng Bot CNPS67 - Donchian Breakout cho VN30F1M
TradingviewBot CNPS67 sử dụng kênh Donchian 20 nến không tự tham chiếu để bắt điểm phá vỡ xu hướng trên VN30F1M, kết hợp bộ lọc ATR, Volume, H1 EMA và quản trị rủi ro cố định SL 5 điểm / TP 15 điểm.

Mục lục
Trong giao dịch hợp đồng tương lai VN30F1M, việc nhận diện chính xác thời điểm giá thoát khỏi vùng tích lũy để bước vào một nhịp xu hướng mới luôn là bài toán khó. Nếu vào lệnh quá sớm khi giá chưa phá vỡ biên độ cũ, trader dễ dính bẫy phá vỡ giả (false breakout); ngược lại, nếu chờ xác nhận quá muộn thì tỷ lệ Risk:Reward không còn hấp dẫn.
CNPS67 DONCHIAN-BREAKOUT (viết bằng Pine Script v6 trên TradingView) được thiết kế để giải quyết trực tiếp bài toán này thông qua mô hình phá vỡ kênh Donchian chuẩn hóa (loại trừ nến hiện tại để tránh tự tham chiếu), đi kèm hệ thống bộ lọc tùy chọn đa lớp và cơ chế quản trị rủi ro cố định theo tỷ lệ 1:3.
Những điểm nổi bật cốt lõi của Bot CNPS67:
- Kênh Donchian không tự tham chiếu (
high[1]/low[1]): Đảm bảo tín hiệu phá vỡ chỉ kích hoạt khi giá đóng cửa thực sự vượt qua đỉnh/đáy củaNnến liền trước. - Lọc sự kiện phá vỡ đầu tiên (
Require First Breakout Event): Tránh vào lệnh đuổi ở các nến tiếp theo khi giá đã đi xa khỏi vùng phá vỡ ban đầu. - Bộ lọc đa lớp tùy chọn: Hỗ trợ lọc biên độ phá vỡ theo ATR, hướng nến, đột biến khối lượng (
Volume Spike) và xu hướng khung H1 (Confirmed H1 EMA Bias). - Quản trị rủi ro kỷ luật: Cố định cắt lỗ 5.0 điểm, chốt lời 15.0 điểm, giới hạn tối đa 2 lệnh/ngày và tự động đóng toàn bộ vị thế trước giờ ATC (
14:45).
1. CNPS67 Donchian Breakout là gì?
CNPS67 Donchian Breakout là chiến lược giao dịch theo xu hướng dạng Breakout, hoạt động dựa trên 4 trụ cột kỹ thuật chính:
- Hệ thống kênh Donchian (
upperBand/lowerBand): Đo lường biên độ cao nhất và thấp nhất của20nến trước đó (không tính nến hiện tại) để xác định ngưỡng kháng cự và hỗ trợ động. - Bộ lọc chất lượng cú phá vỡ (
Breakout Strength&Volume): Tùy chọn kiểm tra độ dứt khoát của nến breakout thông qua khoảng đệmATR, màu nến đồng thuận và sự bùng nổ khối lượng so với trung bình20phiên. - Bộ lọc xu hướng đa khung thời gian (
Confirmed H1 EMA Bias): Tùy chọn đối chiếu giá đóng cửa nến H1 đã hoàn tất với đườngEMA(50)trên khung H1 để giao dịch thuận xu hướng lớn, loại bỏ hoàn toàn hiện tượng repaint. - Động cơ kiểm soát phiên & rủi ro (
Session&Risk Management): Kiểm soát số lượng lệnh tối đa trong ngày, giới hạn khung giờ giao dịch theo múi giờAsia/Ho_Chi_Minh, cố địnhSL 5 điểm / TP 15 điểmvà tất toán vị thế cuối phiên.
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ả chức năng |
|---|---|---|---|
| Donchian | donchianLength | 20 | Số nến hồi quy tính đỉnh/đáy kênh Donchian |
| Donchian | requireFreshBreak | true | Chỉ lấy sự kiện phá vỡ đầu tiên qua biên kênh |
| Breakout Strength | requireBreakoutBuffer | false | Bật/tắt yêu cầu giá vượt biên tối thiểu theo ATR |
| Breakout Strength | breakoutBufferATR | 0.10 | Hệ số ATR tối thiểu giá đóng cửa phải vượt qua biên |
| Breakout Strength | requireCandleDirection | false | Yêu cầu nến phá vỡ là nến tăng (Long) hoặc giảm (Short) |
| Volume | requireVolumeSpike | false | Bật/tắt bộ lọc đột biến khối lượng |
| Volume | volumeAverageLength | 20 | Chu kỳ SMA tính khối lượng trung bình |
| Volume | volumeSpikeFactor | 1.20 | Hệ số nhân khối lượng tối thiểu so với trung bình |
| Trend | useH1EMABias | false | Bật/tắt bộ lọc xu hướng EMA trên khung H1 |
| Trend | h1EMALength | 50 | Chu kỳ đường EMA trên khung H1 |
| ATR | atrLength | 14 | Chu kỳ tính chỉ báo ATR |
| Risk Management | stopLossPoints | 5.0 | Khoảng cách Stop Loss cố định (điểm) |
| Risk Management | takeProfitPoints | 15.0 | Khoảng cách Take Profit cố định (điểm) |
| Trade Control | maximumTradesPerDay | 2 | Số lệnh tối đa được phép vào mỗi ngày |
| Trade Control | tradeDirection | "Long" | Chiều giao dịch ("Long", "Short", "Both") |
| Session | useSessionFilter | false | Bật/tắt lọc khung giờ vào lệnh |
| Session | strategyTimezone | "Asia/Ho_Chi_Minh" | Múi giờ chuẩn của chiến lược |
| Session | sessionStartHour : Minute | 09:00 | Thời điểm bắt đầu cho phép vào lệnh |
| Session | lastEntryHour : Minute | 14:30 | Thời điểm cuối cùng cho phép mở lệnh mới |
| Session | sessionEndHour : Minute | 14:45 | Thời điểm ép đóng toàn bộ vị thế cuối phiên |
| Alerts | disableSLTPAlerts | false | Tắt cảnh báo riêng cho sự kiện chạm SL/TP |
| Display | showDonchian / showActiveSLTP | true / true | Hiển thị kênh Donchian và đường SL/TP đang chạy |
| Display | showH1EMA / showSignalMarkers / showDiagnostics | false | Hiển thị EMA H1, mũi tên Setup và bảng Diagnostics |
Source Code CNPS67 Donchian Breakout
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="CNPS67 DONCHIAN-BREAKOUT", shorttitle="CNPS67 DONCHIAN", 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)
// ============================================================================
// CNPS67 DONCHIAN BREAKOUT
// LONG: Close > highest high of previous N bars
// SHORT: Close < lowest low of previous N bars
// SL: 5 POINTS | TP: 15 POINTS
// ============================================================================
// SECTION 1: DONCHIAN SETTINGS
donchianLength = input.int(20, "Donchian Lookback Bars", minval=2, maxval=500, group="Donchian")
requireFreshBreak = input.bool(true, "Require First Breakout Event?", group="Donchian")
// SECTION 2: BREAKOUT STRENGTH
requireBreakoutBuffer = input.bool(false, "Require ATR Breakout Buffer?", group="Breakout Strength")
breakoutBufferATR = input.float(0.10, "Minimum Close Beyond Channel / ATR", minval=0.0, step=0.05, group="Breakout Strength")
requireCandleDirection = input.bool(false, "Require Bull/Bear Candle?", group="Breakout Strength")
// SECTION 3: VOLUME FILTER
requireVolumeSpike = input.bool(false, "Require Volume Spike?", group="Volume")
volumeAverageLength = input.int(20, "Volume Average Length", minval=2, group="Volume")
volumeSpikeFactor = input.float(1.20, "Volume Spike Factor", minval=0.1, step=0.1, group="Volume")
// SECTION 4: TREND FILTER
useH1EMABias = input.bool(false, "Use Confirmed H1 EMA Bias?", group="Trend")
h1EMALength = input.int(50, "H1 EMA Length", minval=1, group="Trend")
// SECTION 5: ATR
atrLength = input.int(14, "ATR Length", minval=1, group="ATR")
// SECTION 6: RISK MANAGEMENT
stopLossPoints = input.float(5.0, "Stop Loss (Points)", minval=0.1, step=0.5, group="Risk Management")
takeProfitPoints = input.float(15.0, "Take Profit (Points)", minval=0.1, step=0.5, group="Risk Management")
// SECTION 7: TRADE CONTROL
maximumTradesPerDay = input.int(2, "Maximum Trades Per Day", minval=1, maxval=20, group="Trade Control")
tradeDirection = input.string("Long", "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, "Use Entry Session Filter?", group="Session")
strategyTimezone = input.string("Asia/Ho_Chi_Minh", "Strategy Timezone", group="Session")
sessionStartHour = input.int(9, "Session Start Hour", minval=0, maxval=23, group="Session")
sessionStartMinute = input.int(0, "Session Start Minute", minval=0, maxval=59, group="Session")
lastEntryHour = input.int(14, "Last Entry Hour", minval=0, maxval=23, group="Session")
lastEntryMinute = input.int(30, "Last Entry Minute", minval=0, maxval=59, group="Session")
sessionEndHour = input.int(14, "Force Close Hour", minval=0, maxval=23, group="Session")
sessionEndMinute = input.int(45, "Force Close Minute", minval=0, maxval=59, group="Session")
// SECTION 9: ALERT CONTROL
disableSLTPAlerts = input.bool(false, "Disable SL / TP Alerts?", group="Alerts")
// SECTION 10: DISPLAY
showDonchian = input.bool(true, "Show Donchian Channel?", group="Display")
showH1EMA = input.bool(false, "Show Confirmed H1 EMA?", group="Display")
showSignalMarkers = input.bool(false, "Show Setup Markers?", group="Display")
showActiveSLTP = input.bool(true, "Show Active SL / TP?", group="Display")
showDiagnostics = input.bool(false, "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: DONCHIAN CHANNEL
// Exclude current bar to prevent self-referencing breakout.
float upperBand = ta.highest(high[1], donchianLength)
float lowerBand = ta.lowest(low[1], donchianLength)
float middleBand = (upperBand + lowerBand) / 2.0
bool channelReady = not na(upperBand) and not na(lowerBand)
// SECTION 14: CONFIRMED H1 EMA
// Use completed H1 values on chart timeframes below H1.
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 15: ATR
float atr = ta.atr(atrLength)
// SECTION 16: VOLUME SPIKE
float averageVolume = ta.sma(volume, volumeAverageLength)
bool volumeSpike = not na(averageVolume) and volume >= averageVolume * volumeSpikeFactor
bool volumeOK = not requireVolumeSpike or volumeSpike
// SECTION 17: BREAKOUT DETECTION
bool aboveChannel = channelReady and close > upperBand
bool belowChannel = channelReady and close < lowerBand
bool freshLongBreak = aboveChannel and (na(upperBand[1]) or close[1] <= upperBand[1])
bool freshShortBreak = belowChannel and (na(lowerBand[1]) or close[1] >= lowerBand[1])
bool longBreakout = requireFreshBreak ? freshLongBreak : aboveChannel
bool shortBreakout = requireFreshBreak ? freshShortBreak : belowChannel
// SECTION 18: OPTIONAL BREAKOUT FILTERS
bool longCandleOK = not requireCandleDirection or close > open
bool shortCandleOK = not requireCandleDirection or close < open
bool longBufferOK = not requireBreakoutBuffer or (not na(atr) and close - upperBand >= atr * breakoutBufferATR)
bool shortBufferOK = not requireBreakoutBuffer or (not na(atr) and lowerBand - close >= atr * breakoutBufferATR)
// SECTION 19: RAW SIGNALS
bool rawLongSignal = longBreakout and longCandleOK and longBufferOK and volumeOK and longBiasOK
bool rawShortSignal = shortBreakout and shortCandleOK and shortBufferOK and volumeOK and shortBiasOK
// SECTION 20: POSITION STATE
bool positionFlat = strategy.position_size == 0
bool positionLong = strategy.position_size > 0
bool positionShort = strategy.position_size < 0
bool positionJustClosed = positionFlat and strategy.position_size[1] != 0
// SECTION 21: CAN TRADE
bool dailyTradeLimitOK = tradesToday < maximumTradesPerDay
bool canTrade = (positionFlat and dailyTradeLimitOK and sessionOK and currentCloseMinute < sessionEndTotal and barstate.isconfirmed)
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 22: LONG ENTRY
if finalLongSignal
strategy.entry("Long", strategy.long, comment="Donchian Long", alert_message="🟢 VÀO VỊ THẾ LONG (Donchian Breakout)\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 23: SHORT ENTRY
if finalShortSignal
strategy.entry("Short", strategy.short, comment="Donchian Short", alert_message="🔴 VÀO VỊ THẾ SHORT (Donchian Breakout)\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 24: ACTIVE RISK LEVELS
var float activeLongSL = na
var float activeLongTP = na
var float activeShortSL = na
var float activeShortTP = na
// SECTION 25: 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 26: 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 27: POSITION CLEANUP
if positionJustClosed
activeLongSL := na
activeLongTP := na
activeShortSL := na
activeShortTP := na
// SECTION 28: SESSION END
bool finalSessionBar = (currentMinute < sessionEndTotal and currentCloseMinute >= sessionEndTotal)
if finalSessionBar 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))
// SECTION 29: DONCHIAN DISPLAY
plot(showDonchian ? upperBand : na, title="Prior Donchian Upper", color=color.green, linewidth=2)
plot(showDonchian ? middleBand : na, title="Prior Donchian Middle", color=color.gray, linewidth=1)
plot(showDonchian ? lowerBand : na, title="Prior Donchian Lower", color=color.red, linewidth=2)
plot(showH1EMA and useH1EMABias ? h1ConfirmedEMA : na, title="Confirmed H1 EMA", color=color.blue, linewidth=1)
// SECTION 30: ACTIVE 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)
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 31: SETUP MARKERS
plotshape(showSignalMarkers and rawLongSignal, title="Donchian Long Setup", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.tiny, text="L", textcolor=color.white)
plotshape(showSignalMarkers and rawShortSignal, title="Donchian Short Setup", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.tiny, text="S", textcolor=color.white)
// SECTION 32: DIAGNOSTIC COUNTERS
var int bullBreakCount = 0
var int bearBreakCount = 0
var int longSetupCount = 0
var int shortSetupCount = 0
var int longEntryCount = 0
var int shortEntryCount = 0
var int lastDiagnosticsBar = na
if barstate.isconfirmed and (na(lastDiagnosticsBar) or lastDiagnosticsBar != bar_index)
lastDiagnosticsBar := bar_index
if freshLongBreak
bullBreakCount += 1
if freshShortBreak
bearBreakCount += 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 33: DIAGNOSTICS
var table diagnostics = table.new(position.top_right, 2, 16, border_width=1)
if showDiagnostics and barstate.islast
string positionText = positionLong ? "LONG" : positionShort ? "SHORT" : "FLAT"
table.cell(diagnostics, 0, 0, "CNPS67")
table.cell(diagnostics, 1, 0, timeframe.period)
table.cell(diagnostics, 0, 1, "Upper")
table.cell(diagnostics, 1, 1, str.tostring(upperBand, format.mintick))
table.cell(diagnostics, 0, 2, "Middle")
table.cell(diagnostics, 1, 2, str.tostring(middleBand, format.mintick))
table.cell(diagnostics, 0, 3, "Lower")
table.cell(diagnostics, 1, 3, str.tostring(lowerBand, format.mintick))
table.cell(diagnostics, 0, 4, "Bull Breaks")
table.cell(diagnostics, 1, 4, str.tostring(bullBreakCount))
table.cell(diagnostics, 0, 5, "Bear Breaks")
table.cell(diagnostics, 1, 5, str.tostring(bearBreakCount))
table.cell(diagnostics, 0, 6, "Long Setups")
table.cell(diagnostics, 1, 6, str.tostring(longSetupCount))
table.cell(diagnostics, 0, 7, "Short Setups")
table.cell(diagnostics, 1, 7, str.tostring(shortSetupCount))
table.cell(diagnostics, 0, 8, "ATR")
table.cell(diagnostics, 1, 8, str.tostring(atr, format.mintick))
table.cell(diagnostics, 0, 9, "Volume OK")
table.cell(diagnostics, 1, 9, volumeOK ? "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 CNPS67
2.1. Kênh Donchian dịch chuyển 1 nến (Prior Donchian Channel)
Khác với cách tính Donchian thông thường bao gồm cả nến đang chạy (khiến high của nến hiện tại tự nâng upperBand lên và không bao giờ tạo được close > upperBand), CNPS67 sử dụng giá trị dịch chuyển 1 nến (high[1] và low[1]):
upperBand = ta.highest(high[1], donchianLength)lowerBand = ta.lowest(low[1], donchianLength)middleBand = (upperBand + lowerBand) / 2.0
Khi requireFreshBreak = true (mặc định), bot chỉ ghi nhận tín hiệu ở nến phá vỡ đầu tiên (freshLongBreak khi close > upperBand và close[1] <= upperBand[1]; freshShortBreak khi close < lowerBand và close[1] >= lowerBand[1]).
2.2. Bộ lọc sức mạnh cú phá vỡ & Khối lượng
Để tránh các cú phá vỡ yếu ớt hoặc thiếu thanh khoản, CNPS67 tích hợp sẵn 3 bộ lọc tùy chọn (mặc định tắt để giữ nguyên bản chất breakout thuần túy, có thể bật khi tối ưu):
- ATR Breakout Buffer (
requireBreakoutBuffer): Tínhatr = ta.atr(atrLength)(chu kỳ 14). Với Long, yêu cầuclose - upperBand >= atr * breakoutBufferATR(0.10); với Short, yêu cầulowerBand - close >= atr * breakoutBufferATR. - Hướng nến (
requireCandleDirection): Bắt buộc nến breakout phải đóng cửa theo đúng chiều (close > opencho Long,close < opencho Short). - Đột biến khối lượng (
requireVolumeSpike): TínhaverageVolume = ta.sma(volume, 20)và yêu cầuvolume >= averageVolume * 1.20.
2.3. Bộ lọc xu hướng H1 không repaint (Confirmed H1 EMA Bias)
Khi bật useH1EMABias = true, bot lấy dữ liệu từ khung 60 phút thông qua request.security(..., gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on) với tham số dịch [1] (ta.ema(close, h1EMALength)[1] và close[1]). Nhờ chỉ đọc cây nến H1 đã đóng cửa hoàn toàn, tín hiệu hoàn toàn không bị thay đổi lại trong quá khứ (non-repaint):
- Long Bias (
longBiasOK):h1ConfirmedClose > h1ConfirmedEMA - Short Bias (
shortBiasOK):h1ConfirmedClose < h1ConfirmedEMA
3. Nguyên lý hoạt động của CNPS67
Chiến lược vận hành theo quy trình tuần tự 5 bước trên mỗi nến đóng cửa:
- Khởi tạo ngày giao dịch & đồng hồ phiên: Hệ thống tính
tradingDayKeytheo múi giờAsia/Ho_Chi_Minh. Khi sang ngày mới (newTradingDay), bộ đếmtradesTodayđược reset về0. Đồng thời, tính toáncurrentMinutevàcurrentCloseMinuteđể kiểm soát khung giờ vào lệnh và giờ đóng phiên. - Tính toán kênh giá & các chỉ báo nền: Cập nhật
upperBand,lowerBand,middleBand,atr,averageVolume, và giá trịh1ConfirmedEMA/h1ConfirmedClosetừ khung H1. - Phát hiện Setup (
rawLongSignal/rawShortSignal): Kiểm tra xem giá đóng cửa có phá vỡ biên kênh Donchian hay không (longBreakout/shortBreakout), sau đó đối chiếu qua các bộ lọc hướng nến, khoảng đệm ATR, đột biến khối lượng và xu hướng H1. - Kiểm tra điều kiện thực thi (
canTrade) & Gửi lệnh: Chỉ khi trạng thái tài khoản đangFLAT, số lệnh trong ngày< maximumTradesPerDay, thỏa mãn phiên giao dịch, chưa chạm giờ đóng phiên14:45, nến đã đóng (barstate.isconfirmed) và không bị tín hiệu xung đột hai chiều (not ambiguousSignal), bot mới gửi lệnhstrategy.entryvà tăngtradesTodaylên1. - Quản trị & Tất toán vị thế: Ngay khi có vị thế mở (
positionLonghoặcpositionShort), bot đặt cặp lệnh bảo vệstrategy.exitvớiSL = 5.0điểm vàTP = 15.0điểm. Nếu đến nến cuối phiên (finalSessionBar) mà vị thế vẫn còn mở, bot tự động gọistrategy.close_all(immediately=true)để đóng lệnh trước giờ ATC.
4. Điều kiện vào lệnh Long và Short của CNPS67
4.1. Điều kiện vào lệnh Long
Lệnh Long được kích hoạt (finalLongSignal = true) khi thỏa mãn đồng thời tất cả các điều kiện sau:
- Chiều giao dịch cho phép Long (
tradeDirectionlà"Long"hoặc"Both"— mặc định là"Long"). canTrade = truevà không có xung đột tín hiệu Short cùng nến (not ambiguousSignal).- Giá đóng cửa vượt biên trên Donchian (
close > upperBand). NếurequireFreshBreak = true, nến liền trước phải cóclose[1] <= upperBand[1](hoặcna(upperBand[1])). - Thỏa mãn các bộ lọc tùy chọn (nếu được bật):
requireCandleDirection:close > open.requireBreakoutBuffer:close - upperBand >= atr * breakoutBufferATR.requireVolumeSpike:volume >= averageVolume * volumeSpikeFactor.useH1EMABias:h1ConfirmedClose > h1ConfirmedEMA.
4.2. Điều kiện vào lệnh Short
Lệnh Short được kích hoạt (finalShortSignal = true) khi thỏa mãn đồng thời tất cả các điều kiện sau:
- Chiều giao dịch cho phép Short (
tradeDirectionlà"Short"hoặc"Both"). canTrade = truevà không có xung đột tín hiệu Long cùng nến (not ambiguousSignal).- Giá đóng cửa thủng biên dưới Donchian (
close < lowerBand). NếurequireFreshBreak = true, nến liền trước phải cóclose[1] >= lowerBand[1](hoặcna(lowerBand[1])). - Thỏa mãn các bộ lọc tùy chọn (nếu được bật):
requireCandleDirection:close < open.requireBreakoutBuffer:lowerBand - close >= atr * breakoutBufferATR.requireVolumeSpike:volume >= averageVolume * volumeSpikeFactor.useH1EMABias:h1ConfirmedClose < h1ConfirmedEMA.
4.3. Điều kiện kiểm soát giao dịch chung
Biến canTrade đóng vai trò “cổng an toàn” cho mọi lệnh vào mới, yêu cầu đủ 5 yếu tố:
- Trạng thái Flat (
positionFlat):strategy.position_size == 0, không nhồi lệnh (pyramiding = 0). - Giới hạn số lệnh/ngày (
dailyTradeLimitOK):tradesToday < maximumTradesPerDay(mặc định tối đa2lệnh/ngày). - Khung giờ vào lệnh (
sessionOK): Nếu bậtuseSessionFilter = true, thời gian mở nến phải nằm trong khoảng09:00đến14:30theo múi giờAsia/Ho_Chi_Minh. - Trước giờ đóng phiên:
currentCloseMinute < sessionEndTotal(luôn chặn mở lệnh mới nếu giờ đóng nến đã chạm hoặc vượt14:45, kể cả khi tắtuseSessionFilter). - Xác nhận đóng nến (
barstate.isconfirmed): Chỉ khớp lệnh khi nến hiện tại đã hoàn tất.
5. Quản trị Stop Loss, Take Profit và Thoát lệnh
5.1. Cơ chế Stop Loss và khoảng cách cố định
CNPS67 áp dụng cơ chế dừng lỗ cố định theo điểm tuyệt đối tính từ giá khớp lệnh trung bình (strategy.position_avg_price), giúp trader dễ dàng kiểm soát mức lỗ tối đa trên mỗi hợp đồng VN30F1M:
- Long SL (
activeLongSL):entryPrice - stopLossPoints(mặc định-5.0điểm). - Short SL (
activeShortSL):entryPrice + stopLossPoints(mặc định+5.0điểm).
5.2. Cơ chế Take Profit và Đóng vị thế cuối phiên
Bot không sử dụng Break Even hay Trailing Stop, thay vào đó giữ nguyên mục tiêu lợi nhuận cố định với tỷ lệ Risk:Reward = 1:3 để tối ưu hóa các con sóng breakout mạnh:
- Long TP (
activeLongTP):entryPrice + takeProfitPoints(mặc định+15.0điểm). - Short TP (
activeShortTP):entryPrice - takeProfitPoints(mặc định-15.0điểm). - Đóng vị thế cuối phiên (
Session End): Tại nến giao dịch cócurrentMinute < 14:45vàcurrentCloseMinute >= 14:45(finalSessionBar), nếu vẫn còn vị thế mở (strategy.position_size != 0), bot kích hoạtstrategy.close_all(immediately=true)để thoát toàn bộ trạng thái trước phiên ATC. - Khi vị thế vừa đóng (
positionJustClosed), toàn bộ các biếnactiveLongSL,activeLongTP,activeShortSL,activeShortTPđược xóa vềna.
5.3. Bảng tổng hợp cơ chế bảo vệ vị thế
| Cơ chế thoát lệnh | Chiều áp dụng | Công thức / Điều kiện kích hoạt | Hành động của Bot |
|---|---|---|---|
| Stop Loss cố định | Long / Short | entryPrice - 5.0 (Long) hoặc entryPrice + 5.0 (Short) | Cắt lỗ ngay khi giá chạm mức stop qua strategy.exit |
| Take Profit cố định | Long / Short | entryPrice + 15.0 (Long) hoặc entryPrice - 15.0 (Short) | Chốt lời ngay khi giá chạm mức limit qua strategy.exit |
| Session End Force Close | Long / Short | currentMinute < 14:45 và currentCloseMinute >= 14:45 | Gọi strategy.close_all(immediately=true) đóng toàn bộ lệnh |
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 phái sinh VN30F1M (ví dụ
HNX:VN30F1M) trên TradingView, chọn khung thời gian giao dịch phù hợp (thường là 5m hoặc 15m). - Nhấn vào tab Pine Editor ở thanh công cụ phía dưới màn hình.
- Xóa code mẫu mặc định, sao chép toàn bộ mã nguồn CNPS67 DONCHIAN-BREAKOUT ở 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 đồ và xem kết quả kiểm thử trên tab Strategy Tester.
- Vào phần Settings (biểu tượng bánh răng) của chiến lược nếu muốn bật thêm các bộ lọc (
Breakout Strength,Volume,H1 EMA) hoặc thay đổiTrade Directionsang"Both".
Cách đọc bảng chẩn đoán (Diagnostics Table)
Khi bật tùy chọn Show Diagnostics? trong mục Display, bot sẽ vẽ một bảng thống kê 2 cột × 16 dòng ở góc trên bên phải biểu đồ (position.top_right):
| Dòng hiển thị | Giá trị / Ý nghĩa thực tế |
|---|---|
| CNPS67 | Hiển thị khung thời gian hiện tại của biểu đồ (timeframe.period) |
| Upper / Middle / Lower | Giá trị 3 đường biên của kênh Donchian tại nến hiện tại |
| Bull Breaks / Bear Breaks | Tổng số lần giá phá vỡ biên trên (freshLongBreak) và biên dưới (freshShortBreak) |
| Long Setups / Short Setups | Tổng số setup hợp lệ sau khi đã qua tất cả bộ lọc (rawLongSignal / rawShortSignal) |
| ATR | Giá trị biến động ATR(14) hiện tại |
| Volume OK | Trạng thái bộ lọc khối lượng (YES / NO) |
| Long H1 Bias / Short H1 Bias | Trạng thái bộ lọc xu hướng H1 EMA (YES / NO) |
| Long Entries / Short Entries | Tổng số lệnh Long và Short đã thực sự khớp trong lịch sử |
| Trades Today | Số lệnh đã vào trong ngày hiện tại trên tổng giới hạn (tradesToday / maximumTradesPerDay) |
| Position | Trạng thái vị thế hiện tại (LONG, SHORT hoặc FLAT) |
7. Cách thiết lập cảnh báo tín hiệu giao dịch (Alert)
Để nhận thông báo tự động về Telegram, Webhook hoặc ứng dụng TradingView 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 TradingView.
- Tại mục Condition, chọn tên chiến lược CNPS67 DONCHIAN-BREAKOUT.
- Tại ô Message, xóa nội dung mặc định và điền chính xác cú pháp:
{{strategy.order.alert_message}} - Nhấn Create để kích hoạt cảnh báo. Lưu ý: nếu bạn tick chọn
Disable SL / TP Alerts?trong cài đặt bot, các thông báo chốt lời/cắt lỗ sẽ được tắt và chỉ giữ lại thông báo vào lệnh và đóng phiên.
Bảng thông điệp Alert của CNPS67
| Sự kiện | Nội dung thông điệp (alert_message / alert_profit / alert_loss) |
|---|---|
| Vào lệnh Long | 🟢 VÀO VỊ THẾ LONG (Donchian Breakout)🎯 Giá vào: <close>🛑 SL dự kiến: <close - stopLossPoints>🎯 TP dự kiến: <close + takeProfitPoints> |
| Vào lệnh Short | 🔴 VÀO VỊ THẾ SHORT (Donchian Breakout)🎯 Giá vào: <close>🛑 SL dự kiến: <close + stopLossPoints>🎯 TP dự kiến: <close - takeProfitPoints> |
| Chốt lời Long | 💰 CHỐT LỜI LONG (TP HIT)🎯 Giá chốt: <activeLongTP> |
| Cắt lỗ Long | 🛑 CẮT LỖ LONG (SL HIT)🎯 Giá cắt: <activeLongSL> |
| Chốt lời Short | 💰 CHỐT LỜI SHORT (TP HIT)🎯 Giá chốt: <activeShortTP> |
| Cắt lỗ Short | 🛑 CẮT LỖ SHORT (SL HIT)🎯 Giá cắt: <activeShortSL> |
| Đóng hết phiên | ⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End)🎯 Giá đóng: <close> |
Kết luận
CNPS67 Donchian Breakout là một hệ thống giao dịch phái sinh gọn nhẹ, minh bạch và kỷ luật cao. Nhờ cơ chế kênh Donchian không tự tham chiếu kết hợp tỷ lệ SL 5 điểm / TP 15 điểm (R:R 1:3) và giới hạn tối đa 2 lệnh/ngày, bot đặc biệt phù hợp với các giai đoạn thị trường VN30F1M có xu hướng rõ ràng sau khi tích lũy biên độ hẹp. Khi thị trường đi ngang (sideway) kéo dài, trader có thể cân nhắc bật thêm bộ lọc H1 EMA Bias hoặc Volume Spike để hạn chế nhiễu.
Bạn có thể tham khảo thêm các hệ thống giao dịch khác trên hệ sinh thái: 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.





