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

Hướng Dẫn Sử Dụng Bot CNPS69 - Triple EMA Alignment V2 cho VN30F1M

Bot CNPS69 (Triple EMA Alignment V2) tự động giao dịch VN30F1M theo cấu trúc 3 đường EMA (9-21-55), bắt nhịp hồi về EMA21 bằng bộ máy trạng thái chống ghi đè và xác nhận nến lấy lại EMA9.

Hướng dẫn sử dụng Bot CNPS69 cho VN30F1M
Hướng dẫn sử dụng Bot CNPS69 cho VN30F1M
Mục lục
Mục lục

Khi giao dịch hợp đồng tương lai VN30F1M trong ngày, một trong những sai lầm phổ biến nhất của nhà giao dịch theo xu hướng là vào lệnh đuổi khi giá đã đi quá xa đường trung bình, hoặc bị nhiễu liên tục khi giá kiểm tra lại (pullback) vùng hỗ trợ/kháng cự động nhiều lần khiến tín hiệu bị ghi đè sai lệch.

CNPS69 TRIPLE EMA ALIGNMENT V2 (tên ngắn: CNPS69 EMA V2) là chiến lược giao dịch tự động viết bằng Pine Script v6 trên TradingView, được thiết kế để giải quyết triệt để bài toán bắt nhịp hồi (pullback) thuận xu hướng trên VN30F1M. Phiên bản V2 khắc phục lỗi ghi đè trạng thái pullback khi giá chạm EMA21 nhiều lần liên tiếp, giúp đếm cửa sổ xác nhận chính xác và nhất quán.

Những điểm nổi bật cốt lõi của Bot CNPS69:

  • Cấu trúc đồng thuận 3 đường EMA (9 - 21 - 55): Chỉ giao dịch khi xu hướng ngắn, trung và dài hạn sắp xếp theo trật tự rõ ràng (EMA9 > EMA21 > EMA55 cho Long hoặc ngược lại cho Short).
  • Bộ máy trạng thái Pullback cố định (Fixed Pullback State Engine): Ghi nhận nhịp chạm EMA21 một lần duy nhất (pendingBull/pendingBear), không bị reset bộ đếm thời gian bởi các cú chạm lặp lại.
  • Hệ thống bộ lọc tùy chọn đa tầng: Hỗ trợ lọc độ dốc EMA55, độ tách biệt giữa EMA9 và EMA55 theo ATR, đột biến khối lượng (Volume Spike) và xu hướng khung H1 (request.security).
  • Quản trị rủi ro chặt chẽ & kiểm soát phiên: Cắt lỗ/Chốt lời cố định theo điểm (mặc định SL 5 điểm – TP 15 điểm, tỷ lệ R:R 1:3), giới hạn tối đa 2 lệnh/ngày và tự động đóng toàn bộ vị thế khi hết phiên (14:45).

1. CNPS69 Triple EMA Alignment V2 là gì?

CNPS69 Triple EMA Alignment V2 là chiến lược giao dịch theo xu hướng kết hợp bắt nhịp hồi (Trend-Following Pullback) vận hành dựa trên 4 trụ cột kỹ thuật chính:

  1. Hệ thống 3 đường EMA (EMA Engine): Sử dụng EMA Fast (9), EMA Middle (21) và EMA Slow (55) để xác định trạng thái đồng thuận tăng (bullishAlignment) hoặc đồng thuận giảm (bearishAlignment).
  2. Bộ máy phát hiện và lưu trạng thái Pullback (Pullback State Engine): Phát hiện thời điểm giá hồi về chạm EMA21 nhưng vẫn giữ được cấu trúc xu hướng trên/dưới EMA55, sau đó mở cửa sổ chờ tối đa pullbackBarsMax nến (mặc định 5 nến) để đợi tín hiệu xác nhận.
  3. Bộ xác nhận & Bộ lọc tùy chọn (Confirmation & Filter Engine): Xác nhận nến thuận chiều, đóng cửa lấy lại EMA9 (hoặc phá đỉnh/đáy nến trước), kết hợp các bộ lọc tùy chọn như độ dốc EMA55, khoảng cách |EMA9 - EMA55| theo ATR, đột biến khối lượng và xu hướng H1 EMA50.
  4. Kiểm soát lệnh, phiên và rủi ro (Trade Control, Session & Risk Management): Giới hạn số lệnh mỗi ngày, chọn chiều giao dịch (Long, Short, Both), lọc khung giờ vào lệnh, tự động đóng vị thế cuối phiên và đặt sẵn SL/TP theo điểm cố định.

