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

Hướng Dẫn Sử Dụng Bot CNPS71 - Keltner Expansion cho VN30F1M

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

Khi giao dịch hợp đồng tương lai VN30F1M, một trong những rủi ro phổ biến nhất với các hệ thống đánh phá vỡ (Breakout) là nhiễu biên độ (False Breakout) trong các pha thị trường đi ngang tích lũy hoặc biến động thu hẹp. Nếu vào lệnh ngay khi giá vừa chạm biên mà không kiểm tra xung lực mở rộng của biến động, chiến lược rất dễ dính quét Stop Loss liên tục.

CNPS71 KELTNER EXPANSION (tên đầy đủ trong mã nguồn: strategy(title="CNPS71 KELTNER EXPANSION")) được viết bằng Pine Script v6 trên nền tảng TradingView để giải quyết trực tiếp bài toán này. Bot kết hợp dải Keltner Channel với cơ chế xác nhận mở rộng độ rộng kênh (Channel Expansion) và tùy chọn bắt Fresh Breakout (phá vỡ mới), giúp lọc bỏ các pha thoát biên yếu ớt.

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

  • Xác nhận mở rộng kênh Keltner: Chỉ chấp nhận tín hiệu phá vỡ khi độ rộng kênh (kcUpper - kcLower) thực sự mở rộng so với nến trước đó, đảm bảo biến động đang gia tăng theo hướng breakout.
  • Chống vào lệnh đuổi liên tục (Fresh Breakout): Kiểm soát nến đóng cửa liền trước phải nằm trong kênh, ngăn chặn việc mở lệnh lặp lại khi giá đã đi xa ngoài biên.
  • Hệ thống bộ lọc đa tầng linh hoạt: Tích hợp sẵn các bộ lọc tùy chọn gồm xác nhận thân/hướng nến, vùng đệm ATR (Breakout Buffer), bùng nổ khối lượng (Volume Spike), EMA xu hướng hiện tại và H1 EMA Bias.
  • Quản trị rủi ro tỷ lệ 1:3 rõ ràng: Thiết lập sẵn Stop Loss 5 điểm, Take Profit 15 điểm, giới hạn tối đa 2 lệnh/ngày và tự động đóng toàn bộ vị thế vào cuối phiên (14:45).

1. CNPS71 Keltner Expansion là gì?

CNPS71 Keltner Expansion là chiến lược giao dịch theo xung lực phá vỡ (Momentum Breakout) trên biểu đồ VN30F1M, được xây dựng xoay quanh 4 trụ cột kỹ thuật chính:

  1. Động cơ Keltner Channel (EMA + ATR): Sử dụng đường trung tâm EMA(20) kết hợp hai biên trên/dưới cách đường giữa 1.50 * ATR(20) để đo lường dải dao động động theo biến động thực tế của thị trường.
  2. Động cơ xác nhận mở rộng kênh (Channel Expansion): Đo tỷ lệ mở rộng giữa độ rộng kênh hiện tại và độ rộng kênh tại expansionLookback nến trước đó, bảo đảm kênh giá đang phình to thay vì co hẹp.
  3. Bộ lọc xác nhận chất lượng Breakout: Cho phép bật/tắt độc lập các điều kiện như hướng nến, độ dài thân nến tối thiểu theo ATR, khoảng đệm vượt biên theo ATR, khối lượng đột biến so với trung bình 20 phiên, EMA xu hướng và xu hướng khung H1 đã xác nhận.
  4. Động cơ quản trị lệnh và phiên giao dịch: Kiểm soát số lệnh tối đa mỗi ngày, hướng giao dịch (Long, Short hoặc Both), khung giờ giao dịch theo múi giờ Asia/Ho_Chi_Minh và ép đóng vị thế cuối phiên (Session End).

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
KeltnerkcLengthĐộ dài EMA trung tâm Keltner20
KeltnerkcATRLengthĐộ dài ATR tính biên Keltner20
KeltnerkcMultiplierHệ số nhân ATR cho biên trên/dưới1.50
KeltnerrequireFreshBreakYêu cầu phá vỡ mới (nến trước nằm trong kênh)true
Channel ExpansionrequireChannelExpansionBắt buộc kênh đang mở rộngtrue
Channel ExpansionexpansionLookbackSố nến lùi lại để so sánh độ rộng kênh1
Channel ExpansionminimumExpansionFactorTỷ lệ mở rộng độ rộng kênh tối thiểu1.00
Channel ExpansionrequireMinimumWidthYêu cầu độ rộng kênh tối thiểu theo ATRfalse
Channel ExpansionminimumWidthATRĐộ rộng kênh tối thiểu / ATR2.0
Breakout ConfirmationrequireCandleDirectionYêu cầu nến tăng (Long) / giảm (Short)false
Breakout ConfirmationrequireMinimumBodyYêu cầu thân nến tối thiểu theo ATRfalse
Breakout ConfirmationminimumBodyATRThân nến tối thiểu / ATR0.20
Breakout ConfirmationrequireBreakoutBufferYêu cầu khoảng đệm vượt biên theo ATRfalse
Breakout ConfirmationbreakoutBufferATRKhoảng đệm vượt biên / ATR0.10
VolumerequireVolumeSpikeYêu cầu bùng nổ khối lượngfalse
VolumevolumeAverageLengthSố phiên tính SMA khối lượng20
VolumevolumeSpikeFactorHệ số nhân khối lượng đột biến1.20
EMA TrenduseEMATrendBật bộ lọc EMA xu hướngfalse
EMA TrendtrendEMALengthĐộ dài Trend EMA50
H1 TrenduseH1EMABiasBật bộ lọc xu hướng khung H1false
H1 Trendh1EMALengthĐộ dài EMA trên khung H150
Risk ManagementstopLossPointsKhoảng cắt lỗ cố định (điểm)5.0
Risk ManagementtakeProfitPointsKhoảng chốt lời cố định (điểm)15.0
Trade ControlmaximumTradesPerDaySố lệnh tối đa mỗi ngày2
Trade ControltradeDirectionHướng giao dịch cho phép (Long/Short/Both)"Long"
SessionuseSessionFilterBật lọc khung giờ vào lệnhfalse
SessionstrategyTimezoneMúi giờ chiến lược"Asia/Ho_Chi_Minh"
SessionsessionStartHour / MinuteGiờ bắt đầu phiên vào lệnh09:00
SessionlastEntryHour / MinuteGiờ cuối cùng nhận lệnh mới14:30
SessionsessionEndHour / MinuteGiờ ép đóng toàn bộ vị thế (Force Close)14:45
AlertsdisableSLTPAlertsTắt cảnh báo riêng cho SL / TPfalse

