Hướng Dẫn Sử Dụng Bot CNPS75 - CCI Extreme Reversal cho VN30F1M
TradingviewBot CNPS75 CCI Extreme Reversal bắt đảo chiều khi chỉ báo CCI thoát vùng cực trị ±200, xác nhận nến đảo chiều trong 3 thanh và quản trị rủi ro SL 5 điểm / TP 15 điểm trên VN30F1M.

Mục lục
Khi giao dịch hợp đồng tương lai chỉ số VN30F1M, thị trường thường xuyên xuất hiện những nhịp kéo rướn quá đà (quá mua hoặc quá bán cực đoan) trước khi đảo chiều đột ngột. Nếu vào lệnh bắt đỉnh/đáy quá sớm khi động lượng vẫn còn mạnh, nhà đầu tư rất dễ bị quét cắt lỗ; ngược lại, nếu chờ xác nhận quá muộn thì tỷ lệ Risk:Reward không còn tối ưu.
Chiến lược CNPS75 CCI EXTREME REVERSAL (viết bằng Pine Script v6 trên TradingView) được thiết kế để giải quyết bài toán này theo quy trình 3 bước chặt chẽ: Extreme → CCI Re-entry → Price Confirmation (Quá cực trị → CCI quay đầu vào vùng bình thường → Xác nhận hành động giá).
Những điểm nổi bật cốt lõi của Bot CNPS75:
- Bắt điểm quay đầu từ vùng cực trị CCI ±200: Chỉ kích hoạt trạng thái chờ (Pending Setup) khi CCI cắt lên từ dưới
-200(quá bán) hoặc cắt xuống từ trên+200(quá mua). - Cơ chế Pending Setup có thời hạn: Cho phép tín hiệu xác nhận nến diễn ra ngay trên nến re-entry hoặc trong tối đa
3nến kế tiếp, tự động hủy nếu quá hạn hoặc CCI quay lại vùng cực trị. - Hệ thống bộ lọc đa tầng tùy chọn: Tích hợp sẵn 5 bộ lọc độc lập gồm RSI, ADX, Volume Spike, EMA khung biểu đồ và Confirmed H1 EMA (khung H1 đã đóng nến, chống repaint).
- Quản trị rủi ro cố định & đóng vị thế cuối phiên: Mặc định Stop Loss
5.0điểm và Take Profit15.0điểm (tỷ lệ R:R1:3), tự động đóng toàn bộ vị thế vào14:45theo giờ Việt Nam.
1. CNPS75 CCI Extreme Reversal là gì?
CNPS75 CCI EXTREME REVERSAL (shorttitle="CNPS75 CCI REV") là một hệ thống giao dịch đảo chiều (Mean Reversion / Extreme Reversal) hoạt động trên nguyên lý chờ chỉ báo Commodity Channel Index (CCI) đi vào vùng cực trị (< -200 hoặc > +200) rồi quay đầu trở lại, kết hợp xác nhận bằng cấu trúc nến trước khi khớp lệnh.
Chiến lược được xây dựng trên 4 trụ cột kỹ thuật chính:
- CCI Extreme & Re-entry Engine: Sử dụng
ta.cci(hlc3, 20)để phát hiện các pha quá bán (cci < -200) và quá mua (cci > 200), sau đó bắt sự kiệnta.crossover(cci, -200)hoặcta.crossunder(cci, 200). - Pending Setup & Price Confirmation: Lưu trữ trạng thái chờ (
pendingLong/pendingShort) trong tối đaconfirmationBars(3thanh) và chỉ kích hoạt tín hiệu cơ sở khi thỏa mãn điều kiện xác nhận nến (mặc định là nến tăngclose > opencho Long và nến giảmclose < opencho Short). - Multi-Filter Gatekeeper (Tùy chọn): Cho phép bật/tắt linh hoạt các bộ lọc RSI, ADX, Volume Spike, EMA và H1 EMA Bias để loại bỏ các pha bắt dao rơi trong xu hướng quá mạnh hoặc thiếu thanh khoản.
- Risk & Session Control: Kiểm soát chặt số lệnh tối đa mỗi ngày (
2lệnh/ngày), thời gian nghỉ sau khi thoát lệnh (cooldownBars), giờ giao dịch theo múi giờAsia/Ho_Chi_Minhvà đóng vị thế bắt buộc cuối phiên lúc14:45.
Bảng thông số mặc định
Dưới đây là toàn bộ các nhóm thông số đầu vào (input.*) và giá trị mặc định thực tế trong mã nguồn CNPS75:
| Nhóm thông số | Tên biến / Nhãn hiển thị | Giá trị mặc định | Ý nghĩa trong code |
|---|---|---|---|
| CCI | CCI Length (cciLength) | 20 | Chu kỳ tính chỉ báo CCI |
| CCI | CCI Source (cciSource) | hlc3 | Nguồn giá tính CCI (High+Low+Close)/3 |
| CCI | CCI Oversold (cciOversold) | -200.0 | Ngưỡng quá bán cực trị |
| CCI | CCI Overbought (cciOverbought) | 200.0 | Ngưỡng quá mua cực trị |
| Confirmation | Maximum Confirmation Bars | 3 | Số nến tối đa chờ xác nhận sau CCI Re-entry |
| Confirmation | Require Bullish / Bearish Candle? | true | Yêu cầu nến tăng (close > open) / giảm (close < open) |
| Confirmation | Require Previous High / Low Break? | false | Yêu cầu phá đỉnh (high[1]) / đáy (low[1]) nến trước |
| Confirmation | Require CCI Rising / Falling? | false | Yêu cầu CCI đang dốc lên (cci > cci[1]) / xuống (cci < cci[1]) |
| RSI | Use RSI Filter? (useRSIFilter) | false | Bật/tắt bộ lọc RSI (rsiLength = 14, Long ≤ 50, Short ≥ 50) |
| ADX | Use ADX Filter? (useADXFilter) | false | Bật/tắt bộ lọc ADX (diLength = 14, adxSmoothing = 14, maximumADX = 30.0) |
| Volume | Require Volume Spike? | false | Bật/tắt lọc bùng nổ khối lượng (SMA 20, hệ số 1.20) |
| EMA | Use EMA Trend Filter? | false | Bật/tắt lọc xu hướng theo EMA (emaLength = 20) |
| H1 Trend | Use Confirmed H1 EMA Bias? | false | Bật/tắt lọc xu hướng H1 đã đóng nến (h1EMALength = 50) |
| Risk Management | Stop Loss (Points) | 5.0 | Khoảng cách cắt lỗ cố định tính theo điểm |
| Risk Management | Take Profit (Points) | 15.0 | Khoảng cách chốt lời cố định tính theo điểm |
| Trade Control | Maximum Trades Per Day | 2 | Số lệnh tối đa được phép mở trong ngày |
| Trade Control | Trade Direction | "Long" | Hướng giao dịch (Long, Short, hoặc Both) |
| Trade Control | Cooldown Bars After Exit | 0 | Số nến nghỉ bắt buộc sau khi đóng lệnh |
| Session | Use Entry Session Filter? | false | Bật/tắt lọc khung giờ vào lệnh (09:00 – 14:30) |
| Session | Strategy Timezone | "Asia/Ho_Chi_Minh" | Múi giờ chuẩn của chiến lược |
| Session | Force Close Hour / Minute | 14:45 | Giờ tự động đóng toàn bộ vị thế cuối phiên |
| Alerts / Display | Disable SL / TP Alerts? | false | Tắt/bật thông báo khi khớp SL hoặc TP |
| Alerts / Display | Show Active SL / TP? | true | Hiển thị đường SL/TP đang chạy trên biểu đồ |
| Alerts / Display | Show Diagnostics? | false | Bật/tắt bảng thống kê chẩn đoán góc trên bên phải |
Source Code CNPS75 CCI Extreme Reversal
Bạn có thể sao chép toàn bộ mã nguồn Pine Script v6 dưới đây để dán trực tiếp vào Pine Editor trên TradingView:
//@version=6
strategy(title="CNPS75 CCI EXTREME REVERSAL", shorttitle="CNPS75 CCI REV", overlay=true, initial_capital=100000000, default_qty_type=strategy.fixed, default_qty_value=1, pyramiding=0, margin_long=0, margin_short=0, slippage=0, commission_type=strategy.commission.cash_per_contract, commission_value=0, fill_orders_on_standard_ohlc=true, process_orders_on_close=true, calc_on_order_fills=true, max_labels_count=300, max_lines_count=300, max_bars_back=5000)
// ============================================================================
// CNPS75 CCI EXTREME REVERSAL
// EXTREME -> CCI RE-ENTRY -> PRICE CONFIRMATION
//
// LONG:
// CCI crosses above -200 after oversold extreme.
// Wait for bullish candle confirmation.
// Optional RSI / ADX / Volume / EMA filters.
// LONG.
//
// SHORT:
// CCI crosses below +200 after overbought extreme.
// Wait for bearish candle confirmation.
// Optional filters.
// SHORT.
//
// DEFAULT SL = 5 POINTS
// DEFAULT TP = 15 POINTS
// ============================================================================
// ============================================================================
// SECTION 1: CCI SETTINGS
// ============================================================================
cciLength = input.int(20, "CCI Length", minval=2, maxval=500, group="CCI")
cciSource = input.source(hlc3, "CCI Source", group="CCI")
cciOversold = input.float(-200.0, "CCI Oversold", maxval=-1, step=10, group="CCI")
cciOverbought = input.float(200.0, "CCI Overbought", minval=1, step=10, group="CCI")
// ============================================================================
// SECTION 2: REVERSAL CONFIRMATION
// ============================================================================
confirmationBars = input.int(3, "Maximum Confirmation Bars", minval=0, maxval=30, group="Confirmation")
requireCandleDirection = input.bool(true, "Require Bullish / Bearish Candle?", group="Confirmation")
requirePreviousBreak = input.bool(false, "Require Previous High / Low Break?", group="Confirmation")
requireCCIDirection = input.bool(false, "Require CCI Rising / Falling?", group="Confirmation")
// ============================================================================
// SECTION 3: RSI FILTER
// ============================================================================
useRSIFilter = input.bool(false, "Use RSI Filter?", group="RSI")
rsiLength = input.int(14, "RSI Length", minval=2, group="RSI")
longRSIMax = input.float(50.0, "Maximum RSI For Long", minval=1, maxval=100, group="RSI")
shortRSIMin = input.float(50.0, "Minimum RSI For Short", minval=1, maxval=100, group="RSI")
// ============================================================================
// SECTION 4: ADX FILTER
// ============================================================================
useADXFilter = input.bool(false, "Use ADX Filter?", group="ADX")
diLength = input.int(14, "DI Length", minval=2, group="ADX")
adxSmoothing = input.int(14, "ADX Smoothing", minval=2, group="ADX")
maximumADX = input.float(30.0, "Maximum ADX", minval=1, step=1, group="ADX")
// ============================================================================
// SECTION 5: VOLUME FILTER
// ============================================================================
requireVolumeSpike = input.bool(false, "Require Volume Spike?", group="Volume")
volumeAverageLength = input.int(20, "Volume Average Length", minval=2, group="Volume")
volumeSpikeFactor = input.float(1.20, "Volume Spike Factor", minval=0.1, step=0.1, group="Volume")
// ============================================================================
// SECTION 6: EMA FILTER
// ============================================================================
useEMAFilter = input.bool(false, "Use EMA Trend Filter?", group="EMA")
emaLength = input.int(20, "EMA Length", minval=1, group="EMA")
// ============================================================================
// SECTION 7: H1 TREND
// ============================================================================
useH1EMABias = input.bool(false, "Use Confirmed H1 EMA Bias?", group="H1 Trend")
h1EMALength = input.int(50, "H1 EMA Length", minval=1, group="H1 Trend")
// ============================================================================
// SECTION 8: RISK MANAGEMENT
// ============================================================================
stopLossPoints = input.float(5.0, "Stop Loss (Points)", minval=0.1, step=0.5, group="Risk Management")
takeProfitPoints = input.float(15.0, "Take Profit (Points)", minval=0.1, step=0.5, group="Risk Management")
// ============================================================================
// SECTION 9: TRADE CONTROL
// ============================================================================
maximumTradesPerDay = input.int(2, "Maximum Trades Per Day", minval=1, maxval=20, group="Trade Control")
tradeDirection = input.string("Long", "Trade Direction", options=["Long", "Short", "Both"], group="Trade Control")
cooldownBars = input.int(0, "Cooldown Bars After Exit", minval=0, maxval=100, group="Trade Control")
bool allowLong = (tradeDirection == "Long" or tradeDirection == "Both")
bool allowShort = (tradeDirection == "Short" or tradeDirection == "Both")
// ============================================================================
// SECTION 10: SESSION
// ============================================================================
useSessionFilter = input.bool(false, "Use Entry Session Filter?", group="Session")
strategyTimezone = input.string("Asia/Ho_Chi_Minh", "Strategy Timezone", group="Session")
sessionStartHour = input.int(9, "Session Start Hour", minval=0, maxval=23, group="Session")
sessionStartMinute = input.int(0, "Session Start Minute", minval=0, maxval=59, group="Session")
lastEntryHour = input.int(14, "Last Entry Hour", minval=0, maxval=23, group="Session")
lastEntryMinute = input.int(30, "Last Entry Minute", minval=0, maxval=59, group="Session")
sessionEndHour = input.int(14, "Force Close Hour", minval=0, maxval=23, group="Session")
sessionEndMinute = input.int(45, "Force Close Minute", minval=0, maxval=59, group="Session")
// ============================================================================
// SECTION 11: ALERT CONTROL
// ============================================================================
disableSLTPAlerts = input.bool(false, "Disable SL / TP Alerts?", group="Alerts")
// ============================================================================
// SECTION 12: DISPLAY
// ============================================================================
showEMA = input.bool(false, "Show EMA?", group="Display")
showH1EMA = input.bool(false, "Show H1 EMA?", group="Display")
showSignalMarkers = input.bool(false, "Show Signal Markers?", group="Display")
showExtremeMarkers = input.bool(false, "Show CCI Re-entry Markers?", group="Display")
showActiveSLTP = input.bool(true, "Show Active SL / TP?", group="Display")
showDiagnostics = input.bool(false, "Show Diagnostics?", group="Display")
// ============================================================================
// SECTION 13: TIME ENGINE
// ============================================================================
int currentMinute = (hour(time, strategyTimezone) * 60 + minute(time, strategyTimezone))
int currentCloseMinute = (hour(time_close, strategyTimezone) * 60 + minute(time_close, strategyTimezone))
int sessionStartTotal = (sessionStartHour * 60 + sessionStartMinute)
int lastEntryTotal = (lastEntryHour * 60 + lastEntryMinute)
int sessionEndTotal = (sessionEndHour * 60 + sessionEndMinute)
bool entrySession = (currentMinute >= sessionStartTotal and currentCloseMinute <= lastEntryTotal)
bool sessionOK = (not useSessionFilter or entrySession)
// ============================================================================
// SECTION 14: TRADING DAY
// ============================================================================
int tradingDayKey = (year(time, strategyTimezone) * 10000 + month(time, strategyTimezone) * 100 + dayofmonth(time, strategyTimezone))
bool newTradingDay = (bar_index == 0 or tradingDayKey != tradingDayKey[1])
var int tradesToday = 0
if newTradingDay
tradesToday := 0
// ============================================================================
// SECTION 15: CCI ENGINE
// ============================================================================
float cci = ta.cci(cciSource, cciLength)
bool cciExtremeLow = (not na(cci) and cci < cciOversold)
bool cciExtremeHigh = (not na(cci) and cci > cciOverbought)
bool bullishCCIReentry = ta.crossover(cci, cciOversold)
bool bearishCCIReentry = ta.crossunder(cci, cciOverbought)
// ============================================================================
// SECTION 16: RSI ENGINE
// ============================================================================
float rsi = ta.rsi(close, rsiLength)
bool longRSIOK = (not useRSIFilter or (not na(rsi) and rsi <= longRSIMax))
bool shortRSIOK = (not useRSIFilter or (not na(rsi) and rsi >= shortRSIMin))
// ============================================================================
// SECTION 17: ADX ENGINE
// ============================================================================
[diPlus, diMinus, adx] = ta.dmi(diLength, adxSmoothing)
bool adxOK = (not useADXFilter or (not na(adx) and adx <= maximumADX))
// ============================================================================
// SECTION 18: VOLUME ENGINE
// ============================================================================
float averageVolume = ta.sma(volume, volumeAverageLength)
bool volumeSpike = (not na(averageVolume) and volume >= averageVolume * volumeSpikeFactor)
bool volumeOK = (not requireVolumeSpike or volumeSpike)
// ============================================================================
// SECTION 19: EMA ENGINE
// ============================================================================
float ema = ta.ema(close, emaLength)
bool longEMAOK = (not useEMAFilter or close > ema)
bool shortEMAOK = (not useEMAFilter or close < ema)
// ============================================================================
// SECTION 20: CONFIRMED H1 EMA
// ============================================================================
//
// Uses previous completed H1 candle.
// Intended for chart timeframes below H1.
//
// ============================================================================
float h1EMA = request.security(syminfo.tickerid, "60", ta.ema(close, h1EMALength)[1], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
float h1Close = request.security(syminfo.tickerid, "60", close[1], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
bool longBiasOK = (not useH1EMABias or (not na(h1EMA) and not na(h1Close) and h1Close > h1EMA))
bool shortBiasOK = (not useH1EMABias or (not na(h1EMA) and not na(h1Close) and h1Close < h1EMA))
// ============================================================================
// SECTION 21: PRICE CONFIRMATION
// ============================================================================
bool bullishCandle = (close > open)
bool bearishCandle = (close < open)
bool longCandleOK = (not requireCandleDirection or bullishCandle)
bool shortCandleOK = (not requireCandleDirection or bearishCandle)
bool longBreakOK = (not requirePreviousBreak or close > high[1])
bool shortBreakOK = (not requirePreviousBreak or close < low[1])
bool longCCIDirectionOK = (not requireCCIDirection or cci > cci[1])
bool shortCCIDirectionOK = (not requireCCIDirection or cci < cci[1])
bool longConfirmation = (longCandleOK and longBreakOK and longCCIDirectionOK)
bool shortConfirmation = (shortCandleOK and shortBreakOK and shortCCIDirectionOK)
// ============================================================================
// SECTION 22: CCI PENDING SETUP ENGINE
// ============================================================================
//
// When CCI returns inside extreme zone:
// Store one pending reversal setup.
//
// Confirmation can occur on the SAME candle
// or within the next N candles.
//
// Repeated recalculations on the same bar
// do not create duplicate setups.
//
// ============================================================================
var bool pendingLong = false
var bool pendingShort = false
var int pendingLongBar = na
var int pendingShortBar = na
var int bullExtremeCount = 0
var int bearExtremeCount = 0
var int bullReentryCount = 0
var int bearReentryCount = 0
var int expiredLongCount = 0
var int expiredShortCount = 0
var int lastProcessedBar = na
bool processState = (barstate.isconfirmed and (na(lastProcessedBar) or lastProcessedBar != bar_index))
if processState
lastProcessedBar := bar_index
if newTradingDay
pendingLong := false
pendingShort := false
pendingLongBar := na
pendingShortBar := na
if cciExtremeLow and not cciExtremeLow[1]
bullExtremeCount += 1
if cciExtremeHigh and not cciExtremeHigh[1]
bearExtremeCount += 1
// Expire pending setups.
if pendingLong and not na(pendingLongBar)
if (bar_index - pendingLongBar > confirmationBars)
pendingLong := false
pendingLongBar := na
expiredLongCount += 1
if pendingShort and not na(pendingShortBar)
if (bar_index - pendingShortBar > confirmationBars)
pendingShort := false
pendingShortBar := na
expiredShortCount += 1
// Cancel invalid setups.
if pendingLong and cci < cciOversold
pendingLong := false
pendingLongBar := na
if pendingShort and cci > cciOverbought
pendingShort := false
pendingShortBar := na
// Register CCI re-entry events.
if bullishCCIReentry
pendingLong := true
pendingLongBar := bar_index
pendingShort := false
pendingShortBar := na
bullReentryCount += 1
if bearishCCIReentry
pendingShort := true
pendingShortBar := bar_index
pendingLong := false
pendingLongBar := na
bearReentryCount += 1
// ============================================================================
// SECTION 23: VALID SETUPS
// ============================================================================
bool validLongSetup = (pendingLong and not na(pendingLongBar) and bar_index - pendingLongBar <= confirmationBars)
bool validShortSetup = (pendingShort and not na(pendingShortBar) and bar_index - pendingShortBar <= confirmationBars)
// ============================================================================
// SECTION 24: BASE SIGNALS
// ============================================================================
bool longBase = (validLongSetup and longConfirmation)
bool shortBase = (validShortSetup and shortConfirmation)
// ============================================================================
// SECTION 25: RAW SIGNALS
// ============================================================================
bool rawLongSignal = (longBase and longRSIOK and adxOK and volumeOK and longEMAOK and longBiasOK)
bool rawShortSignal = (shortBase and shortRSIOK and adxOK and volumeOK and shortEMAOK and shortBiasOK)
// ============================================================================
// SECTION 26: POSITION STATE
// ============================================================================
bool positionFlat = (strategy.position_size == 0)
bool positionLong = (strategy.position_size > 0)
bool positionShort = (strategy.position_size < 0)
bool positionJustClosed = (positionFlat and strategy.position_size[1] != 0)
// ============================================================================
// SECTION 27: COOLDOWN
// ============================================================================
var int lastExitBar = na
if positionJustClosed
lastExitBar := bar_index
bool cooldownOK = (na(lastExitBar) or bar_index - lastExitBar > cooldownBars)
// ============================================================================
// SECTION 28: CAN TRADE
// ============================================================================
bool dailyTradeLimitOK = (tradesToday < maximumTradesPerDay)
bool canTrade = (positionFlat and dailyTradeLimitOK and cooldownOK and sessionOK and currentCloseMinute < sessionEndTotal and barstate.isconfirmed)
// ============================================================================
// SECTION 29: SIGNAL PROTECTION
// ============================================================================
bool ambiguousSignal = (rawLongSignal and rawShortSignal)
var int lastEntryBar = na
bool notEnteredThisBar = (na(lastEntryBar) or bar_index != lastEntryBar)
bool finalLongSignal = (canTrade and notEnteredThisBar and allowLong and rawLongSignal and not ambiguousSignal)
bool finalShortSignal = (canTrade and notEnteredThisBar and allowShort and rawShortSignal and not ambiguousSignal)
// ============================================================================
// SECTION 30: DIAGNOSTIC COUNTERS
// ============================================================================
var int longBaseCount = 0
var int shortBaseCount = 0
var int longSignalCount = 0
var int shortSignalCount = 0
var int longEntryCount = 0
var int shortEntryCount = 0
if processState
if longBase
longBaseCount += 1
if shortBase
shortBaseCount += 1
if rawLongSignal
longSignalCount += 1
if rawShortSignal
shortSignalCount += 1
// ============================================================================
// SECTION 31: LONG ENTRY
// ============================================================================
if finalLongSignal
strategy.entry("Long", strategy.long, comment="CCI Extreme Long", alert_message="🟢 VÀO VỊ THẾ LONG (CNPS75 CCI Extreme Reversal)\\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\\n🛑 Cắt lỗ (SL): " + str.tostring(close - stopLossPoints, format.mintick) + "\\n💰 Chốt lời (TP): " + str.tostring(close + takeProfitPoints, format.mintick))
tradesToday += 1
longEntryCount += 1
lastEntryBar := bar_index
// Consume current setup.
pendingLong := false
pendingLongBar := na
// ============================================================================
// SECTION 32: SHORT ENTRY
// ============================================================================
if finalShortSignal
strategy.entry("Short", strategy.short, comment="CCI Extreme Short", alert_message="🔴 VÀO VỊ THẾ SHORT (CNPS75 CCI Extreme Reversal)\\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\\n🛑 Cắt lỗ (SL): " + str.tostring(close + stopLossPoints, format.mintick) + "\\n💰 Chốt lời (TP): " + str.tostring(close - takeProfitPoints, format.mintick))
tradesToday += 1
shortEntryCount += 1
lastEntryBar := bar_index
// Consume current setup.
pendingShort := false
pendingShortBar := na
// ============================================================================
// SECTION 33: ACTIVE RISK LEVELS
// ============================================================================
var float activeLongSL = na
var float activeLongTP = na
var float activeShortSL = na
var float activeShortTP = na
// ============================================================================
// SECTION 34: LONG SL / TP
// ============================================================================
if positionLong
float entryPrice = (strategy.position_avg_price)
activeLongSL := (entryPrice - stopLossPoints)
activeLongTP := (entryPrice + takeProfitPoints)
strategy.exit("Long Exit", from_entry="Long", stop=activeLongSL, limit=activeLongTP, comment_profit="TP Long", comment_loss="SL Long", alert_profit="💰 CHỐT LỜI LONG (TP HIT)\\n🎯 Giá chốt: " + str.tostring(activeLongTP, format.mintick), alert_loss="🛑 CẮT LỖ LONG (SL HIT)\\n🎯 Giá cắt: " + str.tostring(activeLongSL, format.mintick), disable_alert=disableSLTPAlerts)
// ============================================================================
// SECTION 35: SHORT SL / TP
// ============================================================================
if positionShort
float entryPrice = (strategy.position_avg_price)
activeShortSL := (entryPrice + stopLossPoints)
activeShortTP := (entryPrice - takeProfitPoints)
strategy.exit("Short Exit", from_entry="Short", stop=activeShortSL, limit=activeShortTP, comment_profit="TP Short", comment_loss="SL Short", alert_profit="💰 CHỐT LỜI SHORT (TP HIT)\\n🎯 Giá chốt: " + str.tostring(activeShortTP, format.mintick), alert_loss="🛑 CẮT LỖ SHORT (SL HIT)\\n🎯 Giá cắt: " + str.tostring(activeShortSL, format.mintick), disable_alert=disableSLTPAlerts)
// ============================================================================
// SECTION 36: POSITION CLEANUP
// ============================================================================
if positionJustClosed
activeLongSL := na
activeLongTP := na
activeShortSL := na
activeShortTP := na
// ============================================================================
// SECTION 37: SESSION END
// ============================================================================
bool finalSessionBar = (currentMinute < sessionEndTotal and currentCloseMinute >= sessionEndTotal)
if finalSessionBar and strategy.position_size != 0
strategy.close_all(immediately=true, comment="Session End", alert_message="⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End)\\n🎯 Giá đóng: " + str.tostring(close, format.mintick))
// ============================================================================
// SECTION 38: EMA DISPLAY
// ============================================================================
plot(showEMA and useEMAFilter ? ema : na, title="EMA Trend", color=color.orange, linewidth=2)
plot(showH1EMA and useH1EMABias ? h1EMA : na, title="Confirmed H1 EMA", color=color.blue, linewidth=1)
// ============================================================================
// SECTION 39: ACTIVE SL / TP DISPLAY
// ============================================================================
plot(showActiveSLTP and positionLong ? activeLongSL : na, title="Long SL", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showActiveSLTP and positionLong ? activeLongTP : na, title="Long TP", color=color.green, linewidth=2, style=plot.style_linebr)
plot(showActiveSLTP and positionShort ? activeShortSL : na, title="Short SL", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showActiveSLTP and positionShort ? activeShortTP : na, title="Short TP", color=color.green, linewidth=2, style=plot.style_linebr)
// ============================================================================
// SECTION 40: SETUP MARKERS
// ============================================================================
plotshape(showExtremeMarkers and bullishCCIReentry, title="CCI Bull Re-entry", style=shape.circle, location=location.belowbar, color=color.aqua, size=size.tiny, text="CCI")
plotshape(showExtremeMarkers and bearishCCIReentry, title="CCI Bear Re-entry", style=shape.circle, location=location.abovebar, color=color.orange, size=size.tiny, text="CCI")
plotshape(showSignalMarkers and rawLongSignal, title="CCI Long Setup", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.tiny, text="L", textcolor=color.white)
plotshape(showSignalMarkers and rawShortSignal, title="CCI Short Setup", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.tiny, text="S", textcolor=color.white)
// ============================================================================
// SECTION 41: CCI DATA WINDOW
// ============================================================================
plot(cci, title="CCI Value", color=color.purple, display=display.data_window)
plot(rsi, title="RSI Value", color=color.blue, display=display.data_window)
// ============================================================================
// SECTION 42: DIAGNOSTICS TABLE
// ============================================================================
var table diagnostics = table.new(position.top_right, 2, 20, border_width=1)
if showDiagnostics and barstate.islast
string positionText = (positionLong ? "LONG" : positionShort ? "SHORT" : "FLAT")
table.cell(diagnostics, 0, 0, "CNPS75")
table.cell(diagnostics, 1, 0, timeframe.period)
table.cell(diagnostics, 0, 1, "CCI")
table.cell(diagnostics, 1, 1, str.tostring(cci, "#.##"))
table.cell(diagnostics, 0, 2, "RSI")
table.cell(diagnostics, 1, 2, str.tostring(rsi, "#.##"))
table.cell(diagnostics, 0, 3, "ADX")
table.cell(diagnostics, 1, 3, str.tostring(adx, "#.##"))
table.cell(diagnostics, 0, 4, "Bull Extremes")
table.cell(diagnostics, 1, 4, str.tostring(bullExtremeCount))
table.cell(diagnostics, 0, 5, "Bear Extremes")
table.cell(diagnostics, 1, 5, str.tostring(bearExtremeCount))
table.cell(diagnostics, 0, 6, "Bull Re-entries")
table.cell(diagnostics, 1, 6, str.tostring(bullReentryCount))
table.cell(diagnostics, 0, 7, "Bear Re-entries")
table.cell(diagnostics, 1, 7, str.tostring(bearReentryCount))
table.cell(diagnostics, 0, 8, "Long Bases")
table.cell(diagnostics, 1, 8, str.tostring(longBaseCount))
table.cell(diagnostics, 0, 9, "Short Bases")
table.cell(diagnostics, 1, 9, str.tostring(shortBaseCount))
table.cell(diagnostics, 0, 10, "Long Signals")
table.cell(diagnostics, 1, 10, str.tostring(longSignalCount))
table.cell(diagnostics, 0, 11, "Short Signals")
table.cell(diagnostics, 1, 11, str.tostring(shortSignalCount))
table.cell(diagnostics, 0, 12, "Pending Long")
table.cell(diagnostics, 1, 12, pendingLong ? "YES" : "NO")
table.cell(diagnostics, 0, 13, "Pending Short")
table.cell(diagnostics, 1, 13, pendingShort ? "YES" : "NO")
table.cell(diagnostics, 0, 14, "Expired Long")
table.cell(diagnostics, 1, 14, str.tostring(expiredLongCount))
table.cell(diagnostics, 0, 15, "Expired Short")
table.cell(diagnostics, 1, 15, str.tostring(expiredShortCount))
table.cell(diagnostics, 0, 16, "Long Entries")
table.cell(diagnostics, 1, 16, str.tostring(longEntryCount))
table.cell(diagnostics, 0, 17, "Short Entries")
table.cell(diagnostics, 1, 17, str.tostring(shortEntryCount))
table.cell(diagnostics, 0, 18, "Trades Today")
table.cell(diagnostics, 1, 18, str.tostring(tradesToday) + " / " + str.tostring(maximumTradesPerDay))
table.cell(diagnostics, 0, 19, "Position")
table.cell(diagnostics, 1, 19, positionText)
2. Những khái niệm kỹ thuật cốt lõi trong CNPS75
2.1. Động cơ CCI Extreme & Re-entry (cciOversold / cciOverbought)
Khác với các hệ thống thông thường dùng ngưỡng ±100, CNPS75 thiết lập ngưỡng cực trị rộng hơn gấp đôi ở mức -200.0 và +200.0 dựa trên ta.cci(hlc3, 20). Điều này đảm bảo bot chỉ chú ý khi giá đã thực sự rơi vào trạng thái quá bán hoặc quá mua bất thường.
Bot không vào lệnh ngay khi CCI chạm ngưỡng, mà đợi sự kiện CCI Re-entry:
bullishCCIReentry = ta.crossover(cci, -200.0): CCI cắt từ dưới-200trở lên trên-200.bearishCCIReentry = ta.crossunder(cci, 200.0): CCI cắt từ trên+200trở xuống dưới+200.
2.2. Cơ chế Pending Setup & Xác nhận hành động giá (Price Confirmation)
Ngay khi xảy ra CCI Re-entry (chỉ xử lý một lần trên mỗi nến đã đóng qua barstate.isconfirmed và lastProcessedBar != bar_index), bot mở một Pending Setup (pendingLong hoặc pendingShort) và ghi nhận bar_index tại thời điểm đó.
Cửa sổ chờ xác nhận kéo dài tối đa confirmationBars = 3 thanh nến (bar_index - pendingBar <= confirmationBars). Trong thời gian này, setup sẽ tự động bị hủy nếu:
- Quá
confirmationBarsthanh nến mà chưa có xác nhận (expiredLongCount/expiredShortCounttăng lên). - Hoặc CCI lại rơi ngược vào vùng cực trị (
cci < -200đối với Long,cci > +200đối với Short). - Hoặc sang ngày giao dịch mới (
newTradingDay). - Hoặc xuất hiện tín hiệu Re-entry ngược chiều (tín hiệu mới sẽ ghi đè và tắt Pending Setup cũ).
Để hoàn tất xác nhận (longConfirmation / shortConfirmation), nến hiện tại cần thỏa mãn:
- Hướng nến (
requireCandleDirection, mặc định bật):close > opencho Long;close < opencho Short. - Phá vỡ đỉnh/đáy nến trước (
requirePreviousBreak, mặc định tắt):close > high[1]cho Long;close < low[1]cho Short. - Hướng dốc CCI (
requireCCIDirection, mặc định tắt):cci > cci[1]cho Long;cci < cci[1]cho Short.
2.3. Hệ thống 5 bộ lọc tùy chọn (RSI, ADX, Volume, EMA, Confirmed H1 EMA)
Khi tín hiệu cơ sở (longBase / shortBase) hình thành, CNPS75 kiểm tra thêm các bộ lọc phụ trợ (mặc định đều tắt, có thể bật tùy khẩu vị):
- RSI Filter (
useRSIFilter): Dùngta.rsi(close, 14). Long yêu cầursi <= 50.0(chưa quá cao), Short yêu cầursi >= 50.0(chưa quá thấp). - ADX Filter (
useADXFilter): Dùngta.dmi(14, 14)yêu cầuadx <= 30.0, tránh bắt đảo chiều khi thị trường đang có xu hướng một chiều quá mạnh. - Volume Spike (
requireVolumeSpike): Yêu cầuvolume >= ta.sma(volume, 20) * 1.20để đảm bảo có dòng tiền xác nhận lực đảo chiều. - EMA Trend Filter (
useEMAFilter): Yêu cầuclose > ta.ema(close, 20)cho Long vàclose < ta.ema(close, 20)cho Short. - Confirmed H1 EMA Bias (
useH1EMABias): Lấy dữ liệu cây nến H1 đã đóng gần nhất ([1]kết hợplookahead=barmerge.lookahead_ontrên khung"60"), yêu cầuh1Close > h1EMA(50)cho Long vàh1Close < h1EMA(50)cho Short (dành cho các khung thời gian dưới H1).
3. Nguyên lý hoạt động của CNPS75
Quy trình vận hành khép kín của CNPS75 trên mỗi thanh nến diễn ra theo 5 bước tuần tự:
- Khởi tạo phiên & cập nhật chỉ báo: Xác định múi giờ
Asia/Ho_Chi_Minh. Khi bước sang ngày giao dịch mới (newTradingDay), bộ đếmtradesTodayđược reset về0và toàn bộ Pending Setup cũ bị xóa. Các chỉ báoCCI,RSI,ADX,Volume SMA,EMAvàH1 EMAđược tính toán đồng thời. - Phát hiện cực trị & lưu Pending Setup: Tại thời điểm đóng nến (
barstate.isconfirmed), nếu CCI cắt lên trên-200(hoặc cắt xuống dưới+200), bot kích hoạtpendingLong(hoặcpendingShort) và lưu vị trí nến. - Xác nhận giá & lọc nhiễu: Trong vòng
0đến3nến kể từ lúc Re-entry, nếu nến thỏa mãn điều kiện Price Confirmation (longBase/shortBase) và vượt qua các bộ lọc đang bật (RSI,ADX,Volume,EMA,H1 EMA), tín hiệu thô (rawLongSignal/rawShortSignal) sẽ được tạo ra. - Kiểm tra điều kiện an toàn & gửi lệnh: Bot kiểm tra
canTrade(đang không có vị thế, chưa vượtmaximumTradesPerDay, hếtcooldownBars, trong khung giờ cho phép và trước giờ đóng phiên14:45), đồng thời loại bỏ trường hợp tín hiệu xung đột (ambiguousSignal) và chống vào trùng 2 lần trên 1 nến (notEnteredThisBar). Khi đạt đủ điều kiện,strategy.entrygửi lệnh và tiêu thụ ngay Pending Setup hiện tại. - Quản trị SL/TP & đóng cuối phiên: Ngay khi có vị thế (
positionLonghoặcpositionShort), bot đặt lệnh thoátstrategy.exitvới mức SL (5.0điểm) và TP (15.0điểm) tính từstrategy.position_avg_price. Nếu đến nến kết phiên14:45mà vẫn còn vị thế mở,strategy.close_allsẽ tự động tất toán toàn bộ.
4. Điều kiện vào lệnh Long và Short của CNPS75
4.1. Điều kiện vào lệnh Long
Một lệnh Long chỉ được khớp khi thỏa mãn đồng thời tất cả các điều kiện sau:
- Setup hợp lệ (
validLongSetup): Đã có sự kiệnta.crossover(cci, -200.0)và hiện tại đang trong phạm viconfirmationBars(≤ 3thanh nến), chưa bị hết hạn hay rơi lại dưới-200. - Xác nhận nến (
longConfirmation): Mặc định yêu cầu nến tăng (close > open). Nếu bật thêm tùy chọn thì phải đạtclose > high[1]và/hoặccci > cci[1]. - Bộ lọc tùy chọn (nếu bật):
rsi <= 50.0,adx <= 30.0,volume >= SMA(20) * 1.20,close > EMA(20), vàh1Close > h1EMA(50). - Quyền giao dịch:
tradeDirectionlà"Long"(mặc định) hoặc"Both", thỏa mãncanTrade,notEnteredThisBarvà không đồng thời xuất hiện tín hiệu Short (not ambiguousSignal).
4.2. Điều kiện vào lệnh Short
Một lệnh Short chỉ được khớp khi thỏa mãn đồng thời tất cả các điều kiện sau:
- Setup hợp lệ (
validShortSetup): Đã có sự kiệnta.crossunder(cci, 200.0)và hiện tại đang trong phạm viconfirmationBars(≤ 3thanh nến), chưa bị hết hạn hay tăng vượt lại trên+200. - Xác nhận nến (
shortConfirmation): Mặc định yêu cầu nến giảm (close < open). Nếu bật thêm tùy chọn thì phải đạtclose < low[1]và/hoặccci < cci[1]. - Bộ lọc tùy chọn (nếu bật):
rsi >= 50.0,adx <= 30.0,volume >= SMA(20) * 1.20,close < EMA(20), vàh1Close < h1EMA(50). - Quyền giao dịch:
tradeDirectionlà"Short"hoặc"Both"(lưu ý mặc định trong code đang để"Long", cần đổi sang"Both"hoặc"Short"nếu muốn đánh Short), thỏa mãncanTrade,notEnteredThisBarvànot ambiguousSignal.
4.3. Điều kiện kiểm soát giao dịch chung
Biến canTrade khóa chặt mọi tín hiệu nếu vi phạm bất kỳ quy tắc nào sau đây:
- Trạng thái phẳng (
positionFlat):strategy.position_size == 0(không nhồi lệnh,pyramiding=0). - Giới hạn lệnh ngày (
dailyTradeLimitOK):tradesToday < maximumTradesPerDay(mặc định tối đa2lệnh/ngày). - Thời gian nghỉ (
cooldownOK):bar_index - lastExitBar > cooldownBars(mặc định0nến). - Khung giờ giao dịch (
sessionOK): Nếu bậtUse Entry Session Filter?, thời gian mở nến phải>= 09:00và thời gian đóng nến phải<= 14:30. - Ngưỡng đóng phiên & đóng nến: Luôn yêu cầu
currentCloseMinute < 14:45(sessionEndTotal) vàbarstate.isconfirmed(chỉ xác nhận khi nến đã đóng).
5. Quản trị Stop Loss, Take Profit và Thoát lệnh
5.1. Cơ chế Stop Loss và bộ lọc Risk
CNPS75 sử dụng cơ chế cắt lỗ cố định theo điểm số (stopLossPoints = 5.0), tính trực tiếp từ giá khớp lệnh trung bình (strategy.position_avg_price):
- Lệnh Long:
activeLongSL = entryPrice - 5.0 - Lệnh Short:
activeShortSL = entryPrice + 5.0
Chiến lược không sử dụng khoảng đệm ATR hay giới hạn Min–Max Risk động, giúp nhà đầu tư kiểm soát chính xác mức rủi ro tối đa trên mỗi hợp đồng ngay từ trước khi vào lệnh.
5.2. Cơ chế Take Profit, Break Even và Trailing
Mục tiêu chốt lời được cố định theo takeProfitPoints = 15.0 (tương ứng tỷ lệ Risk:Reward = 1:3):
- Lệnh Long:
activeLongTP = entryPrice + 15.0 - Lệnh Short:
activeShortTP = entryPrice - 15.0
Trong phiên bản code CNPS75 này, bot không tích hợp dời hòa vốn (Break Even) hay Trailing Stop. Ngoài SL và TP, vị thế chỉ đóng sớm trong trường hợp chạm giờ tất toán cuối phiên 14:45 (finalSessionBar), kích hoạt strategy.close_all(immediately=true, comment="Session End").
5.3. Bảng tổng hợp cơ chế bảo vệ vị thế
| Cơ chế bảo vệ | Tham số mặc định | Điều kiện kích hoạt | Hành động thực thi |
|---|---|---|---|
| Stop Loss cố định | 5.0 điểm | Giá chạm entryPrice ∓ 5.0 | strategy.exit đóng lệnh, ghi nhãn SL Long / SL Short |
| Take Profit cố định | 15.0 điểm | Giá chạm entryPrice ± 15.0 | strategy.exit đóng lệnh, ghi nhãn TP Long / TP Short |
| Đóng vị thế cuối phiên | 14:45 (Asia/Ho_Chi_Minh) | Nến chuyển qua mốc 14:45 và còn vị thế | strategy.close_all(immediately=true), ghi nhãn Session End |
| Cooldown sau thoát lệnh | 0 thanh nến | Vừa đóng lệnh (positionJustClosed) | Chặn mở lệnh mới cho đến khi qua đủ cooldownBars nến |
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 (khuyến nghị khung thời gian dưới H1 như M5 hoặc M15 nếu có ý định bật bộ lọc H1 EMA).
- Nhấn vào tab Pine Editor ở phía dưới màn hình, xóa toàn bộ code mẫu mặc định.
- Quay lại Mục 1, sao chép toàn bộ mã nguồn Pine Script v6 của CNPS75 và dán vào Pine Editor.
- Nhấn Save để lưu script, sau đó nhấn Add to chart để đưa bot lên biểu đồ.
- Vào biểu tượng bánh răng (Settings) của chiến lược để điều chỉnh hướng giao dịch (
Trade Direction:Long,ShorthoặcBoth), bật các bộ lọc cần thiết hoặc bậtShow Diagnostics?nếu muốn theo dõi bảng thống kê.
Cách đọc bảng chẩn đoán (Diagnostics Table)
Khi bật Show Diagnostics?, một bảng gồm 20 dòng sẽ hiển thị ở góc trên bên phải biểu đồ (position.top_right):
- Dòng 0 – 3 (
CNPS75,CCI,RSI,ADX): Hiển thị khung thời gian hiện tại và giá trị thực tế của 3 chỉ báo cốt lõi tại nến cuối cùng. - Dòng 4 – 7 (
Bull/Bear Extremes,Bull/Bear Re-entries): Đếm tổng số lần CCI đi vào vùng cực trị (<-200/>200) và số lần cắt ngược trở lại (Re-entry). - Dòng 8 – 11 (
Long/Short Bases,Long/Short Signals): So sánh số tín hiệu đạt điều kiện giá cơ sở (Base) với số tín hiệu vượt qua toàn bộ bộ lọc (Signal), giúp bạn đánh giá bộ lọc có đang quá khắt khe hay không. - Dòng 12 – 15 (
Pending Long/Short,Expired Long/Short): Cho biết hiện tại có setup nào đang chờ nến xác nhận (YES/NO) và có bao nhiêu setup đã bị hết hạn do quáconfirmationBars. - Dòng 16 – 19 (
Long/Short Entries,Trades Today,Position): Thống kê tổng số lệnh đã khớp, số lệnh đã dùng trong ngày trên giới hạn tối đa (tradesToday / maximumTradesPerDay) và trạng thái vị thế hiện tại (LONG,SHORThoặ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, Email hoặc Webhook khi bot phát tín hiệu:
- Nhấn vào biểu tượng đồng hồ (Create Alert /
Alt + A) trên biểu đồ đã gắn CNPS75. - Ở mục Condition, chọn chiến lược
CNPS75 CCI EXTREME REVERSAL. - Ở ô Message, xóa nội dung mặc định và điền chính xác cú pháp:
{{strategy.order.alert_message}}. - Nếu muốn tắt cảnh báo khi chạm SL/TP và chỉ nhận cảnh báo vào lệnh / đóng phiên, bạn có thể tick vào
Disable SL / TP Alerts?trong phần cài đặt của bot.
Bảng thông điệp Alert của CNPS75
| Sự kiện kích hoạt | Biến / Tham số | Nội dung thông điệp (alert_message / alert_profit / alert_loss) |
|---|---|---|
| Vào lệnh Long | strategy.entry("Long") | 🟢 VÀO VỊ THẾ LONG (CNPS75 CCI Extreme Reversal)\n🎯 Giá vào: <close>\n🛑 Cắt lỗ (SL): <close - stopLossPoints>\n💰 Chốt lời (TP): <close + takeProfitPoints> |
| Vào lệnh Short | strategy.entry("Short") | 🔴 VÀO VỊ THẾ SHORT (CNPS75 CCI Extreme Reversal)\n🎯 Giá vào: <close>\n🛑 Cắt lỗ (SL): <close + stopLossPoints>\n💰 Chốt lời (TP): <close - takeProfitPoints> |
| Chốt lời Long / Short | strategy.exit (alert_profit) | 💰 CHỐT LỜI LONG (TP HIT)\n🎯 Giá chốt: <activeLongTP> (hoặc SHORT với <activeShortTP>) |
| Cắt lỗ Long / Short | strategy.exit (alert_loss) | 🛑 CẮT LỖ LONG (SL HIT)\n🎯 Giá cắt: <activeLongSL> (hoặc SHORT với <activeShortSL>) |
| Đóng vị thế hết phiên | strategy.close_all | ⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End)\n🎯 Giá đóng: <close> |
Kết luận
CNPS75 CCI Extreme Reversal là một hệ thống giao dịch đảo chiều bài bản, giải quyết hiệu quả nhược điểm “bắt đáy/đỉnh mù” nhờ kết hợp ngưỡng cực trị CCI ±200, cơ chế Pending Setup chờ nến xác nhận trong 3 thanh và tỷ lệ Risk:Reward 1:3 (SL 5 điểm / TP 15 điểm). Chiến lược phát huy hiệu quả tốt nhất trong các phiên thị trường dao động biên độ rộng hoặc có những nhịp kéo rướn quá đà rồi đảo chiều về cân bằng.
Bạn có thể tham khảo thêm các hệ thống giao dịch khác trên VN30F1M như Bot CNPS50 - Trend Analysis V2 và Bot CNPS49 - Daily Open để đa dạng hóa danh mục 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.





