OPEN-SOURCE SCRIPT

DUP V12B (tích hợp nến động lượng)

219
DUP V12B - Dynamic Universal Points (Momentum Candles & 3-Tier Menu)
Authors: Đinh Ngọc Thạch
Version: 12B (DUP V12B)
Date: May 15, 2025 (Conceptual publication date based on script header)

Introduction
Welcome to DUP V12B, an advanced TradingView strategy meticulously crafted by Đinh Ngọc Thạch with AI assistance from Gemini. This version builds upon the robust foundation of DUP V11, introducing significant refinements to its core signal logic for bottoming/topping detection, adaptive thresholds, and a highly intuitive 3-Tier Menu System for unparalleled user customization.

A key innovation in V12B is the integration of Dynamic Momentum Candles, offering a unique visual perspective on price action relative to volatility channels. This, combined with a streamlined approach that removes the previous complex "Tier 2" system, focuses on delivering clearer, more actionable insights.

The DUP (Dynamic Universal Points) philosophy centers around identifying potential market turning points by analyzing market context, applying adaptive thresholds, and confirming signals through a consensus of technical indicators. Whether you're a novice trader or an experienced quantitative researcher, DUP V12B provides a flexible and powerful toolkit to explore market dynamics.

Disclaimer
Trading involves substantial risk of loss and is not suitable for every investor. The DUP V12B strategy is provided for educational and informational purposes only. It does not constitute financial advice or a recommendation to buy or sell any 1 financial instrument. All trading decisions are your sole responsibility. Past performance is not indicative of future results. Backtest thoroughly and use at your own risk.  
1.
github.com

github.com

User Guide
Core Concepts
DUP Philosophy: DUP stands for Dynamic Universal Points. The strategy aims to identify potential market bottoms for buying opportunities (and tops for selling, primarily through "Peak Detection") by adapting its parameters and signal thresholds to the prevailing market conditions.
Market Regimes: The script categorizes the market (based on a reference Index like VNINDEX) into three regimes:
REGIME_DOWNTREND: The reference index is in a downtrend.
REGIME_BOTTOMING_RANGE: The reference index is in a consolidation/bottoming phase or not in a clear trend.
REGIME_UPTREND: The reference index is in an uptrend.
LBU (Laddered Buy-in Units): This system allows for scaling into positions. Instead of entering with the full intended capital at once, LBU enables multiple entries (up to 5, configurable) as the price potentially moves into more favorable zones, based on pre-defined or adaptive ratios of your total allocated capital for that specific symbol.
Peak Detection Sell: This is a prioritized selling logic. If enabled, the strategy will actively look for signs of a market top (e.g., RSI falling from overbought, bearish divergences) to exit positions, potentially overriding standard exit methods like Trailing Stops or Take Profits.
Adaptive Layer: The strategy can adjust its internal sensitivity and signal thresholds (e.g., minimum score required for a buy signal) based on the broader market context (trend and volatility). This helps the script to be more or less aggressive depending on market conditions.
Momentum Candles: A new visualization feature in V12B. When enabled, the script plots its own candles, colored based on their position within a chosen volatility channel (Bollinger Bands %B or Keltner Channels). To use this effectively, you MUST HIDE THE ORIGINAL CHART CANDLES via TradingView's main chart settings.
Operating Modes (Key Feature)
DUP V12B introduces a 3-Tier menu system to cater to different user needs. It's crucial to only adjust settings relevant to your selected Operation Mode.

MODE_BASIC (1. Basic - Đơn giản):

The simplest mode, designed for quick setup and ease of use.
Allows toggling main features on/off (e.g., enable simple adaptive mode, show buy/sell signals, choose basic buy signal types, select primary sell methods).
Ideal for beginners or users who prefer a less granular approach.
MODE_ADVANCED (2. Advanced - Nâng cao):

Offers more detailed control over the strategy's parameters.
Fine-tune buy signal components (RSI, Stoch, Volume, Candle, etc.), LBU settings (ratios, max entries), standard exit parameters (Stop Loss, Trailing Stop, Take Profit types and values), Peak Detection Sell logic, and the overall sensitivity of the Adaptive Layer.
Suitable for traders who want to tailor the strategy more closely to specific instruments or their trading style.
MODE_PREMIUM (3. Premium - Developer):

