Hướng Dẫn Sử Dụng Bot CNPS56 - Liquidity Sweep V4 Active Balanced cho VN30F1M
TradingviewBot CNPS56 Liquidity Sweep V4 Active Balanced giao dịch đảo chiều khi giá quét thanh khoản thất bại tại các mốc PDH/PDL, Opening Range và Swing, xác nhận ở nến sau và chốt lời linh hoạt theo Session VWAP hoặc tỷ lệ R cố định.

Mục lục
Khi giao dịch hợp đồng tương lai VN30F1M trong ngày, các vùng giá quan trọng như đỉnh/đáy ngày hôm trước, biên độ mở cửa đầu phiên hay các đỉnh/đáy xoay chiều gần nhất thường xuyên bị thị trường “quét” qua (Liquidity Sweep) để kích hoạt lệnh dừng lỗ của đám đông trước khi đảo chiều quay lại bên trong vùng giá cũ. Nếu vào lệnh ngay trên nến quét thanh khoản, nhà đầu tư dễ gặp rủi ro bị quét tiếp nếu lực phá vỡ thực sự mạnh.
Chiến lược CNPS56 LIQUIDITY SWEEP V4 ACTIVE BALANCED - VN30F1M (tên ngắn: CNPS56 SWEEP V4) được viết bằng Pine Script v6 trên nền tảng TradingView nhằm giải quyết bài toán này thông qua quy trình giao dịch kỷ luật, tách biệt rõ pha quét thanh khoản thất bại và pha xác nhận động lượng ở nến kế tiếp. Đây là phiên bản nghiên cứu V4 hướng đến sự cân bằng tần suất tín hiệu cho khung M1/M5 trên VN30F1M nhưng vẫn giữ nguyên kỷ luật dừng lỗ theo cấu trúc.
Những điểm nổi bật cốt lõi của Bot CNPS56:
- Theo dõi đa nguồn thanh khoản: Tự động giám sát đồng thời 3 nhóm mốc giá gồm Đỉnh/Đáy phiên trước (Previous Day), Biên độ mở cửa (Opening Range) và Đỉnh/Đáy xoay chiều đã xác nhận (Confirmed Swing) với thứ tự ưu tiên rõ ràng.
- Xác nhận ở nến sau (Later-Bar Confirmation): Không vào lệnh ngay tại nến quét thanh khoản; hệ thống chỉ kích hoạt trạng thái chờ (
Pending) và yêu cầu một nến xác nhận tăng/giảm rõ ràng trong cửa sổ tối đa 5 nến sau đó. - Mục tiêu chốt lời thích ứng (Adaptive Target): Ưu tiên chốt lời tại đường Session VWAP được đóng băng tại thời điểm nến tín hiệu đóng cửa nếu đạt tỷ lệ R:R tối thiểu, hoặc tự động chuyển sang mục tiêu Fixed R (mặc định
1.50R). - Bộ lọc bảo vệ toàn diện: Tích hợp bộ lọc ngược xu hướng mạnh (
EMA 55+ADX 14), giới hạn khoảng cách SL hợp lý (1.5 – 10.0điểm), giới hạn lỗ tối đa trong ngày và tự động đóng toàn bộ vị thế trước phiên ATC (14:25).
1. CNPS56 Liquidity Sweep V4 Active Balanced là gì?
CNPS56 Liquidity Sweep V4 Active Balanced là hệ thống giao dịch tự động trong ngày (Intraday) chuyên bắt các nhịp quét thanh khoản thất bại (Failed Liquidity Sweep) trên chỉ số phái sinh VN30F1M. Chiến lược được xây dựng dựa trên 4 trụ cột kỹ thuật chính:
- Xác định vùng thanh khoản biết trước (Known Liquidity Levels): Chỉ sử dụng các mốc giá đã hình thành và xác nhận hoàn chỉnh trong quá khứ (không dùng dữ liệu tương lai), bao gồm
previousHigh/previousLow,openingHigh/openingLow(chỉ có hiệu lực sau khi kết thúc cửa sổ Opening Range) vàswingHigh/swingLow(chỉ có hiệu lực sau khi đủswingLengthnến bên phải xác nhận). - Đánh giá chất lượng nến quét thanh khoản (Failed Sweep & Reclaim): Nến quét phải tiếp cận từ bên trong vùng giá (
close[1]nằm trong mốc), xuyên thủng mốc trong biên độ cho phép (0.30đến6.0điểm), rút chân đóng cửa quay lại bên trong mốc ít nhất0.10điểm (reclaimBuffer), đồng thời thỏa mãn tỷ lệ râu nến từ chối, vị trí giá đóng cửa và biên độ nến không quá3.0 x ATR(14). - Xác nhận động lượng ở nến kế tiếp: Sau khi có nến Sweep hợp lệ, setup chuyển sang trạng thái chờ (
longPending/shortPending). Trong vòngconfirmationWindownến tiếp theo (mặc định5nến), nếu xuất hiện nến xác nhận có thân nến đạt tối thiểu20%biên độ nến và thỏa mãn chế độ xác nhận (Level + Progress,Sweep Body BreakhoặcSweep Extreme Break), bot mới phát tín hiệu vào lệnh. - Quản trị rủi ro cấu trúc & Mục tiêu thích ứng: Điểm cắt lỗ (SL) được đặt ngay ngoài cực trị của nến quét cộng thêm
2ticks đệm. Mục tiêu chốt lời (TP) ưu tiên đườngsessionVWAPhiện tại nếu đáp ứng đồng thời lợi nhuận tối thiểu2.5điểm vàR:R >= 1.10; ngược lại sẽ dùng mục tiêu cố định1.50R.
Bảng thông số mặc định
| Nhóm thông số | Tham số trong code | Giá trị mặc định | Ý nghĩa |
|---|---|---|---|
| Trade Control | tradeDirection | "Both" | Chiều giao dịch (Both, Long, Short) |
contracts | 3 | Số lượng hợp đồng mỗi lệnh | |
maximumTradesPerDay | 4 | Số lệnh tối đa trong một ngày | |
cooldownBars | 3 | Số nến nghỉ tối thiểu sau khi đóng lệnh | |
oneTradePerLevel | true | Chỉ giao dịch 1 lần cho mỗi mốc thanh khoản/ngày | |
| Liquidity Levels | levelSource | "All 3" | Nguồn mức thanh khoản (All 3, Previous Day + Swing, Previous Day, Opening Range, Confirmed Swing) |
swingLength | 4 | Số nến trái/phải để xác nhận Pivot Swing | |
maximumSwingAge | 90 | Tuổi tối đa của Swing tính theo số nến | |
openingRangeMinutes | 15 | Độ dài khung mở cửa Opening Range (phút) | |
requireApproachFromInside | true | Yêu cầu giá đóng cửa nến trước (close[1]) nằm bên trong mốc | |
| Sweep Quality | minimumPenetration | 0.30 | Độ xuyên thủng tối thiểu qua mốc (điểm) |
maximumPenetration | 6.0 | Độ xuyên thủng tối đa qua mốc (điểm) | |
reclaimBuffer | 0.10 | Khoảng đệm đóng cửa quay lại bên trong mốc (điểm) | |
minimumRejectionWick | 0.15 | Tỷ lệ râu nến từ chối tối thiểu / biên độ nến | |
minimumCloseLocation | 0.55 | Vị trí đóng cửa tối thiểu hướng về phía từ chối | |
maximumSweepATR | 3.0 | Biên độ nến Sweep tối đa theo bội số ATR(14) | |
| Confirmation | confirmationMode | "Level + Progress" | Chế độ xác nhận (Level + Progress, Sweep Body Break, Sweep Extreme Break) |
confirmationWindow | 5 | Số nến tối đa sau nến Sweep để chờ xác nhận | |
minimumConfirmBody | 0.20 | Tỷ lệ thân nến xác nhận tối thiểu / biên độ nến | |
invalidateOnNewExtreme | true | Hủy setup chờ nếu giá phá cực trị nến Sweep lần nữa | |
| Regime Filter | useTrendGuard | true | Chặn lệnh ngược xu hướng quá mạnh |
emaLength / emaSlopeBars | 55 / 5 | Chu kỳ EMA xu hướng và số nến đo độ dốc | |
strongTrendADX | 35.0 | Ngưỡng ADX(14) xác định xu hướng mạnh | |
minimumAdverseSlopeATR | 0.55 | Ngưỡng độ dốc EMA ngược chiều theo đơn vị ATR | |
useVolumeFilter / minimumVolumeRatio | false / 0.90 | Lọc khối lượng nến Sweep so với SMA 20 | |
| Risk Management | targetMode | "Adaptive VWAP / Fixed R" | Chế độ chốt lời (Adaptive VWAP / Fixed R, Session VWAP Only, Fixed R Only) |
fixedTargetR | 1.50 | Mục tiêu R cố định dự phòng | |
minimumRewardRisk | 1.10 | Tỷ lệ Reward/Risk tối thiểu tại điểm tín hiệu | |
minimumGrossTarget | 2.5 | Khoảng cách TP tối thiểu (điểm) | |
minimumRisk / maximumRisk | 1.5 / 10.0 | Khoảng cách SL cấu trúc cho phép (điểm) | |
stopBufferTicks | 2 | Số tick đệm đặt SL vượt ngoài cực trị nến Sweep | |
vwapTargetBuffer | 0.0 | Khoảng đệm lùi lại trước đường VWAP (điểm) | |
| Exit Management | useReclaimFailureExit / failureCloses | false / 2 | Thoát lệnh nếu tái chiếm thất bại liên tiếp N nến |
useBreakEven / breakEvenAtR / breakEvenOffset | false / 1.0 / 0.2 | Dời SL về hòa vốn khi đạt 1.0R (+0.2 điểm) | |
useTimeExit / maximumHoldBars | false / 45 | Thoát lệnh theo thời gian giữ tối đa (nến) | |
useDailyLossGuard / maximumDailyLossVND | true / 5,000,000 | Dừng mở lệnh mới khi lỗ đã chốt trong ngày vượt ngưỡng | |
| Session | morningEntry / afternoonEntry | "0905-1125" / "1305-1415" | Khung giờ cho phép vào lệnh phiên sáng/chiều |
forceCloseHour / forceCloseMinute | 14 / 25 | Thời điểm đóng toàn bộ vị thế trước ATC (14:25) |
Source Code CNPS56 Liquidity Sweep V4 Active Balanced
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
// CNPS56 - original research strategy for VN30F1M.
// V4 ACTIVE BALANCED: failed liquidity sweep, reclaim, later-bar confirmation.
strategy(title="CNPS56 LIQUIDITY SWEEP V4 ACTIVE BALANCED - VN30F1M", shorttitle="CNPS56 SWEEP V4", 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_bars_back=5000, max_labels_count=300, max_lines_count=300)
// ============================================================================
// CNPS56 V4 - ACTIVE BALANCED
//
// Increase setup opportunities without removing the structural stop:
// 1. Watch Previous Day, Opening Range and confirmed Swing levels.
// 2. Require a failed sweep and a close back through the known level.
// 3. Confirm momentum on a LATER bar, not on the sweep bar.
// 4. Prefer a frozen session VWAP target when reward is sufficient.
// 5. Otherwise use a fixed R target, with the same reward/risk checks.
//
// V4 is a signal-frequency experiment, NOT a proven profitable model.
// Designed for intraday VN30F1M M1/M5 backtesting and controlled comparison.
// ============================================================================
// ============================================================================
// SECTION 1: TRADE CONTROL
// ============================================================================
tradeDirection = input.string("Both", title="Trade Direction", options=["Both", "Long", "Short"], group="Trade Control")
contracts = input.int(3, title="Contracts Per Entry", minval=1, maxval=20, group="Trade Control")
maximumTradesPerDay = input.int(4, title="Maximum Entries Per Day", minval=1, maxval=20, group="Trade Control")
cooldownBars = input.int(3, title="Cooldown Bars After Exit", minval=0, maxval=100, group="Trade Control")
oneTradePerLevel = input.bool(true, title="One Entry Per Level Per Day?", group="Trade Control")
// ============================================================================
// SECTION 2: LIQUIDITY LEVEL SOURCES
// ============================================================================
levelSource = input.string("All 3", title="Liquidity Level Source", options=["All 3", "Previous Day + Swing", "Previous Day", "Opening Range", "Confirmed Swing"], group="Liquidity Levels")
swingLength = input.int(4, title="Pivot Left / Right Bars", minval=2, maxval=20, group="Liquidity Levels")
maximumSwingAge = input.int(90, title="Maximum Confirmed Swing Age (bars)", minval=10, maxval=500, group="Liquidity Levels")
openingRangeMinutes = input.int(15, title="Opening Range Length (minutes)", options=[10, 15, 20, 30], group="Liquidity Levels")
requireApproachFromInside = input.bool(true, title="Require Previous Close Inside Level?", group="Liquidity Levels")
// ============================================================================
// SECTION 3: SWEEP QUALITY - BALANCED FREQUENCY
// ============================================================================
minimumPenetration = input.float(0.30, title="Minimum Sweep Penetration (points)", minval=0.0, step=0.1, group="Sweep Quality")
maximumPenetration = input.float(6.0, title="Maximum Sweep Penetration (points)", minval=0.5, step=0.5, group="Sweep Quality")
reclaimBuffer = input.float(0.10, title="Close Back Inside Level By (points)", minval=0.0, step=0.1, group="Sweep Quality")
minimumRejectionWick = input.float(0.15, title="Minimum Rejection Wick / Candle Range", minval=0.0, maxval=1.0, step=0.05, group="Sweep Quality")
minimumCloseLocation = input.float(0.55, title="Minimum Close Location Toward Rejection", minval=0.5, maxval=0.95, step=0.05, group="Sweep Quality")
maximumSweepATR = input.float(3.0, title="Maximum Sweep Bar Range x ATR14", minval=0.5, maxval=10.0, step=0.25, group="Sweep Quality")
// ============================================================================
// SECTION 4: ENTRY CONFIRMATION
// ============================================================================
confirmationMode = input.string("Level + Progress", title="Confirmation Mode", options=["Level + Progress", "Sweep Body Break", "Sweep Extreme Break"], group="Confirmation")
confirmationWindow = input.int(5, title="Maximum Bars After Sweep", minval=1, maxval=20, group="Confirmation")
minimumConfirmBody = input.float(0.20, title="Minimum Confirmation Body / Range", minval=0.0, maxval=1.0, step=0.05, group="Confirmation")
invalidateOnNewExtreme = input.bool(true, title="Cancel Setup If Sweep Extreme Breaks Again?", group="Confirmation")
// ============================================================================
// SECTION 5: OPTIONAL TREND / VOLUME GUARDS
// ============================================================================
useTrendGuard = input.bool(true, title="Block Very Strong Countertrend Setups?", group="Regime Filter")
emaLength = input.int(55, title="Trend EMA Length", minval=5, maxval=300, group="Regime Filter")
emaSlopeBars = input.int(5, title="EMA Slope Lookback", minval=1, maxval=30, group="Regime Filter")
strongTrendADX = input.float(35.0, title="Strong Trend ADX14 Threshold", minval=10, maxval=60, step=1.0, group="Regime Filter")
minimumAdverseSlopeATR = input.float(0.55, title="Minimum Adverse EMA Slope In ATR Units", minval=0.05, maxval=5.0, step=0.05, group="Regime Filter")
useVolumeFilter = input.bool(false, title="Require Sweep Relative Volume?", group="Regime Filter")
minimumVolumeRatio = input.float(0.90, title="Minimum Sweep Volume / 20-Bar Average", minval=0.1, maxval=5.0, step=0.1, group="Regime Filter")
// ============================================================================
// SECTION 6: ADAPTIVE OBJECTIVE / STRUCTURAL RISK
// ============================================================================
targetMode = input.string("Adaptive VWAP / Fixed R", title="Target Mode", options=["Adaptive VWAP / Fixed R", "Session VWAP Only", "Fixed R Only"], group="Risk Management")
fixedTargetR = input.float(1.50, title="Fallback Fixed Take Profit (R)", minval=0.5, maxval=8.0, step=0.1, group="Risk Management")
minimumRewardRisk = input.float(1.10, title="Minimum Reward / Risk At Signal", minval=0.5, maxval=5.0, step=0.05, group="Risk Management")
minimumGrossTarget = input.float(2.5, title="Minimum Gross Target (points)", minval=0.0, step=0.5, group="Risk Management")
minimumRisk = input.float(1.5, title="Minimum Structural SL Distance (points)", minval=0.1, step=0.5, group="Risk Management")
maximumRisk = input.float(10.0, title="Maximum Structural SL Distance (points)", minval=0.5, step=0.5, group="Risk Management")
stopBufferTicks = input.int(2, title="Stop Beyond Sweep Extreme (ticks)", minval=0, maxval=100, group="Risk Management")
vwapTargetBuffer = input.float(0.0, title="VWAP Target Buffer (points)", minval=0.0, step=0.1, group="Risk Management")
// ============================================================================
// SECTION 7: EXIT CONTROL / DAILY LOSS GUARD
// ============================================================================
useReclaimFailureExit = input.bool(false, title="Exit If Reclaim Fails After Entry?", group="Exit Management")
failureCloses = input.int(2, title="Consecutive Failed Reclaim Closes", minval=1, maxval=5, group="Exit Management")
useBreakEven = input.bool(false, title="Move Stop To Break Even?", group="Exit Management")
breakEvenAtR = input.float(1.0, title="Break Even Trigger (R, close-confirmed)", minval=0.25, maxval=5.0, step=0.25, group="Exit Management")
breakEvenOffset = input.float(0.2, title="Break Even Offset (points)", minval=0.0, step=0.1, group="Exit Management")
useTimeExit = input.bool(false, title="Exit After Maximum Hold Bars?", group="Exit Management")
maximumHoldBars = input.int(45, title="Maximum Hold Bars", minval=1, maxval=500, group="Exit Management")
useDailyLossGuard = input.bool(true, title="Block New Entries After Daily Realized Loss?", group="Exit Management")
maximumDailyLossVND = input.float(5000000, title="Daily Closed Loss Threshold (VND)", minval=100000, step=100000, group="Exit Management")
// ============================================================================
// SECTION 8: VN30F1M SESSION
// ============================================================================
string strategyTimezone = "Asia/Ho_Chi_Minh"
morningEntry = input.session("0905-1125", title="Morning Entry Window", group="Session")
afternoonEntry = input.session("1305-1415", 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 (Before ATC)", minval=0, maxval=59, group="Session")
// ============================================================================
// SECTION 9: DISPLAY / DIAGNOSTICS
// ============================================================================
showLevels = input.bool(true, "Show Known Liquidity Levels?", group="Display")
showVWAP = input.bool(true, "Show Continuous Session VWAP?", group="Display")
showSweeps = input.bool(false, "Show Raw Sweep Markers?", group="Display")
showSignals = input.bool(true, "Show Entry Markers?", group="Display")
showStops = input.bool(true, "Show Active SL / TP?", group="Display")
showDiagnostics = input.bool(true, "Show Signal Funnel Diagnostics?", group="Display")
// ============================================================================
// SECTION 10: HELPER - LEVEL HAS ALREADY BEEN TRADED
// ============================================================================
f_usedLevel(array<float> usedLevels, float candidate) =>
bool used = false
if not na(candidate) and array.size(usedLevels) > 0
for i = 0 to array.size(usedLevels) - 1
if math.abs(array.get(usedLevels, i) - candidate) <= syminfo.mintick
used := true
used
// ============================================================================
// SECTION 11: TIME ENGINE / CLOCK
// ============================================================================
int minuteOfDay = hour(time, strategyTimezone) * 60 + minute(time, strategyTimezone)
int closeMinute = hour(time_close, strategyTimezone) * 60 + minute(time_close, strategyTimezone)
int cutoffMinute = forceCloseHour * 60 + forceCloseMinute
bool inMorning = not na(time(timeframe.period, morningEntry + ":23456", strategyTimezone))
bool inAfternoon = not na(time(timeframe.period, afternoonEntry + ":23456", strategyTimezone))
bool entrySession = inMorning or inAfternoon
bool afternoonBegins = inAfternoon and not inAfternoon[1]
bool marketBar = (minuteOfDay >= 525 and minuteOfDay < 690) or (minuteOfDay >= 780 and minuteOfDay < 885)
bool continuousBar = (minuteOfDay >= 540 and minuteOfDay < 690) or (minuteOfDay >= 780 and minuteOfDay < 870)
int dayKey = year(time, strategyTimezone) * 10000 + month(time, strategyTimezone) * 100 + dayofmonth(time, strategyTimezone)
bool newDay = bar_index == 0 or dayKey != nz(dayKey[1], dayKey)
bool beforeForcedExit = not na(time_close) and closeMinute < cutoffMinute
bool forceCloseBar = barstate.isconfirmed and not na(time_close) and minuteOfDay < cutoffMinute and closeMinute >= cutoffMinute
// ============================================================================
// SECTION 12: PREVIOUS TRADING DAY HIGH / LOW
// ============================================================================
var float todayHigh = na
var float todayLow = na
var float previousHigh = na
var float previousLow = na
if newDay
previousHigh := todayHigh
previousLow := todayLow
todayHigh := marketBar ? high : na
todayLow := marketBar ? low : na
else if marketBar
todayHigh := math.max(nz(todayHigh, high), high)
todayLow := math.min(nz(todayLow, low), low)
// ============================================================================
// SECTION 13: OPENING RANGE (AVAILABLE ONLY AFTER THE WINDOW ENDS)
// ============================================================================
int openingEndMinute = 540 + openingRangeMinutes
bool openingWindow = minuteOfDay >= 540 and minuteOfDay < openingEndMinute
bool openingReady = minuteOfDay >= openingEndMinute
var float openingHigh = na
var float openingLow = na
if newDay
openingHigh := na
openingLow := na
if openingWindow and barstate.isconfirmed
openingHigh := math.max(nz(openingHigh, high), high)
openingLow := math.min(nz(openingLow, low), low)
bool openingRangeAvailable = openingReady and not na(openingHigh) and not na(openingLow)
// ============================================================================
// SECTION 14: CONFIRMED INTRADAY SWING LEVELS
// ============================================================================
float pivotH = ta.pivothigh(high, swingLength, swingLength)
float pivotL = ta.pivotlow(low, swingLength, swingLength)
var float swingHigh = na
var float swingLow = na
var int swingHighBar = na
var int swingLowBar = na
if newDay
swingHigh := na
swingLow := na
swingHighBar := na
swingLowBar := na
bool highSwingFresh = not na(swingHighBar) and bar_index - swingHighBar <= maximumSwingAge
bool lowSwingFresh = not na(swingLowBar) and bar_index - swingLowBar <= maximumSwingAge
// ============================================================================
// SECTION 15: CONTINUOUS SESSION VWAP (NO FUTURE BARS)
// ============================================================================
var float cumulativePV = 0.0
var float cumulativeVolume = 0.0
if newDay
cumulativePV := 0.0
cumulativeVolume := 0.0
if continuousBar and barstate.isconfirmed and not na(volume) and volume > 0
cumulativePV += hlc3 * volume
cumulativeVolume += volume
float sessionVWAP = cumulativeVolume > 0 ? cumulativePV / cumulativeVolume : na
// ============================================================================
// SECTION 16: CANDLE / TREND METRICS
// ============================================================================
float atr = ta.atr(14)
float emaTrend = ta.ema(close, emaLength)
[pDI, mDI, adx] = ta.dmi(14, 14)
float volumeAverage = ta.sma(volume, 20)
float candleRange = math.max(high - low, syminfo.mintick)
float lowerWickRatio = (math.min(open, close) - low) / candleRange
float upperWickRatio = (high - math.max(open, close)) / candleRange
float closeLocation = (close - low) / candleRange
float bodyRatio = math.abs(close - open) / candleRange
float slopeATR = not na(atr) and atr > 0 ? (emaTrend - emaTrend[emaSlopeBars]) / atr : 0.0
bool strongDown = useTrendGuard and not na(adx) and adx >= strongTrendADX and slopeATR < -minimumAdverseSlopeATR and close < emaTrend and mDI > pDI
bool strongUp = useTrendGuard and not na(adx) and adx >= strongTrendADX and slopeATR > minimumAdverseSlopeATR and close > emaTrend and pDI > mDI
bool volumeOK = not useVolumeFilter or (not na(volumeAverage) and volume >= volumeAverage * minimumVolumeRatio)
bool candleSizeOK = not na(atr) and atr > 0 and candleRange <= maximumSweepATR * atr
// ============================================================================
// SECTION 17: DAILY CONTROL / SIGNAL COUNTERS
// ============================================================================
var int tradesToday = 0
var float dayStartNetProfit = na
var int closedTradesSeen = 0
var int lastExitBar = na
var int lastOrderBar = na
var array<float> usedLongLevels = array.new_float()
var array<float> usedShortLevels = array.new_float()
var int rawLongSweeps = 0
var int rawShortSweeps = 0
var int confirmations = 0
var int rejectTrend = 0
var int rejectRisk = 0
var int rejectTarget = 0
var int rejectControls = 0
var int entriesLong = 0
var int entriesShort = 0
var int entriesVWAP = 0
var int entriesFixedR = 0
if newDay
tradesToday := 0
dayStartNetProfit := strategy.netprofit
array.clear(usedLongLevels)
array.clear(usedShortLevels)
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"
bool allowShort = tradeDirection != "Long"
bool dailyLimitOK = tradesToday < maximumTradesPerDay
bool cooldownOK = na(lastExitBar) or bar_index - lastExitBar > cooldownBars
float dailyRealizedPnL = strategy.netprofit - nz(dayStartNetProfit, strategy.netprofit)
bool dailyLossOK = not useDailyLossGuard or dailyRealizedPnL > -maximumDailyLossVND
bool oneOrderPerBar = na(lastOrderBar) or bar_index != lastOrderBar
bool commonEntry = flat and entrySession and beforeForcedExit and dailyLimitOK and cooldownOK and dailyLossOK and oneOrderPerBar and barstate.isconfirmed
// ============================================================================
// SECTION 18: FAILED SWEEP OF A PREVIOUSLY KNOWN LEVEL
// ============================================================================
bool usePrevious = levelSource == "All 3" or levelSource == "Previous Day + Swing" or levelSource == "Previous Day"
bool useOpening = levelSource == "All 3" or levelSource == "Opening Range"
bool useSwing = levelSource == "All 3" or levelSource == "Previous Day + Swing" or levelSource == "Confirmed Swing"
bool prevLowApproach = not requireApproachFromInside or close[1] >= previousLow
bool prevHighApproach = not requireApproachFromInside or close[1] <= previousHigh
bool orLowApproach = not requireApproachFromInside or close[1] >= openingLow
bool orHighApproach = not requireApproachFromInside or close[1] <= openingHigh
bool swingLowApproach = not requireApproachFromInside or close[1] >= swingLow
bool swingHighApproach = not requireApproachFromInside or close[1] <= swingHigh
bool previousLowSweep = usePrevious and not na(previousLow) and prevLowApproach and previousLow - low >= minimumPenetration and previousLow - low <= maximumPenetration and close >= previousLow + reclaimBuffer and (not oneTradePerLevel or not f_usedLevel(usedLongLevels, previousLow))
bool previousHighSweep = usePrevious and not na(previousHigh) and prevHighApproach and high - previousHigh >= minimumPenetration and high - previousHigh <= maximumPenetration and close <= previousHigh - reclaimBuffer and (not oneTradePerLevel or not f_usedLevel(usedShortLevels, previousHigh))
bool openingLowSweep = useOpening and openingRangeAvailable and orLowApproach and openingLow - low >= minimumPenetration and openingLow - low <= maximumPenetration and close >= openingLow + reclaimBuffer and (not oneTradePerLevel or not f_usedLevel(usedLongLevels, openingLow))
bool openingHighSweep = useOpening and openingRangeAvailable and orHighApproach and high - openingHigh >= minimumPenetration and high - openingHigh <= maximumPenetration and close <= openingHigh - reclaimBuffer and (not oneTradePerLevel or not f_usedLevel(usedShortLevels, openingHigh))
bool swingLowSweep = useSwing and lowSwingFresh and not na(swingLow) and swingLowApproach and swingLow - low >= minimumPenetration and swingLow - low <= maximumPenetration and close >= swingLow + reclaimBuffer and (not oneTradePerLevel or not f_usedLevel(usedLongLevels, swingLow))
bool swingHighSweep = useSwing and highSwingFresh and not na(swingHigh) and swingHighApproach and high - swingHigh >= minimumPenetration and high - swingHigh <= maximumPenetration and close <= swingHigh - reclaimBuffer and (not oneTradePerLevel or not f_usedLevel(usedShortLevels, swingHigh))
// Priority: Previous Day > Opening Range > Confirmed Swing.
// Only one chosen level per direction on a candle.
float sweptLowLevel = previousLowSweep ? previousLow : openingLowSweep ? openingLow : swingLowSweep ? swingLow : na
float sweptHighLevel = previousHighSweep ? previousHigh : openingHighSweep ? openingHigh : swingHighSweep ? swingHigh : na
bool longSweepQuality = lowerWickRatio >= minimumRejectionWick and closeLocation >= minimumCloseLocation and candleSizeOK and volumeOK
bool shortSweepQuality = upperWickRatio >= minimumRejectionWick and closeLocation <= 1.0 - minimumCloseLocation and candleSizeOK and volumeOK
bool rawLongSweep = barstate.isconfirmed and entrySession and beforeForcedExit and not na(sweptLowLevel) and longSweepQuality
bool rawShortSweep = barstate.isconfirmed and entrySession and beforeForcedExit and not na(sweptHighLevel) and shortSweepQuality
bool longSweep = rawLongSweep and not rawShortSweep
bool shortSweep = rawShortSweep and not rawLongSweep
if longSweep
rawLongSweeps += 1
if shortSweep
rawShortSweeps += 1
// ============================================================================
// SECTION 19: PENDING SETUP STATE / INVALIDATION
// ============================================================================
var bool longPending = false
var bool shortPending = false
var int longSweepBar = na
var int shortSweepBar = na
var float longPendingLevel = na
var float shortPendingLevel = na
var float longSweepExtreme = na
var float shortSweepExtreme = na
var float longSweepHigh = na
var float shortSweepLow = na
var float longBodyHigh = na
var float shortBodyLow = na
if newDay or afternoonBegins
longPending := false
shortPending := false
if barstate.isconfirmed
if longPending
bool expiredLong = bar_index - longSweepBar > confirmationWindow
bool failedLong = close < longPendingLevel - reclaimBuffer
bool freshLow = invalidateOnNewExtreme and low < longSweepExtreme - syminfo.mintick
if expiredLong or failedLong or freshLow
longPending := false
if shortPending
bool expiredShort = bar_index - shortSweepBar > confirmationWindow
bool failedShort = close > shortPendingLevel + reclaimBuffer
bool freshHigh = invalidateOnNewExtreme and high > shortSweepExtreme + syminfo.mintick
if expiredShort or failedShort or freshHigh
shortPending := false
// ============================================================================
// SECTION 20: CONFIRMATION ONLY ON A LATER BAR
// ============================================================================
bool longReady = longPending and not na(longSweepBar) and bar_index > longSweepBar and bar_index - longSweepBar <= confirmationWindow
bool shortReady = shortPending and not na(shortSweepBar) and bar_index > shortSweepBar and bar_index - shortSweepBar <= confirmationWindow
bool bullCandle = close > open and bodyRatio >= minimumConfirmBody
bool bearCandle = close < open and bodyRatio >= minimumConfirmBody
bool confirmLongPrice = confirmationMode == "Level + Progress" ? close > close[1] : confirmationMode == "Sweep Body Break" ? close > longBodyHigh : close > longSweepHigh
bool confirmShortPrice = confirmationMode == "Level + Progress" ? close < close[1] : confirmationMode == "Sweep Body Break" ? close < shortBodyLow : close < shortSweepLow
bool longConfirmation = barstate.isconfirmed and longReady and bullCandle and confirmLongPrice and close >= longPendingLevel + reclaimBuffer
bool shortConfirmation = barstate.isconfirmed and shortReady and bearCandle and confirmShortPrice and close <= shortPendingLevel - reclaimBuffer
if longConfirmation or shortConfirmation
confirmations += 1
// ============================================================================
// SECTION 21: STOP DISTANCE / ADAPTIVE TARGET SELECTION
// ============================================================================
float longStop = not na(longSweepExtreme) ? math.round_to_mintick(longSweepExtreme - stopBufferTicks * syminfo.mintick) : na
float shortStop = not na(shortSweepExtreme) ? math.round_to_mintick(shortSweepExtreme + stopBufferTicks * syminfo.mintick) : na
float longRisk = close - longStop
float shortRisk = shortStop - close
bool longRiskOK = not na(longRisk) and longRisk >= minimumRisk and longRisk <= maximumRisk
bool shortRiskOK = not na(shortRisk) and shortRisk >= minimumRisk and shortRisk <= maximumRisk
float vwapLongTarget = math.round_to_mintick(sessionVWAP - vwapTargetBuffer)
float vwapShortTarget = math.round_to_mintick(sessionVWAP + vwapTargetBuffer)
float fixedLongTarget = math.round_to_mintick(close + longRisk * fixedTargetR)
float fixedShortTarget = math.round_to_mintick(close - shortRisk * fixedTargetR)
float vwapLongReward = vwapLongTarget - close
float vwapShortReward = close - vwapShortTarget
bool vwapLongEligible = not na(sessionVWAP) and longRiskOK and vwapLongReward >= minimumGrossTarget and vwapLongReward / longRisk >= minimumRewardRisk
bool vwapShortEligible = not na(sessionVWAP) and shortRiskOK and vwapShortReward >= minimumGrossTarget and vwapShortReward / shortRisk >= minimumRewardRisk
bool useVWAPLong = targetMode == "Session VWAP Only" or (targetMode == "Adaptive VWAP / Fixed R" and vwapLongEligible)
bool useVWAPShort = targetMode == "Session VWAP Only" or (targetMode == "Adaptive VWAP / Fixed R" and vwapShortEligible)
float longObjective = useVWAPLong ? vwapLongTarget : fixedLongTarget
float shortObjective = useVWAPShort ? vwapShortTarget : fixedShortTarget
float longReward = longObjective - close
float shortReward = close - shortObjective
bool longTargetOK = longRiskOK and not na(longReward) and longReward >= minimumGrossTarget and longReward / longRisk >= minimumRewardRisk
bool shortTargetOK = shortRiskOK and not na(shortReward) and shortReward >= minimumGrossTarget and shortReward / shortRisk >= minimumRewardRisk
bool longQualityOK = not strongDown
bool shortQualityOK = not strongUp
bool finalLong = longConfirmation and allowLong and longQualityOK and longTargetOK and commonEntry
bool finalShort = shortConfirmation and allowShort and shortQualityOK and shortTargetOK and commonEntry and not finalLong
if longConfirmation or shortConfirmation
if (longConfirmation and not longQualityOK) or (shortConfirmation and not shortQualityOK)
rejectTrend += 1
else if (longConfirmation and not longRiskOK) or (shortConfirmation and not shortRiskOK)
rejectRisk += 1
else if (longConfirmation and not longTargetOK) or (shortConfirmation and not shortTargetOK)
rejectTarget += 1
else if not finalLong and not finalShort
rejectControls += 1
// ============================================================================
// SECTION 22: ENTRIES / PRESET STRUCTURAL BRACKET
// ============================================================================
var float activeStop = na
var float activeTarget = na
var float initialFillRisk = na
var float activeReclaimLevel = na
var int fillBarSeen = na
var int failureCount = 0
var bool breakEvenActive = false
if finalLong
activeStop := longStop
activeTarget := longObjective
activeReclaimLevel := longPendingLevel
initialFillRisk := na
fillBarSeen := na
failureCount := 0
breakEvenActive := false
strategy.entry("CNPS56-L", strategy.long, comment="SWEEP V4 LONG", alert_message="🟢 VÀO VỊ THẾ LONG (CNPS56)\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("CNPS56-L-X", from_entry="CNPS56-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))
array.push(usedLongLevels, longPendingLevel)
tradesToday += 1
entriesLong += 1
if useVWAPLong
entriesVWAP += 1
else
entriesFixedR += 1
lastOrderBar := bar_index
longPending := false
shortPending := false
else if finalShort
activeStop := shortStop
activeTarget := shortObjective
activeReclaimLevel := shortPendingLevel
initialFillRisk := na
fillBarSeen := na
failureCount := 0
breakEvenActive := false
strategy.entry("CNPS56-S", strategy.short, comment="SWEEP V4 SHORT", alert_message="🔴 VÀO VỊ THẾ SHORT (CNPS56)\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("CNPS56-S-X", from_entry="CNPS56-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))
array.push(usedShortLevels, shortPendingLevel)
tradesToday += 1
entriesShort += 1
if useVWAPShort
entriesVWAP += 1
else
entriesFixedR += 1
lastOrderBar := bar_index
longPending := false
shortPending := false
// ============================================================================
// SECTION 23: ARM NEXT SWEEP / UPDATE CONFIRMED PIVOTS
// ============================================================================
if flat and not finalLong and not finalShort and barstate.isconfirmed
if longSweep
longPending := true
shortPending := false
longSweepBar := bar_index
longPendingLevel := sweptLowLevel
longSweepExtreme := low
longSweepHigh := high
longBodyHigh := math.max(open, close)
else if shortSweep
shortPending := true
longPending := false
shortSweepBar := bar_index
shortPendingLevel := sweptHighLevel
shortSweepExtreme := high
shortSweepLow := low
shortBodyLow := math.min(open, close)
// Confirmed pivots become eligible from the NEXT candle after confirmation.
if marketBar and not newDay and not na(pivotH) and dayKey == dayKey[swingLength]
swingHigh := pivotH
swingHighBar := bar_index - swingLength
if marketBar and not newDay and not na(pivotL) and dayKey == dayKey[swingLength]
swingLow := pivotL
swingLowBar := bar_index - swingLength
// ============================================================================
// SECTION 24: ACTUAL FILL RISK / OPTIONAL EARLY EXITS
// ============================================================================
if strategy.position_size != 0 and strategy.opentrades > 0 and barstate.isconfirmed
int actualEntryBar = strategy.opentrades.entry_bar_index(0)
float actualEntry = strategy.position_avg_price
if na(fillBarSeen) or fillBarSeen != actualEntryBar
fillBarSeen := actualEntryBar
initialFillRisk := inLong ? actualEntry - activeStop : activeStop - actualEntry
float actualReward = inLong ? activeTarget - actualEntry : actualEntry - activeTarget
bool fillValid = not na(initialFillRisk) and initialFillRisk > syminfo.mintick and actualReward > 0
if not fillValid
strategy.close(inLong ? "CNPS56-L" : "CNPS56-S", immediately=true, comment="INVALID NEXT-BAR GAP", alert_message="⚠️ ĐÓNG VỊ THẾ DO GAP/RỦI RO KHÔNG HỢP LỆ (Invalid Gap)")
else
float currentR = (inLong ? close - actualEntry : actualEntry - close) / initialFillRisk
if useBreakEven and currentR >= breakEvenAtR
float breakEvenStop = math.round_to_mintick(inLong ? actualEntry + breakEvenOffset : actualEntry - breakEvenOffset)
activeStop := inLong ? math.max(activeStop, breakEvenStop) : math.min(activeStop, breakEvenStop)
breakEvenActive := true
if inLong
strategy.exit("CNPS56-L-X", from_entry="CNPS56-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
strategy.exit("CNPS56-S-X", from_entry="CNPS56-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))
bool failedReclaim = inLong ? close < activeReclaimLevel - reclaimBuffer : close > activeReclaimLevel + reclaimBuffer
failureCount := failedReclaim ? failureCount + 1 : 0
if useReclaimFailureExit and failureCount >= failureCloses
strategy.close(inLong ? "CNPS56-L" : "CNPS56-S", comment="RECLAIM FAILED", alert_message="⚡ ĐÓNG VỊ THẾ DO TÁI CHIẾM THẤT BẠI (Reclaim Failed)")
if useTimeExit and bar_index - actualEntryBar >= maximumHoldBars
strategy.close(inLong ? "CNPS56-L" : "CNPS56-S", comment="TIME EXIT", alert_message="⏱️ ĐÓNG VỊ THẾ HẾT THỜI GIAN GIỮ LỆNH (Time Exit)")
// ============================================================================
// SECTION 25: FORCE FLAT BEFORE ATC / CLEAR POSITION STATE
// ============================================================================
if forceCloseBar and strategy.position_size != 0
strategy.close_all(immediately=true, comment="FORCED FLAT BEFORE ATC", alert_message="⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End)")
if flat and not finalLong and not finalShort
activeStop := na
activeTarget := na
initialFillRisk := na
activeReclaimLevel := na
fillBarSeen := na
failureCount := 0
breakEvenActive := false
// ============================================================================
// SECTION 26: PLOTS AND SIGNAL MARKERS
// ============================================================================
plot(showLevels and usePrevious ? previousHigh : na, title="Previous Day High", color=color.new(color.red, 65), style=plot.style_linebr)
plot(showLevels and usePrevious ? previousLow : na, title="Previous Day Low", color=color.new(color.teal, 65), style=plot.style_linebr)
plot(showLevels and useOpening and openingRangeAvailable ? openingHigh : na, title="Opening Range High", color=color.new(color.orange, 35), style=plot.style_linebr)
plot(showLevels and useOpening and openingRangeAvailable ? openingLow : na, title="Opening Range Low", color=color.new(color.orange, 35), style=plot.style_linebr)
plot(showLevels and useSwing and highSwingFresh ? swingHigh : na, title="Confirmed Swing High", color=color.new(color.red, 35), style=plot.style_linebr)
plot(showLevels and useSwing and lowSwingFresh ? swingLow : na, title="Confirmed Swing Low", color=color.new(color.teal, 35), style=plot.style_linebr)
plot(showVWAP ? sessionVWAP : na, title="Intraday VWAP", color=color.orange, linewidth=2, style=plot.style_linebr)
plot(showStops and strategy.position_size != 0 ? activeStop : na, title="Active Structural Stop", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showStops and strategy.position_size != 0 ? activeTarget : na, title="Frozen Take Profit", color=color.green, linewidth=2, style=plot.style_linebr)
plotshape(showSweeps and longSweep, title="Raw Low Sweep", style=shape.circle, location=location.belowbar, color=color.new(color.teal, 35), text="SW", size=size.tiny)
plotshape(showSweeps and shortSweep, title="Raw High Sweep", style=shape.circle, location=location.abovebar, color=color.new(color.red, 35), text="SW", size=size.tiny)
plotshape(showSignals and finalLong, title="CNPS56 V4 Long", style=shape.triangleup, location=location.belowbar, color=color.teal, textcolor=color.white, text="L", size=size.small)
plotshape(showSignals and finalShort, title="CNPS56 V4 Short", style=shape.triangledown, location=location.abovebar, color=color.red, textcolor=color.white, text="S", size=size.small)
// ============================================================================
// SECTION 27: DIAGNOSTIC COUNTERS / SIGNAL FUNNEL
// ============================================================================
var table diagnostics = table.new(position.top_right, 2, 17, border_width=1)
if barstate.islast
if showDiagnostics
table.cell(diagnostics, 0, 0, "CNPS56 V4")
table.cell(diagnostics, 1, 0, timeframe.period)
table.cell(diagnostics, 0, 1, "Level Source")
table.cell(diagnostics, 1, 1, levelSource)
table.cell(diagnostics, 0, 2, "Target Mode")
table.cell(diagnostics, 1, 2, targetMode)
table.cell(diagnostics, 0, 3, "Session VWAP")
table.cell(diagnostics, 1, 3, str.tostring(sessionVWAP, format.mintick))
table.cell(diagnostics, 0, 4, "Sweeps Long")
table.cell(diagnostics, 1, 4, str.tostring(rawLongSweeps))
table.cell(diagnostics, 0, 5, "Sweeps Short")
table.cell(diagnostics, 1, 5, str.tostring(rawShortSweeps))
table.cell(diagnostics, 0, 6, "Confirmations")
table.cell(diagnostics, 1, 6, str.tostring(confirmations))
table.cell(diagnostics, 0, 7, "Reject Trend")
table.cell(diagnostics, 1, 7, str.tostring(rejectTrend))
table.cell(diagnostics, 0, 8, "Reject SL Risk")
table.cell(diagnostics, 1, 8, str.tostring(rejectRisk))
table.cell(diagnostics, 0, 9, "Reject Target")
table.cell(diagnostics, 1, 9, str.tostring(rejectTarget))
table.cell(diagnostics, 0, 10, "Reject Controls")
table.cell(diagnostics, 1, 10, str.tostring(rejectControls))
table.cell(diagnostics, 0, 11, "Entries Long")
table.cell(diagnostics, 1, 11, str.tostring(entriesLong))
table.cell(diagnostics, 0, 12, "Entries Short")
table.cell(diagnostics, 1, 12, str.tostring(entriesShort))
table.cell(diagnostics, 0, 13, "Target VWAP / Fixed")
table.cell(diagnostics, 1, 13, str.tostring(entriesVWAP) + " / " + str.tostring(entriesFixedR))
table.cell(diagnostics, 0, 14, "Trades Today")
table.cell(diagnostics, 1, 14, str.tostring(tradesToday) + " / " + str.tostring(maximumTradesPerDay))
table.cell(diagnostics, 0, 15, "PnL Today (closed)")
table.cell(diagnostics, 1, 15, str.tostring(dailyRealizedPnL, "#.0"))
table.cell(diagnostics, 0, 16, "Position")
table.cell(diagnostics, 1, 16, inLong ? "LONG" : inShort ? "SHORT" : "FLAT")
else
table.clear(diagnostics, 0, 0, 1, 16)
// ============================================================================
// RESEARCH / EXECUTION LIMITATIONS
// ============================================================================
// 1. V4 seeks MORE opportunities; this does NOT imply a higher win rate/PF.
// 2. Intraday Previous Day levels require complete loaded prior sessions.
// 3. OR prices become known only after its observation period.
// 4. Swings become known only after both pivot wings confirm.
// 5. No future VWAP: objective is frozen at confirmed signal candle close.
// 6. Initial SL/TP is based on signal CLOSE, not the later fill price.
// 7. Intraday realized-loss guard is not a guaranteed loss limit.
// 8. Force exit at 14:25 assumes suitable intraday chart bar boundaries.
// 9. 0 strategy margin is not the actual VN30F1M margin requirement.
// 10. This code is uncompiled and unbacktested in TradingView here.
2. Những khái niệm kỹ thuật cốt lõi trong CNPS56
2.1. Ba nguồn mức thanh khoản (Liquidity Level Sources) và thứ tự ưu tiên
Bot CNPS56 theo dõi 3 loại ngưỡng thanh khoản theo cơ chế không nhìn trước tương lai (No Future Bars):
- Previous Day High / Low (
previousHigh/previousLow): Được cập nhật từ đỉnh/đáy thực tế của phiên giao dịch trước đó (marketBar:08:45–11:30và13:00–14:45). - Opening Range (
openingHigh/openingLow): Ghi nhận đỉnh/đáy trong khoảng thời gian mở cửa từ09:00(540phút) đến09:00 + openingRangeMinutes(mặc định15phút, tức09:00–09:15). Mốc này chỉ có hiệu lực sau khi cửa sổ kết thúc (openingReady). - Confirmed Intraday Swing (
swingHigh/swingLow): Xác định qua hàmta.pivothigh(high, swingLength, swingLength)vàta.pivotlow(low, swingLength, swingLength)vớiswingLength = 4. Đỉnh/đáy Pivot chỉ được kích hoạt từ nến kế tiếp sau khi hoàn tất 4 nến bên phải trong cùng ngày (dayKey == dayKey[swingLength]) và còn hiệu lực trong phạm vimaximumSwingAge = 90nến.
Nếu một nến quét qua nhiều mốc cùng lúc, bot áp dụng thứ tự ưu tiên cố định: Previous Day > Opening Range > Confirmed Swing, và mỗi nến chỉ chọn tối đa 1 mốc cho mỗi chiều.
2.2. Cấu trúc nến Quét Thanh Khoản (Failed Sweep & Reclaim)
Để được công nhận là một pha quét thanh khoản thất bại hợp lệ, nến Sweep phải đáp ứng đồng thời:
- Tiếp cận từ bên trong: Nếu bật
requireApproachFromInside = true, giá đóng cửa nến trước (close[1]) phải nằm phía trên mức đáy (đối với Sweep đáy) hoặc phía dưới mức đỉnh (đối với Sweep đỉnh). - Biên độ xuyên thủng hợp lệ: Khoảng giá bị quét vượt mốc (
level - lowcho đáy,high - levelcho đỉnh) phải nằm trong đoạn[0.30, 6.0]điểm. - Tái chiếm vùng giá (Reclaim): Giá đóng cửa phải quay trở lại bên trong mốc tối thiểu
reclaimBuffer = 0.10điểm (close >= level + 0.10hoặcclose <= level - 0.10). - Chất lượng hình thái nến:
- Tỷ lệ râu nến từ chối (
lowerWickRatiohoặcupperWickRatio)>= 0.15. - Vị trí giá đóng cửa (
closeLocation = (close - low) / candleRange)>= 0.55(với Long) hoặc<= 0.45(với Short). - Tổng biên độ nến
candleRange <= 3.0 * ATR(14). - Nếu bật
useVolumeFilter:volume >= SMA(volume, 20) * 0.90.
- Tỷ lệ râu nến từ chối (
2.3. Bộ lọc xu hướng mạnh (Regime Filter) & Đường Session VWAP liên tục
- Bộ lọc Regime (
strongDown/strongUp): Sử dụngEMA(close, 55),DMI/ADX(14, 14)và độ dốc EMA chuẩn hóa theo ATR:slopeATR = (emaTrend - emaTrend[5]) / atr. Bot sẽ chặn lệnh Long khi thị trường giảm quá mạnh (adx >= 35.0,slopeATR < -0.55,close < emaTrend,mDI > pDI) và chặn lệnh Short khi thị trường tăng quá mạnh (adx >= 35.0,slopeATR > 0.55,close > emaTrend,pDI > mDI). - Continuous Session VWAP: Tính lũy kế trong ngày trên các nến khớp lệnh liên tục (
09:00–11:30và13:00–14:30, không tính phiên ATC) theo công thứcsessionVWAP = cumulativePV / cumulativeVolumevớihlc3 * volume. Mục tiêu VWAP được đóng băng ngay tại giá đóng cửa nến tín hiệu để tránh dịch chuyển mục tiêu về sau.
3. Nguyên lý hoạt động của CNPS56
Hệ thống vận hành tuần tự qua 5 bước khép kín trên mỗi nến đã đóng (barstate.isconfirmed):
- Bước 1 – Khởi tạo phiên & Cập nhật mốc: Khi sang ngày mới (
newDay), bot reset bộ đếm lệnh, lợi nhuận ngày, danh sách mốc đã giao dịch (usedLongLevels,usedShortLevels), giá trị VWAP lũy kế và cập nhậtpreviousHigh/previousLow. Trong ngày, bot liên tục cập nhậtOpening Range,Confirmed SwingvàsessionVWAP. - Bước 2 – Phát hiện Raw Sweep & Kích hoạt Pending: Khi ở trạng thái
flat, nếu xuất hiện nếnlongSweephoặcshortSweep(loại trừ trường hợp cả hai cùng xảy ra trên một nến) trong khung giờ giao dịch, bot ghi nhận trạng thái chờ (longPending/shortPending), lưu mốc giá, cực trị nến Sweep và thân nến Sweep. Lưu ý: mọi trạng thái chờ sẽ bị xóa khi sang ngày mới hoặc khi bắt đầu phiên chiều (afternoonBegins). - Bước 3 – Kiểm tra hủy setup hoặc Xác nhận ở nến sau: Trong tối đa
5nến sau nến Sweep, setup chờ sẽ bị hủy ngay nếu hết hạn, giá đóng cửa phá ngược lại mốc (close < level - 0.10với Long hoặcclose > level + 0.10với Short), hoặc giá tạo cực trị mới vượt nến Sweep (invalidateOnNewExtreme = true). Ngược lại, nếu xuất hiện nến xác nhận hợp lệ, bot chuyển sang bước kiểm tra rủi ro. - Bước 4 – Tính toán SL/TP & Kiểm tra bộ lọc: Bot tính khoảng cách SL từ
longSweepExtreme/shortSweepExtremecộng2ticks đệm, chọn mục tiêu TP (Adaptive VWAP / Fixed R), kiểm tra điều kiệnminimumRisk/maximumRisk,minimumGrossTarget,minimumRewardRisk, bộ lọcRegime Filtervà các điều kiện kiểm soát giao dịch chung (commonEntry). - Bước 5 – Khớp lệnh & Quản trị vị thế: Gửi lệnh
strategy.entrykèmstrategy.exitcố định, đánh dấu mốc thanh khoản đã dùng để không vào lại trong ngày, và theo dõi các điều kiện thoát lệnh sớm hoặc đóng vị thế trước phiên ATC lúc14:25.
4. Điều kiện vào lệnh Long và Short của CNPS56
4.1. Điều kiện vào lệnh Long
Lệnh Long (CNPS56-L) được kích hoạt khi thỏa mãn đồng thời tất cả các điều kiện sau trên nến đóng (barstate.isconfirmed):
- Đang có setup chờ hợp lệ (
longReady): Đã cólongSweeptrước đó,bar_index > longSweepBarvà khoảng cách không quáconfirmationWindow(5nến). - Nến xác nhận tăng (
bullCandle):close > openvà tỷ lệ thân nếnbodyRatio >= 0.20. - Giá xác nhận theo chế độ (
confirmLongPrice):"Level + Progress":close > close[1]"Sweep Body Break":close > longBodyHigh(giá cao nhất thân nến Sweep)"Sweep Extreme Break":close > longSweepHigh(đỉnh cao nhất nến Sweep)
- Giữ vững vùng tái chiếm:
close >= longPendingLevel + 0.10. - Chiều giao dịch & Bộ lọc xu hướng:
tradeDirection != "Short"và không rơi vào trạng thái giảm quá mạnh (not strongDown). - Rủi ro & Mục tiêu hợp lệ:
longRisknằm trong[1.5, 10.0]điểm;longReward >= 2.5điểm vàlongReward / longRisk >= 1.10. - Thỏa mãn điều kiện kiểm soát chung (
commonEntry).
4.2. Điều kiện vào lệnh Short
Lệnh Short (CNPS56-S) được kích hoạt khi không có finalLong đồng thời và thỏa mãn tất cả điều kiện sau:
- Đang có setup chờ hợp lệ (
shortReady): Đã cóshortSweeptrước đó,bar_index > shortSweepBarvàbar_index - shortSweepBar <= 5. - Nến xác nhận giảm (
bearCandle):close < openvàbodyRatio >= 0.20. - Giá xác nhận theo chế độ (
confirmShortPrice):"Level + Progress":close < close[1]"Sweep Body Break":close < shortBodyLow(giá thấp nhất thân nến Sweep)"Sweep Extreme Break":close < shortSweepLow(đáy thấp nhất nến Sweep)
- Giữ vững vùng tái chiếm:
close <= shortPendingLevel - 0.10. - Chiều giao dịch & Bộ lọc xu hướng:
tradeDirection != "Long"và không rơi vào trạng thái tăng quá mạnh (not strongUp). - Rủi ro & Mục tiêu hợp lệ:
shortRisknằm trong[1.5, 10.0]điểm;shortReward >= 2.5điểm vàshortReward / shortRisk >= 1.10. - Thỏa mãn điều kiện kiểm soát chung (
commonEntry).
4.3. Điều kiện kiểm soát giao dịch chung (commonEntry)
Mọi lệnh mới đều phải vượt qua 8 lớp kiểm soát sau:
- Trạng thái rỗng (
flat):strategy.position_size == 0(không nhồi lệnh,pyramiding = 0). - Khung giờ giao dịch (
entrySession): Nằm trong phiên sáng (09:05–11:25) hoặc phiên chiều (13:05–14:15) theo múi giờAsia/Ho_Chi_Minh. - Trước giờ đóng bắt buộc (
beforeForcedExit): Thời điểm đóng nếncloseMinute < 14:25. - Giới hạn lệnh ngày (
dailyLimitOK):tradesToday < 4. - Thời gian nghỉ sau thoát lệnh (
cooldownOK): Cách nến thoát lệnh gần nhất hơn3nến (bar_index - lastExitBar > 3). - Giới hạn lỗ ngày (
dailyLossOK): Lỗ đã chốt trong ngày không vượt quá-5,000,000 VND. - Tối đa 1 lệnh/nến (
oneOrderPerBar):bar_index != lastOrderBar. - Mỗi mốc 1 lần/ngày (
oneTradePerLevel): Mốc thanh khoản đã giao dịch sẽ được lưu vàousedLongLevels/usedShortLevelsvà không quét lại trong cùng ngày.
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 SL cấu trúc:
- Long:
longStop = math.round_to_mintick(longSweepExtreme - stopBufferTicks * syminfo.mintick)(đáy nến Sweep trừ 2 ticks). - Short:
shortStop = math.round_to_mintick(shortSweepExtreme + stopBufferTicks * syminfo.mintick)(đỉnh nến Sweep cộng 2 ticks).
- Long:
- Bộ lọc Risk tại điểm tín hiệu: Khoảng cách rủi ro (
close - longStophoặcshortStop - close) bắt buộc nằm trong khoảng[1.5, 10.0]điểm. Nếu ngoài khoảng này, tín hiệu bị loại và ghi nhận vào bộ đếmReject SL Risk. - Kiểm tra Gap khi khớp lệnh thực tế: Ở nến khớp lệnh tiếp theo, bot tính lại
initialFillRiskdựa trên giá khớp thực tếstrategy.position_avg_price. Nếu bị trượt giá/Gap làm rủi ro<= syminfo.mintickhoặc mục tiêu TP không còn dương (actualReward <= 0), bot lập tức đóng lệnh (INVALID NEXT-BAR GAP).
5.2. Cơ chế Take Profit, Break Even và Thoát lệnh
- Mục tiêu Take Profit (
targetMode = "Adaptive VWAP / Fixed R"):- Bot kiểm tra trước mục tiêu
sessionVWAP(có trừ/cộngvwapTargetBuffer = 0.0). NếuvwapReward >= 2.5điểm vàvwapReward / risk >= 1.10, bot chọn VWAP làm TP. - Nếu VWAP không đủ hấp dẫn hoặc nằm ngược phía, bot tự động chuyển sang mục tiêu cố định
fixedTargetR = 1.50R(vẫn phải đạt tối thiểu2.5điểm và1.10R).
- Bot kiểm tra trước mục tiêu
- Dời hòa vốn (Break Even – tùy chọn, mặc định
false): Khi bậtuseBreakEven, nếu lợi nhuận đóng nến đạt>= 1.0R, SL sẽ được dời vềactualEntry + 0.2điểm (Long) hoặcactualEntry - 0.2điểm (Short). - Thoát lệnh khi tái chiếm thất bại (tùy chọn, mặc định
false): Nếu giá đóng cửa quay ngược lại phía ngoài mốc tái chiếmfailureCloses = 2nến liên tiếp, bot đóng vị thế (RECLAIM FAILED). - Thoát lệnh theo thời gian (tùy chọn, mặc định
false): Đóng vị thế nếu giữ lệnh quá45nến (TIME EXIT). - Đóng bắt buộc trước ATC: Luôn đóng toàn bộ vị thế bằng
strategy.close_all(immediately=true)tại nến chạm mốc14:25.
5.3. Bảng tổng hợp cơ chế bảo vệ vị thế
| Cơ chế | Trạng thái mặc định | Điều kiện kích hoạt | Hành động của Bot |
|---|---|---|---|
| Structural SL | Luôn bật | Giá chạm activeStop (cực trị Sweep ± 2 ticks) | Cắt lỗ cố định (SL Long / SL Short) |
| Adaptive TP | Luôn bật | Giá chạm activeTarget (VWAP hoặc 1.50R) | Chốt lời (TP Long / TP Short) |
| Invalid Gap Guard | Luôn bật | Giá khớp lệnh thực tế bị Gap khiến Risk/Reward <= 0 | Đóng lệnh ngay (INVALID NEXT-BAR GAP) |
| Break Even | Tắt (false) | currentR >= 1.0 khi đóng nến | Dời SL về giá vào lệnh ± 0.2 điểm |
| Reclaim Failure Exit | Tắt (false) | Giá đóng cửa mất mốc tái chiếm 2 nến liên tiếp | Đóng lệnh (RECLAIM FAILED) |
| Time Exit | Tắt (false) | Giữ lệnh đủ 45 nến chưa chạm SL/TP | Đóng lệnh (TIME EXIT) |
| Forced Flat ATC | Luôn bật | Nến kết thúc lúc >= 14:25 | Đóng toàn bộ vị thế (FORCED FLAT BEFORE ATC) |
| Daily Loss Guard | Bật (true) | Lỗ đã chốt trong ngày >= 5,000,000 VND | Ngừng mở lệnh mới trong ngày |
6. Hướng dẫn cài đặt và đọc bảng Diagnostics trên TradingView
Các bước cài đặt
- Mở biểu đồ hợp đồng phái sinh VN30F1M trên TradingView, chọn khung thời gian M1 hoặc M5.
- 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 toàn bộ mã nguồn Pine Script v6 từ Mục 1 và dán vào Pine Editor.
- Nhấn Save để lưu script, sau đó nhấn Add to chart để đưa chiến lược lên biểu đồ.
- Mở biểu tượng Settings (bánh răng) của chiến lược để tùy chỉnh số lượng hợp đồng (
Contracts Per Entry), chế độ xác nhận hoặc bật/tắt các cơ chế thoát lệnh nâng cao.
Cách đọc bảng chẩn đoán (Diagnostics Table)
Khi bật showDiagnostics = true, bot hiển thị bảng phễu tín hiệu (Signal Funnel) 17 dòng ở góc trên bên phải màn hình:
CNPS56 V4/ Khung thời gian: Hiển thị tên phiên bản và timeframe đang chạy (ví dụ5).Level Source&Target Mode: Cho biết nguồn mức thanh khoản và chế độ TP đang chọn.Session VWAP: Giá trị VWAP phiên hiện tại.Sweeps Long/Sweeps Short: Tổng số nến quét thanh khoản thô đạt chuẩn chất lượng.Confirmations: Số lượng setup đã vượt qua bước xác nhận ở nến sau.Reject Trend/Reject SL Risk/Reject Target/Reject Controls: Phễu thống kê số lượng tín hiệu bị loại theo từng nguyên nhân (ngược xu hướng mạnh, SL ngoài[1.5, 10.0], TP không đủ2.5điểm /1.10R, hoặc vướng giờ/giới hạn ngày/cooldown).Entries Long/Entries Short: Tổng số lệnh Long và Short đã vào.Target VWAP / Fixed: Tỷ lệ số lệnh sử dụng mục tiêu Session VWAP so với Fixed R.Trades Today&PnL Today (closed): Số lệnh đã vào trong ngày trên tổng giới hạn và lãi/lỗ đã chốt trong ngày (VND).Position: Trạng thái vị thế hiện tại (LONG,SHORT, hoặcFLAT).
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 TradingView App, Telegram hoặc Webhook khi bot phát sinh tín hiệu, bạn thực hiện:
- 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
CNPS56 LIQUIDITY SWEEP V4 ACTIVE BALANCED - VN30F1M. - Tại mục Message, xóa nội dung mặc định và điền chính xác cú pháp:
{{strategy.order.alert_message}} - Nhấn Create để kích hoạt cảnh báo.
Bảng thông điệp Alert của CNPS56
| Sự kiện | Mã lệnh / Comment | Nội dung thông điệp (alert_message / alert_profit / alert_loss) |
|---|---|---|
| Vào lệnh Long | CNPS56-L | 🟢 VÀO VỊ THẾ LONG (CNPS56) kèm Giá vào, Cắt lỗ (SL), Chốt lời (TP) |
| Vào lệnh Short | CNPS56-S | 🔴 VÀO VỊ THẾ SHORT (CNPS56) kèm Giá vào, Cắt lỗ (SL), Chốt lời (TP) |
| Chốt lời (TP) | TP Long / TP Short | 💰 CHỐT LỜI LONG (TP HIT) / 💰 CHỐT LỜI SHORT (TP HIT) kèm Giá chốt lời |
| Cắt lỗ (SL) | SL Long / SL Short | 🛑 CẮT LỖ LONG (SL HIT) / 🛑 CẮT LỖ SHORT (SL HIT) kèm Giá cắt lỗ |
| Hòa vốn (BE) | BE Long / BE Short | 🛡️ HÒA VỐN LONG (BE HIT) / 🛡️ HÒA VỐN SHORT (BE HIT) kèm Giá hòa vốn |
| Lỗi Gap khớp lệnh | INVALID NEXT-BAR GAP | ⚠️ ĐÓNG VỊ THẾ DO GAP/RỦI RO KHÔNG HỢP LỆ (Invalid Gap) |
| Tái chiếm thất bại | RECLAIM FAILED | ⚡ ĐÓNG VỊ THẾ DO TÁI CHIẾM THẤT BẠI (Reclaim Failed) |
| Hết thời gian giữ | TIME EXIT | ⏱️ ĐÓNG VỊ THẾ HẾT THỜI GIAN GIỮ LỆNH (Time Exit) |
| Đóng hết phiên | FORCED FLAT BEFORE ATC | ⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End) |
Kết luận
Bot CNPS56 Liquidity Sweep V4 Active Balanced là một mô hình nghiên cứu bài bản cho giao dịch trong ngày trên VN30F1M, kết hợp chặt chẽ giữa hành vi quét thanh khoản tại các mốc giá quan trọng (Previous Day, Opening Range, Confirmed Swing), kỷ luật chờ xác nhận ở nến sau và cơ chế chốt lời thích ứng theo Session VWAP / Fixed R. Hệ thống phù hợp nhất trong các phiên thị trường có cấu trúc hai chiều hoặc dao động quanh các ngưỡng hỗ trợ/kháng cự rõ ràng, đồng thời tự động đứng ngoài khi thị trường bước vào xu hướng một chiều quá mạnh (ADX >= 35).
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 để so sánh hiệu suất và lựa chọn chiến lược phù hợp với khẩu vị rủi ro 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.





