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

Hướng Dẫn Sử Dụng Bot CNPS65 - Directional Velocity Asymmetry V1 cho VN30F1M

Bot CNPS65 Directional Velocity Asymmetry V1 giao dịch VN30F1M theo nguyên lý bất đối xứng vận tốc: xung lực mạnh, nhịp hồi chậm và tái tăng tốc có cấu trúc SL/TP chặt chẽ.

Hướng dẫn sử dụng Bot CNPS65 cho VN30F1M
Hướng dẫn sử dụng Bot CNPS65 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 là vào lệnh đuổi theo các nhịp bứt phá (breakout) đã đi hết biên độ hoặc bắt nhầm các nhịp hồi mạnh mang tính đảo chiều. Để giải quyết bài toán phân biệt giữa một nhịp điều chỉnh lành mạnh và một cú đảo chiều thực sự, Bot CNPS65 tập trung đo lường sự chênh lệch tốc độ giữa xung lực chính và nhịp hồi ngược chiều.

Chiến lược CNPS65 DIRECTIONAL VELOCITY ASYMMETRY V1 - VN30F1M (tên rút gọn CNPS65 DVA V1) được lập trình bằng Pine Script v6 trên nền tảng TradingView, sử dụng thuần dữ liệu giá và khối lượng (OHLCV-only).

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

  • Đo lường bất đối xứng vận tốc (Velocity Asymmetry): Chỉ chấp nhận các nhịp hồi có tốc độ chậm hơn rõ rệt so với xung lực gốc (counterSpeed <= armedImpulseSpeed * maximumCounterVelocity).
  • Đánh giá hiệu suất đường đi (Path Efficiency): Lọc bỏ các pha giằng co nhiễu loạn bằng tỷ lệ giữa độ dịch chuyển ròng và tổng quãng đường đóng cửa.
  • Hai cơ chế vào lệnh linh hoạt (Hybrid): Kết hợp giữa vào lệnh khi giá hồi chậm rồi tái tăng tốc (Slow Pullback) và bứt phá sau nhịp nghỉ nông (Shallow Pause).
  • Quản trị rủi ro chặt chẽ theo R & phiên VN30F1M: Kiểm soát khoảng SL Min–Max, giới hạn thời gian giữ lệnh (45 phút), giới hạn lỗ ngày (2,400,000 VND) và tự động đóng vị thế trước giờ nghỉ trưa (11:25) cũng như trước phiên ATC (14:25).

1. CNPS65 Directional Velocity Asymmetry V1 là gì?

CNPS65 là hệ thống giao dịch theo động lượng có cấu trúc (Structured Momentum), vận hành dựa trên 4 trụ cột kỹ thuật chính:

  1. Nhận diện xung lực có hướng (Directional Impulse): Tìm kiếm các nhịp đẩy giá dứt khoát trong 6 nến với biên độ tối thiểu 1.50 x ATR14, hiệu suất đường đi đạt từ 0.58 trở lên và đóng cửa phá vỡ đỉnh/đáy 5 nến gần nhất.
  2. Theo dõi nhịp hồi chậm (Slow Counter-Move / Velocity Decay): Sau khi xác lập xung lực, bot chuyển sang trạng thái chờ giá điều chỉnh từ 16% đến 72% biên độ xung lực, với điều kiện vận tốc hồi không vượt quá 0.90 lần vận tốc xung lực ban đầu.
  3. Kích hoạt tái tăng tốc hoặc nghỉ nông (Re-acceleration / Shallow Pause): Hỗ trợ chế độ Hybrid cho phép vào lệnh ngay khi giá phá đỉnh/đáy nhịp nghỉ nông (trong 2–4 nến) hoặc khi giá xác nhận phá cấu trúc vi mô (microBreakBars = 2) sau nhịp hồi chậm.
  4. Bảo vệ vị thế & phiên giao dịch (Risk & Session Guard): Chuẩn hóa SL theo cấu trúc Pullback Structure, tính TP theo bội số R = 1.60, kiểm tra tính hợp lệ ngay khi khớp lệnh nến kế tiếp và tự động đưa tài khoản về trạng thái phẳng (Flat) trước giờ nghỉ.

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

Nhóm thông sốTên biến trong codeGiá trị mặc địnhMô tả
01 - Trade ControltradeDirection"Both"Hướng giao dịch (Both, Long, Short)
contracts3Số hợp đồng mỗi lệnh
maximumTradesPerDay5Số lệnh tối đa trong ngày
cooldownBars2Số nến nghỉ sau khi đóng lệnh
oneTradePerDirectionfalseGiới hạn 1 lệnh mỗi chiều/ngày
02 - ImpulseimpulseBars6Số nến quan sát xung lực
minimumImpulseATR1.50Độ dịch chuyển ròng tối thiểu (x ATR14)
minimumPathEfficiency0.58Hiệu suất đường đi tối thiểu
impulseBreakBars5Số nến lookback phá vỡ đỉnh/đáy xung lực
minimumImpulseCloseLocation0.58Vị trí giá đóng cửa theo hướng xung lực
03 - Pullback VelocityminimumRetracement0.16Mức hồi tối thiểu so với xung lực
maximumRetracement0.72Mức hồi tối đa so với xung lực
maximumCounterVelocity0.90Tỷ lệ vận tốc hồi tối đa / vận tốc xung lực
maximumSetupBars10Số nến tối đa từ xung lực đến khi vào lệnh
maximumConfirmBars6Số nến tối đa sau pullback để xác nhận
maximumInvalidationFraction0.90Hủy setup nếu hồi vượt quá tỷ lệ xung lực
04 - EntryentryMode"Hybrid"Chế độ vào lệnh (Hybrid, Slow Pullback Only, Shallow Pause Only)
microBreakBars2Số nến xác nhận phá vỡ vi mô
confirmationBuffer0.10Khoảng đệm phá vỡ xác nhận (điểm)
minimumConfirmBody0.30Tỷ lệ thân nến / biên độ tối thiểu
minimumConfirmCloseLocation0.60Vị trí đóng cửa nến xác nhận tối thiểu
minimumRecoveryFraction0.40Tỷ lệ phục hồi tối thiểu của xung lực
pauseEntryBars4Số nến tối đa cho nhịp nghỉ nông
maximumPauseDepthATR1.20Độ sâu tối đa của nhịp nghỉ nông (x ATR14)
05 - FiltersuseTrendFilterfalseBật/tắt lọc xu hướng EMA (34, slope 4 nến)
useVWAPFilterfalseBật/tắt lọc theo Session VWAP
useRVOLFilterfalseBật/tắt lọc RVOL (>= 0.85, lookback 30)
06 - RiskstopMode"Pullback Structure"Chế độ SL (Pullback Structure, Impulse Midpoint, ATR Fixed)
stopBufferATR0.15Khoảng đệm SL (x ATR14)
fixedStopATR1.30Hệ số ATR nếu dùng ATR Fixed
minimumStopPoints / maximumStopPoints1.50 / 12.0Khoảng SL hợp lệ (điểm)
takeProfitR / minimumGrossTarget1.60 / 2.50Mục tiêu TP (R) và TP gộp tối thiểu (điểm)
07 - ExituseBreakEvenfalseBật/tắt dời hòa vốn (kích hoạt ở 1.00R, offset 0.20)
useVelocityFailureExitfalseThoát khi có 2 nến liên tiếp đảo chiều mạnh
useTimeExittrueBật/tắt đóng lệnh theo thời gian (45 phút)
08 - ProtectionuseDailyLossGuardtrueNgừng mở lệnh nếu lỗ đã chốt trong ngày >= 2,400,000 VND
09 - SessionmorningEntry / afternoonEntry"0910-1120" / "1305-1415"Khung giờ vào lệnh phiên sáng/chiều
closeBeforeLunch / lunchFlatMinutetrue / 25Đóng lệnh trước nghỉ trưa lúc 11:25
finalFlatHour / finalFlatMinute14 / 25Đóng toàn bộ vị thế cuối ngày lúc 14:25