Provides complete control over all aspects of the strategy, including its core "brain."
Market Context Engine: Configure how the script analyzes the reference market index.
Adaptive Layer Deep Dive: Manually input market/volatility scores, blend scores, and fine-tune impact factors.
Scoring Logic (Buy/Sell): Adjust the base thresholds and weights for each individual buy/sell confirmation signal.
V17 Legacy Params (Research): Access to older dynamic parameter settings for research purposes.
Debug Options: Display detailed internal states for in-depth analysis.
This mode is intended for advanced users, quantitative researchers, or those who wish to deeply understand and experiment with the script's internal mechanics.
Key Input Sections Walkthrough
0. CHẾ ĐỘ HOẠT ĐỘNG (QUAN TRỌNG) (Operation Mode - IMPORTANT):

This is the first and most critical setting. Choose Basic, Advanced, or Premium. Your choice here determines which subsequent settings are active and relevant.
1. BASIC MODE SETTINGS: (Only active if MODE_BASIC is selected)

🧠 Bật Chế độ Bám theo Thị trường (Thích ứng Đơn giản)?: Enables/disables a simplified adaptive behavior.
📈 Hiện Tín hiệu Mua? / 📉 Hiện Tín hiệu Bán?: Toggles visibility of buy/sell signal shapes on the chart.
Buy Signal Sources:
Sử dụng Phân kỳ làm Tín hiệu Mua?: Use bullish divergence as a buy condition.
Sử dụng RSI/Stoch Quá bán?: Use oscillator (RSI/Stoch) crossover from oversold as a buy condition.
Sử dụng Nến & Volume?: Use strong bullish candles and volume spikes as buy conditions.
Sell Methods:
🔥 Ưu tiên Bán Dò Đỉnh?: If enabled, prioritizes peak detection signals for exits.
💧 Sử dụng Dừng lỗ Động (Trailing Stop)?: Enables trailing stop (effective if Peak Sell is off or not triggered).
🛡️ Sử dụng Dừng lỗ Cố định (Stop Loss)?: Enables a fixed initial stop loss.
2. ADVANCED MODE SETTINGS: (Active if MODE_ADVANCED or MODE_PREMIUM is selected. Basic mode uses defaults from these.)

