Hướng Dẫn Sử Dụng Bot CNPS69 - Triple EMA Alignment V2 cho VN30F1M
TradingviewBot 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.

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 > EMA55cho 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
EMA21mộ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:
- Hệ thống 3 đường EMA (
EMA Engine): Sử dụngEMA 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). - 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ạmEMA21nhưng vẫn giữ được cấu trúc xu hướng trên/dướiEMA55, sau đó mở cửa sổ chờ tối đapullbackBarsMaxnến (mặc định 5 nến) để đợi tín hiệu xác nhận. - 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ạiEMA9(hoặc phá đỉnh/đáy nến trước), kết hợp các bộ lọc tùy chọn như độ dốcEMA55, khoảng cách|EMA9 - EMA55|theo ATR, đột biến khối lượng và xu hướng H1 EMA50. - 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 code | Mô tả | Giá trị mặc định |
|---|---|---|---|
| EMA | emaFastLength | Chu kỳ EMA nhanh | 9 |
| EMA | emaMiddleLength | Chu kỳ EMA trung bình | 21 |
| EMA | emaSlowLength | Chu kỳ EMA chậm | 55 |
| Pullback | pullbackBarsMax | Số nến tối đa chờ xác nhận sau pullback | 5 |
| Pullback | requireFastEMAReclaim | Yêu cầu đóng cửa vượt EMA nhanh | true |
| Pullback | requirePreviousHighLowBreak | Yêu cầu phá đỉnh/đáy nến trước | false |
| Pullback | requireBullBearCandle | Yêu cầu nến xác nhận tăng/giảm | true |
| Filters | requireEMASlope | Lọc độ dốc EMA chậm | false (lookback = 5) |
| Filters | requireEMASeparation | Lọc độ tách biệt EMA theo ATR | false (min = 0.20 * ATR(14)) |
| Filters | requireVolumeSpike | Lọc đột biến khối lượng | false (factor = 1.20, SMA 20) |
| Filters | useH1EMABias | Lọc xu hướng khung H1 | false (H1 EMA = 50) |
| Risk Management | stopLossPoints | Mức cắt lỗ cố định (điểm) | 5.0 |
| Risk Management | takeProfitPoints | Mức chốt lời cố định (điểm) | 15.0 |
| Trade Control | maximumTradesPerDay | Số lệnh tối đa mỗi ngày | 2 |
| Trade Control | tradeDirection | Chiều giao dịch cho phép | "Long" (Long / Short / Both) |
| Session | useSessionFilter | Bật lọc khung giờ vào lệnh | false (Asia/Ho_Chi_Minh) |
| Session | sessionStartHour / Minute | Giờ bắt đầu phiên | 09:00 |
| Session | lastEntryHour / Minute | Giờ ngừng vào lệnh mới | 14:30 |
| Session | sessionEndHour / Minute | Giờ bắt buộc đóng toàn bộ vị thế | 14:45 |
| Alerts & Display | disableSLTPAlerts | Tắt cảnh báo SL/TP | false |
| Alerts & Display | showEMAs / showActiveSLTP | Hiển thị EMA và đường SL/TP | true |
| Alerts & Display | showDiagnostics | Hiển thị bảng chẩn đoán | false |
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ọccolor.aqua)emaMiddle = ta.ema(close, 21)(vẽ màu camcolor.orange)emaSlow = ta.ema(close, 55)(vẽ màu tímcolor.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 bullishPullbackxảy ra tại nến đã đóng (barstate.isconfirmed), bot bật cờpendingBull := truevà lưubullPullbackBar := bar_index. Nếu các nến tiếp theo tiếp tục chạmEMA21, điều kiệnnot pendingBullsẽ không thỏa mãn nênbullPullbackBarkhông bị reset. - Điều kiện hủy trạng thái chờ:
pendingBullbị 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ạnpullbackBarsMaxnến (bar_index - bullPullbackBar > 5). - Cửa sổ Pullback hợp lệ (
validBullPullback/validBearPullback): Yêu cầubarsSinceBullPullback >= 1và<= 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ầuemaSlow > emaSlow[5](Long) hoặcemaSlow < emaSlow[5](Short). - Độ tách biệt EMA theo ATR (
requireEMASeparation): TínhemaSeparation = math.abs(emaFast - emaSlow)và yêu cầuemaSeparation >= 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ầuvolume >= 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ớilookahead=barmerge.lookahead_ontrên giá trị[1]để tránh repaint), yêu cầuh1Close > h1EMAcho Long vàh1Close < h1EMAcho 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ự:
- Khởi tạo phiên & Reset ngày mới: Tính
currentMinutevàcurrentCloseMinutetheo múi giờAsia/Ho_Chi_Minh. Khi phát hiệnnewTradingDay, bot đặt lạitradesToday := 0và xóa toàn bộ trạng tháipendingBull,pendingBear,bullPullbackBar,bearPullbackBar. - Đá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áipendingBull/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). - 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ànhlongBase/shortBase. - Áp dụng bộ lọc & Kiểm soát lệnh: Kết hợp
longBase/shortBasevới 4 bộ lọc tùy chọn để tạorawLongSignal/rawShortSignal. Kiểm tracanTrade, 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ửistrategy.entry. - 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.exitvới mức SL/TP tính từstrategy.position_avg_price. Nếu chạmfinalSessionBar(14:45), bot thực thistrategy.close_all(immediately=true)và dọn dẹp các biếnactiveLongSL/TP,activeShortSL/TPkhi 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:
validBullPullback: Đang cópendingBull == truevà1 <= (bar_index - bullPullbackBar) <= pullbackBarsMax(mặc định5).bullishAlignment:emaFast > emaMiddle and emaMiddle > emaSlow.bullishCandleOK: Nến hiện tại là nến tăng (close > open, nếurequireBullBearCandle = true).longFastOK: Giá đóng cửa vượt lên trên EMA9 (close > emaFast, nếurequireFastEMAReclaim = true).longBreakOK: Giá đóng cửa vượt đỉnh nến trước (close > high[1], mặc định tắt).- Thỏa mãn các bộ lọc tùy chọn đang bật (
longSlopeOK,separationOK,volumeOK,longBiasOK). allowLong == true,canTrade == truevà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:
validBearPullback: Đang cópendingBear == truevà1 <= (bar_index - bearPullbackBar) <= pullbackBarsMax.bearishAlignment:emaFast < emaMiddle and emaMiddle < emaSlow.bearishCandleOK: Nến hiện tại là nến giảm (close < open, nếurequireBullBearCandle = true).shortFastOK: Giá đóng cửa nằm dưới EMA9 (close < emaFast, nếurequireFastEMAReclaim = true).shortBreakOK: Giá đóng cửa thủng đáy nến trước (close < low[1], mặc định tắt).- Thỏa mãn các bộ lọc tùy chọn đang bật (
shortSlopeOK,separationOK,volumeOK,shortBiasOK). allowShort == true(lưu ý mặc địnhtradeDirectionlà"Long", cần đổi sang"Short"hoặc"Both"nếu muốn đánh Short),canTrade == truevà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 đa2lệnh/ngày). - Lọc phiên (
sessionOK): Nếu bậtuseSessionFilter = true, thời gian mở nến phải nằm trong khoảng09:00đến14:30(Asia/Ho_Chi_Minh). - Trước giờ đóng phiên:
currentCloseMinute < sessionEndTotal(nến phải đóng trước14:45). - Nến đã xác nhận:
barstate.isconfirmed == true. - Chống tín hiệu xung đột:
ambiguousSignal = rawLongSignal and rawShortSignalphải bằngfalse.
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ốcsessionEndTotal(currentMinute < 14:45 and currentCloseMinute >= 14:45), nếustrategy.position_size != 0, bot gọistrategy.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 code | Ghi chú / Mặc định |
|---|---|---|
| Stop Loss (SL) | entryPrice -/+ stopLossPoints | Mặc định 5.0 điểm |
| Take Profit (TP) | entryPrice +/- takeProfitPoints | Mặc định 15.0 điểm (R:R 1:3) |
| Break Even / Trailing | Không có trong mã nguồn | Quản trị thuần SL/TP cố định |
| Session End Close | currentMinute < 14:45 and currentCloseMinute >= 14:45 | strategy.close_all(immediately=true) |
| Giới hạn lệnh ngày | tradesToday < maximumTradesPerDay | Tố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
- 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ị).
- Mở tab Pine Editor ở phía dưới màn hình, xóa mã mặc định nếu có.
- 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.
- Nhấn Save để lưu script, sau đó nhấn Add to chart để đưa chiến lược lên biểu đồ.
- 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ómFiltershoặc bậtShow 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òng | Nhãn hiển thị | Ý nghĩa thực tế |
|---|---|---|
| 0 | CNPS69 V2 | Tên bot và khung thời gian biểu đồ (timeframe.period) |
| 1–3 | EMA Fast / Middle / Slow | Giá trị hiện tại của EMA 9, EMA 21 và EMA 55 |
| 4 | Alignment | Trạng thái 3 EMA: BULLISH, BEARISH hoặc NEUTRAL |
| 5–6 | Bull Pullbacks / Bear Pullbacks | Tổng số lần ghi nhận pullback tăng/giảm |
| 7–8 | Bull Confirms / Bear Confirms | Tổng số lần thỏa điều kiện longBase / shortBase |
| 9–10 | Pending Long / Pending Short | Trạng thái đang chờ xác nhận pullback (YES / NO) |
| 11 | Volume OK | Trạng thái bộ lọc khối lượng (YES / NO) |
| 12–13 | Long Entries / Short Entries | Tổng số lệnh Long / Short đã vào |
| 14 | Trades Today | Số lệnh đã giao dịch trong ngày trên giới hạn (x / 2) |
| 15 | Position | Trạng thái vị thế hiện tại: LONG, SHORT hoặc FLAT |
7. Cách thiết lập cảnh báo tín hiệu giao dịch (Alert)
Để nhận thông báo thời gian thực qua ứng dụng TradingView, Telegram hoặc Webhook:
- Nhấp vào biểu tượng Alert (Đồng hồ báo thức) trên thanh công cụ TradingView.
- Tại mục Condition, chọn chiến lược CNPS69 TRIPLE EMA ALIGNMENT V2.
- Tại ô Message, xóa nội dung mặc định và nhập đúng cú pháp:
{{strategy.order.alert_message}}. - 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ện | Tham số trong code | Nội dung thông điệp thực tế |
|---|---|---|
| Vào lệnh Long | alert_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 Short | alert_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 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
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.





