Change% by Amit Multi-Period Returns Table 
This indicator displays percentage returns across multiple timeframes — 
1 Week, 
1 Month, 
3 Months, 
6 Months, 
12 Months.
This helps traders quickly assess short-term and long-term performance trends.
Positive returns are highlighted in blue, while negative returns are shown in red, allowing instant visual recognition of strength or weakness.
Ideal for spotting momentum shifts, relative performance, and trend consistency across different horizons.
Performance
Momentum Master v1Momentum Master v1 - Advanced Multi-Filter Confluence Trading System
### Technical Methodology
Multi-timeframe EMA crossover system with institutional flow analysis, proprietary Fair Value Gap (FVG) retracement detection, and Point of Control (POC) proximity filtering.
The script combines six distinct confirmation filters: customizable EMA crossover signals (3/21 default), RSI momentum analysis (14-period), proprietary FVG retracement algorithm with 200-bar lookback, multi-timeframe POC proximity calculation (Volume/Session/Daily/Weekly), institutional order block detection with retest confirmation, and adaptive ATR-based risk management with real-time confidence scoring.
### Unique Features
1. **Proprietary FVG Retracement Algorithm** - Advanced institutional flow analysis with 200-bar lookback and 20% ATR tolerance
2. **Multi-Timeframe POC Confluence System** - Combines 4 different POC calculations (Volume Profile 30-bar, Session, Daily, Weekly) for key level analysis
3. **Adaptive Confidence Scoring System** - Dynamic risk management based on signal quality (0-100%) with real-time performance tracking
4. **Advanced Performance Analytics** - Real-time win/loss statistics for each TP level with up to 500 individual trade verification labels
5. **Professional Risk Management** - Six-level take-profit system (2:1, 4:1, 6:1, 8:1, 10:1, 12:1) with ATR-based stops
### How It Works
**Entry Requirements:** Fast EMA (3) crosses above Slow EMA (21) + RSI < 70 + volume > 1.1x average + FVG retracement confirmation + POC proximity within 2.0x ATR + order block direction alignment.
**Risk Management:** ATR-based stop loss placement with 1.0x multiplier. Six take-profit levels at 2:1, 4:1, 6:1, 8:1, 10:1, and 12:1 risk/reward ratios.
**Performance Tracking:** Real-time win/loss statistics with up to 500 individual trade labels for verification, confidence scoring system, and comprehensive performance analytics for each TP level.
### Value Proposition
This script combines 6 different institutional flow analysis techniques that would require multiple free scripts to replicate. The proprietary FVG retracement algorithm, multi-timeframe POC analysis, and adaptive confidence scoring system are not available in any single free script.
### Use Cases
- **Best Timeframes:** 5-minute for scalping, 15-minute for swing trades
- **Suitable Markets:** Forex major pairs, Crypto, major indices
- **Market Conditions:** Trending markets with high volume sessions
### Access Instructions
To request access to this invite-only script:
- **Contact:** with your TradingView username
- **Requirements:** Include your TradingView username and brief trading experience
- **Process:** I will review requests within 24 hours and grant access to qualified traders
---
### Technical Justification for Indicator Combination
**Why These Indicators Work Together:**
This script combines 6 distinct analysis methods because each serves a specific purpose in the signal generation pipeline. The EMA crossover provides trend direction, RSI prevents entries in extreme zones, volume confirms institutional participation, FVG retracement validates institutional flow, POC proximity ensures key level alignment, and order block detection confirms institutional context.
**Component Integration Logic:**
- **EMA Crossover (3/21 customizable):** Primary trend detection mechanism with multiple speed options (Standard 9/21, Fast 7/17, Slow 13/26, Custom)
- **RSI Filter (14-period):** Momentum validation to avoid extreme overbought/oversold entries
- **Volume Analysis (1.1x threshold):** Institutional participation confirmation with trend analysis
- **FVG Retracement (200-bar lookback):** Validates price action within institutional flow zones
- **Multi-Timeframe POC (Volume/Session/Daily/Weekly):** Ensures confluence with key price levels
- **Order Block Detection:** Confirms institutional accumulation/distribution context
### Detailed Functionality Explanation
**What This Script Does:**
Generates high-probability momentum scalping signals with multiple take-profit levels and adaptive risk management. The script analyzes price action across multiple timeframes to identify optimal entry points where institutional flow, key levels, and momentum align.
**How It Works:**
1. **Signal Generation:** EMA crossover triggers base signal
2. **Filter Validation:** Six confirmation filters validate signal quality
3. **Confidence Scoring:** Dynamic scoring system rates signal strength (0-100%)
4. **Risk Management:** ATR-based stops with adaptive sizing based on confidence
5. **Profit Taking:** Six-level TP system with fixed risk/reward ratios
6. **Performance Tracking:** Real-time win/loss statistics with trade verification
**How to Use It:**
- **Timeframes:** 5m for scalping, 15m for swing trades, 1h for position entries
- **Markets:** Forex majors, Crypto, major indices
- **Setup:** Apply to chart, configure filters, set risk parameters, monitor confidence scores
- **Entry:** Wait for all filters to align, enter on signal confirmation
- **Exit:** Use ATR-based stops and multiple TP levels
### Originality and Unique Features
**Proprietary Algorithms:**
1. **Advanced FVG Retracement Detection:** 200-bar lookback with 20% ATR tolerance - not available in free scripts
2. **Multi-Timeframe POC Confluence:** Combines 4 different POC calculations with proximity filtering
3. **Adaptive Confidence Scoring:** Dynamic risk adjustment based on signal quality with real-time tracking
4. **Institutional Order Block Analysis:** Advanced detection with directional alignment filtering
5. **Performance Verification System:** Up to 500 individual trade labels for backtesting verification
6. **Advanced Performance Analytics:** Real-time win/loss statistics for each TP level with comprehensive reporting
### Value Justification
**Why This Is Worth Using:**
- **Institutional-Grade Analysis:** Combines techniques used by professional traders
- **Proprietary Algorithms:** FVG retracement and confidence scoring not available elsewhere
- **Comprehensive Confluence:** 6 different analysis methods in one unified system
- **Professional Risk Management:** Multi-level TP system with adaptive stops
- **Real-Time Performance Tracking:** Live win/loss statistics and confidence monitoring
- **Trade Verification:** Individual trade labels for backtesting and performance analysis
- **Advanced Analytics:** Detailed performance statistics for each take-profit level
- **Time-Saving:** All analysis tools in one script vs. 6+ separate indicators
- **High Accuracy:** Multiple confluence filters reduce false signals significantly
**Technical Specifications:**
- **Pine Script Version:** 6
- **Max Bars Back:** 5000 (for historical analysis)
- **Max Labels:** 500 (for performance optimization and trade verification)
- **Memory Usage:** Optimized for real-time performance
- **Compatibility:** Works on all TradingView timeframes and instruments
- **Alert System:** Built-in alert conditions for long/short entries
- **Visual Elements:** Professional chart display with customizable colors and styles
**No External Dependencies:**
This script operates entirely within TradingView's platform with no external links, contact information, or promotional content. All analysis is performed using built-in Pine Script functions and proprietary algorithms.
AstraAlgo BacktesterOVERVIEW 
The AstraAlgo Backtester allows traders to simulate and evaluate trading strategies directly on TradingView. By simulating trades across different timeframes and markets, it provides valuable insights into win rates, drawdowns, and overall strategy effectiveness.
 SIGNAL MODES 
Signal Modes generate proprietary trade signals based on live price data. Users can choose between Off, Basic, Advanced, or Custom modes to evaluate strategies under different conditions and refine their trading approach.
  
 ADJUSTABLE BACKTESTING 
Parameters for historical simulations can be customized to test different market conditions and trading scenarios. This allows traders to measure strategy performance, including win rate, profit/loss, and risk/reward ratios, helping refine and optimize strategies before live execution.
  
 BAR COLORING 
Bar Coloring highlights bullish and bearish bars on historical charts, allowing traders to visually assess trend direction and trade outcomes during backtesting. This makes it easier to analyze momentum and strategy effectiveness at a glance.
  
 ASTRA CLOUD 
Astra Cloud overlays dynamic support and resistance levels on live price data. These zones adapt automatically to past market movements, helping traders identify areas where trades would have reacted, aiding strategy evaluation and optimization.
 
Rolling Performance Toolkit (Returns, Correlation and Sharpe)This script provides a flexible toolkit for evaluating rolling performance metrics between any asset and a benchmark.  
  
Features:  
  
Library-based: Built on a custom utilities library for consistent return and statistics calculations.  
  
Rolling Window Control: Choose the lookback period (in days) to calculate metrics.  
  
Multiple Modes: Toggle between Rolling Returns, Rolling Correlation, and Rolling Sharpe Ratio.  
  
Benchmark Comparison: Compare your selected ticker against a benchmark (default: S&P 500 / SPX), but you can easily switch to any symbol.  
  
Risk-Free Rate Options: Choose from zero, a constant annual % rate, or a proxy symbol (default: US03M – 3-Month Treasury Yield).  
  
Annualized Sharpe: Sharpe ratios are annualized by default (×√252) for intuitive interpretation.  
  
