Hướng Dẫn Sử Dụng Bot CNPS80 - Break of Structure Retest cho VN30F1M
TradingviewBot CNPS80 Break of Structure Retest tự động phát hiện phá vỡ cấu trúc N nến, lưu mức kháng cự/hỗ trợ bị phá vỡ và chờ nhịp retest từ chối giá kết hợp lọc xu hướng EMA, quản trị SL/TP cố định theo điểm và đóng lệnh cuối phiên trên VN30F1M.

Mục lục
Khi giao dịch hợp đồng tương lai VN30F1M, nhiều nhà giao dịch thường gặp phải bẫy phá vỡ giả (fakeout/bull trap/bear trap) khi vào lệnh đuổi ngay tại cây nến vừa vượt đỉnh hoặc thủng đáy. Điều này không chỉ khiến điểm vào bất lợi mà còn làm khoảng cách cắt lỗ bị nới rộng.
CNPS80 BREAK OF STRUCTURE RETEST (tên rút gọn: CNPS80 BOS RETEST) là chiến lược giao dịch tự động viết bằng Pine Script v6 trên TradingView, được thiết kế để giải quyết triệt để vấn đề trên. Thay vì vào lệnh ngay khi giá phá vỡ cấu trúc, bot sẽ lưu lại vùng giá vừa bị phá vỡ làm hỗ trợ/kháng cự mới và kiên nhẫn chờ một nhịp kiểm tra lại (retest) thành công trước khi kích hoạt vị thế. Toàn bộ logic đều sử dụng nến đã đóng (barstate.isconfirmed) và dữ liệu cấu trúc quá khứ, hoàn toàn không dùng thông tin pivot tương lai.
- Tách biệt pha BOS và pha vào lệnh: Chỉ ghi nhận sự kiện phá vỡ cấu trúc (BOS) để thiết lập vùng chờ, không vào lệnh đuổi tại nến phá vỡ.
- Kiểm soát Retest & Hủy Setup thông minh: Có biên độ dung sai (
retestToleranceATR), cửa sổ chờ tối đa (retestWindow) và cơ chế tự hủy setup khi giá phá ngược quá ngưỡng ATR (invalidationATR). - Bộ lọc xu hướng đa tầng: Kết hợp xu hướng EMA (độ dốc + vị trí giá) cùng các bộ lọc tùy chọn như ADX, Volume và xu hướng khung H1 (
H1 Bias). - Quản trị rủi ro kỷ luật: Cố định Stop Loss
5.0điểm và Take Profit15.0điểm (R:R 1:3), giới hạn tối đa2lệnh/ngày, cooldown sau thoát lệnh và tự động đóng toàn bộ vị thế trước giờ ATC (14:45).
1. CNPS80 Break of Structure Retest là gì?
CNPS80 Break of Structure Retest là hệ thống giao dịch theo cấu trúc thị trường kết hợp hồi quy (pullback/retest), được xây dựng trên 4 trụ cột kỹ thuật chính:
- Phát hiện phá vỡ cấu trúc (Market Structure & BOS): Tính toán đỉnh cấu trúc
structureHighvà đáy cấu trúcstructureLowtrong20nến trước đó (loại trừ nến hiện tạihigh[1],low[1]). Khi giá đóng cửa vượt qua vùng này kèm khoảng đệm ATR (0.10 * ATR), bot ghi nhận tín hiệubullBOShoặcbearBOS. - Động cơ chờ Retest & Xác nhận từ chối giá: Lưu
structureHighlàmlongRetestLevel(hoặcstructureLowlàmshortRetestLevel). Bot theo dõi trong tối đa8nến để tìm nhịp giá chạm lại vùng này với dung sai0.20 * ATR, sau đó xác nhận nến từ chối giá (đóng cửa quay lại phía trên hỗ trợ hoặc phía dưới kháng cự). - Bộ lọc xu hướng & Động lượng: Kiểm tra xu hướng thông qua đường EMA
50(cả độ dốcema > ema[5]lẫn vị trí giá so với EMA) và cho phép bật thêm bộ lọc ADX, Volume trung bình hoặc EMA khung H1. - Kiểm soát lệnh & Quản trị rủi ro: Giới hạn khung giờ vào lệnh từ
09:15đến14:15, tối đa2lệnh mỗi ngày, nghỉ ít nhất3nến sau khi đóng lệnh, bảo vệ bằng SL/TP cố định theo điểm và đóng toàn bộ vị thế lúc14:45.
Bảng thông số mặc định
| Nhóm thông số | Tên tham số trong code | Giá trị mặc định | Ý nghĩa |
|---|---|---|---|
| 01. Market Structure | structureLength | 20 | Số nến nhìn lại để xác định đỉnh/đáy cấu trúc |
atrLength | 14 | Chu kỳ tính chỉ báo ATR | |
useBreakBuffer | true | Yêu cầu khoảng đệm ATR khi phá vỡ cấu trúc | |
breakBufferATR | 0.10 | Hệ số ATR làm khoảng đệm phá vỡ (BOS Buffer) | |
requireFreshBOS | true | Chỉ nhận BOS mới (nến trước chưa vượt cấu trúc) | |
requireBOSCandle | true | Yêu cầu nến BOS đóng xanh (Long) hoặc đỏ (Short) | |
| 02. Retest | retestWindow | 8 | Số nến tối đa chờ đợi nhịp retest sau BOS |
retestToleranceATR | 0.20 | Biên độ dung sai quanh vùng retest (theo ATR) | |
invalidationATR | 0.50 | Ngưỡng ATR đóng cửa ngược chiều làm hủy setup | |
requireRejectionCandle | true | Yêu cầu nến retest là nến tăng (Long) / giảm (Short) | |
requireCloseProgress | true | Yêu cầu giá đóng cửa vượt qua close[1] | |
useWickFilter | false | Bật/tắt bộ lọc tỷ lệ râu nến từ chối | |
minimumWickRatio | 0.20 | Tỷ lệ râu nến tối thiểu trên tổng biên độ nến | |
requireFirstTouch | false | Chỉ vào lệnh ở lần chạm retest đầu tiên | |
| 03. EMA Trend | useEMAFilter | true | Bật bộ lọc xu hướng EMA |
emaLength | 50 | Chu kỳ đường EMA | |
emaSlopeBars | 5 | Số nến so sánh độ dốc EMA (ema vs ema[5]) | |
requirePriceEMA | true | Yêu cầu giá đóng cửa nằm trên/dưới EMA | |
| 04. Optional Filters | useADXFilter | false | Bật/tắt bộ lọc ADX tối thiểu |
diLength / adxSmoothing | 14 / 14 | Chu kỳ DI và làm mượt ADX | |
minimumADX | 18.0 | Ngưỡng ADX tối thiểu khi bật bộ lọc | |
useVolumeFilter | false | Bật/tắt bộ lọc khối lượng giao dịch | |
volumeLength / volumeFactor | 20 / 1.0 | Chu kỳ MA khối lượng và hệ số nhân tối thiểu | |
| 05. H1 Bias | useH1Bias | false | Bật/tắt bộ lọc xu hướng EMA khung 60 phút |
h1EMALength | 50 | Chu kỳ EMA trên khung H1 | |
| 06. Risk Management | stopLossPoints | 5.0 | Mức cắt lỗ cố định (điểm) |
takeProfitPoints | 15.0 | Mức chốt lời cố định (điểm) | |
useTimeExit | false | Bật/tắt thoát lệnh theo thời gian giữ tối đa | |
maximumHoldingBars | 20 | Số nến giữ lệnh tối đa nếu bật Time Exit | |
| 07. Trade Control | tradeDirection | "Long" | Hướng giao dịch ("Long", "Short", "Both") |
contracts | 3 | Tham số số hợp đồng khai báo trong input (lệnh mặc định dùng default_qty_value=1 của strategy) | |
maxTradesPerDay | 2 | Số lệnh tối đa được phép mở trong 1 ngày | |
cooldownBars | 3 | Số nến nghỉ bắt buộc sau khi đóng lệnh | |
| 08. Session | useSessionFilter | true | Bật/tắt bộ lọc khung giờ vào lệnh |
tz | "Asia/Ho_Chi_Minh" | Múi giờ Việt Nam | |
startHour : startMinute | 09:15 | Giờ bắt đầu cho phép vào lệnh | |
lastHour : lastMinute | 14:15 | Giờ cuối cùng cho phép vào lệnh mới | |
endHour : endMinute | 14:45 | Giờ cưỡng chế đóng toàn bộ vị thế trong ngày | |
| 09. Alerts & 10. Display | disableExitAlerts | false | Tắt cảnh báo SL/TP từ strategy.exit |
showDiagnostics | false | Bật/tắt bảng thống kê chẩn đoán góc trên bên phải |
Source Code CNPS80 Break of Structure Retest
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="CNPS80 BREAK OF STRUCTURE RETEST", shorttitle="CNPS80 BOS RETEST", 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=false, max_labels_count=300, max_lines_count=300, max_bars_back=5000)
// ============================================================================
// CNPS80 - BREAK OF STRUCTURE RETEST
//
// LONG:
// 1. Close breaks above previous N-bar high.
// 2. Save broken resistance as a support level.
// 3. Wait for a later candle to retest that level.
// 4. Price rejects support and closes above it.
// 5. Confirm EMA trend and optional filters.
// 6. Enter LONG.
//
// SHORT:
// 1. Close breaks below previous N-bar low.
// 2. Save broken support as resistance.
// 3. Wait for a later retest.
// 4. Price rejects resistance and closes below.
// 5. Confirm filters.
// 6. Enter SHORT.
//
// Uses confirmed bars and previous-bar structure.
// No future pivot information.
// ============================================================================
// ============================================================================
// 01. MARKET STRUCTURE
// ============================================================================
gStructure = "01. Market Structure"
structureLength = input.int(20, "Structure Lookback", minval=3, maxval=300, group=gStructure)
atrLength = input.int(14, "ATR Length", minval=1, group=gStructure)
useBreakBuffer = input.bool(true, "Require BOS Breakout Buffer", group=gStructure)
breakBufferATR = input.float(0.10, "BOS Buffer / ATR", minval=0.0, step=0.05, group=gStructure)
requireFreshBOS = input.bool(true, "Require Fresh BOS", group=gStructure)
requireBOSCandle = input.bool(true, "Require BOS Candle Direction", group=gStructure)
// ============================================================================
// 02. RETEST CONDITIONS
// ============================================================================
gRetest = "02. Retest"
retestWindow = input.int(8, "Maximum Retest Window", minval=1, maxval=50, group=gRetest)
retestToleranceATR = input.float(0.20, "Retest Tolerance / ATR", minval=0.0, step=0.05, group=gRetest)
invalidationATR = input.float(0.50, "Setup Invalidation / ATR", minval=0.05, step=0.05, group=gRetest)
requireRejectionCandle = input.bool(true, "Require Rejection Candle", group=gRetest)
requireCloseProgress = input.bool(true, "Require Close Beyond Previous Close", group=gRetest)
useWickFilter = input.bool(false, "Require Rejection Wick", group=gRetest)
minimumWickRatio = input.float(0.20, "Minimum Wick / Candle Range", minval=0.0, maxval=1.0, step=0.05, group=gRetest)
requireFirstTouch = input.bool(false, "Require First Retest Only", group=gRetest)
// ============================================================================
// 03. EMA TREND
// ============================================================================
gTrend = "03. EMA Trend"
useEMAFilter = input.bool(true, "Use EMA Trend Filter", group=gTrend)
emaLength = input.int(50, "EMA Length", minval=5, group=gTrend)
emaSlopeBars = input.int(5, "EMA Slope Lookback", minval=1, maxval=50, group=gTrend)
requirePriceEMA = input.bool(true, "Require Price Above/Below EMA", group=gTrend)
// ============================================================================
// 04. OPTIONAL FILTERS
// ============================================================================
gFilters = "04. Optional Filters"
useADXFilter = input.bool(false, "Use Minimum ADX", group=gFilters)
diLength = input.int(14, "DI Length", minval=2, group=gFilters)
adxSmoothing = input.int(14, "ADX Smoothing", minval=2, group=gFilters)
minimumADX = input.float(18.0, "Minimum ADX", minval=1.0, step=1.0, group=gFilters)
useVolumeFilter = input.bool(false, "Use Volume Filter", group=gFilters)
volumeLength = input.int(20, "Volume MA Length", minval=2, group=gFilters)
volumeFactor = input.float(1.0, "Volume / Average Volume", minval=0.1, step=0.1, group=gFilters)
// ============================================================================
// 05. CONFIRMED H1 BIAS
// ============================================================================
gH1 = "05. H1 Bias"
useH1Bias = input.bool(false, "Use Confirmed H1 EMA Bias", group=gH1)
h1EMALength = input.int(50, "H1 EMA Length", minval=1, group=gH1)
// ============================================================================
// 06. RISK MANAGEMENT
// ============================================================================
gRisk = "06. Risk Management"
stopLossPoints = input.float(5.0, "Stop Loss (Points)", minval=0.1, step=0.5, group=gRisk)
takeProfitPoints = input.float(15.0, "Take Profit (Points)", minval=0.1, step=0.5, group=gRisk)
useTimeExit = input.bool(false, "Use Time Exit", group=gRisk)
maximumHoldingBars = input.int(20, "Maximum Holding Bars", minval=1, maxval=300, group=gRisk)
// ============================================================================
// 07. TRADE CONTROL
// ============================================================================
gTrade = "07. Trade Control"
tradeDirection = input.string("Long", "Trade Direction", options=["Long", "Short", "Both"], group=gTrade)
contracts = input.int(3, "Contracts", minval=1, maxval=100, group=gTrade)
maxTradesPerDay = input.int(2, "Maximum Trades Per Day", minval=1, maxval=20, group=gTrade)
cooldownBars = input.int(3, "Cooldown After Exit (Bars)", minval=0, maxval=100, group=gTrade)
bool allowLong = (tradeDirection == "Long" or tradeDirection == "Both")
bool allowShort = (tradeDirection == "Short" or tradeDirection == "Both")
// ============================================================================
// 08. SESSION
// ============================================================================
gSession = "08. Session"
useSessionFilter = input.bool(true, "Use Entry Session Filter", group=gSession)
tz = input.string("Asia/Ho_Chi_Minh", "Timezone", group=gSession)
startHour = input.int(9, "Entry Start Hour", minval=0, maxval=23, group=gSession)
startMinute = input.int(15, "Entry Start Minute", minval=0, maxval=59, group=gSession)
lastHour = input.int(14, "Last Entry Hour", minval=0, maxval=23, group=gSession)
lastMinute = input.int(15, "Last Entry Minute", minval=0, maxval=59, group=gSession)
endHour = input.int(14, "Force Close Hour", minval=0, maxval=23, group=gSession)
endMinute = input.int(45, "Force Close Minute", minval=0, maxval=59, group=gSession)
// ============================================================================
// 09. ALERTS
// ============================================================================
gAlerts = "09. Alerts"
disableExitAlerts = input.bool(false, "Disable SL/TP Alerts", group=gAlerts)
// ============================================================================
// 10. DISPLAY
// ============================================================================
gDisplay = "10. Display"
showStructure = input.bool(true, "Show Structure Levels", group=gDisplay)
showEMA = input.bool(true, "Show EMA", group=gDisplay)
showBOSMarkers = input.bool(true, "Show BOS Markers", group=gDisplay)
showRetestLevels = input.bool(true, "Show Active Retest Levels", group=gDisplay)
showEntryMarkers = input.bool(true, "Show Entry Markers", group=gDisplay)
showSLTP = input.bool(true, "Show Active SL/TP", group=gDisplay)
showDiagnostics = input.bool(false, "Show Diagnostics", group=gDisplay)
// ============================================================================
// 11. TIME ENGINE
// ============================================================================
int openMinutes = (hour(time, tz) * 60 + minute(time, tz))
int closeMinutes = (hour(time_close, tz) * 60 + minute(time_close, tz))
int sessionStart = (startHour * 60 + startMinute)
int sessionLast = (lastHour * 60 + lastMinute)
int sessionEnd = (endHour * 60 + endMinute)
bool sessionOK = (not useSessionFilter or (openMinutes >= sessionStart and closeMinutes <= sessionLast))
bool beforeForceClose = (closeMinutes < sessionEnd)
bool forceCloseBar = (openMinutes < sessionEnd and closeMinutes >= sessionEnd)
// ============================================================================
// 12. TRADING DAY
// ============================================================================
int dayKey = (year(time, tz) * 10000 + month(time, tz) * 100 + dayofmonth(time, tz))
bool newDay = (na(dayKey[1]) or dayKey != dayKey[1])
var int tradesToday = 0
if newDay
tradesToday := 0
// ============================================================================
// 13. STRUCTURE LEVELS
// ============================================================================
//
// Excludes current candle.
//
// A close above previous high is bullish BOS.
// A close below previous low is bearish BOS.
//
// ============================================================================
float structureHigh = ta.highest(high[1], structureLength)
float structureLow = ta.lowest(low[1], structureLength)
float atr = ta.atr(atrLength)
bool structureReady = (not na(structureHigh) and not na(structureLow) and not na(atr) and atr > 0)
// ============================================================================
// 14. BOS BREAKOUT CONDITIONS
// ============================================================================
float longBreakBuffer = (useBreakBuffer ? atr * breakBufferATR : 0.0)
float shortBreakBuffer = (useBreakBuffer ? atr * breakBufferATR : 0.0)
bool bullishBreakout = (structureReady and close > structureHigh + longBreakBuffer)
bool bearishBreakout = (structureReady and close < structureLow - shortBreakBuffer)
bool freshBullishBOS = (not requireFreshBOS or close[1] <= structureHigh[1])
bool freshBearishBOS = (not requireFreshBOS or close[1] >= structureLow[1])
bool bullishBOSCandle = (not requireBOSCandle or close > open)
bool bearishBOSCandle = (not requireBOSCandle or close < open)
bool bullBOS = (bullishBreakout and freshBullishBOS and bullishBOSCandle)
bool bearBOS = (bearishBreakout and freshBearishBOS and bearishBOSCandle)
// ============================================================================
// 15. EMA FILTER
// ============================================================================
float ema = ta.ema(close, emaLength)
bool emaUp = (not na(ema[emaSlopeBars]) and ema > ema[emaSlopeBars])
bool emaDown = (not na(ema[emaSlopeBars]) and ema < ema[emaSlopeBars])
bool longTrendOK = (not useEMAFilter or (emaUp and (not requirePriceEMA or close > ema)))
bool shortTrendOK = (not useEMAFilter or (emaDown and (not requirePriceEMA or close < ema)))
// ============================================================================
// 16. ADX
// ============================================================================
[diPlus, diMinus, adx] = ta.dmi(diLength, adxSmoothing)
bool adxOK = (not useADXFilter or (not na(adx) and adx >= minimumADX))
// ============================================================================
// 17. VOLUME
// ============================================================================
float avgVolume = ta.sma(volume, volumeLength)
bool volumeOK = (not useVolumeFilter or (not na(volume) and not na(avgVolume) and volume >= avgVolume * volumeFactor))
// ============================================================================
// 18. CONFIRMED H1 EMA
// ============================================================================
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 validH1Chart = (timeframe.isintraday and timeframe.in_seconds() < 3600)
bool longH1OK = (not useH1Bias or (validH1Chart and not na(h1EMA) and not na(h1Close) and h1Close > h1EMA))
bool shortH1OK = (not useH1Bias or (validH1Chart and not na(h1EMA) and not na(h1Close) and h1Close < h1EMA))
// ============================================================================
// 19. CANDLE ANATOMY
// ============================================================================
float candleRange = (high - low)
float lowerWick = (math.min(open, close) - low)
float upperWick = (high - math.max(open, close))
float lowerWickRatio = (candleRange > 0 ? lowerWick / candleRange : 0.0)
float upperWickRatio = (candleRange > 0 ? upperWick / candleRange : 0.0)
bool bullishCandle = close > open
bool bearishCandle = close < open
// ============================================================================
// 20. POSITION / COOLDOWN
// ============================================================================
bool flat = (strategy.position_size == 0)
bool inLong = (strategy.position_size > 0)
bool inShort = (strategy.position_size < 0)
var int lastExitBar = na
bool closedTradeNow = (strategy.closedtrades > nz(strategy.closedtrades[1], 0))
if closedTradeNow
lastExitBar := bar_index
bool cooldownOK = (na(lastExitBar) or bar_index - lastExitBar > cooldownBars)
// ============================================================================
// 21. BOS STATE
// ============================================================================
//
// Store each broken structure level.
// The original BOS is not an entry.
//
// Wait for a later retest.
//
// ============================================================================
var bool pendingLong = false
var bool pendingShort = false
var int longBOSBar = na
var int shortBOSBar = na
var float longRetestLevel = na
var float shortRetestLevel = na
var bool longTouched = false
var bool shortTouched = false
var int bullBOSCount = 0
var int bearBOSCount = 0
var int longExpiredCount = 0
var int shortExpiredCount = 0
var int longRetestCount = 0
var int shortRetestCount = 0
// Retest touch on current bar.
// Use level saved from a previous confirmed BOS.
float tolerance = (not na(atr) ? atr * retestToleranceATR : 0.0)
bool longRetestTouch = (pendingLong and not na(longBOSBar) and bar_index > longBOSBar and not na(longRetestLevel) and low <= longRetestLevel + tolerance and high >= longRetestLevel - tolerance)
bool shortRetestTouch = (pendingShort and not na(shortBOSBar) and bar_index > shortBOSBar and not na(shortRetestLevel) and high >= shortRetestLevel - tolerance and low <= shortRetestLevel + tolerance)
// ============================================================================
// 22. INVALIDATION
// ============================================================================
bool longInvalid = (pendingLong and not na(longRetestLevel) and close < longRetestLevel - atr * invalidationATR)
bool shortInvalid = (pendingShort and not na(shortRetestLevel) and close > shortRetestLevel + atr * invalidationATR)
bool longExpired = (pendingLong and not na(longBOSBar) and bar_index - longBOSBar > retestWindow)
bool shortExpired = (pendingShort and not na(shortBOSBar) and bar_index - shortBOSBar > retestWindow)
// ============================================================================
// 23. RETEST CONFIRMATION
// ============================================================================
bool longRejectionOK = (not requireRejectionCandle or bullishCandle)
bool shortRejectionOK = (not requireRejectionCandle or bearishCandle)
bool longProgressOK = (not requireCloseProgress or close > close[1])
bool shortProgressOK = (not requireCloseProgress or close < close[1])
bool longWickOK = (not useWickFilter or lowerWickRatio >= minimumWickRatio)
bool shortWickOK = (not useWickFilter or upperWickRatio >= minimumWickRatio)
bool longFirstTouchOK = (not requireFirstTouch or not longTouched)
bool shortFirstTouchOK = (not requireFirstTouch or not shortTouched)
bool longRetestBase = (longRetestTouch and not longInvalid and not longExpired and close > longRetestLevel and longRejectionOK and longProgressOK and longWickOK and longFirstTouchOK)
bool shortRetestBase = (shortRetestTouch and not shortInvalid and not shortExpired and close < shortRetestLevel and shortRejectionOK and shortProgressOK and shortWickOK and shortFirstTouchOK)
// ============================================================================
// 24. FILTERED SIGNALS
// ============================================================================
bool rawLong = (longRetestBase and longTrendOK and adxOK and volumeOK and longH1OK)
bool rawShort = (shortRetestBase and shortTrendOK and adxOK and volumeOK and shortH1OK)
// ============================================================================
// 25. ENTRY GATES
// ============================================================================
var int lastEntryBar = na
bool freshEntryBar = (na(lastEntryBar) or lastEntryBar != bar_index)
bool canTrade = (barstate.isconfirmed and flat and strategy.opentrades == 0 and tradesToday < maxTradesPerDay and cooldownOK and sessionOK and beforeForceClose and freshEntryBar)
bool ambiguous = rawLong and rawShort
bool enterLong = (canTrade and allowLong and rawLong and not ambiguous)
bool enterShort = (canTrade and allowShort and rawShort and not ambiguous)
// ============================================================================
// 26. DIAGNOSTIC COUNTERS
// ============================================================================
var int longBaseCount = 0
var int shortBaseCount = 0
var int filteredLongCount = 0
var int filteredShortCount = 0
var int longEntryCount = 0
var int shortEntryCount = 0
// ============================================================================
// 27. SL / TP IN TICKS
// ============================================================================
int slTicks = math.max(1, int(math.round(stopLossPoints / syminfo.mintick)))
int tpTicks = math.max(1, int(math.round(takeProfitPoints / syminfo.mintick)))
float effectiveSL = (slTicks * syminfo.mintick)
float effectiveTP = (tpTicks * syminfo.mintick)
// ============================================================================
// 28. ENTRIES
// ============================================================================
if enterLong
strategy.entry("Long", strategy.long, comment="BOS Support Retest", alert_message="🟢 VÀO VỊ THẾ LONG (CNPS80 BOS Retest)\\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\\n🛑 Cắt lỗ (SL): " + str.tostring(close - effectiveSL, format.mintick) + "\\n💰 Chốt lời (TP): " + str.tostring(close + effectiveTP, format.mintick))
tradesToday += 1
longEntryCount += 1
lastEntryBar := bar_index
if enterShort
strategy.entry("Short", strategy.short, comment="BOS Resistance Retest", alert_message="🔴 VÀO VỊ THẾ SHORT (CNPS80 BOS Retest)\\n🎯 Giá vào: " + str.tostring(close, format.mintick) + "\\n🛑 Cắt lỗ (SL): " + str.tostring(close + effectiveSL, format.mintick) + "\\n💰 Chốt lời (TP): " + str.tostring(close - effectiveTP, format.mintick))
tradesToday += 1
shortEntryCount += 1
lastEntryBar := bar_index
// ============================================================================
// 29. UPDATE BOS STATE
// ============================================================================
//
// Process state after evaluating entry signals.
// A new BOS on this bar cannot be retested
// on the same bar.
//
// ============================================================================
if barstate.isconfirmed
if newDay
pendingLong := false
pendingShort := false
longBOSBar := na
shortBOSBar := na
longRetestLevel := na
shortRetestLevel := na
longTouched := false
shortTouched := false
else
if longRetestBase
longBaseCount += 1
if shortRetestBase
shortBaseCount += 1
if rawLong
filteredLongCount += 1
if rawShort
filteredShortCount += 1
if longRetestTouch
longRetestCount += 1
if shortRetestTouch
shortRetestCount += 1
// An entry consumes the pending setup.
if enterLong or longInvalid or longExpired
if longExpired
longExpiredCount += 1
pendingLong := false
longBOSBar := na
longRetestLevel := na
longTouched := false
else if longRetestTouch
longTouched := true
if enterShort or shortInvalid or shortExpired
if shortExpired
shortExpiredCount += 1
pendingShort := false
shortBOSBar := na
shortRetestLevel := na
shortTouched := false
else if shortRetestTouch
shortTouched := true
// Register fresh BOS.
// Do not overwrite an active same-side setup.
// Setups are reset at the trading-day boundary.
if bullBOS
bullBOSCount += 1
if not pendingLong and
not pendingShort and
flat and
beforeForceClose
pendingLong := true
longBOSBar := bar_index
longRetestLevel := structureHigh
longTouched := false
if bearBOS
bearBOSCount += 1
if not pendingShort and
not pendingLong and
flat and
beforeForceClose
pendingShort := true
shortBOSBar := bar_index
shortRetestLevel := structureLow
shortTouched := false
// ============================================================================
// 30. LONG EXIT
// ============================================================================
strategy.exit("Long Exit", from_entry="Long", profit=tpTicks, loss=slTicks, comment_profit="TP Long", comment_loss="SL Long", alert_profit="💰 CHỐT LỜI LONG (TP HIT)\\n🎯 Giá chốt: " + str.tostring(strategy.position_avg_price + effectiveTP, format.mintick), alert_loss="🛑 CẮT LỖ LONG (SL HIT)\\n🎯 Giá cắt: " + str.tostring(strategy.position_avg_price - effectiveSL, format.mintick), disable_alert=disableExitAlerts)
// ============================================================================
// 31. SHORT EXIT
// ============================================================================
strategy.exit("Short Exit", from_entry="Short", profit=tpTicks, loss=slTicks, comment_profit="TP Short", comment_loss="SL Short", alert_profit="💰 CHỐT LỜI SHORT (TP HIT)\\n🎯 Giá chốt: " + str.tostring(strategy.position_avg_price - effectiveTP, format.mintick), alert_loss="🛑 CẮT LỖ SHORT (SL HIT)\\n🎯 Giá cắt: " + str.tostring(strategy.position_avg_price + effectiveSL, format.mintick), disable_alert=disableExitAlerts)
// ============================================================================
// 32. OPTIONAL TIME EXIT
// ============================================================================
int barsHeld = (strategy.opentrades > 0 ? bar_index - strategy.opentrades.entry_bar_index(0) : 0)
bool timeExit = (useTimeExit and strategy.position_size != 0 and barsHeld >= maximumHoldingBars and barstate.isconfirmed)
if timeExit and not forceCloseBar
strategy.close_all(immediately=true, comment="Time Exit", alert_message="⏱️ ĐÓNG VỊ THẾ HẾT THỜI GIAN GIỮ (Time Exit)\\n🎯 Giá đóng: " + str.tostring(close, format.mintick))
// ============================================================================
// 33. FORCE CLOSE
// ============================================================================
if forceCloseBar 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))
// ============================================================================
// 34. STRUCTURE PLOTS
// ============================================================================
plot(showStructure ? structureHigh : na, title="Structure High", color=color.new(color.red, 30), linewidth=1, style=plot.style_stepline)
plot(showStructure ? structureLow : na, title="Structure Low", color=color.new(color.green, 30), linewidth=1, style=plot.style_stepline)
plot(showEMA ? ema : na, title="EMA Trend", color=color.orange, linewidth=2)
// ============================================================================
// 35. ACTIVE RETEST LEVELS
// ============================================================================
plot(showRetestLevels and pendingLong ? longRetestLevel : na, title="Bullish Retest Level", color=color.aqua, linewidth=2, style=plot.style_linebr)
plot(showRetestLevels and pendingShort ? shortRetestLevel : na, title="Bearish Retest Level", color=color.fuchsia, linewidth=2, style=plot.style_linebr)
// ============================================================================
// 36. BOS MARKERS
// ============================================================================
plotshape(showBOSMarkers and bullBOS, title="Bullish BOS", style=shape.circle, location=location.belowbar, color=color.aqua, size=size.tiny, text="BOS")
plotshape(showBOSMarkers and bearBOS, title="Bearish BOS", style=shape.circle, location=location.abovebar, color=color.fuchsia, size=size.tiny, text="BOS")
// ============================================================================
// 37. ENTRY MARKERS
// ============================================================================
plotshape(showEntryMarkers and enterLong, title="CNPS80 LONG", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, text="LONG", textcolor=color.white)
plotshape(showEntryMarkers and enterShort, title="CNPS80 SHORT", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small, text="SHORT", textcolor=color.white)
// ============================================================================
// 38. ACTIVE SL / TP
// ============================================================================
float longSL = (inLong ? strategy.position_avg_price - effectiveSL : na)
float longTP = (inLong ? strategy.position_avg_price + effectiveTP : na)
float shortSL = (inShort ? strategy.position_avg_price + effectiveSL : na)
float shortTP = (inShort ? strategy.position_avg_price - effectiveTP : na)
plot(showSLTP ? longSL : na, title="Long SL", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showSLTP ? longTP : na, title="Long TP", color=color.green, linewidth=2, style=plot.style_linebr)
plot(showSLTP ? shortSL : na, title="Short SL", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showSLTP ? shortTP : na, title="Short TP", color=color.green, linewidth=2, style=plot.style_linebr)
// ============================================================================
// 39. DATA WINDOW
// ============================================================================
plot(atr, title="ATR", color=color.gray, display=display.data_window)
plot(adx, title="ADX", color=color.purple, display=display.data_window)
plot(longRetestLevel, title="Saved Long BOS Level", color=color.aqua, display=display.data_window)
plot(shortRetestLevel, title="Saved Short BOS Level", color=color.fuchsia, display=display.data_window)
// ============================================================================
// 40. DIAGNOSTICS
// ============================================================================
var table diagnostics = table.new(position.top_right, 2, 18, border_width=1)
if showDiagnostics and barstate.islast
table.cell(diagnostics, 0, 0, "CNPS80 BOS")
table.cell(diagnostics, 1, 0, timeframe.period)
table.cell(diagnostics, 0, 1, "BOS High")
table.cell(diagnostics, 1, 1, str.tostring(structureHigh, format.mintick))
table.cell(diagnostics, 0, 2, "BOS Low")
table.cell(diagnostics, 1, 2, str.tostring(structureLow, format.mintick))
table.cell(diagnostics, 0, 3, "EMA Up")
table.cell(diagnostics, 1, 3, emaUp ? "YES" : "NO")
table.cell(diagnostics, 0, 4, "EMA Down")
table.cell(diagnostics, 1, 4, emaDown ? "YES" : "NO")
table.cell(diagnostics, 0, 5, "Bull BOS")
table.cell(diagnostics, 1, 5, str.tostring(bullBOSCount))
table.cell(diagnostics, 0, 6, "Bear BOS")
table.cell(diagnostics, 1, 6, str.tostring(bearBOSCount))
table.cell(diagnostics, 0, 7, "Long Retests")
table.cell(diagnostics, 1, 7, str.tostring(longRetestCount))
table.cell(diagnostics, 0, 8, "Short Retests")
table.cell(diagnostics, 1, 8, str.tostring(shortRetestCount))
table.cell(diagnostics, 0, 9, "Long Bases")
table.cell(diagnostics, 1, 9, str.tostring(longBaseCount))
table.cell(diagnostics, 0, 10, "Short Bases")
table.cell(diagnostics, 1, 10, str.tostring(shortBaseCount))
table.cell(diagnostics, 0, 11, "Filtered Long")
table.cell(diagnostics, 1, 11, str.tostring(filteredLongCount))
table.cell(diagnostics, 0, 12, "Filtered Short")
table.cell(diagnostics, 1, 12, str.tostring(filteredShortCount))
table.cell(diagnostics, 0, 13, "Pending Long")
table.cell(diagnostics, 1, 13, pendingLong ? "YES" : "NO")
table.cell(diagnostics, 0, 14, "Pending Short")
table.cell(diagnostics, 1, 14, pendingShort ? "YES" : "NO")
table.cell(diagnostics, 0, 15, "Long Entries")
table.cell(diagnostics, 1, 15, str.tostring(longEntryCount))
table.cell(diagnostics, 0, 16, "Short Entries")
table.cell(diagnostics, 1, 16, str.tostring(shortEntryCount))
table.cell(diagnostics, 0, 17, "Trades Today")
table.cell(diagnostics, 1, 17, str.tostring(tradesToday) + "/" + str.tostring(maxTradesPerDay))
2. Những khái niệm kỹ thuật cốt lõi trong CNPS80
2.1. Cấu trúc thị trường (Structure High/Low) và Break of Structure (BOS)
Bot xác định vùng cấu trúc dựa trên structureLength (20) nến liền trước, loại trừ hoàn toàn nến hiện tại để tránh hiện tượng nhìn trước dữ liệu:
structureHigh = ta.highest(high[1], 20)(kháng cự gần nhất)structureLow = ta.lowest(low[1], 20)(hỗ trợ gần nhất)
Một tín hiệu Break of Structure (BOS) hợp lệ phải thỏa mãn đồng thời 3 yếu tố:
- Phá vỡ kèm khoảng đệm ATR:
close > structureHigh + atr * 0.10(đối với Bullish BOS) hoặcclose < structureLow - atr * 0.10(đối với Bearish BOS). - BOS mới (
requireFreshBOS): Nến trước đó chưa phá vỡ cấu trúc (close[1] <= structureHigh[1]cho Long;close[1] >= structureLow[1]cho Short). - Hướng nến đồng thuận (
requireBOSCandle): Nến phá vỡ phải là nến tăng (close > open) chobullBOSvà nến giảm (close < open) chobearBOS.
2.2. Cơ chế Retest, Tolerance và Invalidation theo ATR
Ngay khi BOS xuất hiện, bot không vào lệnh ngay mà lưu lại longRetestLevel = structureHigh (hoặc shortRetestLevel = structureLow). Ở các nến kế tiếp (trong giới hạn retestWindow = 8 nến):
- Vùng chạm Retest (
tolerance = atr * 0.20): Nến được coi là chạm vùng hỗ trợ Long khilow <= longRetestLevel + tolerancevàhigh >= longRetestLevel - tolerance(tương tự với Short). - Xác nhận từ chối giá: Giá phải đóng cửa phía trên
longRetestLevel(với Long) hoặc dướishortRetestLevel(với Short), đồng thời thỏa mãn nến tăng/giảm (requireRejectionCandle), giá đóng cửa tiến triển so với nến trước (close > close[1]cho Long;close < close[1]cho Short), và tùy chọn râu nến từ chối (lowerWick / candleRange >= 0.20hoặcupperWick / candleRange >= 0.20). - Hủy Setup (
Invalidation&Expired): Setup chờ sẽ bị xóa ngay nếu quá8nến chưa vào lệnh (bar_index - BOSBar > 8) hoặc giá đóng cửa xuyên ngược qua vùng retest quá0.50 * ATR(close < longRetestLevel - atr * 0.50với Long;close > shortRetestLevel + atr * 0.50với Short).
2.3. Bộ lọc xu hướng EMA, H1 Bias, ADX và Volume
- EMA Trend Filter (bật mặc định): Sử dụng
EMA 50và kiểm tra độ dốc so với5nến trước (ema > ema[5]cho Long,ema < ema[5]cho Short), kết hợp điều kiện giá đóng cửa nằm cùng phía với EMA (close > emahoặcclose < ema). - Confirmed H1 Bias (tắt mặc định): Khi bật
useH1Bias, bot dùngrequest.security(..., "60", ...)lấy giá trịEMA 50và giá đóng cửa nến H1 đã hoàn tất ([1]) với điều kiện biểu đồ đang chạy ở khung intraday nhỏ hơn 1 giờ (timeframe.in_seconds() < 3600). - ADX & Volume Filter (tắt mặc định): Có thể kích hoạt để yêu cầu thị trường có xu hướng (
adx >= 18.0) và thanh khoản xác nhận (volume >= SMA(volume, 20) * 1.0).
3. Nguyên lý hoạt động của CNPS80
Quy trình vận hành của CNPS80 trên mỗi cây nến đã đóng (barstate.isconfirmed) diễn ra tuần tự theo 5 bước:
- Khởi tạo phiên & Tính chỉ báo: Khi sang ngày mới (
newDay), bot reset biến đếmtradesToday := 0và xóa toàn bộ trạng thái chờpendingLong/pendingShorttừ ngày cũ. Song song đó, tínhstructureHigh,structureLow,atr(14),ema(50),adxvàavgVolume. - Đánh giá nhịp Retest trên setup đang chờ: Nếu đang có
pendingLonghoặcpendingShorttừ nến BOS trước đó (bar_index > BOSBar), bot kiểm tra xem nến hiện tại có chạm vùng retest (longRetestTouch/shortRetestTouch), có bị vô hiệu hóa (Invalid) hay quá hạn (Expired) không. - Lọc tín hiệu & Mở vị thế: Nếu nến retest từ chối giá thành công (
longRetestBase/shortRetestBase), thỏa mãn các bộ lọc xu hướng (rawLong/rawShort) và vượt qua toàn bộ cổng kiểm soát (canTrade, hướng giao dịch hợp lệ, không đồng thời xảy ra cả Long và Short), bot gửi lệnhstrategy.entryvà tăngtradesToday. - Cập nhật & Đăng ký BOS mới: Sau khi đánh giá tín hiệu vào lệnh, nếu lệnh đã vào hoặc setup bị hủy/hết hạn, trạng thái
pendingđược xóa. Nếu xuất hiệnbullBOShoặcbearBOSmới trong khi không có setup nào đang chờ, tài khoản đangflatvà còn trước giờ đóng phiên (beforeForceClose), bot lưu vùng retest mới cho các nến sau. - Quản trị & Thoát lệnh: Khi đang giữ vị thế, bot đặt sẵn lệnh chờ SL/TP qua
strategy.exit, kiểm tra thoát theo thời gian giữ (useTimeExit) nếu được bật, và tự động đóng toàn bộ vị thế tại nến chạm mốc14:45(forceCloseBar).
4. Điều kiện vào lệnh Long và Short của CNPS80
4.1. Điều kiện vào lệnh Long
Bot mở vị thế Long khi tất cả các điều kiện sau cùng thỏa mãn trên nến đã đóng:
tradeDirectioncho phép Long ("Long"hoặc"Both").- Đang có setup chờ
pendingLongtừ mộtbullBOSở nến trước (bar_index > longBOSBar), trong đólongRetestLevel = structureHigh. - Nến hiện tại chạm vùng retest:
low <= longRetestLevel + tolerancevàhigh >= longRetestLevel - tolerance(vớitolerance = atr * 0.20). - Setup chưa bị hủy (
close >= longRetestLevel - atr * 0.50) và chưa quá hạn (bar_index - longBOSBar <= 8). - Giá đóng cửa giữ trên vùng hỗ trợ:
close > longRetestLevel. - Nến tăng xác nhận từ chối giá:
close > open(khi bậtrequireRejectionCandle) vàclose > close[1](khi bậtrequireCloseProgress). - Nếu bật bộ lọc râu nến (
useWickFilter):lowerWick / candleRange >= 0.20. Nếu bậtrequireFirstTouch: đây phải là lần chạm retest đầu tiên (not longTouched). - Bộ lọc xu hướng EMA đạt (
ema > ema[5]vàclose > ema), cùng các bộ lọc tùy chọn (ADX, Volume, H1 EMA) nếu được bật. - Không xảy ra tín hiệu mâu thuẫn (
not (rawLong and rawShort)) vàcanTradehợp lệ.
4.2. Điều kiện vào lệnh Short
Bot mở vị thế Short khi tất cả các điều kiện sau cùng thỏa mãn trên nến đã đóng:
tradeDirectioncho phép Short ("Short"hoặc"Both"). Lưu ý: mặc định code đang đểtradeDirection = "Long", người dùng cần chuyển sang"Short"hoặc"Both"trong Settings nếu muốn giao dịch chiều Short.- Đang có setup chờ
pendingShorttừ mộtbearBOSở nến trước (bar_index > shortBOSBar), trong đóshortRetestLevel = structureLow. - Nến hiện tại chạm vùng retest:
high >= shortRetestLevel - tolerancevàlow <= shortRetestLevel + tolerance. - Setup chưa bị hủy (
close <= shortRetestLevel + atr * 0.50) và chưa quá hạn (bar_index - shortBOSBar <= 8). - Giá đóng cửa giữ dưới vùng kháng cự:
close < shortRetestLevel. - Nến giảm xác nhận từ chối giá:
close < open(khi bậtrequireRejectionCandle) vàclose < close[1](khi bậtrequireCloseProgress). - Nếu bật
useWickFilter:upperWick / candleRange >= 0.20. Nếu bậtrequireFirstTouch:not shortTouched. - Bộ lọc xu hướng EMA đạt (
ema < ema[5]vàclose < ema), cùng các bộ lọc tùy chọn (ADX, Volume, H1 EMA) nếu được bật. - Không xảy ra tín hiệu mâu thuẫn (
not ambiguous) vàcanTradehợp lệ.
4.3. Điều kiện kiểm soát giao dịch chung
Biến canTrade đóng vai trò cổng kiểm soát an toàn cho mọi lệnh vào:
- Nến đã xác nhận:
barstate.isconfirmed == true. - Trạng thái tài khoản: Đang không có vị thế (
strategy.position_size == 0vàstrategy.opentrades == 0) và chưa mở lệnh nào trên chính cây nến này (freshEntryBar). - Giới hạn số lệnh/ngày:
tradesToday < 2(mặc định tối đa 2 lệnh/ngày). - Thời gian nghỉ (Cooldown): Phải cách lần đóng lệnh gần nhất nhiều hơn
3nến (bar_index - lastExitBar > 3). - Khung giờ giao dịch (
Asia/Ho_Chi_Minh): Chỉ vào lệnh khi thời gian mở nến từ09:15trở đi và thời gian đóng nến không quá14:15, đồng thời phải trước giờ cưỡng chế đóng phiên14:45(closeMinutes < 14:45).
5. Quản trị Stop Loss, Take Profit và Thoát lệnh
5.1. Cơ chế Stop Loss và quy đổi Tick
Bot sử dụng mức cắt lỗ cố định theo điểm (stopLossPoints = 5.0), được quy đổi chính xác sang đơn vị tick nhỏ nhất của hợp đồng (syminfo.mintick):
slTicks = math.max(1, int(math.round(stopLossPoints / syminfo.mintick)))effectiveSL = slTicks * syminfo.mintick
Với VN30F1M (mintick = 0.1), mức cắt lỗ tương ứng là 50 ticks (5.0 điểm). Bot không sử dụng bộ lọc giới hạn Min–Max Risk theo khoảng cách cấu trúc mà áp dụng cố định mức SL này cho mọi vị thế.
5.2. Cơ chế Take Profit, Time Exit và Đóng phiên
- Take Profit cố định: Tương tự SL,
takeProfitPoints = 15.0được quy đổi thànhtpTicks(150ticks trên VN30F1M), mang lại tỷ lệ Risk:Reward chuẩn1:3. Bot không tích hợp cơ chế dời hòa vốn (Break Even) hay Trailing Stop trong mã nguồn. - Thoát lệnh theo thời gian giữ (
useTimeExit): Mặc định đang tắt (false). Nếu bật, bot sẽ đóng toàn bộ vị thế bằngstrategy.close_allkhi số nến nắm giữbarsHeld >= 20trên nến đã đóng (trừ trường hợp trùng nến đóng phiên). - Đóng toàn bộ vị thế cuối phiên (
forceCloseBar): Khi nến có giờ mở trước14:45và giờ đóng từ14:45trở đi, bot lập tức thực thistrategy.close_all(immediately=true, comment="Session End")để tránh rủi ro qua đêm hoặc khớp giá ATC bất lợi.
5.3. Bảng tổng hợp cơ chế bảo vệ vị thế
| Cơ chế thoát lệnh | Trạng thái mặc định | Công thức / Điều kiện trong code | Ghi chú |
|---|---|---|---|
| Stop Loss (SL) | Luôn bật | loss = slTicks (5.0 điểm quy đổi ra tick) | Gửi qua strategy.exit |
| Take Profit (TP) | Luôn bật | profit = tpTicks (15.0 điểm quy đổi ra tick) | Tỷ lệ R:R 1:3 |
| Time Exit | Tắt (false) | barsHeld >= 20 nến trên barstate.isconfirmed | Có thể bật trong mục 06. Risk Management |
| Force Close (Hết phiên) | Luôn bật | openMinutes < 14:45 và closeMinutes >= 14:45 | Đóng toàn bộ vị thế qua strategy.close_all |
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 (khuyến nghị khung thời gian giao dịch trong ngày như M1, M3, M5 hoặc M15).
- Mở tab Pine Editor ở thanh công cụ phía dưới màn hình, xóa code mẫu mặc định.
- Sao chép toàn bộ mã nguồn CNPS80 BREAK OF STRUCTURE RETEST ở Mục 1 và dán vào Pine Editor.
- Nhấn Save (Lưu) và chọn Add to chart (Thêm vào biểu đồ).
- Mở biểu đồ cài đặt (biểu tượng bánh răng) để tùy chỉnh
Trade Direction("Long","Short"hoặc"Both") và bậtShow Diagnosticsnế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 = true, bot hiển thị bảng 18 dòng ở góc trên bên phải (position.top_right) trên cây nến cuối cùng (barstate.islast):
- CNPS80 BOS / Khung thời gian: Hiển thị tên bot và khung thời gian biểu đồ (
timeframe.period). - BOS High / BOS Low: Giá trị
structureHighvàstructureLowhiện tại. - EMA Up / EMA Down: Trạng thái độ dốc EMA tăng hay giảm (
YES/NO). - Bull BOS / Bear BOS: Tổng số lần phá vỡ cấu trúc tăng/giảm đã ghi nhận từ đầu dữ liệu lịch sử.
- Long Retests / Short Retests: Tổng số nến có chạm vùng retest.
- Long Bases / Short Bases: Số lần chạm retest thỏa mãn điều kiện nến từ chối giá (chưa tính bộ lọc EMA/ADX/Volume/H1).
- Filtered Long / Filtered Short: Số tín hiệu vượt qua toàn bộ bộ lọc xu hướng và điều kiện phụ.
- Pending Long / Pending Short: Cho biết hiện tại bot có đang chờ nhịp retest cho chiều Long hoặc Short hay không (
YES/NO). - Long Entries / Short Entries: Tổng số lệnh Long/Short thực tế đã khớp.
- Trades Today: Số lệnh đã thực hiện trong ngày hiện tại trên tổng giới hạn cho phép (ví dụ
1/2).
7. Cách thiết lập cảnh báo tín hiệu giao dịch (Alert)
Để nhận thông báo tự động qua ứng dụng TradingView, Telegram hoặc Webhook khi bot phát sinh tín hiệu:
- Nhấn biểu tượng Alert (đồng hồ báo thức) trên thanh công cụ TradingView.
- Tại mục Condition, chọn chiến lược CNPS80 BREAK OF STRUCTURE RETEST.
- 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}} - Nếu không muốn nhận thông báo khi chạm SL/TP (chỉ nhận thông báo vào lệnh và đóng phiên/hết thời gian giữ), bạn có thể bật tùy chọn
Disable SL/TP Alertstrong phần cài đặt09. Alerts.
Bảng thông điệp Alert của CNPS80
| Sự kiện kích hoạt | Loại lệnh trong code | 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 (CNPS80 BOS Retest) kèm Giá vào, Cắt lỗ (SL), Chốt lời (TP) |
| Vào lệnh Short | strategy.entry("Short") | 🔴 VÀO VỊ THẾ SHORT (CNPS80 BOS Retest) kèm Giá vào, Cắt lỗ (SL), Chốt lời (TP) |
| Chốt lời Long | strategy.exit("Long Exit") | 💰 CHỐT LỜI LONG (TP HIT) kèm Giá chốt |
| Cắt lỗ Long | strategy.exit("Long Exit") | 🛑 CẮT LỖ LONG (SL HIT) kèm Giá cắt |
| Chốt lời Short | strategy.exit("Short Exit") | 💰 CHỐT LỜI SHORT (TP HIT) kèm Giá chốt |
| Cắt lỗ Short | strategy.exit("Short Exit") | 🛑 CẮT LỖ SHORT (SL HIT) kèm Giá cắt |
| Hết thời gian giữ | strategy.close_all (Time Exit) | ⏱️ ĐÓNG VỊ THẾ HẾT THỜI GIAN GIỮ (Time Exit) kèm Giá đóng |
| Đóng hết phiên | strategy.close_all (Session End) | ⏰ ĐÓNG VỊ THẾ HẾT PHIÊN (Session End) kèm Giá đóng |
Kết luận
CNPS80 BREAK OF STRUCTURE RETEST là hệ thống giao dịch kỷ luật dành cho VN30F1M, đặc biệt phù hợp với các giai đoạn thị trường có xu hướng rõ ràng (trending) và xuất hiện những nhịp phá vỡ cấu trúc đi kèm kiểm tra lại vùng hỗ trợ/kháng cự. Việc kiên nhẫn chờ retest giúp trader tránh được phần lớn các pha phá vỡ giả, tối ưu điểm vào lệnh và duy trì tỷ lệ R:R 1:3 ổn định.
Bạn có thể tham khảo thêm các chiến lược khác trong cùng hệ sinh thái như Bot CNPS50 - Trend Analysis V2 và Bot CNPS49 - Daily Open.
Thông tin chỉ mang tính tham khảo, không phải khuyến nghị đầu tư. Kết quả kiểm thử quá khứ không đảm bảo lợi nhuận trong tương lai.
Thông tin trong bài chỉ mang tính tham khảo, không phải khuyến nghị mua bán. Giao dịch phái sinh có rủi ro cao do sử dụng đòn bẩy; nhà đầu tư tự chịu trách nhiệm với quyết định của mình.





