Portfolio [Afnan]🚀  Portfolio   - Advanced Portfolio Management Indicator  📊  
A game-changing portfolio management tool designed to help traders stay on top of their positions and manage risk efficiently. This indicator combines detailed tracking, real-time analytics, and visual clarity to ensure traders are well-equipped for the dynamic world of financial markets.  
📈  Key Features  💡  
   
  Track up to 14 positions with ease  
  Real-time Profit & Loss (P&L) updates and risk metrics  
  Visual representation of entry, stop-loss (SL), and target levels  
  Alerts for stop-loss breaches and target achievements  
  Comprehensive portfolio summaries for quick analysis  
  Customizable options to suit individual trading styles  
   
🔍  Main Components  ⚙️  
📊  1. Position Tracking   
   
  Detailed position data: entry, stop-loss, target levels, and more  
  Real-time risk-reward ratios  
  Insights into position size and exposure percentages  
  Continuous updates on P&L in real-time  
   
📉  2. Visual Indicators   
   
  Clear visual markers for entry, SL, and target prices  
  Price labels with detailed percentage changes  
  Indicators that show the current position's market status  
   
💼  3. Portfolio Summary   
   
  Aggregate account values and exposure  
  Summarized P&L metrics across all positions  
  Risk management insights for better decision-making  
  Daily performance tracking to evaluate strategies  
   
⚠️  4. Alert System   
   
  Instant notifications for stop-loss breaches  
  Alerts when target prices are hit  
  Alerts operate for the current chart symbol  
   
⚡  Customization Options  🎨  
   
  Show or hide specific data columns  
  Adjust the table's position and size for better visibility  
  Personalize color schemes and text styles  
  Switch between full portfolio view and single symbol focus  
   
📱  How to Use  📝  
   
  Input your positions in the indicator's settings  
  Enable or disable specific positions dynamically  
  Customize display preferences to your liking  
  Set up alerts for proactive risk management  
  Monitor all your trading activities in one comprehensive dashboard  
   
📌  Important Notes  ℹ️  
   
  Compatible with any trading symbol  
  Updates seamlessly during market hours  
  Alerts are specific to the currently active chart symbol  
  Maximum capacity: 14 simultaneous positions  
   
 Created by:  @AfnanTAjuddin  
⚠️  Disclaimer  ⚠️  
This indicator is a tool for informational purposes only. Ensure all calculations are verified and consult a financial professional before making investment decisions.  
🎯 "Stay disciplined, trade smart, and let data guide your decisions." 📊  
Performance
US/JP Factor/Sector Performance RankingThis indicator is designed to help you easily understand the strengths and weaknesses of different factors and sectors in the U.S. stock market. It looks at various ETFs, ranks their performance over a specific period (20 days by default), and shows the results visually.
 = How the Ranking Works 
The best-performing rank is shown as -1, with lower ranks as -2, -3, -4, and so on. This setup makes it easy to see rank order in TradingView’s default view.
If you turn on the “Inverse” setting, ranks will be shown as positive numbers in order (e.g., 1, 2, 3…). In this case, it’s recommended to reverse the TradingView scale for better understanding.
 = How the Indicator Reacts to Market Conditions 
- Normal Market Conditions
Certain factors or sectors often stay at the top rank. For example, during the rallies at the start of 2024 and in May, the Momentum factor performed well, showing a risk-on market environment.
On the other hand, sectors at the bottom rank also tend to stay in specific positions.
- Market Tops
Capital flows within sectors slow down, and top ranks begin to change frequently. This may suggest a market turning point.
- Bear Markets or High Volatility
Rankings become more chaotic in these conditions. These large changes can help you understand market sentiment and the level of volatility.
 = Way of using the Indicator 
You can use this indicator in the following ways:
- To apply sector rotation strategies.
- To build positions after volatile markets calm down.
- To take long positions on strong elements (higher ranks) and short positions on weaker ones (lower ranks).
 = Things to Keep in Mind 
It’s a Lagging Indicator
This indicator calculates rankings using the past 20 days of data. It doesn’t provide signals for the future but is a tool for analyzing past performance. To predict the market, you should combine this with other tools or leading indicators.
However, since trends in capital flows often continue, this indicator can help you spot those trends.
 = Customization 
This indicator is set up for U.S. and Japanese stock markets. However, you can customize it for other markets by changing the ticker and label description in the script.
==Japanese Description==
このインジケーターは、米国株市場におけるファクターやセクターの強弱を直感的に把握するために設計されています。
各ETFを参照し、特定期間(デフォルトでは20日間)のパフォーマンスを順位付けし、それを視覚的に表示します。
 = インジケーターの特徴 
- ランク付けの仕様
ランク1位は-1で表され、順位が下がるごとに-2、-3、-4…と減少します。この仕様により、TradingViewの標準状態でランクの高低を直感的に把握できるようにしました。
さらに、Inverse設定をONにすると、1位から順に正の値(例: 1, 2, 3…)で表示されるようになります。この場合、TradingViewのスケールを反転させることを推奨します。
 = 市況とインジケーターの動き 
- 平常時の市況
特定のファクターやセクターがランク1位を維持することが多いです。
例えば、2024年の年初や同年5月の上昇相場では、Momentumファクターが効果を発揮し、リスクオンの市場環境であったことを示しています。
一方、最下位に位置するセクターも特定の順位を維持する傾向があります。
- 天井圏の市況
セクター内の資金流入や流出が停滞し、上位ランクの変動が起こり始めます。これが市場の転換点を示唆する場合があります。
- 下落相場や荒れた市況
ランク順位が大きく乱れることが特徴です。この変動の大きさは、市況の雰囲気やボラティリティの高さを感じ取る材料として活用できます。
 = 活用方法 
このインジケーターは以下のような投資戦略に役立てることができます:
- セクターローテーションを活用した投資戦略
- 荒れた相場が落ち着いたタイミングでのポジション構築
- 強い要素(ランク上位)のロング、弱い要素(ランク下位)のショート
 = 注意点 
- 遅行指標であること
本インジケーターは、過去20日間のデータを基にランクを算出します。そのため、先行的なシグナルを提供するものではなく、過去のパフォーマンスに基づいた分析ツールです。市場を先回りするには、別途先行指標や分析を組み合わせる必要があります。
ただし、特定のファクターやセクターへの資金流入・流出が継続する傾向があるため、これを見極める手助けにはなります。
 = カスタマイズについて 
このインジケーターは米国・日本株市場に特化しています。ただし、他国のファクターやセクターのETFや指数が利用可能であれば、スクリプト内のtickerとlabel descriptionを変更することでカスタマイズが可能です。
MultiSector Performance Tracker [LuxAlgo]The  MultiSector Performance Tracker  tool shows the overall performance of different crypto market sectors within a selected time frame, overlaid on a single chart for easy comparison. 
Users can customize the time frame to suit their specific needs, whether daily, weekly, monthly, or yearly.
🔶  USAGE 
  
The tool displays the performance of up to 6 crypto sectors within a selected time period, such as each day, week, month or year, or from the beginning of the year for any of the last 4 years.
The sectors and tickers within each sector are as follows:
 
 Layer 1:   CRYPTOCAP:ETH   CRYPTOCAP:SOL   CRYPTOCAP:TON 
 Layer 2:   SEED_DONKEYDAN_MARKET_CAP:MATIC   TSX:MNT   AMEX:ARB 
 CEX:   CRYPTOCAP:BNB   CRYPTOCAP:OKB   NYSE:BGB 
 DEX:   CRYPTOCAP:UNI   LSE:JUP   CRYPTOCAP:RUNE 
 AI:   CRYPTOCAP:NEAR   GETTEX:TAO   CRYPTOCAP:ICP 
 Ethereum Memes:   CRYPTOCAP:PEPE   CRYPTOCAP:SHIB   CRYPTOCAP:FLOKI 
 
Traders can compare the relative performance of a custom ticker against the sector of their choice and view the average of all sectors.
The tool is fully customizable, allowing traders to enable or disable any of the features or sectors.
🔹  Dashboard 
  
The tool also displays the data in an ascending or descending sector performance dashboard, allowing traders to see at a glance which sectors are overperforming or underperforming.
Other dashboard features include custom ticker vs. sector comparison and sectors average, and traders can choose the location and size of the dashboard.
🔶  SETTINGS 
 
 Period:  View all data by time period, daily, weekly, etc. Or view data from last year, last 2 years, etc.
 Relative Performance Against:  Enable/Disable relative performance comparison against a sector.
 Use chart ticker:  Enable the use of the chart ticker or a custom ticker for relative performance comparison.
 
🔹  Dashboard 
 
 Show Dashboard:  Enable / disable Dashboard display.
 Order:  Choose between ascending and descending order.
 Position:  Selection of dashboard location.
 Size:  Selection of dashboard size.
 
🔹  Style 
 
 Show Sectors Labels:  Enable / disable sector labels
 Layer 1:  Enable / disable Layer 1 sector
 Layer 2:  Enable / disable Layer 2 sector
 CEX:  Enable / disable CEX sector
 DEX:  Enable / disable DEX sector
 AI:  Enable / disable AI sector
 Ethereum Memes:  Enable / disable Ethereum Memes sector
 Average:  Enable / disable sectors average display
 Custom Ticker:  Enable / disable custom ticker display