Bảng thông số mặc định

Nhóm thông sốTên biến trong codeMô tảGiá trị mặc định
EMAemaFastLengthChu kỳ EMA nhanh9
EMAemaMiddleLengthChu kỳ EMA trung bình21
EMAemaSlowLengthChu kỳ EMA chậm55
PullbackpullbackBarsMaxSố nến tối đa chờ xác nhận sau pullback5
PullbackrequireFastEMAReclaimYêu cầu đóng cửa vượt EMA nhanhtrue
PullbackrequirePreviousHighLowBreakYêu cầu phá đỉnh/đáy nến trướcfalse
PullbackrequireBullBearCandleYêu cầu nến xác nhận tăng/giảmtrue
FiltersrequireEMASlopeLọc độ dốc EMA chậmfalse (lookback = 5)
FiltersrequireEMASeparationLọc độ tách biệt EMA theo ATRfalse (min = 0.20 * ATR(14))
FiltersrequireVolumeSpikeLọc đột biến khối lượngfalse (factor = 1.20, SMA 20)
FiltersuseH1EMABiasLọc xu hướng khung H1false (H1 EMA = 50)
Risk ManagementstopLossPointsMức cắt lỗ cố định (điểm)5.0
Risk ManagementtakeProfitPointsMức chốt lời cố định (điểm)15.0
Trade ControlmaximumTradesPerDaySố lệnh tối đa mỗi ngày2
Trade ControltradeDirectionChiều giao dịch cho phép"Long" (Long / Short / Both)
SessionuseSessionFilterBật lọc khung giờ vào lệnhfalse (Asia/Ho_Chi_Minh)
SessionsessionStartHour / MinuteGiờ bắt đầu phiên09:00
SessionlastEntryHour / MinuteGiờ ngừng vào lệnh mới14:30
SessionsessionEndHour / MinuteGiờ bắt buộc đóng toàn bộ vị thế14:45
Alerts & DisplaydisableSLTPAlertsTắt cảnh báo SL/TPfalse
Alerts & DisplayshowEMAs / showActiveSLTPHiển thị EMA và đường SL/TPtrue
Alerts & DisplayshowDiagnosticsHiển thị bảng chẩn đoánfalse

Source Code CNPS69 Triple EMA Alignment V2

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="CNPS69 TRIPLE EMA ALIGNMENT V2", shorttitle="CNPS69 EMA V2", 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)

// ============================================================================
// CNPS69 TRIPLE EMA ALIGNMENT - V2 FIXED
//
// LONG:
// EMA9 > EMA21 > EMA55
// -> Price touches EMA21
// -> Store pullback
// -> Bullish confirmation within N bars
// -> Close above EMA9
// -> LONG
//
// SHORT: Reverse logic
//
// Fixed: Pullback state is NOT overwritten by repeated touches.
// ============================================================================
// ============================================================================
// SECTION 1: EMA
// ============================================================================
emaFastLength = input.int(9, "Fast EMA", minval=1, group="EMA")
emaMiddleLength = input.int(21, "Middle EMA", minval=2, group="EMA")
emaSlowLength = input.int(55, "Slow EMA", minval=3, group="EMA")

// ============================================================================
// SECTION 2: PULLBACK
// ============================================================================
pullbackBarsMax = input.int(5, "Maximum Bars After Pullback", minval=1, maxval=30, group="Pullback")
requireFastEMAReclaim = input.bool(true, "Require Close Beyond Fast EMA?", group="Pullback")
requirePreviousHighLowBreak = input.bool(false, "Require Previous High/Low Break?", group="Pullback")
requireBullBearCandle = input.bool(true, "Require Bullish/Bearish Candle?", group="Pullback")

// ============================================================================
// SECTION 3: OPTIONAL FILTERS
// ============================================================================
requireEMASlope = input.bool(false, "Require Slow EMA Slope?", group="Filters")
emaSlopeLookback = input.int(5, "Slope Lookback", minval=1, group="Filters")
requireEMASeparation = input.bool(false, "Require EMA Separation?", group="Filters")
minimumSeparationATR = input.float(0.20, "Minimum EMA Separation / ATR", minval=0, step=0.05, group="Filters")
requireVolumeSpike = input.bool(false, "Require Volume Spike?", group="Filters")
volumeAverageLength = input.int(20, "Volume Average Length", minval=2, group="Filters")
volumeSpikeFactor = input.float(1.20, "Volume Spike Factor", minval=0.1, step=0.1, group="Filters")
useH1EMABias = input.bool(false, "Use Confirmed H1 EMA Bias?", group="Filters")
h1EMALength = input.int(50, "H1 EMA Length", minval=1, group="Filters")
atrLength = input.int(14, "ATR Length", minval=1, group="Filters")