Source Code CNPS71 Keltner Expansion

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="CNPS71 KELTNER EXPANSION", shorttitle="CNPS71 KELTNER", 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)

// ============================================================================
// CNPS71 KELTNER EXPANSION
//
// KELTNER CHANNEL:
// Middle = EMA(Close, Length)
// Upper  = Middle + ATR * Multiplier
// Lower  = Middle - ATR * Multiplier
//
// LONG:
// Close breaks above Upper Keltner
// -> Channel expansion confirmed
// -> Optional filters
// -> LONG
//
// SHORT:
// Close breaks below Lower Keltner
// -> Channel expansion confirmed
// -> Optional filters
// -> SHORT
//
// DEFAULT SL = 5 POINTS
// DEFAULT TP = 15 POINTS
// ============================================================================
// ============================================================================
// SECTION 1: KELTNER SETTINGS
// ============================================================================
kcLength = input.int(20, title="Keltner EMA Length", minval=2, maxval=500, group="Keltner")
kcATRLength = input.int(20, title="Keltner ATR Length", minval=1, maxval=500, group="Keltner")
kcMultiplier = input.float(1.50, title="Keltner ATR Multiplier", minval=0.1, step=0.1, group="Keltner")
requireFreshBreak = input.bool(true, title="Require Fresh Breakout?", group="Keltner")

// ============================================================================
// SECTION 2: CHANNEL EXPANSION
// ============================================================================
requireChannelExpansion = input.bool(true, title="Require Channel Expansion?", group="Channel Expansion")
expansionLookback = input.int(1, title="Expansion Comparison Bars", minval=1, maxval=50, group="Channel Expansion")
minimumExpansionFactor = input.float(1.00, title="Minimum Width Expansion Factor", minval=0.1, step=0.05, group="Channel Expansion")
requireMinimumWidth = input.bool(false, title="Require Minimum Channel Width?", group="Channel Expansion")
minimumWidthATR = input.float(2.0, title="Minimum Channel Width / ATR", minval=0.1, step=0.1, group="Channel Expansion")

// ============================================================================
// SECTION 3: BREAKOUT CONFIRMATION
// ============================================================================
requireCandleDirection = input.bool(false, title="Require Bullish / Bearish Candle?", group="Breakout Confirmation")
requireMinimumBody = input.bool(false, title="Require Minimum Candle Body?", group="Breakout Confirmation")
minimumBodyATR = input.float(0.20, title="Minimum Candle Body / ATR", minval=0.0, step=0.05, group="Breakout Confirmation")
requireBreakoutBuffer = input.bool(false, title="Require ATR Breakout Buffer?", group="Breakout Confirmation")
breakoutBufferATR = input.float(0.10, title="Breakout Buffer / ATR", minval=0.0, step=0.05, group="Breakout Confirmation")

// ============================================================================
// SECTION 4: VOLUME FILTER
// ============================================================================
requireVolumeSpike = input.bool(false, title="Require Volume Spike?", group="Volume")
volumeAverageLength = input.int(20, title="Volume Average Length", minval=2, group="Volume")
volumeSpikeFactor = input.float(1.20, title="Volume Spike Factor", minval=0.1, step=0.1, group="Volume")

// ============================================================================
// SECTION 5: EMA TREND FILTER
// ============================================================================
useEMATrend = input.bool(false, title="Use EMA Trend Filter?", group="EMA Trend")
trendEMALength = input.int(50, title="Trend EMA Length", minval=1, group="EMA Trend")

// ============================================================================
// SECTION 6: H1 TREND FILTER
// ============================================================================
useH1EMABias = input.bool(false, title="Use Confirmed H1 EMA Bias?", group="H1 Trend")
h1EMALength = input.int(50, title="H1 EMA Length", minval=1, group="H1 Trend")

