Normalized Portfolio TrackerThis script lets you create, visualize, and track a custom portfolio of up to 15 assets directly on TradingView.
It calculates a synthetic "portfolio index" by combining multiple tickers with user-defined weights, automatically normalizing them so the total allocation always equals 100%.
All assets are scaled to a common starting point, allowing you to compare your portfolio’s performance versus any benchmark like SPY, QQQ, or BTC.
🚀 Goal
This script helps traders and investors:
• Understand the combined performance of their portfolio.
• Normalize diverse assets into a single synthetic chart .
• Make portfolio-level insights without relying on external spreadsheets.
🎯 Use Cases
• Backtest your portfolio allocations directly on the chart.
• Compare your portfolio vs. benchmarks like SPY, QQQ, BTC.
• Track thematic baskets (commodities, EV supply chain, regional ETFs).
• Visualize how each component contributes to overall performance.
📊 Features
• Weighted Portfolio Performance : Combines selected assets into a synthetic value series.
• Base Price Alignment : Each asset is normalized to its starting price at the chosen date.
• Dynamic Portfolio Table : Displays symbols, normalized weights (%), equivalent shares (based on each asset’s start price, sums to 100 shares), and a total row that always sums to 100%.
• Multi-Asset Support : Works with stocks, ETFs, indices, crypto, or any TradingView-compatible symbol.
⚙️ Configuration
Flexible Portfolio Setup
• Add up to 15 assets with custom weight inputs.
• You can enter any arbitrary numbers (e.g. 30, 15, 55).
• The script automatically normalizes all weights so the total allocation always equals 100%.
Start Date Selection
• Choose any custom start date to normalize all assets.
• The portfolio value is then scaled relative to the main chart symbol, so you can directly compare portfolio performance against benchmarks like SPY or QQQ.
Chart Styles
• Candlestick chart
• Heikin Ashi chart
• Line chart
Custom Display
• Adjustable colors and line widths
• Optionally display asset list, normalized weights, and equivalent shares
⚙️ How It Works
• Fetch OHLC data for each asset.
• Normalizes weights internally so totals = 100%.
• Stores each asset’s base price at the selected start date.
• Calculates equivalent “shares” for each allocation.
• Builds a synthetic portfolio value series by summing weighted contributions.
• Renders as Candlestick, Heikin Ashi, or Line chart.
• Adds a portfolio info table for clarity.
⚠️ Notes
• This script is for visualization only . It does not place trades or auto-rebalance.
• Weight inputs are automatically normalized, so you don’t need to enter exact percentages.
Gestão de carteira
DCA vs One-ShotCompare a DCA strategy by choosing the payment frequency (daily, weekly, or monthly), and by choosing whether or not to pay on weekends for cryptocurrency. You can add fees and the reference price (opening, closing, etc.).
RSI Momentum ScalperOverview
The "RSI Momentum Scalper" is a Pine Script v5 strategy crafted for trading highly volatile markets, with a special focus on newly listed cryptocurrencies. This strategy harnesses the Relative Strength Index (RSI) alongside volume analysis and momentum thresholds to pinpoint short-term trading opportunities. It supports both long and short trades, managed with customizable take profit, stop loss, and trailing stop levels, which are visually plotted on the chart for easy tracking.
Why I Created This Strategy
I developed the "RSI Momentum Scalper" because I was seeking a reliable trading strategy tailored to newly listed, highly volatile cryptocurrencies. These assets often experience rapid price fluctuations, rendering traditional strategies less effective. I aimed to create a tool that could exploit momentum and volume spikes while managing risk through adaptable exit parameters. This strategy is designed to address that need, offering a flexible approach for traders in dynamic crypto markets.
How It Works
The strategy utilizes RSI to identify momentum shifts, combined with volume confirmation, to trigger long or short entries. Trades are controlled with take profit, stop loss, and trailing stop levels, which adjust dynamically as the price moves in your favor. The trailing stop helps lock in profits, while the plotted exit levels provide clear visual cues for trade management.
Customizable Settings
The script is highly customizable, allowing you to adjust it to various market conditions and trading styles. Here’s a brief overview of the key settings:
Trade Mode: Select "Both," "Long Only," or "Short Only" to determine the trade direction.
(Default: Both)
RSI Length: Sets the lookback period for the RSI calculation (2 to 30).
(Default: 8)
A shorter length increases RSI sensitivity, suitable for volatile assets.
RSI Overbought: Defines the upper RSI threshold (60 to 99) for short entries.
(Default: 90)
Higher values signal stronger overbought conditions.
RSI Oversold: Defines the lower RSI threshold (1 to 40) for long entries.
(Default: 10)
Lower values indicate stronger oversold conditions.
RSI Momentum Threshold: Sets the minimum RSI momentum change (1 to 15) to trigger entries.
(Default: 14)
Adjusts the sensitivity to price momentum.
Volume Multiplier: Multiplies the volume moving average to filter high-volume bars (1.0 to 3.0).
(Default: 1)
Higher values require stronger volume confirmation.
Volume MA Length: Sets the lookback period for the volume moving average (5 to 50).
(Default: 13)
Influences the volume trend sensitivity.
Take Profit %: Sets the profit target as a percentage of the entry price (0.1 to 10.0).
(Default: 4.15)
Determines when to close a winning trade.
Stop Loss %: Sets the loss limit as a percentage of the entry price (0.1 to 6.0).
(Default: 1.85)
Protects against significant losses.
Trailing Stop %: Sets the trailing stop distance as a percentage (0.1 to 4.0).
(Default: 2.55)
Locks in profits as the price moves favorably.
Visual Features
Exit Levels: Take profit (green), fixed stop loss (red), and trailing stop (orange) levels are plotted when in a position.
Performance Table: Displays win rate, total trades, and net profit in the top-right corner.
How to Use
Add the strategy to your chart in TradingView.
Adjust the input settings based on the cryptocurrency and timeframe you’re trading.
Monitor the plotted exit levels for trade management.
Use the performance table to assess the strategy’s performance over time.
Notes
Test the strategy on a demo account or with historical data before live trading.
The strategy is optimized for short-term scalping; adjust settings for longer timeframes if needed.
🔵Blue Mark📌 Blue Mark – TradingView Indicator
The Blue Mark indicator highlights extreme price points across multiple timeframes (15m, 5m, 1m), helping intraday traders identify liquidity zones and areas of institutional interest. It is designed for traders who want to spot high-probability entry and exit points based on market structure and volume concentration.
✔️ Marks extreme highs and lows on 15m, 5m, and 1m charts
✔️ Ideal for intraday trading and short-term strategies
✔️ Helps detect liquidity zones where institutional orders are likely concentrated
✔️ Supports tactical entries and exits aligned with market structure
How to use:
Apply the indicator to your chart.
Observe the marked extreme points on different timeframes.
Use these levels to plan entries, exits, or confirm areas of institutional interest.
Altcoins Exit Executor: 3Commas-Integrated [SwissAlgo]Title: Altcoins Exit Executor: 3Commas-Integrated
Plan and Execute your Altcoins Exits via 3Commas Integration
------------------------------------------------------------------
1. Facing These Struggles?
You're holding a portfolio of altcoins, and the question keeps nagging you: when should you exit? how?
If you're like many crypto traders, you might recognize these familiar struggles:
The Planning Problem : You know you should have an exit strategy, but every time you sit down to plan it, you get overwhelmed. Should you sell at 2x? 5x? What about that resistance level you spotted last month? You end up postponing the decision again and again.
The Execution Headache : You use 3Commas (or an Exchange directly) for your trades, but setting up Smart Trades for multiple coins means endless manual data entry. Price levels, percentages, quantities - by the time you finish entering everything, the market may have already moved.
The Portfolio Scale Problem : Managing 5 altcoins is challenging enough, but what about 15? Or 30? The complexity grows exponentially with each additional position. What started as a manageable analysis for a few coins becomes an overwhelming juggling act that may lead to rushed decisions or complete paralysis.
The Consistency Challenge : You approach each coin differently. Maybe you're conservative with one position and aggressive with another, without any systematic reasoning. Your portfolio becomes a patchwork of random decisions rather than a coherent strategy. With dozens of positions, maintaining any consistent approach becomes nearly impossible.
The "What If" Anxiety : What happens if the market crashes while you're sleeping? You know you should have stop-losses, but setting them up properly across multiple positions feels overwhelming. The more coins you hold, the more potential failure points you need to monitor.
The Information Overload : You collect multiple data points, but how do you synthesize all this information into actionable exit points? Multiply this analysis across 20+ different altcoins, and the task becomes nearly impossible to execute consistently.
This indicator may help address these challenges by providing you with:
A systematic approach to analyzing potential resistance levels across multiple technical frameworks. All potential resistances (including Fibonacci levels) are calculated automatically
Tools to structure your exit plan with clear take-profit levels and position sizing
Automated generation of 3Commas 'Smart Trades' that match your exit strategy exactly, without manual entry
Optional emergency exit protection that could potentially guard against sudden market reversals (exit managed within the 3Commas 'Smart Trade' itself)
A consistent methodology you can apply across your entire altcoin portfolio, regardless of size
The goal is to transform exit planning from a source of stress and procrastination into a structured, repeatable process that may help you execute your trading plan in a consistent fashion, whether you're managing 3 coins or 30.
------------------------------------------------------------------
2. Is this for You?
This indicator is designed for cryptocurrency traders who:
Hold a portfolio of multiple altcoins (typically 5+ positions)
Are actively seeking a systematic solution to plan and execute exit strategies
Have an active 3Commas account connected to their exchange
Understand 3Commas basics: Smart Trades, API connections, and account management
Have an account tier that supports their portfolio size (3Commas Free Plan: up to 3 trades/alts, Pro Plan: up to 50+ trades/alts)
Important: This tool provides analysis and automation assistance, not trading advice. All exit decisions require your individual judgment and proper risk management.
If you don't use 3Commas, you may still find value in the resistance analysis components, though the automated execution features require a 3Commas account and basic platform knowledge.
------------------------------------------------------------------
3. How does it work?
This indicator streamlines your exit planning process into four steps:
Step 1: Analyze Your Coin & Define Exit Plan
The indicator automatically calculates multiple types of resistance levels that may act as potential exit points:
Fibonacci Extensions (projected resistance from recent price swings)
Fibonacci Retracements (resistance from previous cycle highs)
Major Pivot Highs (historical price rejection points)
Volume Imbalances (PVSRA analysis showing institutional activity zones)
Price Multipliers (2x, 3x, 4x, 5x psychological levels)
Market Trend Analysis (bull/bear market strength assessment)
You can view all resistance types together or focus on specific categories to identify potential exit zones.
Step 2: Enter Your Exit Plan.
Define your sequential take-profit strategy:
Set up to 5 take-profit levels with specific prices
Assign percentage of coins to sell at each level
Add your total coin quantity and average entry price
Optionally enable emergency exit (stop-loss) protection. The indicator validates your plan in real-time, ensuring percentages sum to 100% and prices follow logical sequences.
Step 3: Connect with 3Commas
Relay Secret
3Commas API keys (Public and Private)
Account ID (your exchange account on 3Commas)
Step 4: Generate Smart Trade on 3Commas
Create a TradingView alert that automatically:
Sends your complete exit plan to 3Commas
Creates a Smart Trade with all your take-profit levels
Includes stop-loss protection if enabled
Requires no manual data entry on the 3Commas platform
The entire process is designed to streamline the time required to move from analysis to execution, providing a standardized methodology across your altcoin positions.
User Experience Features:
Step-by-step guided workflow
Interactive submission helper with status tracking
Exit plan table with detailed projections
Comprehensive legend and educational tooltips
Dark/light theme compatibility
Organized visual presentation of all resistance levels
------------------------------------------------------------------
4. Using the Indicator
Complete the 4-step guided workflow within the indicator to set up an Exit Plan and submit it to 3Commas.
At the end of the process, you will see a Smart Trade created on 3Commas reflecting your custom Exit Plan (inclusive of Stop Loss, if enabled).
Recommended Settings
Analyze your Exit Plan on the 1-Day timeframe
Use the Tradingview's Dark-Theme for high visual contrast
Set candles to 'Bar-Type' to view volumr-based candle colors (PVSRA analysis)
Use desktop for full content visibility
Analyzing Resistance Levels
Enable "Show all Resistance Levels" to view comprehensive analysis across your chart
Focus on resistance clusters where multiple resistance seem to converge - these may indicate stronger potential exit zones
Note the color-coded system: gray lines indicate closer levels, red lines suggest stronger resistance or potentially "out-of-reach" targets
Pay attention to the Golden Zone (Fibonacci 0.618-0.786 area) highlighted in green, it might act as a significant price magnet for average altcoins
Decide how many Take Profit Steps to use (min. 1 - max- 5)
Setting up your Plan
Enter the total number of coins you want to sell with the script
Enter your average entry price, if known (otherwise the script will use the current price as backup)
Enter the TP levels you decided to activate (price, qty to sell at each TP level)
Decide about the Emergency Exit (the price that, when broken, will trigger the sale of 100% of your coins with a close limit order)
Setting Up Your 3Commas Connection
Generate API keys in your 3Commas account with (User Profile→3Commas API→New API Access Token→System Generated→Permission: "Smart Trades Only" (leave all other permissions unchecked) + Whitelisted IP→Create→Save API public/private key securely)
Find your Account ID in the 3Commas exchange URL (My Portfolio→View Exchange→Look at the last number in the url of the webpage - should be a 8-digit number)
Enter all credentials in the indicator's connection section
Verify the green checkmarks appear on the Exit Table, confirming that plan and connection are validated
Deploying Your Plan
Check box "Step 1: Check and confirm Exit Plan" in section 4 of User Settings
Create a TradingView alert (Alert→Select Altcoins Exit Planner PRO→Any alert() function call→Interval Same as Chart→Open Ended→Message: coin name→Notifications: enable Webhook→save and exit
Your Smart Trade appears automatically in 3Commas within minutes
IMPORTANT: Delete the alert after successful deployment to prevent duplicated Smart Trades
To modify the Exit Plan: Delete the Smart Trade on 3Commas and repeat the process above
Monitor your Smart Trade execution through your 3Commas dashboard
Important Notes
Always verify your plan in the Exit Table before deployment
Test with smaller positions initially to familiarize yourself with the process
The indicator provides analysis - final trading decisions remain yours
Manage your API keys and Relay secret with caution: do not share with third parties, store them securely, use malware protection on your PC
Your API keys, trading data, and credentials are transmitted securely through direct API connections and are never stored, logged, or accessible to the indicator author - all communication occurs directly between your browser and the target platforms that support the service.
------------------------------------------------------------------
5. Understanding the Resistance Analysis
Fibonacci Extensions: Calculated from three key points: 2022 bear market bottom → early 2024 bull market high → 2025 retracement low. These project where price might encounter resistance during future rallies based on mathematical ratios (0.618, 1.0, 1.618, 2.0, etc.).
Fibonacci Retracements: For established altcoins: calculated from 2021 cycle peak to 2022 bottom. For newer altcoins: from all-time high to subsequent major low. These show potential resistance zones where price may struggle to reclaim previous highs.
Major Pivot Highs: Historical price levels where significant reversals occurred. These act as potential resistance because traders may remember these levels and place sell orders near them.
Volume Imbalances (PVSRA) : Areas where price moved rapidly on abnormal volume, creating gaps that may attract future price action or orders. The indicator uses volume-to-price-range analysis (PVSRA candles or "Vector Candles") to identify these zones.
Price Multipliers: Reference lines showing 2x, 3x, 4x, 5x current price to help you assess the feasibility of your exit targets. These serve as a "reality check" - if you're setting a take-profit at 4x current price, you can quickly evaluate whether that level seems reasonable given current market conditions and your risk tolerance.
Market Trend Analysis: Uses EMA combined with ADX/DMI indicators to assess current market phase (bull/strong bull, bear/strong/bear, weakening trend)
This technical foundation helps explain why certain price levels appear as potential exit zones, though market conditions ultimately determine actual price behavior.
------------------------------------------------------------------
6. FAQs
GENERAL FAQS
Can I use one indicator for multiple altcoins?
Answer: No, each altcoin needs its own chart layout with a separate indicator installation. Resistance levels are calculated from each coin's unique price history, and your exit plan will be different for each position. When you deploy an alert, it creates one Smart Trade on 3Commas for that specific coin only.
To manage multiple coins, create separate TradingView layouts for each altcoin, configure the indicator individually on each chart, then deploy one alert per coin when ready to execute. This ensures each position gets personalized analysis and allows different exit strategies across your portfolio.
EXIT PLAN ANALYSIS/RESISTANCE LEVELS
Are resistance lines calculated automatically by the script?
Answer: Yes, all resistance lines are calculated automatically based on your coin's price history and market data. You don't need to manually identify or draw any levels. The script analyzes historical pivots, calculates Fibonacci ratios from key price swings, identifies volume imbalance zones, and plots everything on your chart.
Simply enable "Show all Resistance Levels" in the settings and the indicator will display all potential resistance zones with color-coded lines and labels showing the exact price levels and their significance.
What's the difference between Fibonacci Extensions and Fibonacci Retracements?
Answer: Fibonacci Retracements look at completed moves from the past and show where price might struggle to reclaim previous highs. For established coins, they're calculated from 2021 peaks down to 2022 bottoms.
Fibonacci Extensions project forward from recent price swings to estimate where ongoing rallies might encounter resistance. They use three points: 2022 bottom, 2024 high, and 2025 retracement low.
Retracements ask "where might recovery stall based on old highs" while Extensions ask "where might this current rally run into trouble." Both use the same mathematical ratios but different reference points to give you complementary resistance perspectives.
Why are some resistance lines gray and others red?
Answer: The color coding helps you assess the potential difficulty of reaching different resistance levels. Gray lines represent closer resistance levels, while red lines indicate stronger resistance or potentially "out-of-reach" targets that may require exceptional market conditions to break through.
This visual system helps you prioritize your exit planning by distinguishing between near-term targets and more ambitious longer-term objectives when setting your take-profit levels.
What is the resistance from major pivot highs?
Answer: Major pivot highs are historical price levels where significant reversals occurred in the past. These levels often act as resistance because traders remember these previous "ceiling" points where price failed to break higher and may place sell orders near them again.
The indicator automatically identifies these pivot points from your coin's price history and draws horizontal lines at those levels. When price approaches these areas again, it may struggle to break through due to psychological resistance and clustered sell orders from traders who expect similar rejection patterns.
What is the resistance from abnormal volumes?
Answer: Volume imbalances occur when price moves rapidly on abnormally high volume, creating gaps or zones where institutions moved large amounts quickly. These areas often act as resistance when price returns to them because institutional traders may want to "fill" these gaps or add to their positions at those levels.
The indicator uses PVSRA analysis to identify candles with abnormal volume-to-price ratios and marks these zones on your chart. When price approaches these imbalance areas again, it may encounter resistance from institutional activity or algorithmic trading systems programmed to react at these levels.
What are price multipliers?
Answer: Price multipliers are reference lines showing 2x, 3x, 4x, and 5x the current price. They serve as a reality check when setting your take-profit targets. If you're considering a take-profit at $10 and current price is $2, you can quickly see that's a 5x target and evaluate whether that seems realistic given current market conditions.
These lines help you assess the feasibility of your exit goals and avoid setting unrealistic expectations. They're not resistance levels themselves, but visual aids to help you gauge whether your planned targets are conservative, aggressive, or somewhere in between
How is the EMA calculated and why does it represent bull/bear market intensity?
Answer: The indicator uses a 147-period EMA (1D tf) combined with ADX and DMI indicators to assess market phases. The EMA provides the basic trend direction - when price is above the EMA, it suggests bullish conditions, and when below, bearish conditions.
The intensity comes from the ADX/DMI analysis. Strong bull markets occur when price is above the EMA, ADX is above 25 (indicating strong trend), and the positive directional indicator dominates. Strong bear markets show the opposite pattern with negative directional movement dominating.
The system also uses weekly ADX slope to confirm trend strength is increasing rather than fading. This combination helps distinguish between weak sideways markets and genuine strong trending phases, giving you context at the time of exit planning.
EXIT PLAN
Why does my exit plan show errors?
Answer: The indicator validates your plan in real-time and shows specific error messages to help you fix issues. Common problems include take-profit percentages that don't sum to exactly 100%, price levels set in wrong order (TP2 must be higher than TP1), or gaps in your sequence (you can't use TP3 without filling TP1 and TP2 first).
Check the Exit Plan Validation section in the table - it will show exactly what needs fixing with messages like "TP percentages must sum to exactly 100%" or "Fill TPs consecutively starting from TP1." Fix the highlighted issue and the error will clear automatically, turning your validation checkmark green when everything is correct.
Why do I need to provide my coin quantity and average entry price?
Answer: The coin quantity is essential because the indicator calculates exact amounts to sell at each take-profit level based on your percentages. If you set TP1 to sell 25% of your position, the script needs to know your total quantity to calculate that 25% means exactly X coins in your 3Commas Smart Trade.
The average entry price helps calculate your projected gains and portfolio performance in the Exit Table. If you don't know your exact entry price, leave it at zero and the indicator will use current price as a fallback for calculations. Both pieces of information ensure your Smart Trade matches your actual position size and gives you accurate profit projections.
What is the emergency exit price?
Answer: The emergency exit price is an optional stop-loss feature that automatically sells 100% of your coin position if price falls to your specified level. This is critical to understand because once triggered, 3Commas will execute the sale immediately without further confirmation.
When price hits your emergency exit level, 3Commas places a limit sell order at 3% below that price to avoid poor market execution. However, execution is not guaranteed because limit orders may not fill during extreme volatility or if price gaps below your limit level. Use this feature cautiously and set the emergency price well below normal support levels to account for typical market fluctuations.
This sells your entire position regardless of your take-profit plan, so only enable it if you want automated crash protection and understand the risks of potential false breakdowns triggering unnecessary exits.
3COMMAS CONNECTION
How do I get my 3Commas API keys and Account ID?
Answer:
For API Keys: Log into 3Commas, go to User Profile → 3Commas API → New API Access Token → System Generated. Set permissions to "Smart Trades Only" (leave all other permissions unchecked) and add your IP to the whitelist for security. Save both the public and private keys securely after creation.
For Account ID: Go to My Portfolio → View Exchange in 3Commas. Look at the URL in your browser - the Account ID is the 8-digit number at the end of the webpage address (example: if the URL shows "/accounts/12345678" then your Account ID is 12345678).
Important: Never share these credentials with anyone. The indicator transmits them directly to 3Commas through secure API connections without storing or logging them. If you suspect your keys are compromised, revoke them immediately in your 3Commas account and generate new ones.
ALERTS
I have set up my exit plan, what's next?
Answer: Once your exit plan is configured and shows green checkmarks in the validation section, follow the 4-step workflow in the indicator. Check "Step 1: Check and confirm Exit Plan" to enable alert firing, then create a TradingView alert using the Altcoins Exit Planner PRO condition with "Any alert() function call" trigger.
The alert fires immediately and sends your plan to 3Commas. Within minutes, you should see a new Smart Trade appear in your 3Commas dashboard matching your exact exit strategy. After confirming the Smart Trade was created successfully, delete the TradingView alert to prevent duplicate submissions.
From that point, 3Commas manages your exit automatically according to your plan. Monitor execution through your 3Commas dashboard and let the platform handle the sequential take-profit levels as price moves.
How do I create the TradingView alert?
Answer: Click the "Alert" button in TradingView (bell icon in the top toolbar). In the alert setup window, set Condition to "Altcoins Exit Planner PRO" and Trigger to "Any alert() function call." Keep Interval as "Same as Chart" and Expiration as "Open Ended."
In the Message section, you can name your alert anything you want. In the Notifications section, enable the webhook option (leave the URL field as you'll handle that separately). You can also enable email or sound notifications if desired.
Click "Create" to activate the alert. If Step 1 is already checked in your indicator, the alert will fire immediately and send your exit plan to 3Commas. Remember to delete this alert after your Smart Trade appears to prevent duplicates.
I got the Smart Trade on 3Commas, what's next?
Answer: Congratulations! Your exit plan is now active and automated. Delete the TradingView alert immediately to prevent duplicate Smart Trades from being created. You can now monitor your Smart Trade's progress through your 3Commas dashboard.
3Commas will automatically execute your take-profit levels as price reaches each target, selling the specified percentages of your position according to your plan. If you enabled emergency exit protection, that stop-loss is also active and monitoring for downside protection.
Your job is essentially done - let 3Commas handle the execution while you monitor overall market conditions. You can view trade progress, modify the Smart Trade if needed, or manually close it early through your 3Commas interface. The platform will manage all the sequential selling according to your original exit strategy.
Can I cancel my exit plan and resubmit to 3Commas?
Answer: Yes, you can modify your exit strategy by first deleting the existing Smart Trade in your 3Commas dashboard, then resubmitting a new plan through the indicator.
To cancel and resubmit: Go to your 3Commas Smart Trades section and delete the current trade. Return to the TradingView indicator, modify your exit plan settings (prices, percentages, emergency exit, etc.), then repeat the deployment process by checking Step 1 and creating a new alert.
This creates a fresh Smart Trade with your updated parameters. Always ensure you delete the old Smart Trade first to avoid having multiple conflicting exit plans running simultaneously. The new deployment will overwrite nothing automatically - you must manually clean up the old trade before submitting the revised plan.
Why did I get a second Smart Trade after the first one?
Answer: This happens when you forget to delete the TradingView alert after your first Smart Trade was created successfully. The alert remains active and continues firing, creating duplicate Smart Trades each time it triggers.
Always delete your TradingView alert immediately after confirming your Smart Trade appears in 3Commas. Go to your TradingView alerts list, find the alert you created for this exit plan, and delete it completely. Also delete any duplicate Smart Trades in your 3Commas dashboard to avoid confusion.
To prevent this in future deployments, remember the workflow: create alert → Smart Trade appears → delete alert immediately. Each exit plan should only generate one Smart Trade, and keeping alerts active will cause unwanted duplicates.
------------------------------------------------------------------
7. Limitations and Disclaimer
Limitations:
Doesn't provide trading signals or entry points
Doesn't guarantee resistance levels will hold
Requires manual monitoring of 3Commas execution
Works for exit planning only, not position building
Disclaimer
This indicator is for educational and informational purposes only. It does not constitute financial, investment, or trading advice.
The indicator:
Makes no guarantees about future market performance
Cannot predict market movements with certainty
May generate false indications
Relies on historical patterns that may not repeat
Should not be used as the sole basis for trading decisions
Users are responsible for:
Conducting independent research and analysis
Understanding the risks of cryptocurrency trading
Making their own investment/divestment decisions
Managing position sizes and risk exposure appropriately
Managing API keys and secret codes diligently (do not share with third parties, store them securely, use malware protection on your PC)
Cryptocurrency trading involves substantial risk and may not be suitable for all investors. Past performance does not guarantee future results. Users should only invest what they can afford to lose and consult qualified professionals before making financial decisions.
The indicator’s assumptions may be invalidated by changing market conditions.
By using this tool, users acknowledge these limitations and accept full responsibility for their trading decisions.
Sortable Relative Performance | viResearchSortable Relative Performance | viResearch
Conceptual Foundation and Purpose
The Sortable Relative Performance indicator from viResearch is designed as a multi-asset ranking and comparison system that allows traders to evaluate the relative strength of up to 14 different assets over a user-defined lookback period. Unlike single-symbol indicators, this tool provides a comparative view of performance, making it ideal for traders seeking to understand how assets perform relative to each other within a watchlist, sector, or market segment. The indicator calculates the percentage return of each asset from a chosen starting point and presents the results both graphically and in a sorted, tabular format, helping traders identify outperformers and underperformers at a glance.
Technical Composition and Methodology
At its core, the script calculates the relative performance of each selected asset by comparing its current closing price with the closing price from the lookback period. This performance metric is expressed as a percentage and computed using Pine Script’s request.security() function, allowing for seamless cross-asset analysis within a single pane. Each asset is visually represented as a vertical column, color-coded according to a predefined identity map that reflects common asset branding. The best-performing asset is dynamically labeled on the chart, displaying its name and current return, while a real-time performance table updates and ranks all active assets in descending order based on their return values. The table and columns automatically adjust based on the user’s selection, creating an interactive and responsive comparative dashboard.
Features and Configuration
The indicator includes a customizable date filter, allowing traders to activate the display from a specific start date. This is particularly useful for performance reviews tied to events, such as earnings reports, Fed meetings, or macroeconomic releases. The lookback period is adjustable and determines how far back in time performance is measured, making the tool adaptable to both short-term and long-term strategies. Traders can toggle individual assets on or off, enabling focused analysis on specific coins, stocks, or indices. Up to 14 assets can be analyzed simultaneously, with each one clearly distinguished by unique, branded colors in both the plot and the ranking table. The script intelligently highlights the top performer with a floating label, drawing immediate attention to the strongest asset within the group.
Strategic Use and Application
This indicator is especially valuable for traders employing relative strength or momentum-based strategies. By visualizing asset performance in real time, it becomes easier to rotate capital into strong assets and away from laggards. Whether tracking cryptocurrencies, sectors, or forex pairs, the ability to assess comparative returns without switching charts provides an operational edge. The tool supports portfolio analysis, sector rotation, and cross-market studies, making it suitable for discretionary traders, systematic investors, and even macro analysts looking for a visual breakdown of market behavior.
Conclusion and Practical Value
The Sortable Relative Performance indicator by viResearch delivers a clean and effective way to measure and rank asset performance over time. By combining visual clarity with real-time calculation and dynamic sorting, it offers a powerful lens through which traders can evaluate market leadership and laggard behavior. Its flexibility and modular design ensure it can be integrated into a wide range of strategies and trading styles. Whether you're managing a crypto portfolio or monitoring traditional markets, this tool provides essential insights into where momentum resides and how capital is flowing across assets.
Note: Backtests are based on past results and are not indicative of future performance.
TrendIsYourFriend Strategy (SPY,IWM,VYM,XLK,SPXL,BTC,GOLD,VT...)Personal disclaimer
Don’t trust this strategy. Don’t trust any other model either just because of its author or a backtest curve. Overfitting is an easy trap, and beginners often fall into it. This script isn’t meant to impress you. It’s meant to survive reality. If it does, maybe it will raise questions and you’ll remember it.
Legal disclaimer
Educational purposes only. Not financial advice. Past performance is not indicative of future results.
Strategy description
Long-only, trend-based logic with two entry types (trend continuation or excess-move reversion), dynamic stop-losses, and a VIX filter to avoid turbulent markets.
Minimal number of parameters with enough trades to support robustness.
For backtest, each trade is sized at $10,000 flat (no compounding, to focus on raw model quality and the regularity of its results over time).
Fees = $0 (neutral choice, as brokers differ).
Slippage = $0, deliberate choice: most entries occur on higher timeframes, and some assets start their history on charts at very low prices, which would otherwise distort results.
What makes this script original
Beyond a classical trend calculation, both excess-move entries and dynamic stop-loss exits also rely on trend logic. Except for the VIX filter, everything comes from trend functions, with very few parameters.
Pre-configurations are fixed in the code, allowing sincere performance tracking across a dozen cases over the medium to long term.
Allowed
SPY (ARCA) — 2-hour chart: S&P 500 ETF, most liquid equity benchmark
IWM (ARCA) — Daily chart: Russell 2000 ETF, US small caps
VYM (ARCA) — Daily chart: Vanguard High Dividend Yield ETF
XLK (ARCA) — Daily chart: Technology Select Sector SPDR
SPXL (ARCA) — Daily chart: 3× leveraged S&P 500 ETF
BTCUSD (COINBASE) — 4-hour chart: Bitcoin vs USD
GOLD (TVC) — Daily chart: Gold spot price
VT (ARCA) — Daily chart: Vanguard Total World Stock ETF
PG (NYSE) — Daily chart: Procter & Gamble Co.
CQQQ (ARCA) — Daily chart: Invesco China Technology ETF
EWC (ARCA) — Daily chart: iShares MSCI Canada ETF
EWJ (ARCA) — Daily chart: iShares MSCI Japan ETF
How to use and form an opinion on it
Works only on the pairs above.
Feel free to modify the input parameters (slippage, fees, order size, margins, …) to see how the model behaves under your own conditions
Compare it with a simple Buy & Hold (requires an order size of 100% equity).
You may also want to look at its time-in-market — the share of time your capital is actually at risk.
Finally, let me INSIST on this : let it run live for months before forming an opinion!
Share your thoughts in the comments 🚀 if you’d like to discuss its live performance.
Alpha VolumeThis script is a comprehensive trading toolkit designed to integrate position sizing, risk management, and key data metrics directly onto your chart. It goes beyond a simple volume indicator by providing two interactive tables and a special volume signal to aid in trade planning and analysis.
What It Does
The "Alpha Volume" indicator is a multi-functional tool that helps traders make more informed decisions. Its core components are:
- A Position Size Calculator that dynamically determines how many shares to trade based on your account size, risk tolerance, and different stop-loss strategies.
- A Data Metrics Table that displays essential fundamental information like Market Cap, Industry, Sector, and Float shares.
- An Episodic Pivot (EP) signal that highlights bars with exceptionally high volume, pinpointing potentially significant market events.
Key Features
Dynamic Position Sizing: Automatically calculates the ideal trade size based on various stop-loss points:
- The low or high of the day.
- The midpoint of the current candle.
- Three customizable fixed percentage stop-losses (e.g., 0.75%, 1.00%, 1.25%).
Interactive Risk Management: After you enter a trade, you can input your actual entry price and quantity. The script will then calculate:
- The exact stop-loss price required to meet your predefined risk.
- The distance to your stop-loss in both percentage and currency.
- Up to 10 R-Multiple price targets to help with profit-taking.
On-Chart Fundamental Data: The Data Metrics table provides a quick snapshot of the company's financial health and classification, saving you from switching between screens.
- Episodic Pivot Signal: A simple triangle appears below a daily candle when its volume surpasses a user-defined threshold (e.g., 9 million shares), drawing your attention to stocks under significant accumulation or distribution.
How to Use
Pre-Trade Planning:
- In the indicator settings, enter your Capital and define your Risk per trade (either as a percentage like 0.5% or a fixed currency amount like $5000).
- The "Position Size Table" will instantly show you the quantity you can trade based on different potential stop-loss levels. For example, Q shows the quantity if your stop is the day's low, and SQ shows quantities for fixed percentage stops.
Trade Execution & Management:
- Once you're in a trade, enter your Position Opened (PO) price and Quantity Actual (QA) in the settings.
- The second table will update to show your calculated stop-loss (PC), the distance to it (DA), and your R-Multiple targets (RM), giving you a clear plan for managing the trade.
Market Analysis:
- Use the Episodic Pivot signal on the daily chart to identify stocks experiencing unusual volume, which often precedes significant price moves.
- Glance at the Data Metrics Table to quickly understand the company's size (Market Cap) and business (Industry/Sector).
Cumulative Outperformance | viResearchCumulative Outperformance | viResearch
Conceptual Foundation and Innovation
The "Cumulative Outperformance" indicator by viResearch is a relative strength analysis tool designed to measure an asset’s cumulative performance against a chosen benchmark over a user-defined period. Rooted in comparative return analysis, this indicator allows traders and analysts to assess whether an asset is outperforming or underperforming a broader market or sector, offering insights into trend strength and leadership.
Unlike traditional relative strength indicators that may rely on static ratio comparisons, this script uses cumulative return differentials to provide a more contextual understanding of long-term performance trends. A clean visual representation and dynamic text summary are provided to highlight not only the degree of outperformance but also the directional status — making it accessible to both novice and advanced users.
Technical Composition and Calculation
The indicator compares the cumulative returns of the selected asset and a benchmark symbol over a specified lookback period (length). Returns are calculated as the percent change from the current price to the price length bars ago.
This differential is plotted and color-coded, with a baseline zero line to make outperformance and underperformance visually distinct. A dynamic table in the bottom-right corner displays real-time values for the benchmark symbol, the current outperformance percentage, and a status label (e.g., "Outperforming", "Underperforming", or "Even").
Additionally, a floating label is plotted directly on the chart to make the latest outperformance value immediately visible.
Features and User Inputs
The script includes the following customizable inputs:
Start Date: Defines the point from which to begin tracking outperformance data.
Length: The period over which cumulative returns are measured.
Benchmark Symbol: Select any market index, stock, or crypto as the benchmark (e.g., INDEX:BTCUSD, SPX, etc.).
Practical Applications
This indicator is especially effective in:
Identifying Market Leaders: Compare sectors, stocks, or altcoins against a leading benchmark to identify outperformers.
Sector Rotation Strategies: Monitor when certain assets begin to outperform or lag behind the broader market.
Cross-Market Analysis: Compare crypto pairs, equities, or commodities to their sector benchmarks to find relative strength opportunities.
Visual Aids and Alerts
A purple outperformance line highlights the degree of cumulative difference.
A horizontal dotted white line marks the baseline (zero performance difference).
Real-time table overlay updates the benchmark name, performance delta, and relative status.
Alerts are built-in to notify users when assets begin to outperform or underperform, helping you stay ahead of major shifts.
Advantages and Strategic Value
Benchmark Flexibility: Analyze any asset class against any benchmark of your choice.
Visual Clarity: Dynamic labels and tables make performance tracking intuitive and immediate.
No Repainting: Calculations are based on closed bar data for consistent backtesting and real-time use.
Summary and Usage Tips
The "Cumulative Outperformance | viResearch" script offers a clean and effective way to visualize relative strength between any asset and its benchmark. By focusing on cumulative returns over time, it filters out short-term noise and gives a strategic view of long-term strength or weakness. Use this tool in combination with other momentum or trend-following indicators to refine your market entries and asset selection.
Note: Backtests are based on past results and are not indicative of future performance.
LB PortLag Exit IndicatorAllows you to compare a benchmark against any asset over the last X candles. Simple.
Dynamic Levels This indicator plots key price levels (Open, High, Low, Mid, Close) from multiple higher timeframes (Monday, Daily, Weekly, Monthly, Yearly).
It allows you to track how price interacts with important reference levels without switching timeframes.
🔑 Features
✅ Monday levels (MO, MH, MM)
By default: shows the last completed Monday (fixed values).
Option: “live mode” to update Monday High/Low/Mid while Monday’s candle is forming.
✅ Daily levels (DO, DH, DL, DM, DC)
Live: Daily High/Low/Mid update dynamically while today’s candle is forming.
Previous Daily Close (DC) is always fixed.
✅ Weekly levels (WO, WH, WL, WM)
Live: Weekly High/Low/Mid update dynamically while this week’s candle is forming.
Weekly Open is fixed.
✅ Monthly levels (MO(n), MH(n-1), ML(n-1), MM(n-1), MC(n-1))
Shows last completed month’s values (constant, never changing).
Current Monthly Open is also shown (naturally fixed).
✅ Yearly levels (YO(n), YH(n-1), YL(n-1), YM(n-1), YC(n-1))
Shows last completed year’s values (constant, never changing).
Current Yearly Open is also shown (naturally fixed).
🎨 Customization
Toggle each level (on/off) in indicator settings.
Individual color settings for Monday, Daily, Weekly, Monthly, and Yearly.
Adjustable line width and transparency.
Optional short labels (MO, DO, WM, etc.) displayed on the right side of the chart.
🔄 Dynamic Logic
Daily and Weekly → update dynamically while their candle is forming.
Monday, Monthly, and Yearly → use fixed values from the last completed bar (do not “breathe”).
📌 Use cases
Quickly see where price stands relative to previous close, current open, or mid-levels.
Use Monday Open/High/Mid as strong intraday references.
Use Monthly/Yearly levels as long-term support/resistance zones.
Dynamic Levels: Mon + D/W/M/Y (O/H/L/C/Mid)Purpose!
This Pine Script plots key reference levels (Open,High,Low,Close,Mid) for Monday,Daily,Weekly, Monthly, and Yearly timeframes.
All levels update live while the bar is forming. ( intrabar updates).
USAGE
Add the script to Pine Editor on TradingView (desktop Web)
Save - Add to chart
On mobile app: Find it under indicators - My scripts.
Great for identifying key reaction zones (opens,mids,previous closes).
Pro Volume Lite📘 Pro Volume Lite
What it is:
Pro Volume Lite is a tool that helps you quickly figure out:
How much quantity to buy or sell,
Where your risk stands,
How volume and trend strength are behaving,
Plus some quick company fundamentals.
🔹 1. Position Size & Risk Management
✅ Settings
Trade Direction:
Long → Bullish trades only.
Short → Bearish trades only.
Both → Auto-switch depending on whether today’s price change is up or down.
Capital (CP):
Enter your account size (example: 10,00,000).
This is the base for position size calculations.
Risk Mode (R):
Currency → Risk a fixed amount per trade (e.g., $5000).
Percentage → Risk a fixed % of your capital (e.g., 0.5%).
⚡ The script automatically calculates how much money you’re risking per trade based on your choice.
✅ Stop & Quantity Calculations
D (Stop Low %) → How far today’s close is from the day’s low.
DH (Stop High %) → How far close is from the mid-body of today’s candle.
Q (Quantity) → How many shares you can buy/sell if stop = day’s low.
QH (Quantity High) → Quantity if stop = mid-body.
SSL #1, #2, #3 → Standard stop-loss setups (e.g., 0.75%, 1%, 1.25%).
💡 If you enable Lot Size, all quantities are converted into nearest lot multiples (good for futures).
🔹 2. Volume Bar Coloring
Green = Price closed higher than it opened.
Red = Price closed lower than it opened.
Plots on the volume chart so you can see bullish/bearish volume.
🔹 3. Trend Intensity (TI)
Uses two moving averages (fast & slow).
Green dot on top → Trend strongly bullish.
Red dot on top → Trend strongly bearish.
Helps you spot momentum shifts.
🔹 4. Episodic Pivot (EP)
Marks big volume spikes with orange triangles under candles.
Default threshold = 9 million volume.
Shows when institutions may be entering/exiting.
🔹 5. Data Metrics Table
Quick fundamentals shown in a table:
MC (Market Cap): Company’s total market value.
Industry × Sector: Classification for the stock.
FF (Free Float): Value of shares available for public trading.
💡 In INR stocks → values are shown in Crores.
💡 In USD stocks → values shown in raw currency format.
⚡ Bottom Line
Pro Volume Lite helps you:
Size your trades correctly,
Control your risk,
Spot strong volume moves,
Check quick fundamentals,
All inside your TradingView chart.
Interval Price AlertsInterval Price Alerts
A versatile indicator that creates horizontal price levels with customizable alerts. Perfect for tracking multiple price levels simultaneously without having to create individual horizontal lines manually.
Features:
• Create evenly spaced price levels between a start and end price
• Customizable price interval spacing
• Optional price labels with flexible positioning
• Alert capabilities for both price crossovers and crossunders
• Highly customizable visual settings
Settings Groups:
1. Price Settings
• Start Price: The lower boundary for price levels
• End Price: The upper boundary for price levels
• Price Interval: The spacing between price levels
2. Line Style
• Line Color: Choose any color for the price level lines
• Line Style: Choose between Solid, Dashed, or Dotted lines
• Line Width: Adjustable from 2-4 pixels (optimized for opacity)
• Line Opacity: Control the transparency of lines (0-100%)
3. Label Style
• Show Price Labels: Toggle price labels on/off
• Label Color: Customize label text color
• Label Size: Choose from Tiny, Small, Normal, or Large
• Label Position: Place labels on Left or Right side
• Label Background: Set the background color
• Background Opacity: Control label background transparency
• Text Opacity: Adjust label text transparency
4. Alert Settings
• Alert on Crossover: Enable/disable upward price cross alerts
• Alert on Crossunder: Enable/disable downward price cross alerts
Usage Tips:
• Great for marking key price levels, support/resistance zones
• Useful for tracking multiple entry/exit points
• Perfect for scalping when you need to monitor multiple price levels
• Ideal for pre-market planning and level setting
Notes:
• Line width starts at 2 for optimal opacity rendering
• Labels can be fully customized or hidden completely
• Alert messages include the symbol and price level crossed
Merged Strategy with $1 TP (Avg Price)Merged Strategy with $1 TP (Avg Price)" is a custom Pine Script that combines moving average signals with an averaging technique. It opens trades based on MA crossovers, manages multiple entries, and automatically sets a fixed $1 take-profit target calculated on the average entry price. The strategy is designed for scalpers who want small, consistent gains without using stop-loss.
Sine Weighted Trend Navigator [QuantAlgo]🟢 Overview
The Sine Weighted Trend Navigator utilizes trigonometric mathematics to create a trend-following system that adapts to various market volatility. Unlike traditional moving averages that apply uniform weights, this indicator employs sine wave calculations to distribute weights across historical price data, creating a more responsive yet smooth trend measurement. Combined with volatility-adjusted boundaries, it produces actionable directional signals for traders and investors across various market conditions and asset classes.
🟢 How It Works
At its core, the indicator applies sine wave mathematics to weight historical prices. The system generates angular values across the lookback period and transforms them through sine calculations, creating a weight distribution pattern that naturally emphasizes recent price action while preserving smoothness. The phase shift feature allows rotation of this weighting pattern, enabling adjustment of the indicator's responsiveness to different market conditions.
Surrounding this sine-weighted calculation, the system establishes volatility-responsive boundaries through market volatility analysis. These boundaries expand and contract based on current market conditions, creating a dynamic framework that helps distinguish meaningful trend movements from random price fluctuations.
The trend determination logic compares the sine-weighted value against these adaptive boundaries. When the weighted value exceeds the upper boundary, it signals upward momentum. When it drops below the lower boundary, it indicates downward pressure. This comparison drives the color transitions of the main trend line, shifting between bullish (green) and bearish (red) states to provide clear directional guidance on price charts.
🟢 How to Use
Green/Bullish Trend Line: Rising momentum indicating optimal conditions for long positions (buy)
Red/Bearish Trend Line: Declining momentum signaling favorable timing for short positions (sell)
Steepening Green Line: Accelerating bullish momentum with increasing sine-weighted values indicating strengthening upward pressure and high-probability trend continuation
Steepening Red Line: Intensifying bearish momentum with declining sine-weighted calculations suggesting persistent downward pressure and optimal shorting opportunities
Flattening Trend Lines: Gradual reduction in directional momentum regardless of color may indicate approaching consolidation or trend exhaustion requiring position management review
🟢 Pro Tips for Trading and Investing
→ Preset Strategy Selection: Utilize the built-in presets strategically - Scalping preset for ultra-responsive 1-15 minute charts, Default preset for balanced general trading, and Swing Trading preset for 1-4 hour charts and multi-day positions.
→ Phase Shift Optimization: Fine-tune the phase shift parameter based on market bias - use positive values (0.1-0.5) in trending bull markets to enhance uptrend sensitivity, negative values (-0.1 to -0.5) in bear markets for improved downtrend detection, and zero for balanced neutral market conditions.
→ Multiplier Calibration: Adjust the multiplier according to market volatility and trading style. Use lower values (0.5-1.0) for tight, responsive signals in stable markets, higher values (2.0-3.0) during earnings seasons or high-volatility periods to filter noise and reduce whipsaws.
→ Sine Period Adaptation: Customize the sine weighted period based on your trading timeframe and market conditions. Use 5-14 for day trading to capture short-term momentum shifts, 14-25 for swing trading to balance responsiveness with reliability, and 25-50 for position trading to maintain long-term trend clarity.
→ Multi-Timeframe Sine Validation: Apply the indicator across multiple timeframes simultaneously, using higher timeframes (4H/Daily) for overall trend bias and lower timeframes (15m/1H) for entry timing, ensuring sine-weighted calculations align across different time horizons.
→ Alert-Driven Systematic Execution: Leverage the built-in trend change alerts to eliminate emotional decision-making and capture every mathematically-confirmed trend transition, particularly valuable for traders managing multiple instruments or those unable to monitor charts continuously.
→ Risk Management: Increase position sizes during strong directional sine-weighted momentum while reducing exposure during frequent color changes that indicate mathematical uncertainty or ranging market conditions lacking clear directional bias.
📊 Portafoglio Verticale Personalizzabile (5 Tickers, Net ROI)📊 Customizable Vertical Portfolio (5 Tickers, Net ROI)
Type: Pine Script v6 Indicator (TradingView)
Layout: Vertical table (up to 5 tickers + header)
🔹 Features
Tracks up to 5 tickers simultaneously
Table position selectable (top, middle, bottom; left, center, right)
Customizable colors (header, rows, borders)
Optional header display
🔹 Calculations
For each ticker:
Total cost = Entry price × Qty + Entry commissions
Current value = Current price × Qty – Exit commissions
Net P/L = Current value – Cost – Taxes
Net ROI (%) = (Net P/L ÷ Cost) × 100
🔹 Commission & Tax
Entry/Exit: Fixed or Percentage
CGT: user-defined %, applied only on profits
🔹 Output Table
| Ticker | Net P/L | Net ROI (%) |
Color-coded: Green = Profit, Red = Loss, Silver = Neutral/NA
✅ Best for
Multi-asset tracking in one chart
Real-time evaluation of profits after fees & taxes
Clear, visual portfolio monitoring
Copeland Dynamic Dominance Matrix System | GForgeCopeland Dynamic Dominance Matrix System | GForge - v1
---
📊 COMPREHENSIVE SYSTEM OVERVIEW
The GForge Dynamic BB% TrendSync System represents a revolutionary approach to algorithmic portfolio management, combining cutting-edge statistical analysis, momentum detection, and regime identification into a unified framework. This system processes up to 39 different cryptocurrency assets simultaneously, using advanced mathematical models to determine optimal capital allocation across dynamic market conditions.
Core Innovation: Multi-Dimensional Analysis
Unlike traditional single-asset indicators, this system operates on multiple analytical dimensions:
Momentum Analysis: Dual Bollinger Band Modified Deviation (DBBMD) calculations
Relative Strength: Comprehensive dominance matrix with head-to-head comparisons
Fundamental Screening: Alpha and Beta statistical filtering
Market Regime Detection: Five-component statistical testing framework
Portfolio Optimization: Dynamic weighting and allocation algorithms
Risk Management: Multi-layered protection and regime-based positioning
---
🔧 DETAILED COMPONENT BREAKDOWN
1. Dynamic Bollinger Band % Modified Deviation Engine (DBBMD)
The foundation of this system is an advanced oscillator that combines two independent Bollinger Band systems with asymmetric parameters to create unique momentum readings.
Technical Implementation:
[
// BB System 1: Fast-reacting with extended standard deviation
primary_bb1_ma_len = 40 // Shorter MA for responsiveness
primary_bb1_sd_len = 65 // Longer SD for stability
primary_bb1_mult = 1.0 // Standard deviation multiplier
// BB System 2: Complementary asymmetric design
primary_bb2_ma_len = 8 // Longer MA for trend following
primary_bb2_sd_len = 66 // Shorter SD for volatility sensitivity
primary_bb2_mult = 1.7 // Wider bands for reduced noise
Key Features:
Asymmetric Design: The intentional mismatch between MA and Standard Deviation periods creates unique oscillation characteristics that traditional Bollinger Bands cannot achieve
Percentage Scale: All readings are normalized to 0-100% scale for consistent interpretation across assets
Multiple Combination Modes:
BB1 Only: Fast/reactive system
BB2 Only: Smooth/stable system
Average: Balanced blend (recommended)
Both Required: Conservative (both must agree)
Either One: Aggressive (either can trigger)
Mean Deviation Filter: Additional volatility-based layer that measures the standard deviation of the DBBMD% itself, creating dynamic trigger bands
Signal Generation Logic:
// Primary thresholds
primary_long_threshold = 71 // DBBMD% level for bullish signals
primary_short_threshold = 33 // DBBMD% level for bearish signals
// Mean Deviation creates dynamic bands around these thresholds
upper_md_band = combined_bb + (md_mult * bb_std)
lower_md_band = combined_bb - (md_mult * bb_std)
// Signal triggers when DBBMD crosses these dynamic bands
long_signal = lower_md_band > long_threshold
short_signal = upper_md_band < short_threshold
For more information on this BB% indicator, find it here:
2. Revolutionary Dominance Matrix System
This is the system's most sophisticated innovation - a comprehensive framework that compares every asset against every other asset to determine relative strength hierarchies.
Mathematical Foundation:
The system constructs a mathematical matrix where each cell represents whether asset i dominates asset j:
// Core dominance matrix (39x39 for maximum assets)
var matrix dominance_matrix = matrix.new(39, 39, 0)
// For each qualifying asset pair (i,j):
for i = 0 to active_count - 1
for j = 0 to active_count - 1
if i != j
// Calculate price ratio BB% TrendSync for asset_i/asset_j
ratio_array = calculate_price_ratios(asset_i, asset_j)
ratio_dbbmd = calculate_dbbmd(ratio_array)
// Asset i dominates j if ratio is in uptrend
if ratio_dbbmd_state == 1
matrix.set(dominance_matrix, i, j, 1)
Copeland Scoring Algorithm:
Each asset receives a dominance score calculated as:
Dominance Score = Total Wins - Total Losses
// Calculate net dominance for each asset
for i = 0 to active_count - 1
wins = 0
losses = 0
for j = 0 to active_count - 1
if i != j
if matrix.get(dominance_matrix, i, j) == 1
wins += 1
else
losses += 1
copeland_score = wins - losses
array.set(dominance_scores, i, copeland_score)
Head-to-Head Analysis Process:
Ratio Construction: For each asset pair, calculate price_asset_A / price_asset_B
DBBMD Application: Apply the same DBBMD analysis to these ratios
Trend Determination: If ratio DBBMD shows uptrend, Asset A dominates Asset B
Matrix Population: Store dominance relationships in mathematical matrix
Score Calculation: Sum wins minus losses for final ranking
This creates a tournament-style ranking where each asset's strength is measured against all others, not just against a benchmark.
3. Advanced Alpha & Beta Filtering System
The system incorporates fundamental analysis through Capital Asset Pricing Model (CAPM) calculations to filter assets based on risk-adjusted performance.
Alpha Calculation (Excess Return Analysis):
// CAPM Alpha calculation
f_calc_alpha(asset_prices, benchmark_prices, alpha_length, beta_length, risk_free_rate) =>
// Calculate asset and benchmark returns
asset_returns = calculate_returns(asset_prices, alpha_length)
benchmark_returns = calculate_returns(benchmark_prices, alpha_length)
// Get beta for expected return calculation
beta = f_calc_beta(asset_prices, benchmark_prices, beta_length)
// Average returns over period
avg_asset_return = array_average(asset_returns) * 100
avg_benchmark_return = array_average(benchmark_returns) * 100
// Expected return using CAPM: E(R) = Beta * Market_Return + Risk_Free_Rate
expected_return = beta * avg_benchmark_return + risk_free_rate
// Alpha = Actual Return - Expected Return
alpha = avg_asset_return - expected_return
Beta Calculation (Volatility Relationship):
// Beta measures how much an asset moves relative to benchmark
f_calc_beta(asset_prices, benchmark_prices, length) =>
// Calculate return series for both assets
asset_returns =
benchmark_returns =
// Populate return arrays
for i = 0 to length - 1
asset_return = (current_price - previous_price) / previous_price
benchmark_return = (current_bench - previous_bench) / previous_bench
// Calculate covariance and variance
covariance = calculate_covariance(asset_returns, benchmark_returns)
benchmark_variance = calculate_variance(benchmark_returns)
// Beta = Covariance(Asset, Market) / Variance(Market)
beta = covariance / benchmark_variance
Filtering Applications:
Alpha Filter: Only includes assets with alpha above specified threshold (e.g., >0.5% monthly excess return)
Beta Filter: Screens for desired volatility characteristics (e.g., beta >1.0 for aggressive assets)
Combined Screening: Both filters must pass for asset qualification
Dynamic Thresholds: User-configurable parameters for different market conditions
4. Intelligent Tie-Breaking Resolution System
When multiple assets have identical dominance scores, the system employs sophisticated methods to determine final rankings.
Standard Tie-Breaking Hierarchy:
// Primary tie-breaking logic
if score_i == score_j // Tied dominance scores
// Level 1: Compare Beta values (higher beta wins)
beta_i = array.get(beta_values, i)
beta_j = array.get(beta_values, j)
if beta_j > beta_i
swap_positions(i, j)
else if beta_j == beta_i
// Level 2: Compare Alpha values (higher alpha wins)
alpha_i = array.get(alpha_values, i)
alpha_j = array.get(alpha_values, j)
if alpha_j > alpha_i
swap_positions(i, j)
Advanced Tie-Breaking (Head-to-Head Analysis):
For the top 3 performers, an enhanced tie-breaking mechanism analyzes direct head-to-head price ratio performance:
// Advanced tie-breaker for top performers
f_advanced_tiebreaker(asset1_idx, asset2_idx, lookback_period) =>
// Calculate price ratio over lookback period
ratio_history =
for k = 0 to lookback_period - 1
price_ratio = price_asset1 / price_asset2
array.push(ratio_history, price_ratio)
// Apply simplified trend analysis to ratio
current_ratio = array.get(ratio_history, 0)
average_ratio = calculate_average(ratio_history)
// Asset 1 wins if current ratio > average (trending up)
if current_ratio > average_ratio
return 1 // Asset 1 dominates
else
return -1 // Asset 2 dominates
5. Five-Component Aggregate Market Regime Filter
This sophisticated framework combines multiple statistical tests to determine whether market conditions favor trending strategies or require defensive positioning.
Component 1: Augmented Dickey-Fuller (ADF) Test
Tests for unit root presence to distinguish between trending and mean-reverting price series.
// Simplified ADF implementation
calculate_adf_statistic(price_series, lookback) =>
// Calculate first differences
differences =
for i = 0 to lookback - 2
diff = price_series - price_series
array.push(differences, diff)
// Statistical analysis of differences
mean_diff = calculate_mean(differences)
std_diff = calculate_standard_deviation(differences)
// ADF statistic approximation
adf_stat = mean_diff / std_diff
// Compare against threshold for trend determination
is_trending = adf_stat <= adf_threshold
Component 2: Directional Movement Index (DMI)
Classic Wilder indicator measuring trend strength through directional movement analysis.
// DMI calculation for trend strength
calculate_dmi_signal(high_data, low_data, close_data, period) =>
// Calculate directional movements
plus_dm_sum = 0.0
minus_dm_sum = 0.0
true_range_sum = 0.0
for i = 1 to period
// Directional movements
up_move = high_data - high_data
down_move = low_data - low_data
// Accumulate positive/negative movements
if up_move > down_move and up_move > 0
plus_dm_sum += up_move
if down_move > up_move and down_move > 0
minus_dm_sum += down_move
// True range calculation
true_range_sum += calculate_true_range(i)
// Calculate directional indicators
di_plus = 100 * plus_dm_sum / true_range_sum
di_minus = 100 * minus_dm_sum / true_range_sum
// ADX calculation
dx = 100 * math.abs(di_plus - di_minus) / (di_plus + di_minus)
adx = dx // Simplified for demonstration
// Trending if ADX above threshold
is_trending = adx > dmi_threshold
Component 3: KPSS Stationarity Test
Complementary test to ADF that examines stationarity around trend components.
// KPSS test implementation
calculate_kpss_statistic(price_series, lookback, significance_level) =>
// Calculate mean and variance
series_mean = calculate_mean(price_series, lookback)
series_variance = calculate_variance(price_series, lookback)
// Cumulative sum of deviations
cumulative_sum = 0.0
cumsum_squared_sum = 0.0
for i = 0 to lookback - 1
deviation = price_series - series_mean
cumulative_sum += deviation
cumsum_squared_sum += math.pow(cumulative_sum, 2)
// KPSS statistic
kpss_stat = cumsum_squared_sum / (lookback * lookback * series_variance)
// Compare against critical values
critical_value = significance_level == 0.01 ? 0.739 :
significance_level == 0.05 ? 0.463 : 0.347
is_trending = kpss_stat >= critical_value
Component 4: Choppiness Index
Measures market directionality using fractal dimension analysis of price movement.
// Choppiness Index calculation
calculate_choppiness(price_data, period) =>
// Find highest and lowest over period
highest = price_data
lowest = price_data
true_range_sum = 0.0
for i = 0 to period - 1
if price_data > highest
highest := price_data
if price_data < lowest
lowest := price_data
// Accumulate true range
if i > 0
true_range = calculate_true_range(price_data, i)
true_range_sum += true_range
// Choppiness calculation
range_high_low = highest - lowest
choppiness = 100 * math.log10(true_range_sum / range_high_low) / math.log10(period)
// Trending if choppiness below threshold (typically 61.8)
is_trending = choppiness < 61.8
Component 5: Hilbert Transform Analysis
Phase-based cycle detection and trend identification using mathematical signal processing.
// Hilbert Transform trend detection
calculate_hilbert_signal(price_data, smoothing_period, filter_period) =>
// Smooth the price data
smoothed_price = calculate_moving_average(price_data, smoothing_period)
// Calculate instantaneous phase components
// Simplified implementation for demonstration
instant_phase = smoothed_price
delayed_phase = calculate_moving_average(price_data, filter_period)
// Compare instantaneous vs delayed signals
phase_difference = instant_phase - delayed_phase
// Trending if instantaneous leads delayed
is_trending = phase_difference > 0
Aggregate Regime Determination:
// Combine all five components
regime_calculation() =>
trending_count = 0
total_components = 0
// Test each enabled component
if enable_adf and adf_signal == 1
trending_count += 1
if enable_adf
total_components += 1
// Repeat for all five components...
// Calculate trending proportion
trending_proportion = trending_count / total_components
// Market is trending if proportion above threshold
regime_allows_trading = trending_proportion >= regime_threshold
The system only allows asset positions when the specified percentage of components indicate trending conditions. During choppy or mean-reverting periods, the system automatically positions in USD to preserve capital.
6. Dynamic Portfolio Weighting Framework
Six sophisticated allocation methodologies provide flexibility for different market conditions and risk preferences.
Weighting Method Implementations:
1. Equal Weight Distribution:
// Simple equal allocation
if weighting_mode == "Equal Weight"
weight_per_asset = 1.0 / selection_count
for i = 0 to selection_count - 1
array.push(weights, weight_per_asset)
2. Linear Dominance Scaling:
// Linear scaling based on dominance scores
if weighting_mode == "Linear Dominance"
// Normalize scores to 0-1 range
min_score = array.min(dominance_scores)
max_score = array.max(dominance_scores)
score_range = max_score - min_score
total_weight = 0.0
for i = 0 to selection_count - 1
score = array.get(dominance_scores, i)
normalized = (score - min_score) / score_range
weight = 1.0 + normalized * concentration_factor
array.push(weights, weight)
total_weight += weight
// Normalize to sum to 1.0
for i = 0 to selection_count - 1
current_weight = array.get(weights, i)
array.set(weights, i, current_weight / total_weight)
3. Conviction Score (Exponential):
// Exponential scaling for high conviction
if weighting_mode == "Conviction Score"
// Combine dominance score with DBBMD strength
conviction_scores =
for i = 0 to selection_count - 1
dominance = array.get(dominance_scores, i)
dbbmd_strength = array.get(dbbmd_values, i)
conviction = dominance + (dbbmd_strength - 50) / 25
array.push(conviction_scores, conviction)
// Exponential weighting
total_weight = 0.0
for i = 0 to selection_count - 1
conviction = array.get(conviction_scores, i)
normalized = normalize_score(conviction)
weight = math.pow(1 + normalized, concentration_factor)
array.push(weights, weight)
total_weight += weight
// Final normalization
normalize_weights(weights, total_weight)
Advanced Features:
Minimum Position Constraint: Prevents dust allocations below specified threshold
Concentration Factor: Adjustable parameter controlling weight distribution aggressiveness
Dominance Boost: Extra weight for assets exceeding specified dominance thresholds
Dynamic Rebalancing: Automatic weight recalculation on portfolio changes
7. Intelligent USD Management System
The system treats USD as a competing asset with its own dominance score, enabling sophisticated cash management.
USD Scoring Methodologies:
Smart Competition Mode (Recommended):
f_calculate_smart_usd_dominance() =>
usd_wins = 0
// USD beats assets in downtrends or weak uptrends
for i = 0 to active_count - 1
asset_state = get_asset_state(i)
asset_dbbmd = get_asset_dbbmd(i)
// USD dominates shorts and weak longs
if asset_state == -1 or (asset_state == 1 and asset_dbbmd < long_threshold)
usd_wins += 1
// Calculate Copeland-style score
base_score = usd_wins - (active_count - usd_wins)
// Boost during weak market conditions
qualified_assets = count_qualified_long_assets()
if qualified_assets <= active_count * 0.2
base_score := math.round(base_score * usd_boost_factor)
base_score
Auto Short Count Mode:
// USD dominance based on number of bearish assets
usd_dominance = count_assets_in_short_state()
// Apply boost during low activity
if qualified_long_count <= active_count * 0.2
usd_dominance := usd_dominance * usd_boost_factor
Regime-Based USD Positioning:
When the five-component regime filter indicates unfavorable conditions, the system automatically overrides all asset signals and positions 100% in USD, protecting capital during choppy markets.
8. Multi-Asset Infrastructure & Data Management
The system maintains comprehensive data structures for up to 39 assets simultaneously.
Data Collection Framework:
// Full OHLC data matrices (200 bars depth for performance)
var matrix open_data = matrix.new(39, 200, na)
var matrix high_data = matrix.new(39, 200, na)
var matrix low_data = matrix.new(39, 200, na)
var matrix close_data = matrix.new(39, 200, na)
// Real-time data collection
if barstate.isconfirmed
for i = 0 to active_count - 1
ticker = array.get(assets, i)
= request.security(ticker, timeframe.period,
[open , high , low , close ],
lookahead=barmerge.lookahead_off)
// Store in matrices with proper shifting
matrix.set(open_data, i, 0, nz(o, 0))
matrix.set(high_data, i, 0, nz(h, 0))
matrix.set(low_data, i, 0, nz(l, 0))
matrix.set(close_data, i, 0, nz(c, 0))
Asset Configuration:
The system comes pre-configured with 39 major cryptocurrency pairs across multiple exchanges:
Major Pairs: BTC, ETH, XRP, SOL, DOGE, ADA, etc.
Exchange Coverage: Binance, KuCoin, MEXC for optimal liquidity
Configurable Count: Users can activate 2-39 assets based on preferences
Custom Tickers: All asset selections are user-modifiable
---
⚙️ COMPREHENSIVE CONFIGURATION GUIDE
Portfolio Management Settings
Maximum Portfolio Size (1-10):
Conservative (1-2): High concentration, captures strong trends
Balanced (3-5): Moderate diversification with trend focus
Diversified (6-10): Lower concentration, broader market exposure
Dominance Clarity Threshold (0.1-1.0):
Low (0.1-0.4): Prefers diversification, holds multiple assets frequently
Medium (0.5-0.7): Balanced approach, context-dependent allocation
High (0.8-1.0): Concentration-focused, single asset preference
Signal Generation Parameters
DBBMD Thresholds:
// Standard configuration
primary_long_threshold = 71 // Conservative: 75+, Aggressive: 65-70
primary_short_threshold = 33 // Conservative: 25-30, Aggressive: 35-40
// BB System parameters
bb1_ma_len = 40 // Fast system: 20-50
bb1_sd_len = 65 // Stability: 50-80
bb2_ma_len = 8 // Trend: 60-100
bb2_sd_len = 66 // Sensitivity: 10-20
Risk Management Configuration
Alpha/Beta Filters:
Alpha Threshold: 0.0-2.0% (higher = more selective)
Beta Threshold: 0.5-2.0 (1.0+ for aggressive assets)
Calculation Periods: 20-50 bars (longer = more stable)
Regime Filter Settings:
Trending Threshold: 0.3-0.8 (higher = stricter trend requirements)
Component Lookbacks: 30-100 bars (balance responsiveness vs stability)
Enable/Disable: Individual component control for customization
---
📊 PERFORMANCE TRACKING & VISUALIZATION
Real-Time Dashboard Features
The compact dashboard provides essential information:
Current Holdings: Asset names and allocation percentages
Dominance Score: Current position's relative strength ranking
Active Assets: Qualified long signals vs total asset count
Returns: Total portfolio performance percentage
Maximum Drawdown: Peak-to-trough decline measurement
Trade Count: Total portfolio transitions executed
Regime Status: Current market condition assessment
Comprehensive Ranking Table
The left-side table displays detailed asset analysis:
Ranking Position: Numerical order by dominance score
Asset Symbol: Clean ticker identification with color coding
Dominance Score: Net wins minus losses in head-to-head comparisons
Win-Loss Record: Detailed breakdown of dominance relationships
DBBMD Reading: Current momentum percentage with threshold highlighting
Alpha/Beta Values: Fundamental analysis metrics when filters enabled
Portfolio Weight: Current allocation percentage in signal portfolio
Execution Status: Visual indicator of actual holdings vs signals
Visual Enhancement Features
Color-Coded Assets: 39 distinct colors for easy identification
Regime Background: Red tinting during unfavorable market conditions
Dynamic Equity Curve: Portfolio value plotted with position-based coloring
Status Indicators: Symbols showing execution vs signal states
---
🔍 ADVANCED TECHNICAL FEATURES
State Persistence System
The system maintains asset states across bars to prevent excessive switching:
// State tracking for each asset and ratio combination
var array asset_states = array.new(1560, 0) // 39 * 40 ratios
// State changes only occur on confirmed threshold breaks
if long_crossover and current_state != 1
current_state := 1
array.set(asset_states, asset_index, 1)
else if short_crossover and current_state != -1
current_state := -1
array.set(asset_states, asset_index, -1)
Transaction Cost Integration
Realistic modeling of trading expenses:
// Transaction cost calculation
transaction_fee = 0.4 // Default 0.4% (fees + slippage)
// Applied on portfolio transitions
if should_execute_transition
was_holding_assets = check_current_holdings()
will_hold_assets = check_new_signals()
// Charge fees for meaningful transitions
if transaction_fee > 0 and (was_holding_assets or will_hold_assets)
fee_amount = equity * (transaction_fee / 100)
equity -= fee_amount
total_fees += fee_amount
Dynamic Memory Management
Optimized data structures for performance:
200-Bar History: Sufficient for calculations while maintaining speed
Matrix Operations: Efficient storage and retrieval of multi-asset data
Array Recycling: Memory-conscious data handling for long-running backtests
Conditional Calculations: Skip unnecessary computations during initialization
12H 30 assets portfolio
---
🚨 SYSTEM LIMITATIONS & TESTING STATUS
CURRENT DEVELOPMENT PHASE: ACTIVE TESTING & OPTIMIZATION
This system represents cutting-edge algorithmic trading technology but remains in continuous development. Key considerations:
Known Limitations:
Requires significant computational resources for 39-asset analysis
Performance varies significantly across different market conditions
Complex parameter interactions may require extensive optimization
Slippage and liquidity constraints not fully modeled for all assets
No consideration for market impact in large position sizes
Areas Under Active Development:
Enhanced regime detection algorithms
Improved transaction cost modeling
Additional portfolio weighting methodologies
Machine learning integration for parameter optimization
Cross-timeframe analysis capabilities
---
🔒 ANTI-REPAINTING ARCHITECTURE & LIVE TRADING READINESS
One of the most critical aspects of any trading system is ensuring that signals and calculations are based on confirmed, historical data rather than current bar information that can change throughout the trading session. This system implements comprehensive anti-repainting measures to ensure 100% reliability for live trading .
The Repainting Problem in Trading Systems
Repainting occurs when an indicator uses current, unconfirmed bar data in its calculations, causing:
False Historical Signals: Backtests appear better than reality because calculations change as bars develop
Live Trading Failures: Signals that looked profitable in testing fail when deployed in real markets
Inconsistent Results: Different results when running the same indicator at different times during a trading session
Misleading Performance: Inflated win rates and returns that cannot be replicated in practice
GForge Anti-Repainting Implementation
This system eliminates repainting through multiple technical safeguards:
1. Historical Data Usage for All Calculations
// CRITICAL: All calculations use PREVIOUS bar data (note the offset)
= request.security(ticker, timeframe.period,
[open , high , low , close , close],
lookahead=barmerge.lookahead_off)
// Store confirmed previous bar OHLC for calculations
matrix.set(open_data, i, 0, nz(o1, 0)) // Previous bar open
matrix.set(high_data, i, 0, nz(h1, 0)) // Previous bar high
matrix.set(low_data, i, 0, nz(l1, 0)) // Previous bar low
matrix.set(close_data, i, 0, nz(c1, 0)) // Previous bar close
// Current bar close only for visualization
matrix.set(current_prices, i, 0, nz(c0, 0)) // Live price display
2. Confirmed Bar State Processing
// Only process data when bars are confirmed and closed
if barstate.isconfirmed
// All signal generation and portfolio decisions occur here
// using only historical, unchanging data
// Shift historical data arrays
for i = 0 to active_count - 1
for bar = math.min(data_bars, 199) to 1
// Move confirmed data through historical matrices
old_data = matrix.get(close_data, i, bar - 1)
matrix.set(close_data, i, bar, old_data)
// Process new confirmed bar data
calculate_all_signals_and_dominance()
3. Lookahead Prevention
// Explicit lookahead prevention in all security calls
request.security(ticker, timeframe.period, expression,
lookahead=barmerge.lookahead_off)
// This ensures no future data can influence current calculations
// Essential for maintaining signal integrity across all timeframes
4. State Persistence with Historical Validation
// Asset states only change based on confirmed threshold breaks
// using historical data that cannot change
var array asset_states = array.new(1560, 0)
// State changes use only confirmed, previous bar calculations
if barstate.isconfirmed
=
f_calculate_enhanced_dbbmd(confirmed_price_array, ...)
// Only update states after bar confirmation
if long_crossover_confirmed and current_state != 1
current_state := 1
array.set(asset_states, asset_index, 1)
Live Trading vs. Backtesting Consistency
The system's architecture ensures identical behavior in both environments:
Backtesting Mode:
Uses historical offset data for all calculations
Processes confirmed bars with `barstate.isconfirmed`
Maintains identical signal generation logic
No access to future information
Live Trading Mode:
Uses same historical offset data structure
Waits for bar confirmation before signal updates
Identical mathematical calculations and thresholds
Real-time price display without affecting signals
Technical Implementation Details
Data Collection Timing
// Example of proper data collection timing
if barstate.isconfirmed // Wait for bar to close
// Collect PREVIOUS bar's confirmed OHLC data
for i = 0 to active_count - 1
ticker = array.get(assets, i)
// Get confirmed previous bar data (note offset)
=
request.security(ticker, timeframe.period,
[open , high , low , close , close],
lookahead=barmerge.lookahead_off)
// ALL calculations use prev_* values
// current_close only for real-time display
portfolio_calculations_use_previous_bar_data()
Signal Generation Process
// Signal generation workflow (simplified)
if barstate.isconfirmed and data_bars >= minimum_required_bars
// Step 1: Calculate DBBMD using historical price arrays
for i = 0 to active_count - 1
historical_prices = get_confirmed_price_history(i) // Uses offset data
= calculate_dbbmd(historical_prices)
update_asset_state(i, state)
// Step 2: Build dominance matrix using confirmed data
calculate_dominance_relationships() // All historical data
// Step 3: Generate portfolio signals
new_portfolio = generate_target_portfolio() // Based on confirmed calculations
// Step 4: Compare with previous signals for changes
if portfolio_signals_changed()
execute_portfolio_transition()
Verification Methods for Users
Users can verify the anti-repainting behavior through several methods:
1. Historical Replay Test
Run the indicator on historical data
Note signal timing and portfolio changes
Replay the same period - signals should be identical
No retroactive changes in historical signals
2. Intraday Consistency Check
Load indicator during active trading session
Observe that previous day's signals remain unchanged
Only current day's final bar should show potential signal changes
Refresh indicator - historical signals should be identical
Live Trading Deployment Considerations
Data Quality Assurance
Exchange Connectivity: Ensure reliable data feeds for all 39 assets
Missing Data Handling: System includes safeguards for data gaps
Price Validation: Automatic filtering of obvious price errors
Timeframe Synchronization: All assets synchronized to same bar timing
Performance Impact of Anti-Repainting Measures
The robust anti-repainting implementation requires additional computational resources:
Memory Usage: 200-bar historical data storage for 39 assets
Processing Delay: Signals update only after bar confirmation
Calculation Overhead: Multiple historical data validations
Alert Timing: Slight delay compared to current-bar indicators
However, these trade-offs are essential for reliable live trading performance and accurate backtesting results.
Critical: Equity Curve Anti-Repainting Architecture
The most sophisticated aspect of this system's anti-repainting design is the temporal separation between signal generation and performance calculation . This creates a realistic trading simulation that perfectly matches live trading execution.
The Timing Sequence
// STEP 1: Store what we HELD during the current bar (for performance calc)
if barstate.isconfirmed
// Record positions that were active during this bar
array.clear(held_portfolio)
array.clear(held_weights)
for i = 0 to array.size(execution_portfolio) - 1
array.push(held_portfolio, array.get(execution_portfolio, i))
array.push(held_weights, array.get(execution_weights, i))
// STEP 2: Calculate performance based on what we HELD
portfolio_return = 0.0
for i = 0 to array.size(held_portfolio) - 1
held_asset = array.get(held_portfolio, i)
held_weight = array.get(held_weights, i)
// Performance from current_price vs reference_price
// This is what we ACTUALLY earned during this bar
if held_asset != "USD"
current_price = get_current_price(held_asset) // End of bar
reference_price = get_reference_price(held_asset) // Start of bar
asset_return = (current_price - reference_price) / reference_price
portfolio_return += asset_return * held_weight
// STEP 3: Apply return to equity (realistic timing)
equity := equity * (1 + portfolio_return)
// STEP 4: Generate NEW signals for NEXT period (using confirmed data)
= f_generate_target_portfolio()
// STEP 5: Execute transitions if signals changed
if signal_changed
// Update execution_portfolio for NEXT bar
array.clear(execution_portfolio)
array.clear(execution_weights)
for i = 0 to array.size(new_signal_portfolio) - 1
array.push(execution_portfolio, array.get(new_signal_portfolio, i))
array.push(execution_weights, array.get(new_signal_weights, i))
Why This Prevents Equity Curve Repainting
Performance Attribution: Returns are calculated based on positions that were **actually held** during each bar, not future signals
Signal Timing: New signals are generated **after** performance calculation, affecting only **future** bars
Realistic Execution: Mimics real trading where you earn returns on current positions while planning future moves
No Retroactive Changes: Once a bar closes, its performance contribution to equity is permanent and unchangeable
The One-Bar Offset Mechanism
This system implements a critical one-bar timing offset:
// Bar N: Performance Calculation
// ================================
// 1. Calculate returns on positions held during Bar N
// 2. Update equity based on actual holdings during Bar N
// 3. Plot equity point for Bar N (based on what we HELD)
// Bar N: Signal Generation
// ========================
// 4. Generate signals for Bar N+1 (using confirmed Bar N data)
// 5. Send alerts for what will be held during Bar N+1
// 6. Update execution_portfolio for Bar N+1
// Bar N+1: The Cycle Continues
// =============================
// 1. Performance calculated on positions from Bar N signals
// 2. New signals generated for Bar N+2
Alert System Timing
The alert system reflects this sophisticated timing:
Transaction Cost Realism
Even transaction costs follow realistic timing:
// Fees applied when transitioning between different portfolios
if should_execute_transition
// Charge fees BEFORE taking new positions (realistic timing)
if transaction_fee > 0
fee_amount = equity * (transaction_fee / 100)
equity -= fee_amount // Immediate cost impact
total_fees += fee_amount
// THEN update to new portfolio
update_execution_portfolio(new_signals)
transitions += 1
// Fees reduce equity immediately, affecting all future calculations
// This matches real trading where fees are deducted upon execution
LIVE TRADING CERTIFICATION:
This system has been specifically designed and tested for live trading deployment. The comprehensive anti-repainting measures ensure that:
Backtesting results accurately represent real trading potential
Signals are generated using only confirmed, historical data
No retroactive changes can occur to previously generated signals
Portfolio transitions are based on reliable, unchanging calculations
Performance metrics reflect realistic trading outcomes including proper timing
Users can deploy this system with confidence that live trading results will closely match backtesting performance, subject to normal market execution factors such as slippage and liquidity.
---
⚡ ALERT SYSTEM & AUTOMATION
The system provides comprehensive alerting for automation and monitoring:
Available Alert Conditions
Portfolio Signal Change: Triggered when new portfolio composition is generated
Regime Override Active: Alerts when market regime forces USD positioning
Individual Asset Signals: Can be configured for specific asset transitions
Performance Thresholds: Drawdown or return-based notifications
---
📈 BACKTESTING & PERFORMANCE ANALYSIS
8 Comprehensive Metrics Tracking
The system maintains detailed performance statistics:
Equity Curve: Real-time portfolio value progression
Returns Calculation: Total and annualized performance metrics
Drawdown Analysis: Peak-to-trough decline measurements
Transaction Counting: Portfolio transition frequency
Fee Tracking: Cumulative transaction cost impact
Win Rate Analysis: Success rate of position changes
Backtesting Configuration
// Backtesting parameters
initial_capital = 10000.0 // Starting capital
use_custom_start = true // Enable specific start date
custom_start = timestamp("2023-09-01") // Backtest beginning
transaction_fee = 0.4 // Combined fees and slippage %
// Performance calculation
total_return = (equity - initial_capital) / initial_capital * 100
current_drawdown = (peak_equity - equity) / peak_equity * 100
---
🔧 TROUBLESHOOTING & OPTIMIZATION
Common Configuration Issues
Insufficient Data: Ensure 100+ bars available before start date
[*} Not Compiling: Go on an asset's price chart with 2 or 3 years of data to
make the system compile or just simply reapply the indicator again
Too Many Assets: Reduce active count if experiencing timeouts
Regime Filter Too Strict: Lower trending threshold if always in USD
Excessive Switching: Increase MD multiplier or adjust thresholds
---
💡 USER FEEDBACK & ENHANCEMENT REQUESTS
The continuous evolution of this system depends heavily on user experience and community feedback. Your insights will help motivate me for new improvements and new feature developments.
---
⚖️ FINAL COMPREHENSIVE RISK DISCLAIMER
TRADING INVOLVES SUBSTANTIAL RISK OF LOSS
This indicator is a sophisticated analytical tool designed for educational and research purposes. Important warnings and considerations:
System Limitations:
No algorithmic system can guarantee profitable outcomes
Complex systems may fail in unexpected ways during extreme market events
Historical backtesting does not account for all real-world trading challenges
Slippage, liquidity constraints, and market impact can significantly affect results
System parameters require careful optimization and ongoing monitoring
The creator and distributor of this indicator assume no liability for any financial losses, system failures, or adverse outcomes resulting from its use. This tool is provided "as is" without any warranties, express or implied.
By using this indicator, you acknowledge that you have read, understood, and agreed to assume all risks associated with algorithmic trading and cryptocurrency investments.
Zakaat CalculatorZakaat Calculator
The Zakaat Calculator is a dedicated tool designed to assist with transparent and structured wealth assessments based on Islamic finance principles. This script dynamically references live gold and silver prices, applies Nisab thresholds, and evaluates whether Zakaat is obligatory based on the user’s net worth.
Core Features
Live market data: Automatically fetches daily gold and silver prices (TVC:GOLD & TVC:SILVER).
Nisab thresholds: Choose between the gold standard (85g) or silver standard (595g) to set the eligibility baseline.
Flexible inputs: Enter your current holdings across gold, silver, investments, and cash.
Automated calculation: Compares your total net worth against the selected Nisab threshold and calculates the payable Zakaat at a customizable percentage (default 2.5%).
Clear visualization: Results are displayed in a structured on-chart table for full transparency, including thresholds, holdings, total net worth, and final Zakaat due.
Practical Use
This tool is built for individuals who want a precise, real-time view of their Zakaat obligations. By combining faith-based calculation rules with live market data, it ensures accuracy and ease of use.
Note
This indicator is designed for educational and personal financial planning purposes. It may also be used for broader applications such as donations or calculating contributions towards charitable causes. Always consult with qualified scholars or financial advisors for personal guidance.
Altcoins Exit Planner [SwissAlgo]Altcoins Exit Planner
Navigating Altcoin Exits: A Strategic Approach: Planning your exits before emotions take over
------------------------------------------------------------------
✅ THE PSYCHOLOGY OF ALTCOIN TRADING
Many traders face recurring challenges when managing altcoin positions:
The Greed Trap : Holding through euphoric rallies, hoping for unrealistic targets, only to watch gains evaporate during market reversals.
The Paralysis Problem : Sitting on large unrealized profits but unsure which assets to exit, when, or how much — leading to inaction.
The FOMO Cycle : Rotating into trending coins too early or too late, often abandoning solid positions prematurely.
Analysis Overload : Consuming endless opinions and indicators without ever forming a clear, actionable exit strategy.
These patterns often stem from a lack of structure and planning . Emotional decision-making in volatile markets can be costly — especially with altcoins.
Developing a systematic framework can help define exit levels in advance , aiming to reduce emotional bias and improve decision clarity. The goal is to build disciplined exit strategies based on predefined logic rather than reactive impulses.
------------------------------------------------------------------
✅ FEATURES & FUNCTIONALITY
This indicator is designed to provide traders with a structured framework for exit planning. It aims to reduce decision-making under pressure by offering a visual roadmap on the chart.
The tool provides an analysis of key data points, including:
Structured Analysis : The indicator evaluates asset strength, identifies potential market phases, and derives potential exit levels from historical price behavior. This analysis may help traders assess whether an asset shows characteristics of strength (e.g., potential for extended targets) or weakness (e.g., early exit signals).
Actionable Information : It generates specific price levels and quantities for consideration as part of a predefined exit strategy.
Proactive Alerts : The system includes configurable alerts that can notify users as prices approach these key levels, allowing time for preparation. This feature is intended to support a shift from reactive trading toward systematic, criteria-based exit planning.
------------------------------------------------------------------
✅ HOW IT WORKS - AUTOMATED ANALYSIS & PLANNING
This indicator is designed to automate key aspects of exit planning that would otherwise require manual effort:
Fibonacci Level Calculation & Plotting : Automatically identifies key historical cycle points (e.g., bear market lows, bull market highs, recent pullbacks) and calculates relevant Fibonacci levels (both "Fib Retracments" from previous cycle ATH to bear market bottom, and "Fib. extensions" - considering major price impulses/waves in current bull market). This may help reduce manual drawing errors and streamline target identification.
Automated Calculation and Plotting of "Fib. Retracement "Levels
(from ATH of previous cycle to bottom in bear market)
Fibonacci retracement levels are a popular tool used in technical analysis to identify potential support and resistance levels in a market. After a significant price move, traders look for the price to "retrace" or pull back to one of several key Fibonacci ratios of the original move before continuing in its original direction. The most common retracement levels are 23.6%, 38.2%, 50%, 61.8%, and 78.6%. These levels are static horizontal lines on a chart, and their predictive power is based on the idea that they are "areas of interest" where a trend might pause or reverse.
Automated Calculation and Plotting of "Fib. Extension" Levels
(Price Impulses/Waves within current Bull Market)
Fibonacci extension levels are used to identify potential price targets or profit zones once a market has moved past its previous high or low. Unlike retracements, which measure a pullback, extensions project how far a trend might continue in the direction of its impulse move. They are typically used to anticipate where a wave or a rally might end and are based on ratios like 127.2%, 161.8%, 261.8%, and sometimes even higher. Extensions are a key tool for traders looking to set price targets for taking profits.
Coin Strength Assessment: Evaluates recovery performance relative to previous cycle peaks and classifies assets into four categories (Weak, Average, Strong, Outlier). Strength ratings may adjust dynamically based on momentum conditions — all derived from price data.
Market Phase Detection : Continuously monitors trend indicators, volume behavior, and altseason dynamics to estimate the current market phase. This may assist in contextualizing exit decisions without requiring manual phase analysis.
Exit Level Generation : Based on the asset’s strength classification and selected strategy (Conservative, Balanced, Aggressive), the system generates sequential exit levels with suggested percentages and quantities. Designed to support structured planning across three stages.
Signal Detection : Tracks multiple conditions — including price extensions, volume surges, momentum shifts, and cycle patterns — to generate alerts when predefined criteria are met.
Emergency Exit Detection : Scans for rare but high-risk scenarios (e.g., cycle top formations with multiple confluences) that may warrant immediate attention. Alerts are designed to highlight potential overextension during volatile phases.
Transfer Alerts : Calculates proximity to key exit zones and may issue early warnings to prepare for execution (e.g., moving assets from cold storage to exchanges), aiming to reduce last-minute decision pressure.
The script operates in two distinct modes:
Coin Analysis Mode Displays automatically-calculated Fibonacci levels, asset strength classification, market phase estimation, and contextual risk factors — designed to support structured analysis.
Exit Plan Mode Generates a customizable exit strategy with calculated price levels, suggested quantities, and potential outcome scenarios — aiming to assist with disciplined planning and reduce emotional bias.
------------------------------------------------------------------
✅ SETUP & INSTALLATION
Step 1: Chart Setup
Add the indicator to your altcoin USD chart (e.g., spot market pairs).
Recommended timeframe: 3 days for signal clarity.
Dark theme suggested for visual contrast.
Step 2: Configure Your Exit Strategy
Open Settings → “Setup Your Exit Plan”
Choose your strategy: Conservative: Prioritizes earlier exits for stricter risk control; Balanced: Combines early and late exits for a mixed approach; Aggressive: Targets later exits, accepting potentially higher volatility.
Input your asset quantity.
(Optional) Set a minimum sell price to block exit signals below your defined threshold.
(Optional) Set a sell-now price to trigger a sell alert when your exit target is reached, bypassing intermediate levels.
Step 3: Choose Display Mode
Coin Analysis Mode: View market conditions, strength classification, Fibonacci levels, and contextual risk insights. Designed to support monitoring and signal validation.
Exit Plan Mode: Displays your structured exit roadmap with suggested price levels, quantities, and visual chart overlays. Focuses on execution and planning.
Step 4: Set Up Alerts (Recommended)
Click the “Alert” button on the chart.
Select “Altcoins Exit Planner” as the condition.
Choose alert type: Planned Exit, Emergency Exit, Transfer Alert, Local Top, Trend Change
Set expiration to “Open-ended”
Configure your preferred notification method.
Alert Types Include:
Planned Exit Alerts: Triggered when suggested exit levels are reached (Exit #1, #2, #3).
Emergency Exit Alerts: Highlight potential cycle tops or full-exit conditions.
Transfer Alerts: Advance notice to prepare for execution (e.g., moving assets to exchanges).
Local Top Alerts: Short-term pullback signals for tactical decisions.
Trend Change Alerts: Indicate potential market phase transitions.
Once configured, the indicator begins analyzing and may notify you when exit conditions align with your selected strategy.
------------------------------------------------------------------
✅ USER INTERFACE
The interface is organized into two primary modes:
1) Coin Analysis Mode
Analysis Table Includes:
Fibonacci levels with price targets and percentage differentials
Market trend status (e.g., Strong Bull, Weakening Bull, Bear Market)
Volume behavior (Normal / Abnormal)
Price extension status (Overextended / Within range)
Altseason detection
Coin strength classification
Reversal risk assessment (Low / Average / High)
Suggested action based on current conditions
Visual Elements:
Bull/Bear trend EMA line
Volume-based candle coloring (overrides default chart candles)
Pivot points for key structural levels
Selectable Fibonacci extension/retracement lines
Background highlighting during altseason periods (potential cycle peak phase)
2) Exit Plan Mode
Exit Plan Table Displays:
Suggested quantity to sell at each exit level
Estimated portfolio value in USD
Structured exit plan with Fibonacci levels, percentages, quantities, and projected amounts
Average exit price calculation
Potential outcome scenarios if all exit levels are reached
Price Lines:
Individual exit level markers with contextual details
Average exit price reference line
Minimum sell price line (if enabled)
Sell-now price line (if enabled)
Signal Indicators:
Blue diamonds: Planned exit levels reached
Red triangles: Cycle top warnings
Orange triangles: Local top signals
These elements are designed to assist with visual interpretation and structured decision-making. All outputs are derived from price data and user-defined settings.
------------------------------------------------------------------
✅ LIMITATIONS
Market Cycle Dependency: This indicator is designed for cryptocurrency market cycles and will not perform similarly in other asset classes or market conditions. Its logic is based on historical crypto behavior, which may not repeat.
Assumption-Based Framework: The methodology relies on assumptions about market cycles, Fibonacci relationships, and altcoin behavior patterns. These assumptions may not hold under future conditions.
User Responsibility
All signals require user interpretation and decision-making.
The indicator provides information, not investment advice.
Signals should be validated with additional analysis.
Position sizing and risk management remain the user's responsibility.
Technical Requirements
Intended for use on the 3-day timeframe.
Designed for altcoin/USD trading pairs.
Requires sufficient historical data for Fibonacci calculations.
May not function properly on newly listed assets with limited price history.
Risk Management Guidelines. Recommended practices include:
Use with limited portions of your portfolio.
Combine with other technical and fundamental tools.
Consider broader market context beyond indicator signals.
Maintain independent stop-loss levels.
Review and adjust settings as market conditions evolve.
Signal Interpretation
Emergency signals highlight conditions that may warrant immediate review.
Planned exits support gradual, structured position reduction.
Transfer alerts provide preparation time before potential execution.
Local top signals may assist short-term tactical decisions.
------------------------------------------------------------------
✅ DISCLAIMER
This indicator is for educational and informational purposes only . It does not constitute financial, investment, or trading advice.
The indicator:
Makes no guarantees about future market performance.
Cannot predict market movements with certainty.
May generate false signals or miss key developments.
Relies on historical patterns that may not repeat.
Should not be used as the sole basis for trading decisions.
Users are responsible for:
Conducting independent research and analysis.
Understanding the risks of cryptocurrency trading.
Making their own investment/divestment decisions.
Managing position sizes and risk exposure appropriately.
Cryptocurrency trading involves substantial risk and may not be suitable for all investors. Past performance does not guarantee future results. Users should only invest what they can afford to lose and consult qualified professionals before making financial decisions.
The indicator’s assumptions may be invalidated by changing market conditions.
By using this tool, users acknowledge these limitations and accept full responsibility for their trading decisions.
Fed Rate Change Impact📊 Fed Rate Change Impact — Macro Event-Driven Indicator
Fed Rate Change Impact is an advanced indicator designed to analyze the impact of Federal Reserve interest rate changes on financial markets. It integrates event-driven logic with dynamic visualization, percentage diagnostics, and multi-asset selection, offering a clear and customizable view of post-event effects.
🔍 Key Features 📅 Preloaded Fed Events : Includes over 30 historical rate cut (↓) and hike (↑) dates from 2008 to 2024.
📈 Post-Event Analysis : Calculates the percentage change of the selected asset 5, 10, and 30 days after each event.
📌 Vertical Chart Lines : Visually highlights each event directly on the chart, with dynamic coloring (red for hikes, green for cuts).
📋 Diagnostic Table : Displays real-time impact for each event, with color-coded values and a compact layout.
🧠 Interactive Filter: Choose to display only hikes, only cuts, or both.
🧭 Flexible Asset Selection : Analyze the current chart asset, pick from a predefined list, or manually input any ticker via input.symbol().
🎯 Contextual Highlighting : The table highlights the analyzed asset if it matches the active chart symbol.
⚙️ Customizable Parameters lookahead5, lookahead10, lookahead30: Define the time horizon for measuring post-event impact.
eventFilter : Choose which type of events to display.
presetAsset / customAsset : Select or input the asset to analyze.
🧪 Recommended Use Cases Macroeconomic analysis on indices, commodities, crypto, and forex
Studying delayed effects of rate changes on sensitive assets
Building event-driven strategies or diagnostic overlays
Visual backtesting and cross-asset comparison
🧠 Technical Notes The indicator is compatible with overlay=true and works best on Daily timeframe.
The table automatically adapts to the number of events and includes visual padding for improved readability.
All calculations are performed in real time and require no external data.
Expected Value Monte CarloI created this indicator after noticing that there was no Expected Value indicator here on TradingView.
The EVMC provides statistical Expected Value to what might happen in the future regarding the asset you are analyzing.
It uses 2 quantitative methods:
Historical Backtest to ground your analysis in long-term, factual data.
Monte Carlo Simulation to project a cone of probable future outcomes based on recent market behavior.
This gives you a data-driven edge to quantify risk, and make more informed trading decisions.
The indicator includes:
Dual analysis: Combines historical probability with forward-looking simulation.
Quantified projections: Provides the Expected Value ($ and %), Win Rate, and Sharpe Ratio for both methods.
Asset-aware: Automatically adjusts its calculations for Stocks (252 trading days) and Crypto (365 days) for mathematical accuracy.
The projection cone shows the mean expected path and the +/- 1 standard deviation range of outcomes.
No repainting
Calculation:
1. Historical Expected Value:
This is a systematic backtest over thousands of bars. It calculates the return Rᵢ for N past trades (buy-and-hold). The Historical EV is the simple average of these returns, giving a baseline performance measure.
Historical EV % = (Σ Rᵢ) / N
2. Monte Carlo Projection:
This projection uses the Geometric Brownian Motion (GBM) model to simulate thousands of future price paths based on the market's recent behavior.
It first measures the drift (μ), or recent trend, and volatility (σ), or recent risk, from the Projection Lookback period. It then projects a final return for each simulation using the core GBM formula:
Projected Return = exp( (μ - σ²/2)T + σ√T * Z ) - 1
(Where T is the time horizon and Z is a random variable for the simulation.)
The purple line on the chart is the average of all simulated outcomes (the Monte Carlo EV). The cone represents one standard deviation of those outcomes.
The dashed lines represent one standard deviation (+/- 1σ) from the average, forming a cone of probable outcomes. Roughly 68% of the simulated paths ended within this cone.
This projection answers the question: "If the recent trend and volatility continue, where is the price most likely to go?"
Here's how to read the indicator
Expected Value ($/%): Is my average trade profitable?
Win Rate: How often can I expect to be right?
Sharpe Ratio: Am I being adequately compensated for the risk I'm taking?
User Guide
Max trade duration (bars): This is your analysis timeframe. Are you interested in the probable outcome over the next month (21 bars), quarter (63 bars), or year (252 bars)?
Position size ($): Set this to your typical trade size to see the Expected Value in real dollar terms.
Projection lookback (bars): This is the most important input for the Monte Carlo model. A short lookback (e.g., 50) makes the projection highly sensitive to recent momentum. Use this to identify potential recency bias. A long lookback (e.g., 252) provides a more stable, long-term projection of trend and volatility.
Historical Lookback (bars): For the historical backtest, more data is always better. Use the maximum that your TradingView plan allows for the most statistically significant results.
Use TP/SL for Historical EV: Check this box to see how the historical performance would have changed if you had used a simple Take Profit and Stop Loss, rather than just holding for the full duration.
I hope you find this indicator useful and please let me know if you have any suggestions. 😊
DCA Cost Basis (with Lump Sum)DCA Cost Basis (with Lump Sum) — Pine Script v6
This indicator simulates a Dollar Cost Averaging (DCA) plan directly on your chart. Pick a start date, choose how often to buy (daily/weekly/monthly), set the per-buy amount, optionally add a one-time lump sum on the first date, and visualize your evolving average cost as a VWAP-style line.
Features
Customizable DCA Plan — Set Start Date , buy Frequency (Daily / Weekly / Monthly), and Recurring Amount (in quote currency, e.g., USD).
Lump Sum Option — Add a one-time lump sum on the very first eligible date; recurring DCA continues automatically after that.
Cost Basis Line — Plots the live average price (Total Cost / Total Units) as a smooth, VWAP-style line for instant breakeven awareness.
Buy Markers — Optional triangles below bars to show when simulated buys occur.
Performance Metrics — Tracks:
Total Invested (quote)
Total Units (base)
Cost Basis (avg entry)
Current Value (mark-to-market)
CAGR (Annualized) from first buy to current bar
On-Chart Summary Table — Displays Start Date, Plan Type (Lump + DCA or DCA only), Total Invested, and CAGR (Annualized).
Data Window Integration — All key values also appear in the Data Window for deeper inspection.
Why use it?
Visualize long-term strategies for Bitcoin, crypto, or stocks.
See how a lump sum affects your average entry over time.
Gauge breakeven at a glance and evaluate historical performance.
Note: This tool is for educational/simulation purposes. Results are based on bar closes and do not represent live orders or fees.