// ============================================================================
// SECTION 4: 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 5: 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 6: 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 7: ALERTS
// ============================================================================
disableSLTPAlerts = input.bool(false, "Disable SL / TP Alerts?", group="Alerts")

// ============================================================================
// SECTION 8: DISPLAY
// ============================================================================
showEMAs = input.bool(true, "Show EMAs?", group="Display")
showH1EMA = input.bool(false, "Show H1 EMA?", group="Display")
showPullbackMarkers = input.bool(false, "Show Pullback Markers?", group="Display")
showSignalMarkers = input.bool(false, "Show Signal Markers?", group="Display")
showActiveSLTP = input.bool(true, "Show SL / TP?", group="Display")
showDiagnostics = input.bool(false, "Show Diagnostics?", group="Display")

// ============================================================================
// SECTION 9: 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
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 10: EMA ENGINE
// ============================================================================
float emaFast = ta.ema(close, emaFastLength)
float emaMiddle = ta.ema(close, emaMiddleLength)
float emaSlow = ta.ema(close, emaSlowLength)
bool bullishAlignment = emaFast > emaMiddle and emaMiddle > emaSlow
bool bearishAlignment = emaFast < emaMiddle and emaMiddle < emaSlow

// ============================================================================
// SECTION 11: FILTER ENGINE
// ============================================================================
float atr = ta.atr(atrLength)
bool longSlopeOK = not requireEMASlope or (not na(emaSlow[emaSlopeLookback]) and emaSlow > emaSlow[emaSlopeLookback])
bool shortSlopeOK = not requireEMASlope or (not na(emaSlow[emaSlopeLookback]) and emaSlow < emaSlow[emaSlopeLookback])
float emaSeparation = math.abs(emaFast - emaSlow)
bool separationOK = not requireEMASeparation or (not na(atr) and atr > 0 and emaSeparation >= minimumSeparationATR * atr)
float averageVolume = ta.sma(volume, volumeAverageLength)
bool volumeSpike = not na(averageVolume) and volume >= averageVolume * volumeSpikeFactor
bool volumeOK = not requireVolumeSpike or volumeSpike
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 12: PULLBACK DETECTION
// ============================================================================
bool bullishPullback = (bullishAlignment and low <= emaMiddle and close > emaSlow)
bool bearishPullback = (bearishAlignment and high >= emaMiddle and close < emaSlow)

// ============================================================================
// SECTION 13: PULLBACK STATE ENGINE - FIXED
// ============================================================================
//
// A pullback is registered once.
// Repeated touches will NOT reset the timer.
//
// ============================================================================
var bool pendingBull = false
var bool pendingBear = false
var int bullPullbackBar = na
var int bearPullbackBar = na
var int bullPullbackCount = 0
var int bearPullbackCount = 0
var int bullConfirmCount = 0
var int bearConfirmCount = 0
if newTradingDay
    pendingBull := false
    pendingBear := false
    bullPullbackBar := na
    bearPullbackBar := na
if barstate.isconfirmed
    if pendingBull
        bool bullInvalid = not bullishAlignment or close < emaSlow
        bool bullExpired = bar_index - bullPullbackBar > pullbackBarsMax
        if bullInvalid or bullExpired
            pendingBull := false
            bullPullbackBar := na
    if pendingBear
        bool bearInvalid = not bearishAlignment or close > emaSlow
        bool bearExpired = bar_index - bearPullbackBar > pullbackBarsMax
        if bearInvalid or bearExpired
            pendingBear := false
            bearPullbackBar := na
    if not pendingBull and bullishPullback
        pendingBull := true
        bullPullbackBar := bar_index
        bullPullbackCount += 1
    if not pendingBear and bearishPullback
        pendingBear := true
        bearPullbackBar := bar_index
        bearPullbackCount += 1