Source Code CNPS65 Directional Velocity Asymmetry V1

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
// CNPS65 - Directional Velocity Asymmetry V1 - VN30F1M.
// Fast directional displacement -> slow counter-move -> renewed directional speed.
// Original OHLCV-only research strategy. No dashboard or diagnostic table.
strategy(title="CNPS65 DIRECTIONAL VELOCITY ASYMMETRY V1 - VN30F1M", shorttitle="CNPS65 DVA V1", overlay=true, initial_capital=100000000, currency=currency.VND, default_qty_type=strategy.fixed, default_qty_value=1, pyramiding=0, margin_long=12, margin_short=12, slippage=0, commission_type=strategy.commission.cash_per_contract, commission_value=0, process_orders_on_close=false, calc_on_order_fills=false, calc_on_every_tick=false, fill_orders_on_standard_ohlc=true, max_bars_back=5000, max_labels_count=100)

// ============================================================================
// SECTION 1: TRADE CONTROL
// ============================================================================
tradeDirection = input.string("Both", title="Trade Direction", options=["Both", "Long", "Short"], group="01 - Trade Control")
contracts = input.int(3, title="Contracts Per Trade", minval=1, maxval=20, group="01 - Trade Control")
maximumTradesPerDay = input.int(5, title="Maximum Trades Per Day", minval=1, maxval=20, group="01 - Trade Control")
cooldownBars = input.int(2, title="Cooldown After Exit (bars)", minval=0, maxval=100, group="01 - Trade Control")
oneTradePerDirection = input.bool(false, title="One Trade Per Direction Per Day?", group="01 - Trade Control")

// ============================================================================
// SECTION 2: DIRECTIONAL IMPULSE
// ============================================================================
impulseBars = input.int(6, title="Impulse Observation Bars", minval=3, maxval=30, group="02 - Impulse")
minimumImpulseATR = input.float(1.50, title="Minimum Net Displacement / ATR14", minval=0.25, maxval=8.0, step=0.10, group="02 - Impulse")
minimumPathEfficiency = input.float(0.58, title="Minimum Net Displacement / Absolute Close Travel", minval=0.10, maxval=1.0, step=0.02, group="02 - Impulse")
impulseBreakBars = input.int(5, title="Minimum Recent High / Low Breakout Lookback", minval=2, maxval=30, group="02 - Impulse")
minimumImpulseCloseLocation = input.float(0.58, title="Impulse Close Location Toward Direction", minval=0.50, maxval=0.95, step=0.05, group="02 - Impulse")

// ============================================================================
// SECTION 3: SLOW COUNTER-MOVE / VELOCITY DECAY
// ============================================================================
minimumRetracement = input.float(0.16, title="Minimum Pullback / Impulse Displacement", minval=0.02, maxval=0.75, step=0.02, group="03 - Pullback Velocity")
maximumRetracement = input.float(0.72, title="Maximum Pullback / Impulse Displacement", minval=0.20, maxval=1.20, step=0.02, group="03 - Pullback Velocity")
maximumCounterVelocity = input.float(0.90, title="Maximum Counter-Move Speed / Impulse Speed", minval=0.10, maxval=2.0, step=0.05, group="03 - Pullback Velocity")
maximumSetupBars = input.int(10, title="Maximum Bars From Impulse To Entry", minval=2, maxval=40, group="03 - Pullback Velocity")
maximumConfirmBars = input.int(6, title="Maximum Bars After Pullback To Confirm", minval=1, maxval=20, group="03 - Pullback Velocity")
maximumInvalidationFraction = input.float(0.90, title="Cancel If Pullback Exceeds Impulse Fraction", minval=0.30, maxval=1.50, step=0.05, group="03 - Pullback Velocity")

// ============================================================================
// SECTION 4: RE-ACCELERATION / OPTIONAL SHALLOW PAUSE
// ============================================================================
entryMode = input.string("Hybrid", title="Entry Mode", options=["Hybrid", "Slow Pullback Only", "Shallow Pause Only"], group="04 - Entry")
microBreakBars = input.int(2, title="Confirmation Micro Break Bars", minval=1, maxval=10, group="04 - Entry")
confirmationBuffer = input.float(0.10, title="Confirmation Break Buffer (points)", minval=0.0, step=0.10, group="04 - Entry")
minimumConfirmBody = input.float(0.30, title="Minimum Confirmation Candle Body / Range", minval=0.0, maxval=1.0, step=0.05, group="04 - Entry")
minimumConfirmCloseLocation = input.float(0.60, title="Minimum Entry Close Location", minval=0.50, maxval=0.95, step=0.05, group="04 - Entry")
minimumRecoveryFraction = input.float(0.40, title="Minimum Recovered Share Of Impulse At Confirmation", minval=0.0, maxval=1.0, step=0.05, group="04 - Entry")
pauseEntryBars = input.int(4, title="Maximum Bars For Shallow Pause Breakout", minval=2, maxval=12, group="04 - Entry")
maximumPauseDepthATR = input.float(1.20, title="Maximum Shallow Pause Depth Below / Above Impulse Extreme x ATR", minval=0.10, maxval=5.0, step=0.10, group="04 - Entry")

// ============================================================================
// SECTION 5: OPTIONAL DIRECTIONAL FILTERS
// ============================================================================
useTrendFilter = input.bool(false, title="Require EMA Trend Alignment?", group="05 - Filters")
trendEMALength = input.int(34, title="EMA Trend Length", minval=5, maxval=200, group="05 - Filters")
trendSlopeBars = input.int(4, title="EMA Slope Lookback", minval=1, maxval=30, group="05 - Filters")
useVWAPFilter = input.bool(false, title="Require Session VWAP Alignment?", group="05 - Filters")
useRVOLFilter = input.bool(false, title="Require Entry Relative Volume?", group="05 - Filters")
volumeLookback = input.int(30, title="Prior Average Volume Lookback", minval=5, maxval=150, group="05 - Filters")
minimumEntryRVOL = input.float(0.85, title="Minimum Entry Relative Volume", minval=0.10, maxval=5.0, step=0.05, group="05 - Filters")

// ============================================================================
// SECTION 6: STOP LOSS / TAKE PROFIT
// ============================================================================
stopMode = input.string("Pullback Structure", title="Stop Mode", options=["Pullback Structure", "Impulse Midpoint", "ATR Fixed"], group="06 - Risk")
stopBufferATR = input.float(0.15, title="Stop Buffer x ATR14", minval=0.0, maxval=2.0, step=0.05, group="06 - Risk")
fixedStopATR = input.float(1.30, title="ATR Fixed Stop Multiple", minval=0.25, maxval=5.0, step=0.05, group="06 - Risk")
minimumStopPoints = input.float(1.50, title="Minimum Stop Distance (points)", minval=0.1, step=0.50, group="06 - Risk")
maximumStopPoints = input.float(12.0, title="Maximum Stop Distance (points)", minval=0.50, step=0.50, group="06 - Risk")
takeProfitR = input.float(1.60, title="Take Profit (R)", minval=0.25, maxval=8.0, step=0.10, group="06 - Risk")
minimumGrossTarget = input.float(2.50, title="Minimum Gross Target (points)", minval=0.0, step=0.50, group="06 - Risk")

// ============================================================================
// SECTION 7: POSITION MANAGEMENT
// ============================================================================
useBreakEven = input.bool(false, title="Use Break Even?", group="07 - Exit")
breakEvenAtR = input.float(1.00, title="Break Even Trigger (R)", minval=0.25, maxval=5.0, step=0.25, group="07 - Exit")
breakEvenOffset = input.float(0.20, title="Break Even Offset (points)", minval=0.0, step=0.10, group="07 - Exit")
useVelocityFailureExit = input.bool(false, title="Exit On Confirmed Counter-Direction Acceleration?", group="07 - Exit")
failureCloses = input.int(2, title="Consecutive Adverse Closes", minval=1, maxval=5, group="07 - Exit")
useTimeExit = input.bool(true, title="Maximum Hold Time Enabled?", group="07 - Exit")
maximumHoldMinutes = input.int(45, title="Maximum Hold Minutes", minval=5, maxval=240, group="07 - Exit")

