Hướng Dẫn Sử Dụng Bot CNPS70 - ADX Trend Acceleration cho VN30F1M
TradingviewBot CNPS70 ADX Trend Acceleration giao dịch VN30F1M theo pha tăng tốc xu hướng dựa trên ADX và +DI/-DI, kết hợp cơ chế Fresh Signal và quản trị rủi ro SL 5 điểm - TP 15 điểm (R:R 1:3).

Mục lục
Trong giao dịch hợp đồng tương lai chỉ số VN30F1M, một trong những rủi ro phổ biến nhất là vào lệnh quá sớm khi thị trường đang đi ngang (sideway) không có động lượng, hoặc vào lệnh đuổi liên tục trong cùng một nhịp sóng đã kéo dài. Khi thiếu bộ đo lường sức mạnh xu hướng khách quan, nhà giao dịch rất dễ bị quét dừng lỗ liên tiếp bởi các nhịp nhiễu trong phiên.
Bot CNPS70 — tên đầy đủ trong mã nguồn là CNPS70 ADX TREND ACCELERATION — được lập trình trên nền tảng Pine Script v6 của TradingView nhằm giải quyết trực tiếp bài toán bắt đúng thời điểm xu hướng bắt đầu tăng tốc. Thay vì giao dịch theo cảm tính hoặc chỉ dựa vào giao cắt giá đơn thuần, hệ thống sử dụng chỉ báo ADX kết hợp với +DI/-DI để nhận diện pha tăng tốc động lượng và chỉ kích hoạt lệnh khi xuất hiện tín hiệu mới hợp lệ.
Những điểm nổi bật cốt lõi của CNPS70 ADX Trend Acceleration:
- Bắt nhịp tăng tốc xu hướng bằng ADX & DMI: Yêu cầu đồng thời
ADX >= 18.0,ADXđang tăng (ta.rising) và sự phân tách rõ phe kiểm soát (+DI > -DIhoặc-DI > +DI). - Cơ chế Fresh Signal Engine: Chỉ kích hoạt tín hiệu ngay tại nến đầu tiên điều kiện nền chuyển từ sai sang đúng, tránh vào lệnh lặp lại liên tục trong cùng một pha ADX tăng.
- Hệ thống bộ lọc tùy chọn đa tầng: Hỗ trợ bật/tắt linh hoạt 5 lớp lọc nâng cao gồm khoảng cách DI (
DI Separation), mở rộng biến động (ATR Expansion), đột biến khối lượng (Volume Spike), xu hướngEMAkhung hiện tại và xu hướngH1 EMAđã xác nhận. - Quản trị rủi ro kỷ luật tỷ lệ 1:3: Mặc định cắt lỗ cố định 5 điểm và chốt lời 15 điểm, giới hạn tối đa 2 lệnh/ngày và tự động đóng vị thế khi hết phiên lúc 14:45.
1. CNPS70 ADX Trend Acceleration là gì?
CNPS70 ADX Trend Acceleration là chiến lược giao dịch theo động lượng xu hướng (Trend Acceleration) dành cho thị trường phái sinh VN30F1M. Bot được xây dựng xoay quanh 4 trụ cột kỹ thuật chính:
- Động cơ đo sức mạnh xu hướng (ADX & DI Engine): Sử dụng hàm
ta.dmi(diLength, adxSmoothing)để tính đồng thời+DI,-DIvàADX. Bot chỉ tìm kiếm cơ hội khiADXđạt ngưỡng tối thiểu (minimumADX = 18.0) và đang có độ dốc đi lên trongadxRisingBarsnến liên tiếp. - Bộ lọc Fresh Signal (Chống trùng lặp tín hiệu): Hệ thống theo dõi trạng thái
longBasevàshortBase. KhirequireFreshSignal = true, tín hiệu chỉ hợp lệ tại thời điểm điều kiện nền vừa chuyển từfalsesangtrue(longBase and not longBase[1]), giúp loại bỏ việc nhồi lệnh hoặc vào lại liên tục trên cùng một nhịp đẩy. - Hệ thống 5 bộ lọc xác nhận tùy chọn: Cho phép người dùng tinh chỉnh độ khắt khe của tín hiệu thông qua độ chênh lệch
|+DI - -DI|, tỷ lệATR / SMA(ATR), đột biếnVolume / SMA(Volume), vị thế giá so vớiEMA(50)trên khung biểu đồ hiện tại và xu hướngEMA(50)trên nếnH1đã đóng cửa. - Kiểm soát rủi ro & phiên giao dịch: Áp dụng SL/TP cố định theo điểm (
5.0/15.0), giới hạn số lệnh trong ngày (maximumTradesPerDay = 2), chọn chiều giao dịch (Long,ShorthoặcBoth) và tự động tất toán vị thế ở nến kết phiên (14:45theo múi giờAsia/Ho_Chi_Minh).
Bảng thông số mặc định
| Nhóm thông số | Tên biến trong code | Nhãn hiển thị (TradingView) | Giá trị mặc định | Ghi chú |
|---|---|---|---|---|
| ADX | diLength | DI Length | 14 | Chu kỳ tính +DI / -DI |
| ADX | adxSmoothing | ADX Smoothing | 14 | Chu kỳ làm mượt ADX |
| ADX | minimumADX | Minimum ADX | 18.0 | Ngưỡng ADX tối thiểu để xác nhận có xu hướng |
| ADX | adxRisingBars | ADX Rising Bars | 1 | Số nến ADX phải tăng liên tiếp (1–10) |
| ADX | requireFreshSignal | Require Fresh ADX Signal? | true | Chỉ lấy tín hiệu mới chuyển trạng thái |
| DI Filter | requireDISeparation | Require DI Separation? | false | Bật/tắt lọc độ chênh lệch +DI và -DI |
| DI Filter | minimumDIDifference | Minimum +DI / -DI Difference | 5.0 | Chênh lệch tối thiểu giữa +DI và -DI |
| ATR | atrLength | ATR Length | 14 | Chu kỳ tính ATR |
| ATR | requireATRExpansion | Require ATR Expansion? | false | Bật/tắt lọc mở rộng biến động ATR |
| ATR | atrAverageLength | ATR Average Length | 20 | Chu kỳ SMA của ATR |
| ATR | atrExpansionFactor | Minimum ATR / Average ATR | 1.0 | Hệ số ATR tối thiểu so với trung bình |
| Volume | requireVolumeSpike | Require Volume Spike? | false | Bật/tắt lọc đột biến khối lượng |
| Volume | volumeAverageLength | Volume Average Length | 20 | Chu kỳ SMA của Volume |
| Volume | volumeSpikeFactor | Volume Spike Factor | 1.20 | Hệ số Volume tối thiểu so với trung bình |
| EMA Trend | useEMATrend | Use EMA Trend Filter? | false | Bật/tắt lọc xu hướng theo EMA khung hiện tại |
| EMA Trend | emaLength | EMA Length | 50 | Chu kỳ đường EMA khung biểu đồ |
| H1 Trend | useH1EMABias | Use Confirmed H1 EMA Bias? | false | Bật/tắt lọc xu hướng H1 từ nến đã đóng |
| H1 Trend | h1EMALength | H1 EMA Length | 50 | Chu kỳ đường EMA trên khung 60 phút |
| Risk Management | stopLossPoints | Stop Loss (Points) | 5.0 | Mức cắt lỗ cố định (điểm) |
| Risk Management | takeProfitPoints | Take Profit (Points) | 15.0 | Mức chốt lời cố định (điểm) |
| Trade Control | maximumTradesPerDay | Maximum Trades Per Day | 2 | Số lệnh tối đa mỗi ngày (1–20) |
| Trade Control | tradeDirection | Trade Direction | "Long" | Tùy chọn: "Long", "Short", "Both" |
| Session | useSessionFilter | Use Entry Session Filter? | false | Bật/tắt lọc khung giờ vào lệnh |
| Session | strategyTimezone | Strategy Timezone | "Asia/Ho_Chi_Minh" | Múi giờ tính phiên giao dịch |
| Session | sessionStartHour / Minute | Session Start | 09:00 | Giờ bắt đầu nhận lệnh khi bật lọc phiên |
| Session | lastEntryHour / Minute | Last Entry | 14:30 | Giờ cuối cùng cho phép mở lệnh mới |
| Session | sessionEndHour / Minute | Force Close | 14:45 | Giờ cưỡng chế đóng toàn bộ vị thế |
| Alerts & Display | disableSLTPAlerts | Disable SL / TP Alerts? | false | Tắt/bật thông báo khi khớp SL hoặc TP |
| Display | showActiveSLTP | Show Active SL / TP? | true | Hiển thị đường SL/TP đang chạy trên chart |
| Display | showEMA, showH1EMA, showSignalMarkers, showDiagnostics | Các tùy chọn hiển thị | false | Bật/tắt EMA, mũi tên L/S và bảng chẩn đoán |
Source Code CNPS70 ADX Trend Acceleration
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="CNPS70 ADX TREND ACCELERATION", shorttitle="CNPS70 ADX", 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)
// ============================================================================
// CNPS70 ADX TREND ACCELERATION
//
// LONG:
// ADX >= MINIMUM ADX
// ADX RISING
// +DI > -DI
// NEW VALID SIGNAL
// -> LONG
//
// SHORT:
// ADX >= MINIMUM ADX
// ADX RISING
// -DI > +DI
// NEW VALID SIGNAL
// -> SHORT
//
// DEFAULT SL = 5 POINTS
// DEFAULT TP = 15 POINTS
// ============================================================================
// ============================================================================
// SECTION 1: ADX SETTINGS
// ============================================================================
diLength = input.int(14, "DI Length", minval=2, group="ADX")
adxSmoothing = input.int(14, "ADX Smoothing", minval=2, group="ADX")
minimumADX = input.float(18.0, "Minimum ADX", minval=1.0, step=1.0, group="ADX")
adxRisingBars = input.int(1, "ADX Rising Bars", minval=1, maxval=10, group="ADX")
requireFreshSignal = input.bool(true, "Require Fresh ADX Signal?", group="ADX")
// ============================================================================
// SECTION 2: DI SEPARATION FILTER
// ============================================================================
requireDISeparation = input.bool(false, "Require DI Separation?", group="DI Filter")
minimumDIDifference = input.float(5.0, "Minimum +DI / -DI Difference", minval=0, step=0.5, group="DI Filter")
// ============================================================================
// SECTION 3: ATR FILTER
// ============================================================================
atrLength = input.int(14, "ATR Length", minval=1, group="ATR")
requireATRExpansion = input.bool(false, "Require ATR Expansion?", group="ATR")
atrAverageLength = input.int(20, "ATR Average Length", minval=2, group="ATR")
atrExpansionFactor = input.float(1.0, "Minimum ATR / Average ATR", minval=0.1, step=0.05, group="ATR")
// ============================================================================
// SECTION 4: 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 5: EMA TREND FILTER
// ============================================================================
useEMATrend = input.bool(false, "Use EMA Trend Filter?", group="EMA Trend")
emaLength = input.int(50, "EMA Length", minval=1, group="EMA Trend")
// ============================================================================
// SECTION 6: H1 TREND FILTER
// ============================================================================
useH1EMABias = input.bool(false, "Use Confirmed H1 EMA Bias?", group="H1 Trend")
h1EMALength = input.int(50, "H1 EMA Length", minval=1, group="H1 Trend")
// ============================================================================
// SECTION 7: 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 8: 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 9: 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 10: ALERT CONTROL
// ============================================================================
disableSLTPAlerts = input.bool(false, "Disable SL / TP Alerts?", group="Alerts")
// ============================================================================
// SECTION 11: DISPLAY
// ============================================================================
showEMA = input.bool(false, "Show EMA?", group="Display")
showH1EMA = input.bool(false, "Show H1 EMA?", group="Display")
showSignalMarkers = input.bool(false, "Show Signal Markers?", group="Display")
showActiveSLTP = input.bool(true, "Show Active SL / TP?", group="Display")
showDiagnostics = input.bool(false, "Show Diagnostics?", group="Display")
// ============================================================================
// SECTION 12: 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 currentCloseMinute <= lastEntryTotal)
bool sessionOK = (not useSessionFilter or entrySession)
// ============================================================================
// SECTION 13: 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 14: ADX AND DI ENGINE
// ============================================================================
//
// ta.dmi returns:
//
// +DI
// -DI
// ADX
//
// ============================================================================
[diPlus, diMinus, adx] = ta.dmi(diLength, adxSmoothing)
// ============================================================================
// SECTION 15: ADX STRENGTH
// ============================================================================
bool adxStrong = (not na(adx) and adx >= minimumADX)
bool adxRising = (not na(adx[adxRisingBars]) and ta.rising(adx, adxRisingBars))
float adxChange = (adx - adx[1])
// ============================================================================
// SECTION 16: DIRECTIONAL MOVEMENT
// ============================================================================
bool bullishDI = (diPlus > diMinus)
bool bearishDI = (diMinus > diPlus)
float diDifference = (math.abs(diPlus - diMinus))
bool diSeparationOK = (not requireDISeparation or diDifference >= minimumDIDifference)
// ============================================================================
// SECTION 17: ATR ENGINE
// ============================================================================
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 18: VOLUME ENGINE
// ============================================================================
float averageVolume = ta.sma(volume, volumeAverageLength)
bool volumeSpike = (not na(averageVolume) and volume >= averageVolume * volumeSpikeFactor)
bool volumeOK = (not requireVolumeSpike or volumeSpike)
// ============================================================================
// SECTION 19: EMA TREND
// ============================================================================
float ema = ta.ema(close, emaLength)
bool longEMAOK = (not useEMATrend or close > ema)
bool shortEMAOK = (not useEMATrend or close < ema)
// ============================================================================
// SECTION 20: CONFIRMED H1 EMA
// ============================================================================
//
// Uses previous completed H1 candle.
//
// Recommended for chart timeframes below H1.
//
// ============================================================================
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 longBiasOK = (not useH1EMABias or (not na(h1EMA) and not na(h1Close) and h1Close > h1EMA))
bool shortBiasOK = (not useH1EMABias or (not na(h1EMA) and not na(h1Close) and h1Close < h1EMA))
// ============================================================================
// SECTION 21: ADX BASE CONDITIONS
// ============================================================================
bool longBase = (adxStrong and adxRising and bullishDI)
bool shortBase = (adxStrong and adxRising and bearishDI)
// ============================================================================
// SECTION 22: FRESH SIGNAL ENGINE
// ============================================================================
//
// A new signal occurs when all base conditions
// become true after previously being false.
//
// This avoids continuous repeated entries
// while ADX remains in the same rising phase.
//
// ============================================================================
bool freshLongBase = (longBase and not longBase[1])
bool freshShortBase = (shortBase and not shortBase[1])
bool longTrigger = (requireFreshSignal ? freshLongBase : longBase)
bool shortTrigger = (requireFreshSignal ? freshShortBase : shortBase)
// ============================================================================
// SECTION 23: RAW SIGNALS
// ============================================================================
bool rawLongSignal = (longTrigger and diSeparationOK and atrFilterOK and volumeOK and longEMAOK and longBiasOK)
bool rawShortSignal = (shortTrigger and diSeparationOK and atrFilterOK and volumeOK and shortEMAOK and shortBiasOK)
// ============================================================================
// SECTION 24: 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 25: CAN TRADE
// ============================================================================
bool dailyTradeLimitOK = (tradesToday < maximumTradesPerDay)
bool canTrade = (positionFlat and dailyTradeLimitOK and sessionOK and currentCloseMinute < sessionEndTotal and barstate.isconfirmed)
// ============================================================================
// SECTION 26: SIGNAL PROTECTION
// ============================================================================
bool ambiguousSignal = (rawLongSignal and rawShortSignal)
var int lastEntryBar = na
bool notEnteredThisBar = (na(lastEntryBar) or bar_index != lastEntryBar)
bool finalLongSignal = (canTrade and notEnteredThisBar and allowLong and rawLongSignal and not ambiguousSignal)
bool finalShortSignal = (canTrade and notEnteredThisBar and allowShort and rawShortSignal and not ambiguousSignal)
// ============================================================================
// SECTION 27: DIAGNOSTIC COUNTERS
// ============================================================================
var int adxStrongCount = 0
var int adxRisingCount = 0
var int bullDIPhaseCount = 0
var int bearDIPhaseCount = 0
var int longBaseCount = 0
var int shortBaseCount = 0
var int longSignalCount = 0
var int shortSignalCount = 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 adxStrong and not adxStrong[1]
adxStrongCount += 1
if adxRising and not adxRising[1]
adxRisingCount += 1
if bullishDI and not bullishDI[1]
bullDIPhaseCount += 1
if bearishDI and not bearishDI[1]
bearDIPhaseCount += 1
if freshLongBase
longBaseCount += 1
if freshShortBase
shortBaseCount += 1
if rawLongSignal and not rawLongSignal[1]
longSignalCount += 1
if rawShortSignal and not rawShortSignal[1]
shortSignalCount += 1
// ============================================================================
// SECTION 28: LONG ENTRY
// ============================================================================
if finalLongSignal
strategy.entry("Long", strategy.long, comment="ADX Acceleration Long", alert_message="🟢 VÀO VỊ THẾ LONG (ADX Trend Acceleration)\\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
longEntryCount += 1
lastEntryBar := bar_index
// ============================================================================
// SECTION 29: SHORT ENTRY
// ============================================================================
if finalShortSignal
strategy.entry("Short", strategy.short, comment="ADX Acceleration Short", alert_message="🔴 VÀO VỊ THẾ SHORT (ADX Trend Acceleration)\\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
shortEntryCount += 1
lastEntryBar := bar_index
// ============================================================================
// SECTION 30: ACTIVE RISK LEVELS
// ============================================================================
var float activeLongSL = na
var float activeLongTP = na
var float activeShortSL = na
var float activeShortTP = na
// ============================================================================
// SECTION 31: 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 32: 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 33: POSITION CLEANUP
// ============================================================================
if positionJustClosed
activeLongSL := na
activeLongTP := na
activeShortSL := na
activeShortTP := na
// ============================================================================
// SECTION 34: SESSION END
// ============================================================================
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 35: EMA DISPLAY
// ============================================================================
plot(showEMA and useEMATrend ? ema : na, title="EMA Trend", color=color.orange, linewidth=2)
plot(showH1EMA and useH1EMABias ? h1EMA : na, title="Confirmed H1 EMA", color=color.blue, linewidth=1)
// ============================================================================
// SECTION 36: 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 37: 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 38: SIGNAL MARKERS
// ============================================================================
plotshape(showSignalMarkers and rawLongSignal, title="ADX Long Setup", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.tiny, text="L", textcolor=color.white)
plotshape(showSignalMarkers and rawShortSignal, title="ADX Short Setup", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.tiny, text="S", textcolor=color.white)
// ============================================================================
// SECTION 39: DIAGNOSTICS TABLE
// ============================================================================
var table diagnostics = table.new(position.top_right, 2, 19, border_width=1)
if showDiagnostics and barstate.islast
string positionText = "FLAT"
if positionLong
positionText := "LONG"
if positionShort
positionText := "SHORT"
table.cell(diagnostics, 0, 0, "CNPS70")
table.cell(diagnostics, 1, 0, timeframe.period)
table.cell(diagnostics, 0, 1, "ADX")
table.cell(diagnostics, 1, 1, str.tostring(adx, "#.##"))
table.cell(diagnostics, 0, 2, "+DI")
table.cell(diagnostics, 1, 2, str.tostring(diPlus, "#.##"))
table.cell(diagnostics, 0, 3, "-DI")
table.cell(diagnostics, 1, 3, str.tostring(diMinus, "#.##"))
table.cell(diagnostics, 0, 4, "ADX Change")
table.cell(diagnostics, 1, 4, str.tostring(adxChange, "#.##"))
table.cell(diagnostics, 0, 5, "ADX Strong")
table.cell(diagnostics, 1, 5, adxStrong ? "YES" : "NO")
table.cell(diagnostics, 0, 6, "ADX Rising")
table.cell(diagnostics, 1, 6, adxRising ? "YES" : "NO")
table.cell(diagnostics, 0, 7, "Bull DI")
table.cell(diagnostics, 1, 7, bullishDI ? "YES" : "NO")
table.cell(diagnostics, 0, 8, "Bear DI")
table.cell(diagnostics, 1, 8, bearishDI ? "YES" : "NO")
table.cell(diagnostics, 0, 9, "Long Bases")
table.cell(diagnostics, 1, 9, str.tostring(longBaseCount))
table.cell(diagnostics, 0, 10, "Short Bases")
table.cell(diagnostics, 1, 10, str.tostring(shortBaseCount))
table.cell(diagnostics, 0, 11, "Long Signals")
table.cell(diagnostics, 1, 11, str.tostring(longSignalCount))
table.cell(diagnostics, 0, 12, "Short Signals")
table.cell(diagnostics, 1, 12, str.tostring(shortSignalCount))
table.cell(diagnostics, 0, 13, "Volume OK")
table.cell(diagnostics, 1, 13, volumeOK ? "YES" : "NO")
table.cell(diagnostics, 0, 14, "ATR OK")
table.cell(diagnostics, 1, 14, atrFilterOK ? "YES" : "NO")
table.cell(diagnostics, 0, 15, "Long Entries")
table.cell(diagnostics, 1, 15, str.tostring(longEntryCount))
table.cell(diagnostics, 0, 16, "Short Entries")
table.cell(diagnostics, 1, 16, str.tostring(shortEntryCount))
table.cell(diagnostics, 0, 17, "Trades Today")
table.cell(diagnostics, 1, 17, str.tostring(tradesToday) + " / " + str.tostring(maximumTradesPerDay))
table.cell(diagnostics, 0, 18, "Position")
table.cell(diagnostics, 1, 18, positionText)
2. Những khái niệm kỹ thuật cốt lõi trong CNPS70
2.1. Chỉ báo ADX, +DI, -DI và pha tăng tốc (ADX Acceleration)
Bot sử dụng bộ chỉ báo Directional Movement Index thông qua ta.dmi(diLength, adxSmoothing) với chu kỳ mặc định 14 và 14:
adxStrong: Kiểm tranot na(adx) and adx >= minimumADX(mặc định18.0), đảm bảo thị trường đã thoát khỏi vùng tích lũy yếu.adxRising: Kiểm trata.rising(adx, adxRisingBars)(mặc định1nến), tứcADXhiện tại cao hơnADXcủaadxRisingBarsnến trước đó, xác nhận động lượng xu hướng đang gia tốc.bullishDI(diPlus > diMinus) vàbearishDI(diMinus > diPlus): Xác định phe mua hay phe bán đang chiếm ưu thế. Nếu bậtrequireDISeparation, bot yêu cầu thêmmath.abs(diPlus - diMinus) >= minimumDIDifference(mặc định5.0) để loại bỏ các pha giao cắt hẹp.
2.2. Cơ chế Fresh Signal Engine
Điều kiện nền được định nghĩa là longBase = adxStrong and adxRising and bullishDI và shortBase = adxStrong and adxRising and bearishDI. Trong thực tế, khi một xu hướng mạnh hình thành, longBase hoặc shortBase có thể duy trì trạng thái true qua nhiều nến liên tiếp.
Để tránh vào lệnh dồn dập trong cùng một con sóng, bot tạo bộ lọc chuyển trạng thái:
freshLongBase = longBase and not longBase[1]freshShortBase = shortBase and not shortBase[1]
Khi requireFreshSignal = true (mặc định), bot chỉ phát tín hiệu tại đúng cây nến đầu tiên mà điều kiện nền chuyển từ false sang true.
2.3. Bộ lọc biến động, khối lượng và xu hướng đa khung (Tùy chọn)
Ngoài lõi ADX, CNPS70 tích hợp sẵn 4 bộ lọc tùy chọn giúp người dùng tinh chỉnh theo từng giai đoạn thị trường:
- ATR Expansion (
requireATRExpansion): So sánhta.atr(14)với trung bình trượtta.sma(atr, 20). Khi bật, yêu cầuatr >= averageATR * atrExpansionFactor(mặc định1.0) để tránh vào lệnh lúc biên độ nến quá hẹp. - Volume Spike (
requireVolumeSpike): So sánh khối lượng nến hiện tại vớita.sma(volume, 20). Khi bật, yêu cầuvolume >= averageVolume * volumeSpikeFactor(mặc định1.20) để xác nhận dòng tiền tham gia. - EMA Trend (
useEMATrend): Dùngta.ema(close, 50)trên khung biểu đồ hiện tại, chỉ cho phép Long khiclose > emavà Short khiclose < ema. - Confirmed H1 EMA Bias (
useH1EMABias): Lấy dữ liệu từ khung60phút bằngrequest.security(syminfo.tickerid, "60", ...)với chỉ số[1](nến H1 đã đóng cửa hoàn toàn) vàlookahead=barmerge.lookahead_onđể chống repaint. Long yêu cầuh1Close > h1EMA, Short yêu cầuh1Close < h1EMA.
3. Nguyên lý hoạt động của CNPS70
Hệ thống CNPS70 ADX Trend Acceleration vận hành theo quy trình tuần tự 5 bước trên mỗi cây nến:
- Khởi tạo ngày giao dịch & khung giờ: Theo múi giờ
Asia/Ho_Chi_Minh, biếntradingDayKeykiểm tra sang ngày mới để reset bộ đếmtradesToday := 0. Đồng thời, Time Engine tínhcurrentMinutevàcurrentCloseMinuteđể xác định trạng tháisessionOKvàfinalSessionBar. - Tính toán động lượng và bộ lọc: Bot tính
[diPlus, diMinus, adx], xác địnhlongBase/shortBase, sau đó qua Fresh Signal Engine để tạolongTrigger/shortTrigger. Kết hợp với 5 bộ lọc tùy chọn (diSeparationOK,atrFilterOK,volumeOK,EMA,H1 EMA) để cho rarawLongSignalvàrawShortSignal. - Kiểm tra điều kiện giao dịch (
canTrade) & bảo vệ tín hiệu: Bot chỉ cho phép vào lệnh khi không có vị thế mở (positionFlat), chưa vượt quámaximumTradesPerDay, thỏa mãnsessionOK, thời gian đóng nến nhỏ hơn14:45(currentCloseMinute < sessionEndTotal) và nến đã đóng cửa xác nhận (barstate.isconfirmed). Đồng thời kiểm tranot ambiguousSignal(không đồng thời có cả Long và Short) vànotEnteredThisBar. - Gửi lệnh & đếm thống kê: Khi
finalLongSignalhoặcfinalShortSignalhợp lệ, bot gửi lệnhstrategy.entry, tăngtradesToday, cập nhậtlastEntryBarvà bộ đếm chẩn đoán. - Quản trị vị thế & đóng lệnh cuối phiên: Ngay khi có vị thế, bot thiết lập
strategy.exitvới mức SL/TP cố định. Nếu đến nếnfinalSessionBar(14:45) mà vẫn còn vị thế mở,strategy.close_all(immediately=true)sẽ tự động đóng lệnh hết phiên.
4. Điều kiện vào lệnh Long và Short của CNPS70
4.1. Điều kiện vào lệnh Long
Một lệnh Long (finalLongSignal) chỉ được kích hoạt khi thỏa mãn đồng thời toàn bộ các điều kiện sau:
- Chiều giao dịch cho phép Long:
tradeDirectionlà"Long"hoặc"Both"(allowLong = true). - Điều kiện nền ADX Long (
longBase):adx >= minimumADX(mặc định18.0).ta.rising(adx, adxRisingBars)làtrue(mặc định1nến tăng).diPlus > diMinus(+DInằm trên-DI).
- Tín hiệu mới (
longTrigger): NếurequireFreshSignal = true,longBasephải vừa chuyển từfalseở nến trước sangtrueở nến hiện tại. - Các bộ lọc tùy chọn (nếu được bật):
math.abs(diPlus - diMinus) >= minimumDIDifference(nếu bậtrequireDISeparation).atr >= averageATR * atrExpansionFactor(nếu bậtrequireATRExpansion).volume >= averageVolume * volumeSpikeFactor(nếu bậtrequireVolumeSpike).close > ema(nếu bậtuseEMATrend).h1Close > h1EMAtừ nến H1 đã đóng (nếu bậtuseH1EMABias).
- Không xung đột & đủ điều kiện
canTrade:rawShortSignalkhông đồng thời xảy ra (not ambiguousSignal) và thỏa mãn toàn bộ điều kiện kiểm soát giao dịch chung.
4.2. Điều kiện vào lệnh Short
Một lệnh Short (finalShortSignal) chỉ được kích hoạt khi thỏa mãn đồng thời toàn bộ các điều kiện sau:
- Chiều giao dịch cho phép Short:
tradeDirectionlà"Short"hoặc"Both"(allowShort = true). Lưu ý: mặc định trong codetradeDirection = "Long", bạn cần chuyển sang"Short"hoặc"Both"nếu muốn bot đánh chiều Short. - Điều kiện nền ADX Short (
shortBase):adx >= minimumADX(mặc định18.0).ta.rising(adx, adxRisingBars)làtrue.diMinus > diPlus(-DInằm trên+DI).
- Tín hiệu mới (
shortTrigger): NếurequireFreshSignal = true,shortBasephải vừa chuyển từfalsesangtrue. - Các bộ lọc tùy chọn (nếu được bật):
diSeparationOK,atrFilterOK,volumeOKtương tự chiều Long.close < ema(nếu bậtuseEMATrend).h1Close < h1EMAtừ nến H1 đã đóng (nếu bậtuseH1EMABias).
- Không xung đột & đủ điều kiện
canTrade:rawLongSignalkhông đồng thời xảy ra và thỏa mãn điều kiện kiểm soát giao dịch chung.
4.3. Điều kiện kiểm soát giao dịch chung
Toàn bộ lệnh vào mới đều phải đi qua cổng kiểm soát canTrade và Signal Protection:
- Trạng thái phẳng (Flat):
strategy.position_size == 0(pyramiding=0, không nhồi lệnh khi đang giữ vị thế). - Giới hạn số lệnh/ngày:
tradesToday < maximumTradesPerDay(mặc định tối đa2lệnh/ngày). - Khung giờ giao dịch:
- Nếu bật
useSessionFilter = true, thời gian mở nến phải từ09:00trở đi và thời gian đóng nến không vượt quá14:30(entrySession). - Luôn yêu cầu
currentCloseMinute < sessionEndTotal(trước14:45) để không mở lệnh mới sát giờ đóng cửa.
- Nếu bật
- Xác nhận đóng nến & chống trùng lặp:
barstate.isconfirmedphải làtruevàbar_index != lastEntryBar.
5. Quản trị Stop Loss, Take Profit và Thoát lệnh
5.1. Cơ chế Stop Loss và bộ lọc Risk
CNPS70 sử dụng cơ chế cắt lỗ cố định theo số điểm tuyệt đối (stopLossPoints, mặc định 5.0 điểm) tính từ giá khớp lệnh trung bình strategy.position_avg_price:
- Vị thế Long:
activeLongSL = entryPrice - stopLossPoints - Vị thế Short:
activeShortSL = entryPrice + stopLossPoints
Chiến lược không sử dụng giới hạn Min–Max Risk động theo ATR hay giới hạn lỗ theo ngày (Daily Loss Limit) bằng tiền, mà kiểm soát rủi ro thông qua mức SL cố định 5.0 điểm kết hợp giới hạn tối đa 2 lệnh/ngày.
5.2. Cơ chế Take Profit và Thoát lệnh hết phiên
- Chốt lời cố định (Take Profit): Tính theo
takeProfitPoints(mặc định15.0điểm), tạo tỷ lệ Risk:Reward chuẩn 1:3:- Vị thế Long:
activeLongTP = entryPrice + takeProfitPoints - Vị thế Short:
activeShortTP = entryPrice - takeProfitPoints
- Vị thế Long:
- Không sử dụng Break Even / Trailing Stop: Trong mã nguồn hiện tại, bot giữ nguyên hai mốc
activeLongSL/activeLongTP(hoặcactiveShortSL/activeShortTP) cho đến khi chạm SL, chạm TP hoặc hết phiên. - Thoát lệnh hết phiên (Session End): Khi nến chạm ngưỡng
finalSessionBar(currentMinute < 14:45vàcurrentCloseMinute >= 14:45), nếustrategy.position_size != 0, bot lập tức gọistrategy.close_all(immediately=true, comment="Session End")để đóng toàn bộ vị thế trước giờ ATC, tránh rủi ro giữ lệnh qua đêm. Khi vị thế đóng (positionJustClosed), các biến đường SL/TP được dọn dẹp vềna.
5.3. Bảng tổng hợp cơ chế bảo vệ vị thế
| Cơ chế bảo vệ | Tham số / Biến code | Giá trị mặc định | Cách thức hoạt động |
|---|---|---|---|
| Cắt lỗ (Stop Loss) | stopLossPoints | 5.0 điểm | Đặt lệnh dừng cố định cách entryPrice 5 điểm (SL Long / SL Short). |
| Chốt lời (Take Profit) | takeProfitPoints | 15.0 điểm | Đặt lệnh giới hạn cố định cách entryPrice 15 điểm (TP Long / TP Short). |
| Đóng hết phiên (Force Close) | sessionEndHour / Minute | 14:45 | Gọi strategy.close_all(immediately=true) tại nến kết phiên. |
| Giới hạn lệnh/ngày | maximumTradesPerDay | 2 lệnh | Khóa mở lệnh mới khi tradesToday >= 2, reset đầu ngày mới. |
| Chống nhồi lệnh | pyramiding=0, positionFlat | 0 | Chỉ cho phép vào lệnh mới khi đang không có vị thế. |
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 (khung thời gian gợi ý dưới H1 như M5 hoặc M15, đặc biệt khi bật bộ lọc
H1 EMA Bias). - Nhấn vào tab Pine Editor ở thanh công cụ phía dưới màn hình.
- Xóa toàn bộ code mặc định, sau đó sao chép toàn bộ mã nguồn CNPS70 ADX Trend Acceleration ở Mục 1 và dán vào Pine Editor.
- Nhấn Save (Lưu), đặt tên tùy chọn rồi nhấn Add to chart (Thêm vào biểu đồ).
- Mở biểu tượng bánh răng (Settings) của chiến lược để điều chỉnh các thông số như
Trade Direction(chọn"Both"nếu muốn giao dịch cả 2 chiều Long/Short), bật các bộ lọc nâng cao hoặc bậtShow Diagnostics?vàShow Signal Markers?.
Cách đọc bảng chẩn đoán (Diagnostics Table)
Khi bật tùy chọn Show Diagnostics? (showDiagnostics = true), bot sẽ vẽ một bảng gồm 2 cột x 19 hàng ở góc trên bên phải biểu đồ (position.top_right) hiển thị trạng thái theo thời gian thực ở nến cuối cùng:
- Hàng 0 (
CNPS70): Khung thời gian biểu đồ đang chạy (timeframe.period). - Hàng 1–4 (
ADX,+DI,-DI,ADX Change): Giá trị hiện tại củaADX,+DI,-DIvà mức thay đổiadx - adx[1]của nến hiện tại. - Hàng 5–8 (
ADX Strong,ADX Rising,Bull DI,Bear DI): Trạng tháiYES/NOcủa từng điều kiện nền cấu thành tín hiệu. - Hàng 9–12 (
Long Bases,Short Bases,Long Signals,Short Signals): Bộ đếm lịch sử số lần xuất hiện điều kiện nền mới (freshLongBase/freshShortBase) và số lần tín hiệu thô (rawLongSignal/rawShortSignal) vượt qua toàn bộ bộ lọc. - Hàng 13–14 (
Volume OK,ATR OK): Trạng tháiYES/NOcủa bộ lọc khối lượng và biến động ATR tại nến hiện tại. - Hàng 15–16 (
Long Entries,Short Entries): Tổng số lệnh Long và Short đã được khớp thực tế trong toàn bộ giai đoạn backtest. - Hàng 17–18 (
Trades Today,Position): Số lệnh đã vào trong ngày hiện tại trên tổng mức cho phép (ví dụ1 / 2) và trạng thái vị thế hiện tại (FLAT,LONGhoặcSHORT).
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ề điện thoại, email hoặc kết nối Webhook đẩy lệnh từ TradingView, bạn thiết lập Alert theo các bước sau:
- 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ía trên biểu đồ TradingView.
- Tại mục Condition, chọn đúng tên chiến lược CNPS70 ADX TREND ACCELERATION.
- Tại mục Message, xóa nội dung mặc định và nhập chính xác cú pháp:
{{strategy.order.alert_message}} - Cấu hình thông báo (App, Email, Webhook URL) theo nhu cầu và nhấn Create.
(Lưu ý: Nếu bạn chỉ muốn nhận thông báo vào lệnh và đóng phiên, có thể tích chọn Disable SL / TP Alerts? trong phần Settings của bot để tắt cảnh báo khi chạm SL/TP).
Bảng thông điệp Alert của CNPS70
| Sự kiện kích hoạt | Loại thông điệp trong code | Nội dung thông báo thực tế |
|---|---|---|
| Vào lệnh Long | alert_message (strategy.entry) | 🟢 VÀO VỊ THẾ LONG (ADX Trend Acceleration) kèm Giá vào (close), SL dự kiến (close - stopLossPoints) và TP dự kiến (close + takeProfitPoints). |
| Vào lệnh Short | alert_message (strategy.entry) | 🔴 VÀO VỊ THẾ SHORT (ADX Trend Acceleration) kèm Giá vào (close), SL dự kiến (close + stopLossPoints) và TP dự kiến (close - takeProfitPoints). |
| Chốt lời Long | alert_profit (strategy.exit) | 💰 CHỐT LỜI LONG (TP HIT) kèm Giá chốt (activeLongTP). |
| Cắt lỗ Long | alert_loss (strategy.exit) | 🛑 CẮT LỖ LONG (SL HIT) kèm Giá cắt (activeLongSL). |
| Chốt lời Short | alert_profit (strategy.exit) | 💰 CHỐT LỜI SHORT (TP HIT) kèm Giá chốt (activeShortTP). |
| Cắt lỗ Short | alert_loss (strategy.exit) | 🛑 CẮT LỖ SHORT (SL HIT) kèm Giá cắt (activeShortSL). |
| Đóng hết phiên | alert_message (strategy.close_all) | ⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End) kèm Giá đóng (close). |
Kết luận
Bot CNPS70 ADX Trend Acceleration là một hệ thống giao dịch VN30F1M có cấu trúc tinh gọn, minh bạch và kỷ luật cao. Điểm mạnh lớn nhất của bot nằm ở việc kết hợp bộ đo gia tốc xu hướng ADX + DMI với cơ chế Fresh Signal Engine để bắt đúng nhịp khởi phát động lượng, tránh sa lầy vào các pha sideway hoặc vào lệnh lặp lại trong cùng một con sóng. Hệ thống quản trị rủi ro cố định SL 5 điểm – TP 15 điểm (R:R 1:3) cùng cơ chế đóng vị thế cuối phiên 14:45 giúp kiểm soát chặt chẽ mức độ phơi nhiễm rủi ro trong ngày. Bot phát huy hiệu quả tốt nhất trong các phiên thị trường có xu hướng rõ ràng và biên độ mở rộng sau giai đoạn tích lũy.
Bạn có thể tham khảo thêm các hệ thống giao dịch khác trên phaisinh.online như Bot CNPS50 - Trend Analysis V2 và Bot CNPS49 - Daily Open.
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.