// ============================================================================
// SECTION 14: VALID PULLBACK WINDOW
// ============================================================================
int barsSinceBullPullback = na(bullPullbackBar) ? -1 : bar_index - bullPullbackBar
int barsSinceBearPullback = na(bearPullbackBar) ? -1 : bar_index - bearPullbackBar
bool validBullPullback = (pendingBull and barsSinceBullPullback >= 1 and barsSinceBullPullback <= pullbackBarsMax)
bool validBearPullback = (pendingBear and barsSinceBearPullback >= 1 and barsSinceBearPullback <= pullbackBarsMax)

// ============================================================================
// SECTION 15: CONFIRMATION
// ============================================================================
bool bullishCandleOK = not requireBullBearCandle or close > open
bool bearishCandleOK = not requireBullBearCandle or close < open
bool longFastOK = not requireFastEMAReclaim or close > emaFast
bool shortFastOK = not requireFastEMAReclaim or close < emaFast
bool longBreakOK = not requirePreviousHighLowBreak or close > high[1]
bool shortBreakOK = not requirePreviousHighLowBreak or close < low[1]
bool longConfirmation = (bullishAlignment and bullishCandleOK and longFastOK and longBreakOK)
bool shortConfirmation = (bearishAlignment and bearishCandleOK and shortFastOK and shortBreakOK)

// ============================================================================
// SECTION 16: BASE SETUPS
// ============================================================================
bool longBase = validBullPullback and longConfirmation
bool shortBase = validBearPullback and shortConfirmation
bool rawLongSignal = (longBase and longSlopeOK and separationOK and volumeOK and longBiasOK)
bool rawShortSignal = (shortBase and shortSlopeOK and separationOK and volumeOK and shortBiasOK)