This tool is useful for traders and investors who want to monitor relative performance, diversification benefits, or risk-adjusted returns over time.
Apex Edge - London Open Session# Apex Edge - London Open Session Trading System
## Overview
The London Open Session indicator captures institutional price action during the first hour of the London forex session (8:00-9:00 AM GMT) and identifies high-probability breakout and retest opportunities. This system tracks the session's high/low range and generates precise entry signals when price breaks or retests these key institutional levels.
## Core Strategy
**Session Tracking**: Automatically identifies and marks the London Open session boundaries, creating a trading zone from the first hour's price range.
**Dual Entry Logic**: 
- **Breakout Entries**: Triggers when price closes beyond the session high/low and continues in that direction
- **Retest Entries**: Activates when price returns to test the broken level as new support/resistance
**Performance Analytics**: Built-in win rate tracking displays real-time performance statistics over user-defined lookback periods, enabling data-driven optimization for each currency pair.
## Key Features
### Automated Zone Detection
- Precise London session timing with timezone offset controls
- Visual session boundaries with customizable colours
- Automatic high/low range calculation and display
### Smart Entry System
- Breakout confirmation requiring candle close beyond zone
- Retest detection with configurable pip distance tolerance
- Separate risk/reward ratios for breakout vs retest entries
- Visual entry arrows with clear trade direction labels
### Performance HUD
- Real-time win rate calculation over customizable periods (7-365 days)
- Total trades tracking with win/loss breakdown
- Average risk-reward ratio display
- Color-coded performance metrics (green >70%, yellow >50%, red <50%)
### PineConnector Integration
- Direct MT4/MT5 execution via PineConnector alerts
- Proper forex pip calculations for all currency pairs
- Customizable risk percentage per trade
- Symbol override capability for broker compatibility
- Automatic SL/TP level calculation in pips
## Critical Usage Requirements
### Pair-Specific Optimization
Each currency pair requires individual optimization due to varying volatility characteristics, institutional participation levels, and typical price ranges during London hours. The performance HUD is essential for identifying optimal settings before live trading.
**Recommended Testing Process**:
1. Apply indicator to desired currency pair and timeframe
2. Experiment with session timing - while 8:00-9:00 AM GMT is standard, some pairs may show improved performance with alternative hourly windows (e.g., 7:00-8:00 AM or 9:00-10:00 AM)
3. Adjust Stop Loss distances, Risk/Reward ratios, and Retest distances
4. Monitor win rate over 30+ day periods using the performance HUD
5. Only proceed with live alerts once consistent 60%+ win rates are achieved
6. Create separate optimized chart setups for each profitable pair/timeframe combination
### Timeframe Specifications
This indicator is specifically designed and tested for:
- **1-minute charts**: Optimal for capturing immediate institutional reactions
- **5-minute charts**: Balanced approach between noise reduction and opportunity frequency
Higher timeframes generally produce inferior results due to increased noise and reduced institutional edge during the London session window.
## Settings Configuration
### Session Timing
- **London Open/Close Hours**: Adjust for your chart's timezone
- **Rectangle End Time**: Set to 4:30 PM to stop signals before NY session close
- **Timezone Offset**: Ensure accurate London session capture
### Entry Parameters
- **Retest Distance**: 3-8 pips depending on pair volatility
- **Stop Loss Pips**: Separate settings for breakouts (10-15 pips) and retests (8-12 pips)
- **Risk/Reward Ratios**: Independent ratios for different entry types
### PineConnector Setup
- **License ID**: Your PineConnector license key
- **Symbol Override**: MT4/MT5 symbol names if different from TradingView
- **Risk Percentage**: Position size as percentage of account balance
- **Prefix/Comment**: Organize trades in terminal
## Manual Trading Limitations
Without PineConnector automation, traders face significant practical challenges:
**Settings Management**: Each currency pair requires different optimized parameters. Switching between charts means manually adjusting multiple settings each time, creating potential for errors and missed opportunities.
**Timing Sensitivity**: London Open signals can occur rapidly during high-volatility periods. Manual execution may result in slippage or missed entries.
**Multi-Pair Monitoring**: Tracking 4-11 currency pairs simultaneously while manually adjusting settings for each switch becomes impractical for most traders.
**Parameter Consistency**: Risk of using suboptimal settings when quickly switching between pairs, potentially compromising the careful optimization work.
## Recommended Workflow
1. **Historical Testing**: Use win rate HUD to identify profitable pairs and optimal parameters
2. **Demo Automation**: Test PineConnector alerts on demo accounts with optimized settings
3. **Live Implementation**: Deploy alerts only on proven profitable pair/timeframe combinations
4. **Ongoing Monitoring**: Regular review of performance metrics to maintain edge
## Risk Disclaimer
This indicator provides analysis tools and automation capabilities but does not guarantee profitable trading outcomes. Past performance does not predict future results. Users should thoroughly backtest and demo trade before risking live capital. The London session strategy works best during specific market conditions and may underperform during low volatility or unusual market environments.
## Support Requirements
Successful implementation requires:
- Basic understanding of London session market dynamics
- PineConnector subscription for automation features
- Patience for proper optimization process
- Realistic expectations about win rates and drawdown periods
This system is designed for serious traders willing to invest time in proper optimization and risk management rather than plug-and-play solutions.
Trading Report Generator from CSVMany people use the Trading Panel. Unfortunately, it doesn't have a Performance Report. However, TradingView has strategies, and they have a Performance Report :-D
What if we combine the first and second? It's easy!
This script is a special strategy that parses transactions in csv format from Paper Trading (and it will also work for other brokers) and “plays” them. As a result, we get a Performance Report for a specific instrument based on our real trades in Paper or another broker.
 How to use it :
First, we need to get a CSV file with transactions. To do this, go to the Trading Panel and connect the desired broker. Select the History tab, then the Filled sub-tab, and configure the columns there, leaving only: Side, Qty, Fill Price, Closing Time. After that, open the Export data dialog, select History, and click Export. Open the downloaded CSV file in a regular text editor (Notepad or similar). It will contain a text like this:
 
Symbol,Side,Qty,Fill Price,Closing Time
FX:EURUSD,Buy,1000,1.0938700000000001,2023-04-05 14:29:23
COINBASE:ETHUSD,Sell,1,1332.05,2023-01-11 17:41:33
CME_MINI:ESH2023,Sell,1,3961.75,2023-01-11 17:30:40
CME_MINI:ESH2023,Buy,1,3956.75,2023-01-11 17:08:53
 
Next select all the text (Ctrl+A) and copy it to the clipboard.
Now apply the "Trading Report Generator from CSV" strategy to the chart with the desired symbol and TF, open the settings/input dialog, paste the contents of the clipboard into the single text input field of the strategy, and click Ok.
That's it.
In the Strategy Tester, we see a detailed Performance Report based on our real transactions.
P.S. The CSV file may contain transactions for different instruments, for example, you may have transactions for CRYPTO:BTCUSD and NASDAQ:AAPL. To view the report is based on CRYPTO:BTCUSD trades, simply change the symbol on the chart to CRYPTO:BTCUSD. To view the report is based on NASDAQ:AAPL trades, simply change the symbol on the chart to NASDAQ:AAPL. No changes to the strategy are required.
 How it works :
At the beginning of the calculation, we parse the csv once, create trade objects (Trade) and sort them in chronological order. Next, on each bar, we check whether we have trades for the time period of the next bar. If there are, we place a limit order for each trade, with limit price == Fill Price of the trade. Here, we assume that if the trade is real, its execution price will be within the bar range, and the Pine strategy engine will execute this order at the specified limit price.
Custom Portfolio [BackQuant]Custom Portfolio {BackQuant]  
 Overview 
This script turns TradingView into a lightweight portfolio optimizer with institutional-grade analytics and real-time position management capabilities.
Rank up to 15 tickers every bar using a pair-wise relative-strength "league table" that compares each asset against all others through your choice of 12 technical indicators.
Auto-allocate 100% of capital to the single strongest asset and optionally apply dynamic leverage when the aggregate market is trending, with full position tracking and rebalancing logic.
Track performance against a custom buy-and-hold benchmark while watching a fully fledged stats dashboard update in real time, including 15 professional risk metrics.
 How it works 
 Relative-strength engine  – Each asset is compared against every other asset with a user-selectable indicator (default: 9/21 EMA cross). The system generates a complete comparison matrix where Asset A vs Asset B, Asset A vs Asset C, and so on, creating strength scores. The summed scores crown a weekly/daily/hourly "winner" that receives the full allocation.
 Regime filter  – A second indicator applied to TOTAL crypto-market cap (or any symbol you choose) classifies the environment as  trending  or  mean-reverting . Leverage activates only in trending regimes, protecting capital during choppy or declining markets. Choose from indicators like Universal Trend Model, Relative Strength Overlay, Momentum Velocity, or Custom RSI for regime detection.
 Capital & position logic  – Equity grows linearly when flat and multiplicatively while invested. The system tracks entry prices, calculates returns including leverage adjustments, and handles position transitions seamlessly. Optional intra-trade leverage rebalancing keeps exposure in sync with market conditions, recalculating position sizes as regime conditions change.
 Risk & performance analytics  – Every confirmed bar records return, drawdown, VaR/CVaR, Sharpe, Sortino, alpha/beta vs your benchmark, gain-to-pain, Calmar, win-rate, Omega ratio, portfolio variance, skewness, and annualized statistics. All metrics render in a professional table for instant inspection with proper annualization based on your selected trading days (252 for traditional markets, 365 for crypto).
 Key inputs 
 Backtest window  – Hard-code a start date or let the script run from series' inception with full date range validation.
 Asset list (15 slots)  – Works with spot, futures, indices, even synthetic spreads (e.g., BYBIT:BTCUSDT.P). The script automatically cleans ticker symbols for display.
 Indicator universe  – Switch the comparative metric to DEMA, BBPCT, LSMAz adaptive scores, Volatility WMA, DEMA ATR, Median Supertrend, and more proprietary indicators.
 With more always being added! 
 Leverage settings  – Max leverage from 1x to any multiple, auto-rebalancing toggle, trend/reversion thresholds with precision controls.
 Visual toggles  – Show/hide equity curve, rolling drawdown heat-map, daily PnL spikes, position label, advanced metrics table, buy-and-hold comparison equity.
 Risk-free rate input  – Customize the risk-free rate for accurate Sharpe ratio calculations, supporting both percentage and decimal inputs.
 On-chart visuals 
