Thứ Ba, 01/12/202601/12/2026

Hướng Dẫn Sử Dụng Bot CNPS70 - ADX Trend Acceleration cho VN30F1M

Bot 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).

Hướng dẫn sử dụng Bot CNPS70 cho VN30F1M
Hướng dẫn sử dụng Bot CNPS70 cho VN30F1M
Mục lục
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 > -DI hoặ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ướng EMA khung hiện tại và xu hướng H1 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:

  1. Độ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, -DI và ADX. Bot chỉ tìm kiếm cơ hội khi ADX đạt ngưỡng tối thiểu (minimumADX = 18.0) và đang có độ dốc đi lên trong adxRisingBars nến liên tiếp.
  2. 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 longBase và shortBase. Khi requireFreshSignal = 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ừ false sang true (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.
  3. 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ến Volume / SMA(Volume), vị thế giá so với EMA(50) trên khung biểu đồ hiện tại và xu hướng EMA(50) trên nến H1 đã đóng cửa.
  4. 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, Short hoặc Both) và tự động tất toán vị thế ở nến kết phiên (14:45 theo 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 codeNhãn hiển thị (TradingView)Giá trị mặc địnhGhi chú
ADXdiLengthDI Length14Chu kỳ tính +DI / -DI
ADXadxSmoothingADX Smoothing14Chu kỳ làm mượt ADX
ADXminimumADXMinimum ADX18.0Ngưỡng ADX tối thiểu để xác nhận có xu hướng
ADXadxRisingBarsADX Rising Bars1Số nến ADX phải tăng liên tiếp (1–10)
ADXrequireFreshSignalRequire Fresh ADX Signal?trueChỉ lấy tín hiệu mới chuyển trạng thái
DI FilterrequireDISeparationRequire DI Separation?falseBật/tắt lọc độ chênh lệch +DI và -DI
DI FilterminimumDIDifferenceMinimum +DI / -DI Difference5.0Chênh lệch tối thiểu giữa +DI và -DI
ATRatrLengthATR Length14Chu kỳ tính ATR
ATRrequireATRExpansionRequire ATR Expansion?falseBật/tắt lọc mở rộng biến động ATR
ATRatrAverageLengthATR Average Length20Chu kỳ SMA của ATR
ATRatrExpansionFactorMinimum ATR / Average ATR1.0Hệ số ATR tối thiểu so với trung bình
VolumerequireVolumeSpikeRequire Volume Spike?falseBật/tắt lọc đột biến khối lượng
VolumevolumeAverageLengthVolume Average Length20Chu kỳ SMA của Volume
VolumevolumeSpikeFactorVolume Spike Factor1.20Hệ số Volume tối thiểu so với trung bình
EMA TrenduseEMATrendUse EMA Trend Filter?falseBật/tắt lọc xu hướng theo EMA khung hiện tại
EMA TrendemaLengthEMA Length50Chu kỳ đường EMA khung biểu đồ
H1 TrenduseH1EMABiasUse Confirmed H1 EMA Bias?falseBật/tắt lọc xu hướng H1 từ nến đã đóng
H1 Trendh1EMALengthH1 EMA Length50Chu kỳ đường EMA trên khung 60 phút
Risk ManagementstopLossPointsStop Loss (Points)5.0Mức cắt lỗ cố định (điểm)
Risk ManagementtakeProfitPointsTake Profit (Points)15.0Mức chốt lời cố định (điểm)
Trade ControlmaximumTradesPerDayMaximum Trades Per Day2Số lệnh tối đa mỗi ngày (1–20)
Trade ControltradeDirectionTrade Direction"Long"Tùy chọn: "Long", "Short", "Both"
SessionuseSessionFilterUse Entry Session Filter?falseBật/tắt lọc khung giờ vào lệnh
SessionstrategyTimezoneStrategy Timezone"Asia/Ho_Chi_Minh"Múi giờ tính phiên giao dịch
SessionsessionStartHour / MinuteSession Start09:00Giờ bắt đầu nhận lệnh khi bật lọc phiên
SessionlastEntryHour / MinuteLast Entry14:30Giờ cuối cùng cho phép mở lệnh mới
SessionsessionEndHour / MinuteForce Close14:45Giờ cưỡng chế đóng toàn bộ vị thế
Alerts & DisplaydisableSLTPAlertsDisable SL / TP Alerts?falseTắt/bật thông báo khi khớp SL hoặc TP
DisplayshowActiveSLTPShow Active SL / TP?trueHiển thị đường SL/TP đang chạy trên chart
DisplayshowEMA, showH1EMA, showSignalMarkers, showDiagnosticsCác tùy chọn hiển thịfalseBậ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 tra not na(adx) and adx >= minimumADX (mặc định 18.0), đảm bảo thị trường đã thoát khỏi vùng tích lũy yếu.
  • adxRising: Kiểm tra ta.rising(adx, adxRisingBars) (mặc định 1 nến), tức ADX hiện tại cao hơn ADX của adxRisingBars nế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ật requireDISeparation, bot yêu cầu thêm math.abs(diPlus - diMinus) >= minimumDIDifference (mặc định 5.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ánh ta.atr(14) với trung bình trượt ta.sma(atr, 20). Khi bật, yêu cầu atr >= averageATR * atrExpansionFactor (mặc định 1.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ới ta.sma(volume, 20). Khi bật, yêu cầu volume >= averageVolume * volumeSpikeFactor (mặc định 1.20) để xác nhận dòng tiền tham gia.
  • EMA Trend (useEMATrend): Dùng ta.ema(close, 50) trên khung biểu đồ hiện tại, chỉ cho phép Long khi close > ema và Short khi close < ema.
  • Confirmed H1 EMA Bias (useH1EMABias): Lấy dữ liệu từ khung 60 phút bằng request.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ầu h1Close > h1EMA, Short yêu cầu h1Close < 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:

  1. Khởi tạo ngày giao dịch & khung giờ: Theo múi giờ Asia/Ho_Chi_Minh, biến tradingDayKey kiểm tra sang ngày mới để reset bộ đếm tradesToday := 0. Đồng thời, Time Engine tính currentMinute và currentCloseMinute để xác định trạng thái sessionOK và finalSessionBar.
  2. Tính toán động lượng và bộ lọc: Bot tính [diPlus, diMinus, adx], xác định longBase / shortBase, sau đó qua Fresh Signal Engine để tạo longTrigger / shortTrigger. Kết hợp với 5 bộ lọc tùy chọn (diSeparationOK, atrFilterOK, volumeOK, EMA, H1 EMA) để cho ra rawLongSignal và rawShortSignal.
  3. 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ãn sessionOK, thời gian đóng nến nhỏ hơn 14:45 (currentCloseMinute < sessionEndTotal) và nến đã đóng cửa xác nhận (barstate.isconfirmed). Đồng thời kiểm tra not ambiguousSignal (không đồng thời có cả Long và Short) và notEnteredThisBar.
  4. Gửi lệnh & đếm thống kê: Khi finalLongSignal hoặc finalShortSignal hợp lệ, bot gửi lệnh strategy.entry, tăng tradesToday, cập nhật lastEntryBar và bộ đếm chẩn đoán.
  5. Quản trị vị thế & đóng lệnh cuối phiên: Ngay khi có vị thế, bot thiết lập strategy.exit với mức SL/TP cố định. Nếu đến nến finalSessionBar (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: tradeDirection là "Long" hoặc "Both" (allowLong = true).
  • Điều kiện nền ADX Long (longBase):
    • adx >= minimumADX (mặc định 18.0).
    • ta.rising(adx, adxRisingBars) là true (mặc định 1 nến tăng).
    • diPlus > diMinus (+DI nằm trên -DI).
  • Tín hiệu mới (longTrigger): Nếu requireFreshSignal = true, longBase phải vừa chuyển từ false ở nến trước sang true ở 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ật requireDISeparation).
    • atr >= averageATR * atrExpansionFactor (nếu bật requireATRExpansion).
    • volume >= averageVolume * volumeSpikeFactor (nếu bật requireVolumeSpike).
    • close > ema (nếu bật useEMATrend).
    • h1Close > h1EMA từ nến H1 đã đóng (nếu bật useH1EMABias).
  • Không xung đột & đủ điều kiện canTrade: rawShortSignal khô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: tradeDirection là "Short" hoặc "Both" (allowShort = true). Lưu ý: mặc định trong code tradeDirection = "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 định 18.0).
    • ta.rising(adx, adxRisingBars) là true.
    • diMinus > diPlus (-DI nằm trên +DI).
  • Tín hiệu mới (shortTrigger): Nếu requireFreshSignal = true, shortBase phải vừa chuyển từ false sang true.
  • Các bộ lọc tùy chọn (nếu được bật):
    • diSeparationOK, atrFilterOK, volumeOK tương tự chiều Long.
    • close < ema (nếu bật useEMATrend).
    • h1Close < h1EMA từ nến H1 đã đóng (nếu bật useH1EMABias).
  • Không xung đột & đủ điều kiện canTrade: rawLongSignal khô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 đa 2 lệnh/ngày).
  • Khung giờ giao dịch:
    • Nếu bật useSessionFilter = true, thời gian mở nến phải từ 09:00 trở đ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ước 14:45) để không mở lệnh mới sát giờ đóng cửa.
  • Xác nhận đóng nến & chống trùng lặp: barstate.isconfirmed phải là true và 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 định 15.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
  • 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ặc activeShortSL/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:45 và currentCloseMinute >= 14:45), nếu strategy.position_size != 0, bot lập tức gọi strategy.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 codeGiá trị mặc địnhCách thức hoạt động