// ============================================================================
// SECTION 8: DAILY PROTECTION
// ============================================================================
useDailyLossGuard = input.bool(true, title="Block New Trades After Daily Closed Loss?", group="08 - Protection")
maximumDailyLossVND = input.float(2400000, title="Daily Closed Loss Threshold (VND)", minval=100000, step=100000, group="08 - Protection")

// ============================================================================
// SECTION 9: VN30F1M SESSION
// ============================================================================
string timezoneVN = "Asia/Ho_Chi_Minh"
morningEntry = input.session("0910-1120", title="Morning Entry Window", group="09 - Session")
afternoonEntry = input.session("1305-1415", title="Afternoon Entry Window", group="09 - Session")
closeBeforeLunch = input.bool(true, title="Force Flat Before Lunch?", group="09 - Session")
lunchFlatMinute = input.int(25, title="Lunch Flat Minute (11:xx)", minval=15, maxval=30, group="09 - Session")
finalFlatHour = input.int(14, title="Final Flat Hour", minval=0, maxval=23, group="09 - Session")
finalFlatMinute = input.int(25, title="Final Flat Minute", minval=0, maxval=59, group="09 - Session")

// ============================================================================
// SECTION 10: DISPLAY - NO DASHBOARD
// ============================================================================
showImpulseMarkers = input.bool(false, title="Show Impulse Markers?", group="10 - Display")
showPullbackMarkers = input.bool(false, title="Show Slow-Pullback Markers?", group="10 - Display")
showEntrySignals = input.bool(true, title="Show Long / Short Entry Markers?", group="10 - Display")
showActiveLevels = input.bool(true, title="Show Active SL / TP?", group="10 - Display")
showTrendEMA = input.bool(false, title="Show Trend EMA?", group="10 - Display")

// ============================================================================
// SECTION 11: TIME / SESSION ENGINE
// ============================================================================
int minuteOpen = hour(time, timezoneVN) * 60 + minute(time, timezoneVN)
int minuteClose = hour(time_close, timezoneVN) * 60 + minute(time_close, timezoneVN)
int lunchCutoff = 660 + lunchFlatMinute
int finalCutoff = finalFlatHour * 60 + finalFlatMinute
bool morningContinuous = minuteOpen >= 540 and minuteOpen < 690
bool afternoonContinuous = minuteOpen >= 780 and minuteOpen < 870
bool continuousSession = morningContinuous or afternoonContinuous
bool morningBegins = morningContinuous and not morningContinuous[1]
bool afternoonBegins = afternoonContinuous and not afternoonContinuous[1]
bool inMorningEntry = not na(time(timeframe.period, morningEntry + ":23456", timezoneVN))
bool inAfternoonEntry = not na(time(timeframe.period, afternoonEntry + ":23456", timezoneVN))
bool entrySession = continuousSession and (inMorningEntry or inAfternoonEntry)
int dayKey = year(time, timezoneVN) * 10000 + month(time, timezoneVN) * 100 + dayofmonth(time, timezoneVN)
bool newTradingDay = bar_index == 0 or dayKey != nz(dayKey[1], dayKey)
bool beforeCutoff = (not na(time_close) and minuteClose < finalCutoff and (not closeBeforeLunch or not morningContinuous or minuteClose < lunchCutoff))
bool lunchFlatBar = (closeBeforeLunch and barstate.isconfirmed and morningContinuous and minuteOpen < lunchCutoff and minuteClose >= lunchCutoff)
bool finalFlatBar = (barstate.isconfirmed and afternoonContinuous and minuteOpen < finalCutoff and minuteClose >= finalCutoff)
var int barsSinceSessionStart = 0
if newTradingDay or morningBegins or afternoonBegins
    barsSinceSessionStart := continuousSession ? 1 : 0
else if continuousSession
    barsSinceSessionStart += 1
else
    barsSinceSessionStart := 0

// ============================================================================
// SECTION 12: IMPULSE METRICS - PRICE SPEED AND PATH PERSISTENCE
// ============================================================================
float atr = ta.atr(14)
float trendEMA = ta.ema(close, trendEMALength)
float candleRange = math.max(high - low, syminfo.mintick)
float candleBody = math.abs(close - open) / candleRange
float closeLocation = (close - low) / candleRange
float netDisplacement = close - close[impulseBars]
float closePathTravel = math.sum(math.abs(close - close[1]), impulseBars)
float pathEfficiency = closePathTravel > 0 ? math.abs(netDisplacement) / closePathTravel : na
float impulseSpeed = math.abs(netDisplacement) / impulseBars
float previousBreakHigh = ta.highest(high, impulseBreakBars)[1]
float previousBreakLow = ta.lowest(low, impulseBreakBars)[1]
float previousMicroHigh = ta.highest(high, microBreakBars)[1]
float previousMicroLow = ta.lowest(low, microBreakBars)[1]
float pauseRecentLow = ta.lowest(low, 3)
float pauseRecentHigh = ta.highest(high, 3)
bool bullishCandle = (close > open and candleBody >= minimumConfirmBody and closeLocation >= minimumConfirmCloseLocation)
bool bearishCandle = (close < open and candleBody >= minimumConfirmBody and closeLocation <= 1.0 - minimumConfirmCloseLocation)
bool sessionDataReady = barsSinceSessionStart > impulseBars
bool impulseDataReady = (sessionDataReady and not na(atr) and atr > 0 and not na(netDisplacement) and not na(pathEfficiency) and pathEfficiency >= minimumPathEfficiency and math.abs(netDisplacement) >= atr * minimumImpulseATR)
bool bullishImpulse = (impulseDataReady and netDisplacement > 0 and close > previousBreakHigh and closeLocation >= minimumImpulseCloseLocation)
bool bearishImpulse = (impulseDataReady and netDisplacement < 0 and close < previousBreakLow and closeLocation <= 1.0 - minimumImpulseCloseLocation)

// ============================================================================
// SECTION 13: OPTIONAL TREND / VOLUME / VWAP FILTERS
// ============================================================================
float trendSlopeATR = (not na(atr) and atr > 0 ? (trendEMA - trendEMA[trendSlopeBars]) / atr : 0.0)
float previousAverageVolume = ta.sma(volume, volumeLookback)[1]
float entryRVOL = (previousAverageVolume > 0 ? volume / previousAverageVolume : na)
var float cumulativePV = 0.0
var float cumulativeVolume = 0.0
if newTradingDay
    cumulativePV := 0.0
    cumulativeVolume := 0.0
if continuousSession and barstate.isconfirmed and not na(volume) and volume > 0
    cumulativePV += hlc3 * volume
    cumulativeVolume += volume
float sessionVWAP = cumulativeVolume > 0 ? cumulativePV / cumulativeVolume : na
bool longTrendOK = (not useTrendFilter or (close > trendEMA and trendSlopeATR >= 0))
bool shortTrendOK = (not useTrendFilter or (close < trendEMA and trendSlopeATR <= 0))
bool longVWAPOK = (not useVWAPFilter or (not na(sessionVWAP) and close > sessionVWAP))
bool shortVWAPOK = (not useVWAPFilter or (not na(sessionVWAP) and close < sessionVWAP))
bool volumeOK = (not useRVOLFilter or (not na(entryRVOL) and entryRVOL >= minimumEntryRVOL))