Color-coded equity curve with "shadow" offset for depth perception that changes from green (profitable) to red (losing) based on recent performance momentum.
Rolling drawdown strip that fades from light to deep red as losses widen, with customizable maximum drawdown scaling for visual clarity.
Optional daily-return histogram line and zero reference for understanding day-to-day volatility patterns.
Bottom-center table prints the current winning ticker in real time with clean formatting.
Top-right metrics grid updates every bar with 15 key performance indicators formatted to three decimal places for precision.
Benchmark overlay showing buy-and-hold performance of your selected index (default: SPX) for relative performance comparison.
 Typical workflow 
Add the indicator on a blank chart (overlay off).
Populate ticker slots with the assets you actually trade from your broker's symbol list.
Pick your momentum or mean-reversion metric and a regime filter that matches your market hypothesis.
Set max leverage (1 = spot only) and decide if you want dynamic rebalancing.
Press the little " L " on the price axis to view the equity curve in log scale for better long-term visualization.
Enable the metrics table to monitor Sharpe, Sortino, and drawdown in real time.
Iterate through different asset combinations and indicator settings; compare performance vs buy-and-hold; refine until you find robust parameters.
 Who is it for? 
Systematic crypto traders looking for a one-click, cross-sectional rotation model with professional risk management.
Portfolio quants who need rapid prototyping without leaving TradingView or exporting to Python/R.
Swing traders wanting an at-a-glance health check of their multi-coin basket with instant position signals.
Fund managers requiring detailed performance attribution and risk metrics for client reporting.
Researchers backtesting momentum and mean-reversion strategies across multiple assets simultaneously.
 Important notes & tips 
Set  Trading Days in a Year  to 252 for traditional markets; 365 for 24/7 crypto to ensure accurate annualization.
CAGR and Sharpe assume the backtest start date you choose—short windows can inflate stats, so test across multiple market cycles.
Leverage is theoretical; always confirm your broker's margin rules and account for funding costs not modeled here.
The script is computationally heavy at 15 assets due to the N×N comparison matrix—reduce the list or lengthen the timeframe if you hit execution limits.
Best results often come from mixing assets with different volatility profiles rather than highly correlated instruments.
The regime filter symbol can be changed from CRYPTOCAP:TOTAL to any broad market index that represents your asset universe.
DCA Investment Tracker Pro [tradeviZion]DCA Investment Tracker Pro: Educational DCA Analysis Tool 
 An educational indicator that helps analyze Dollar-Cost Averaging strategies by comparing actual performance with historical data calculations. 
---
 💡 Why I Created This Indicator 
As someone who practices Dollar-Cost Averaging, I was frustrated with constantly switching between spreadsheets, calculators, and charts just to understand how my investments were really performing. I wanted to see everything in one place - my actual performance, what I should expect based on historical data, and most importantly,  visualize where my strategy could take me over the long term .
What really motivated me was watching friends and family underestimate the incredible power of consistent investing. When Napoleon Bonaparte first learned about compound interest, he reportedly exclaimed  "I wonder it has not swallowed the world"  - and he was right! Yet most people can't visualize how their $500 monthly contributions today could become substantial wealth decades later.
Traditional DCA tracking tools exist, but they share similar limitations:
 
 Require manual data entry and complex spreadsheets
 Use fixed assumptions that don't reflect real market behavior  
 Can't show future projections overlaid on actual price charts
 Lose the visual context of what's happening in the market
 Make compound growth feel abstract rather than tangible 
 
I wanted to create something different - a tool that automatically analyzes real market history, detects volatility periods, and shows you both current performance AND educational projections based on historical patterns right on your TradingView charts. As Warren Buffett said:  "Someone's sitting in the shade today because someone planted a tree a long time ago."   This tool helps you visualize your financial tree growing over time. 
This isn't just another calculator - it's a visualization tool that makes the magic of compound growth impossible to ignore.
---
 🎯 What This Indicator Does 
This educational indicator provides DCA analysis tools. Users can input investment scenarios to study:
 
 Theoretical Performance:  Educational calculations based on historical return data
 Comparative Analysis:  Study differences between actual and theoretical scenarios
 Historical Projections:  Theoretical projections for educational analysis (not predictions)
 Performance Metrics:  CAGR, ROI, and other analytical metrics for study
 Historical Analysis:  Calculates historical return data for reference purposes
 
  
---
 🚀 Key Features 
 Volatility-Adjusted Historical Return Calculation 
 
 Analyzes 3-20 years of actual price data for any symbol
 Automatically detects high-volatility stocks (meme stocks, growth stocks)
 Uses median returns for volatile stocks, standard CAGR for stable stocks
 Provides conservative estimates when extreme outlier years are detected
 Smart fallback to manual percentages when data insufficient
 
 Customizable Performance Dashboard 
 
 Educational DCA performance analysis with compound growth calculations
 Customizable table sizing (Tiny to Huge text options)
 9 positioning options (Top/Middle/Bottom + Left/Center/Right)
 Theme-adaptive colors (automatically adjusts to dark/light mode)
 Multiple display layout options
 
 Future Projection System 
 
 Visual future growth projections
 Timeframe-aware calculations (Daily/Weekly/Monthly charts)
 1-30 year projection options
 Shows projected portfolio value and total investment amounts
 
 Investment Insights 
 
 Performance vs benchmark comparison
 ROI from initial investment tracking
 Monthly average return analysis
 Investment milestone alerts (25%, 50%, 100% gains)
 Contribution tracking and next milestone indicators
 
---
 📊 Step-by-Step Setup Guide 
 1. Investment Settings 💰 
 
 Initial Investment:  Enter your starting lump sum (e.g., $60,000)
 Monthly Contribution:  Set your regular DCA amount (e.g., $500/month)
 Return Calculation:  Choose "Auto (Stock History)" for real data or "Manual" for fixed %
 Historical Period:  Select 3-20 years for auto calculations (default: 10 years)
 Start Year:  When you began investing (e.g., 2020)
 Current Portfolio Value:  Your actual portfolio worth today (e.g., $150,000)
 
 2. Display Settings 📊 
 
 Table Sizes:  Choose from Tiny, Small, Normal, Large, or Huge
 Table Positions:  9 options - Top/Middle/Bottom + Left/Center/Right
 Visibility Toggles:  Show/hide Main Table and Stats Table independently
 
 3. Future Projection 🔮 
 
 Enable Projections:  Toggle on to see future growth visualization
 Projection Years:  Set 1-30 years ahead for analysis
 
 Live Example -  NASDAQ:META  Analysis: 
  
 Settings shown: $60K initial + $500/month + Auto calculation + 10-year history + 2020 start + $150K current value 
---
 🔬 Pine Script Code Examples 
 Core DCA Calculations: 
 
// Calculate total invested over time
months_elapsed = (year - start_year) * 12 + month - 1
total_invested = initial_investment + (monthly_contribution * months_elapsed)
// Compound growth formula for initial investment
theoretical_initial_growth = initial_investment * math.pow(1 + annual_return, years_elapsed)
// Future Value of Annuity for monthly contributions
monthly_rate = annual_return / 12
fv_contributions = monthly_contribution * ((math.pow(1 + monthly_rate, months_elapsed) - 1) / monthly_rate)
// Total expected value
theoretical_total = theoretical_initial_growth + fv_contributions
 
 Volatility Detection Logic: 
 
// Detect extreme years for volatility adjustment
extreme_years = 0
for i = 1 to historical_years
    yearly_return = ((price_current / price_i_years_ago) - 1) * 100
    if yearly_return > 100 or yearly_return < -50
        extreme_years += 1
// Use median approach for high volatility stocks
high_volatility = (extreme_years / historical_years) > 0.2
calculated_return = high_volatility ? median_of_returns : standard_cagr
 
 Performance Metrics: 
 
// Calculate key performance indicators
absolute_gain = actual_value - total_invested
total_return_pct = (absolute_gain / total_invested) * 100
roi_initial = ((actual_value - initial_investment) / initial_investment) * 100
cagr = (math.pow(actual_value / initial_investment, 1 / years_elapsed) - 1) * 100
 
---
 📊 Real-World Examples 
See the indicator in action across different investment types:
 Stable Index Investments: 
 AMEX:SPY  (SPDR S&P 500)  - Shows steady compound growth with standard CAGR calculations
  
 Classic DCA success story: $60K initial + $500/month starting 2020. The indicator shows SPY's historical 10%+ returns, demonstrating how consistent broad market investing builds wealth over time. Notice the smooth theoretical growth line vs actual performance tracking. 
 MIL:VUAA  (Vanguard S&P 500 UCITS)  - Shows both data limitation and solution approaches
  
 Data limitation example: VUAA shows "Manual (Auto Failed)" and "No Data" when default 10-year historical setting exceeds available data. The indicator gracefully falls back to manual percentage input while maintaining all DCA calculations and projections. 
 MIL:VUAA  (Vanguard S&P 500 UCITS)  - European ETF with successful 5-year auto calculation
  
 Solution demonstration: By adjusting historical period to 5 years (matching available data), VUAA auto calculation works perfectly. Shows how users can optimize settings for newer assets. European market exposure with EUR denomination, demonstrating DCA effectiveness across different markets and currencies. 
   NYSE:BRK.B  (Berkshire Hathaway)  - Quality value investment with Warren Buffett's proven track record
   
 Value investing approach: Berkshire Hathaway's legendary performance through DCA lens. The indicator demonstrates how quality companies compound wealth over decades. Lower volatility than tech stocks = standard CAGR calculations used. 
 High-Volatility Growth Stocks: 
 NASDAQ:NVDA  (NVIDIA Corporation)  - Demonstrates volatility-adjusted calculations for extreme price swings
  
 High-volatility example: NVIDIA's explosive AI boom creates extreme years that trigger volatility detection. The indicator automatically switches to "Median (High Vol): 50%" calculations for conservative projections, protecting against unrealistic future estimates based on outlier performance periods. 
 NASDAQ:TSLA  (Tesla)  - Shows how 10-year analysis can stabilize volatile tech stocks
  
 Stable long-term growth: Despite Tesla's reputation for volatility, the 10-year historical analysis (34.8% CAGR) shows consistent enough performance that volatility detection doesn't trigger. Demonstrates how longer timeframes can smooth out extreme periods for more reliable projections. 
 NASDAQ:META  (Meta Platforms)  - Shows stable tech stock analysis using standard CAGR calculations
  
 Tech stock with stable growth: Despite being a tech stock and experiencing the 2022 crash, META's 10-year history shows consistent enough performance (23.98% CAGR) that volatility detection doesn't trigger. The indicator uses standard CAGR calculations, demonstrating how not all tech stocks require conservative median adjustments. 
 Notice how the indicator automatically detects high-volatility periods and switches to median-based calculations for more conservative projections, while stable investments use standard CAGR methods. 
