BTC Dominance PercentageThis BTC Dominance Percentage indicator calculates Bitcoin's dominance relative to altcoins, excluding stablecoins.
🔹 Unlike the standard BTC.D metric, which includes all cryptocurrencies (including stablecoins like USDT, USDC, and DAI), this version focuses only on Bitcoin’s market share compared to altcoins.
🔹 It calculates BTC dominance relative to major altcoins (ETH, BNB, ADA, XRP, SOL) and the OTHERS.D index, which represents smaller-cap altcoins.
🔹 Stablecoins are excluded, providing a clearer view of Bitcoin’s actual strength against the altcoin market, without distortion from fiat-pegged assets.
🚀 This is a true BTC dominance metric for tracking Bitcoin’s market position against altcoins!
Statistics
Multi-Faceted Analysis ToolHere’s a detailed description for the **Multi-Faceted Analysis Tool** TradingView indicator:
---
## Multi-Faceted Analysis Tool
### Overview
The **Multi-Faceted Analysis Tool** is a powerful TradingView indicator designed to enhance your technical analysis by combining several popular indicators: Simple Moving Average (SMA), Relative Strength Index (RSI), and Moving Average Convergence Divergence (MACD). This indicator provides traders with insightful market signals that can be tailored to fit various trading strategies and timeframes.
### Key Features
1. **Simple Moving Average (SMA)**:
- Plots a customizable SMA on the price chart. The length of the SMA can be adjusted to suit your analysis needs (default is set to 50). The SMA helps identify the overall trend direction.
2. **Relative Strength Index (RSI)**:
- Calculates and plots RSI values, providing insights into potential overbought or oversold market conditions. The user can customize the length of the RSI calculation (default is 14).
- Overbought (70) and oversold (30) levels are visually marked, helping traders identify potential reversal points.
3. **MACD**:
- Computes MACD values with customizable parameters for fast length, slow length, and signal length (defaults are 12, 26, and 9 respectively).
- The MACD histogram is displayed, highlighting the difference between the MACD line and the signal line, which can help traders visualize momentum shifts.
4. **Buy and Sell Signals**:
- Generates clear buy and sell signals based on RSI crossover with established thresholds (buy when RSI crosses above 30, sell when RSI crosses below 70). These signals are visually represented on the chart for easy decision-making.
5. **User-Friendly Customization**:
- All parameters are adjustable, allowing traders to set their preferred values based on individual strategies or market conditions. This flexibility ensures that the tool can cater to a wide range of trading styles.
CHG FROM OPEN %As an intraday trader, I'm more interested in seeing the CHG FROM OPEN % than the CHG % measured from yesterday's close. I overlay this script on a separate Volume pane so it doesn't hide my price chart, and I hide the line since the line isn't particularly useful to me.
This script shows the current real-time CHG FROM OPEN % when you hover outside of the chart during regular trading hours (all times NYC/EST). Hovering over the chart will show you the historical CHG FROM OPEN % and, if extended hours, the CHG FROM OPEN % at the previous close.
You can also find CHG FROM OPEN % in the stock screener, but having it in the chart is more convenient for me.
Share Value Indicator**Share Value Indicator**
This TradingView indicator allows traders to track the real-time total value of their stock holdings. Users can input the number of shares they own, and the script calculates the total value based on the current stock price. A horizontal ray is drawn at the last price level, and a label displays the total value of the shares. The indicator updates dynamically, ensuring only one ray and label are visible at a time. Ideal for traders who want to visualize their investment's real-time worth directly on the chart.
rate_of_changeLibrary "rate_of_change"
// @description: Applies ROC algorithm to any pair of values.
// This library function is used to scale change of value (price, volume) to a percentage value, just as the ROC indicator would do. It is good practice to scale arbitrary ranges to set boundaries when you try to train statistical model.
rateOfChange(value, base, hardlimit)
This function is a helper to scale a value change to its percentage value.
Parameters:
value (float)
base (float)
hardlimit (int)
Returns: per: A float comprised between 0 and 100
TradingView Financial Data ViewerTrading view provides request.security function to view the financial information of a script. The available sets of data is documented on below link
www.tradingview.com
The problem is there is no easy way to view this data as there are limitations to the # of unique requests that can be made. The limit is 40 for general paid accounts. So its makes it impossible to view the data in case you are looking to build a plugin related to some financial analysis.
So I came up with this trading view plugin which based on the documentation bifurcates the values available in the FQ, TTM and FY periods. Then you can select which period you would like to see. How many values you want to see at a time. And then next set of data can be viewed by increasing the Set # from 1 to which ever number keeps giving you the data.
Notes:
This is a data view only indicator and it will only display the latest data available for which quarter was there.
In case you want to view past data then you should go to replay mode and cut to the relative earning tags where you want to view the data
This is again for educational or study purpose only and is majorly helpful for those who want to create indicators based on Trading view supported financials and want to view what values are given for specific financial ids
The documentation reference and source of the plugin can be checked
Avg.ROC TableThis indicator calculates the average Rate of Change (ROC) for up to 30 user-selected assets over a specified number of candles. It then ranks the assets—assigning rank 1 to the asset with the highest average ROC (strongest momentum) and rank 30 to the asset with the lowest. The results are displayed in a clean, easy-to-read table split into two stacks of 15 assets each, allowing you to quickly see which assets are performing best.
MonthlyReturnTableLibrary "MonthlyReturnTable"
TODO: The table displays monthly returns, profits, MDD, and number of trades.
get_table(mode, tablePosition, precision, textSize, marginTop, marginBottom, marginLeft, marginRight, colorHead, colorBull, colorBear, colorZero)
: get_table
Parameters:
mode (string)
tablePosition (string)
precision (int)
textSize (int)
marginTop (int)
marginBottom (int)
marginLeft (int)
marginRight (int)
colorHead (color)
colorBull (color)
colorBear (color)
colorZero (color)
Returns: : null, plot perfTable
Normalized VolumeOVERVIEW
The Normalized Volume (NV) is an attempt at visualizing volume in a format that is more understandable by placing the values on a scale of 0 to 100. 0 in this case is the lowest volume candle available on the chart, and 100 being the highest. Calling a candle “high volume” can be misleading without having something to compare to. For example, in scaling the volume this way we can clearly see that a given candle had 80% of the peak volume or 20%, and gauge the validity of price moves more accurately.
FEATURES
NV by session
Allows user to filter the volume values across 4 different sessions. This can add context to the volume output, because what it high volume during London session may not be high volume relative to New York session.
Overlay plotting
When volume boxes are turned on, this will allow you to toggle how they are plotted.
Color theme
A standard color theme will color the NV based on if the respective candle closed green or red. Selecting variables will color the NV plot based on which range the value falls within.
Session inputs
Activated with the “By session?” Input. Allows user to break the day up into 4 sessions to more accurately gauge volume relative to time of day.
Show Box (X)
Toggles on chart boxes on and off.
Show historical boxes
Will plot prior occurrences of selected volume boxes, deleting them when price fully moves through them in the opposite direction of the initial candle.
Color inputs
Allows for intensive customization in how this tool appears visually.
INTERPRETATION
There are 6 pre-defined ranges that NV can fall within.
NV <= 10
Volume is insignificant
In this range, volume should not be a confirmation in your trading strategy.
NV > 10 and <= 20
Volume is low
In this range, volume should not be a confirmation in your trading strategy.
NV > 20 and <= 40
Volume is fair
In this range, volume should not be the primary confirmation in your trading strategy.
NV > 40 and <= 60
Volume is high
In this range, volume can be the primary confirmation in your trading strategy.
NV > 60 and <= 80
Volume is very high
In this range, volume can be the primary confirmation in your trading strategy.
NV > 80
Volume is extreme
In this range, volume is likely news driven and caution should be taken. High price volatility possible.
To utilize this tool in conjunction with your current strategy, follow the range explanations above section in this section. The higher the NV value, the stronger you can feel about your directional confirmation.
If NV = 100, this means that the highest volume candle occurred up to that point on your selected timeframe. All future data points will be weighed off of this value.
LIMITATIONS
This tool will not load on tickers that do not have volume data, such as VIX.
STRATEGY
The Normalized Volume plot can be used in exactly the same way as you would normally utilize volume in your trading strategy. All we are doing is weighing the volume relative to itself.
Volume boxes can be used as targets to be filled in a similar way to commonly used “fair value gap” strategies. To utilize this strategy, I recommend selecting “Plot to Wicks” in Overlay Plotting and toggling on Show Historical Boxes.
Volume boxes can be used as areas for entry in a similar way to commonly used “order block” strategies. To utilize this strategy, I recommend selecting “Open To Close” in Overlay Plotting.
NOTES
You are able to plot an info label on right side of NV plot using the "Toggle box label" input. When a box is toggled on this label will tell you when the most recent box of that intensity occurred.
This tool is deeply visually customizable, with the ability to adjust line width for plotted boxes, all colors on both box overlays, and all colors on NV panel. Customize it to your liking!
I have a handful of additional features that I plan on adding to this tool in future updates. If there is anything you would like to see added, any bugs you identify, or any strategies you encounter with this tool, I would love to hear from you!
Huge shoutout to @joebaus for assisting in bringing this tool to life, please check out his work here on TradingView!
Volume +OBV + ADXVolume + OBV + ADX Table
Optimized Buyer & Seller Volume with Trend Indications
Overview:
This indicator provides a comprehensive view of market participation and trend strength by integrating Volume, On Balance Volume (OBV) trends, and ADX (Average Directional Index) signals into a visually structured table. Designed for quick decision-making, it highlights buyer and seller dominance while comparing the selected stock with another custom symbol.
Features:
✅ Buyer & Seller Volume Analysis:
Computes buyer and seller volume percentages based on market movements.
Displays daily cumulative volume statistics to assess ongoing market participation.
✅ On Balance Volume (OBV) Trends:
Identifies positive, negative, or neutral OBV trends using an advanced smoothing mechanism.
Highlights accumulation or distribution phases with colored visual cues.
✅ ADX-Based Trend Confirmation:
Evaluates Directional Indicators (DI+ and DI-) to determine the trend direction.
Uses customizable ADX settings to filter out weak trends.
Provides uptrend, downtrend, or neutral signals based on strength conditions.
✅ Custom Symbol Comparison:
Allows users to compare two different assets (e.g., a stock vs. an index or ETF).
Displays a side-by-side comparison of volume dynamics and trend strength.
✅ User-Friendly Table Display:
Presents real-time calculations in a compact and structured table format.
Uses color-coded trend signals for easier interpretation.
Recommended Usage for Best Results:
📌 Pairing this indicator with Sri_Momentum and Sri(+) Pivot will enhance accuracy and provide better trade confirmations.
📌 Adding other major indicators like RSI, CCI, etc., will further increase the probability of winning trades.
How to Use:
Select a custom symbol for comparison.
Adjust ADX settings based on market conditions.
Analyze the table to identify buyer/seller dominance, OBV trends, and ADX trend strength.
Use the combined signals to confirm trade decisions and market direction.
Best Use Cases:
🔹 Trend Confirmation – Validate breakout or reversal signals.
🔹 Volume Strength Analysis – Assess buyer/seller participation before entering trades.
🔹 Multi-Asset Comparison – Compare the behavior of two related instruments.
This indicator is ideal for traders looking to combine volume dynamics with trend-following strategies. 🚀📈
Time of Day Background with Bar Count & TableDescription:
This indicator provides a comprehensive overview of market activity by dynamically displaying the time-of-day background and tracking bullish and bearish bar counts across different sessions. It also features a table summarizing the market performance for the last 7 days, segmented into four time-based sessions: Morning, Afternoon, Evening, and Night.
Key Features:
Time of Day Background:
The chart's background color changes based on the time of day:
Evening (12 AM - 6 AM) is shaded blue.
Morning (6 AM - 12 PM) is shaded aqua.
Afternoon (12 PM - 6 PM) is shaded yellow.
Night (6 PM - 12 AM) is shaded silver.
Bullish and Bearish Bar Counting:
It tracks the number of bullish (closing higher than opening) and bearish (closing lower than opening) candles.
The sum of the price differences (bullish minus bearish) for each session is displayed as a dynamic label, indicating overall market direction for each session.
Session Breakdown:
The chart is divided into four sessions, each lasting 6 hours (Morning, Afternoon, Evening, Night).
A new label is generated at the start of each session, indicating the bullish/bearish performance and the net difference in price movements for that session.
Historical Session Performance:
The indicator tracks and stores the performance for each session over the past 7 days.
A table is generated in the top-right corner of the chart, summarizing the performance for each session (Morning, Afternoon, Evening, Night) and the price changes for each of the past 7 days.
The values are color-coded to indicate positive (green) or negative (red) results.
Dynamic Table:
The table presents performance data for each time session over the past week with color-coded cells:
Green cells indicate positive performance.
Red cells indicate negative performance.
Empty cells represent no data for that session.
Use Case:
This indicator is useful for traders who want to track market activity and performance across different times of day and monitor how each session contributes to the overall market trend. It provides both visual insights (through background color) and numerical data (via the table) for better decision-making.
Settings:
The background color and session labels update automatically based on the time of day.
The table updates every day, tracking the performance of each session over the past week.
Vortex Candle MarkerVortex Candle Marker
The Vortex Candle Marker is a specialized TradingView indicator designed to identify and highlight **Vortex Candles**—candles that momentarily form without wicks on either the high or low. This unique price behavior can signal potential price retracements or reversals, aligning with the **Power of Three (PO3)** concept in price action theory.
Indicator Logic:
A candle is classified as a **Vortex Candle** if either of these conditions is met during its formation:
1. **Vortex Top:** The **high** equals either the **open** or **close**, indicating no upper wick.
2. **Vortex Bottom:** The **low** equals either the **open** or **close**, indicating no lower wick.
When a Vortex Candle is detected, the indicator changes the **candle border color** to **aqua**, making it easy to identify these significant price moments.
Market Insight & PO3 Interpretation:
In typical price behavior, most candles exhibit both upper and lower wicks, representing price exploration before settling at a closing value. A candle forming without a wick suggests **strong directional intent** at that moment. However, by the **Power of Three (PO3)** concept—Accumulation, Manipulation, and Distribution—such wickless formations often imply:
- **Price Reversion Likelihood:** When a candle temporarily forms without a wick, it suggests the market may **revisit the opening price** to establish a wick before the candle closes.
- **Liquidity Manipulation:** The absence of a wick may indicate a **stop-hunt** or liquidity grab, where the price manipulates one side before reversing.
- **Entry Triggers:** Identifying these moments can help traders anticipate potential **retracements** or **continuations** within the PO3 framework.
Practical Application
- **Early Reversal Detection:** Spot potential price reversals by observing wickless candles forming at key levels.
- **Breakout Validation:** Use Vortex Candles to confirm **true breakouts** or **false moves** before the price returns.
- **Liquidity Zones:** Identify areas where the market is likely to revisit to create a wick, signaling entry/exit points.
This indicator is a powerful tool for traders applying **Po3** methodologies and seeking to capture price manipulation patterns.
CAPM Alpha & BetaThe CAPM Alpha & Beta indicator is a crucial tool in finance and investment analysis derived from the Capital Asset Pricing Model (CAPM) . It provides insights into an asset's risk-adjusted performance (Alpha) and its relationship to broader market movements (Beta). Here’s a breakdown:
1. How Does It Work?
Alpha:
Definition: Alpha measures the portion of an investment's return that is not explained by market movements, i.e., the excess return over and above what the market is expected to deliver.
Purpose: It represents the value a fund manager or strategy adds (or subtracts) from an investment’s performance, adjusting for market risk.
Calculation:
Alpha is derived from comparing actual returns to expected returns predicted by CAPM:
Alpha = Actual Return − (Risk-Free Rate + β × (Market Return − Risk-Free Rate))
Alpha = Actual Return − (Risk-Free Rate + β × (Market Return − Risk-Free Rate))
Interpretation:
Positive Alpha: The investment outperformed its CAPM prediction (good performance for additional value/risk).
Negative Alpha: The investment underperformed its CAPM prediction.
Beta:
Definition: Beta measures the sensitivity of an asset's returns relative to the overall market's returns. It quantifies systematic risk.
Purpose: Indicates how volatile or correlated an investment is relative to the market benchmark (e.g., S&P 500).
Calculation:
Beta is computed as the ratio of the covariance of the asset and market returns to the variance of the market returns:
β = Covariance (Asset Return, Market Return) / Variance (Market Return)
β = Variance (Market Return) Covariance (Asset Return, Market Return)
Interpretation:
Beta = 1: The asset’s price moves in line with the market.
Beta > 1: The asset is more volatile than the market (higher risk/higher potential reward).
Beta < 1: The asset is less volatile than the market (lower risk/lower reward).
Beta < 0: The asset moves inversely to the market.
2. How to Use It?
Using Alpha:
Portfolio Evaluation: Investors use Alpha to gauge whether a portfolio manager or a strategy has successfully outperformed the market on a risk-adjusted basis.
If Alpha is consistently positive, the portfolio may deliver higher-than-expected returns for the given level of risk.
Stock/Asset Selection: Compare Alpha across multiple securities. Positive Alpha signals that the asset may be a good addition to your portfolio for excess returns.
Adjusting Investment Strategy: If Alpha is negative, reassess the asset's role in the portfolio and refine strategies.
Using Beta:
Risk Management:
A high Beta (e.g., 1.5) indicates higher sensitivity to market movements. Use such assets if you want to take on more risk during bullish market phases or expect higher returns.
A low Beta (e.g., 0.7) indicates stability and is useful in diversifying risk in volatile or bearish markets.
Portfolio Diversification: Combine assets with varying Betas to achieve the desired level of market responsiveness and smooth out portfolio volatility.
Monitoring Systematic Risk: Beta helps identify whether an investment aligns with your risk tolerance. For example, high-Beta stocks may not be suitable for conservative investors.
Practical Application:
Use both Alpha and Beta together:
Assess performance with Alpha (excess returns).
Assess risk exposure with Beta (market sensitivity).
Example: A stock with a Beta of 1.2 and a highly positive Alpha might suggest a solid performer that is slightly more volatile than the market, making it a suitable pick for risk-tolerant, return-maximizing investors.
In conclusion, the CAPM Alpha & Beta indicator gives a comprehensive view of an asset's performance and risk. Alpha enables performance evaluation on a risk-adjusted basis, while Beta reveals the level of market risk. Together, they help investors make informed decisions, build optimal portfolios, and align investments with their risk-return preferences.
ATR Percentages BoxThis custom indicator provides a quick visual reference for volatility-based price ranges, directly on your TradingView charts. It calculates and displays three ranges derived from the Daily Average True Range (ATR) with a standard 14-period setting:
5 Min (3% ATR): Ideal for very short-term scalping and quick intraday moves.
1 Hour (5% ATR): Useful for hourly setups, short-term trades, and intraday volatility assessment.
Day (10% ATR): Perfect for daily volatility context, swing trades, or placing stops and targets.
The ranges are clearly shown in a compact box at the top-right corner, providing traders immediate insights into realistic price movements, helping to optimise entries, stops, and profit targets efficiently.
Simple APF Strategy Backtesting [The Quant Science]Simple backtesting strategy for the quantitative indicator Autocorrelation Price Forecasting. This is a Buy & Sell strategy that operates exclusively with long orders. It opens long positions and generates profit based on the future price forecast provided by the indicator. It's particularly suitable for trend-following trading strategies or directional markets with an established trend.
Main functions
1. Cycle Detection: Utilize autocorrelation to identify repetitive market behaviors and cycles.
2. Forecasting for Backtesting: Simulate trades and assess the profitability of various strategies based on future price predictions.
Logic
The strategy works as follow:
Entry Condition: Go long if the hypothetical gain exceeds the threshold gain (configurable by user interface).
Position Management: Sets a take-profit level based on the future price.
Position Sizing: Automatically calculates the order size as a percentage of the equity.
No Stop-Loss: this strategy doesn't includes any stop loss.
Example Use Case
A trader analyzes a dayli period using 7 historical bars for autocorrelation.
Sets a threshold gain of 20 points using a 5% of the equity for each trade.
Evaluates the effectiveness of a long-only strategy in this period to assess its profitability and risk-adjusted performance.
User Interface
Length: Set the length of the data used in the autocorrelation price forecasting model.
Thresold Gain: Minimum value to be considered for opening trades based on future price forecast.
Order Size: percentage size of the equity used for each single trade.
Strategy Limit
This strategy does not use a stop loss. If the price continues to drop and the future price forecast is incorrect, the trader may incur a loss or have their capital locked in the losing trade.
Disclaimer!
This is a simple template. Use the code as a starting point rather than a finished solution. The script does not include important parameters, so use it solely for educational purposes or as a boilerplate.
*Auto Backtest & Optimize EngineFull-featured Engine for Automatic Backtesting and parameter optimization. Allows you to test millions of different combinations of stop-loss and take profit parameters, including on any connected indicators.
⭕️ Key Futures
Quickly identify the optimal parameters for your strategy.
Automatically generate and test thousands of parameter combinations.
A simple Genetic Algorithm for result selection.
Saves time on manual testing of multiple parameters.
Detailed analysis, sorting, filtering and statistics of results.
Detailed control panel with many tooltips.
Display of key metrics: Profit, Win Rate, etc..
Comprehensive Strategy Score calculation.
In-depth analysis of the performance of different types of stop-losses.
Possibility to use to calculate the best Stop-Take parameters for your position.
Ability to test your own functions and signals.
Customizable visualization of results.
Flexible Stop-Loss Settings:
• Auto ━ Allows you to test all types of Stop Losses at once(listed below).
• S.VOLATY ━ Static stop based on volatility (Fixed, ATR, STDEV).
• Trailing ━ Classic trailing stop following the price.
• Fast Trail ━ Accelerated trailing stop that reacts faster to price movements.
• Volatility ━ Dynamic stop based on volatility indicators.
• Chandelier ━ Stop based on price extremes.
• Activator ━ Dynamic stop based on SAR.
• MA ━ Stop based on moving averages (9 different types).
• SAR ━ Parabolic SAR (Stop and Reverse).
Advanced Take-Profit Options:
• R:R: Risk/Reward ━ sets TP based on SL size.
• T.VOLATY ━ Calculation based on volatility indicators (Fixed, ATR, STDEV).
Testing Modes:
• Stops ━ Cyclical stop-loss testing
• Pivot Point Example ━ Example of using pivot points
• External Example ━ Built-in example how test functions with different parameters
• External Signal ━ Using external signals
⭕️ Usage
━ First Steps:
When opening, select any point on the chart. It will not affect anything until you turn on Manual Start mode (more on this below).
The chart will immediately show the best results of the default Auto mode. You can switch Part's to try to find even better results in the table.
Now you can display any result from the table on the chart by entering its ID in the settings.
Repeat steps 3-4 until you determine which type of Stop Loss you like best. Then set it in the settings instead of Auto mode.
* Example: I flipped through 14 parts before I liked the first result and entered its ID so I could visually evaluate it on the chart.
Then select the stop loss type, choose it in place of Auto mode and repeat steps 3-4 or immediately follow the recommendations of the algorithm.
Now the Genetic Algorithm at the bottom right will prompt you to enter the Parameters you need to search for and select even better results.
Parameters must be entered All at once before they are updated. Enter recommendations strictly in fields with the same names.
Repeat steps 5-6 until there are approximately 10 Part's left or as you like. And after that, easily pour through the remaining Parts and select the best parameters.
━ Example of the finished result.
━ Example of use with Takes
You can also test at the same time along with Take Profit. In this example, I simply enabled Risk/Reward mode and immediately specified in the TP field Maximum RR, Minimum RR and Step. So in this example I can test (3-1) / 0.1 = 20 Takes of different sizes. There are additional tips in the settings.
━
* Soon you will start to understand how the system works and things will become much easier.
* If something doesn't work, just reset the engine settings and start over again.
* Use the tips I have left in the settings and on the Panel.
━ Details:
Sort ━ Sorting results by Score, Profit, Trades, etc..
Filter ━ Filtring results by Score, Profit, Trades, etc..
Trade Type ━ Ability to disable Long\Short but only from statistics.
BackWin ━ Backtest Window Number of Candle the script can test.
Manual Start ━ Enabling it will allow you to call a Stop from a selected point. which you selected when you started the engine.
* If you have a real open position then this mode can help to save good Stop\Take for it.
1 - 9 Сheckboxs ━ Allow you to disable any stop from Auto mode.
Ex Source - Allow you to test Stops/Takes from connected indicators.
Connection guide:
//@version=6
indicator("My script")
rsi = ta.rsi(close, 14)
buy = not na(rsi) and ta.crossover (rsi, 40) // OS = 40
sell = not na(rsi) and ta.crossunder(rsi, 60) // OB = 60
Signal = buy ? +1 : sell ? -1 : 0
plot(Signal, "🔌Connector🔌", display = display.none)
* Format the signal for your indicator in a similar style and then select it in Ex Source.
⭕️ How it Works
Hypothesis of Uniform Distribution of Rare Elements After Mixing.
'This hypothesis states that if an array of N elements contains K valid elements, then after mixing, these valid elements will be approximately uniformly distributed.'
'This means that in a random sample of k elements, the proportion of valid elements should closely match their proportion in the original array, with some random variation.'
'According to the central limit theorem, repeated sampling will result in an average count of valid elements following a normal distribution.'
'This supports the assumption that the valid elements are evenly spread across the array.'
'To test this hypothesis, we can conduct an experiment:'
'Create an array of 1,000,000 elements.'
'Select 1,000 random elements (1%) for validation.'
'Shuffle the array and divide it into groups of 1,000 elements.'
'If the hypothesis holds, each group should contain, on average, 1~ valid element, with minor variations.'
* I'd like to attach more details to My hypothesis but it won't be very relevant here. Since this is a whole separate topic, I will leave the minimum part for understanding the engine.
Practical Application
To apply this hypothesis, I needed a way to generate and thoroughly mix numerous possible combinations. Within Pine, generating over 100,000 combinations presents significant challenges, and storing millions of combinations requires excessive resources.
I developed an efficient mechanism that generates combinations in random order to address these limitations. While conventional methods often produce duplicates or require generating a complete list first, my approach guarantees that the first 10% of possible combinations are both unique and well-distributed. Based on my hypothesis, this sampling is sufficient to determine optimal testing parameters.
Most generators and randomizers fail to accommodate both my hypothesis and Pine's constraints. My solution utilizes a simple Linear Congruential Generator (LCG) for pseudo-randomization, enhanced with prime numbers to increase entropy during generation. I pre-generate the entire parameter range and then apply systematic mixing. This approach, combined with a hybrid combinatorial array-filling technique with linear distribution, delivers excellent generation quality.
My engine can efficiently generate and verify 300 unique combinations per batch. Based on the above, to determine optimal values, only 10-20 Parts need to be manually scrolled through to find the appropriate value or range, eliminating the need for exhaustive testing of millions of parameter combinations.
For the Score statistic I applied all the same, generated a range of Weights, distributed them randomly for each type of statistic to avoid manual distribution.
Score ━ based on Trade, Profit, WinRate, Profit Factor, Drawdown, Sharpe & Sortino & Omega & Calmar Ratio.
⭕️ Notes
For attentive users, a little tricks :)
To save time, switch parts every 3 seconds without waiting for it to load. After 10-20 parts, stop and wait for loading. If the pause is correct, you can switch between the rest of the parts without loading, as they will be cached. This used to work without having to wait for a pause, but now it does slower. This will save a lot of time if you are going to do a deeper backtest.
Sometimes you'll get the error “The scripts take too long to execute.”
For a quick fix you just need to switch the TF or Ticker back and forth and most likely everything will load.
The error appears because of problems on the side of the site because the engine is very heavy. It can also appear if you set too long a period for testing in BackWin or use a heavy indicator for testing.
Manual Start - Allow you to Start you Result from any point. Which in turn can help you choose a good stop-stick for your real position.
* It took me half a year from idea to current realization. This seems to be one of the few ways to build something automatic in backtest format and in this particular Pine environment. There are already better projects in other languages, and they are created much easier and faster because there are no limitations except for personal PC. If you see solutions to improve this system I would be glad if you share the code. At the moment I am tired and will continue him not soon.
Also You can use my previosly big Backtest project with more manual settings(updated soon)
Clustering Volatility (ATR-ADR-ChaikinVol) [Sam SDF-Solutions]The Clustering Volatility indicator is designed to evaluate market volatility by combining three widely used measures: Average True Range (ATR), Average Daily Range (ADR), and the Chaikin Oscillator.
Each indicator is normalized using one of the available methods (MinMax, Rank, or Z-score) to create a unified metric called the Score. This Score is further smoothed with an Exponential Moving Average (EMA) to reduce noise and provide a clearer view of market conditions.
Key Features:
Multi-Indicator Integration: Combines ATR, ADR, and the Chaikin Oscillator into a single Score that reflects overall market volatility.
Flexible Normalization: (Supports three normalization methods)
MinMax: Scales values between the observed minimum and maximum.
Rank: Normalizes based on the relative rank within a moving window.
Z-score: Standardizes values using mean and standard deviation.
Dynamic Window Selection: Offers an automatic window selection option based on a specified lookback period, or a fixed window size can be used.
Customizable Weights: Allows the user to assign individual weights to ATR, ADR, and the Chaikin Oscillator. Optionally, weights can be normalized to sum to 1.
Score Smoothing: Applies an EMA to the computed Score to smooth out short-term fluctuations and reduce market noise.
Cluster Visualization: Divides the smoothed Score into a number of clusters, each represented by a distinct color. These colors can be applied to the price bars (if enabled) for an immediate visual indication of the current volatility regime.
How It Works:
Input & Window Setup: Users set parameters for indicator periods, normalization methods, weights, and window size. The indicator can automatically determine the analysis window based on the number of lookback days.
Calculation of Metrics: The indicator computes the ATR, ADR (as the average of bar ranges), and the Chaikin Oscillator (based on the difference between short and long EMAs of the Accumulation/Distribution line).
Normalization & Scoring: Each indicator’s value is normalized and then weighted to form a raw Score. This raw Score is scaled to a range using statistics from the chosen window.
Smoothing & Clustering: The raw Score is smoothed using an EMA. The resulting smoothed Score is then multiplied by the number of clusters to assign a cluster index, which is used to choose a color for visual signals.
Visualization: The smoothed Score is plotted on the chart with a color that changes based on its value (e.g., lime for low, red for high, yellow for intermediate values). Optionally, the price bars are colored according to the assigned cluster.
_____________
This indicator is ideal for traders seeking a quick and clear assessment of market volatility. By integrating multiple volatility measures into one comprehensive Score, it simplifies analysis and aids in making more informed trading decisions.
For more detailed instructions, please refer to the guide here:
Broad Market MOEX### **Broad Market for Russia**
The **Broad Market for Russia** indicator provides a comparative analysis of the price deviation of major Russian stocks relative to their average closing price over a customizable lookback period. This tool helps traders identify market trends and detect relative strength or weakness among different assets.
### **How It Works:**
- The indicator calculates the **percentage deviation** of each stock’s current price from its **simple moving average (SMA)** over the defined **lookback period (in hours).**
- The **default lookback period is 24 hours**, but it can be adjusted based on the trader’s needs.
- It tracks major Russian assets, including **Gazprom, Sberbank, Lukoil, Rosneft, Norilsk Nickel, Yandex, and others**, alongside the currently selected instrument.
- Each stock’s deviation is plotted on a separate panel, allowing for quick visual comparison.
- **Positive deviation** indicates that the price is trading above its average, signaling potential **bullish momentum**.
- **Negative deviation** suggests the price is below its average, possibly indicating **bearish conditions**.
This indicator is particularly useful for traders in the Russian stock market who want to gauge broader market strength and detect divergence patterns across multiple assets.
---
### **Broad Market for Russia**
Индикатор **Broad Market for Russia** предоставляет сравнительный анализ отклонения цены крупнейших российских акций относительно их среднего значения за настраиваемый период. Этот инструмент помогает трейдерам выявлять рыночные тренды и определять относительную силу или слабость активов.
### **Как это работает:**
- Индикатор рассчитывает **процентное отклонение** текущей цены каждой акции от её **простого скользящего среднего (SMA)** за заданный **период анализа (в часах).**
- **Период анализа по умолчанию — 24 часа**, но его можно изменять в зависимости от предпочтений трейдера.
- В индикаторе отслеживаются **крупнейшие российские активы**, такие как **Газпром, Сбербанк, Лукойл, Роснефть, Норникель, Яндекс и другие**, а также текущий выбранный инструмент.
- Отклонение каждой акции отображается на отдельной панели, что позволяет быстро проводить визуальное сравнение.
- **Положительное отклонение** означает, что цена торгуется выше своего среднего значения, что может сигнализировать о **бычьем тренде**.
- **Отрицательное отклонение** указывает, что цена ниже своего среднего значения, что может свидетельствовать о **медвежьей тенденции**.
Этот индикатор особенно полезен для трейдеров российского фондового рынка, которые хотят оценить силу всего рынка и выявлять расхождения между различными активами.
Broad Market for Crypto**Broad Market for Crypto** indicator provides a comparative analysis of the price deviation of multiple major cryptocurrencies relative to their average closing price over a customizable lookback period. This tool helps traders identify market trends and spot relative strength or weakness among different assets.
### **How It Works:**
- The indicator calculates the percentage deviation of each cryptocurrency’s current price from its simple moving average (SMA) over the defined **lookback period (in hours).**
- The **default lookback period is 24 hours**, but it can be adjusted according to the trader's preference.
- It tracks major crypto assets, including **BTC, ETH, BNB, SOL, XRP, ADA, AVAX, LINK, DOGE, and TRX**, alongside the currently selected instrument.
- Each cryptocurrency’s deviation is plotted on a separate panel, allowing for quick visual comparison.
- Positive deviation indicates that the price is trading above its average, signaling potential bullish momentum.
- Negative deviation suggests the price is below its average, possibly indicating bearish conditions.
This indicator is particularly useful for crypto traders who want to gauge the broader market’s strength and detect divergence patterns across multiple assets.
---------------------------------------------------------------------------------
**Broad Market for Crypto - Описание индикатора**
Индикатор **Broad Market for Crypto** предоставляет сравнительный анализ отклонения цены различных крупных криптовалют относительно их среднего значения за настраиваемый период. Этот инструмент помогает трейдерам выявлять рыночные тренды и определять относительную силу или слабость активов.
### **Как это работает:**
- Индикатор рассчитывает **процентное отклонение** текущей цены каждой криптовалюты от её **простого скользящего среднего (SMA)** за заданный **период анализа (в часах)**.
- **Период анализа по умолчанию — 24 часа**, но его можно изменять в зависимости от предпочтений трейдера.
- В индикаторе отслеживаются основные криптоактивы: **BTC, ETH, BNB, SOL, XRP, ADA, AVAX, LINK, DOGE и TRX**, а также текущий выбранный инструмент.
- Отклонение каждой криптовалюты отображается на отдельной панели, что позволяет быстро проводить визуальное сравнение.
- **Положительное отклонение** означает, что цена торгуется выше своего среднего значения, что может сигнализировать о **бычьем тренде**.
- **Отрицательное отклонение** указывает, что цена ниже своего среднего значения, что может свидетельствовать о **медвежьей тенденции**.
Этот индикатор особенно полезен для криптотрейдеров, желающих оценить силу всего рынка и выявлять расхождения между различными активами.
Fibonacci-Only Strategy V2Fibonacci-Only Strategy V2
This strategy combines Fibonacci retracement levels with pattern recognition and statistical confirmation to identify high-probability trading opportunities across multiple timeframes.
Core Strategy Components:
Fibonacci Levels: Uses key Fibonacci retracement levels (19% and 82.56%) to identify potential reversal zones
Pattern Recognition: Analyzes recent price patterns to find similar historical formations
Statistical Confirmation: Incorporates statistical analysis to validate entry signals
Risk Management: Includes customizable stop loss (fixed or ATR-based) and trailing stop features
Entry Signals:
Long entries occur when price touches or breaks the 19% Fibonacci level with bullish confirmation
Short entries require Fibonacci level interaction, bearish confirmation, and statistical validation
All signals are visually displayed with color-coded markers and dashboard
Trading Method:
When a triangle signal appears, open a position on the next candle
Alternatively, after seeing a signal on a higher timeframe, you can switch to a lower timeframe to find a more precise entry point
Entry signals are clearly marked with visual indicators for easy identification
Risk Management Features:
Adjustable stop loss (percentage-based or ATR-based)
Optional trailing stops for protecting profits
Multiple take-profit levels for strategic position exit
Customization Options:
Timeframe selection (1m to Daily)
Pattern length and similarity threshold adjustment
Statistical period and weight configuration
Risk parameters including stop loss and trailing stop settings
This strategy is particularly well-suited for cryptocurrency markets due to their tendency to respect Fibonacci levels and technical patterns. Crypto's volatility is effectively managed through the customizable stop-loss and trailing-stop mechanisms, making it an ideal tool for traders in digital asset markets.
For optimal performance, this strategy works best on higher timeframes (30m, 1h and above) and is not recommended for low timeframe scalping. The Fibonacci pattern recognition requires sufficient price movement to generate reliable signals, which is more consistently available in medium to higher timeframes.
Users should avoid trading during sideways market conditions, as the strategy performs best during trending markets with clear directional movement. The statistical confirmation component helps filter out some sideways market signals, but it's recommended to manually avoid ranging markets for best results.
Round NumbersTries to only show major round numbers regardless of whether you're looking at something priced in the thousands or under a dollar.
Relative Strength RatioWhen comparing a stock’s strength against NIFTY 50, the Relative Strength (RS) is calculated to measure how the stock is performing relative to the index. This is different from the RSI but is often used alongside it.
How It Works:
Relative Strength (RS) Calculation:
𝑅
𝑆
=
Stock Price
NIFTY 50 Price
RS=
NIFTY 50 Price
Stock Price
This shows how a stock is performing relative to the NIFTY 50 index.
Relative Strength Ratio Over Time:
If the RS value is increasing, the stock is outperforming NIFTY 50.
If the RS value is decreasing, the stock is underperforming NIFTY 50.
Liquidity Depth [AlgoAlpha]OVERVIEW
This script visualizes market liquidity by identifying key price levels where significant volume has transacted. It highlights zones of high buying and selling interest, helping traders understand where liquidity is accumulating and how price may respond to these areas. By dynamically tracking volume at highs and lows, the script builds a real-time liquidity profile, making it a powerful tool for identifying potential support and resistance levels.
CONCEPTS
Liquidity depth analysis helps traders determine how price interacts with supply and demand at different levels. The script processes historical volume data to distinguish between high-liquidity and low-liquidity zones. It assigns transparency levels to plotted lines , ensuring that more relevant liquidity areas stand out visually. The script adds a profile to show the depth of liquidity (derived from historical volume data) for levels above and below the current price
FEATURES
Liquidity Levels: Tracks liquidity levels based on volume concentration at price high and lows.
Volume-Based Transparency: More significant liquidity levels are displayed with higher visibility, showing their significance.
Interpolation: interpolates the bullish and bearish liquidity depth at a user defined range away from the price, helping in comparing the liquidity amounts between bullish and bearish.
Depth Profile: Allows traders to visualize depth of liquidity in a more quantitative and clearer way than the liquidity levels/list]
USAGE
This indicator is best used to track liquidity levels and potential price reaction areas. Traders can adjust the Liquidity Lookback setting to analyze past liquidity levels over different historical periods. The Profile Resolution setting controls the granularity of liquidity depth visualization, with higher values providing more detail. The script can be applied across different timeframes, from intraday scalping to swing trading analysis. The plotted liquidity zones provide traders with insights into where price may encounter strong support, resistance, or potential liquidity-driven reversals.