// ============================================================================
// SECTION 14: DAILY TRADE CONTROL
// ============================================================================
var int tradesToday = 0
var int closedTradesSeen = 0
var int lastExitBar = na
var int lastOrderBar = na
var float dayStartNetProfit = na
var bool tradedLongToday = false
var bool tradedShortToday = false
if newTradingDay
    tradesToday := 0
    dayStartNetProfit := strategy.netprofit
    tradedLongToday := false
    tradedShortToday := false
if strategy.closedtrades > closedTradesSeen
    closedTradesSeen := strategy.closedtrades
    lastExitBar := bar_index
bool flat = strategy.position_size == 0
bool inLong = strategy.position_size > 0
bool inShort = strategy.position_size < 0
bool allowLong = (tradeDirection != "Short" and (not oneTradePerDirection or not tradedLongToday))
bool allowShort = (tradeDirection != "Long" and (not oneTradePerDirection or not tradedShortToday))
float dailyClosedPnL = strategy.netprofit - nz(dayStartNetProfit, strategy.netprofit)
bool tradeCountOK = tradesToday < maximumTradesPerDay
bool cooldownOK = na(lastExitBar) or bar_index - lastExitBar > cooldownBars
bool oneOrderPerBar = na(lastOrderBar) or lastOrderBar != bar_index
bool dailyLossOK = not useDailyLossGuard or dailyClosedPnL > -maximumDailyLossVND
bool commonControlOK = (flat and entrySession and beforeCutoff and tradeCountOK and cooldownOK and oneOrderPerBar and dailyLossOK and volumeOK and barstate.isconfirmed)

// ============================================================================
// SECTION 15: PENDING IMPULSE / PULLBACK STATE
// ============================================================================
//  0: Waiting for directional impulse.
//  1: Bullish impulse, awaiting slow pullback or shallow-pause release.
// -1: Bearish impulse, awaiting slow pullback or shallow-pause release.
//  2: Slow bullish pullback registered; awaiting buy re-acceleration.
// -2: Slow bearish pullback registered; awaiting sell re-acceleration.
// ============================================================================
var int setupState = 0
var int impulseBar = na
var int pullbackBar = na
var float impulseStart = na
var float impulseEnd = na
var float impulseExtreme = na
var float impulseDistance = na
var float armedImpulseSpeed = na
var float pullbackLow = na
var float pullbackHigh = na
var float pullbackTrigger = na
bool bullImpulseMarker = false
bool bearImpulseMarker = false
bool bullPullbackMarker = false
bool bearPullbackMarker = false
bool rawLong = false
bool rawShort = false
float stopAnchor = na
if newTradingDay or morningBegins or afternoonBegins or lunchFlatBar or finalFlatBar
    setupState := 0
    impulseBar := na
    pullbackBar := na

// ============================================================================
// SECTION 16: PROCESS BULLISH IMPULSE / MEASURE SLOW RETRACEMENT
// ============================================================================
if setupState == 1 and barstate.isconfirmed and bar_index > impulseBar
    int elapsed = bar_index - impulseBar
    bool expired = elapsed > maximumSetupBars
    bool invalid = (close < impulseEnd - impulseDistance * maximumInvalidationFraction)
    if expired or invalid or not entrySession or not beforeCutoff
        setupState := 0
    else
        float retracement = (impulseDistance > 0 ? (impulseEnd - close) / impulseDistance : na)
        float counterSpeed = (elapsed > 0 ? math.max(impulseEnd - close, 0) / elapsed : na)
        bool slowPullback = (entryMode != "Shallow Pause Only" and not na(retracement) and retracement >= minimumRetracement and retracement <= maximumRetracement and not na(counterSpeed) and counterSpeed <= armedImpulseSpeed * maximumCounterVelocity)
        bool shallowPauseRelease = (entryMode != "Slow Pullback Only" and elapsed >= 2 and elapsed <= pauseEntryBars and not na(atr) and atr > 0 and low[1] >= impulseExtreme - atr * maximumPauseDepthATR and close > impulseExtreme + confirmationBuffer and close > high[1] and bullishCandle)
        if shallowPauseRelease
            rawLong := true
            stopAnchor := pauseRecentLow
            setupState := 0
        else if slowPullback
            pullbackBar := bar_index
            pullbackLow := low
            pullbackHigh := high
            pullbackTrigger := high
            bullPullbackMarker := true
            setupState := 2

// ============================================================================
// SECTION 17: PROCESS BEARISH IMPULSE / MEASURE SLOW RETRACEMENT
// ============================================================================
if setupState == -1 and barstate.isconfirmed and bar_index > impulseBar
    int elapsed = bar_index - impulseBar
    bool expired = elapsed > maximumSetupBars
    bool invalid = (close > impulseEnd + impulseDistance * maximumInvalidationFraction)
    if expired or invalid or not entrySession or not beforeCutoff
        setupState := 0
    else
        float retracement = (impulseDistance > 0 ? (close - impulseEnd) / impulseDistance : na)
        float counterSpeed = (elapsed > 0 ? math.max(close - impulseEnd, 0) / elapsed : na)
        bool slowPullback = (entryMode != "Shallow Pause Only" and not na(retracement) and retracement >= minimumRetracement and retracement <= maximumRetracement and not na(counterSpeed) and counterSpeed <= armedImpulseSpeed * maximumCounterVelocity)
        bool shallowPauseRelease = (entryMode != "Slow Pullback Only" and elapsed >= 2 and elapsed <= pauseEntryBars and not na(atr) and atr > 0 and high[1] <= impulseExtreme + atr * maximumPauseDepthATR and close < impulseExtreme - confirmationBuffer and close < low[1] and bearishCandle)
        if shallowPauseRelease
            rawShort := true
            stopAnchor := pauseRecentHigh
            setupState := 0
        else if slowPullback
            pullbackBar := bar_index
            pullbackLow := low
            pullbackHigh := high
            pullbackTrigger := low
            bearPullbackMarker := true
            setupState := -2

// ============================================================================
// SECTION 18: BULLISH COUNTER-MOVE -> RE-ACCELERATION
// ============================================================================
if setupState == 2 and barstate.isconfirmed and bar_index > pullbackBar
    bool expired = (bar_index - impulseBar > maximumSetupBars or bar_index - pullbackBar > maximumConfirmBars)
    bool invalid = (close < impulseEnd - impulseDistance * maximumInvalidationFraction)
    if expired or invalid or not entrySession or not beforeCutoff
        setupState := 0
    else
        bool microRecovered = (close > previousMicroHigh + confirmationBuffer and close > pullbackTrigger + confirmationBuffer and close >= impulseStart + impulseDistance * minimumRecoveryFraction and bullishCandle)
        if microRecovered
            rawLong := true
            stopAnchor := math.min(pullbackLow, low)
            setupState := 0
        else
            pullbackLow := math.min(pullbackLow, low)

// ============================================================================
// SECTION 19: BEARISH COUNTER-MOVE -> RE-ACCELERATION
// ============================================================================
if setupState == -2 and barstate.isconfirmed and bar_index > pullbackBar
    bool expired = (bar_index - impulseBar > maximumSetupBars or bar_index - pullbackBar > maximumConfirmBars)
    bool invalid = (close > impulseEnd + impulseDistance * maximumInvalidationFraction)
    if expired or invalid or not entrySession or not beforeCutoff
        setupState := 0
    else
        bool microRecovered = (close < previousMicroLow - confirmationBuffer and close < pullbackTrigger - confirmationBuffer and close <= impulseStart - impulseDistance * minimumRecoveryFraction and bearishCandle)
        if microRecovered
            rawShort := true
            stopAnchor := math.max(pullbackHigh, high)
            setupState := 0
        else
            pullbackHigh := math.max(pullbackHigh, high)