// ============================================================================
// SECTION 17: 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 18: TRADE CONTROL
// ============================================================================
bool canTrade = (positionFlat and tradesToday < maximumTradesPerDay 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 19: ENTRY COUNTERS
// ============================================================================
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 longBase
        bullConfirmCount += 1
    if shortBase
        bearConfirmCount += 1

// ============================================================================
// SECTION 20: LONG ENTRY
// ============================================================================
if finalLongSignal
    strategy.entry("Long", strategy.long, comment="Triple EMA Long", alert_message="🟢 VÀO VỊ THẾ LONG (Triple EMA Alignment)\\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
    pendingBull := false
    bullPullbackBar := na

// ============================================================================
// SECTION 21: SHORT ENTRY
// ============================================================================
if finalShortSignal
    strategy.entry("Short", strategy.short, comment="Triple EMA Short", alert_message="🔴 VÀO VỊ THẾ SHORT (Triple EMA Alignment)\\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
    pendingBear := false
    bearPullbackBar := na

// ============================================================================
// SECTION 22: ACTIVE RISK LEVELS
// ============================================================================
var float activeLongSL = na
var float activeLongTP = na
var float activeShortSL = na
var float activeShortTP = na

// ============================================================================
// SECTION 23: LONG EXIT
// ============================================================================
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 24: SHORT EXIT
// ============================================================================
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 25: CLEANUP
// ============================================================================
if positionJustClosed
    activeLongSL := na
    activeLongTP := na
    activeShortSL := na
    activeShortTP := na

// ============================================================================
// SECTION 26: 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 27: EMA DISPLAY
// ============================================================================
plot(showEMAs ? emaFast : na, "EMA Fast", color=color.aqua, linewidth=2)
plot(showEMAs ? emaMiddle : na, "EMA Middle", color=color.orange, linewidth=2)
plot(showEMAs ? emaSlow : na, "EMA Slow", color=color.purple, linewidth=2)
plot(showH1EMA and useH1EMABias ? h1EMA : na, "Confirmed H1 EMA", color=color.blue, linewidth=1)

// ============================================================================
// SECTION 28: SL TP DISPLAY
// ============================================================================
plot(showActiveSLTP and positionLong ? activeLongSL : na, "Long SL", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showActiveSLTP and positionLong ? activeLongTP : na, "Long TP", color=color.green, linewidth=2, style=plot.style_linebr)
plot(showActiveSLTP and positionShort ? activeShortSL : na, "Short SL", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showActiveSLTP and positionShort ? activeShortTP : na, "Short TP", color=color.green, linewidth=2, style=plot.style_linebr)

// ============================================================================
// SECTION 29: SIGNAL MARKERS
// ============================================================================
plotshape(showPullbackMarkers and bullishPullback, "Bullish Pullback", shape.circle, location.belowbar, color=color.aqua, size=size.tiny)
plotshape(showPullbackMarkers and bearishPullback, "Bearish Pullback", shape.circle, location.abovebar, color=color.orange, size=size.tiny)
plotshape(showSignalMarkers and rawLongSignal, "Long Signal", shape.triangleup, location.belowbar, color=color.green, size=size.tiny)
plotshape(showSignalMarkers and rawShortSignal, "Short Signal", shape.triangledown, location.abovebar, color=color.red, size=size.tiny)

// ============================================================================
// SECTION 30: DIAGNOSTICS
// ============================================================================
var table diagnostics = table.new(position.top_right, 2, 16, border_width=1)
if showDiagnostics and barstate.islast
    string trendText = bullishAlignment ? "BULLISH" : bearishAlignment ? "BEARISH" : "NEUTRAL"
    string positionText = positionLong ? "LONG" : positionShort ? "SHORT" : "FLAT"
    table.cell(diagnostics, 0, 0, "CNPS69 V2")
    table.cell(diagnostics, 1, 0, timeframe.period)
    table.cell(diagnostics, 0, 1, "EMA Fast")
    table.cell(diagnostics, 1, 1, str.tostring(emaFast, format.mintick))
    table.cell(diagnostics, 0, 2, "EMA Middle")
    table.cell(diagnostics, 1, 2, str.tostring(emaMiddle, format.mintick))
    table.cell(diagnostics, 0, 3, "EMA Slow")
    table.cell(diagnostics, 1, 3, str.tostring(emaSlow, format.mintick))
    table.cell(diagnostics, 0, 4, "Alignment")
    table.cell(diagnostics, 1, 4, trendText)
    table.cell(diagnostics, 0, 5, "Bull Pullbacks")
    table.cell(diagnostics, 1, 5, str.tostring(bullPullbackCount))
    table.cell(diagnostics, 0, 6, "Bear Pullbacks")
    table.cell(diagnostics, 1, 6, str.tostring(bearPullbackCount))
    table.cell(diagnostics, 0, 7, "Bull Confirms")
    table.cell(diagnostics, 1, 7, str.tostring(bullConfirmCount))
    table.cell(diagnostics, 0, 8, "Bear Confirms")
    table.cell(diagnostics, 1, 8, str.tostring(bearConfirmCount))
    table.cell(diagnostics, 0, 9, "Pending Long")
    table.cell(diagnostics, 1, 9, pendingBull ? "YES" : "NO")
    table.cell(diagnostics, 0, 10, "Pending Short")
    table.cell(diagnostics, 1, 10, pendingBear ? "YES" : "NO")
    table.cell(diagnostics, 0, 11, "Volume OK")
    table.cell(diagnostics, 1, 11, volumeOK ? "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 CNPS69

2.1. Đồng thuận 3 đường EMA (Triple EMA Alignment)

Bot tính toán 3 đường trung bình lũy thừa trên giá đóng cửa (close):

  • emaFast = ta.ema(close, 9) (vẽ màu xanh ngọc color.aqua)
  • emaMiddle = ta.ema(close, 21) (vẽ màu cam color.orange)
  • emaSlow = ta.ema(close, 55) (vẽ màu tím color.purple)

Trạng thái xu hướng được xác lập khi cả 3 đường xếp lớp theo đúng thứ tự:

  • Đồng thuận tăng (bullishAlignment): emaFast > emaMiddle and emaMiddle > emaSlow
  • Đồng thuận giảm (bearishAlignment): emaFast < emaMiddle and emaMiddle < emaSlow

2.2. Bộ máy trạng thái Pullback không ghi đè (Fixed Pullback State Engine)

Đây là cải tiến quan trọng nhất của bản V2 FIXED:

  • Phát hiện Pullback:
    • bullishPullback: Đang có bullishAlignment, giá thấp nhất chạm/thủng EMA21 (low <= emaMiddle) nhưng giá đóng cửa vẫn giữ trên EMA55 (close > emaSlow).
    • bearishPullback: Đang có bearishAlignment, giá cao nhất chạm/vượt EMA21 (high >= emaMiddle) nhưng giá đóng cửa vẫn nằm dưới EMA55 (close < emaSlow).
  • Cơ chế chống ghi đè: Khi not pendingBull and bullishPullback xảy ra tại nến đã đóng (barstate.isconfirmed), bot bật cờ pendingBull := true và lưu bullPullbackBar := bar_index. Nếu các nến tiếp theo tiếp tục chạm EMA21, điều kiện not pendingBull sẽ không thỏa mãn nên bullPullbackBar không bị reset.
  • Điều kiện hủy trạng thái chờ: pendingBull bị xóa (false) khi sang ngày mới (newTradingDay), mất đồng thuận hoặc đóng cửa dưới EMA55 (not bullishAlignment or close < emaSlow), hoặc quá hạn pullbackBarsMax nến (bar_index - bullPullbackBar > 5).
  • Cửa sổ Pullback hợp lệ (validBullPullback / validBearPullback): Yêu cầu barsSinceBullPullback >= 1 và <= pullbackBarsMax (tức nến xác nhận phải xuất hiện từ nến kế tiếp sau nến pullback trở đi, không vào ngay trên cùng nến chạm EMA21).

2.3. Hệ thống bộ lọc tùy chọn đa tầng (Filter Engine)

Ngoài điều kiện nến xác nhận, CNPS69 trang bị 4 bộ lọc tùy chọn (mặc định tắt để giữ độ nhạy, có thể bật khi thị trường nhiễu):

  • Độ dốc EMA chậm (requireEMASlope): Yêu cầu emaSlow > emaSlow[5] (Long) hoặc emaSlow < emaSlow[5] (Short).
  • Độ tách biệt EMA theo ATR (requireEMASeparation): Tính emaSeparation = math.abs(emaFast - emaSlow) và yêu cầu emaSeparation >= 0.20 * ta.atr(14) nhằm tránh giai đoạn 3 đường EMA xoắn vào nhau (sideway).
  • Đột biến khối lượng (requireVolumeSpike): Yêu cầu volume >= ta.sma(volume, 20) * 1.20.
  • Xu hướng khung H1 (useH1EMABias): Lấy dữ liệu nến H1 đã đóng cửa (close[1] và ta.ema(close, 50)[1] với lookahead=barmerge.lookahead_on trên giá trị [1] để tránh repaint), yêu cầu h1Close > h1EMA cho Long và h1Close < h1EMA cho Short.

3. Nguyên lý hoạt động của CNPS69

Quy trình xử lý của bot trên mỗi nến tuân theo 5 bước tuần tự:

  1. Khởi tạo phiên & Reset ngày mới: Tính currentMinute và currentCloseMinute theo múi giờ Asia/Ho_Chi_Minh. Khi phát hiện newTradingDay, bot đặt lại tradesToday := 0 và xóa toàn bộ trạng thái pendingBull, pendingBear, bullPullbackBar, bearPullbackBar.
  2. Đánh giá cấu trúc EMA & Pullback: Tính toán 3 đường EMA, kiểm tra bullishAlignment / bearishAlignment. Tại thời điểm nến đóng (barstate.isconfirmed), cập nhật trạng thái pendingBull/pendingBear (hủy nếu quá hạn/phá vỡ cấu trúc, hoặc đăng ký mới nếu chưa có pending).
  3. Kiểm tra xác nhận trong cửa sổ hợp lệ: Nếu đang trong cửa sổ 1 <= barsSincePullback <= pullbackBarsMax, bot kiểm tra các điều kiện nến xác nhận (longConfirmation / shortConfirmation) để hình thành longBase / shortBase.
  4. Áp dụng bộ lọc & Kiểm soát lệnh: Kết hợp longBase/shortBase với 4 bộ lọc tùy chọn để tạo rawLongSignal/rawShortSignal. Kiểm tra canTrade, chiều giao dịch cho phép (allowLong/allowShort) và loại bỏ tín hiệu mơ hồ (not ambiguousSignal) trước khi gửi strategy.entry.
  5. Quản trị vị thế & Đóng cuối phiên: Khi có vị thế mở, bot liên tục duy trì lệnh strategy.exit với mức SL/TP tính từ strategy.position_avg_price. Nếu chạm finalSessionBar (14:45), bot thực thi strategy.close_all(immediately=true) và dọn dẹp các biến activeLongSL/TP, activeShortSL/TP khi vị thế đã đóng (positionJustClosed).

4. Điều kiện vào lệnh Long và Short của CNPS69

4.1. Điều kiện vào lệnh Long

Lệnh strategy.entry("Long", strategy.long) được kích hoạt khi thỏa mãn đồng thời:

  1. validBullPullback: Đang có pendingBull == true và 1 <= (bar_index - bullPullbackBar) <= pullbackBarsMax (mặc định 5).
  2. bullishAlignment: emaFast > emaMiddle and emaMiddle > emaSlow.
  3. bullishCandleOK: Nến hiện tại là nến tăng (close > open, nếu requireBullBearCandle = true).
  4. longFastOK: Giá đóng cửa vượt lên trên EMA9 (close > emaFast, nếu requireFastEMAReclaim = true).
  5. longBreakOK: Giá đóng cửa vượt đỉnh nến trước (close > high[1], mặc định tắt).
  6. Thỏa mãn các bộ lọc tùy chọn đang bật (longSlopeOK, separationOK, volumeOK, longBiasOK).
  7. allowLong == true, canTrade == true và not ambiguousSignal.

4.2. Điều kiện vào lệnh Short

Lệnh strategy.entry("Short", strategy.short) được kích hoạt theo logic đảo ngược:

  1. validBearPullback: Đang có pendingBear == true và 1 <= (bar_index - bearPullbackBar) <= pullbackBarsMax.
  2. bearishAlignment: emaFast < emaMiddle and emaMiddle < emaSlow.
  3. bearishCandleOK: Nến hiện tại là nến giảm (close < open, nếu requireBullBearCandle = true).
  4. shortFastOK: Giá đóng cửa nằm dưới EMA9 (close < emaFast, nếu requireFastEMAReclaim = true).
  5. shortBreakOK: Giá đóng cửa thủng đáy nến trước (close < low[1], mặc định tắt).
  6. Thỏa mãn các bộ lọc tùy chọn đang bật (shortSlopeOK, separationOK, volumeOK, shortBiasOK).
  7. allowShort == true (lưu ý mặc định tradeDirection là "Long", cần đổi sang "Short" hoặc "Both" nếu muốn đánh Short), canTrade == true và not ambiguousSignal.

4.3. Điều kiện kiểm soát giao dịch chung

Biến canTrade yêu cầu toàn bộ các điều kiện sau phải đúng cùng lúc:

  • Không có vị thế đang mở (positionFlat): strategy.position_size == 0 (pyramiding=0, không nhồi lệnh).
  • Giới hạn lệnh ngày: tradesToday < maximumTradesPerDay (mặc định tối đa 2 lệnh/ngày).
  • Lọc phiên (sessionOK): Nếu bật useSessionFilter = true, thời gian mở nến phải nằm trong khoảng 09:00 đến 14:30 (Asia/Ho_Chi_Minh).
  • Trước giờ đóng phiên: currentCloseMinute < sessionEndTotal (nến phải đóng trước 14:45).
  • Nến đã xác nhận: barstate.isconfirmed == true.
  • Chống tín hiệu xung đột: ambiguousSignal = rawLongSignal and rawShortSignal phải bằng false.

5. Quản trị Stop Loss, Take Profit và Thoát lệnh

5.1. Cơ chế Stop Loss và khoảng đệm điểm

Bot sử dụng mức cắt lỗ cố định theo số điểm (stopLossPoints, mặc định 5.0 điểm) tính trực tiếp từ giá khớp lệnh trung bình (strategy.position_avg_price), không sử dụng bộ lọc Min–Max Risk theo ATR:

  • Vị thế Long: activeLongSL = strategy.position_avg_price - stopLossPoints
  • Vị thế Short: activeShortSL = strategy.position_avg_price + stopLossPoints

5.2. Cơ chế Take Profit và Đóng vị thế cuối phiên

Bot sử dụng mức chốt lời cố định theo số điểm (takeProfitPoints, mặc định 15.0 điểm) và chưa tích hợp cơ chế dời hòa vốn (Break Even) hay Trailing Stop trong mã nguồn:

  • Vị thế Long: activeLongTP = strategy.position_avg_price + takeProfitPoints
  • Vị thế Short: activeShortTP = strategy.position_avg_price - takeProfitPoints
  • Đóng bắt buộc hết phiên (Session End): Tại nến giao cắt qua mốc sessionEndTotal (currentMinute < 14:45 and currentCloseMinute >= 14:45), nếu strategy.position_size != 0, bot gọi strategy.close_all(immediately=true, comment="Session End") để tất toán toàn bộ vị thế trước giờ ATC.

5.3. Bảng tổng hợp cơ chế bảo vệ vị thế

Cơ chếCông thức / Điều kiện trong codeGhi chú / Mặc định
Stop Loss (SL)entryPrice -/+ stopLossPointsMặc định 5.0 điểm
Take Profit (TP)entryPrice +/- takeProfitPointsMặc định 15.0 điểm (R:R 1:3)
Break Even / TrailingKhông có trong mã nguồnQuản trị thuần SL/TP cố định
Session End ClosecurrentMinute < 14:45 and currentCloseMinute >= 14:45strategy.close_all(immediately=true)
Giới hạn lệnh ngàytradesToday < maximumTradesPerDayTối đa 2 lệnh/ngày

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 khuyến nghị như 1m, 3m hoặc 5m tùy khẩu vị).
  2. Mở tab Pine Editor ở phía dưới màn hình, xóa mã mặc định nếu có.
  3. Sao chép toàn bộ mã nguồn CNPS69 TRIPLE EMA ALIGNMENT V2 từ Mục 1 và dán vào Pine Editor.
  4. Nhấn Save để lưu script, sau đó nhấn Add to chart để đưa chiến lược lên biểu đồ.
  5. Vào phần Settings (Cài đặt) của chiến lược để điều chỉnh Trade Direction (mặc định đang là "Long", chuyển sang "Both" nếu muốn giao dịch cả 2 chiều), bật/tắt các bộ lọc ở nhóm Filters hoặc bật Show Diagnostics? để theo dõi bảng thông số.

Cách đọc bảng chẩn đoán (Diagnostics Table)

Khi bật showDiagnostics = true, bot sẽ vẽ bảng table.new(position.top_right, 2, 16) ở góc trên bên phải tại nến cuối cùng (barstate.islast) gồm 16 dòng thông tin:

DòngNhãn hiển thịÝ nghĩa thực tế
0CNPS69 V2Tên bot và khung thời gian biểu đồ (timeframe.period)
1–3EMA Fast / Middle / SlowGiá trị hiện tại của EMA 9, EMA 21 và EMA 55
4AlignmentTrạng thái 3 EMA: BULLISH, BEARISH hoặc NEUTRAL
5–6Bull Pullbacks / Bear PullbacksTổng số lần ghi nhận pullback tăng/giảm
7–8Bull Confirms / Bear ConfirmsTổng số lần thỏa điều kiện longBase / shortBase
9–10Pending Long / Pending ShortTrạng thái đang chờ xác nhận pullback (YES / NO)
11Volume OKTrạng thái bộ lọc khối lượng (YES / NO)
12–13Long Entries / Short EntriesTổng số lệnh Long / Short đã vào
14Trades TodaySố lệnh đã giao dịch trong ngày trên giới hạn (x / 2)
15PositionTrạ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 thời gian thực qua ứng dụng TradingView, Telegram hoặc Webhook:

  1. Nhấp vào biểu tượng Alert (Đồng hồ báo thức) trên thanh công cụ TradingView.
  2. Tại mục Condition, chọn chiến lược CNPS69 TRIPLE EMA ALIGNMENT V2.
  3. Tại ô Message, xóa nội dung mặc định và nhập đúng cú pháp: {{strategy.order.alert_message}}.
  4. Nhấn Create để kích hoạt cảnh báo. Nếu chỉ muốn nhận cảnh báo vào lệnh và đóng phiên mà không nhận cảnh báo SL/TP, hãy tích chọn Disable SL / TP Alerts? trong cài đặt bot.

Bảng thông điệp Alert của CNPS69

Sự kiệnTham số trong codeNội dung thông điệp thực tế
Vào lệnh Longalert_message (strategy.entry)🟢 VÀO VỊ THẾ LONG (Triple EMA Alignment) kèm Giá vào, SL dự kiến, TP dự kiến
Vào lệnh Shortalert_message (strategy.entry)🔴 VÀO VỊ THẾ SHORT (Triple EMA Alignment) kèm Giá vào, SL dự kiến, TP dự kiến
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

CNPS69 TRIPLE EMA ALIGNMENT V2 là một hệ thống giao dịch VN30F1M có cấu trúc rõ ràng, kỷ luật và giải quyết tốt nhược điểm đếm lại nhịp pullback khi giá kiểm tra vùng EMA21 nhiều lần. Chiến lược phát huy hiệu quả cao nhất trong những phiên thị trường có xu hướng rõ rệt (trending) khi 3 đường EMA 9 - 21 - 55 tách lớp mượt mà, đồng thời người dùng nên cân nhắc bật thêm bộ lọc EMA Separation hoặc H1 EMA Bias trong các giai đoạn thị trường đi ngang biên độ hẹp.

Bạn có thể tham khảo thêm các chiến lược giao dịch phái sinh khác như Bot CNPS50 - Trend Analysis V2 và Bot CNPS49 - Daily Open để tối ưu hóa danh mục hệ thống giao dịch của mình.

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