---
 📈 Performance Metrics Explained 
 
 Current Portfolio Value:  Your actual investment worth today
 Expected Value:  What you  should  have based on historical returns (Auto) or your target return (Manual)
 Total Invested:  Your actual money invested (initial + all monthly contributions)
 Total Gains/Loss:  Absolute dollar difference between current value and total invested
 Total Return %:  Percentage gain/loss on your total invested amount
 ROI from Initial Investment:  How your starting lump sum has performed
 CAGR:  Compound Annual Growth Rate of your initial investment  (Note: This shows initial investment performance, not full DCA strategy) 
 vs Benchmark:  How you're performing compared to the expected returns
 
---
 ⚠️ Important Notes & Limitations 
 
 Data Requirements:  Auto mode requires sufficient historical data (minimum 3 years recommended)
 CAGR Limitation:  CAGR calculation is based on initial investment growth only, not the complete DCA strategy
 Projection Accuracy:  Future projections are theoretical and based on historical returns - actual results may vary
 Timeframe Support:  Works ONLY on Daily (1D), Weekly (1W), and Monthly (1M) charts - no other timeframes supported
 Update Frequency:  Update "Current Portfolio Value" regularly for accurate tracking
 
---
 📚 Educational Use & Disclaimer 
This analysis tool can be applied to various stock and ETF charts for educational study of DCA mathematical concepts and historical performance patterns.
 Study Examples:  Can be used with symbols like  AMEX:SPY ,  NASDAQ:QQQ ,  AMEX:VTI ,  NASDAQ:AAPL ,  NASDAQ:MSFT ,  NASDAQ:GOOGL ,  NASDAQ:AMZN ,  NASDAQ:TSLA ,  NASDAQ:NVDA  for learning purposes.
 EDUCATIONAL DISCLAIMER: This indicator is a study tool for analyzing Dollar-Cost Averaging strategies. It does not provide investment advice, trading signals, or guarantees. All calculations are theoretical examples for educational purposes only. Past performance does not predict future results. Users should conduct their own research and consult qualified financial professionals before making any investment decisions. 
---
 © 2025 TradeVizion. All rights reserved.  
Momentum TrackerDescription 
To screen for momentum movers, one can filter for stocks that have made a noticeable move over a set period. This initial move defines the momentum or swing move. From this list of candidates, we can create a watchlist by selecting those showing a momentum pause, such as a pullback or consolidation, which later could set up for a continuation.
 Momentum = Magnitude × Time 
This Momentum Tracker indicator serves as a study tool to visualize when stocks historically met these momentum conditions. It marks on the chart where a stock would have appeared on the screener, allowing us to review past momentum patterns and screener requirements. The indicator measures momentum in three different ways:
Normalized Momentum
Identifies when the current price reaches a new high or low compared to a historical window. This is the most standardized measurement and adapts well across markets.
 Normalized = Current Price ≥ Maximum Price in Lookback
Normalized = Current Price ≤ Minimum Price in Lookback 
Relative Momentum
Measures the percentage difference between a fast and a slow moving average. This method helps capture acceleration, the rate at which momentum is building over time.
 Relative = |Fast MA − Slow MA| ÷ Slow MA × 100 
Absolute Momentum
Measures how far price has moved from the highest or lowest point within a defined lookback period.
 Absolute = (Current Price − Lowest Price) ÷ Lowest Price × 100
Absolute = (Highest Price − Current Price) ÷ Highest Price × 100 
 Customization 
The tool is customizable in terms of lookback period and thresholds to accommodate different trading styles and timeframes, allowing users to set criteria that align with specific hold times and momentum requirements. While the various calculations can be enabled, the tool is best used in isolation of each to visualize different momentum conditions.
Sector Relative StrengthDescription 
This script compares sector performance relative to the S&P 500. Sector price levels or charts alone can mislead, because they tend to move with the broader market. An increase in a sector’s price does not necessarily indicate strength, as it may simply be following the index. 
For more a more reliable picture, the script calculates a ratio between each sector ETF and SPY. If the ratio has increased, the sector has outperformed the index. In case it has declined, the sector has underperformed. If the value is near zero, the sector has moved in line with the index. The sectors are presented in a table and sorted on relative performance.
 Calculation Method 
The performance is expressed as a percentage change in the ratio over a user-defined lookback period. The default lookback is set to 21 bars, which corresponds to one month on a daily chart. This value can be adopted in the settings to match preferred time period.
 Z-Score 
In addition to the percentage change, the script calculates a Z-score of the ratio, which measures how far the current value deviates from its recent mean. A high positive Z-score indicates that the ratio is significantly above its average, while a negative value indicates it is below. This normalization allows for comparison between sectors with different price levels or volatility profiles.
 Table Columns 
- Relative %: The sector's performance relative to SPY over the selected lookback period
- Z-Score: Standardized measure of current performance ratio is relative to its average
- Trend Arrow: Indicates the direction of relative performance up down or flat
 Example Interpretation 
For example, if XLK shows a 3.7% change, it has outperformed SPY over the selected period. Another sector might show a -2.1% change, which indicates underperformance. While both values shows relative strength or weakness, the Z-score is optional and can provide additional context based on how unusual that performance is compared to the sector's own recent behavior.
 Use Case 
This approach helps evaluate overall market conditions and supports a top-down method. By starting with sector performance, it becomes easier to identify where the market is showing leadership or weakness. This allows the stock selection process to be more deliberate and can help refine or customize screeners based on certain sectors.
Custom Performance TableThis script generates a table designed to provide a concise yet highly customizable overview of the performance of multiple financial instruments, displayed directly on the chart. The table can include up to 40 tickers, each individually configurable, with values updated in real time based on either the current chart timeframe or a specific user-selected timeframe.
	 NOTE : The update frequency of the table values depends on the refresh rate of the chart's main ticker to which the indicator is applied. To ensure a consistent and reliable data feed, especially when monitoring heterogeneous instruments, it is recommended to apply the indicator to a highly liquid and continuously traded asset, such as BTCUSD.
 PERFORMANCE CALCULATION MODES 
You can choose from three different performance calculation modes:
1)  Change %  (Percentage Change)
	Displays the percentage change of the current price compared to the previous candle within the selected timeframe.
	 (Current Price - Previous Price) / Previous Price * 100 
    This mode provides an immediate and straightforward measure of each instrument's percentage movement, useful for quick visual comparisons of relative strength among assets.
2)  Z-Score 
	The Z-Score measures how much the current price variation deviates from the historical average variation, relative to the standard deviation of those variations.
	 (Current Variation - Average Variation) / Standard Deviation of Variations 
	The result indicates how statistically unusual a movement is:
		- Values near 0 suggest normal variations.
		- Values above ±2 indicate statistically significant deviations.
	This is a valuable tool for identifying overbought/oversold conditions or market stress events and is often used in mean reversion strategies.
	
	 NOTE : Due to technical constraints, Z-Score can only be calculated when the selected timeframe matches the chart's timeframe exactly.
3)  RAROC  (Risk-Adjusted Return on Capital)
	RAROC expresses an asset's performance in relation to the risk taken, measured through its volatility (standard deviation of price).
	 Percentage Change / Standard Deviation of Price 
	It allows for an assessment of return efficiency in relation to volatility.
	A high RAROC value indicates a high return relative to the risk, making it a useful tool for comparing assets with different risk profiles. It is especially suitable for portfolio selection and allocation purposes.
 TABLE CONFIGURATION 
Each ticker can be customized with its own label, colors, and position in the table.
Each row can display the ticker name or a custom label, which, at the user's discretion, can either replace the name or be shown as an informational tooltip.
The table can be placed anywhere on the chart using horizontal and vertical offset parameters. Thanks to offset support, you can, for example, create financial market overview layouts. This can be done by completely “cleaning” the chart from price and indicators using TradingView settings, and then displaying multiple tables simultaneously (see the example chart published here).
Advanced customization options are also available for the table's appearance, including font settings, colors, borders, and more.
 CALCULATION TIMEFRAME 
The indicator allows the user to force a specific timeframe (Daily, Weekly, Monthly, Yearly) when applied to intraday charts.
However, for Z-Score mode, the selected timeframe must match the chart's timeframe exactly to ensure correct computation. Otherwise, the script will halt until settings are properly adjusted.
 USAGE NOTES 