// ============================================================================
// SECTION 20: ARM NEW COMPLETED DIRECTIONAL IMPULSE
// ============================================================================
if setupState == 0 and not rawLong and not rawShort and commonControlOK
    if bullishImpulse and allowLong and longTrendOK and longVWAPOK
        setupState := 1
        impulseBar := bar_index
        impulseStart := close[impulseBars]
        impulseEnd := close
        impulseExtreme := high
        impulseDistance := netDisplacement
        armedImpulseSpeed := impulseSpeed
        bullImpulseMarker := true
    else if bearishImpulse and allowShort and shortTrendOK and shortVWAPOK
        setupState := -1
        impulseBar := bar_index
        impulseStart := close[impulseBars]
        impulseEnd := close
        impulseExtreme := low
        impulseDistance := -netDisplacement
        armedImpulseSpeed := impulseSpeed
        bearImpulseMarker := true

// ============================================================================
// SECTION 21: STOP / REWARD VALIDATION
// ============================================================================
float longStopReference = (stopMode == "Impulse Midpoint" ? impulseStart + impulseDistance * 0.5 : stopAnchor)
float shortStopReference = (stopMode == "Impulse Midpoint" ? impulseStart - impulseDistance * 0.5 : stopAnchor)
float candidateLongStop = (not na(atr) and atr > 0 ? math.round_to_mintick(stopMode == "ATR Fixed" ? close - atr * fixedStopATR : longStopReference - atr * stopBufferATR) : na)
float candidateShortStop = (not na(atr) and atr > 0 ? math.round_to_mintick(stopMode == "ATR Fixed" ? close + atr * fixedStopATR : shortStopReference + atr * stopBufferATR) : na)
float longRisk = close - candidateLongStop
float shortRisk = candidateShortStop - close
bool longRiskOK = (not na(longRisk) and longRisk >= minimumStopPoints and longRisk <= maximumStopPoints and longRisk * takeProfitR >= minimumGrossTarget)
bool shortRiskOK = (not na(shortRisk) and shortRisk >= minimumStopPoints and shortRisk <= maximumStopPoints and shortRisk * takeProfitR >= minimumGrossTarget)
float candidateLongTarget = (not na(longRisk) ? math.round_to_mintick(close + longRisk * takeProfitR) : na)
float candidateShortTarget = (not na(shortRisk) ? math.round_to_mintick(close - shortRisk * takeProfitR) : na)
bool finalLong = (rawLong and allowLong and longTrendOK and longVWAPOK and longRiskOK and commonControlOK)
bool finalShort = (rawShort and allowShort and shortTrendOK and shortVWAPOK and shortRiskOK and commonControlOK and not finalLong)

// ============================================================================
// SECTION 22: ACTIVE POSITION STATE
// ============================================================================
var float activeStop = na
var float activeTarget = na
var float actualEntryPrice = na
var float initialFillRisk = na
var int actualEntryBar = na
var int adverseCloseCount = 0
var bool breakEvenActive = false

// ============================================================================
// SECTION 23: LONG ENTRY / INITIAL BRACKET
// ============================================================================
if finalLong
    activeStop := candidateLongStop
    activeTarget := candidateLongTarget
    actualEntryPrice := na
    initialFillRisk := na
    actualEntryBar := na
    adverseCloseCount := 0
    breakEvenActive := false
    strategy.entry("CNPS65-L", strategy.long, comment="VELOCITY ASYMMETRY LONG", alert_message="🟢 VÀO VỊ THẾ LONG (Directional Velocity Asymmetry)\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\n🛑 SL dự kiến: " + str.tostring(activeStop, format.mintick) + "\n🎯 TP dự kiến: " + str.tostring(activeTarget, format.mintick))
    strategy.exit("CNPS65-L-X", from_entry="CNPS65-L", stop=activeStop, limit=activeTarget, comment_profit="TP Long", comment_loss="SL Long", alert_profit="💰 CHỐT LỜI LONG (TP HIT)\n🎯 Giá chốt: " + str.tostring(activeTarget, format.mintick), alert_loss="🛑 CẮT LỖ LONG (SL HIT)\n🎯 Giá cắt: " + str.tostring(activeStop, format.mintick))
    tradesToday += 1
    tradedLongToday := true
    lastOrderBar := bar_index
    setupState := 0

// ============================================================================
// SECTION 24: SHORT ENTRY / INITIAL BRACKET
// ============================================================================
else if finalShort
    activeStop := candidateShortStop
    activeTarget := candidateShortTarget
    actualEntryPrice := na
    initialFillRisk := na
    actualEntryBar := na
    adverseCloseCount := 0
    breakEvenActive := false
    strategy.entry("CNPS65-S", strategy.short, comment="VELOCITY ASYMMETRY SHORT", alert_message="🔴 VÀO VỊ THẾ SHORT (Directional Velocity Asymmetry)\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\n🛑 SL dự kiến: " + str.tostring(activeStop, format.mintick) + "\n🎯 TP dự kiến: " + str.tostring(activeTarget, format.mintick))
    strategy.exit("CNPS65-S-X", from_entry="CNPS65-S", stop=activeStop, limit=activeTarget, comment_profit="TP Short", comment_loss="SL Short", alert_profit="💰 CHỐT LỜI SHORT (TP HIT)\n🎯 Giá chốt: " + str.tostring(activeTarget, format.mintick), alert_loss="🛑 CẮT LỖ SHORT (SL HIT)\n🎯 Giá cắt: " + str.tostring(activeStop, format.mintick))
    tradesToday += 1
    tradedShortToday := true
    lastOrderBar := bar_index
    setupState := 0

// ============================================================================
// SECTION 25: FILLED RISK VALIDATION / BREAK EVEN
// ============================================================================
if strategy.position_size != 0 and strategy.opentrades > 0 and barstate.isconfirmed
    int fillBar = strategy.opentrades.entry_bar_index(0)
    float fillPrice = strategy.position_avg_price
    if na(actualEntryBar) or actualEntryBar != fillBar
        actualEntryBar := fillBar
        actualEntryPrice := fillPrice
        initialFillRisk := (inLong ? fillPrice - activeStop : activeStop - fillPrice)
    bool validFill = (not na(initialFillRisk) and initialFillRisk > syminfo.mintick and (inLong ? activeTarget > fillPrice : activeTarget < fillPrice))
    if not validFill
        strategy.close(inLong ? "CNPS65-L" : "CNPS65-S", immediately=true, comment="INVALID NEXT-BAR FILL", alert_message="🔄 ĐÓNG VỊ THẾ (Khớp lệnh không hợp lệ)\n🎯 Giá đóng: " + str.tostring(close, format.mintick))
    else
        float currentR = (inLong ? (close - fillPrice) / initialFillRisk : (fillPrice - close) / initialFillRisk)
        if useBreakEven and currentR >= breakEvenAtR
            float beStop = math.round_to_mintick(inLong ? fillPrice + breakEvenOffset : fillPrice - breakEvenOffset)
            activeStop := (inLong ? math.max(activeStop, beStop) : math.min(activeStop, beStop))
            breakEvenActive := true
        if inLong
            strategy.exit("CNPS65-L-X", from_entry="CNPS65-L", stop=activeStop, limit=activeTarget, comment_profit="TP Long", comment_loss=breakEvenActive ? "BE Long" : "SL Long", alert_profit="💰 CHỐT LỜI LONG (TP HIT)\n🎯 Giá chốt: " + str.tostring(activeTarget, format.mintick), alert_loss=breakEvenActive ? ("🛡️ HÒA VỐN LONG (BE HIT)\n🎯 Giá thoát: " + str.tostring(activeStop, format.mintick)) : ("🛑 CẮT LỖ LONG (SL HIT)\n🎯 Giá cắt: " + str.tostring(activeStop, format.mintick)))
        else
            strategy.exit("CNPS65-S-X", from_entry="CNPS65-S", stop=activeStop, limit=activeTarget, comment_profit="TP Short", comment_loss=breakEvenActive ? "BE Short" : "SL Short", alert_profit="💰 CHỐT LỜI SHORT (TP HIT)\n🎯 Giá chốt: " + str.tostring(activeTarget, format.mintick), alert_loss=breakEvenActive ? ("🛡️ HÒA VỐN SHORT (BE HIT)\n🎯 Giá thoát: " + str.tostring(activeStop, format.mintick)) : ("🛑 CẮT LỖ SHORT (SL HIT)\n🎯 Giá cắt: " + str.tostring(activeStop, format.mintick)))

