Hướng Dẫn Sử Dụng Bot CNPS58 - Basis Trend Contradiction V1 cho VN30F1M
TradingviewBot CNPS58 khai thác sự phân kỳ tạm thời giữa VN30F1M và VN30 Spot bằng Basis Z-Score, kết hợp lọc xu hướng Spot, độ trễ tương đối và quản trị rủi ro theo cấu trúc giá.

Mục lục
Khi giao dịch hợp đồng tương lai chỉ số VN30F1M, nhà đầu tư thường xuyên đối mặt với hiện tượng lệch pha ngắn hạn giữa giá phái sinh và chỉ số cơ sở VN30 Spot: chỉ số VN30 đã xác nhận xu hướng rõ ràng, nhưng hợp đồng tương lai VN30F1M lại phản ứng thái quá ngược chiều (giảm sâu hơn khi Spot tăng, hoặc tăng quá đà khi Spot giảm), tạo ra mức Basis chiết khấu (Discount) hoặc Basis thặng dư (Premium) cực đoan.
Chiến lược CNPS58 BASIS TREND CONTRADICTION V1 - VN30F1M (tên rút gọn CNPS58 BASIS V1), được lập trình trên nền tảng Pine Script v6 của TradingView, giải quyết trực tiếp bài toán giao dịch hội tụ giá trị tương đối (relative-value convergence) giữa VN30F1M và HOSE:VN30.
Những điểm nổi bật cốt lõi của Bot CNPS58:
- Đồng bộ dữ liệu Spot không lookahead: Lấy trực tiếp dữ liệu
HOSE:VN30quarequest.securityvớigaps=barmerge.gaps_onvàlookahead=barmerge.lookahead_off, đảm bảo không dùng dữ liệu tương lai và không tự điền giá cũ khi thiếu nến Spot. - Mô hình hóa Basis bằng Z-Score: Định lượng mức độ lệch pha giữa Futures và Spot theo cửa sổ trượt 55 nến, chỉ kích hoạt Setup khi
Basis Z-Scorevượt ngưỡng cực đoan và bắt đầu có dấu hiệu hồi phục. - Bộ lọc kép Xu hướng Spot & Độ trễ tương đối (Relative Lag): Chỉ cho phép nạp Setup khi VN30 Spot giữ vững cấu trúc EMA 21/55 cùng độ dốc chuẩn hóa theo ATR, đồng thời Futures thực sự tụt lại hoặc vượt quá Spot đủ lớn (
minimumLagPoints = 1.20điểm). - Quản trị rủi ro đa tầng: Kết hợp Stop Loss theo cực trị cấu trúc Setup + đệm ATR, Take Profit cố định
1.6R, thoát lệnh thống kê khi Basis chuẩn hóa, giới hạn thời gian giữ lệnh (45nến) và khóa giao dịch nếu lỗ thực hiện trong ngày chạm-2,400,000 VND.
1. CNPS58 Basis Trend Contradiction V1 là gì?
CNPS58 Basis Trend Contradiction V1 là hệ thống giao dịch tự động theo cơ chế hội tụ Basis thuận xu hướng cơ sở, vận hành dựa trên 4 trụ cột kỹ thuật chính:
- Động cơ xu hướng VN30 Spot (Spot Trend Engine): Đánh giá hướng đi chủ đạo của chỉ số
HOSE:VN30thông qua cấu trúcEMA 21vàEMA 55, độ dốc chuẩn hóa củaEMA 21trênATR(14)và tùy chọn phá vỡ đỉnh/đáy15nến. - Mô hình chuẩn hóa Basis (Basis Normalization Model): Tính chênh lệch tức thời
Basis = close (VN30F1M) - spotClose (VN30)và chuyển đổi thànhBasis Z-Scoretrên cửa sổ55nến để phát hiện trạng thái chiết khấu/thặng dư bất thường. - Bộ lọc độ trễ tương đối & Xác nhận nến Futures (Relative Lag & Price Confirmation): Kiểm tra mức chênh lệch biến động giá giữa Spot và Futures trong
5nến gần nhất (relativeLag), sau đó chờ nến VN30F1M xác nhận đảo chiều quaEMA 9và tỷ lệ thân nến (bodyRatio >= 0.25). - Hệ thống bảo vệ vị thế & Kiểm soát phiên (Risk & Session Control): Giới hạn giao dịch trong khung giờ chuẩn VN30F1M (
09:10–11:20và13:10–14:10), tối đa3lệnh/ngày, đóng toàn bộ vị thế trước phiên ATC lúc14:25, cùng các cơ chế thoát lệnh theo R, thống kê Basis và thời gian nắm giữ.
Bảng thông số mặc định
| Nhóm thông số | Tên tham số trong code | Giá trị mặc định | Ý nghĩa |
|---|---|---|---|
| Trade Control | tradeDirection | "Both" | Hướng giao dịch cho phép (Long, Short, Both) |
| Trade Control | contracts | 3 | Số hợp đồng mỗi lệnh (thông số tham chiếu) |
| Trade Control | maximumTradesPerDay | 3 | Số lệnh tối đa trong một ngày |
| Trade Control | cooldownBars | 5 | Số nến nghỉ tối thiểu sau khi đóng lệnh |
| Spot Reference | referenceSymbol | "HOSE:VN30" | Mã chỉ số cơ sở tham chiếu |
| Spot Reference | spotFastEMALength / spotSlowEMALength | 21 / 55 | Chu kỳ EMA nhanh và chậm trên VN30 Spot |
| Spot Reference | spotSlopeBars / spotStructureBars | 5 / 15 | Số nến tính độ dốc EMA và đỉnh/đáy cấu trúc Spot |
| Basis Model | basisLookback / minimumBasisStdev | 55 / 0.30 | Cửa sổ tính Mean/Stdev Basis và độ lệch chuẩn tối thiểu |
| Basis Model | entryZScore / minimumZRecovery / minimumRemainingZ | 1.25 / 0.25 / 0.15 | Ngưỡng Z-Score nạp Setup, mức hồi tối thiểu và độ lệch Z còn lại |
| Spot Trend | useSpotTrendFilter / minimumSpotSlopeATR | true / 0.08 | Bật lọc xu hướng Spot và độ dốc tối thiểu theo ATR |
| Spot Trend | requireSpotStructureBreak | false | Yêu cầu Spot phá đỉnh/đáy 15 nến |
| Relative Lag | useRelativeLagFilter / lagLookback / minimumLagPoints | true / 5 / 1.20 | Lọc độ trễ tương đối giữa Spot và Futures trong 5 nến |
| Setup Control | maximumSetupBars / resetSetupAtAfternoon | 12 / true | Thời hạn Setup tối đa 12 nến; reset khi mở phiên chiều |
| Setup Control | invalidateOnNewPriceExtreme | false | Hủy Setup nếu Futures tạo cực trị giá mới |
| Confirmation | futuresEMALength / requireFuturesEMA | 9 / true | EMA 9 xác nhận hướng giá trên VN30F1M |
| Confirmation | requirePreviousHighLowBreak / minimumBodyRatio | false / 0.25 | Phá High/Low nến trước; tỷ lệ thân/biên độ nến tối thiểu 25% |
| Risk Management | stopBufferATR / minimumStopPoints / maximumStopPoints | 0.15 / 2.0 / 12.0 | Đệm SL theo ATR(14) và biên độ rủi ro hợp lệ 2.0–12.0 điểm |
| Risk Management | takeProfitR / minimumGrossTarget | 1.60 / 3.50 | Mục tiêu chốt lời 1.6R và tối thiểu 3.50 điểm |
| Statistical Exit | useBasisMeanExit / statisticalExitZ / minimumStatExitProfit | true / 0.20 / 2.50 | Thoát lệnh khi Z về gần 0 (±0.20) và lãi mở ≥ 2.50 điểm |
| Exit Management | useBreakEven / breakEvenAtR / breakEvenOffset | false / 1.00 / 0.20 | Dời SL hòa vốn (tắt mặc định) |
| Exit Management | useTimeExit / maximumHoldBars | true / 45 | Đóng lệnh nếu giữ quá 45 nến |
| Daily Protection | useDailyLossGuard / maximumDailyLossVND | true / 2400000 | Chặn vào lệnh mới khi lỗ đã chốt trong ngày ≥ 2,400,000 VND |
| Session | morningEntry / afternoonEntry / forceClose | 0910-1120 / 1310-1410 / 14:25 | Khung giờ vào lệnh sáng/chiều và giờ đóng lệnh cưỡng bức |
Source Code CNPS58 Basis Trend Contradiction 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
// CNPS58 - Original VN30F1M Strategy
// BASIS-TREND CONTRADICTION V1
// Futures / VN30 Spot relative-value convergence.
strategy(title="CNPS58 BASIS TREND CONTRADICTION V1 - VN30F1M", shorttitle="CNPS58 BASIS V1", overlay=true, initial_capital=100000000, currency=currency.VND, 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=false, calc_on_order_fills=false, calc_on_every_tick=false, max_labels_count=300, max_lines_count=300, max_bars_back=5000)
// ============================================================================
// CNPS58 BASIS TREND CONTRADICTION V1
//
// CORE HYPOTHESIS:
//
// VN30 SPOT has a confirmed direction, but VN30F1M moves
// disproportionately against that direction.
//
// LONG:
// 1. VN30 Spot maintains a bullish structure.
// 2. Futures underperforms Spot.
// 3. Basis Z-Score reaches an extreme discount.
// 4. Basis contraction begins.
// 5. Futures confirms bullish price recovery.
// 6. Enter LONG.
//
// SHORT:
// 1. VN30 Spot maintains a bearish structure.
// 2. Futures outperforms Spot.
// 3. Basis Z-Score reaches an extreme premium.
// 4. Basis contraction begins.
// 5. Futures confirms bearish price movement.
// 6. Enter SHORT.
//
// Basis = Futures Close - VN30 Spot Close.
//
// Structural SL + Fixed R TP.
// Optional statistical exit on Basis normalization.
//
// 3 CONTRACTS / VN30F1M / CURRENT CHART TIMEFRAME.
// ============================================================================
// ============================================================================
// SECTION 1: TRADE CONTROL
// ============================================================================
tradeDirection = input.string("Both", title="Trade Direction", options=["Long", "Short", "Both"], group="Trade Control")
contracts = input.int(3, title="Contracts Per Entry", minval=1, maxval=20, group="Trade Control")
maximumTradesPerDay = input.int(3, title="Maximum Trades Per Day", minval=1, maxval=15, group="Trade Control")
cooldownBars = input.int(5, title="Cooldown Bars After Exit", minval=0, maxval=100, group="Trade Control")
// ============================================================================
// SECTION 2: VN30 SPOT REFERENCE
// ============================================================================
referenceSymbol = input.symbol("HOSE:VN30", title="VN30 Spot Reference", group="Spot Reference")
spotFastEMALength = input.int(21, title="Spot Fast EMA", minval=3, maxval=200, group="Spot Reference")
spotSlowEMALength = input.int(55, title="Spot Slow EMA", minval=10, maxval=300, group="Spot Reference")
spotSlopeBars = input.int(5, title="Spot Fast EMA Slope Lookback", minval=1, maxval=50, group="Spot Reference")
spotStructureBars = input.int(15, title="Spot Structure Lookback", minval=3, maxval=100, group="Spot Reference")
// ============================================================================
// SECTION 3: BASIS NORMALIZATION
// ============================================================================
basisLookback = input.int(55, title="Basis Mean / Standard Deviation Window", minval=20, maxval=500, group="Basis Model")
minimumBasisStdev = input.float(0.30, title="Minimum Basis Standard Deviation", minval=0.01, step=0.05, group="Basis Model")
entryZScore = input.float(1.25, title="Absolute Z-Score To Arm Setup", minval=0.50, maxval=4.0, step=0.05, group="Basis Model")
minimumZRecovery = input.float(0.25, title="Minimum Z-Score Recovery From Extreme", minval=0.05, maxval=2.0, step=0.05, group="Basis Model")
minimumRemainingZ = input.float(0.15, title="Minimum Remaining Z Dislocation At Entry", minval=0.0, maxval=2.0, step=0.05, group="Basis Model")
// ============================================================================
// SECTION 4: SPOT TREND CONFIRMATION
// ============================================================================
useSpotTrendFilter = input.bool(true, title="Require Confirmed Spot Trend?", group="Spot Trend")
minimumSpotSlopeATR = input.float(0.08, title="Minimum Spot EMA Slope / ATR", minval=0.0, maxval=3.0, step=0.02, group="Spot Trend")
requireSpotStructureBreak = input.bool(false, title="Require Spot Breakout Of Recent High / Low?", group="Spot Trend")
// ============================================================================
// SECTION 5: FUTURES RELATIVE LAG
// ============================================================================
useRelativeLagFilter = input.bool(true, title="Require Futures / Spot Relative Underperformance?", group="Relative Lag")
lagLookback = input.int(5, title="Relative Performance Lookback Bars", minval=1, maxval=50, group="Relative Lag")
minimumLagPoints = input.float(1.20, title="Minimum Futures / Spot Lag (points)", minval=0.0, maxval=20.0, step=0.20, group="Relative Lag")
// ============================================================================
// SECTION 6: SETUP LIFETIME
// ============================================================================
maximumSetupBars = input.int(12, title="Maximum Bars To Confirm Basis Reversal", minval=2, maxval=100, group="Setup Control")
resetSetupAtAfternoon = input.bool(true, title="Reset Pending Setup At Afternoon Open?", group="Setup Control")
invalidateOnNewPriceExtreme = input.bool(false, title="Cancel If Futures Makes A New Extreme?", group="Setup Control")
// ============================================================================
// SECTION 7: FUTURES PRICE CONFIRMATION
// ============================================================================
futuresEMALength = input.int(9, title="Futures Confirmation EMA", minval=2, maxval=100, group="Confirmation")
requireFuturesEMA = input.bool(true, title="Require Futures Price Above / Below EMA?", group="Confirmation")
requirePreviousHighLowBreak = input.bool(false, title="Require Previous Candle High / Low Break?", group="Confirmation")
minimumBodyRatio = input.float(0.25, title="Minimum Confirmation Candle Body / Range", minval=0.0, maxval=1.0, step=0.05, group="Confirmation")
// ============================================================================
// SECTION 8: HARD RISK MANAGEMENT
// ============================================================================
stopBufferATR = input.float(0.15, title="Stop Buffer Beyond Setup Extreme x ATR", minval=0.0, maxval=2.0, step=0.05, group="Risk Management")
minimumStopPoints = input.float(2.0, title="Minimum Stop Distance (points)", minval=0.1, step=0.5, group="Risk Management")
maximumStopPoints = input.float(12.0, title="Maximum Stop Distance (points)", minval=0.5, step=0.5, group="Risk Management")
takeProfitR = input.float(1.60, title="Take Profit Multiple (R)", minval=0.25, maxval=8.0, step=0.10, group="Risk Management")
minimumGrossTarget = input.float(3.50, title="Minimum Gross Profit Target (points)", minval=0.0, step=0.5, group="Risk Management")
// ============================================================================
// SECTION 9: STATISTICAL BASIS EXIT
// ============================================================================
useBasisMeanExit = input.bool(true, title="Exit On Basis Normalization?", group="Statistical Exit")
statisticalExitZ = input.float(0.20, title="Basis Z Distance From Mean For Exit", minval=0.0, maxval=2.0, step=0.05, group="Statistical Exit")
minimumStatExitProfit = input.float(2.50, title="Minimum Open Profit Before Basis Exit (points)", minval=0.0, step=0.5, group="Statistical Exit")
// ============================================================================
// SECTION 10: OPTIONAL BREAK EVEN / TIME EXIT
// ============================================================================
useBreakEven = input.bool(false, title="Use Break Even?", group="Exit Management")
breakEvenAtR = input.float(1.00, title="Move Stop At R", minval=0.25, maxval=5.0, step=0.25, group="Exit Management")
breakEvenOffset = input.float(0.20, title="Break Even Offset (points)", minval=0.0, step=0.10, group="Exit Management")
useTimeExit = input.bool(true, title="Use Maximum Hold Time?", group="Exit Management")
maximumHoldBars = input.int(45, title="Maximum Hold Bars", minval=5, maxval=300, group="Exit Management")
// ============================================================================
// SECTION 11: DAILY LOSS PROTECTION
// ============================================================================
useDailyLossGuard = input.bool(true, title="Block New Entries After Daily Realized Loss?", group="Daily Protection")
maximumDailyLossVND = input.float(2400000, title="Daily Realized Loss Limit (VND)", minval=100000, step=100000, group="Daily Protection")
// ============================================================================
// SECTION 12: VN30F1M SESSION
// ============================================================================
string strategyTimezone = "Asia/Ho_Chi_Minh"
morningEntry = input.session("0910-1120", title="Morning Entry Window", group="Session")
afternoonEntry = input.session("1310-1410", title="Afternoon Entry Window", group="Session")
forceCloseHour = input.int(14, title="Force Close Hour", minval=0, maxval=23, group="Session")
forceCloseMinute = input.int(25, title="Force Close Minute", minval=0, maxval=59, group="Session")
// ============================================================================
// SECTION 13: DISPLAY
// ============================================================================
showFuturesEMA = input.bool(false, title="Show Futures Confirmation EMA?", group="Display")
showEntrySignals = input.bool(true, title="Show Entry Signals?", group="Display")
showSetupSignals = input.bool(false, title="Show Basis Extreme Setup Markers?", group="Display")
showActiveSLTP = input.bool(true, title="Show Active Stop / Target?", group="Display")
showDiagnostics = input.bool(true, title="Show Diagnostics?", group="Display")
// ============================================================================
// SECTION 14: TIME ENGINE
// ============================================================================
int currentMinute = (hour(time, strategyTimezone) * 60 + minute(time, strategyTimezone))
int currentCloseMinute = (hour(time_close, strategyTimezone) * 60 + minute(time_close, strategyTimezone))
int forceCloseTotal = (forceCloseHour * 60 + forceCloseMinute)
bool morningSession = not na(time(timeframe.period, morningEntry + ":23456", strategyTimezone))
bool afternoonSession = not na(time(timeframe.period, afternoonEntry + ":23456", strategyTimezone))
bool entrySession = morningSession or afternoonSession
bool afternoonBegins = (afternoonSession and not afternoonSession[1])
int dayKey = (year(time, strategyTimezone) * 10000 + month(time, strategyTimezone) * 100 + dayofmonth(time, strategyTimezone))
bool newTradingDay = (bar_index == 0 or dayKey != nz(dayKey[1], dayKey))
bool beforeForceClose = (not na(time_close) and currentCloseMinute < forceCloseTotal)
bool forceCloseBar = (barstate.isconfirmed and not na(time_close) and currentMinute < forceCloseTotal and currentCloseMinute >= forceCloseTotal)
// ============================================================================
// SECTION 15: REQUEST SYNCHRONIZED VN30 SPOT DATA
// ============================================================================
// All Spot indicators are calculated inside the Spot context.
// Gaps ON prevents silently using a carried-forward Spot value
// on Futures bars without a corresponding Spot update.
[spotClose, spotPastClose, spotFastEMA, spotFastEMAPast, spotSlowEMA, spotATR, spotPreviousHigh, spotPreviousLow] = request.security(referenceSymbol, timeframe.period, [close, close[lagLookback], ta.ema(close, spotFastEMALength), ta.ema(close, spotFastEMALength)[spotSlopeBars], ta.ema(close, spotSlowEMALength), ta.atr(14), ta.highest(high, spotStructureBars)[1], ta.lowest(low, spotStructureBars)[1]], gaps=barmerge.gaps_on, lookahead=barmerge.lookahead_off, ignore_invalid_symbol=true)
bool spotAvailable = (not na(spotClose) and not na(spotFastEMA) and not na(spotSlowEMA) and not na(spotATR))
// ============================================================================
// SECTION 16: FUTURES / SPOT BASIS MODEL
// ============================================================================
float basis = na
if spotAvailable
basis := close - spotClose
float basisMean = ta.sma(basis, basisLookback)
float basisStdev = ta.stdev(basis, basisLookback)
float basisZ = na
if (not na(basis) and not na(basisMean) and not na(basisStdev) and basisStdev >= minimumBasisStdev)
basisZ := (basis - basisMean) / basisStdev
bool basisReady = (spotAvailable and not na(basisZ) and not na(basisMean) and not na(basisStdev))
// ============================================================================
// SECTION 17: VN30 SPOT TREND ENGINE
// ============================================================================
float spotSlope = (spotFastEMA - spotFastEMAPast)
float spotSlopeNormalized = na
if not na(spotATR) and spotATR > 0
spotSlopeNormalized := spotSlope / spotATR
bool spotBullStructure = (spotAvailable and spotClose > spotFastEMA and spotFastEMA > spotSlowEMA)
bool spotBearStructure = (spotAvailable and spotClose < spotFastEMA and spotFastEMA < spotSlowEMA)
bool spotBullSlope = (not na(spotSlopeNormalized) and spotSlopeNormalized >= minimumSpotSlopeATR)
bool spotBearSlope = (not na(spotSlopeNormalized) and spotSlopeNormalized <= -minimumSpotSlopeATR)
bool spotLongBreakOK = (not requireSpotStructureBreak or (not na(spotPreviousHigh) and spotClose > spotPreviousHigh))
bool spotShortBreakOK = (not requireSpotStructureBreak or (not na(spotPreviousLow) and spotClose < spotPreviousLow))
bool spotBullTrend = (spotAvailable and (not useSpotTrendFilter or (spotBullStructure and spotBullSlope)) and spotLongBreakOK)
bool spotBearTrend = (spotAvailable and (not useSpotTrendFilter or (spotBearStructure and spotBearSlope)) and spotShortBreakOK)
// ============================================================================
// SECTION 18: FUTURES RELATIVE PERFORMANCE ENGINE
// ============================================================================
// Positive lag:
// Spot rises more, or falls less, than Futures.
//
// Negative lag:
// Futures rises more, or falls less, than Spot.
float spotMove = (spotClose - spotPastClose)
float futuresMove = (close - close[lagLookback])
float relativeLag = (spotMove - futuresMove)
bool relativeLagReady = not na(relativeLag)
bool longRelativeLagOK = (not useRelativeLagFilter or (relativeLagReady and relativeLag >= minimumLagPoints))
bool shortRelativeLagOK = (not useRelativeLagFilter or (relativeLagReady and relativeLag <= -minimumLagPoints))
// ============================================================================
// SECTION 19: FUTURES PRICE / CANDLE CONFIRMATION
// ============================================================================
float futuresEMA = ta.ema(close, futuresEMALength)
float futuresATR = ta.atr(14)
float candleRange = math.max(high - low, syminfo.mintick)
float candleBody = math.abs(close - open)
float bodyRatio = candleBody / candleRange
bool bullishCandle = (close > open and bodyRatio >= minimumBodyRatio)
bool bearishCandle = (close < open and bodyRatio >= minimumBodyRatio)
bool longFuturesEMAOK = (not requireFuturesEMA or close > futuresEMA)
bool shortFuturesEMAOK = (not requireFuturesEMA or close < futuresEMA)
bool longPreviousBreakOK = (not requirePreviousHighLowBreak or close > high[1])
bool shortPreviousBreakOK = (not requirePreviousHighLowBreak or close < low[1])
bool bullishPriceConfirmation = (bullishCandle and close > close[1] and longFuturesEMAOK and longPreviousBreakOK)
bool bearishPriceConfirmation = (bearishCandle and close < close[1] and shortFuturesEMAOK and shortPreviousBreakOK)
// ============================================================================
// SECTION 20: DAILY COUNTERS / TRADE APPROVAL
// ============================================================================
var int tradesToday = 0
var float dayStartNetProfit = na
var int closedTradesSeen = 0
var int lastExitBar = na
var int lastEntrySignalBar = na
var int longExtremeCount = 0
var int shortExtremeCount = 0
var int longConfirmationCount = 0
var int shortConfirmationCount = 0
var int rejectedSpotCount = 0
var int rejectedRiskCount = 0
var int rejectedControlCount = 0
var int longEntryCount = 0
var int shortEntryCount = 0
if newTradingDay
tradesToday := 0
dayStartNetProfit := strategy.netprofit
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 == "Both" or tradeDirection == "Long")
bool allowShort = (tradeDirection == "Both" or tradeDirection == "Short")
bool cooldownOK = (na(lastExitBar) or bar_index - lastExitBar > cooldownBars)
bool tradeLimitOK = (tradesToday < maximumTradesPerDay)
float realizedToday = (strategy.netprofit - nz(dayStartNetProfit, strategy.netprofit))
bool dailyLossOK = (not useDailyLossGuard or realizedToday > -maximumDailyLossVND)
bool oneOrderPerBar = (na(lastEntrySignalBar) or bar_index != lastEntrySignalBar)
bool commonEntryOK = (flat and basisReady and entrySession and beforeForceClose and tradeLimitOK and cooldownOK and dailyLossOK and oneOrderPerBar and barstate.isconfirmed)
// ============================================================================
// SECTION 21: EXTREME BASIS SETUP STATE
// ============================================================================
var bool longSetupArmed = false
var bool shortSetupArmed = false
var int longSetupBar = na
var int shortSetupBar = na
var float longExtremeZ = na
var float shortExtremeZ = na
var float longSetupLow = na
var float shortSetupHigh = na
bool longExtremeEvent = ta.crossunder(basisZ, -entryZScore)
bool shortExtremeEvent = ta.crossover(basisZ, entryZScore)
bool longArmEvent = false
bool shortArmEvent = false
// ============================================================================
// SECTION 22: RESET / INVALIDATE PENDING SETUPS
// ============================================================================
if (newTradingDay or (resetSetupAtAfternoon and afternoonBegins))
longSetupArmed := false
shortSetupArmed := false
longSetupBar := na
shortSetupBar := na
longExtremeZ := na
shortExtremeZ := na
longSetupLow := na
shortSetupHigh := na
if barstate.isconfirmed
if longSetupArmed
bool longExpired = (bar_index - longSetupBar > maximumSetupBars)
bool longTrendLost = (not spotBullTrend or not spotAvailable)
bool longBasisNormalized = (not na(basisZ) and basisZ > -minimumRemainingZ)
bool longNewPriceExtreme = (invalidateOnNewPriceExtreme and low < longSetupLow - syminfo.mintick)
if (longExpired or longTrendLost or longBasisNormalized or longNewPriceExtreme)
longSetupArmed := false
if shortSetupArmed
bool shortExpired = (bar_index - shortSetupBar > maximumSetupBars)
bool shortTrendLost = (not spotBearTrend or not spotAvailable)
bool shortBasisNormalized = (not na(basisZ) and basisZ < minimumRemainingZ)
bool shortNewPriceExtreme = (invalidateOnNewPriceExtreme and high > shortSetupHigh + syminfo.mintick)
if (shortExpired or shortTrendLost or shortBasisNormalized or shortNewPriceExtreme)
shortSetupArmed := false
// ============================================================================
// SECTION 23: UPDATE BASIS EXTREME / PRICE EXTREME
// ============================================================================
if barstate.isconfirmed
if longSetupArmed
longExtremeZ := math.min(longExtremeZ, basisZ)
longSetupLow := math.min(longSetupLow, low)
if shortSetupArmed
shortExtremeZ := math.max(shortExtremeZ, basisZ)
shortSetupHigh := math.max(shortSetupHigh, high)
// ============================================================================
// SECTION 24: BASIS RECOVERY CONFIRMATION
// ============================================================================
bool longSetupAlive = (longSetupArmed and not na(longSetupBar) and bar_index > longSetupBar and bar_index - longSetupBar <= maximumSetupBars)
bool shortSetupAlive = (shortSetupArmed and not na(shortSetupBar) and bar_index > shortSetupBar and bar_index - shortSetupBar <= maximumSetupBars)
bool longBasisRecovering = (basisReady and not na(longExtremeZ) and basisZ >= longExtremeZ + minimumZRecovery and basisZ > basisZ[1] and basisZ <= -minimumRemainingZ)
bool shortBasisRecovering = (basisReady and not na(shortExtremeZ) and basisZ <= shortExtremeZ - minimumZRecovery and basisZ < basisZ[1] and basisZ >= minimumRemainingZ)
bool rawLongSignal = (barstate.isconfirmed and longSetupAlive and longBasisRecovering and bullishPriceConfirmation)
bool rawShortSignal = (barstate.isconfirmed and shortSetupAlive and shortBasisRecovering and bearishPriceConfirmation)
if rawLongSignal
longConfirmationCount += 1
if rawShortSignal
shortConfirmationCount += 1
// ============================================================================
// SECTION 25: STRUCTURAL STOP / REWARD MODEL
// ============================================================================
float longStopCandidate = (not na(longSetupLow) ? math.round_to_mintick(longSetupLow - nz(futuresATR, 0) * stopBufferATR) : na)
float shortStopCandidate = (not na(shortSetupHigh) ? math.round_to_mintick(shortSetupHigh + nz(futuresATR, 0) * stopBufferATR) : na)
float longRiskPoints = (close - longStopCandidate)
float shortRiskPoints = (shortStopCandidate - close)
bool longRiskOK = (not na(longRiskPoints) and longRiskPoints >= minimumStopPoints and longRiskPoints <= maximumStopPoints and longRiskPoints * takeProfitR >= minimumGrossTarget)
bool shortRiskOK = (not na(shortRiskPoints) and shortRiskPoints >= minimumStopPoints and shortRiskPoints <= maximumStopPoints and shortRiskPoints * takeProfitR >= minimumGrossTarget)
float longTargetCandidate = math.round_to_mintick(close + longRiskPoints * takeProfitR)
float shortTargetCandidate = math.round_to_mintick(close - shortRiskPoints * takeProfitR)
// ============================================================================
// SECTION 26: FINAL ENTRY FILTER
// ============================================================================
bool finalLongSignal = (rawLongSignal and allowLong and spotBullTrend and longRiskOK and commonEntryOK)
bool finalShortSignal = (rawShortSignal and allowShort and spotBearTrend and shortRiskOK and commonEntryOK and not finalLongSignal)
if rawLongSignal or rawShortSignal
if ((rawLongSignal and not spotBullTrend) or (rawShortSignal and not spotBearTrend))
rejectedSpotCount += 1
else if ((rawLongSignal and not longRiskOK) or (rawShortSignal and not shortRiskOK))
rejectedRiskCount += 1
else if not finalLongSignal and not finalShortSignal
rejectedControlCount += 1
// ============================================================================
// SECTION 27: ENTRY / ACTIVE POSITION STATE
// ============================================================================
var float activeEntryPrice = na
var float activeStop = na
var float activeTarget = na
var float originalFillRisk = na
var int activeEntryBar = na
var bool breakEvenActive = false
// ============================================================================
// SECTION 28: LONG ENTRY
// ============================================================================
if finalLongSignal
activeStop := longStopCandidate
activeTarget := longTargetCandidate
originalFillRisk := na
activeEntryPrice := na
activeEntryBar := na
breakEvenActive := false
strategy.entry("CNPS58-L", strategy.long, comment="BASIS DISCOUNT RECOVERY", alert_message="🟢 VÀO VỊ THẾ LONG (CNPS58)\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\n🛑 Cắt lỗ (SL): " + str.tostring(activeStop, format.mintick) + "\n🎯 Chốt lời (TP): " + str.tostring(activeTarget, format.mintick))
strategy.exit("CNPS58-L-X", from_entry="CNPS58-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 lời: " + str.tostring(activeTarget, format.mintick), alert_loss="🛑 CẮT LỖ LONG (SL HIT)\nGiá cắt lỗ: " + str.tostring(activeStop, format.mintick))
lastEntrySignalBar := bar_index
tradesToday += 1
longEntryCount += 1
longSetupArmed := false
shortSetupArmed := false
// ============================================================================
// SECTION 29: SHORT ENTRY
// ============================================================================
else if finalShortSignal
activeStop := shortStopCandidate
activeTarget := shortTargetCandidate
originalFillRisk := na
activeEntryPrice := na
activeEntryBar := na
breakEvenActive := false
strategy.entry("CNPS58-S", strategy.short, comment="BASIS PREMIUM RECOVERY", alert_message="🔴 VÀO VỊ THẾ SHORT (CNPS58)\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\n🛑 Cắt lỗ (SL): " + str.tostring(activeStop, format.mintick) + "\n🎯 Chốt lời (TP): " + str.tostring(activeTarget, format.mintick))
strategy.exit("CNPS58-S-X", from_entry="CNPS58-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 lời: " + str.tostring(activeTarget, format.mintick), alert_loss="🛑 CẮT LỖ SHORT (SL HIT)\nGiá cắt lỗ: " + str.tostring(activeStop, format.mintick))
lastEntrySignalBar := bar_index
tradesToday += 1
shortEntryCount += 1
longSetupArmed := false
shortSetupArmed := false
// ============================================================================
// SECTION 30: ARM NEW CONTRADICTION SETUPS
// ============================================================================
// Extreme crossing must occur while the Spot trend and relative lag
// support the contradiction. Entries are evaluated on later bars.
if (flat and not finalLongSignal and not finalShortSignal and not longSetupArmed and not shortSetupArmed and basisReady and entrySession and beforeForceClose and barstate.isconfirmed)
if (longExtremeEvent and spotBullTrend and longRelativeLagOK)
longSetupArmed := true
longSetupBar := bar_index
longExtremeZ := basisZ
longSetupLow := low
shortSetupArmed := false
longExtremeCount += 1
longArmEvent := true
else if (shortExtremeEvent and spotBearTrend and shortRelativeLagOK)
shortSetupArmed := true
shortSetupBar := bar_index
shortExtremeZ := basisZ
shortSetupHigh := high
longSetupArmed := false
shortExtremeCount += 1
shortArmEvent := true
// ============================================================================
// SECTION 31: INITIALIZE ACTUAL FILLED POSITION
// ============================================================================
if (strategy.position_size != 0 and strategy.opentrades > 0 and barstate.isconfirmed)
int actualEntryBar = (strategy.opentrades.entry_bar_index(0))
float actualFillPrice = (strategy.position_avg_price)
if (na(activeEntryBar) or actualEntryBar != activeEntryBar)
activeEntryBar := actualEntryBar
activeEntryPrice := actualFillPrice
originalFillRisk := (inLong ? actualFillPrice - activeStop : activeStop - actualFillPrice)
if (not na(originalFillRisk) and originalFillRisk > syminfo.mintick)
activeTarget := math.round_to_mintick(inLong ? actualFillPrice + originalFillRisk * takeProfitR : actualFillPrice - originalFillRisk * takeProfitR)
// ============================================================================
// SECTION 32: PROTECTIVE STOP / TAKE PROFIT
// ============================================================================
bool positionOpen = strategy.position_size != 0
bool validActiveRisk = (positionOpen and not na(originalFillRisk) and originalFillRisk > syminfo.mintick and not na(activeEntryPrice) and not na(activeStop) and not na(activeTarget) and (inLong ? activeTarget > activeEntryPrice : activeTarget < activeEntryPrice))
if (positionOpen and strategy.opentrades > 0 and barstate.isconfirmed)
if not validActiveRisk
strategy.close(inLong ? "CNPS58-L" : "CNPS58-S", immediately=true, comment="INVALID FILLED RISK", alert_message="⚠️ ĐÓNG VỊ THẾ DO GAP/RỦI RO KHÔNG HỢP LỆ (Invalid Gap)")
else
float currentR = (inLong ? (close - activeEntryPrice) / originalFillRisk : (activeEntryPrice - close) / originalFillRisk)
if (useBreakEven and currentR >= breakEvenAtR)
float breakEvenStop = math.round_to_mintick(inLong ? activeEntryPrice + breakEvenOffset : activeEntryPrice - breakEvenOffset)
activeStop := (inLong ? math.max(activeStop, breakEvenStop) : math.min(activeStop, breakEvenStop))
breakEvenActive := true
if inLong
strategy.exit("CNPS58-L-X", from_entry="CNPS58-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 lời: " + str.tostring(activeTarget, format.mintick), alert_loss=breakEvenActive ? "🛡️ HÒA VỐN LONG (BE HIT)\nGiá hòa vốn: " + str.tostring(activeStop, format.mintick) : "🛑 CẮT LỖ LONG (SL HIT)\nGiá cắt lỗ: " + str.tostring(activeStop, format.mintick))
else if inShort
strategy.exit("CNPS58-S-X", from_entry="CNPS58-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 lời: " + str.tostring(activeTarget, format.mintick), alert_loss=breakEvenActive ? "🛡️ HÒA VỐN SHORT (BE HIT)\nGiá hòa vốn: " + str.tostring(activeStop, format.mintick) : "🛑 CẮT LỖ SHORT (SL HIT)\nGiá cắt lỗ: " + str.tostring(activeStop, format.mintick))
// ============================================================================
// SECTION 33: OPEN TRADE PROFIT IN POINTS
// ============================================================================
float openTradePoints = 0.0
if inLong and not na(activeEntryPrice)
openTradePoints := (close - activeEntryPrice)
if inShort and not na(activeEntryPrice)
openTradePoints := (activeEntryPrice - close)
// ============================================================================
// SECTION 34: STATISTICAL BASIS NORMALIZATION EXIT
// ============================================================================
bool longBasisNormalized = (basisReady and basisZ >= -statisticalExitZ)
bool shortBasisNormalized = (basisReady and basisZ <= statisticalExitZ)
bool profitableEnoughForStatExit = (openTradePoints >= minimumStatExitProfit)
bool longStatisticalExit = (inLong and validActiveRisk and useBasisMeanExit and longBasisNormalized and profitableEnoughForStatExit and barstate.isconfirmed)
bool shortStatisticalExit = (inShort and validActiveRisk and useBasisMeanExit and shortBasisNormalized and profitableEnoughForStatExit and barstate.isconfirmed)
if longStatisticalExit
strategy.close("CNPS58-L", comment="BASIS NORMALIZATION", alert_message="🔄 ĐÓNG VỊ THẾ LONG DO CHUẨN HÓA BASIS (Statistical Exit)")
if shortStatisticalExit
strategy.close("CNPS58-S", comment="BASIS NORMALIZATION", alert_message="🔄 ĐÓNG VỊ THẾ SHORT DO CHUẨN HÓA BASIS (Statistical Exit)")
// ============================================================================
// SECTION 35: OPTIONAL MAXIMUM HOLD EXIT
// ============================================================================
int barsInTrade = 0
if (positionOpen and not na(activeEntryBar))
barsInTrade := (bar_index - activeEntryBar)
bool timeExitCondition = (useTimeExit and positionOpen and barsInTrade >= maximumHoldBars and barstate.isconfirmed)
if timeExitCondition
strategy.close(inLong ? "CNPS58-L" : "CNPS58-S", comment="MAXIMUM HOLD EXIT", alert_message="⏱️ ĐÓNG VỊ THẾ HẾT THỜI GIAN GIỮ LỆNH (Time Exit)")
// ============================================================================
// SECTION 36: FORCE CLOSE BEFORE ATC
// ============================================================================
if (forceCloseBar and strategy.position_size != 0)
strategy.close_all(immediately=true, comment="END CONTINUOUS SESSION", alert_message="⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End)")
// ============================================================================
// SECTION 37: CLEAN UP COMPLETED POSITIONS
// ============================================================================
if (flat and not finalLongSignal and not finalShortSignal)
activeEntryPrice := na
activeStop := na
activeTarget := na
originalFillRisk := na
activeEntryBar := na
breakEvenActive := false
// ============================================================================
// SECTION 38: CHART DISPLAY
// ============================================================================
plot(showFuturesEMA ? futuresEMA : na, title="Futures Confirmation EMA", color=color.orange, linewidth=1)
plot(showActiveSLTP and positionOpen ? activeStop : na, title="Active Structural SL", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showActiveSLTP and positionOpen ? activeTarget : na, title="Active Profit Target", color=color.green, linewidth=2, style=plot.style_linebr)
// ============================================================================
// SECTION 39: SETUP / ENTRY SIGNAL MARKERS
// ============================================================================
plotshape(showSetupSignals and longArmEvent, title="Basis Discount Extreme", text="DZ", style=shape.circle, location=location.belowbar, color=color.new(color.teal, 45), textcolor=color.white, size=size.tiny)
plotshape(showSetupSignals and shortArmEvent, title="Basis Premium Extreme", text="PZ", style=shape.circle, location=location.abovebar, color=color.new(color.red, 45), textcolor=color.white, size=size.tiny)
plotshape(showEntrySignals and finalLongSignal, title="CNPS58 Long Entry", text="LONG", style=shape.triangleup, location=location.belowbar, color=color.teal, textcolor=color.white, size=size.small)
plotshape(showEntrySignals and finalShortSignal, title="CNPS58 Short Entry", text="SHORT", style=shape.triangledown, location=location.abovebar, color=color.red, textcolor=color.white, size=size.small)
// ============================================================================
// SECTION 40: DATA WINDOW VALUES
// ============================================================================
plot(spotClose, title="VN30 Spot Close", display=display.data_window)
plot(basis, title="Futures Minus Spot Basis", display=display.data_window)
plot(basisMean, title="Basis Mean", display=display.data_window)
plot(basisZ, title="Basis Z-Score", display=display.data_window)
plot(relativeLag, title="Futures / Spot Relative Lag", display=display.data_window)
plot(spotSlopeNormalized, title="Spot EMA Slope / ATR", display=display.data_window)
// ============================================================================
// SECTION 41: DIAGNOSTIC TABLE
// ============================================================================
var table diagnostics = table.new(position.top_right, 2, 18, border_width=1)
if barstate.islast
if showDiagnostics
string spotTrendText = "NEUTRAL"
if spotBullTrend
spotTrendText := "BULLISH"
else if spotBearTrend
spotTrendText := "BEARISH"
string setupText = "NONE"
if longSetupArmed
setupText := "LONG ARMED"
else if shortSetupArmed
setupText := "SHORT ARMED"
string positionText = "FLAT"
if inLong
positionText := "LONG"
else if inShort
positionText := "SHORT"
table.cell(diagnostics, 0, 0, "CNPS58 V1")
table.cell(diagnostics, 1, 0, timeframe.period)
table.cell(diagnostics, 0, 1, "Spot Available")
table.cell(diagnostics, 1, 1, spotAvailable ? "YES" : "NO")
table.cell(diagnostics, 0, 2, "VN30 Spot")
table.cell(diagnostics, 1, 2, str.tostring(spotClose, format.mintick))
table.cell(diagnostics, 0, 3, "Futures")
table.cell(diagnostics, 1, 3, str.tostring(close, format.mintick))
table.cell(diagnostics, 0, 4, "Basis")
table.cell(diagnostics, 1, 4, str.tostring(basis, "#.00"))
table.cell(diagnostics, 0, 5, "Basis Z")
table.cell(diagnostics, 1, 5, str.tostring(basisZ, "#.00"))
table.cell(diagnostics, 0, 6, "Relative Lag")
table.cell(diagnostics, 1, 6, str.tostring(relativeLag, "#.00"))
table.cell(diagnostics, 0, 7, "Spot Trend")
table.cell(diagnostics, 1, 7, spotTrendText)
table.cell(diagnostics, 0, 8, "Setup")
table.cell(diagnostics, 1, 8, setupText)
table.cell(diagnostics, 0, 9, "Extreme L / S")
table.cell(diagnostics, 1, 9, str.tostring(longExtremeCount) + " / " + str.tostring(shortExtremeCount))
table.cell(diagnostics, 0, 10, "Confirm L / S")
table.cell(diagnostics, 1, 10, str.tostring(longConfirmationCount) + " / " + str.tostring(shortConfirmationCount))
table.cell(diagnostics, 0, 11, "Reject Spot")
table.cell(diagnostics, 1, 11, str.tostring(rejectedSpotCount))
table.cell(diagnostics, 0, 12, "Reject Risk")
table.cell(diagnostics, 1, 12, str.tostring(rejectedRiskCount))
table.cell(diagnostics, 0, 13, "Reject Control")
table.cell(diagnostics, 1, 13, str.tostring(rejectedControlCount))
table.cell(diagnostics, 0, 14, "Entries L / S")
table.cell(diagnostics, 1, 14, str.tostring(longEntryCount) + " / " + str.tostring(shortEntryCount))
table.cell(diagnostics, 0, 15, "Trades Today")
table.cell(diagnostics, 1, 15, str.tostring(tradesToday))
table.cell(diagnostics, 0, 16, "Closed PnL Today")
table.cell(diagnostics, 1, 16, str.tostring(realizedToday, "#.0"))
table.cell(diagnostics, 0, 17, "Position")
table.cell(diagnostics, 1, 17, positionText)
else
table.clear(diagnostics, 0, 0, 1, 17)
// ============================================================================
// CNPS58 V1 - RESEARCH / EXECUTION NOTES
// ============================================================================
//
// 1. Strategy logic is independently designed for VN30F1M.
// 2. VN30 Spot is requested without lookahead.
// 3. Spot values are not forward-filled across missing source bars.
// 4. Basis uses contemporaneous Spot and Futures prices.
// 5. Signals require confirmed Futures candles.
// 6. No future pivots or future-session data are used.
// 7. Setups are armed at extreme Basis Z and traded after recovery.
// 8. Structural Stop uses price extremes observed since setup arming.
// 9. Market orders normally fill after the signal close.
// 10. Initial protective brackets are submitted with entry orders.
// 11. Target is adjusted to actual entry risk on a subsequent calculation.
// 12. Statistical exit requires a minimum gross open profit.
// 13. Daily realized loss filter blocks new orders only.
// 14. Zero margin is a backtest setting, not actual futures margin.
// 15. Profitability has not been established by a TradingView backtest.
// ============================================================================
2. Những khái niệm kỹ thuật cốt lõi trong CNPS58
2.1. Đồng bộ VN30 Spot và Mô hình Basis Z-Score
Chiến lược lấy dữ liệu từ HOSE:VN30 ở cùng khung thời gian hiện tại thông qua request.security(..., gaps=barmerge.gaps_on, lookahead=barmerge.lookahead_off). Cờ gaps_on đảm bảo nếu một thanh nến Futures không có dữ liệu Spot tương ứng thì spotClose sẽ mang giá trị na thay vì tự động sao chép giá cũ.
Khi spotAvailable hợp lệ, bot tính:
basis = close - spotClosebasisMean = ta.sma(basis, 55)vàbasisStdev = ta.stdev(basis, 55)basisZ = (basis - basisMean) / basisStdev(chỉ tính khibasisStdev >= 0.30để tránh chia cho phương sai quá nhỏ).
2.2. Động cơ xu hướng VN30 Spot (Spot Trend Engine)
Toàn bộ chỉ báo xu hướng cơ sở được tính bên trong ngữ cảnh HOSE:VN30:
- Cấu trúc EMA: Tăng giá khi
spotClose > spotFastEMA (21) > spotSlowEMA (55)(spotBullStructure), giảm giá khispotClose < spotFastEMA < spotSlowEMA(spotBearStructure). - Độ dốc chuẩn hóa:
spotSlopeNormalized = (spotFastEMA - spotFastEMA[5]) / spotATR(14). Xu hướng tăng yêu cầuspotSlopeNormalized >= 0.08, xu hướng giảm yêu cầu<= -0.08. - Phá vỡ cấu trúc (tùy chọn): Nếu bật
requireSpotStructureBreak, giá Spot phải đóng cửa vượt đỉnh/đáy15nến trước đó.
2.3. Độ trễ tương đối (Relative Lag) và Xác nhận giá Futures
- Relative Lag (
relativeLag): Đo mức lệch biến động tronglagLookback = 5nến:relativeLag = (spotClose - spotClose[5]) - (close - close[5])- Giá trị dương (
>= 1.20điểm): Spot tăng mạnh hơn hoặc giảm ít hơn Futures (Futures bị tụt lại -> điều kiện Long). - Giá trị âm (
<= -1.20điểm): Futures tăng mạnh hơn hoặc giảm ít hơn Spot (Futures bị kéo thặng dư quá mức -> điều kiện Short).
- Giá trị dương (
- Xác nhận nến Futures: Yêu cầu nến đóng cửa có thân nến
bodyRatio >= 0.25, đóng cửa tăng/giảm so vớiclose[1]và nằm trên/dướiEMA 9của VN30F1M (requireFuturesEMA = true).
3. Nguyên lý hoạt động của CNPS58
Hệ thống vận hành theo chu trình 5 bước tuần tự trên mỗi nến đã đóng (barstate.isconfirmed):
- Khởi tạo phiên & Dọn dẹp: Khi sang ngày mới (
newTradingDay), resettradesToday = 0và ghi nhậndayStartNetProfit. Khi sang phiên chiều (afternoonBegins), nếu bậtresetSetupAtAfternoon, bot hủy mọi Setup đang chờ từ phiên sáng. - Nạp Setup cực trị Basis (Arming): Khi chưa có vị thế (
flat) và chưa có Setup nào đang chờ, nếubasisZcắt xuống dưới-1.25(hoặc cắt lên trên+1.25) đồng thời thỏa mãn xu hướng Spot vàrelativeLag, bot kích hoạtlongSetupArmed(hoặcshortSetupArmed), lưu lạilongSetupBar,longExtremeZvàlongSetupLow(hoặcshortSetupHigh). - Theo dõi & Cập nhật Setup: Trong tối đa
12nến (maximumSetupBars), bot liên tục cập nhật cực trị mới củabasisZvà giá (longSetupLow/shortSetupHigh). Setup sẽ bị hủy nếu quá hạn 12 nến, Spot mất xu hướng, hoặc Basis đã tự chuẩn hóa vượt ngưỡngminimumRemainingZ(0.15). - Xác nhận hồi phục & Kiểm tra rủi ro: Khi
basisZhồi phục từ cực trị tối thiểu0.25(minimumZRecovery), đang quay đầu (basisZ > basisZ[1]với Long) và nến Futures xác nhận tăng/giảm, bot tínhactiveStopvàactiveTarget. Nếu rủi ro nằm trong[2.0, 12.0]điểm và mục tiêu thô>= 3.50điểm, lệnh được gửi đi. - Quản trị vị thế & Thoát lệnh: Sau khi khớp lệnh (
strategy.opentrades > 0), bot cập nhật lạioriginalFillRiskvàactiveTargettheo giá khớp thực tế (strategy.position_avg_price), đồng thời giám sát song song SL/TP, thoát lệnh thống kê Basis, giới hạn thời gian giữ lệnh và đóng cưỡng bức lúc14:25.
4. Điều kiện vào lệnh Long và Short của CNPS58
4.1. Điều kiện vào lệnh Long
- Nạp Setup (
longArmEvent):- Đang
flat, trong phiên vào lệnh và trước14:25. basisZcắt xuống dưới-1.25(ta.crossunder(basisZ, -entryZScore)).spotBullTrendđúng (spotClose > EMA21 > EMA55vàspotSlopeNormalized >= 0.08).longRelativeLagOKđúng (relativeLag >= 1.20điểm).
- Đang
- Kích hoạt lệnh (
finalLongSignal):- Setup còn hiệu lực trong
1..12nến kể từ lúc nạp (longSetupAlive). basisZ >= longExtremeZ + 0.25,basisZ > basisZ[1]vàbasisZ <= -0.15(longBasisRecovering).- Nến Futures tăng (
close > open),bodyRatio >= 0.25,close > close[1]vàclose > futuresEMA (9)(bullishPriceConfirmation). spotBullTrendvẫn duy trì và rủi ro hợp lệ (2.0 <= longRiskPoints <= 12.0,longRiskPoints * 1.60 >= 3.50).tradeDirectioncho phép Long ("Both"hoặc"Long") và thỏa mãncommonEntryOK.
- Setup còn hiệu lực trong
4.2. Điều kiện vào lệnh Short
- Nạp Setup (
shortArmEvent):- Đang
flat, trong phiên vào lệnh và trước14:25. basisZcắt lên trên+1.25(ta.crossover(basisZ, entryZScore)).spotBearTrendđúng (spotClose < EMA21 < EMA55vàspotSlopeNormalized <= -0.08).shortRelativeLagOKđúng (relativeLag <= -1.20điểm).
- Đang
- Kích hoạt lệnh (
finalShortSignal):- Setup còn hiệu lực trong
1..12nến kể từ lúc nạp (shortSetupAlive). basisZ <= shortExtremeZ - 0.25,basisZ < basisZ[1]vàbasisZ >= 0.15(shortBasisRecovering).- Nến Futures giảm (
close < open),bodyRatio >= 0.25,close < close[1]vàclose < futuresEMA (9)(bearishPriceConfirmation). spotBearTrendvẫn duy trì và rủi ro hợp lệ (2.0 <= shortRiskPoints <= 12.0,shortRiskPoints * 1.60 >= 3.50).tradeDirectioncho phép Short ("Both"hoặc"Short") và thỏa mãncommonEntryOK(và không trùng tín hiệu Long).
- Setup còn hiệu lực trong
4.3. Điều kiện kiểm soát giao dịch chung
Tất cả lệnh vào mới đều phải vượt qua commonEntryOK:
- Trạng thái tài khoản: Đang không có vị thế (
strategy.position_size == 0) và chỉ gửi tối đa 1 lệnh mỗi nến (oneOrderPerBar) khi nến đã đóng (barstate.isconfirmed). - Khung giờ giao dịch: Thuộc phiên sáng
09:10–11:20hoặc phiên chiều13:10–14:10(múi giờAsia/Ho_Chi_Minh) và thời điểm đóng nến phải trước14:25(beforeForceClose). - Giới hạn tần suất:
tradesToday < 3và khoảng cách từ nến thoát lệnh gần nhất lớn hơn5nến (bar_index - lastExitBar > 5). - Giới hạn lỗ ngày: Khi
useDailyLossGuard = true, lợi nhuận đã chốt trong ngàyrealizedTodayphải lớn hơn-2,400,000 VND.
5. Quản trị Stop Loss, Take Profit và Thoát lệnh
5.1. Cơ chế Stop Loss và bộ lọc Risk
- Công thức Stop Loss cấu trúc:
- Long:
longStopCandidate = math.round_to_mintick(longSetupLow - futuresATR * 0.15) - Short:
shortStopCandidate = math.round_to_mintick(shortSetupHigh + futuresATR * 0.15)Trong đólongSetupLow/shortSetupHighlà cực trị giá thấp nhất/cao nhất ghi nhận từ lúc nạp Setup đến trước khi khớp lệnh.
- Long:
- Bộ lọc Risk: Khoảng cách rủi ro (
longRiskPointshoặcshortRiskPoints) phải nằm trong khoảng2.0đến12.0điểm vàriskPoints * 1.60 >= 3.50điểm. - Bảo vệ rủi ro khi khớp lệnh bị Gap: Nếu sau khi khớp lệnh thực tế,
originalFillRisk <= syminfo.mintickhoặc mục tiêu không hợp lệ (not validActiveRisk), bot lập tức đóng vị thế bằngstrategy.close(..., immediately=true)với ghi chúINVALID FILLED RISK.
5.2. Cơ chế Take Profit, Break Even và Thoát lệnh
- Take Profit cố định: Tính theo tỷ lệ
1.60R(takeProfitR = 1.60). Khi lệnh khớp ở nến kế tiếp, bot tự động điều chỉnh lạiactiveTargettheoactualFillPrice(giá khớp thực tế) vàoriginalFillRisk. - Break Even (tùy chọn, tắt mặc định): Nếu bật
useBreakEven = truevàcurrentR >= 1.00, SL được dời vềactiveEntryPrice ± 0.20điểm. - Thoát lệnh thống kê Basis (Statistical Exit): Bật mặc định (
useBasisMeanExit = true). Khi vị thế đang có lãi mở>= 2.50điểm vàbasisZđã hồi về vùng cân bằng (basisZ >= -0.20với Long,basisZ <= 0.20với Short), bot chủ động chốt lời sớm. - Thoát lệnh theo thời gian & Hết phiên: Đóng lệnh nếu giữ từ
45nến trở lên (useTimeExit = true) hoặc đóng toàn bộ vị thế bằngstrategy.close_alltại nến chạm14:25trước giờ ATC.
5.3. Bảng tổng hợp cơ chế bảo vệ vị thế
| Cơ chế thoát lệnh | Điều kiện kích hoạt mặc định | Hành động của Bot |
|---|---|---|
| Stop Loss cấu trúc | Giá chạm Setup Extreme ± 0.15 * ATR(14) | Thoát lệnh qua strategy.exit (SL Long / SL Short) |
| Take Profit (1.6R) | Giá chạm Entry ± 1.60 * originalFillRisk | Chốt lời qua strategy.exit (TP Long / TP Short) |
| Invalid Filled Risk | Giá khớp thực tế tạo rủi ro <= mintick hoặc TP ngược chiều | Đóng khẩn cấp immediately=true (INVALID FILLED RISK) |
| Break Even (Tắt mặc định) | useBreakEven = true và lợi nhuận đạt >= 1.00R | Dời SL về giá vốn ± 0.20 điểm (BE Long / BE Short) |
| Statistical Basis Exit | Lãi mở >= 2.50 điểm và ` | basisZ |
| Maximum Hold Exit | Số nến nắm giữ barsInTrade >= 45 | Đóng vị thế qua strategy.close (MAXIMUM HOLD EXIT) |
| Force Close trước ATC | Nến đóng cửa vượt mốc 14:25 (forceCloseBar) | Đóng toàn bộ vị thế immediately=true (END CONTINUOUS SESSION) |
6. Hướng dẫn cài đặt và đọc bảng Diagnostics trên TradingView
Các bước cài đặt
- Mở biểu đồ hợp đồng tương lai VN30F1M trên TradingView ở khung thời gian giao dịch mong muốn (ví dụ
1m,3mhoặc5m). - Nhấn vào tab Pine Editor ở thanh công cụ phía dưới màn hình.
- Xóa toàn bộ mã mẫu hiện có, sao chép nguyên văn đoạn mã Pine Script v6 ở Mục 1 và dán vào Pine Editor.
- Nhấn Save để lưu script với tên
CNPS58 BASIS TREND CONTRADICTION V1 - VN30F1M, sau đó nhấn Add to chart để hiển thị chiến lược và bảng chẩn đoán lên biểu đồ.
Cách đọc bảng chẩn đoán (Diagnostics Table)
Khi bật Show Diagnostics? (showDiagnostics = true), bot hiển thị bảng trạng thái thời gian thực ở góc trên bên phải biểu đồ gồm 18 dòng thông số:
| Dòng hiển thị | Ý nghĩa thực tế |
|---|---|
| CNPS58 V1 | Tên bot và khung thời gian biểu đồ hiện tại (timeframe.period) |
| Spot Available | Trạng thái dữ liệu HOSE:VN30 (YES hoặc NO) |
| VN30 Spot / Futures | Giá đóng cửa hiện tại của chỉ số VN30 Spot và VN30F1M |
| Basis / Basis Z | Giá trị chênh lệch Futures - Spot và điểm chuẩn hóa Basis Z-Score |
| Relative Lag | Độ trễ tương đối trong 5 nến giữa Spot và Futures |
| Spot Trend | Trạng thái xu hướng Spot (BULLISH, BEARISH, NEUTRAL) |
| Setup | Trạng thái nạp Setup hiện tại (LONG ARMED, SHORT ARMED, NONE) |
| Extreme L / S | Tổng số lần chạm cực trị Basis Z để nạp Setup Long / Short |
| Confirm L / S | Tổng số lần nến Futures xác nhận hồi phục sau Setup (rawLongSignal / rawShortSignal) |
| Reject Spot / Risk / Control | Số tín hiệu bị từ chối do mất xu hướng Spot, lỗi Risk (SL/TP) hoặc bộ lọc kiểm soát chung |
| Entries L / S | Tổng số lệnh Long / Short thực tế đã vào |
| Trades Today / Closed PnL Today | Số lệnh đã mở trong ngày và lãi/lỗ đã chốt trong ngày (VND) |
| Position | Vị thế hiện tại của bot (LONG, SHORT hoặc FLAT) |
7. Cách thiết lập cảnh báo tín hiệu giao dịch (Alert)
Để nhận thông báo tự động qua ứng dụng TradingView hoặc Webhook khi Bot CNPS58 phát sinh lệnh, bạn thực hiện như sau:
- Nhấn vào biểu tượng Alert (hình đồng hồ báo thức) trên thanh công cụ TradingView.
- Tại mục Condition, chọn chiến lược CNPS58 BASIS TREND CONTRADICTION V1 - VN30F1M.
- Tại ô Message, xóa nội dung mặc định và nhập chính xác biến:
{{strategy.order.alert_message}}. - Chọn kênh nhận thông báo (Notify on app, Show pop-up hoặc Webhook URL) và nhấn Create.
Bảng thông điệp Alert của CNPS58
| Sự kiện | Nội dung alert_message / alert_profit / alert_loss trong code |
|---|---|
| Vào lệnh Long | 🟢 VÀO VỊ THẾ LONG (CNPS58) kèm Giá vào, Cắt lỗ (SL), Chốt lời (TP) |
| Vào lệnh Short | 🔴 VÀO VỊ THẾ SHORT (CNPS58) kèm Giá vào, Cắt lỗ (SL), Chốt lời (TP) |
| Chốt lời (TP) | 💰 CHỐT LỜI LONG (TP HIT) hoặc 💰 CHỐT LỜI SHORT (TP HIT) kèm Giá chốt lời |
| Cắt lỗ (SL) | 🛑 CẮT LỖ LONG (SL HIT) hoặc 🛑 CẮT LỖ SHORT (SL HIT) kèm Giá cắt lỗ |
| Hòa vốn (BE) | 🛡️ HÒA VỐN LONG (BE HIT) hoặc 🛡️ HÒA VỐN SHORT (BE HIT) kèm Giá hòa vốn |
| Đóng do lỗi Gap/Risk | ⚠️ ĐÓNG VỊ THẾ DO GAP/RỦI RO KHÔNG HỢP LỆ (Invalid Gap) |
| Thoát thống kê Basis | 🔄 ĐÓNG VỊ THẾ LONG/SHORT DO CHUẨN HÓA BASIS (Statistical Exit) |
| Hết thời gian giữ lệnh | ⏱️ ĐÓNG VỊ THẾ HẾT THỜI GIAN GIỮ LỆNH (Time Exit) |
| Đóng hết phiên (14:25) | ⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End) |
Kết luận
CNPS58 Basis Trend Contradiction V1 là một hệ thống giao dịch định lượng bài bản dành cho VN30F1M, kết hợp chặt chẽ giữa cấu trúc xu hướng của chỉ số cơ sở VN30 Spot và sự lệch pha ngắn hạn của hợp đồng tương lai thông qua Basis Z-Score. Chiến lược phát huy hiệu quả tốt nhất trong những phiên thị trường cơ sở có xu hướng rõ ràng nhưng VN30F1M xuất hiện các nhịp rung lắc, ép Basis chiết khấu hoặc kéo Basis thặng dư quá mức rồi nhanh chóng hội tụ trở lại.
Bạn có thể tham khảo thêm các hệ thống giao dịch phái sinh khác như Bot CNPS50 - Trend Analysis V2 và Bot CNPS49 - Daily Open để đa dạng hóa góc nhìn chiến lược.
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.