Crypto Wallets Profitability & Performance [LuxAlgo]The  Crypto Wallets Profitability & Performance  indicator provides a comprehensive view of the financial status of cryptocurrency wallets by leveraging on-chain data from IntoTheBlock. It measures the percentage of wallets profiting, losing, or breaking even based on current market prices.
Additionally, it offers performance metrics across different timeframes, enabling traders to better assess market conditions.
This information can be crucial for understanding market sentiment and making informed trading decisions.
🔶  USAGE 
  
🔹  Wallets Profitability 
This indicator is designed to help traders and analysts evaluate the profitability of cryptocurrency wallets in real-time. It aggregates data gathered from the blockchain on the number of wallets that are in profit, loss, or breaking even and presents it visually on the chart. 
Breaking even line demonstrates how realized gains and losses have changed, while the profit and the loss monitor unrealized gains and losses.
  
The signal line helps traders by providing a smoothed average and highlighting areas relative to profiting and losing levels. This makes it easier to identify and confirm trading momentum, assess strength, and filter out market noise.
  
🔹  Profitability Meter 
The Profitability Meter is an alternative display that visually represents the percentage of wallets that are profiting, losing, or breaking even.
  
🔹  Performance 
The script provides a view of the financial health of cryptocurrency wallets, showing the percentage of wallets in profit, loss, or breaking even. By combining these metrics with performance data across various timeframes, traders can gain valuable insights into overall wallet performance, assess trend strength, and identify potential market reversals.
  
🔹  Dashboard 
The dashboard presents a consolidated view of key statistics. It allows traders to quickly assess the overall financial health of wallets, monitor trend strength, and gauge market conditions.
  
🔶  DETAILS 
🔹  The Chart Occupation Option 
The chart occupation option adjusts the occupation percentage of the chart to balance the visibility of the indicator.
  
🔹  The Height in Performance Options 
Crypto markets often experience significant volatility, leading to rapid and substantial gains or losses. Hence, plotting performance graphs on top of the chart alongside other indicators can result in a cluttered display. The height option allows you to adjust the plotting for balanced visibility, ensuring a clearer and more organized chart.
  
🔶  SETTINGS 
The script offers a range of customizable settings to tailor the analysis to your trading needs.
 
 Chart Occupation %: Adjust the occupation percentage of the chart to balance the visibility of the indicator.
 
🔹  Profiting Wallets 
 
 Profiting Percentage: Toggle to display the percentage of wallets in profit.
 Smoothing: Adjust the smoothing period for the profiting percentage line.
 Signal Line: Choose a signal line type (SMA, EMA, RMA, or None) to overlay on the profiting percentage.
 
🔹  Losing Wallets 
 
 Losing Percentage: Toggle to display the percentage of wallets in loss.
 Smoothing: Adjust the smoothing period for the losing percentage line.
 Signal Line: Choose a signal line type (SMA, EMA, RMA, or None) to overlay on the losing percentage.
 
🔹  Breaking Even Wallets 
 
 Breaking-Even Percentage: Toggle to display the percentage of wallets breaking even.
 Smoothing: Adjust the smoothing period for the breaking-even percentage line.
 
🔹  Profitability Meter 
 
 Profitability Meter: Enable or disable the meter display, set its width, and adjust the offset.
 
🔹  Performance 
 
 Performance Metrics: Choose the timeframe for performance metrics (Day to Date, Week to Date, etc.).
 Height: Adjust the height of the chart visuals to balance the visibility of the indicator.
 
🔹  Dashboard 
 
 Block Profitability Stats: Toggle the display of profitability stats.
 Performance Stats: Toggle the display of performance stats.
 Dashboard Size and Position: Customize the size and position of the performance dashboard on the chart.
 
🔶  RELATED SCRIPTS 
 
 Market-Sentiment-Technicals 
 Multi-Chart-Widget 
Performance IndicatorPerformance Indicator
This TradingView indicator calculates and displays the performance of a selected price type over a specified timeframe. It also provides the option to display an additional price type with a customizable line color.
Features:
Timeframe Selection: Choose the timeframe for performance calculation (e.g., 3-Month, 1-Year).
Price Type Selection: Select the price type for performance calculation (Open, High, Low, Close).
Customizable Colors: Set colors for the box, text, and lines.
Box Positioning: Choose the position of the information box on the chart.
Additional Price Type: Display an additional price type with a separate customizable line color.
Inputs:
Timeframe: Select the timeframe for performance calculation.
Price Type: Choose the price type (Open, High, Low, Close) for performance calculation.
Box Color: Set the color of the information box.
Text Color: Set the color of the text inside the box.
Line Color: Set the color of the main performance line.
Line Width: Set the width of the main performance line.
Box Position: Choose the position of the information box (Top Right, Top Left, Bottom Right, Bottom Left).
Additional Price Type: Select an additional price type to display (Open, High, Low, Close).
Additional Line Color: Set the color of the additional price line.
How to Use:
Add the Indicator: Add the indicator to your TradingView chart.
Configure Inputs: Use the input options to configure the timeframe, price types, colors, and box position according to your preferences.
View Performance: The indicator will display the performance of the selected price type over the chosen timeframe in the information box.
Additional Price: The additional price type will also be displayed in the information box with a separate line on the chart.
Example:
If you select a 3-Month timeframe and choose “Close” as the price type, the indicator will calculate the performance of the closing price over the last 3 months. It will also display an additional price type (e.g., “Low”) with a separate line on the chart.
Sector Daily Gain/Loss TableOverview: The "Sector Daily Gain/Loss Table" is a custom TradingView indicator designed to display the daily percentage changes in selected cryptocurrency sectors. This indicator provides a comprehensive view of the performance of various cryptocurrencies organized into specific sectors, helping traders and analysts to make informed decisions based on sector performance.
Key Features:
Dynamic Data Retrieval: The indicator retrieves daily closing prices for multiple cryptocurrencies across different exchanges (Binance and Bybit) using the request.security function. This allows users to monitor real-time price movements.
Sectors Covered:
BTC Sector: Includes Bitcoin (BTC).
ETH Sector: Includes Ethereum (ETH).
RWA Sector: Comprises various assets such as OM, ONDO, POLYX, SNX, PENDLE, and HIFI.
L1/L2 Sector: Features major Layer 1 and Layer 2 solutions including ETH, BNB, SOL, XRP, TON, ADA, AVAX, DOT, SUI, APT, ICP, POL, and more.
MEME Sector: Showcases popular meme coins like DOGE, SHIB, PEPE, WIF, BONK, FLOKI, ORDI, BOME, and NEIRO, along with MEW and POPCAT from Bybit.
AI Sector: Highlights AI-related tokens such as TAO, FET, GRT, THETA, WLD, and TURBO.
DEFI Sector: Displays decentralized finance projects including UNI, AAVE, INJ, RUNE, MKR, JUP, LDO, PENDLE, CAKE, LUNA, RAY, OSMO, KAVA, and RSR.
Average Gain/Loss Calculations: For each sector, the indicator calculates the average percentage change in price based on the included cryptocurrencies, offering insights into sector-wide performance trends.
Table Display: The performance metrics are presented in a clean and organized table format on the TradingView chart, providing easy access to vital information for traders.
User-Friendly Design: The table is designed to be visually appealing and informative, with color coding and clear labeling for each sector and its corresponding percentage change.
Usage: Traders can utilize this indicator to quickly assess the performance of various cryptocurrency sectors and make informed trading decisions based on the daily changes in sector performance.
analytics_tablesLibrary  "analytics_tables" 
📝  Description 
This library provides the implementation of several performance-related statistics and metrics, presented in the form of tables.
The metrics shown in the afforementioned tables where developed during the past years of my in-depth analalysis of various strategies in an atempt to reason about the performance of each strategy.
The visualization and some statistics where inspired by the existing implementations of the "Seasonality" script, and the performance matrix implementations of @QuantNomad and @ZenAndTheArtOfTrading scripts.
While this library is meant to be used by my strategy framework "Template Trailing Strategy (Backtester)" script, I wrapped it in a library hoping this can be usefull for other community strategy scripts that will be released in the future.
🤔  How to Guide 
To use the functionality this library provides in your script you have to import it first!
Copy the import statement of the latest release by pressing the copy button below and then paste it into your script. Give a short name to this library so you can refer to it later on. The import statement should look like this:
 import jason5480/analytics_tables/1 as ant 
There are three types of tables provided by this library in the initial release. The stats table the metrics table and the seasonality table.
Each one shows different kinds of performance statistics.
The table UDT shall be initialized once using the `init()` method.
They can be updated using the `update()` method where the updated data UDT object shall be passed.
The data UDT can also initialized and get updated on demend depending on the use case
A code example for the StatsTable is the following:
 var ant.StatsData statsData = ant.StatsData.new()
statsData.update(SideStats.new(), SideStats.new(), 0)
if (barstate.islastconfirmedhistory or (barstate.isrealtime and barstate.isconfirmed))
        var statsTable = ant.StatsTable.new().init(ant.getTablePos('TOP', 'RIGHT'))
        statsTable.update(statsData) 
A code example for the MetricsTable is the following:
 var ant.StatsData statsData = ant.StatsData.new()