2.1. Advanced - Buy Signals & Base Params:
EMA Dài hạn (Base): Length for the long-term Exponential Moving Average.
Loại Kênh Trigger: Choose "Keltner Channel" or "Bollinger Bands" as the primary trigger for buy zones.
KC/BB Parameters: Lengths, Multipliers/Standard Deviations (these are "Base" values, potentially adjusted by the adaptive layer if active in Premium).
Detailed Buy Confirmation Toggles: Enable/disable and configure parameters for RSI (Oversold, Divergence), Volume, Candle patterns, Stochastic (Oversold, Divergence), MACD crossover, OBV trend, and ADX weakness.
2.2. Advanced - LBU Settings:
Tổng Vốn Dự kiến (Cho mã này) & Đơn vị Tiền tệ: Your intended total capital for this specific trading instrument and its currency (used for calculating position size with strategy.cash).
Chế độ Giải ngân LBU:
"Fixed Ratio": Uses pre-defined fixed percentage steps for LBU.
"Adaptive Ratio": (Currently simplified in V12 - may use a fixed factor).
"Custom Ratio": Manually set the percentage of capital for each LBU entry (LBU 1% to LBU 5%).
Số Lần Mua Tối Đa (Bậc LBU): Maximum number of LBU entries (1 to 5).
Tỷ lệ LBU 1 (%) - Tỷ lệ LBU 5 (%): Custom percentages for each LBU step if "Custom Ratio" is selected.
Buffer Giá LBU (%): Allows buying on a new LBU step if the new low is not strictly lower than the previous buy's low, but within this buffer percentage. 0.0 requires a strictly lower low.
⛔ Chặn Mua khi vào Uptrend?: Prevents further LBU entries if the market regime shifts to REGIME_UPTREND.
2.3. Advanced - Standard Exit Settings (SL/TS/TP):
Stop Loss (SL):
🛡️ Bật Stop Loss Chuẩn?: Enable/disable standard stop loss.
Loại SL: "ATR" (based on Average True Range) or "Swing Low" (based on recent lowest lows).
Parameters for ATR (Length, Base Multiplier) and Swing Low (Lookback, Buffer ATR Multiplier).
Trailing Stop (TS):
💧 Bật Trailing Stop Chuẩn?: Enable/disable standard trailing stop.
Loại TS: "EMA Trail", "PSAR", "Chandelier Trail", "ATR Trail (SuperTrend)".
Base parameters for each TS type (e.g., EMA Length, PSAR Start/Inc/Max, Chandelier Period/Multiplier, ATR Trail Length/Multiplier).
Take Profit (TP):
🎯 Loại Chốt lời:
"Không dùng TP": Disables automatic take profit.
"TP Đa mức (ATR/RR/Kênh)": Calculates 1-3 TP levels based on ATR, Risk/Reward, or Channel Uppers.
"TP % Mục tiêu": Exits when a fixed profit percentage from the average entry price is reached.
% Lãi Mục tiêu: The target profit percentage if "TP % Mục tiêu" is chosen.
Settings for "TP Đa mức":
Bật Tính toán & Vẽ TP Đa mức?: Whether to calculate and display these levels (useful even if not auto-exiting).
Số Mức TP Đa mức: How many TP levels to calculate (1-3).
Cách Tính TP Đa mức: "KC/BB Upper", "ATR Offset", "Fixed RR".
Detailed parameters for each calculation method.
Tự động Thoát lệnh tại TP Đa mức?: If "TP Đa mức" is the chosen type, enable this to auto-exit.
Mức TP Đa mức Thoát lệnh: Which of the calculated TP levels (1, 2, or 3) will trigger an automatic exit.
2.4. Advanced - Peak Detection Sell Settings:
🔥 Ưu tiên Bán Dò Đỉnh?: Enables the Peak Sell mode.
Signal Sources: RSI Fall from Overbought (OB), Bearish Divergence (RSI or MACD source), Stochastic OB Cross. Includes parameters like thresholds, lookbacks.
Logic Kết hợp Đỉnh: "ANY" (any peak signal triggers) or "ALL" (all enabled peak signals must trigger).
2.5. Advanced - Adaptive Layer Control:
🧠 Bật Chế độ Thích ứng?: Enable/disable the adaptive adjustments for Advanced mode.
⚙️ Độ nhạy Thích ứng Tổng thể: Controls how strongly the adaptive layer influences thresholds (uses internal market scores in this mode).
3. PREMIUM (DEV) MODE SETTINGS: (Only active if MODE_PREMIUM is selected)

3.1. Premium - Market Context Engine: Configure the reference Index (HOSE:VNINDEX by default), EMA/RSI/ADX/BB lengths, and thresholds for defining market regimes and internal scores.
3.2. Premium - Adaptive Layer Deep Dive: Input manual market/volatility scores, choose the source for adaptive scores ("Manual", "Internal Assessment", "Blended"), adjust overall sensitivity, and fine-tune impact factors for trend, volatility, and breadth. Includes base parameters for trailing stops that can be adaptively modified.
3.3. Premium - Scoring Logic (Buy/Sell): Set base minimum scores for bottoming/topping and, critically, assign weights (w - ...) to each individual confirmation signal (e.g., w - RSI OS, w - Divergence). This determines how influential each signal is in the overall buy/sell consensus score. Option to Điều chỉnh Trọng số Tín hiệu theo Bối cảnh TT? (Adjust signal weights by market context).
3.4. Premium - V17 Legacy Params (Research): For research, enables older V17 dynamic parameter adjustments.
3.5. Premium - Debug Options: Show detailed debug information on the chart for market context, adaptive layer calculations, scoring, and signal states.
4. COMMON SETTINGS - Display & UI:

Toggles for showing/hiding Buy (▲) / Sell (▼) shapes, EMA line, Trigger Channel lines, SL/TS/TP lines.
Buy Label customization (background/text color, size, offset).
Tô màu Nến theo Tín hiệu?: Note: This is traditional bar coloring. For the new Momentum Candles, see section 5 and disable this if using Momentum Candles.
Dashboard settings: Show/hide, position, background/text color, and toggles for what information to display (Market Context, Scores, LBU status, Position, SL/TP distance, Exit Mode).
5. COMMON SETTINGS - Momentum Candle Viz: (New in V12B)