Custom Performance Table is a flexible and adaptable tool, suitable for both intraday operations and medium- to long-term analysis. It is designed for traders and analysts who need to compare assets based on quantitative metrics, whether simple (like percentage change) or more advanced and risk-adjusted (such as Z-Score and RAROC).
CAM | Currency Strength PerformanceOverview 📊
The "CAM | Currency Strength Performance" indicator is a powerful forex trading tool that blends traditional composite analysis with dynamic performance tracking! 🚀 It compares the strength of a currency pair’s base and quote currencies against the pair’s price movement, offering traders a clear, colorful view of market dynamics through normalized lines and an upgraded strength-based histogram. 🎨
How It Works 🛠️
🔍 Automatic Currency Detection: Instantly identifies the base (e.g., XAU in XAUUSD) and quote (e.g., USD) currencies—no setup required!
📈 Composite Strength Calculation: Measures each currency’s power by averaging its exchange rate against a basket of 10 major currencies (GBP, EUR, CHF, USD, AUD, CAD, NZD, JPY, NOK, XAU). A classic strength snapshot! 💪
📏 Normalization: Scales composites and pair prices with a smart formula (price minus moving average, divided by standard deviation) for easy comparison. ⚖️
🎨 Dynamic Visualization:
Plots 3 normalized lines with unique colors:
Base Composite
Quote Composite
Actual Pair (⚪ white)
Benefits 🌈
🧠 Simplified Analysis: Normalized composites make static strength clear, while the new histogram reveals dynamic trends.
✅ Enhanced Decisions: Color-coded lines and a performance-driven histogram pinpoint trading opportunities fast—spot when base or quote takes the lead! 🚨
⏱️ Time-Saver: Auto-detection and dual metrics (static + dynamic) streamline your workflow.
🌍 Versatile: Works across all supported pairs, with colors adapting to currencies (e.g., orange AUD, yellow XAU).
👀 Eye-Catching: Vibrant visuals (purple GBP, green USD) and a purple histogram make it engaging and intuitive.
How It Helps Traders 💡
📈 Spot Trends: Normalized lines show steady strength; the histogram tracks recent outperformance—perfect for timing trades.
⚠️ Catch Divergences: See when strength shifts (e.g., base surging, quote lagging) don’t match price—hello, reversal signals! 🔍
🛡️ Manage Risk: Levels (1, -1) and histogram swings help gauge overbought/oversold conditions for smarter stops.
🔮 Big Picture: Combines static strength with dynamic momentum, giving a fuller market view for scalping or long-term strategies.
Conclusion ✨
"CAM | Currency Strength Performance" now fuses classic strength analysis with real-time performance tracking. With its upgraded histogram, traders get a dual lens—static composites plus dynamic strength—turning complex forex data into actionable insights! 📈💰
Mar 11
Release Notes
✨ New Feature: Strength Histogram:
Tracks the performance of base and quote currencies over a customizable lookback period (default: 10 bars). 📅
Calculates strength as the currency’s percentage change minus the basket’s average change, then plots the difference (base - quote) as a purple histogram. 📊
⚙️ Customizable Settings: Adjust Scaling Period (50), Histogram Scale Factor (0.5), Lookback Bars (10), and Levels (1, -1) to fit your trading style! 🎚️
How It Differs from the Previous Version 🔄
Old Histogram:
Showed the static difference between normalized base and quote composites—a snapshot of relative strength at a single point in time. 📷
Focused on current exchange rate levels, scaled by the pair’s normalized price movement.
New Histogram:
Displays the dynamic strength difference (base strength - quote strength) over a user-defined lookback period (e.g., 10 bars). 🌊
Measures past and current performance by calculating percentage changes relative to a basket, highlighting momentum and trends. 📈
Offers a more responsive, time-based view, showing how each currency has performed recently rather than just its absolute strength.
ValueAtTime█ OVERVIEW 
This library is a Pine Script® programming tool for accessing historical values in a time series using  UNIX timestamps . Its data structure and functions index values by time, allowing scripts to retrieve past values based on absolute timestamps or relative time offsets instead of relying on bar index offsets. 
 █ CONCEPTS 
 UNIX timestamps 
In Pine Script®, a  UNIX timestamp  is an integer representing the number of milliseconds elapsed since January 1, 1970, at 00:00:00 UTC (the  UNIX Epoch ). The timestamp is a unique,  absolute  representation of a specific point in time. Unlike a calendar date and time, a UNIX timestamp's meaning does not change relative to any  time zone . 
This library's functions process series values and corresponding UNIX timestamps in  pairs , offering a simplified way to identify values that occur at or near distinct points in time instead of on specific bars. 
 Storing and retrieving time-value pairs 
This library's `Data`  type  defines the structure for collecting time and value information in pairs.  Objects  of the `Data` type contain the following two fields:
 • `times` – An array of "int" UNIX timestamps for each recorded value.
 • `values` – An array of "float" values for each saved timestamp.
Each index in both  arrays  refers to a specific time-value pair. For instance, the `times` and `values` elements at index 0 represent the  first  saved timestamp and corresponding value. The library functions that maintain `Data` objects  queue  up to one time-value pair per bar into the object's arrays, where the saved timestamp represents the bar's  opening time . 
Because the `times` array contains a distinct UNIX timestamp for each item in the `values` array, it serves as a custom mapping for retrieving saved values. All the library functions that return information from a `Data` object use this simple two-step process to identify a value based on time:
 1. Perform a  binary search  on the `times` array to find the earliest saved timestamp closest to the specified time or offset and get the element's index.
 2. Access the element from the `values` array at the retrieved index, returning the stored value corresponding to the found timestamp. 
 Value search methods 
There are several techniques programmers can use to identify historical values from corresponding timestamps. This library's functions include three different search methods to locate and retrieve values based on absolute times or relative time offsets:
 Timestamp search  
Find the value with the earliest saved timestamp closest to a specified timestamp. 
 Millisecond offset search  
Find the value with the earliest saved timestamp closest to a specified number of milliseconds behind the current bar's opening time. This search method provides a time-based alternative to retrieving historical values at specific bar offsets. 
 Period offset search  
Locate the value with the earliest saved timestamp closest to a defined period offset behind the current bar's opening time. The function calculates the span of the offset based on a  period string . The "string" must contain one of the following unit tokens: 
 • "D" for days
 • "W" for weeks
 • "M" for months
 • "Y" for years
 • "YTD" for year-to-date, meaning the time elapsed since the beginning of the bar's opening year in the exchange time zone. 
The period string can include a multiplier prefix for all supported units except "YTD" (e.g., "2W" for two weeks). 
Note that the precise span covered by the "M", "Y", and "YTD" units varies across time. The "1M" period can cover 28, 29, 30, or 31 days, depending on the bar's opening month and year in the exchange time zone. The "1Y" period covers 365 or 366 days, depending on leap years. The "YTD" period's span changes with each new bar, because it always measures the time from the start of the current bar's opening year.  
 █ CALCULATIONS AND USE 
This library's functions offer a flexible, structured approach to retrieving historical values at or near specific timestamps, millisecond offsets, or period offsets for different analytical needs.
See below for explanations of the exported functions and how to use them. 
 Retrieving single values 
The library includes three functions that retrieve a single stored value using timestamp, millisecond offset, or period offset search methods:
 • `valueAtTime()` – Locates the saved value with the earliest timestamp closest to a specified timestamp. 
 • `valueAtTimeOffset()` – Finds the saved value with the earliest timestamp closest to the specified number of milliseconds behind the current bar's opening time. 
 • `valueAtPeriodOffset()` – Finds the saved value with the earliest timestamp closest to the period-based offset behind the current bar's opening time. 
Each function has  two overloads  for advanced and simple use cases. The first overload searches for a value in a user-specified `Data` object created by the `collectData()` function (see below). It returns a  tuple  containing the found value and the corresponding timestamp. 
The second overload maintains a `Data` object  internally  to store and retrieve values for a specified `source` series. This overload returns a tuple containing the historical `source` value, the corresponding timestamp, and the current bar's `source` value, making it helpful for comparing past and present values from requested contexts. 
 Retrieving multiple values 
The library includes the following functions to retrieve values from multiple historical points in time, facilitating calculations and comparisons with values retrieved across several intervals:
 • `getDataAtTimes()` – Locates a past `source` value for each item in a `timestamps` array. Each retrieved value's timestamp represents the earliest time closest to one of the specified timestamps. 
 • `getDataAtTimeOffsets()` – Finds a past `source` value for each item in a `timeOffsets` array. Each retrieved value's timestamp represents the earliest time closest to one of the specified millisecond offsets behind the current bar's opening time. 
 • `getDataAtPeriodOffsets()` – Finds a past value for each item in a `periods` array. Each retrieved value's timestamp represents the earliest time closest to one of the specified period offsets behind the current bar's opening time. 
Each function returns a tuple with arrays containing the found `source` values and their corresponding timestamps. In addition, the tuple includes the current `source` value and the symbol's description, which also makes these functions helpful for multi-interval comparisons using data from requested contexts. 
 Processing period inputs 
When writing scripts that retrieve historical values based on several user-specified period offsets, the most concise approach is to create a single text input that allows users to list each period, then process the "string" list into an array for use in the `getDataAtPeriodOffsets()` function. 
This library includes a `getArrayFromString()` function to provide a simple way to process strings containing comma-separated lists of periods. The function splits the specified `str` by its commas and returns an array containing every  non-empty  item in the list with surrounding whitespaces removed. View the example code to see how we use this function to process the value of a  text area input . 
 Calculating period offset times 