Cắt lỗ (Stop Loss)stopLossPoints5.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)takeProfitPoints15.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 / Minute14:45Gọi strategy.close_all(immediately=true) tại nến kết phiên.
Giới hạn lệnh/ngàymaximumTradesPerDay2 lệnhKhóa mở lệnh mới khi tradesToday >= 2, reset đầu ngày mới.
Chống nhồi lệnhpyramiding=0, positionFlat0Chỉ 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

  1. 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).
  2. Nhấn vào tab Pine Editor ở thanh công cụ phía dưới màn hình.
  3. 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.
  4. 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 đồ).
  5. 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ật Show 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ủa ADX, +DI, -DI và mức thay đổi adx - 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ái YES / NO củ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ái YES / NO củ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, 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 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:

  1. 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.
  2. Tại mục Condition, chọn đúng tên chiến lược CNPS70 ADX TREND ACCELERATION.
  3. 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}}
  4. 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ạtLoại thông điệp trong codeNội dung thông báo thực tế
Vào lệnh Longalert_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 Shortalert_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 Longalert_profit (strategy.exit)💰 CHỐT LỜI LONG (TP HIT) kèm Giá chốt (activeLongTP).
Cắt lỗ Longalert_loss (strategy.exit)🛑 CẮT LỖ LONG (SL HIT) kèm Giá cắt (activeLongSL).
Chốt lời Shortalert_profit (strategy.exit)💰 CHỐT LỜI SHORT (TP HIT) kèm Giá chốt (activeShortTP).
Cắt lỗ Shortalert_loss (strategy.exit)🛑 CẮT LỖ SHORT (SL HIT) kèm Giá cắt (activeShortSL).
Đóng hết phiênalert_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.

Đinh Mạnh Đạt

Nhà nghiên cứu định lượng, chuyên sâu về dữ liệu Open Interest và quản trị vị thế.

Bản tin phái sinh mỗi phiên
Nhận bản tin mỗi phiên + Dự báo Nhịp đập phái sinh

Giao dịch & cuộc sống

Xem tất cả →
Cộng đồng