🕯️ Bật Tô màu Nến Động Lượng?: Enable this to use Momentum Candles. If enabled, you MUST HIDE THE ORIGINAL CHART CANDLES from TradingView's main chart style settings for the effect to be visible correctly.
MC - Nguồn Vị Trí Nến: Choose "Bollinger Bands (%B)" or "Keltner Channels" as the basis for candle coloring.
Parameters for the chosen indicator (BB Length/Mult or KC Length/Mult for momentum calculation).
MC - Màu Bắt đầu (Thấp) & MC - Màu Kết thúc (Cao): Gradient colors for the candle body.
MC - Màu Bấc Nến & MC - Độ Trong Suốt Thân (%): Wick color and body transparency.
6. COMMON SETTINGS - Alert Messages:

Templates for Buy, Stop Loss, Trailing Stop, Take Profit, and Peak Sell alerts. You can customize these using placeholders (see "Alerts" section below).
How to Use
Initial Setup: Add the DUP V12B script to your chart. The first and most important step is to select your desired ⚙️ Chọn Chế độ Hoạt động (Operation Mode).
Basic Mode Users:
Navigate to "1. BASIC MODE SETTINGS."
Toggle the main features on/off as per your preference (e.g., Bật Chế độ Bám theo Thị trường, choose buy signal sources, select sell methods).
Advanced Mode Users:
Navigate to "2. ADVANCED MODE SETTINGS."
Configure Buy Signals & Base Parameters (EMA, Trigger Channel, confirmation indicators).
Set up your LBU strategy (Total Capital, Ratios, Max Entries).
Define your Standard Exit rules (SL, TS, TP types and their specific parameters).
Configure Peak Detection Sell if you intend to use it.
Adjust Adaptive Layer sensitivity if desired.
Premium Mode Users:
Navigate to "3. PREMIUM (DEV) MODE SETTINGS."
Dive deep into the Market Context Engine, Adaptive Layer, Scoring Logic, etc. Exercise caution, as these settings significantly impact the strategy's core behavior.
Momentum Candles (All Modes):
If you enable 🕯️ Bật Tô màu Nến Động Lượng? in "5. COMMON SETTINGS - Momentum Candle Viz," remember to hide the main chart's candles. Right-click on the chart -> Settings -> Symbol -> Untick "Body", "Borders", "Wick". This will prevent visual overlap.
LBU (Laddered Buy-in Units):
The strategy will attempt to buy in multiple steps if LBU is configured for more than one entry.
Each buy signal (rawDupBuySignal) is a potential LBU entry. The actual entry depends on lbuCounter, price conditions (lowerPriceCondition), budget, and uptrend restrictions.
Your Tổng Vốn Dự kiến is divided according to the LBU ratios for each entry.
Exits:
The strategy has a clear exit hierarchy:
Stop Loss (Hard SL): Always has the highest priority.
Peak Sell Mode (If Active): If Ưu tiên Bán Dò Đỉnh? is enabled and a peak sell signal occurs, this will take precedence over standard TS/TP.
Standard Exits (If Peak Sell is Inactive or Not Triggered): Trailing Stop or Take Profit (either multi-level or target %).
Dashboard:
Enable the Dashboard in "4. COMMON SETTINGS - Display & UI" to get a real-time overview of the market regime, current buy/sell scores vs. thresholds, LBU status, active position details, and SL/TP distances.
Alerts
The DUP V12B strategy supports customizable alert messages using placeholders that get dynamically replaced with real-time values when an alert is triggered.

Placeholders: You can use placeholders like:

{{ticker}}: Trading symbol (e.g., BTCUSD)
{{exchange}}: Exchange name (e.g., NASDAQ)
{{price}}: Price at which the alert condition met.
{{plot_X}}: Value of a specific plot (e.g., {{plot_0}} for the first plot() output). More complex for strategy-specific info.
Strategy-Specific Placeholders (as defined in the script's alert message inputs):
{{lbu_info}}: Information about the LBU entry.
{{sl_level}}: Stop loss level.
{{tp_level}}: Take profit level.
{{bottom_score}}: Buy score.
{{ratio}}%: LBU ratio percentage.
{{ts_type}}: Type of trailing stop hit.
{{ts_level}}: Trailing stop level.
{{tp_num}}: Take profit level number (for multi-level TP).
{{top_score}}: Sell score for peak detection.
{{peak_reason}}: Reason for peak detection sell.
Setting up Alerts in TradingView:

Click the "Alert" icon (clock) in TradingView's right-hand toolbar or on the script's name on the chart.
Condition: Select "DUP V12B".
Choose the specific alert condition you want (e.g., "Buy", "Sell", or any custom alert setup via alertcondition() if you were to add them – though strategies typically use strategy.entry, strategy.exit, strategy.close_all which can trigger alerts). For strategies, you often select the script name and then the specific entry/exit condition provided by TradingView (e.g., "Order fills and alert function calls").
Trigger: "Once Per Bar Close" is generally recommended for strategies to avoid premature signals based on intra-bar price fluctuations.
Alert Actions: Choose how you want to be notified (Notify on app, Show pop-up, Send email, Webhook URL, etc.).
Message: You can use the default messages from the script's input settings or craft your own using the placeholders.
To use the script's dynamic messages for strategy alerts, you typically use {{strategy.order.alert_message}} in the TradingView alert message box if the strategy call (like strategy.entry) includes an alert_message parameter. Since this script defines alert templates in inputs but doesn't explicitly pass them to strategy.entry/order via alert_message parameter in the provided code, you'd manually copy your desired template from the script's input into the TradingView alert message box, replacing placeholders as needed for what TradingView offers natively for strategies.
Example Alert Message (manual setup in TradingView alert dialog for a buy):
{{ticker}} DUP V12 BUY | LBU: {{strategy.order.comment}} | Price: {{strategy.order.price}} | SL: CheckScript | TP: CheckScript
(Note: Accessing exact dynamic SL/TP levels directly in strategy.order.alert_message without them being part of the order comment or a dedicated alert variable can be tricky. Often, the comment field is used, or you set separate alerts for SL/TP breaches if possible.)

For strategy alerts, it's often best to rely on the "Order Fill" alerts and use the comment field of your strategy.entry or strategy.close_all calls to pass dynamic information, then reference {{strategy.order.comment}} in your alert message.

Backtesting and Optimization
Thorough Backtesting: Before trading live, extensively backtest DUP V12B on various financial instruments (stocks, forex, crypto, etc.) and timeframes.
Parameter Optimization:
Adjust LBU ratios, stop-loss percentages, take-profit targets, and indicator lengths based on the specific asset's volatility and your risk tolerance.
The Advanced and Premium modes offer many parameters to fine-tune. Start with Advanced before moving to Premium.
max_bars_back: The script requests 1000 bars of historical data (max_bars_back=1000). Ensure your chart has sufficient data for accurate calculations, especially for longer-term indicators.
Commission & Slippage: The script includes settings for commission_value (e.g., 0.15%) and slippage (in ticks). Adjust these to reflect your actual trading costs for more realistic backtest results.
Troubleshooting & Tips
No Signals/Lines:
Check "COMMON SETTINGS - Display & UI" to ensure shapes and lines are enabled.
Verify that the features you expect to see signals from are enabled in your chosen Operation Mode (Basic, Advanced, or Premium settings).
Momentum Candles Not Displaying Correctly: Ensure you have hidden the original chart candles from TradingView's main chart settings (Style -> untick Body, Borders, Wick).
Start Simple: Begin with Basic or Advanced mode to understand the fundamental behavior before venturing into the Premium settings.
Read Tooltips: Hover over the input settings in the script's configuration panel. Many options have tooltips (in Vietnamese in the original script, but their function is described here) explaining their purpose.
Dashboard is Your Friend: Keep an eye on the on-chart dashboard (if enabled) for a quick status check of the script's internal state.

Declinazione di responsabilità

Le informazioni ed i contenuti pubblicati non costituiscono in alcun modo una sollecitazione ad investire o ad operare nei mercati finanziari. Non sono inoltre fornite o supportate da TradingView. Maggiori dettagli nelle Condizioni d'uso.