Because the exact amount of time covered by a specified period offset can vary, it is often helpful to verify the resulting times when using the `valueAtPeriodOffset()` or `getDataAtPeriodOffsets()` functions to ensure the calculations work as intended for your use case. 
The library's `periodToTimestamp()` function calculates an offset timestamp from a given period and reference time. With this function, programmers can verify the time offsets in a period-based data search and use the calculated offset times in additional operations. 
For periods with "D" or "W" units, the function calculates the time offset based on the absolute number of milliseconds the period covers (e.g., `86400000` for "1D"). For periods with "M", "Y", or "YTD" units, the function calculates an offset time based on the reference time's  calendar date  in the exchange time zone. 
 Collecting data 
All the `getDataAt*()` functions, and the second overloads of the `valueAt*()` functions, collect and maintain data internally, meaning scripts do not require a separate `Data` object when using them. However, the first overloads of the `valueAt*()` functions  do not  collect data, because they retrieve values from a  user-specified  `Data` object. 
For cases where a script requires a separate `Data` object for use with these overloads or other custom routines, this library exports the `collectData()` function. This function queues each bar's `source` value and opening timestamp into a `Data` object and returns the object's ID. 
This function is particularly useful when searching for values from a specific series more than once. For instance, instead of using multiple calls to the second overloads of `valueAt*()` functions with the same `source` argument, programmers can call `collectData()` to store each bar's `source` and opening timestamp, then use the returned `Data` object's ID in calls to the  first  `valueAt*()` overloads to reduce memory usage. 
The `collectData()` function and all the functions that collect data internally include two optional parameters for limiting the saved time-value pairs to a sliding window: `timeOffsetLimit` and `timeframeLimit`. When either has a non-na argument, the function restricts the collected data to the maximum number of recent bars covered by the specified millisecond- and timeframe-based intervals. 
 NOTE : All calls to the functions that collect data for a `source` series can execute up to  once  per bar or realtime tick, because each stored value requires a unique corresponding timestamp. Therefore, scripts  cannot  call these functions iteratively within a  loop . If a call to these functions executes more than once inside a loop's scope, it causes a runtime error. 
 █ EXAMPLE CODE 
The example code at the end of the script demonstrates one possible use case for this library's functions. The code retrieves historical price data at user-specified period offsets, calculates price returns for each period from the retrieved data, and then populates a  table  with the results. 
The example code's process is as follows:
  1. Input a list of periods  – The user specifies a comma-separated list of period strings in the script's "Period list" input (e.g., "1W, 1M, 3M, 1Y, YTD"). Each item in the input list represents a period offset from the latest bar's opening time. 
  2. Process the period list  – The example calls `getArrayFromString()` on the first bar to split the input list by its commas and construct an array of period strings. 
  3. Request historical data  – The code uses a call to `getDataAtPeriodOffsets()` as the `expression` argument in a  request.security()  call to retrieve the closing prices of "1D" bars for each period included in the processed `periods` array. 
  4. Display information in a table  – On the latest bar, the code uses the retrieved data to calculate price returns over each specified period, then populates a two-row table with the results. The cells for each return percentage are color-coded based on the magnitude and direction of the price change. The cells also include tooltips showing the compared daily bar's opening date in the exchange time zone. 
 █ NOTES 
 • This library's architecture relies on a  user-defined type (UDT)  for its data storage format. UDTs are blueprints from which scripts create  objects , i.e., composite structures with fields containing independent values or references of any supported type. 
 • The library functions search through a `Data` object's `times` array using the  array.binary_search_leftmost()  function, which is more efficient than looping through collected data to identify matching timestamps. Note that this built-in works only for arrays with elements sorted in  ascending order . 
 • Each function that collects data from a `source` series updates the values and times stored in a local `Data` object's arrays. If a single call to these functions were to execute in a  loop , it would store multiple values with an  identical  timestamp, which can cause erroneous search behavior. To prevent looped calls to these functions, the library uses the `checkCall()` helper function in their scopes. This function maintains a counter that increases by one each time it executes on a confirmed bar. If the count  exceeds  the total number of bars, indicating the call executes more than once in a loop, it raises a  runtime error . 
 • Typically, when requesting  higher-timeframe  data with  request.security()  while using  barmerge.lookahead_on  as the `lookahead` argument, the `expression` argument should be  offset  with the  history-referencing operator  to prevent  lookahead bias  on historical bars. However, the call in this script's example code enables lookahead without offsetting the `expression` because the script displays results only on the last historical bar and all realtime bars, where there is  no future data  to leak into the past. This call ensures the displayed results use the latest data available from the context on realtime bars.
 Look first. Then leap. 
 █ EXPORTED TYPES 
 Data 
  A structure for storing successive timestamps and corresponding values from a dataset.
  Fields:
     times (array) : An "int" array containing a UNIX timestamp for each value in the `values` array.
     values (array) : A "float" array containing values corresponding to the timestamps in the `times` array.
 █ EXPORTED FUNCTIONS 
 getArrayFromString(str) 
  Splits a "string" into an array of substrings using the comma (`,`) as the delimiter. The function trims surrounding whitespace characters from each substring, and it excludes empty substrings from the result.
  Parameters:
     str (series string) : The "string" to split into an array based on its commas.
  Returns: (array) An array of trimmed substrings from the specified `str`.
 periodToTimestamp(period, referenceTime) 
  Calculates a UNIX timestamp representing the point offset behind a reference time by the amount of time within the specified `period`.
  Parameters:
     period (series string) : The period string, which determines the time offset of the returned timestamp. The specified argument must contain a unit and an optional multiplier (e.g., "1Y", "3M", "2W", "YTD"). Supported units are:
- "Y" for years.
- "M" for months.
- "W" for weeks.
- "D" for days.
- "YTD" (Year-to-date) for the span from the start of the `referenceTime` value's year in the exchange time zone. An argument with this unit cannot contain a multiplier.
     referenceTime (series int) : The millisecond UNIX timestamp from which to calculate the offset time.
  Returns: (int) A millisecond UNIX timestamp representing the offset time point behind the `referenceTime`.
 collectData(source, timeOffsetLimit, timeframeLimit) 
  Collects `source` and `time` data successively across bars. The function stores the information within a `Data` object for use in other exported functions/methods, such as `valueAtTimeOffset()` and `valueAtPeriodOffset()`. Any call to this function cannot execute more than once per bar or realtime tick.
  Parameters:
     source (series float) : The source series to collect. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
     timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
     timeframeLimit (simple string) : Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
  Returns: (Data) A `Data` object containing collected `source` values and corresponding timestamps over the allowed time range.
 method valueAtTime(data, timestamp) 
  (Overload 1 of 2) Retrieves value and time data from a `Data` object's fields at the index of the earliest timestamp closest to the specified `timestamp`. Callable as a method or a function.
  Parameters:
     data (series Data) : The `Data` object containing the collected time and value data.
     timestamp (series int) : The millisecond UNIX timestamp to search. The function returns data for the earliest saved timestamp that is closest to the value.
  Returns: ( ) A tuple containing the following data from the `Data` object:
- The stored value corresponding to the identified timestamp ("float").
- The earliest saved timestamp that is closest to the specified `timestamp` ("int").
 valueAtTime(source, timestamp, timeOffsetLimit, timeframeLimit) 
  (Overload 2 of 2) Retrieves `source` and time information for the earliest bar whose opening timestamp is closest to the specified `timestamp`. Any call to this function cannot execute more than once per bar or realtime tick.
  Parameters:
     source (series float) : The source series to analyze. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
     timestamp (series int) : The millisecond UNIX timestamp to search. The function returns data for the earliest bar whose timestamp is closest to the value.
     timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
     timeframeLimit (simple string) : (simple string) Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
  Returns: ( ) A tuple containing the following data:
- The `source` value corresponding to the identified timestamp ("float").
- The earliest bar's timestamp that is closest to the specified `timestamp` ("int").
- The current bar's `source` value ("float").
 method valueAtTimeOffset(data, timeOffset) 
  (Overload 1 of 2) Retrieves value and time data from a `Data` object's fields at the index of the earliest saved timestamp closest to `timeOffset` milliseconds behind the current bar's opening time. Callable as a method or a function.
  Parameters:
     data (series Data) : The `Data` object containing the collected time and value data.
     timeOffset (series int) : The millisecond offset behind the bar's opening time. The function returns data for the earliest saved timestamp that is closest to the calculated offset time.
  Returns: ( ) A tuple containing the following data from the `Data` object:
- The stored value corresponding to the identified timestamp ("float").
- The earliest saved timestamp that is closest to `timeOffset` milliseconds before the current bar's opening time ("int").
 valueAtTimeOffset(source, timeOffset, timeOffsetLimit, timeframeLimit) 
  (Overload 2 of 2) Retrieves `source` and time information for the earliest bar whose opening timestamp is closest to `timeOffset` milliseconds behind the current bar's opening time. Any call to this function cannot execute more than once per bar or realtime tick.
  Parameters:
     source (series float) : The source series to analyze. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
     timeOffset (series int) : The millisecond offset behind the bar's opening time. The function returns data for the earliest bar's timestamp that is closest to the calculated offset time.
     timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
     timeframeLimit (simple string) : Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
  Returns: ( ) A tuple containing the following data:
- The `source` value corresponding to the identified timestamp ("float").
- The earliest bar's timestamp that is closest to `timeOffset` milliseconds before the current bar's opening time ("int").
- The current bar's `source` value ("float").
 method valueAtPeriodOffset(data, period) 
  (Overload 1 of 2) Retrieves value and time data from a `Data` object's fields at the index of the earliest timestamp closest to a calculated offset behind the current bar's opening time. The calculated offset represents the amount of time covered by the specified `period`. Callable as a method or a function.
  Parameters:
     data (series Data) : The `Data` object containing the collected time and value data.
     period (series string) : The period string, which determines the calculated time offset. The specified argument must contain a unit and an optional multiplier (e.g., "1Y", "3M", "2W", "YTD"). Supported units are:
- "Y" for years.
- "M" for months.
- "W" for weeks.
- "D" for days.
- "YTD" (Year-to-date) for the span from the start of the current bar's year in the exchange time zone. An argument with this unit cannot contain a multiplier.
  Returns: ( ) A tuple containing the following data from the `Data` object:
- The stored value corresponding to the identified timestamp ("float").
- The earliest saved timestamp that is closest to the calculated offset behind the bar's opening time ("int").
 valueAtPeriodOffset(source, period, timeOffsetLimit, timeframeLimit) 
  (Overload 2 of 2) Retrieves `source` and time information for the earliest bar whose opening timestamp is closest to a calculated offset behind the current bar's opening time. The calculated offset represents the amount of time covered by the specified `period`. Any call to this function cannot execute more than once per bar or realtime tick.
  Parameters:
     source (series float) : The source series to analyze. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
     period (series string) : The period string, which determines the calculated time offset. The specified argument must contain a unit and an optional multiplier (e.g., "1Y", "3M", "2W", "YTD"). Supported units are:
- "Y" for years.
- "M" for months.
- "W" for weeks.
- "D" for days.
- "YTD" (Year-to-date) for the span from the start of the current bar's year in the exchange time zone. An argument with this unit cannot contain a multiplier.
     timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
     timeframeLimit (simple string) : Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
  Returns: ( ) A tuple containing the following data:
- The `source` value corresponding to the identified timestamp ("float").
- The earliest bar's timestamp that is closest to the calculated offset behind the current bar's opening time ("int").
- The current bar's `source` value ("float").
 getDataAtTimes(timestamps, source, timeOffsetLimit, timeframeLimit) 
  Retrieves `source` and time information for each bar whose opening timestamp is the earliest one closest to one of the UNIX timestamps specified in the `timestamps` array. Any call to this function cannot execute more than once per bar or realtime tick.
  Parameters:
     timestamps (array) : An array of "int" values representing UNIX timestamps. The function retrieves `source` and time data for each element in this array.
     source (series float) : The source series to analyze. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
     timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
     timeframeLimit (simple string) : Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
  Returns: ( ) A tuple of the following data:
- An array containing a `source` value for each identified timestamp (array).
- An array containing an identified timestamp for each item in the `timestamps` array (array).
- The current bar's `source` value ("float").
- The symbol's description from `syminfo.description` ("string").
 getDataAtTimeOffsets(timeOffsets, source, timeOffsetLimit, timeframeLimit) 
  Retrieves `source` and time information for each bar whose opening timestamp is the earliest one closest to one of the time offsets specified in the `timeOffsets` array. Each offset in the array represents the absolute number of milliseconds behind the current bar's opening time. Any call to this function cannot execute more than once per bar or realtime tick.
  Parameters:
     timeOffsets (array) : An array of "int" values representing the millisecond time offsets used in the search. The function retrieves `source` and time data for each element in this array. For example, the array ` ` specifies that the function returns data for the timestamps closest to one day and one week behind the current bar's opening time.
     source (float) : (series float) The source series to analyze. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
     timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
     timeframeLimit (simple string) : Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
  Returns: ( ) A tuple of the following data:
- An array containing a `source` value for each identified timestamp (array).
- An array containing an identified timestamp for each offset specified in the `timeOffsets` array (array).
- The current bar's `source` value ("float").
- The symbol's description from `syminfo.description` ("string").
 getDataAtPeriodOffsets(periods, source, timeOffsetLimit, timeframeLimit) 
  Retrieves `source` and time information for each bar whose opening timestamp is the earliest one closest to a calculated offset behind the current bar's opening time. Each calculated offset represents the amount of time covered by a period specified in the `periods` array. Any call to this function cannot execute more than once per bar or realtime tick.
  Parameters:
     periods (array) : An array of period strings, which determines the time offsets used in the search. The function retrieves `source` and time data for each element in this array. For example, the array ` ` specifies that the function returns data for the timestamps closest to one day, week, and month behind the current bar's opening time. Each "string" in the array must contain a unit and an optional multiplier. Supported units are:
- "Y" for years.
- "M" for months.
- "W" for weeks.
- "D" for days.
- "YTD" (Year-to-date) for the span from the start of the current bar's year in the exchange time zone. An argument with this unit cannot contain a multiplier.
     source (float) : (series float) The source series to analyze. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
     timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
     timeframeLimit (simple string) : Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
  Returns: ( ) A tuple of the following data:
- An array containing a `source` value for each identified timestamp (array).
- An array containing an identified timestamp for each period specified in the `periods` array (array).
- The current bar's `source` value ("float").
- The symbol's description from `syminfo.description` ("string").
Month of Year Performance█  OVERVIEW 
The  Month of Year Performance  indicator is designed to visualize and compare the cumulative percentage change for each month of the year. By aggregating monthly returns, it helps uncover seasonal trends and potential anomalies in financial markets.
In financial analysis, a calendar based anomaly refers to recurring patterns or tendencies associated with specific time periods, such as days of the week. By calculating the cumulative percentage change for each month (January through December) and displaying the results both graphically and in a summary table, this indicator helps identify whether certain months 
consistently outperform others.
█  FEATURES 
 
 Customisable time window via Time Settings.
 Calculates cumulative percentage change for each month (January to December) separately.
 Built-in error check to ensure the indicator is applied on a Monthly timeframe.
 Distinct visual representation for each month using unique colours.
 Customisable table settings including location and font size.
 Displays a performance summary table with metrics such as performance, average return, % positive, and count.
 
█  HOW TO USE 
 
 Add the indicator to a chart set to a Monthly timeframe.
 Select your desired Start Time and End Time in the Time Settings.
 Toggle the performance table on or off in the Table Settings.
 Adjust the table’s location and font size as needed.
 View the cumulative monthly performance plotted in distinct colours.
 
 Colour Scheme: 
 
 January: Blue  
 February: Red  
 March: Green  
 April: Orange  
 May: Purple  
 June: Fuchsia  
 July: Teal  
 August: Yellow  
 September: Navy  
 October: Lime  
 November: Maroon  
 December: Aqua
 
Day of Week Performance█  OVERVIEW 
The  Day of Week Performance  indicator is designed to visualise and compare the cumulative percentage change for each day of the week. This indicator explores one of the many calendar based anomalies in financial markets.
In financial analysis, a calendar based anomaly refers to recurring patterns or tendencies associated with specific time periods, such as days of the week. By calculating the cumulative percentage change for each day (Monday through Friday) and displaying the results both graphically and in a summary table, this indicator helps identify whether certain days consistently outperform others.
█  FEATURES 
 
 Customisable time window via Time Settings.
 Calculates cumulative percentage change for each day (Monday to Friday) separately.
 Option to use Sunday instead of Friday for CFDs and Futures analysis.
 Distinct visual representation for each day using unique colours.
 Customisable table settings including position and font size.
 Built-in error checks to ensure the indicator is applied on a Daily timeframe.
 
█  HOW TO USE 
 
 Add the indicator to a chart set to a Daily timeframe.
 Select your desired Start Time and End Time in the Time Settings.
 Toggle the performance table on or off in the Table Settings.
 Adjust the table’s location and font size as needed.
 Use the "Use Sunday instead of Friday" option if your market requires it.
 View the cumulative performance plotted in distinct colours.
 
 Colour Scheme: 
 
 Monday: Blue  
 Tuesday: Red  
 Wednesday: Green  
 Thursday: Orange  
 Friday: Purple
Quarterly Performance█ OVERVIEW
The  Quarterly Performance  indicator is designed to visualise and compare the performance of different Quarters of the year. This indicator explores one of the many calendar based anomalies that exist in financial markets.
In the context of financial analysis, a calendar based anomaly refers to patterns or tendencies that are linked to specific time periods, such as days of the week, weeks of the month, or months of the year. This indicator helps explore whether such a calendar based anomaly exists between quarters.
By calculating cumulative quarterly performance and counting the number of quarters with positive returns, it provides a clear snapshot of whether one set of quarters tends to outperform the others, potentially highlighting a calendar based anomaly if a significant difference is observed.
█ FEATURES
 
 Customisable time window through input settings.
 Tracks cumulative returns for each quarter separately.
 Easily adjust table settings like position and font size via input options.
 Clear visual distinction between quarterly performance using different colours.
 Built-in error checks to ensure the indicator is applied to the correct timeframe.
 
█ HOW TO USE
 
 Add the indicator to a chart with a 3 Month (Quarterly) timeframe.
 Choose your start and end dates in the Time Settings.
 Enable or disable the performance table in the Table Settings as needed.
 View the cumulative performance, with Q1 in blue, Q2 in red, Q3 in green and Q4 in purple.
Live Portfolio P<his script calculates live P&L (Profit & Loss) for up to 40 instruments — stocks, ETFs, options, futures, and Forex pairs supported by TradingView. Instead of juggling numerous inputs, you paste your portfolio in CSV format into a single text field, and the script handles the rest. It parses each position and displays a comprehensive table showing the symbol, current price, position value, total P&L, and today’s P&L—all updated in real time.
 Key Features 
 
 CSV Portfolio Input  – Effortlessly import all your positions at once without filling in multiple fields. You can export the position from your broker, save it in the required format, and paste it into this script.  
 Supports Various Asset Classes  – Works with any instrument that TradingView provides data for, including futures, options, and Forex.
 Up to 40 Instruments  – Track a broad and diverse set of holdings in one place.
 Real-Time Updates  – Get immediate feedback on live price changes, total value, and current P&L.
 Today’s P&L  – Monitor your daily performance to gauge short-term trends.
 
 CSV is consumed in the following format:  
 
  Symbol (supported TradingView instruments)
  Entry Price
  Quantity (negative for short position)
  Lot Size (for futures/options, it might not be one) 
 
 For example:  
 AAPL,237,100,1