statsData.update(ant.SideStats.new(), ant.SideStats.new(), 0)
if (barstate.islastconfirmedhistory or (barstate.isrealtime and barstate.isconfirmed))
    var metricsTable = ant.MetricsTable.new().init(ant.getTablePos('BOTTOM', 'RIGHT'))
    metricsTable.update(statsData, 10) 
A code example for the SeasonalityTable is the following:
 var ant.SeasonalData seasonalData = ant.SeasonalData.new().init(Seasonality.monthOfYear)
seasonalData.update()
if (barstate.islastconfirmedhistory or (barstate.isrealtime and barstate.isconfirmed))
    var seasonalTable = ant.SeasonalTable.new().init(seasonalData, ant.getTablePos('BOTTOM', 'LEFT'))
    seasonalTable.update(seasonalData) 
🏋️♂️ Please refer to the "EXAMPLE" regions of the script for more advanced and up to date code examples!
Special thanks to @Mrcrbw for the proposal to develop this library and @DCNeu for the constructive feedback 🏆.
 getTablePos(ypos, xpos) 
  Get table position compatible string
  Parameters:
     ypos (simple string) : The position on y axise
     xpos (simple string) : The position on x axise
  Returns: The position to be passed to the table
 method init(this, pos, height, width, positiveTxtColor, negativeTxtColor, neutralTxtColor, positiveBgColor, negativeBgColor, neutralBgColor) 
  Initialize the stats table object with the given colors in the given position
  Namespace types: StatsTable
  Parameters:
     this (StatsTable) : The stats table object
     pos (simple string) : The table position string
     height (simple float) : The height of the table as a percentage of the charts height. By default, 0 auto-adjusts the height based on the text inside the cells
     width (simple float) : The width of the table as a percentage of the charts height. By default, 0 auto-adjusts the width based on the text inside the cells
     positiveTxtColor (simple color) : The text color when positive
     negativeTxtColor (simple color) : The text color when negative
     neutralTxtColor (simple color) : The text color when neutral
     positiveBgColor (simple color) : The background color with transparency when positive
     negativeBgColor (simple color) : The background color with transparency when negative
     neutralBgColor (simple color) : The background color with transparency when neutral
 method init(this, pos, height, width, neutralBgColor) 
  Initialize the metrics table object with the given colors in the given position
  Namespace types: MetricsTable
  Parameters:
     this (MetricsTable) : The metrics table object
     pos (simple string) : The table position string
     height (simple float) : The height of the table as a percentage of the charts height. By default, 0 auto-adjusts the height based on the text inside the cells
     width (simple float) : The width of the table as a percentage of the charts width. By default, 0 auto-adjusts the width based on the text inside the cells
     neutralBgColor (simple color) : The background color with transparency when neutral
 method init(this, seas) 
  Initialize the seasonal data
  Namespace types: SeasonalData
  Parameters:
     this (SeasonalData) : The seasonal data object
     seas (simple Seasonality) : The seasonality of the matrix data
 method init(this, data, pos, maxNumOfYears, height, width, extended, neutralTxtColor, neutralBgColor) 
  Initialize the seasonal table object with the given colors in the given position
  Namespace types: SeasonalTable
  Parameters:
     this (SeasonalTable) : The seasonal table object
     data (SeasonalData) : The seasonality data of the table
     pos (simple string) : The table position string
     maxNumOfYears (simple int) : The maximum number of years that fit into the table
     height (simple float) : The height of the table as a percentage of the charts height. By default, 0 auto-adjusts the height based on the text inside the cells
     width (simple float) : The width of the table as a percentage of the charts width. By default, 0 auto-adjusts the width based on the text inside the cells
     extended (simple bool) : The seasonal table with extended columns for performance
     neutralTxtColor (simple color) : The text color when neutral
     neutralBgColor (simple color) : The background color with transparency when neutral
 method update(this, wins, losses, numOfInconclusiveExits) 
  Update the strategy info data of the strategy
  Namespace types: StatsData
  Parameters:
     this (StatsData) : The strategy statistics object
     wins (SideStats) 
     losses (SideStats) 
     numOfInconclusiveExits (int) : The number of inconclusive trades
 method update(this, stats, positiveTxtColor, negativeTxtColor, negativeBgColor, neutralBgColor) 
  Update the stats table object with the given data
  Namespace types: StatsTable
  Parameters:
     this (StatsTable) : The stats table object
     stats (StatsData) : The stats data to update the table
     positiveTxtColor (simple color) : The text color when positive
     negativeTxtColor (simple color) : The text color when negative
     negativeBgColor (simple color) : The background color with transparency when negative
     neutralBgColor (simple color) : The background color with transparency when neutral
 method update(this, stats, buyAndHoldPerc, positiveTxtColor, negativeTxtColor, positiveBgColor, negativeBgColor) 
  Update the metrics table object with the given data
  Namespace types: MetricsTable
  Parameters:
     this (MetricsTable) : The metrics table object
     stats (StatsData) : The stats data to update the table
     buyAndHoldPerc (float) : The buy and hold percetage
     positiveTxtColor (simple color) : The text color when positive
     negativeTxtColor (simple color) : The text color when negative
     positiveBgColor (simple color) : The background color with transparency when positive
     negativeBgColor (simple color) : The background color with transparency when negative
 method update(this) 
  Update the seasonal data based on the season and eon timeframe
  Namespace types: SeasonalData
  Parameters:
     this (SeasonalData) : The seasonal data object
 method update(this, data, positiveTxtColor, negativeTxtColor, neutralTxtColor, positiveBgColor, negativeBgColor, neutralBgColor, timeBgColor) 
  Update the seasonal table object with the given data
  Namespace types: SeasonalTable
  Parameters:
     this (SeasonalTable) : The seasonal table object
     data (SeasonalData) : The seasonal cell data to update the table
     positiveTxtColor (simple color) : The text color when positive
     negativeTxtColor (simple color) : The text color when negative
     neutralTxtColor (simple color) : The text color when neutral
     positiveBgColor (simple color) : The background color with transparency when positive
     negativeBgColor (simple color) : The background color with transparency when negative
     neutralBgColor (simple color) : The background color with transparency when neutral
     timeBgColor (simple color) : The background color of the time gradient
 SideStats 
  Object that represents the strategy statistics data of one side win or lose
  Fields:
     numOf (series int) 
     sumFreeProfit (series float) 
     freeProfitStDev (series float) 
     sumProfit (series float) 
     profitStDev (series float) 
     sumGain (series float) 
     gainStDev (series float) 
     avgQuantityPerc (series float) 
     avgCapitalRiskPerc (series float) 
     avgTPExecutedCount (series float) 
     avgRiskRewardRatio (series float) 
     maxStreak (series int) 
 StatsTable 
  Object that represents the stats table
  Fields:
     table (series table) : The actual table
     rows (series int) : The number of rows of the table
     columns (series int) : The number of columns of the table
 StatsData 
  Object that represents the statistics data of the strategy
  Fields:
     wins (SideStats) 
     losses (SideStats) 
     numOfInconclusiveExits (series int) 
     avgFreeProfitStr (series string) 
     freeProfitStDevStr (series string) 
     lossFreeProfitStDevStr (series string) 
     avgProfitStr (series string) 
     profitStDevStr (series string) 
     lossProfitStDevStr (series string) 
     avgQuantityStr (series string) 
 MetricsTable 
  Object that represents the metrics table
  Fields:
     table (series table) : The actual table
     rows (series int) : The number of rows of the table
     columns (series int) : The number of columns of the table
 SeasonalData 
  Object that represents the seasonal table dynamic data
  Fields:
     seasonality (series Seasonality) 
     eonToMatrixRow (map) 
     numOfEons (series int) 
     mostRecentMatrixRow (series int) 
     balances (matrix) 
     returnPercs (matrix) 
     maxDDs (matrix) 
     eonReturnPercs (array) 
     eonCAGRs (array) 
     eonMaxDDs (array) 
 SeasonalTable 
  Object that represents the seasonal table
  Fields:
     table (series table) : The actual table
     headRows (series int) : The number of head rows of the table
     headColumns (series int) : The number of head columns of the table
     eonRows (series int) : The number of eon rows of the table
     seasonColumns (series int) : The number of season columns of the table
     statsRows (series int) 
     statsColumns (series int) : The number of stats columns of the table
     rows (series int) : The number of rows of the table
     columns (series int) : The number of columns of the table
     extended (series bool) : Whether the table has additional performance statistics
Relative Performance AnalysisRelative Performance Analysis Script 
This Pine Script creates a detailed table on your TradingView chart to compare the performance of a specified asset against a benchmark over multiple time frames. The table is fully customizable, allowing you to select its location on the chart and display performance metrics for different periods.
 Features: 
 
  Customizable Table Location: Choose where the table appears on your chart from a range of predefined positions (e.g., bottom left, top center).
  Dynamic Column Headers: The table includes columns for the ticker, description, and performance metrics for various time periods (1 day, 1 week, 1 month, 3 months, 6 months, and 1 year).
  Performance Calculation: Calculates the percentage change in performance between the current close price and the previous close price for each time frame.
  Color-Coded Performance: Uses a color scheme to highlight performance levels, with specific colors for positive and negative changes to easily visualize performance trends.
  Benchmark and Asset Comparison: Displays performance metrics for both a benchmark (e.g., SPY) and the asset currently viewed on the chart, providing a clear comparison.
 
 Inputs: 
 
 Benchmark Symbol: Specify the symbol of the benchmark asset (e.g., SPY).
  Benchmark Description: Provide a description for the benchmark asset.
  Chart Symbol: Automatically uses the symbol of the chart for comparison.
 
 Usage: 
 
 Add the script to your TradingView chart.
 Configure the benchmark symbol and description as needed.
 The table will automatically populate with performance data and be positioned according to your selection.
 
 Disclaimer:
This script is for informational and educational purposes only and is not intended as financial advice. The performance data displayed in the table is based on historical prices and is not indicative of future performance. Trading involves risk, and you should always do your own research and consult with a qualified financial advisor before making any investment decisions. The creator of this script assumes no responsibility for any losses or damages incurred as a result of using this tool.
TrendMaster ProTrendMaster Pro: A Comprehensive Trend Analysis Tool for Long-Term Investors
TrendMaster Pro is an advanced technical indicator designed to provide long-term investors with a robust and comprehensive analysis of market trends. This sophisticated tool operates exclusively on daily timeframes, making it ideal for those focused on long-term investment strategies. By combining multiple analytical approaches, TrendMaster Pro offers investors a powerful means to assess trend quality and make informed decisions.
Automatic Trend Detection
At the heart of TrendMaster Pro lies its ability to automatically identify the most statistically significant trend. The indicator analyzes various timeframes ranging from 1000 to 5000 days, selecting the one that exhibits the highest correlation. This feature ensures that investors are always working with the most relevant trend data, eliminating the subjectivity often associated with manual trend identification.
The trend detection algorithm employs a regression analysis approach, evaluating approximately 80,000 different trend alternatives each day. Each potential trend is assigned a score based on criteria such as trend density, deviation from regression, and the number of price points near the trend's floor and ceiling. The trend with the highest score is then selected and displayed on the chart.
Comprehensive Scoring System
TrendMaster Pro employs a multi-faceted scoring system that evaluates four key aspects of a trend, providing a holistic view of its quality and potential. Each aspect is scored on a scale of 0 to 10, with the overall trend quality score being a weighted average of these individual scores.
1. Length Score
The Length Score measures the duration of the detected trend. Longer trends receive higher scores, reflecting increased reliability and significance. This score is calculated by normalizing the auto-selected period (which ranges from 1000 to 5000 days) to a scale of 5 to 10.
For example, if the auto-selected period is 3000 days, it would receive a score of around 7.5. This emphasizes the importance of long-term trends in investment decision-making, as they tend to be more stable and indicative of underlying market forces.
2. Strength Score
The Strength Score utilizes Pearson's Correlation Coefficient to assess trend strength. This statistical measure gauges the linear relationship between price and trend projection. A value closer to 1 indicates a strong positive correlation, reinforcing confidence in the trend direction based on historical price movements.
The indicator translates the Pearson's Correlation Coefficient into a score from 0 to 10. For instance, a correlation coefficient of 0.95 might translate to a Strength Score of 8, indicating a strong and reliable trend.
3. Performance Score
The Performance Score compares the asset's Compound Annual Growth Rate (CAGR) to a chosen benchmark, typically a major index like the S&P 500. This score provides insight into how well the asset is performing relative to the broader market.
The CAGR is calculated using the formula: CAGR = (Ending Value / Beginning Value)^(1/n) - 1, where n is the number of years. The Performance Score is then determined by comparing this CAGR to the benchmark's CAGR over the same period. A higher score indicates outperformance relative to the benchmark.
4. Level Score
The Level Score evaluates the current price position within the trend channel. Lower prices within the channel receive higher scores, suggesting potential value or buying opportunities. This score helps identify possible entry points based on historical trend behavior.
For example, if the current price is near the lower boundary of the trend channel, it might receive a Level Score of 9, indicating a potentially attractive entry point.
Visual Representation
TrendMaster Pro provides a clear visual representation of the detected trend by displaying a regression channel on the chart. This channel consists of three lines: a middle line representing the main trend, and upper and lower lines representing standard deviations from the main trend.
The channel offers a quick visual reference for support and resistance levels, helping investors identify potential entry and exit points. The color and style of these lines can be customized to suit individual preferences.
Detailed Information Table
A comprehensive table presents all scores and relevant data, allowing for quick and easy interpretation of the trend analysis. This table includes:
 
 The auto-selected trend length
 The Pearson's Correlation Coefficient
 The asset's CAGR and the benchmark's CAGR
 Individual scores for Length, Strength, Performance, and Level
 The overall Trend Quality Score
 
This table provides investors with a clear, at-a-glance summary of the trend's key characteristics and quality.
Practical Application
To use TrendMaster Pro effectively, investors should consider the following:
 
 Focus on the overall Trend Quality Score as a primary indicator of trend strength and reliability.
 Use the Length Score to gauge the trend's longevity and potential stability.
 Pay attention to the Strength Score to assess how well the price action aligns with the identified trend.
 Utilize the Performance Score to compare the asset's performance against the broader market.
 Consider the Level Score when timing entries, looking for opportunities when prices are relatively low within the trend channel.
 Use the visual trend channel as a guide for potential support and resistance levels.
 
Limitations and Considerations
While TrendMaster Pro offers powerful insights, it's important to remember that no indicator can predict future market movements with certainty. The tool should be used in conjunction with fundamental analysis and other market information.
Additionally, as the indicator is designed for daily charts and long-term analysis, it may not be suitable for short-term trading strategies. Users should also be aware that past performance does not guarantee future results, even with strong trend indications.
Conclusion
TrendMaster Pro represents a significant advancement in trend analysis for long-term investors. By combining automatic trend detection, comprehensive scoring, and benchmark comparison, it offers a powerful tool for those seeking to make informed, data-driven investment decisions. Its ability to objectively assess trend quality across multiple dimensions provides investors with a valuable edge in navigating complex market conditions.
For investors looking to deepen their understanding of market trends and enhance their long-term investment strategies, TrendMaster Pro offers a sophisticated yet accessible solution. As with any investment tool, users are encouraged to thoroughly familiarize themselves with its features and interpret its outputs in the context of their overall investment approach.
(CF|360) Caruso Financial DashboardThe Caruso Financial 360 Dashboard (CF|360)  revolutionizes your TradingView charts by seamlessly integrating comprehensive Fundamental, Statistical, Technical, Performance, and Event information into an intuitively organized dashboard. This empowers users to make informed investment decisions effortlessly, eliminating the need to switch between pages or applications.  
The dashboard is strategically divided into five distinct sections, each color-coded for user-friendly navigation. A quick glance at the dark blue  "Fundamentals"  table reveals two years of quarterly EPS and Sales data, YoY % change, and Surprise %, complete with report dates. Users can explore eight years of annual data and choose between Non-GAAP EPS, Diluted EPS, and Basic EPS for versatile analysis. Opting for Non-GAAP EPS also unveils next quarter estimates. The Fundamentals section further encompasses P/E and P/S data, alongside TTM dividend and dividend yield information.  
In the yellow  "Extended Fundamentals"  section, users gain insights into Gross, EBITDA, and Net margins for easy profitability comparisons within the same industry group. Return on Equity data and Free Cashflow per share provide perspectives on profitability, efficiency, and financial flexibility.  
The light blue  "Statistics"  section furnishes essential statistical measures for a rapid grasp of a company's trading characteristics. Metrics such as Market Cap, Average Volume per day (Shares and $ value), VWAP, Up/Down volume ratio, ATR%, Alpha, Beta, Shares Outstanding & Float, 52-week High/Low, and % distance from the 52-week high are presented. Additionally, market breadth is depicted through Nasdaq and NYSE 52-week high/low data.  
The purple  "Technical & Performance"  section seamlessly integrates both  Technical Analysis   data and  Performance  statistics, enabling users to assess the stock's technical context and performance against the market over different periods. Technical indicators, including three customizable moving average types, RSI, ADX, Bollinger Band, Keltner Band, and daily and weekly closing ranges, are featured.  
The grey top  "Events"  section offers a quick overview of the next earnings release date, countdown, and associated color changes as the date approaches. Company name, sector, and industry details are also presented.  
To enhance information visibility, record EPS and Sales data are highlighted, emphasizing new records, along with highlights for new 52-week highs and lows. 
The CF|360 offers  customization options , including three display styles for Desktops, Desktop Slim, and Mobile devices.
Users can also tailor the lengths of technical indicators to suit their preferences.  International market enthusiasts will appreciate that the CF|360 provides financial and market data for various regions, including the US, EU, Canada, and beyond.
 88 Metrics Included: 
 Fundamentals Section  (Dark Blue Group)
EPS (Adjusted Non-GAAP, Diluted, Basic) 
- Quarterly, YoY % Chg, Surprise, Report Date, Next Quarter Estimate (Adjusted EPS only)
- Annual, YoY % Chg
Sales 
- Quarterly, YoY % Chg, Surprise, Report Date, Next Quarter Estimate
- Annual, YoY % Chg
P/E ratio
P/S ratio
Dividend TTM
Dividend TTM Yield
 Fundamentals Extended  (Yellow Group) 