// ============================================================================
// SECTION 26: OPTIONAL MOMENTUM FAILURE / MAXIMUM HOLD
// ============================================================================
if strategy.position_size != 0 and strategy.opentrades > 0 and barstate.isconfirmed
    bool counterAccelerating = (inLong ? (close < close[1] and close < open and candleBody >= 0.55 and close < trendEMA) : (close > close[1] and close > open and candleBody >= 0.55 and close > trendEMA))
    adverseCloseCount := (counterAccelerating ? adverseCloseCount + 1 : 0)
    if useVelocityFailureExit and adverseCloseCount >= failureCloses
        strategy.close(inLong ? "CNPS65-L" : "CNPS65-S", comment="DIRECTIONAL PERSISTENCE LOST", alert_message="⚡ ĐÓNG VỊ THẾ (Mất động lượng xu hướng)\n🎯 Giá đóng: " + str.tostring(close, format.mintick))
    int entryTimestamp = strategy.opentrades.entry_time(0)
    if (useTimeExit and not na(time_close) and time_close >= entryTimestamp + maximumHoldMinutes * 60000)
        strategy.close(inLong ? "CNPS65-L" : "CNPS65-S", comment="MAXIMUM HOLD", alert_message="⏱️ ĐÓNG VỊ THẾ (Hết thời gian giữ lệnh tối đa)\n🎯 Giá đóng: " + str.tostring(close, format.mintick))

// ============================================================================
// SECTION 27: LUNCH / PRE-ATC FORCE FLAT
// ============================================================================
if (lunchFlatBar or finalFlatBar) and strategy.position_size != 0
    strategy.close_all(immediately=true, comment="VN30F1M CONTINUOUS SESSION FLAT", alert_message="⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End)\n🎯 Giá đóng: " + str.tostring(close, format.mintick))

// ============================================================================
// SECTION 28: CLEAR CLOSED-POSITION DATA
// ============================================================================
if flat and not finalLong and not finalShort
    activeStop := na
    activeTarget := na
    actualEntryPrice := na
    initialFillRisk := na
    actualEntryBar := na
    adverseCloseCount := 0
    breakEvenActive := false

// ============================================================================
// SECTION 29: CLEAN CHART PLOTS
// ============================================================================
plot(showTrendEMA ? trendEMA : na, title="EMA Trend", color=color.orange, linewidth=1)
plot(showActiveLevels and strategy.position_size != 0 ? activeStop : na, title="Active Stop Loss", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showActiveLevels and strategy.position_size != 0 ? activeTarget : na, title="Active Take Profit", color=color.green, linewidth=2, style=plot.style_linebr)

// ============================================================================
// SECTION 30: CLEAN SIGNAL MARKERS - NO TABLE
// ============================================================================
plotshape(showImpulseMarkers and bullImpulseMarker, title="Bullish Directional Impulse", text="I+", style=shape.circle, location=location.belowbar, color=color.new(color.teal, 45), textcolor=color.white, size=size.tiny)
plotshape(showImpulseMarkers and bearImpulseMarker, title="Bearish Directional Impulse", text="I-", style=shape.circle, location=location.abovebar, color=color.new(color.red, 45), textcolor=color.white, size=size.tiny)
plotshape(showPullbackMarkers and bullPullbackMarker, title="Slow Bullish Pullback", text="PB+", style=shape.circle, location=location.belowbar, color=color.new(color.teal, 60), textcolor=color.white, size=size.tiny)
plotshape(showPullbackMarkers and bearPullbackMarker, title="Slow Bearish Pullback", text="PB-", style=shape.circle, location=location.abovebar, color=color.new(color.red, 60), textcolor=color.white, size=size.tiny)
plotshape(showEntrySignals and finalLong, title="CNPS65 LONG", text="L", style=shape.triangleup, location=location.belowbar, color=color.teal, textcolor=color.white, size=size.small)
plotshape(showEntrySignals and finalShort, title="CNPS65 SHORT", text="S", style=shape.triangledown, location=location.abovebar, color=color.red, textcolor=color.white, size=size.small)

// ============================================================================
// CNPS65 V1 - RESEARCH NOTES
// ============================================================================
// 1. Impulse speed = absolute directional net move / observation bars.
// 2. Impulse persistence = net move / absolute close-to-close path travel.
// 3. Counter-move is only accepted when slower than the original impulse.
// 4. Entry routes are a slow-pullback re-acceleration or shallow-pause break.
// 5. Signals rely on confirmed current / past candles, no future pivots.
// 6. Market entries normally fill on the following chart bar.
// 7. Initial stop/target are based on signal-close structure.
// 8. 12% margin is a simulation input, not a real broker margin requirement.
// 9. Closed-loss guard only prevents new positions, not open-position losses.
// 10. Strategy profitability and TradingView compilation are not verified.
// ============================================================================

2. Những khái niệm kỹ thuật cốt lõi trong CNPS65

2.1. Hiệu suất đường đi (Path Efficiency) và Vận tốc xung lực (Impulse Speed)

Bot không chỉ nhìn vào biên độ tăng/giảm thuần túy mà đo lường chất lượng đường đi của giá trong impulseBars = 6 nến:

  • Độ dịch chuyển ròng (netDisplacement): close - close[impulseBars].
  • Tổng quãng đường đóng cửa (closePathTravel): math.sum(math.abs(close - close[1]), impulseBars).
  • Hiệu suất đường đi (pathEfficiency): math.abs(netDisplacement) / closePathTravel. Giá trị càng tiến gần 1.0 chứng tỏ giá đi thẳng một mạch, ít rung lắc; mặc định yêu cầu >= 0.58.
  • Vận tốc xung lực (impulseSpeed): math.abs(netDisplacement) / impulseBars (số điểm dịch chuyển trung bình trên mỗi nến).

2.2. Bất đối xứng vận tốc ở nhịp hồi (Counter-Move Velocity Decay)

Khi một xung lực được ghi nhận (setupState = 1 hoặc -1), bot theo dõi số nến trôi qua (elapsed = bar_index - impulseBar):

  • Tỷ lệ hồi (retracement): Mức lùi lại so với impulseDistance, phải nằm trong vùng [0.16, 0.72].
  • Vận tốc hồi (counterSpeed): math.max(±(impulseEnd - close), 0) / elapsed.
  • Điều kiện bất đối xứng cốt lõi là counterSpeed <= armedImpulseSpeed * 0.90. Nếu giá hồi quá nhanh ngang ngửa xung lực gốc, setup sẽ bị loại vì có nguy cơ đảo chiều thực sự.

2.3. Hai tuyến vào lệnh: Slow Pullback vs Shallow Pause

Ở chế độ mặc định Hybrid, bot hỗ trợ song song 2 kịch bản tiếp diễn xu hướng:

  • Slow Pullback (Hồi chậm rồi tái tăng tốc): Khi ghi nhận nhịp hồi chậm (setupState = 2 hoặc -2), bot lưu vùng đỉnh/đáy hồi (pullbackTrigger) và chờ nến xác nhận phá vỡ cả đỉnh/đáy microBreakBars = 2 nến lẫn pullbackTrigger kèm khoảng đệm 0.10 điểm, đồng thời phục hồi tối thiểu 40% quãng đường xung lực.
  • Shallow Pause (Nghỉ nông rồi bứt phá): Nếu trong 2–4 nến sau xung lực, giá chỉ đi ngang/hồi rất nông không sâu quá 1.20 x ATR14 tính từ cực trị xung lực (impulseExtreme) và đóng cửa phá hẳn cực trị đó cộng 0.10 điểm với nến xác nhận đạt chuẩn, bot sẽ vào lệnh trực tiếp không cần qua bước setupState = ±2.

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