TSLA,400,-150,1
ESM2025,6000,5,50 
 Planned Enhancements 
 
 Multi-Currency Support  – Automatically convert and display your positions’ values in different currencies.
 Advanced Metrics  – Get deeper insights with calculations for drawdown, Sharpe ratio, and more.
 Risk Management Tools  – Set stop-loss and take-profit levels and receive alerts when thresholds are hit.
 Option Greeks & Margin Calculations  – Manage complex option strategies and track margin requirements.
 
 Questions for You 
 
  What additional features would you like to see?
  Are there any specific metrics or analytics you’d find especially valuable?
  How might this script fit into your current trading workflow?
 
Feel free to share your thoughts and suggestions. Your feedback will help shape future updates and make this tool even more helpful for traders like you!
 Disclaimer 
Please remember that past performance may not be indicative of future results.
Due to various factors, including changing market conditions, the strategy may no longer perform as well as in historical backtesting.
This post and the script don’t provide any financial advice.
Even vs Odd Days Performance█ OVERVIEW
The Even vs Odd Days Performance indicator is designed to visualise and compare the performance of even-numbered days versus odd-numbered days. This indicator explores one of the many calendar based anomalies that exist in financial markets.
In the context of financial analysis, a calendar based anomaly refers to patterns or tendencies that are linked to specific time periods, such as days of the week, weeks of the month, or months of the year. This indicator helps explore whether such a calendar based anomaly exists between even and odd days.
By calculating cumulative daily performance and counting the number of days with positive returns, it provides a clear snapshot of whether one set of days tends to outperform the other, potentially highlighting a calendar based anomaly if a significant difference is observed.
█ FEATURES
 
 Customisable time window through input settings.
 Tracks cumulative returns for even and odd days separately.
 Easily adjust table settings like position and font size via input options.
 Clear visual distinction between even and odd day performance using different colours.
 Built-in error checks to ensure the indicator is applied to the correct timeframe.
 
█ HOW TO USE
 
 Add the indicator to a chart with a Daily timeframe.
 Choose your start and end dates in the Time Settings.
 Enable or disable the performance table in the Table Settings as needed.
 View the cumulative performance, with even days in green and odd days in red.
Even vs Odd Weeks Performance█  OVERVIEW 
The  Even vs Odd Weeks Performance  indicator is designed to visualise and compare the performance of even-numbered weeks versus odd-numbered weeks. This indicator explores one of the many calendar based anomalies that exist in financial markets.
In the context of financial analysis, a calendar based anomaly refers to patterns or tendencies that are linked to specific time periods, such as days of the week, weeks of the month, or months of the year.  This indicator helps explore whether such a calendar based anomaly exists between even and odd weeks.
By calculating cumulative weekly performance and counting the number of weeks with positive returns, it provides a clear snapshot of whether one set of weeks tends to outperform the other, potentially highlighting a calendar based anomaly if a significant difference is observed.
█  FEATURES 
 
 Customisable time window through input settings.
 Tracks cumulative returns for even and odd weeks separately.
 Easily adjust table settings like position and font size via input options.
 Clear visual distinction between even and odd week performance using different colours.
 Built-in error checks to ensure the indicator is applied to the correct timeframe.
 
  
█  HOW TO USE 
 
 Add the indicator to a chart with a Weekly timeframe.
 Choose your start and end dates in the Time Settings.
 Enable or disable the performance table in the Table Settings as needed.
 View the cumulative performance, with even weeks in green and odd weeks in red.
Overnight vs Intra-day Performance█  STRATEGY OVERVIEW 
The "Overnight vs Intra-day Performance" indicator quantifies price behaviour differences between trading hours and overnight periods. It calculates cumulative returns, compound growth rates, and visualizes performance components across user-defined time windows. Designed for analytical use, it helps identify whether returns are primarily generated during market hours or overnight sessions.
█  USAGE 
Use this indicator on  Stocks  and  ETFs  to visualise and compare intra-day vs overnight performance
█  KEY FEATURES 
 
 Return Segmentation : Separates total returns into overnight (close-to-open) and intraday (open-to-close) components
 Growth Tracking : Shows simple cumulative returns and compound annual growth rates (CAGR)
 
█  VISUALIZATION SYSTEM 
1.  Time-Series 
 
 Overnight Returns (Red)
 Intraday Returns (Blue)
 Total Returns (White)
 
2.  Summary Table 
 
 Displays CAGR
 
3.  Price Chart Labels 
 
 Floating annotations showing absolute returns and CAGR
 Color-coded to match plot series
 
█  PURPOSE 
 
 Quantify market behaviour disparities between active trading sessions and overnight positioning
 Provide institutional-grade attribution analysis for returns generation
 Enable tactical adjustment of trading schedules based on historical performance patterns
 Serve as foundational research for session-specific trading strategies
 
█  IDEAL USERS 
1.  Portfolio Managers 
 
 Analyse overnight risk exposure across holdings
 Optimize execution timing based on return distributions
 
2.  Quantitative Researchers 
 
 Study market microstructure through time-segmented returns
 Develop alpha models leveraging session-specific anomalies
 
3.  Market Microstructure Analysts 
 
 Identify liquidity patterns in overnight vs daytime sessions
 Research ETF premium/discount mechanics
 
4.  Day Traders 
 
 Align trading hours with highest probability return windows
 Avoid overnight gaps through informed position sizing
Market Performance by Yearly Seasons [LuxAlgo]The  Market Performance by Yearly Seasons  tool allows traders to analyze the average returns of the four seasons of the year and the raw returns of each separate season.
🔶  USAGE 
  
By default, the tool displays the average returns for each season over the last 10 years in the form of bars, with the current session highlighted as a bordered bar.
Traders can choose to display the raw returns by year for each season separately and select the maximum number of seasons (years) to display.
🔹  Hemispheres 
  
Traders can select the hemisphere in which they prefer to view the data.
🔹  Season Types 
  
Traders can select the type of seasons between meteorological (by default) and astronomical.
The meteorological seasons are as follows:
 
 Autumn:  months from September to November
 Winter:  months from December to February
 Spring:  months from March to May
 Summer:  months from June to August
 
The astronomical seasons are as follows:
 
 Autumn:  from the equinox on September 22
 Winter:  from the solstice on December 21
 Spring:  from the equinox on March 20
 Summer:  from the solstice on June 21
 
🔹  Displaying the data 
  
Traders can choose between two display modes, average returns by season or raw returns by season and year.
🔶  SETTINGS 
 
 Max seasons:  Maximum number of seasons
 Hemisphere:  Select NORTHERN or SOUTHERN hemisphere
 Season Type:  Select the type of season - ASTRONOMICAL or METEOROLOGICAL
 Display:  Select display mode, all four seasons, or any one of them
 
🔹  Style 
 
 Bar Size & Autofit:  Select the size of the bars and enable/disable the autofit feature
 Labels Size:  Select the label size
 Colors & Gradient:  Select the default color for bullish and bearish returns and enable/disable the gradient feature
Annual Performance Table with Average PeformanceAn indicator that displays annual performance in a table format, providing a quick overview of yearly returns with historical context. 
It calculates the performance based on the first and last monthly close prices of each year. It displays returns chronologically from left to right, concluding with an average performance column.
 Features :
 
 Works exclusively on monthly timeframes
 Customizable number of years to display (1-50 years)
 Shows year-by-year performance percentages
 Color-coded returns (green for positive, red for negative)
 Includes average performance across displayed years
 Semi-transparent overlay design for better chart visibility
 
Performance calculation method:
Performance = ((December Close - January Close) / January Close) × 100%
 Usage :
 
 Apply to any chart on monthly timeframe
 Adjust the "Number of Years to Display" parameter as needed
 Table appears as an overlay with years, individual performances, and average
 
Note: The indicator will display an error message if applied to any timeframe other than monthly.
Relative Performance Indicator by ComLucro - 2025_V01The "Relative Performance Indicator by ComLucro - 2025_V01" is a powerful tool designed to analyze an asset's performance relative to a benchmark index over multiple timeframes. This indicator provides traders with a clear view of how their chosen asset compares to a market index in short, medium, and long-term periods.
 Key Features: 
 
 Customizable Lookback Periods: Analyze performance across three adjustable periods (default: 20, 50, and 200 bars).
 Relative Performance Analysis: Calculate and visualize the difference in percentage performance between the asset and the benchmark index.
 Dynamic Summary Label: Displays a detailed breakdown of the asset's and index's performance for the latest bar.
 User-Friendly Interface: Includes customizable colors and display options for clear visualization.
 
 How It Works: 
 
 The script fetches closing prices of both the asset and a benchmark index.
 It calculates percentage changes over the selected lookback periods.
 The indicator then computes the relative performance difference between the asset and the index, plotting it on the chart for easy trend analysis.
 
 Who Is This For?: 
 
 Traders and investors who want to compare an asset’s performance against a benchmark index.
 Those looking to identify trends and deviations between an asset and the broader market.
 
 Disclaimer: 
This tool is for educational purposes only and does not constitute financial or trading advice. Always use it alongside proper risk management strategies and backtest thoroughly before applying it to live trading.
 Chart Recommendation: 
Use this script on clean charts for better clarity. Combine it with other technical indicators like moving averages or trendlines to enhance your analysis. Ensure you adjust the lookback periods to match your trading style and the timeframe of your analysis.
 Additional Notes: 
For optimal performance, ensure the benchmark index's data is available on your TradingView subscription. The script uses fallback mechanisms to avoid interruptions when index data is unavailable. Always validate the settings and test them to suit your trading strategy.






