Gross Margin  
EBITDA Margin  
Net Margin  
Return on Equity (ROE)  
Free Cashflow per Share (FCFPS)  
Debt to Equity (Debt)  
Effective Interest Rate (Int Rate)  
 Statistics  (Light Blue Group) 
Market Cap
Average Daily Volume (Shares)
Average Daily Volume (Dollar Value)
VWAP (Daily)
Average True Range Percent
Shares Outstanding
Shares in Float
Percentage of Share in Float
52-Week High
52-Week Low
% off of 52-Week High
Up / Down Volume Ratio
Beta
Alpha
Nasdaq Net 52-Week High/Lows
Nasdaq 52-Week Highs
Nasdaq 52-Week Lows
NYSE Net 52-Week High/Lows
NYSE 52-Week Highs
NYSE 52-Week Lows
 Technical & Performance  (Purple Group)
Moving Average Value (3 different averages)
Distance from Moving Average (3 different averages)
Relative Strength Index (RSI)
Average Directional Index (ADX)
Bollinger Band Value (Upper/Lower)
%b
Keltner Band Value (Upper/Lower)
%k
Percentage Changes Since Today’s Open
Daily Closing Range (DCR)
Weekly Closing Range (WCR)
Current Week % Change
1 Month % Change
3 Month % Change
6 Month % Change
1 Year % Change
3 Year % Change
YTD % Change
S&P 500 YTD % Change
 Name, Group, & Events  (Grey Section)
Company Name
Sector
Industry
Next Earnings Date
Days Until Next Earnings Date
 Event Highlights 
Record EPS (Quarterly/Annual)  
Record Sales (Quarterly/Annual)  
52-Week High  
52-Week Low  
 Layout Types 
 Desktop
 Get the full experience with the Desktop view.
  
 Desktop Slim
 Save screen real estate with a slim version of the dashboard.
  
 Mobile 
Take the most vital metrics with you on your mobile device. For the best experience, view in landscape mode.
  
Blockunity Level Presets (BLP)A simple tool for setting performance targets. 
Level Presets (BLP) is a simple tool for setting upside and downside levels relative to the current price of any asset. In this way, you can track which price the asset needs to move towards in order to achieve a defined performance.
 How to Use 
This indicator is very easy to use, you can set up to 5 upward and downward targets in the parameters.
 Elements 
The main elements of this tool are upward (default green) and downward (default red) levels.
 Settings 
Several parameters can be defined in the indicator configuration.
In addition to configuring which performance value to set the level at, you can choose not to display it if you don't need it. For example, here we display only two levels: 
  
You can also choose not to display the labels:
  