// ============================================================================
// SECTION 7: RISK MANAGEMENT
// ============================================================================
stopLossPoints = input.float(5.0, title="Stop Loss (Points)", minval=0.1, step=0.5, group="Risk Management")
takeProfitPoints = input.float(15.0, title="Take Profit (Points)", minval=0.1, step=0.5, group="Risk Management")

// ============================================================================
// SECTION 8: TRADE CONTROL
// ============================================================================
maximumTradesPerDay = input.int(2, title="Maximum Trades Per Day", minval=1, maxval=20, group="Trade Control")
tradeDirection = input.string("Long", title="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, title="Use Entry Session Filter?", group="Session")
strategyTimezone = input.string("Asia/Ho_Chi_Minh", title="Strategy Timezone", group="Session")
sessionStartHour = input.int(9, title="Session Start Hour", minval=0, maxval=23, group="Session")
sessionStartMinute = input.int(0, title="Session Start Minute", minval=0, maxval=59, group="Session")
lastEntryHour = input.int(14, title="Last Entry Hour", minval=0, maxval=23, group="Session")
lastEntryMinute = input.int(30, title="Last Entry Minute", minval=0, maxval=59, group="Session")
sessionEndHour = input.int(14, title="Force Close Hour", minval=0, maxval=23, group="Session")
sessionEndMinute = input.int(45, title="Force Close Minute", minval=0, maxval=59, group="Session")

// ============================================================================
// SECTION 10: ALERT CONTROL
// ============================================================================
disableSLTPAlerts = input.bool(false, title="Disable SL / TP Alerts?", group="Alerts")

// ============================================================================
// SECTION 11: DISPLAY
// ============================================================================
showKeltner = input.bool(true, title="Show Keltner Channel?", group="Display")
showTrendEMA = input.bool(false, title="Show Trend EMA?", group="Display")
showH1EMA = input.bool(false, title="Show H1 EMA?", group="Display")
showSignalMarkers = input.bool(false, title="Show Setup Markers?", group="Display")
showActiveSLTP = input.bool(true, title="Show Active SL / TP?", group="Display")
showDiagnostics = input.bool(false, title="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: KELTNER CHANNEL ENGINE
// ============================================================================
//
// Keltner center uses EMA.
//
// ATR defines the dynamic upper and lower bands.
//
// ============================================================================
float kcMiddle = ta.ema(close, kcLength)
float kcATR = ta.atr(kcATRLength)
float kcUpper = (kcMiddle + kcMultiplier * kcATR)
float kcLower = (kcMiddle - kcMultiplier * kcATR)
bool channelReady = (not na(kcUpper) and not na(kcLower))

// ============================================================================
// SECTION 15: CHANNEL WIDTH
// ============================================================================
float channelWidth = (kcUpper - kcLower)
float previousChannelWidth = (channelWidth[expansionLookback])
float channelExpansionRatio = (not na(previousChannelWidth) and previousChannelWidth > 0 ? channelWidth / previousChannelWidth : na)
bool channelExpanding = (not na(channelExpansionRatio) and channelWidth > previousChannelWidth and channelExpansionRatio >= minimumExpansionFactor)
bool expansionOK = (not requireChannelExpansion or channelExpanding)

// ============================================================================
// SECTION 16: MINIMUM CHANNEL WIDTH
// ============================================================================
bool widthOK = (not requireMinimumWidth or (not na(kcATR) and kcATR > 0 and channelWidth >= minimumWidthATR * kcATR))

// ============================================================================
// SECTION 17: BREAKOUT ENGINE
// ============================================================================
//
// LONG:
// Close breaks above current Upper Keltner.
//
// SHORT:
// Close breaks below current Lower Keltner.
//
// ============================================================================
bool aboveUpper = (channelReady and close > kcUpper)
bool belowLower = (channelReady and close < kcLower)

// ============================================================================
// SECTION 18: FRESH BREAKOUT
// ============================================================================
//
// Uses the previous completed candle.
//
// This prevents continuous breakout entries
// while price remains outside the channel.
//
// ============================================================================
bool freshBullBreak = (aboveUpper and not na(kcUpper[1]) and close[1] <= kcUpper[1])
bool freshBearBreak = (belowLower and not na(kcLower[1]) and close[1] >= kcLower[1])
bool longBreakout = (requireFreshBreak ? freshBullBreak : aboveUpper)
bool shortBreakout = (requireFreshBreak ? freshBearBreak : belowLower)

// ============================================================================
// SECTION 19: CANDLE CONFIRMATION
// ============================================================================
float candleBody = math.abs(close - open)
bool bullishCandle = (close > open)
bool bearishCandle = (close < open)
bool longCandleOK = (not requireCandleDirection or bullishCandle)
bool shortCandleOK = (not requireCandleDirection or bearishCandle)
bool bodyOK = (not requireMinimumBody or (not na(kcATR) and kcATR > 0 and candleBody >= minimumBodyATR * kcATR))

// ============================================================================
// SECTION 20: BREAKOUT BUFFER
// ============================================================================
float longBreakoutDistance = (close - kcUpper)
float shortBreakoutDistance = (kcLower - close)
bool longBufferOK = (not requireBreakoutBuffer or (not na(kcATR) and longBreakoutDistance >= breakoutBufferATR * kcATR))
bool shortBufferOK = (not requireBreakoutBuffer or (not na(kcATR) and shortBreakoutDistance >= breakoutBufferATR * kcATR))

// ============================================================================
// SECTION 21: VOLUME FILTER
// ============================================================================
float averageVolume = ta.sma(volume, volumeAverageLength)
bool volumeSpike = (not na(averageVolume) and volume >= averageVolume * volumeSpikeFactor)
bool volumeOK = (not requireVolumeSpike or volumeSpike)

// ============================================================================
// SECTION 22: EMA TREND
// ============================================================================
float trendEMA = ta.ema(close, trendEMALength)
bool longTrendOK = (not useEMATrend or close > trendEMA)
bool shortTrendOK = (not useEMATrend or close < trendEMA)

// ============================================================================
// SECTION 23: CONFIRMED H1 EMA
// ============================================================================
//
// Uses previous completed H1 candle.
//
// Intended for chart timeframes below 60 minutes.
//
// ============================================================================
float h1ConfirmedEMA = request.security(syminfo.tickerid, "60", ta.ema(close, h1EMALength)[1], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
float h1ConfirmedClose = request.security(syminfo.tickerid, "60", close[1], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
bool longBiasOK = (not useH1EMABias or (not na(h1ConfirmedEMA) and not na(h1ConfirmedClose) and h1ConfirmedClose > h1ConfirmedEMA))
bool shortBiasOK = (not useH1EMABias or (not na(h1ConfirmedEMA) and not na(h1ConfirmedClose) and h1ConfirmedClose < h1ConfirmedEMA))

// ============================================================================
// SECTION 24: BASE LONG SETUP
// ============================================================================
bool longBase = (longBreakout and expansionOK and widthOK)

// ============================================================================
// SECTION 25: BASE SHORT SETUP
// ============================================================================
bool shortBase = (shortBreakout and expansionOK and widthOK)

// ============================================================================
// SECTION 26: RAW LONG SIGNAL
// ============================================================================
bool rawLongSignal = (longBase and longCandleOK and bodyOK and longBufferOK and volumeOK and longTrendOK and longBiasOK)

// ============================================================================
// SECTION 27: RAW SHORT SIGNAL
// ============================================================================
bool rawShortSignal = (shortBase and shortCandleOK and bodyOK and shortBufferOK and volumeOK and shortTrendOK and shortBiasOK)

// ============================================================================
// SECTION 28: 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 29: CAN TRADE
// ============================================================================
bool dailyTradeLimitOK = (tradesToday < maximumTradesPerDay)
bool canTrade = (positionFlat and dailyTradeLimitOK and sessionOK and currentCloseMinute < sessionEndTotal and barstate.isconfirmed)

// ============================================================================
// SECTION 30: 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 31: DIAGNOSTIC COUNTERS
// ============================================================================
var int bullBreakCount = 0
var int bearBreakCount = 0
var int expansionCount = 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 freshBullBreak
        bullBreakCount += 1
    if freshBearBreak
        bearBreakCount += 1
    if channelExpanding and not channelExpanding[1]
        expansionCount += 1
    if longBase and not longBase[1]
        longBaseCount += 1
    if shortBase and not shortBase[1]
        shortBaseCount += 1
    if rawLongSignal and not rawLongSignal[1]
        longSignalCount += 1
    if rawShortSignal and not rawShortSignal[1]
        shortSignalCount += 1

// ============================================================================
// SECTION 32: LONG ENTRY
// ============================================================================
if finalLongSignal
    strategy.entry("Long", strategy.long, comment="Keltner Expansion Long", alert_message="🟢 VÀO VỊ THẾ LONG (CNPS71 Keltner Expansion)\\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\\n🛑 Cắt lỗ (SL): " + str.tostring(close - stopLossPoints, format.mintick) + "\\n💰 Chốt lời (TP): " + str.tostring(close + takeProfitPoints, format.mintick))
    tradesToday += 1
    longEntryCount += 1
    lastEntryBar := bar_index

// ============================================================================
// SECTION 33: SHORT ENTRY
// ============================================================================
if finalShortSignal
    strategy.entry("Short", strategy.short, comment="Keltner Expansion Short", alert_message="🔴 VÀO VỊ THẾ SHORT (CNPS71 Keltner Expansion)\\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\\n🛑 Cắt lỗ (SL): " + str.tostring(close + stopLossPoints, format.mintick) + "\\n💰 Chốt lời (TP): " + str.tostring(close - takeProfitPoints, format.mintick))
    tradesToday += 1
    shortEntryCount += 1
    lastEntryBar := bar_index

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

// ============================================================================
// SECTION 35: 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 36: 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 37: POSITION CLEANUP
// ============================================================================
if positionJustClosed
    activeLongSL := na
    activeLongTP := na
    activeShortSL := na
    activeShortTP := na

// ============================================================================
// SECTION 38: 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 39: KELTNER DISPLAY
// ============================================================================
plot(showKeltner ? kcUpper : na, title="Keltner Upper", color=color.green, linewidth=2)
plot(showKeltner ? kcMiddle : na, title="Keltner Middle", color=color.orange, linewidth=2)
plot(showKeltner ? kcLower : na, title="Keltner Lower", color=color.red, linewidth=2)

// ============================================================================
// SECTION 40: TREND DISPLAY
// ============================================================================
plot(showTrendEMA and useEMATrend ? trendEMA : na, title="Trend EMA", color=color.purple, linewidth=1)
plot(showH1EMA and useH1EMABias ? h1ConfirmedEMA : na, title="Confirmed H1 EMA", color=color.blue, linewidth=1)

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

// ============================================================================
// SECTION 42: SIGNAL MARKERS
// ============================================================================
plotshape(showSignalMarkers and rawLongSignal, title="Keltner Long Setup", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.tiny, text="L", textcolor=color.white)
plotshape(showSignalMarkers and rawShortSignal, title="Keltner Short Setup", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.tiny, text="S", textcolor=color.white)

// ============================================================================
// SECTION 43: DIAGNOSTICS
// ============================================================================
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, "CNPS71")
    table.cell(diagnostics, 1, 0, timeframe.period)
    table.cell(diagnostics, 0, 1, "KC Upper")
    table.cell(diagnostics, 1, 1, str.tostring(kcUpper, format.mintick))
    table.cell(diagnostics, 0, 2, "KC Middle")
    table.cell(diagnostics, 1, 2, str.tostring(kcMiddle, format.mintick))
    table.cell(diagnostics, 0, 3, "KC Lower")
    table.cell(diagnostics, 1, 3, str.tostring(kcLower, format.mintick))
    table.cell(diagnostics, 0, 4, "Channel Width")
    table.cell(diagnostics, 1, 4, str.tostring(channelWidth, "#.##"))
    table.cell(diagnostics, 0, 5, "Expansion Ratio")
    table.cell(diagnostics, 1, 5, str.tostring(channelExpansionRatio, "#.###"))
    table.cell(diagnostics, 0, 6, "Expanding")
    table.cell(diagnostics, 1, 6, channelExpanding ? "YES" : "NO")
    table.cell(diagnostics, 0, 7, "Bull Breaks")
    table.cell(diagnostics, 1, 7, str.tostring(bullBreakCount))
    table.cell(diagnostics, 0, 8, "Bear Breaks")
    table.cell(diagnostics, 1, 8, str.tostring(bearBreakCount))
    table.cell(diagnostics, 0, 9, "Expansion Events")
    table.cell(diagnostics, 1, 9, str.tostring(expansionCount))
    table.cell(diagnostics, 0, 10, "Long Bases")
    table.cell(diagnostics, 1, 10, str.tostring(longBaseCount))
    table.cell(diagnostics, 0, 11, "Short Bases")
    table.cell(diagnostics, 1, 11, str.tostring(shortBaseCount))
    table.cell(diagnostics, 0, 12, "Long Signals")
    table.cell(diagnostics, 1, 12, str.tostring(longSignalCount))
    table.cell(diagnostics, 0, 13, "Short Signals")
    table.cell(diagnostics, 1, 13, str.tostring(shortSignalCount))
    table.cell(diagnostics, 0, 14, "Volume OK")
    table.cell(diagnostics, 1, 14, volumeOK ? "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 CNPS71

2.1. Dải Keltner Channel và cơ chế Fresh Breakout

Bot xây dựng Keltner Channel dựa trên EMA làm trục giữa và ATR làm biên độ dao động:

  • kcMiddle = ta.ema(close, kcLength) (mặc định kcLength = 20)
  • kcATR = ta.atr(kcATRLength) (mặc định kcATRLength = 20)
  • kcUpper = kcMiddle + kcMultiplier * kcATR (mặc định kcMultiplier = 1.50)
  • kcLower = kcMiddle - kcMultiplier * kcATR

Để tránh vào lệnh muộn khi giá đã chạy nhiều cây nến bên ngoài dải Keltner, mặc định requireFreshBreak = true kích hoạt logic Fresh Breakout:

  • Fresh Bull Break: Giá đóng cửa hiện tại vượt lên trên biên trên (close > kcUpper) và giá đóng cửa nến liền trước nằm trong hoặc tại biên trên (close[1] <= kcUpper[1]).
  • Fresh Bear Break: Giá đóng cửa hiện tại cắt xuống dưới biên dưới (close < kcLower) và giá đóng cửa nến liền trước nằm trong hoặc tại biên dưới (close[1] >= kcLower[1]).

2.2. Đo lường độ rộng và sự mở rộng kênh (Channel Expansion)

Đây là bộ lọc đặc trưng nhất của CNPS71. Độ rộng kênh được tính theo công thức:

  • channelWidth = kcUpper - kcLower
  • previousChannelWidth = channelWidth[expansionLookback] (mặc định expansionLookback = 1)
  • channelExpansionRatio = channelWidth / previousChannelWidth

Khi requireChannelExpansion = true (mặc định bật), bot chỉ xác nhận kênh đang mở rộng (channelExpanding) nếu đồng thời thỏa mãn:

  1. channelWidth > previousChannelWidth (độ rộng hiện tại lớn hơn nến so sánh).
  2. channelExpansionRatio >= minimumExpansionFactor (mặc định 1.00).

Ngoài ra, nếu người dùng bật requireMinimumWidth = true, bot sẽ kiểm tra thêm channelWidth >= minimumWidthATR * kcATR (mặc định 2.0 * ATR) để loại bỏ giai đoạn biên độ quá hẹp.

2.3. Hệ thống bộ lọc xác nhận bổ sung (Optional Filters)

Mặc định các bộ lọc mở rộng bên dưới đang để false để giữ nguyên tính nhạy của Keltner Expansion, nhưng có thể bật từng phần tùy khẩu vị rủi ro:

  • Breakout Confirmation:
    • requireCandleDirection: Nến phá vỡ Long phải là nến tăng (close > open), Short phải là nến giảm (close < open).
    • requireMinimumBody: Độ lớn thân nến |close - open| >= minimumBodyATR * kcATR (mặc định 0.20 * ATR).
    • requireBreakoutBuffer: Khoảng cách vượt biên (close - kcUpper hoặc kcLower - close) phải đạt tối thiểu breakoutBufferATR * kcATR (mặc định 0.10 * ATR).
  • Volume Filter (requireVolumeSpike): Khối lượng nến breakout phải đạt ít nhất volumeSpikeFactor * ta.sma(volume, volumeAverageLength) (mặc định 1.20 * SMA(20)).
  • EMA Trend Filter (useEMATrend): Giá đóng cửa phải nằm trên ta.ema(close, 50) đối với lệnh Long và dưới ta.ema(close, 50) đối với lệnh Short.
  • Confirmed H1 EMA Bias (useH1EMABias): Sử dụng request.security(syminfo.tickerid, "60", ...[1], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on) để lấy giá đóng cửa và EMA(50) của nến H1 đã hoàn tất liền trước (tránh repaint), yêu cầu h1ConfirmedClose > h1ConfirmedEMA cho Long và ngược lại cho Short.

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

Quy trình xử lý của CNPS71 trên mỗi cây nến diễn ra tuần tự qua 5 bước:

  1. Khởi tạo ngày giao dịch và bộ đếm thời gian: Chuyển đổi thời gian về múi giờ Asia/Ho_Chi_Minh. Khi phát hiện sang ngày mới (newTradingDay), biến đếm tradesToday được reset về 0.
  2. Tính toán Keltner Channel và độ mở rộng: Tính kcMiddle, kcATR, kcUpper, kcLower, độ rộng channelWidth và tỷ lệ channelExpansionRatio.
  3. Hình thành Base Setup và Raw Signal:
    • Tổng hợp longBase / shortBase từ tín hiệu breakout, expansionOK và widthOK.
    • Áp dụng các bộ lọc tùy chọn (nến, thân nến, buffer, volume, Trend EMA, H1 EMA) để tạo ra rawLongSignal và rawShortSignal.
  4. Kiểm tra điều kiện giao dịch (canTrade) và chống xung đột: Đảm bảo tài khoản đang không có vị thế (positionFlat), chưa vượt quá maximumTradesPerDay, hợp lệ khung giờ, trước giờ đóng phiên (currentCloseMinute < sessionEndTotal), nến đã đóng (barstate.isconfirmed), chưa vào lệnh trên cùng nến (notEnteredThisBar) và không có tín hiệu hai chiều cùng lúc (not ambiguousSignal).
  5. Thực thi và quản trị lệnh: Gửi lệnh strategy.entry khi thỏa mãn finalLongSignal hoặc finalShortSignal, tăng tradesToday, đồng thời gắn strategy.exit với mức SL/TP cố định. Nếu đến nến cuối phiên (finalSessionBar) mà vẫn còn vị thế mở, bot tự động gọi strategy.close_all.

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

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

Lệnh Long được kích hoạt khi finalLongSignal = true, bao gồm đầy đủ các điều kiện sau:

  1. Cho phép hướng Long: tradeDirection là "Long" hoặc "Both" (mặc định là "Long").
  2. Phá vỡ biên trên (longBreakout):
    • Nếu requireFreshBreak = true (mặc định): close > kcUpper và close[1] <= kcUpper[1].
    • Nếu requireFreshBreak = false: close > kcUpper.
  3. Kênh mở rộng (expansionOK & widthOK): Kênh có channelWidth > previousChannelWidth và channelExpansionRatio >= minimumExpansionFactor (nếu bật requireChannelExpansion), cùng độ rộng tối thiểu (nếu bật requireMinimumWidth).
  4. Bộ lọc xác nhận (nếu bật): Nến tăng (close > open), thân nến đạt ngưỡng ATR, khoảng vượt biên close - kcUpper >= breakoutBufferATR * kcATR, volume >= averageVolume * volumeSpikeFactor, close > trendEMA, và h1ConfirmedClose > h1ConfirmedEMA.
  5. Điều kiện hệ thống (canTrade & bảo vệ): Không đồng thời xuất hiện rawShortSignal, thỏa mãn giới hạn số lệnh và khung giờ giao dịch.

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

Lệnh Short được kích hoạt khi finalShortSignal = true, bao gồm đầy đủ các điều kiện sau:

  1. Cho phép hướng Short: tradeDirection là "Short" hoặc "Both" (lưu ý: mặc định code đang để "Long", cần đổi sang "Short" hoặc "Both" nếu muốn đánh hai chiều).
  2. Phá vỡ biên dưới (shortBreakout):
    • Nếu requireFreshBreak = true (mặc định): close < kcLower và close[1] >= kcLower[1].
    • Nếu requireFreshBreak = false: close < kcLower.
  3. Kênh mở rộng (expansionOK & widthOK): Thỏa mãn điều kiện mở rộng độ rộng kênh và độ rộng tối thiểu (nếu bật).
  4. Bộ lọc xác nhận (nếu bật): Nến giảm (close < open), thân nến đạt ngưỡng ATR, khoảng vượt biên kcLower - close >= breakoutBufferATR * kcATR, volume >= averageVolume * volumeSpikeFactor, close < trendEMA, và h1ConfirmedClose < h1ConfirmedEMA.
  5. Điều kiện hệ thống (canTrade & bảo vệ): Không đồng thời xuất hiện rawLongSignal, thỏa mãn giới hạn số lệnh và khung giờ giao dịch.

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

  • Trạng thái vị thế (positionFlat): Chỉ mở lệnh mới khi strategy.position_size == 0 (pyramiding = 0, không nhồi lệnh).
  • Giới hạn số lệnh/ngày (dailyTradeLimitOK): tradesToday < maximumTradesPerDay (mặc định tối đa 2 lệnh/ngày).
  • Khung giờ giao dịch (sessionOK & sessionEndTotal):
    • Dù useSessionFilter mặc định là false, biến canTrade luôn yêu cầu currentCloseMinute < sessionEndTotal (trước 14:45 theo giờ Việt Nam) để không mở lệnh sát giờ đóng cửa.
    • Khi 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 quá 14:30.
  • Xác nhận đóng nến (barstate.isconfirmed) & chống trùng nến (notEnteredThisBar): Lệnh chỉ tính trên nến đã đóng và tối đa 1 lệnh trên mỗi cây nến.

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

5.1. Cơ chế Stop Loss

Bot áp dụng mức cắt lỗ cố định theo điểm số từ giá khớp lệnh trung bình (strategy.position_avg_price):

  • Với vị thế Long: activeLongSL = entryPrice - stopLossPoints (mặc định trừ 5.0 điểm).
  • Với vị thế Short: activeShortSL = entryPrice + stopLossPoints (mặc định cộng 5.0 điểm).

Chiến lược không sử dụng bộ lọc Min–Max Risk hay khoảng đệm ATR cho Stop Loss.

5.2. Cơ chế Take Profit và Đóng phiên

  • Chốt lời cố định (Take Profit):
    • Với vị thế Long: activeLongTP = entryPrice + takeProfitPoints (mặc định cộng 15.0 điểm).
    • Với vị thế Short: activeShortTP = entryPrice - takeProfitPoints (mặc định trừ 15.0 điểm).
  • Đóng vị thế cuối phiên (Session End): Khi nến chạm ngưỡng chuyển giao sang giờ đóng phiên (currentMinute < sessionEndTotal and currentCloseMinute >= sessionEndTotal, mặc định 14:45), nếu vẫn đang giữ vị thế (strategy.position_size != 0), bot sẽ gọi strategy.close_all(immediately=true, comment="Session End") để tất toán trong ngày, tránh rủi ro qua đêm (Overnight Gap).
  • Break Even / Trailing: Không có cơ chế dời hòa vốn (Break Even) hay Trailing Stop trong mã nguồn của CNPS71.

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

Cơ chế bảo vệÁp dụng choGiá trị / Điều kiện trong codeGhi chú
Stop Loss cố địnhLong & Short5.0 điểm từ position_avg_priceĐặt qua strategy.exit
Take Profit cố địnhLong & Short15.0 điểm từ position_avg_priceTỷ lệ Risk:Reward mặc định 1:3
Đóng lệnh cuối phiênToàn bộ vị thế mở14:45 (Asia/Ho_Chi_Minh)Gọi strategy.close_all(immediately=true)
Giới hạn lệnh ngàyTài khoản2 lệnh/ngày (maximumTradesPerDay)Reset về 0 khi sang ngày mới
Giới hạn hướng đánhLong / ShortMặc định "Long"Đổi sang "Both" để đánh 2 chiều

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 đồ phái sinh VN30F1M trên TradingView (khung thời gian khuyến nghị dưới H1 như M5 hoặc M15 nếu dùng bộ lọc H1 EMA).
  2. Mở tab Pine Editor ở phía dưới màn hình, xóa code mẫu mặc định.
  3. Sao chép toàn bộ mã nguồn CNPS71 KELTNER EXPANSION ở Mục 1 và dán vào Pine Editor.
  4. Nhấn Save, đặt tên chiến lược, sau đó bấm Add to chart để đưa bot lên biểu đồ.
  5. Vào phần Settings (Cài đặt) của chiến lược để điều chỉnh hướng giao dịch (Trade Direction), bộ lọc tùy chọn và tích chọn Show Diagnostics? nếu muốn theo dõi bảng thống kê trực tiếp.

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

Khi bật Show Diagnostics?, bot hiển thị bảng table.new gồm 19 dòng ở góc trên bên phải (position.top_right) cập nhật tại nến cuối cùng (barstate.islast):

Dòng hiển thịÝ nghĩa thực tế trong code
CNPS71 / timeframe.periodTên bot và khung thời gian biểu đồ đang chạy
KC Upper / KC Middle / KC LowerGiá trị hiện tại của 3 đường Keltner Channel
Channel WidthĐộ rộng kênh hiện tại (kcUpper - kcLower)
Expansion RatioTỷ lệ mở rộng kênh so với expansionLookback nến trước
ExpandingTrạng thái mở rộng kênh (YES / NO)
Bull Breaks / Bear BreaksSố lần xảy ra freshBullBreak / freshBearBreak đã đếm
Expansion EventsSố sự kiện bắt đầu mở rộng kênh (channelExpanding and not channelExpanding[1])
Long Bases / Short BasesSố lần hình thành longBase / shortBase
Long Signals / Short SignalsSố lần xuất hiện rawLongSignal / rawShortSignal (sau khi qua toàn bộ bộ lọc)
Volume OKTrạng thái bộ lọc khối lượng ở nến hiện tại (YES / NO)
Long Entries / Short EntriesTổng số lệnh Long / Short thực tế đã vào
Trades TodaySố lệnh đã vào trong ngày / Giới hạn tối đa (tradesToday / maximumTradesPerDay)
PositionTrạ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ề Telegram, Webhook hoặc ứng dụng TradingView khi bot phát sinh giao dịch:

  1. Nhấp vào biểu tượng Alert (Cảnh báo) hoặc nhấn Alt + A trên biểu đồ đang gắn CNPS71.
  2. Ở mục Condition, chọn chiến lược CNPS71 KELTNER EXPANSION.
  3. Ở mục Message, xóa nội dung mặc định và điền chính xác biến: {{strategy.order.alert_message}}.
  4. Nhấn Create để kích hoạt cảnh báo. (Lưu ý: Nếu chỉ muốn nhận thông báo vào lệnh và đóng phiên mà không nhận thông báo SL/TP, hãy bật Disable SL / TP Alerts? trong phần cài đặt).

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

Sự kiệnLoại Alert trong codeNội dung thông điệp (alert_message / alert_profit / alert_loss)
Vào lệnh Longstrategy.entry (alert_message)🟢 VÀO VỊ THẾ LONG (CNPS71 Keltner Expansion) + Giá vào + SL + TP
Vào lệnh Shortstrategy.entry (alert_message)🔴 VÀO VỊ THẾ SHORT (CNPS71 Keltner Expansion) + Giá vào + SL + TP
Chốt lời Longstrategy.exit (alert_profit)💰 CHỐT LỜI LONG (TP HIT) + Giá chốt (activeLongTP)
Cắt lỗ Longstrategy.exit (alert_loss)🛑 CẮT LỖ LONG (SL HIT) + Giá cắt (activeLongSL)
Chốt lời Shortstrategy.exit (alert_profit)💰 CHỐT LỜI SHORT (TP HIT) + Giá chốt (activeShortTP)
Cắt lỗ Shortstrategy.exit (alert_loss)🛑 CẮT LỖ SHORT (SL HIT) + Giá cắt (activeShortSL)
Đóng hết phiênstrategy.close_all (alert_message)⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End) + Giá đóng (close)

Kết luận

Bot CNPS71 Keltner Expansion là một hệ thống đánh breakout gọn gàng, minh bạch và kỷ luật trên VN30F1M. Điểm mạnh lớn nhất của chiến lược nằm ở bộ lọc Channel Expansion kết hợp Fresh Breakout, giúp tránh phần lớn các pha phá vỡ giả khi biến động thị trường chưa thực sự mở rộng, đồng thời duy trì tỷ lệ Risk:Reward cố định 1:3 (SL 5 điểm – TP 15 điểm) và tự động tất toán vị thế trước giờ đóng cửa 14:45. Hệ thống phát huy hiệu quả tốt nhất trong các phiên có xu hướng rõ ràng và biên độ mở rộng mạnh sau giai đoạn tích lũy; cần cân nhắc thận trọng hoặc bật thêm bộ lọc Volume / Trend EMA trong những giai đoạn thị trường đi ngang biên độ hẹp kéo dài.

Bạn có thể tham khảo thêm các hệ thống giao dịch tự động khác tại Bot CNPS50 - Trend Analysis V2 và Bot CNPS49 - Daily Open.

Thông tin chỉ mang tính tham khảo, không phải khuyến nghị đầu tư. Kết quả kiểm thử quá khứ không đảm bảo lợi nhuận trong tương lai.

Thông tin trong bài chỉ mang tính tham khảo, không phải khuyến nghị mua bán. Giao dịch phái sinh có rủi ro cao do sử dụng đòn bẩy; nhà đầu tư tự chịu trách nhiệm với quyết định của mình.

Đ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