Quy trình vận hành của CNPS65 trên mỗi cây nến đóng cửa (barstate.isconfirmed) diễn ra tuần tự qua 5 bước:

  1. Khởi tạo phiên và kiểm soát đầu ngày: Xác định phiên liên tục sáng (09:00–11:30), chiều (13:00–14:30) theo múi giờ Asia/Ho_Chi_Minh. Reset biến đếm lệnh tradesToday, trạng thái tradedLongToday/tradedShortToday, dayStartNetProfit và dữ liệu Session VWAP khi sang ngày mới; reset setupState = 0 khi đổi phiên hoặc đến giờ Flat.
  2. Săn tìm xung lực (setupState == 0): Khi thỏa mãn commonControlOK, bot kiểm tra điều kiện bullishImpulse hoặc bearishImpulse (kèm bộ lọc EMA/VWAP nếu bật). Nếu đạt, bot chuyển setupState sang 1 (Tăng) hoặc -1 (Giảm) và lưu lại impulseStart, impulseEnd, impulseExtreme, impulseDistance, armedImpulseSpeed.
  3. Đo lường nhịp hồi / nghỉ nông (setupState == ±1): Trên các nến kế tiếp, nếu không bị quá hạn (elapsed > 10) hoặc hồi sâu quá mức hủy (> 90% xung lực), bot kiểm tra shallowPauseRelease (vào lệnh ngay) hoặc slowPullback (chuyển sang setupState = ±2).
  4. Xác nhận tái tăng tốc (setupState == ±2): Theo dõi tối đa 6 nến sau khi ghi nhận pullback (và tổng không quá 10 nến từ xung lực). Khi giá phá vỡ cấu trúc vi mô + pullbackTrigger và đạt minimumRecoveryFraction = 0.40, tín hiệu rawLong/rawShort được kích hoạt.
  5. Kiểm định Risk, gửi lệnh và quản trị vị thế: Tính toán SL/TP dự kiến, kiểm tra nằm trong [1.50, 12.0] điểm và TP gộp >= 2.50 điểm. Sau khi khớp lệnh ở nến kế tiếp, bot liên tục kiểm tra tính hợp lệ của giá khớp (validFill), kích hoạt Break Even (nếu bật), kiểm tra mất động lượng hoặc quá 45 phút giữ lệnh, và đóng toàn bộ vị thế trước 11:25 / 14:25.

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

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

  1. Xung lực tăng (bullishImpulse): barsSinceSessionStart > 6, netDisplacement > 0, math.abs(netDisplacement) >= 1.50 * ATR14, pathEfficiency >= 0.58, close > ta.highest(high, 5)[1], và closeLocation >= 0.58.
  2. Kích hoạt tín hiệu (rawLong):
    • Nhánh Shallow Pause: elapsed trong [2, 4], low[1] >= impulseExtreme - 1.20 * ATR14, close > impulseExtreme + 0.10, close > high[1], và nến tăng đạt chuẩn (bullishCandle: close > open, thân nến >= 0.30, closeLocation >= 0.60).
    • Nhánh Slow Pullback: Đã qua slowPullback (retracement trong [0.16, 0.72], counterSpeed <= armedImpulseSpeed * 0.90), sau đó close > previousMicroHigh + 0.10, close > pullbackTrigger + 0.10, close >= impulseStart + impulseDistance * 0.40, và đạt bullishCandle.
  3. Bộ lọc bổ sung & Rủi ro (finalLong): Thỏa allowLong (tradeDirection != "Short"), longTrendOK (nếu bật: close > trendEMA và độ dốc EMA >= 0), longVWAPOK (nếu bật: close > sessionVWAP), longRiskOK (longRisk trong [1.50, 12.0] điểm và longRisk * 1.60 >= 2.50), cùng commonControlOK.

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

  1. Xung lực giảm (bearishImpulse): barsSinceSessionStart > 6, netDisplacement < 0, math.abs(netDisplacement) >= 1.50 * ATR14, pathEfficiency >= 0.58, close < ta.lowest(low, 5)[1], và closeLocation <= 0.42.
  2. Kích hoạt tín hiệu (rawShort):
    • Nhánh Shallow Pause: elapsed trong [2, 4], high[1] <= impulseExtreme + 1.20 * ATR14, close < impulseExtreme - 0.10, close < low[1], và nến giảm đạt chuẩn (bearishCandle: close < open, thân nến >= 0.30, closeLocation <= 0.40).
    • Nhánh Slow Pullback: Đã qua slowPullback, sau đó close < previousMicroLow - 0.10, close < pullbackTrigger - 0.10, close <= impulseStart - impulseDistance * 0.40, và đạt bearishCandle.
  3. Bộ lọc bổ sung & Rủi ro (finalShort): Thỏa allowShort, shortTrendOK, shortVWAPOK, shortRiskOK, commonControlOK và not finalLong.

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

Biến commonControlOK chỉ cho phép vào lệnh khi đồng thời thỏa mãn tất cả các điều kiện sau trên nến đã đóng (barstate.isconfirmed):

  • Trạng thái phẳng (flat): strategy.position_size == 0 (pyramiding = 0).
  • Khung giờ vào lệnh (entrySession & beforeCutoff): Nằm trong phiên sáng 09:10–11:20 hoặc chiều 13:05–14:15, đồng thời time_close trước 11:25 (nếu closeBeforeLunch = true) và trước 14:25.
  • Giới hạn số lệnh & Cooldown: tradesToday < 5, khoảng cách từ lần thoát lệnh gần nhất bar_index - lastExitBar > 2 nến, và không gửi quá 1 lệnh trên cùng 1 nến (oneOrderPerBar).
  • Bảo vệ lỗ ngày (dailyLossOK): Lỗ đã chốt trong ngày (dailyClosedPnL) chưa chạm ngưỡng -2,400,000 VND.
  • Khối lượng (volumeOK): Nếu bật useRVOLFilter, entryRVOL phải đạt từ 0.85 trở lên.

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

5.1. Cơ chế Stop Loss và bộ lọc Risk

Bot cung cấp 3 chế độ đặt cắt lỗ (stopMode), mặc định là Pullback Structure:

  • Pullback Structure (Mặc định): Neo SL tại đáy/đỉnh của nhịp nghỉ 3 nến (pauseRecentLow/pauseRecentHigh) đối với nhánh Shallow Pause, hoặc math.min(pullbackLow, low) / math.max(pullbackHigh, high) đối với nhánh Slow Pullback, cộng thêm khoảng đệm 0.15 x ATR14.
  • Impulse Midpoint: Neo SL tại điểm giữa (50%) của xung lực gốc (impulseStart ± impulseDistance * 0.5) cộng thêm khoảng đệm 0.15 x ATR14.
  • ATR Fixed: Đặt SL cách giá đóng cửa tín hiệu một khoảng cố định 1.30 x ATR14.

Sau khi tính candidateLongStop/candidateShortStop, bộ lọc Risk yêu cầu khoảng cách SL phải nằm trong [1.50, 12.0] điểm và mục tiêu lợi nhuận gộp (Risk * 1.60) tối thiểu đạt 2.50 điểm.