Also concerning labels, you can choose not to display them in currency format, but in numerical format only (for example, if you're viewing a non-USD pair, such as ETHBTC):
  
Finally, you can modify design elements such as colors, level widths and text size:
  
 How it Works 
Here's how upside (_u) and downside (_d) levels are calculated:
 
source          =   close
level_1_u       =   source + (source * (level_1 / 100))
level_1_d       =   math.max(source - (source * (level_1 / 100)), 0)
Annualized ReturnThis is a straightforward tool for investors, offering the capability to select a specific start date and visualize the annualized return of the currently displayed asset.
Annualized return is a crucial metric for investors, as it provides a standardized measure of an investment's performance, making it easier to compare different investments.  By annualizing returns, investors can gain insights into the average yearly growth rate of their investments, enabling more informed decision-making and portfolio management .
Selecting various start dates enables users to understand how market timing can influence the success of their investments.
The annualized return is calculated using the following formula :
AnnualizedReturn = (Ending price / Beginning price) ^ (1 / Number of Years) − 1
Blockunity Performance Oscillator (BPO)The Performance Oscillator (BPO) is an intuitive indicator that makes it easy to analyze the performance of any asset. It operates over 5 simultaneously configurable periods. All design elements are also customizable. The integrated table summarizes the information in color, so you can quickly assess the different variations.
 How it works 
The operation of this script is quite simple. It calculates the performance of the selected asset over the different lookback periods indicated in the parameters (default: 1, 7, 30, 120 and 365). It then plots the lines in an independent panel (it is possible to hide lines by unchecking them in the parameters). Finally, performance information is displayed in a table for enhanced clarity.
 The Idea 
The idea is to bring information about the performance of any asset into your TradingView chart, and to make it visual. What's more, it can give an idea of the asset's trend, as, for example, if all periods are green (positive) in the table, then we can deduce that the selected asset is in a clear uptrend.
Being able to visually analyze several variations over different periods at the same time, while adding this information to a colorful table, makes it unique.
 Usage Advice 
You can use this indicator on any asset or index.
For example, if you use the indicator in a daily timeframe, the default periods will be 1 day, 7 days, 30 days, etc. If you use the indicator in a horary timeframe, the default periods will be 1 hour, 7 hours, 30 hours, etc.
 Parameters 
 
  Display of different periods.
  Periods according to the timeframe selected on the graph.
  Line widths.
  Line colors.
  Table parameters.
S&P Sector PerformanceS&P Sector Performance calculate and display the logarithmic returns of SPX and each S&P Sector for a predefined timeframe or for a custom date. 
Momentum ChannelbandsThe "Momentum Channelbands" is indicator that measures and displays an asset's momentum. It includes options to calculate Bollinger Bands and Donchian Channels around the momentum. Users can customize settings for a comprehensive view of momentum-related insights. This tool helps assess trend strength, identify overbought/oversold conditions, and pinpoint highs/lows. It should be used alongside other indicators due to potential lag and false signals.
Multi-Asset Performance [Spaghetti] - By LeviathanThis indicator visualizes the cumulative percentage changes or returns of 30 symbols over a given period and offers a unique set of tools and data analytics for deeper insight into the performance of different assets.
Multi Asset Performance indicator (also called “Spaghetti”) makes it easy to monitor the changes in Price, Open Interest, and On Balance Volume across multiple assets simultaneously, distinguish assets that are overperforming or underperforming, observe the relative strength of different assets or currencies, use it as a tool for identifying mean reversion opportunities and even for constructing pairs trading strategies, detect "risk-on" or "risk-off" periods, evaluate statistical relationships between assets through metrics like correlation and beta, construct hedging strategies, trade rotations and much more.
Start by selecting a time period (e.g., 1 DAY) to set the interval for when data is reset. This will provide insight into how price, open interest, and on-balance volume change over your chosen period. In the settings, asset selection is fully customizable, allowing you to create three groups of up to 30 tickers each. These tickers can be displayed in a variety of styles and colors. Additional script settings offer a range of options, including smoothing values with a Simple Moving Average (SMA), highlighting the top or bottom performers, plotting the group mean, applying heatmap/gradient coloring, generating a table with calculations like beta, correlation, and RSI, creating a profile to show asset distribution around the mean, and much more.
One of the most important script tools is the screener table, which can display:
🔸 Percentage Change (Represents the return or the percentage increase or decrease in Price/OI/OBV over the current selected period)
🔸 Beta (Represents the sensitivity or responsiveness of asset's returns to the returns of a benchmark/mean. A beta of 1 means the asset moves in tandem with the market. A beta greater than 1 indicates the asset is more volatile than the market, while a beta less than 1 indicates the asset is less volatile. For example, a beta of 1.5 means the asset typically moves 150% as much as the benchmark. If the benchmark goes up 1%, the asset is expected to go up 1.5%, and vice versa.)
🔸 Correlation (Describes the strength and direction of a linear relationship between the asset and the mean. Correlation coefficients range from -1 to +1. A correlation of +1 means that two variables are perfectly positively correlated; as one goes up, the other will go up in exact proportion. A correlation of -1 means they are perfectly negatively correlated; as one goes up, the other will go down in exact proportion. A correlation of 0 means that there is no linear relationship between the variables. For example, a correlation of 0.5 between Asset A and Asset B would suggest that when Asset A moves, Asset B tends to move in the same direction, but not perfectly in tandem.)
🔸 RSI (Measures the speed and change of price movements and is used to identify overbought or oversold conditions of each asset. The RSI ranges from 0 to 100 and is typically used with a time period of 14. Generally, an RSI above 70 indicates that an asset may be overbought, while RSI below 30 signals that an asset may be oversold.)
⚙️ Settings Overview:
◽️ Period
Periodic inputs (e.g. daily, monthly, etc.) determine when the values are reset to zero and begin accumulating again until the period is over. This visualizes the net change in the data over each period. The input "Visible Range" is auto-adjustable as it starts the accumulation at the leftmost bar on your chart, displaying the net change in your chart's visible range. There's also the "Timestamp" option, which allows you to select a specific point in time from where the values are accumulated. The timestamp anchor can be dragged to a desired bar via Tradingview's interactive option. Timestamp is particularly useful when looking for outperformers/underperformers after a market-wide move. The input positioned next to the period selection determines the timeframe on which the data is based. It's best to leave it at default (Chart Timeframe) unless you want to check the higher timeframe structure of the data.
◽️ Data
The first input in this section determines the data that will be displayed. You can choose between Price, OI, and OBV. The second input lets you select which one out of the three asset groups should be displayed. The symbols in the asset group can be modified in the bottom section of the indicator settings.
◽️ Appearance
You can choose to plot the data in the form of lines, circles, areas, and columns. The colors can be selected by choosing one of the six pre-prepared color palettes.
◽️ Labeling
This input allows you to show/hide the labels and select their appearance and size. You can choose between Label (colored pointed label), Label and Line (colored pointed label with a line that connects it to the plot), or Text Label (colored text).
◽️ Smoothing
If selected, this option will smooth the values using a Simple Moving Average (SMA) with a custom length. This is used to reduce noise and improve the visibility of plotted data.
◽️ Highlight 
If selected, this option will highlight the top and bottom N (custom number) plots, while shading the others. This makes the symbols with extreme values stand out from the rest.
◽️ Group Mean
This input allows you to select the data that will be considered as the group mean. You can choose between Group Average (the average value of all assets in the group) or First Ticker (the value of the ticker that is positioned first on the group's list). The mean is then used in calculations such as correlation (as the second variable) and beta (as a benchmark). You can also choose to plot the mean by clicking on the checkbox.
◽️ Profile
If selected, the script will generate a vertical volume profile-like display with 10 zones/nodes, visualizing the distribution of assets below and above the mean. This makes it easy to see how many or what percentage of assets are outperforming or underperforming the mean.
◽️ Gradient
If selected, this option will color the plots with a gradient based on the proximity of the value to the upper extreme, zero, and lower extreme.
◽️ Table
This section includes several settings for the table's appearance and the data displayed in it. The "Reference Length" input determines the number of bars back that are used for calculating correlation and beta, while "RSI Length" determines the length used for calculating the Relative Strength Index. You can choose the data that should be displayed in the table by using the checkboxes.
◽️ Asset Groups
This section allows you to modify the symbols that have been selected to be a part of the 3 asset groups. If you want to change a symbol, you can simply click on the field and type the ticker of another one. You can also show/hide a specific asset by using the checkbox next to the field.
Sector Spaghetti [CE]Sector Spaghetti  
An overlay indicator for multiple sectors that is configurable for multi asset configuration to track the returns of sectors in the market.
The tool provides three different viewing modes for returns; a rolling bar lookback, a specific data and time anchor, and a visible range.
Included is a pre built list of sectors created by none other than DaanCryptoTrades, the list includes a large range of sectors to cover the depth of the market as a whole.
Additionally a pre configured custom sectors list has been provided, we have included Daan's custom list within the custom sectors but provided the use of an additional feature "weight".
The weight feature is an intuitive method of applying importance to assets in there relevant sectors, we have used this as an opportunity to show the ability of creating market cap weighted sectors to balance the assets accordingly. This can provide useful in sectors where a low market cap + high beta asset could typically skew the results in one direction even if the remainder of the sector may be performing differently.
Non Market Cap:
  
Meme and Dex seem to be performing similarly
Market Cap: 
  
Assets weighted via market cap shows relatively Meme sector is out performing
We have also added an optional table to the right of the screen so that the trader can clearly see outperforming assets. This table is toggleable using radio buttons within the Style menu. Updating the code we have provided users the ability to customize the table to further improve readability of the Text and reduce screen noise where needed.
To improve asset visibility, the script also calculates the 'long tail' of the list distribution and automatically lowers the visibility of clustered assets in the centre.
 To Do 
 
  Alerts for sector performance
 
Rolling Risk-Adjusted Performance RatiosThis simple indicator calculates and provides insights into different performance metrics of an asset - Sharpe, Sortino and Omega Ratios in particular. It allows users to customize the lookback period and select their preferred data source for evaluation of an asset.
 Sharpe Ratio: 
The Sharpe Ratio measures the risk-adjusted return of an asset by considering both the average return and the volatility or riskiness of the investment. A higher Sharpe Ratio indicates better risk-adjusted performance. It allows investors to compare different assets or portfolios and assess whether the returns adequately compensate for the associated risks. A higher Sharpe Ratio implies that the asset generates more return per unit of risk taken.
 Sortino Ratio: 
The Sortino Ratio is a variation of the Sharpe Ratio that focuses specifically on the downside risk or volatility of an asset. It takes into account only the negative deviations from the average return (downside deviation). By considering downside risk, the Sortino Ratio provides a more refined measure of risk-adjusted performance, particularly for investors who are more concerned with minimizing losses. A higher Sortino Ratio suggests that the asset has superior risk-adjusted returns when considering downside volatility.
 Omega Ratio: 
The Omega Ratio measures the probability-weighted ratio of gains to losses beyond a certain threshold or target return. It assesses the skewed nature of an asset's returns by differentiating between positive and negative returns and assigning more weight to extreme gains or losses. The Omega Ratio provides insights into the potential asymmetry of returns, highlighting the potential for significant positive or negative outliers. A higher Omega Ratio indicates a higher probability of achieving large positive returns compared to large negative returns.
 Utility: 
 
 Performance Evaluation:  Provides assessment of an asset's performance, considering both returns and risk factors.
 Risk Comparison:  Allows for comparing the risk-adjusted returns of different assets or portfolios. Helps identify investments with better risk-reward trade-offs.
 Risk Management:  Assists in managing risk exposure by evaluating downside risks and volatility.
Monthly Strategy Performance TableWhat Is This? 
This script code adds a Monthly Strategy Performance Table to your Pine Script strategy scripts so you can see a month-by-month and year-by-year breakdown of your P&L as a percentage of your account balance.
The table is based on realized equity rather than open equity, so it only updates the metrics when a trade is closed. 
That's why some numbers will not match the Strategy Tester metrics (such as max drawdown), as the Strategy Tester bases metrics like max drawdown on open trade equity and not realized equity (closed trades).
The script is still a work-in-progress, so make sure to read the disclaimer below. But I think it's ready to release the code for others to play around with.
 How To Use It 
The script code includes one of my strategies as an example strategy. You need to replace my strategy code with your own. To do that just copy the source code below into a blank script, delete lines 11 -> 60 and paste your strategy code in there instead of mine. The script should work with most systems, but make sure to read the disclaimer below.
It works best with a significant amount of historical data, so it may not work very effectively on intraday timeframes as there is a severe limitation of available bars on TradingView. I recommend using it on 4HR timeframes and above, as anything less will produce very little usable data. Having a premium TradingView plan will also help boost the number of available bars.
You can hover your mouse over a table cell to get more information in the form of tooltips (such as the Long and Short win rate if you hover over your total return cell).
 Credit 
The code in this script is based on open-source code originally written by QuantNomad, I've made significant changes and additions to the original script but all credit for the idea and especially the display table code goes to them - I just built on top of it:
  
 Why Did I Make This? 
None of this is trading or investment advice, just my personal opinion based on my experience as a trader and systems developer these past 6+ years:
The TradingView Strategy Tester is severely limited in some important ways. And unless you use complex Excel formulas on exported test data, you can't see a granular perspective of your system's historical performance.
There is much more to creating profitable and tradeable systems than developing a strategy with a good win rate and a good return with a reasonable drawdown.
Some additional questions we need to ask ourselves are:
 
 What did the system's worst drawdown look like?
 How long did it last?
 How often do drawdowns occur, and how quickly are they typically recovered?
 How often do we have a break-even or losing month or year?
 What is our expected compounded annual growth rate, and how does that growth rate compare to our max drawdown?
 
And many more questions that are too long to list and take a lifetime of trading experience to answer.
Without answering these kinds of questions, we run the risk of developing systems that look good on paper, but when it comes to live trading, we are uncomfortable or incapable of enduring the system's granular characteristics.
This Monthly Performance Table script code is intended to help bridge some of that gap with the Strategy Tester's limited default performance data.
 Disclaimer 
I've done my best to ensure the numbers this code outputs are accurate, and according to my testing with my personal strategy scripts it appears to work fine. But there is always a good chance I've missed something, or that this code will not work with your particular system.
The majority of my TradingView systems are extremely simple single-target systems that operate on a closed-candle basis to minimize many of the data reliability issues with the Strategy Tester, so I was unable to do much testing with multiple targets and pyramiding etc.
I've included a Debug option in the script that will display important data and information on a label each time a trade is closed. I recommend using the Debug option to confirm that the numbers you see in the table are accurate and match what your strategy is actually doing.
Always do your own due diligence, verify all claims as best you can, and never take anyone's word for anything.
Take care, and best of luck with your trading :)
Kind regards,
Matt.
 PS. If you're interested in learning how this script works, I have a free hour-long video lesson breaking down the source code - just check out the links below this script or in my profile.
relative performanceThis indicator is built to mesure the performance of a stock vs the index of choice. it is best use for the intraday session because it doesn't take gap into account when doing the calculation. This is how i made my math (using AAPL compared to SPY for simplicity)
(change AAPL / ATR AAPL) - (change SPY / ATR SPY) * beta factor * volume factor
change is calculated open to close for each candle instead of close to close. this is why gap does not affect the calculation
blue columns is an instant snap shot of the RP
red and green columns is the moving average of the blue columns
limit is the max value for the blue line when ploting them on the chart but doesn't affect the calculation
option: 
indice: default with SPY but could use any stock 
moving average choice:  let you choose between EMA or SMA green and red columns
rolling average length : number of bar for the moving average
I made an auto adjust for the 5 min chart and the 2 min chart so you can swithc between both chart and have the same average (default value set to 6x 5min and 15x 2 min, giving you the average of the last 30min)
volume weighing let you choose if you want a volume factor or not. volume factor is only going to multiplie the result of the price move. it cannot move it from positive to negative. 
this is the calculation 
(volume AAPL / volume SMA AAPL) / (volume SPY / volume sma SPY) 
meaning that a higher volume on the thicker compared to it's sma while having a lower volume on SPY will give you a big relative performance.
you can choose the number of bar in the average for the volume.
BETA factor work the same way that the volume factor does. you got to manualy enter your beta. default is set to 1.5
table 
top line : blue square is you RP value (same has the blue columns bar) and your reference thicker
middle line : pourcentage move from the open (9:30 open) for your stock on the left and the reference on the right
bottom line : beta on the left and volume factor on the right
feel free to ask question or give modification idea!
Bitwise, Encode, DecodeLibrary   "Bitwise, Encode, Decode" 
Bitwise, Encode, Decode, and more Library
 docs() 
      Hover-Over Documentation for inside Text Editor
 bAnd(a, b) 
  Returns the bitwise AND of two integers  
  Parameters:
     a : `int` - The first integer
     b : `int` - The second integer
  Returns: `int` - The bitwise AND of the two integers
 bOr(a, b) 
  Performs a bitwise OR operation on two integers.  
  Parameters:
     a : `int` - The first integer.
     b : `int` - The second integer.
  Returns: `int` - The result of the bitwise OR operation.
 bXor(a, b) 
  Performs a bitwise Xor operation on two integers.  
  Parameters:
     a : `int` - The first integer.
     b : `int` - The second integer.
  Returns: `int` - The result of the bitwise Xor operation.
 bNot(n) 
  Performs a bitwise NOT operation on an integer.  
  Parameters:
     n : `int` - The integer to perform the bitwise NOT operation on.
  Returns: `int` - The result of the bitwise NOT operation.
 bShiftLeft(n, step) 
  Performs a bitwise left shift operation on an integer.  
  Parameters:
     n : `int` - The integer to perform the bitwise left shift operation on.
     step : `int` - The number of positions to shift the bits to the left.
  Returns: `int` - The result of the bitwise left shift operation.
 bShiftRight(n, step) 
  Performs a bitwise right shift operation on an integer.  
  Parameters:
     n : `int` - The integer to perform the bitwise right shift operation on.
     step : `int` - The number of bits to shift by.
  Returns: `int` - The result of the bitwise right shift operation.
 bRotateLeft(n, step) 
  Performs a bitwise right shift operation on an integer.
  Parameters:
     n : `int` - The int to perform the bitwise Left rotation on the bits.                        
     step : `int` - The number of bits to shift by.
  Returns: `int`- The result of the bitwise right shift operation.
 bRotateRight(n, step) 
  Performs a bitwise right shift operation on an integer.
  Parameters:
     n : `int` - The int to perform the bitwise Right rotation on the bits.
     step : `int` - The number of bits to shift by.
  Returns: `int` - The result of the bitwise right shift operation.
 bSetCheck(n, pos) 
  Checks if the bit at the given position is set to 1.
  Parameters:
     n : `int` - The integer to check.
     pos : `int` - The position of the bit to check.
  Returns: `bool` - True if the bit is set to 1, False otherwise.
 bClear(n, pos) 
  Clears a particular bit of an integer (changes from 1 to 0) passes if bit at pos is 0.
  Parameters:
     n : `int` - The integer to clear a bit from.
     pos : `int` - The zero-based index of the bit to clear.
  Returns: `int` - The result of clearing the specified bit.
 bFlip0s(n) 
  Flips all 0 bits in the number to 1.
  Parameters:
     n : `int` - The integer to flip the bits of.
  Returns: `int` - The result of flipping all 0 bits in the number.
 bFlip1s(n) 
  Flips all 1 bits in the number to 0.
  Parameters:
     n : `int` - The integer to flip the bits of.
  Returns: `int` - The result of flipping all 1 bits in the number.
 bFlipAll(n) 
  Flips all bits in the number.
  Parameters:
     n : `int` - The integer to flip the bits of.
  Returns: `int` - The result of flipping all bits in the number.
 bSet(n, pos, newBit) 
  Changes the value of the bit at the given position.
  Parameters:
     n : `int` - The integer to modify.
     pos : `int` - The position of the bit to change.
     newBit : `int` - na = flips bit at pos reguardless 1 or 0 | The new value of the bit (0 or 1).
  Returns: `int` - The modified integer.
 changeDigit(n, pos, newDigit) 
  Changes the value of the digit at the given position.
  Parameters:
     n : `int` - The integer to modify.
     pos : `int` - The position of the digit to change.
     newDigit : `int` - The new value of the digit (0-9).
  Returns: `int` - The modified integer.
 bSwap(n, i, j) 
  Switch the position of 2 bits of an int
  Parameters:
     n : `int` - int to manipulate
     i : `int` - bit pos to switch with j
     j : `int` - bit pos to switch with i
  Returns: `int` - new int with bits switched
 bPalindrome(n) 
  Checks to see if the binary form is a Palindrome (reads the same left to right and vice versa)
  Parameters:
     n : `int` - int to check
  Returns: `bool` - result of check
 bEven(n) 
  Checks if n is Even
  Parameters:
     n : `int` - The integer to check.
  Returns: `bool` - result.
 bOdd(n) 
  checks if n is Even if not even Odd
  Parameters:
     n : `int` - The integer to check.
  Returns: `bool` - result.
 bPowerOfTwo(n) 
  Checks if n is a Power of 2.
  Parameters:
     n : `int` - number to check.
  Returns: `bool` - result.
 bCount(n, to_count) 
  Counts the number of bits that are equal to 1 in an integer.
  Parameters:
     n : `int` - The integer to count the bits in.
     to_count  `string` -   the bits to count
  Returns: `int` - The number of bits that are equal to 1 in n.
 GCD(a, b) 
  Finds the greatest common divisor (GCD) of two numbers.
  Parameters:
     a : `int` - The first number.
     b : `int` - The second number.
  Returns: `int` - The GCD of a and b.
 LCM(a, b) 
  Finds the least common multiple (LCM) of two integers.
  Parameters:
     a : `int` - The first integer.
     b : `int` - The second integer.
  Returns: `int` - The LCM of a and b.
 aLCM(nums) 
  Finds the LCM of an array of integers.
  Parameters:
     nums : `int ` - The list of integers.
  Returns: `int` - The LCM of the integers in nums.
 adjustedLCM(nums, LCM) 
  adjust an array of integers to Least Common Multiple (LCM)
  Parameters:
     nums : `int ` - The first integer
     LCM : `int` - The second integer
  Returns: `int ` - array of ints with LCM
 charAt(str, pos) 
  gets a Char at a given position.
  Parameters:
     str : `string` - string to pull char from.
     pos : `int` - pos to get char from string (left to right index).
  Returns: `string` - char from pos of string or "" if pos is not within index range
 decimalToBinary(num) 
  Converts a decimal number to binary
  Parameters:
     num : `int` - The decimal number to convert to binary
  Returns: `string` - The binary representation of the decimal number
 decimalToBinary(num, to_binary_int) 
  Converts a decimal number to binary
  Parameters:
     num : `int` - The decimal number to convert to binary
     to_binary_int : `bool` - bool to convert to int or to string (true for int, false for string)
  Returns: `string` - The binary representation of the decimal number
 binaryToDecimal(binary) 
  Converts a binary number to decimal
  Parameters:
     binary : `string` - The binary number to convert to decimal
  Returns: `int` - The decimal representation of the binary number
 decimal_len(n) 
  way of finding decimal length using arithmetic
  Parameters:
     n  `float` - floating decimal point to get length of.
  Returns: `int` - number of decimal places
 int_len(n) 
  way of finding number length using arithmetic
  Parameters:
     n : `int`- value to find length of number
  Returns: `int` - lenth of nunber i.e. 23 == 2
 float_decimal_to_whole(n) 
  Converts a float decimal number to an integer `0.365 to 365`.
  Parameters:
     n : `string` - The decimal number represented as a string.
  Returns: `int` - The integer obtained by removing the decimal point and leading zeroes from s.
 fractional_part(x) 
  Returns the fractional part of a float.
  Parameters:
     x : `float` - The float to get the fractional part of.
  Returns: `float` - The fractional part of the float.
 form_decimal(a, b, zero_fix) 
  helper to form 2 ints into 1 float seperated by the decimal
  Parameters:
     a : `int` - a int
     b : `int` - b int
     zero_fix : `bool` - fix for trailing zeros being truncated when converting to float
  Returns: ` ` - float = float decimal of ints | string = string version of b for future use to ref length
 bEncode(n1, n2) 
  Encodes two numbers into one using bit OR. (fastest)
  Parameters:
     n1 : `int` - The first number to Encodes.
     n2 : `int` - The second number to Encodes.
  Returns: `int` - The result of combining the two numbers using bit OR.
 bDecode(n) 
  Decodes an integer created by the bCombine function.(fastest)
  Parameters:
     n : `int` - The integer to decode.
  Returns: ` ` - A tuple containing the two decoded components of the integer.
 Encode(a, b) 
  Encodes by seperating ints into left and right of decimal float
  Parameters:
     a : `int` - a int
     b : `int` - b int
  Returns: `float` - new float of encoded ints one on left of decimal point one on right
 Decode(encoded) 
  Decodes float of 2 ints seperated by decimal point
  Parameters:
     encoded : `float` - the encoded float value
  Returns: ` ` - tuple of the 2 ints from encoded float
 encode_heavy(a, b) 
  Encodes by combining numbers and tracking size in the
decimal of a floating number (slowest)
  Parameters:
     a : `int` - a int
     b : `int` - b int
  Returns: `float` - new decimal of encoded ints
 decode_heavy(encoded) 
  Decodes encoded float that tracks size of ints in float decimal 
  Parameters:
     encoded : `float` - encoded float
  Returns: ` ` - tuple of decoded ints
 decimal of float (slowest) 
  Parameters:
     encoded : `float` - the encoded float value
  Returns: ` ` - tuple of the 2 ints from encoded float
 Bitwise, Encode, Decode Docs  
 
  In the documentation you may notice the word decimal   
not used as normal this is because when referring to   
binary a decimal number is a number that  
can be represented with base 10 numbers 0-9   
(the wiki below explains better)  
  A rule of thumb for the two integers being   
encoded it to keep both numbers   
less than 65535 this is because anything lower uses 16 bits or less   
this will maintain 100% accuracy when decoding   
although it is possible to do numbers up to 2147483645 with   
this library doesnt seem useful enough  
to explain or demonstrate.  
  The functions provided work within this 32-bit range,   
where the highest number is all 1s and   
the lowest number is all 0s. These functions were created   
to overcome the lack of built-in bitwise functions in Pinescript.   
By combining two integers into a single number,  
the code can access both values i.e when   
indexing only one array index  
for a matrices row/column, thus improving execution time.   
This technique can be applied to various coding   
scenarios to enhance performance.  
  Bitwise functions are a way to use integers in binary form      
that can be used to speed up several different processes      
most languages have operators to perform these function such as      
`<<, >>, &, ^, |, ~` 
 
 en.wikipedia.org  
SFC Smart Money  BenchmarkA benchmark is a standard or point of reference, which traders can use to measure something else.
This indicator is showing how correlated pairs are performing and what is the current correlation between them.
Features:
- Market performance - daily, weekly, monthly
- Sigma - volatility . It will be coloured in red, if the volatility is bigger than one standard deviation.
-Correlation - Positive correlation will be coloured in green if it is confirmed by the P-value, negative correlation in red.
-Confidence intervals
-Determination
Markets:
- Metal sector
- US Stock Indices
- Major USD Pairs
 Market performance 
The indicator is plotting a table with the current performance of the particular group, for example the metal sector and all correlated Gold pairs. The table is showing the performance of the pairs based on monthly, weekly and daily bases in the same time. In this case the trader can track all pairs simultaneously and see if there are anomalies between the pairs - SMT Divergence.
For example:
We know that Gold and Silver are very strong correlated pairs. In this case if Gold is going up, but Silver not, probably this move is only current manipulation and the true move is not clear. In that moment the trader can decide not to open an order or take some profit.
With the Sigma value traders also can track the current volatility of the price. The strength of the volatility is measured by the standard deviation.
-1>Sigma<1 - The asset is moving normally
-2>Sigma<-1 or 21 - The asset is volatile
-3>Sigma<-2 or 32 - The asset is very volatile
 Correlation 
The indicator is showing the current correlation between all pair from the table. The correlation is set to the first pair of the table. In order to make the correlation more accurate the indicator calculates the P-value and the Determination coefficient. The confidence intervals are also displayed in order to show how strong correlation should be expected.
Pearson correlation is a measure of linear correlation between two sets of data. It is the ratio between the covariance of two variables and the product of their standard deviations; thus, it is essentially a normalized measurement of the covariance, such that the result always has a value between −1 and 1. As with covariance itself, the measure can only reflect a linear correlation of variables, and ignores many other types of relationships or correlations.
P-value evaluates how well your data rejects the null hypothesis, which states that there is no relationship between two compared groups. Successfully rejecting this hypothesis tells you that your results may be statistically significant. In academic research, p-value is defined as the probability of obtaining results ‘as extreme’ or ‘more extreme’, given that the null hypothesis is true — essentially, how likely it is that you would receive the results (or more dramatic results) you did assuming that there is no correlation or relationship (e.g. the thing that you’re testing) among the subjects
Coefficient of Determination is just the square of pearson’s correlation coefficient R. This is done as it is easier to explain linear regression in terms of R² than R. As R ranges from -1 to 1, R² would range from 0 to 1 — clearly explaining relationship with 0 being not related and 1 being perfectly related.
The correlation confidence interval is the range in which the population correlation is most likely to be found.
The degree of certainty for which it is likely to be within that range is called the confidence level.
When you collect sample data, you can not know the exact value of the correlation.
Note:
For the Stock indices there is an extra calculation, showing the current market expectations - Fear and Greed Index. The calculated index could differs a bit from the original CNN Fear and Greed indicator, because they calculate the index based on Future markets. This indicator calculate the index based on the market that we trade - indices.
Supported pairs:
-Option Gold - XAUUSD , GDX , Silver , Aluminum, Platinum , Palladium, 30Y US Yields, 10Y US Yields, 2Y US Yields, XAUEUR, XAUGBP, XAUAUD , XAUCAD , XAUCNY , XAUJPY
-Option Others - Table1: SP500 , US30, NAS100 ; Table2: DXY , EURUSD , GBPUSD , AUDUSD
Shaktiman [DSS_Rajput]I'm a Momentum Trader, following the Indian markets, Mark Minervini and William O'Neil follower.
 User Settings 
 Inputs tab 
 EMA option for Table  -  It compares the current price of the symbol to its key EMA's and calculates the rate of return to make it easier to track the performance of the symbol.  It Helps you to identify how far the price is from its Key EMA's 
 ADDITIONAL TABLE DATA  - It will allow you to use multiple performance data sets with your set of customizable inputs (You can change periods as per your requirements)
 Show Inside Bar (IB):  Allows you to add Inside Bar on your chart
 Show NR4 (Narrow Range):  Allows you to add an NR4 bar on your chart
 Show INR7(Narrow Range):  Allows you to add NR7 Bar on your chart
 Distance_From_EMA_Table:  Allows you to enable/disable the price difference with its key EMA's table.
 ROC_Table:  It compares the current price of the symbol to its past price and calculates the rate of return to make it easier to track the performance of the symbol. 
                            Note that the Performance sidebar is not updated in real-time, while this indicator is, so on real-time charts.
                           The formula of the calculation is (Current value - Past value) * 100 / Past value, where Past value is: 1W, 1M, 3M, 6M, 1Y
 Momentum_Table:  It compares the current price of the symbol to its past lowest price of that period and calculates the %Gain of the symbol from the low of that period
 Power_Play_Candidate:  It will show the power play candidate, similar to IBD, It merely qualifies for Power_Play.
                                               You need to wait for the Right Entry point. It will give you 8 Week Range. 
                                               According to IBD, it should move 100%+ in less than 8 weeks. You can modify your criteria by changing the percentage gain.
 U/D Ratio:  IBD defines the U/D ratio as "A 50-day ratio that is derived by dividing total volume on up days by the total volume on down days.
                         A ratio greater than 1.0 implies positive demand for a stock"
                        UpVol criteria: close>open and vice versa for DownVol
 Rvol (Relative Vol):  Percentage volume change (compared to daily average volume)
 ADR : It allows you to add the Average Daily Range to the table.
 Show 50D Avg. Vol & Avg. Vol rupee:  It allows you to add 50-Day Avg. Vol and 50-Day Avg. Vol rupee.
 Show_Bull_Snort:  Allows you to add bull snort to your chart and style the bar.
                                     Bull Snort is the work of Oliver Kell. For more info about Oliver kell, check youtube videos of Oliver Kell.
 Normal Moving Average:   Plot 4 Simple, Exponential, and Weighted Moving Averages. (You can choose an option between EMA/SMA/WMA)
 Fixed Moving Average  :   Plot 4 Simple, Exponential, and Weighted Moving Averages. (You can choose an option between EMA/SMA/WMA) 
                 Plus Point: It will not change its value when you switch to a different timeframe. Let's say you applied Fixed Daily 20MA, on the intraday chart.
                 It will not change its value and It will give you much more clarity that, from where the price is bouncing from 20MA. Explore it (You will definitely love it!)
 Fixed Moving Average  :   Plot 2 Simple, Exponential, and Weighted Moving Averages. (You can choose an option between EMA/SMA/WMA)  
                 Plus Point: It will not change its value when you switch to a different timeframe. (It's like Plotting 10 Week Line on Daily Chart & Intraday Charts)
 Numbers of weeks to show High & Low:  It will add data to the tables and also add 52 weeks of High & Low lines on the charts.
                                                                          (Number of weeks is customizable, you can change as per your requirements.)
 Style tab 
 You can modify the style and color of any of the inputs except table color.
 Conclusion 
If you like this script, click on Add to favorite indicators, so that you can easily add this indicator from your favorites tab right away.
Hope you find this useful. Please leave any questions you have in the comment section and I'll be happy to answer them.
Thanks!






