5.2. Cơ chế Take Profit, Break Even và Thoát lệnh

  • Take Profit cố định theo R: activeTarget = close ± Risk * 1.60, làm tròn theo syminfo.mintick.
  • Kiểm tra khớp lệnh nến kế tiếp (validFill): Vì lệnh Market khớp ở nến sau, bot kiểm tra ngay khi khớp nếu initialFillRisk <= syminfo.mintick hoặc giá khớp đã vượt qua activeTarget thì đóng lệnh ngay lập tức (INVALID NEXT-BAR FILL).
  • Break Even (Tùy chọn, mặc định false): Nếu bật useBreakEven, khi lợi nhuận đóng cửa đạt >= 1.00R, SL được dời về fillPrice ± 0.20 điểm.
  • Thoát khi mất động lượng (Tùy chọn, mặc định false): Nếu bật useVelocityFailureExit, khi xuất hiện 2 nến đóng cửa liên tiếp ngược hướng với thân nến >= 0.55 và nằm dưới/trên trendEMA, bot sẽ đóng lệnh (DIRECTIONAL PERSISTENCE LOST).
  • Giới hạn thời gian giữ lệnh (useTimeExit = true): Tự động đóng vị thế nếu thời gian nắm giữ đạt 45 phút (MAXIMUM HOLD).
  • Đóng lệnh cuối phiên: Bắt buộc đóng toàn bộ vị thế (strategy.close_all) tại nến chạm mốc 11:25 (trước nghỉ trưa) và 14:25 (trước ATC).

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

Cơ chế bảo vệTrạng thái mặc địnhĐiều kiện kích hoạtHành động của Bot
Stop Loss cấu trúcBật (Pullback Structure)Giá chạm mức SL (± 0.15 ATR14)Đóng lệnh cắt lỗ (SL Long/SL Short)
Take Profit theo RBật (1.60R)Giá chạm mức TP (>= 2.50 điểm)Chốt lời toàn bộ (TP Long/TP Short)
Invalid Next-Bar FillLuôn bậtGiá khớp nến sau làm Risk <= mintick hoặc vượt TPĐóng lệnh ngay (INVALID NEXT-BAR FILL)
Break EvenTắt (false)Lãi đóng cửa >= 1.00RDời SL về giá vốn ± 0.20 điểm
Velocity Failure ExitTắt (false)2 nến liên tiếp đảo chiều thân >= 0.55 qua EMAĐóng lệnh sớm (DIRECTIONAL PERSISTENCE LOST)
Maximum Hold TimeBật (true)Giữ lệnh quá 45 phútĐóng lệnh hết giờ (MAXIMUM HOLD)
Session Force FlatBật (true)Chạm mốc 11:25 hoặc 14:25Đóng toàn bộ vị thế (VN30F1M CONTINUOUS SESSION FLAT)
Daily Closed Loss GuardBật (true)Lỗ đã chốt trong ngày >= 2,400,000 VNDChặn mở lệnh mới trong phần còn lại của 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 (khuyến nghị khung thời gian intraday như 1m, 3m hoặc 5m).
  2. Mở tab Pine Editor ở thanh công cụ phía dưới màn hình.
  3. Xóa toàn bộ code mẫu mặc định, sao chép toàn bộ mã nguồn Pine Script v6 tại Mục 1 và dán vào Pine Editor.
  4. Nhấn Save (Lưu) để đặt tên cho chiến lược, sau đó nhấn Add to chart (Thêm vào biểu đồ).
  5. Nhấp vào biểu tượng bánh răng (Settings) bên cạnh tên chiến lược CNPS65 DVA V1 để tùy chỉnh số hợp đồng (contracts), chế độ vào lệnh (Hybrid / Slow Pullback Only / Shallow Pause Only) hoặc bật/tắt các bộ lọc EMA, VWAP, RVOL theo nhu cầu.

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

Lưu ý quan trọng theo đúng thiết kế mã nguồn: Bot CNPS65 không sử dụng bảng chẩn đoán (table.new) trên biểu đồ (được ghi chú rõ NO DASHBOARD / NO TABLE trong code nhằm giữ biểu đồ sạch và tối ưu hiệu năng). Thay vào đó, bạn theo dõi trực tiếp các thành phần hiển thị trên đồ thị giá:

  • Mũi tên L (xanh ngọc) / S (đỏ): Vị trí xác nhận tín hiệu vào lệnh Long hoặc Short chính thức (showEntrySignals = true).
  • Đường Active Stop Loss (đỏ) & Active Take Profit (xanh lá): Hiển thị trực tiếp mức cắt lỗ và chốt lời đang có hiệu lực khi có vị thế mở (showActiveLevels = true).
  • Nhãn I+ / I- và PB+ / PB- (tùy chọn bật trong mục 10 - Display): Đánh dấu nến hoàn thành xung lực (Bullish/Bearish Directional Impulse) và nến ghi nhận nhịp hồi chậm (Slow Pullback).
  • Đường EMA Trend (cam, tùy chọn): Hiển thị đường EMA 34 khi bật showTrendEMA.

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 qua ứng dụng TradingView, Telegram hoặc kết nối Webhook đặt lệnh, bạn thực hiện thiết lập Alert như sau:

  1. Nhấn vào biểu tượng Alert (hình đồng hồ báo thức) trên thanh công cụ bên phải hoặc nhấn Alt + A.
  2. Tại mục Condition, chọn chiến lược CNPS65 DIRECTIONAL VELOCITY ASYMMETRY V1 - VN30F1M.
  3. Tại mục Message, xóa nội dung mặc định và nhập đúng cú pháp: {{strategy.order.alert_message}}.
  4. Chọn phương thức nhận thông báo (Notify on app, Webhook URL, Email…) và nhấn Create.

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

Sự kiệnLệnh / Tham số trong codeNội dung thông điệp Alert
Vào lệnh LongCNPS65-L (alert_message)🟢 VÀO VỊ THẾ LONG (Directional Velocity Asymmetry) kèm Giá vào, SL dự kiến, TP dự kiến
Vào lệnh ShortCNPS65-S (alert_message)🔴 VÀO VỊ THẾ SHORT (Directional Velocity Asymmetry) kèm Giá vào, SL dự kiến, TP dự kiến
Chốt lời Long / ShortCNPS65-L-X / CNPS65-S-X (alert_profit)💰 CHỐT LỜI LONG (TP HIT) hoặc 💰 CHỐT LỜI SHORT (TP HIT) kèm Giá chốt
Cắt lỗ Long / ShortCNPS65-L-X / CNPS65-S-X (alert_loss)🛑 CẮT LỖ LONG (SL HIT) hoặc 🛑 CẮT LỖ SHORT (SL HIT) kèm Giá cắt
Thoát hòa vốn (khi bật BE)CNPS65-L-X / CNPS65-S-X (alert_loss)🛡️ HÒA VỐN LONG (BE HIT) hoặc 🛡️ HÒA VỐN SHORT (BE HIT) kèm Giá thoát
Khớp lệnh không hợp lệINVALID NEXT-BAR FILL🔄 ĐÓNG VỊ THẾ (Khớp lệnh không hợp lệ) kèm Giá đóng
Mất động lượng (khi bật)DIRECTIONAL PERSISTENCE LOST⚡ ĐÓNG VỊ THẾ (Mất động lượng xu hướng) kèm Giá đóng
Hết thời gian giữ lệnhMAXIMUM HOLD⏱️ ĐÓNG VỊ THẾ (Hết thời gian giữ lệnh tối đa) kèm Giá đóng
Đóng vị thế hết phiênVN30F1M CONTINUOUS SESSION FLAT⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End) kèm Giá đóng

Kết luận

Bot CNPS65 Directional Velocity Asymmetry V1 là một hệ thống giao dịch phái sinh VN30F1M có tính kỷ luật cao, giải quyết trực diện bài toán chọn điểm vào sau xung lực bằng cách lượng hóa hiệu suất đường đi (Path Efficiency) và sự suy giảm vận tốc ở nhịp hồi. Chiến lược đặc biệt phù hợp với các phiên thị trường có xung lực rõ ràng, cấu trúc sóng tiếp diễn mạch lạc và cần bộ khung quản trị rủi ro chặt chẽ theo R cũng như thời gian giữ lệnh.

Bạn có thể tham khảo thêm các hệ thống giao dịch VN30F1M khác như Bot CNPS50 - Trend Analysis V2 và Bot CNPS49 - Daily Open để so sánh và lựa chọn phương pháp phù hợp với phong cách 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