R-based Strategy Template [Daveatt]Have you ever wondered how to properly track your trading performance based on risk rather than just profits?
This template solves that problem by implementing R-multiple tracking directly in TradingView's strategy tester.
This script is a tool that you must update with your own trading entry logic.
Quick notes
Before we dive in, I want to be clear: this is a template focused on R-multiple calculation and visualization.
I'm using a basic RSI strategy with dummy values just to demonstrate how the R tracking works. The actual trading signals aren't important here - you should replace them with your own strategy logic.
R multiple logic
Let's talk about what R-multiple means in practice.
Think of R as your initial risk per trade.
For instance, if you have a $10,000 account and you're risking 1% per trade, your 1R would be $100.
A trade that makes twice your risk would be +2R ($200), while hitting your stop loss would be -1R (-$100).
This way of measuring makes it much easier to evaluate your strategy's performance regardless of account size.
Whenever the SL is hit, we lose -1R
Proof showing the strategy tester whenever the SL is hit: i.imgur.com
The magic happens in how we calculate position sizes.
The script automatically determines the right position size to risk exactly your specified percentage on each trade.
This is done through a simple but powerful calculation:
risk_amount = (strategy.equity * (risk_per_trade_percent / 100))
sl_distance = math.abs(entry_price - sl_price)
position_size = risk_amount / (sl_distance * syminfo.pointvalue)
Limitations with lower timeframe gaps
This ensures that if your stop loss gets hit, you'll lose exactly the amount you intended to risk. No more, no less.
Well, could be more or less actually ... let's assume you're trading futures on a 15-minute chart but in the 1-minute chart there is a gap ... then your 15 minute SL won't get filled and you'll likely to not lose exactly -1R
This is annoying but it can't be fixed - and that's how trading works anyway.
Features
The template gives you flexibility in how you set your stop losses. You can use fixed points, ATR-based stops, percentage-based stops, or even tick-based stops.
Regardless of which method you choose, the position sizing will automatically adjust to maintain your desired risk per trade.
To help you track performance, I've added a comprehensive statistics table in the top right corner of your chart.
It shows you everything you need to know about your strategy's performance in terms of R-multiples: how many R you've won or lost, your win rate, average R per trade, and even your longest winning and losing streaks.
Happy trading!
And remember, measuring your performance in R-multiples is one of the most classical ways to evaluate and improve your trading strategies.
Daveatt
Statistics
Spread Analysis (COIN/BTC)The Spread Analysis (COIN/BTC) indicator calculates the Z-score of the price ratio between Coinbase stock ( NASDAQ:COIN ) and Bitcoin ( CRYPTOCAP:BTC ). It helps identify overbought or oversold conditions based on deviations from the historical mean of their price relationship.
Key Features:
Z-Score Calculation:
• Tracks the relative price ratio of NASDAQ:COIN to $BTC.
• Compares the current ratio to its historical average, highlighting extreme overvaluation or undervaluation.
• Buy and Sell Signals:
• Buy Signal: Triggered when the Z-score is less than -2, indicating NASDAQ:COIN may be undervalued relative to $BTC.
• Sell Signal: Triggered when the Z-score exceeds 2, suggesting NASDAQ:COIN may be overvalued relative to $BTC.
• Dynamic Z-Score Visualization:
• Blue line plots the Z-score over time.
• Dashed lines at +2 and -2 mark overbought and oversold thresholds.
• Green and red triangles highlight actionable buy and sell signals.
Use Case:
This indicator is ideal for identifying relative valuation opportunities between NASDAQ:COIN and $BTC. Use it to exploit divergences in their historical relationship and anticipate potential reversions to the mean.
Limitations:
• Best suited for range-bound markets; may produce false signals in strongly trending conditions.
• Assumes a consistent correlation between NASDAQ:COIN and CRYPTOCAP:BTC , which may break during independent price drivers like news or earnings.
Market MonitorOverview
The Market Monitor Indicator provides a customisable view of dynamic percentage changes across selected indices or sectors, calculated by comparing current and previous closing prices over the chosen timeframe.
Key Features
Choose up to 20 predefined indices or your own selected indices/stocks.
Use checkboxes to show or hide individual entries.
Monitor returns over daily, weekly, monthly, quarterly, half-yearly, or yearly timeframes
Sort by returns (descending) to quickly identify top-performing indices or alphabetically for an organised and systematic review.
Customisation
Switch between Light Mode (Blue or Green themes) and Dark Mode for visual clarity.
Adjust the table’s size, position, and location.
Customise the table title to your own choice e.g. Sectoral, Broad, Portfolio etc.
Use Cases
Use multiple instances of the script with varying timeframes to study sectoral rotation and trends.
Customise the stocks to see your portfolio returns for the day or over the past week, or longer.
TradingCharts SCTR [Bginvestor]This indicator is replicating Tradingcharts, SCTR plot. If you know, you know.
Brief description: The StockCharts Technical Rank (SCTR), conceived by technical analyst John Murphy, emerges as a pivotal tool in evaluating a stock’s technical prowess. This numerical system, colloquially known as “scooter,” gauges a stock’s strength within various groups, employing six key technical indicators across different time frames.
How to use it:
Long-term indicators (30% weight each)
-Percent above/below the 200-day exponential moving average (EMA)
-125-day rate-of-change (ROC)
Medium-term indicators (15% weight each)
-percent above/below 50-day EMA
-20-day rate-of-change
Short-term indicators (5% weight each)
-Three-day slope of percentage price oscillator histogram divided by three
-Relative strength index
How to use SCTR:
Investors select a specific group for analysis, and the SCTR assigns rankings within that group. A score of 99.99 denotes robust technical performance, while zero signals pronounced underperformance. Traders leverage this data for strategic decision-making, identifying stocks with increasing SCTR for potential buying or spotting weak stocks for potential shorting.
Credit: I've made some modifications, but credit goes to GodziBear for back engineering the averaging / scaling of the equations.
Note: Not a perfect match to TradingCharts, but very, very close.
Sector Relative Strength [Afnan]This indicator calculates and displays the relative strength (RS) of multiple sectors against a chosen benchmark. It allows you to quickly compare the performance of various sectors within any global stock market. While the default settings are configured for the Indian stock market , this tool is not limited to it; you can use it for any market by selecting the appropriate benchmark and sector indices.
📊 Key Features ⚙️
Customizable Benchmark: Select any symbol as your benchmark for relative strength calculation. The default benchmark is set to `NSE:CNX100`. This allows for global market analysis by selecting the appropriate benchmark index of any country.
Multiple Sectors: Analyze up to 23 different sector indices. The default settings include major NSE sector indices. This can be customized to any market by using the relevant sector indices of that country.
Individual Sector Control: Toggle the visibility of each sector's RS on the chart.
Color-Coded Plots: Each sector's RS is plotted with a distinct color for easy identification.
Adjustable Lookback Period: Customize the lookback period for RS calculation.
Interactive Table: A sortable table displays the current RS values for all visible sectors, allowing for quick ranking.
Table Customization: Adjust the table's position, text size, and visibility.
Zero Line: A horizontal line at zero provides a reference point for RS values.
🧭 How to Use 🗺️
Add the indicator to your TradingView chart.
Select your desired benchmark symbol. The default is `NSE:CNX100`. For example, use SPY for the US market, or DAX for the German market.
Adjust the lookback period as needed.
Enable/disable the sector indices you want to analyze. The default includes major NSE sector indices like `NSE:CNXIT`, `NSE:CNXAUTO`, etc.
Customize the table's appearance as needed.
Observe the RS plots and the table to identify sectors with relative strength or weakness.
📝 Note 💡
This indicator is designed for sectorial analysis. You can use it with any market by selecting the appropriate benchmark and sector indices.
The default settings are configured for the Indian stock market with `NSE:CNX100` as the benchmark and major NSE sector indices pre-selected.
The relative strength calculation is based on the price change of the sector index compared to the benchmark over the lookback period.
Positive RS values indicate relative outperformance, while negative values indicate relative underperformance.
👨💻 Developer 🛠️
Afnan Tajuddin
Scatter Plot with Symbol or Data Source InputsDescription of setting items
Use Symbol for X Data?
Type: Checkbox (input.bool)
Explanation: Selects whether the data used for the X axis is obtained from a “symbol” or a “data source”.
If true: data for the X axis will be taken from a symbol (e.g. stock ticker).
If false: X axis data will be taken from the specified data source (e.g., closing price or volume).
Use Symbol for Y Data?
type: checkbox (input.bool)
Explanation: Selects whether the data used for the Y axis is retrieved from a “symbol” or a “data source”.
If true: Y-axis data is obtained from symbols.
If false: Data for the Y axis is obtained from the specified data source.
Select Ticker Symbol for X Data
type: symbol input (input.symbol)
description: selects the symbol to be used for the X axis (default is “AAPL”).
If “Use Symbol for X Data?” is set to true, this symbol will be used as the data for the X axis.
Select Ticker Symbol for Y Data
Type: Symbol input (input.symbol)
description: selects the symbol to be used for the Y axis (default is “GOOG”).
If “Use Symbol for Y Data?” is set to true, this symbol will be used as the data for the Y axis.
X Data Source
type: data source input (input.source)
description: specifies the data source to be used for the X axis.
Default is “close” (closing price).
Other possible values include open, high, low, volume, etc.
Y Data Source
Type: data source input (input.source)
Description: Specifies the data source to be used for the Y axis.
Default is “volume” (volume).
Other possible values include open, high, low, close, etc.
X Offset
type: integer input (input.int)
description: sets the offset value of the X axis.
This shifts the position of the X axis on the grid. The range is from -500 to 500.
Y Offset
Type: Integer input (constant)
description: offset value for y-axis.
Defaults to 0, but can be changed to adjust the Y axis position.
grid_width
type: integer input (input.int)
description: sets the width of the grid.
The default is 200. Increasing the value results in a finer grid.
grid_height
type: integer input (input.int)
description: sets the height of the grid.
Defaults to 200. Increasing the value results in a finer grid.
Frequency of updates
type: integer input (input.int)
description: set frequency of updates.
The higher the frequency of updates, the more bars will be used to calculate minimum and maximum values.
X Tick Interval
type: integer input (input.int)
description: sets the tick interval for the X axis.
The default is 10. To increase the number of ticks, decrease the value.
Y Tick Interval
Box border color
type: select color (input.color)
description: select color for grid box border
Default is blue.
Explanation of usage
To use symbol data: Set Use Symbol for X Data?
When “Use Symbol for X Data?” and “Use Symbol for Y Data?” are set to true, the data of the specified symbol is displayed on each axis. For example, you can use “AAPL” (Apple's stock price data) for the X axis and “GOOG” (Google's stock price data) for the Y axis.
To set the symbol, select the desired ticker in Select Ticker Symbol for X Data and Select Ticker Symbol for Y Data.
To use a data source: select the
You can set Use Symbol for X Data? and Use Symbol for Y Data? to false and use the data source specified in X Data Source or Y Data Source instead (e.g., closing price or volume).
Change Grid Size:.
Set the width and height of the grid with grid_width and grid_height. Larger values allow for more detailed scatter plots.
Set Tick Intervals: Set the X Tick Interval and Y Tick Interval.
Adjust X Tick Interval and Y Tick Interval to change the tick spacing on the X and Y axes.
Data Range Adjustment: Adjust the Frequency of updates to change the frequency of updates.
The Frequency of updates can be changed to control how often the data range is updated. The higher this value, the more historical data is considered and displayed.
Box Color.
Box Border Color allows you to change the color of the box border.
This script is useful for visualizing different symbols and data sources, especially to show the relationship between financial data.
Caution.
Some data may exceed the memory size, but the scale is the same, so you will know most of the locations.
*I made it myself because I could not find anything to draw a scatter plot. You can also compare more than 3 pieces of data by displaying more than one scatter plot. Here is how to do it. Set X or Y as the reference data. Set the data you want to compare to the one that is not the standard. Next, set the same indicator and set the reference to another set of data you wish to compare. Now you can compare the three sets of data. It is effective to change the color of the display box to prevent the user from not knowing which is which. Thus, you should be able to compare more than 3 pieces of data, so give it a try.
Employee Portfolio Generator [By MUQWISHI]▋ INTRODUCTION :
The “Employee Portfolio Generator” simplifies the process of building a long-term investment portfolio tailored for employees seeking to build wealth through investments rather than traditional bank savings. The tool empowers employees to set up recurring deposits at customizable intervals, enabling to make additional purchases in a list of preferred holdings, with the ability to define the purchasing investment weight for each security. The tool serves as a comprehensive solution for tracking portfolio performance, conducting research, and analyzing specific aspects of portfolio investments. The output includes an index value, a table of holdings, and chart plots, providing a deeper understanding of the portfolio's historical movements.
_______________________
▋ OVERVIEW:
● Scenario (The chart above can be taken as an example) :
Let say, in 2010, a newly employed individual committed to saving $1,000 each month. Rather than relying on a traditional savings account, chose to invest the majority of monthly savings in stable well-established stocks. Allocating 30% of monthly saving to AMEX:SPY and another 30% to NASDAQ:QQQ , recognizing these as reliable options for steady growth. Additionally, there was an admired toward innovative business models of NASDAQ:AAPL , NASDAQ:MSFT , NASDAQ:AMZN , and NASDAQ:EBAY , leading to invest 10% in each of those companies. By the end of 2024, after 15 years, the total monthly deposits amounted to $179,000, which would have been the result of traditional saving alone. However, by sticking into long term invest, the value of the portfolio assets grew, reaching nearly $900,000.
_______________________
▋ OUTPUTS:
The table can be displayed in three formats:
1. Portfolio Index Title: displays the index name at the top, and at the bottom, it shows the index value, along with the chart timeframe, e.g., daily change in points and percentage.
2. Specifications: displays the essential information on portfolio performance, including the investment date range, total deposits, free cash, returns, and assets.
3. Holdings: a list of the holding securities inside a table that contains the ticker, last price, entry price, return percentage of the portfolio's total deposits, and latest weighted percentage of the portfolio. Additionally, a tooltip appears when the user passes the cursor over a ticker's cell, showing brief information about the company, such as the company's name, exchange market, country, sector, and industry.
4. Indication of New Deposit: An indication of a new deposit added to the portfolio for additional purchasing.
5. Chart: The portfolio's historical movements can be visualized in a plot, displayed as a bar chart, candlestick chart, or line chart, depending on the preferred format, as shown below.
_______________________
▋ INDICATOR SETTINGS:
Section(1): Table Settings
(1) Naming the index.
(2) Table location on the chart and cell size.
(3) Sorting Holdings Table. By securities’ {Return(%) Portfolio, Weight(%) Portfolio, or Ticker Alphabetical} order.
(4) Choose the type of index: {Assets, Return, or Return (%)}, and the plot type for the portfolio index: {Candle, Bar, or Line}.
(5) Positive/Negative colors.
(6) Table Colors (Title, Cell, and Text).
(7) To show/hide any of selected indicator’s components.
Section(2): Recurring Deposit Settings
(1) From DateTime of starting the investment.
(2) To DateTime of ending the investment
(3) The amount of recurring deposit into portfolio and currency.
(4) The frequency of recurring deposits into the portfolio {Weekly, 2-Weeks, Monthly, Quarterly, Yearly}
(5) The Depositing Model:
● Fixed: The amount for recurring deposits remains constant throughout the entire investment period.
● Increased %: The recurring deposit amount increases at the selected frequency and percentage throughout the entire investment period.
(5B) If the user selects “ Depositing Model: Increased % ”, specify the growth model (linear or exponential) and define the rate of increase.
Section(3): Portfolio Holdings
(1) Enable a ticker in the investment portfolio.
(2) The selected deposit frequency weight for a ticker. For example, if the monthly deposit is $1,000 and the selected weight for XYZ stock is 30%, $300 will be used to purchase shares of XYZ stock.
(3) Select up to 6 tickers that the investor is interested in for long-term investment.
Please let me know if you have any questions
Calculate Order Entry Units based on set Dollar ValuesFUNCTIONS
- Calculate UNITS quantity based on user's input dollar values.
- Show Units in table
USAGE
- Enter 6 usual order $ values
- Use units value in order entry
Tradingview doesn't have order entry in dollar value for most connections/exchanges so it's really tedious to calculate Units some other way every time.
This gives you the Units based on your most used order value sizes in a quick way.
Possible future updates
- Allow user settings for number of values to display
- Allow user option to set titles for each row
Note:
Tradingview really need to get off their butts and give us a real DOM panel and working dollar value order entry for all exchanges among other order entry panel updates.
I hope everyone is suggesting this to them.
DynamicPeriodPublicDynamic Period Calculation Library
This library provides tools for adaptive period determination, useful for creating indicators or strategies that automatically adjust to market conditions.
Overview
The Dynamic Period Library calculates adaptive periods based on pivot points, enabling the creation of responsive indicators and strategies that adjust to market volatility.
Key Features
Dynamic Periods: Computes periods using distances between pivot highs and lows.
Customizable Parameters: Users can adjust detection settings and period constraints.
Robust Handling: Includes fallback mechanisms for cases with insufficient pivot data.
Use Cases
Adaptive Indicators: Build tools that respond to market volatility by adjusting their periods dynamically.
Dynamic Strategies: Enhance trading strategies by integrating pivot-based period adjustments.
Function: `dynamic_period`
Description
Calculates a dynamic period based on the average distances between pivot highs and lows.
Parameters
`left` (default: 5): Number of left-hand bars for pivot detection.
`right` (default: 5): Number of right-hand bars for pivot detection.
`numPivots` (default: 5): Minimum pivots required for calculation.
`minPeriod` (default: 2): Minimum allowed period.
`maxPeriod` (default: 50): Maximum allowed period.
`defaultPeriod` (default: 14): Fallback period if no pivots are found.
Returns
A dynamic period calculated based on pivot distances, constrained by `minPeriod` and `maxPeriod`.
Example
//@version=6
import CrimsonVault/DynamicPeriodPublic/1
left = input.int(5, "Left bars", minval = 1)
right = input.int(5, "Right bars", minval = 1)
numPivots = input.int(5, "Number of Pivots", minval = 2)
period = DynamicPeriodPublic.dynamic_period(left, right, numPivots)
plot(period, title = "Dynamic Period", color = color.blue)
Implementation Notes
Pivot Detection: Requires sufficient historical data to identify pivots accurately.
Edge Cases: Ensures a default period is applied when pivots are insufficient.
Constraints: Limits period values to a user-defined range for stability.
Market Anomaly Detector (MAD)Market Anomaly Detector (MAD) Indicator - Detailed Description:
The Market Anomaly Detector (MAD) Indicator is a unique tool designed to identify potential market anomalies by combining several price action-based and momentum indicators. This indicator is especially useful for traders who seek to identify significant market shifts and anomalies before they become visible in conventional technical indicators.
Key Features of the MAD Indicator:
1. Z-Score Threshold for Anomaly Detection:
• The Z-Score measures how far a current price is from its average over a defined period, normalized by standard deviation. This allows the MAD indicator to detect outliers or anomalies in price movements.
• By adjusting the Z-Score Threshold, traders can tune the sensitivity of the indicator to capture only the most significant price deviations, filtering out noise and reducing false signals.
2. Volume and Liquidity Filter:
• Volume is a key indicator of market participation and sentiment. The MAD Indicator uses a volume multiplier to assess when price movements are supported by sufficient trading volume.
• A volume spike is identified when the current volume exceeds the average volume by a certain multiplier. This ensures that only high-confidence signals are generated, particularly useful for spotting trend reversals and breakout opportunities.
3. Signal Cooldown Period:
• To prevent overfitting and reduce false signals, a signal cooldown period is implemented. Once a buy or sell signal is triggered, the indicator waits for a specified number of bars (e.g., 5) before triggering another signal, even if the price action meets the criteria for a new signal. This helps maintain a cleaner trading environment and avoids confusion when the market is volatile.
4. Upper and Lower Bands for Trend Confirmation:
• The MAD Indicator uses bands based on the mean price and standard deviation, similar to Bollinger Bands. These upper and lower bands help to define the expected price range for a given period, indicating overbought or oversold conditions.
• The combination of Z-Score, volume, and band analysis helps pinpoint when the price breaks out of expected ranges, providing early warning signs for potential market shifts.
5. Trend Confirmation from Higher Timeframes:
• The MAD Indicator includes a multi-timeframe approach to trend confirmation, using the 50-period EMA on a higher timeframe (e.g., 1-hour chart). This ensures that signals are aligned with the overall market trend, enhancing the reliability of buy and sell signals.
How It Works:
• The MAD Indicator continuously monitors price action, volume, and statistical anomalies, using the Z-Score to determine when the price is significantly deviating from its historical average.
• When the price breaks above the upper band and a bullish anomaly is detected, a buy signal is generated. (Green Background)
• Similarly, when the price breaks below the lower band and a bearish anomaly is detected, a sell signal is triggered. (Red Background
• By filtering signals based on volume and using the cooldown period, the MAD Indicator ensures that only high-quality trades are signaled.
How to Use the MAD Indicator:
• Buy Signal: Occurs when the price breaks above the upper band and there is a significant deviation from the mean (bullish anomaly).
• Sell Signal: Occurs when the price breaks below the lower band and there is a significant deviation from the mean (bearish anomaly).
• Volume Confirmation: Ensure that the buy/sell signals are supported by a volume spike, indicating strong market participation.
• Signal Cooldown Period: After a signal is triggered, the indicator waits for the cooldown period to avoid triggering multiple signals in quick succession.
Why It’s Worth Paying For:
The MAD Indicator combines advanced statistical analysis (Z-Score), price action, and volume analysis to identify market anomalies and breakouts before they are visible on standard indicators. By leveraging the power of mean reversion and statistical anomalies, this tool provides traders with high-confidence signals that can lead to profitable trades, especially in volatile markets. The integration of a multi-timeframe trend filter ensures that signals are aligned with the overall market trend, reducing the likelihood of false breakouts.
This indicator is ideal for trend-following traders looking for high-probability entries and mean-reversion traders aiming to capture price deviations. The signal cooldown period and volume filter provide an additional layer of precision, ensuring that you only act on the strongest market signals.
Quantify [Entry Model] | FractalystWhat’s the indicator’s purpose and functionality?
Quantify is a machine learning entry model designed to help traders identify high-probability setups to refine their strategies.
➙ Simply pick your bias, select your entry timeframes, and let Quantify handle the rest for you.
Can the indicator be applied to any market approach/trading strategy?
Absolutely, all trading strategies share one fundamental element: Directional Bias
Once you’ve determined the market bias using your own personal approach, whether it’s through technical analysis or fundamental analysis, select the trend direction in the Quantify user inputs.
The algorithm will then adjust its calculations to provide optimal entry levels aligned with your chosen bias. This involves analyzing historical patterns to identify setups with the highest potential expected values, ensuring your setups are aligned with the selected direction.
Can the indicator be used for different timeframes or trading styles?
Yes, regardless of the timeframe you’d like to take your entries, the indicator adapts to your trading style.
Whether you’re a swing trader, scalper, or even a position trader, the algorithm dynamically evaluates market conditions across your chosen timeframe.
How can this indicator help me to refine my trading strategy?
1. Focus on Positive Expected Value
• The indicator evaluates every setup to ensure it has a positive expected value, helping you focus only on trades that statistically favor long-term profitability.
2. Adapt to Market Conditions
• By analyzing real-time market behavior and historical patterns, the algorithm adjusts its calculations to match current conditions, keeping your strategy relevant and adaptable.
3. Eliminate Emotional Bias
• With clear probabilities, expected values, and data-driven insights, the indicator removes guesswork and helps you avoid emotional decisions that can damage your edge.
4. Optimize Entry Levels
• The indicator identifies optimal entry levels based on your selected bias and timeframes, improving robustness in your trades.
5. Enhance Risk Management
• Using tools like the Kelly Criterion, the indicator suggests optimal position sizes and risk levels, ensuring that your strategy maintains consistency and discipline.
6. Avoid Overtrading
• By highlighting only high-potential setups, the indicator keeps you focused on quality over quantity, helping you refine your strategy and avoid unnecessary losses.
How can I get started to use the indicator for my entries?
1. Set Your Market Bias
• Determine whether the market trend is Bullish or Bearish using your own approach.
• Select the corresponding bias in the indicator’s user inputs to align it with your analysis.
2. Choose Your Entry Timeframes
• Specify the timeframes you want to focus on for trade entries.
• The indicator will dynamically analyze these timeframes to provide optimal setups.
3. Let the Algorithm Analyze
• Quantify evaluates historical data and real-time price action to calculate probabilities and expected values.
• It highlights setups with the highest potential based on your selected bias and timeframes.
4. Refine Your Entries
• Use the insights provided—entry levels, probabilities, and risk calculations—to align your trades with a math-driven edge.
• Avoid overtrading by focusing only on setups with positive expected value.
5. Adapt to Market Conditions
• The indicator continuously adapts to real-time market behavior, ensuring its recommendations stay relevant and precise as conditions change.
How does the indicator calculate the current range?
The indicator calculates the current range by analyzing swing points from the very first bar on your charts to the latest available bar it identifies external liquidity levels, also known as BSLQ (buy-side liquidity levels) and SSLQ (sell-side liquidity levels).
What's the purpose of these levels? What are the underlying calculations?
1. Understanding Swing highs and Swing Lows
Swing High: A Swing High is formed when there is a high with 2 lower highs to the left and right.
Swing Low: A Swing Low is formed when there is a low with 2 higher lows to the left and right.
2. Understanding the purpose and the underlying calculations behind Buyside, Sellside and Pivot levels.
3. Identifying Discount and Premium Zones.
4. Importance of Risk-Reward in Premium and Discount Ranges
How does the script calculate probabilities?
The script calculates the probability of each liquidity level individually. Here's the breakdown:
1. Upon the formation of a new range, the script waits for the price to reach and tap into pivot level level. Status: "■" - Inactive
2. Once pivot level is tapped into, the pivot status becomes activated and it waits for either liquidity side to be hit. Status: "▶" - Active
3. If the buyside liquidity is hit, the script adds to the count of successful buyside liquidity occurrences. Similarly, if the sellside is tapped, it records successful sellside liquidity occurrences.
4. Finally, the number of successful occurrences for each side is divided by the overall count individually to calculate the range probabilities.
Note: The calculations are performed independently for each directional range. A range is considered bearish if the previous breakout was through a sellside liquidity. Conversely, a range is considered bullish if the most recent breakout was through a buyside liquidity.
What does the multi-timeframe functionality offer?
You can incorporate up to 4 higher timeframe probabilities directly into the table.
This feature allows you to analyze the probabilities of buyside and sellside liquidity across multiple timeframes, without the need to manually switch between them.
By viewing these higher timeframe probabilities in one place, traders can spot larger market trends and refine their entries and exits with a better understanding of the overall market context.
What are the multi-timeframe underlying calculations?
The script uses the same calculations (mentioned above) and uses security function to request the data such as price levels, bar time, probabilities and booleans from the user-input timeframe.
How does the Indicator Identifies Positive Expected Values?
Quantify instantly calculates whether a trade setup has the potential to generate positive expected value (EV).
To determine a positive EV setup, the indicator uses the formula:
EV = ( P(Win) × R(Win) ) − ( P(Loss) × R(Loss))
where:
- P(Win) is the probability of a winning trade.
- R(Win) is the reward or return for a winning trade, determined by the current risk-to-reward ratio (RR).
- P(Loss) is the probability of a losing trade.
- R(Loss) is the loss incurred per losing trade, typically assumed to be -1.
By calculating these values based on historical data and the current trading setup, the indicator helps you understand whether your trade has a positive expected value.
How can I know that the setup I'm going to trade with has a positive EV?
If the indicator detects that the adjusted pivot and buy/sell side probabilities have generated positive expected value (EV) in historical data, the risk-to-reward (RR) label within the range box will be colored blue and red .
If the setup does not produce positive EV, the RR label will appear gray.
This indicates that even the risk-to-reward ratio is greater than 1:1, the setup is not likely to yield a positive EV because, according to historical data, the number of losses outweighs the number of wins relative to the RR gain per winning trade.
What is the confidence level in the indicator, and how is it determined?
The confidence level in the indicator reflects the reliability of the probabilities calculated based on historical data. It is determined by the sample size of the probabilities used in the calculations. A larger sample size generally increases the confidence level, indicating that the probabilities are more reliable and consistent with past performance.
How does the confidence level affect the risk-to-reward (RR) label?
The confidence level (★) is visually represented alongside the probability label. A higher confidence level indicates that the probabilities used to determine the RR label are based on a larger and more reliable sample size.
How can traders use the confidence level to make better trading decisions?
Traders can use the confidence level to gauge the reliability of the probabilities and expected value (EV) calculations provided by the indicator. A confidence level above 95% is considered statistically significant and indicates that the historical data supporting the probabilities is robust. This high confidence level suggests that the probabilities are reliable and that the indicator’s recommendations are more likely to be accurate.
In data science and statistics, a confidence level above 95% generally means that there is less than a 5% chance that the observed results are due to random variation. This threshold is widely accepted in research and industry as a marker of statistical significance. Studies such as those published in the Journal of Statistical Software and the American Statistical Association support this threshold, emphasizing that a confidence level above 95% provides a strong assurance of data reliability and validity.
Conversely, a confidence level below 95% indicates that the sample size may be insufficient and that the data might be less reliable. In such cases, traders should approach the indicator’s recommendations with caution and consider additional factors or further analysis before making trading decisions.
How does the sample size affect the confidence level, and how does it relate to my TradingView plan?
The sample size for calculating the confidence level is directly influenced by the amount of historical data available on your charts. A larger sample size typically leads to more reliable probabilities and higher confidence levels.
Here’s how the TradingView plans affect your data access:
Essential Plan
The Essential Plan provides basic data access with a limited amount of historical data. This can lead to smaller sample sizes and lower confidence levels, which may weaken the robustness of your probability calculations. Suitable for casual traders who do not require extensive historical analysis.
Plus Plan
The Plus Plan offers more historical data than the Essential Plan, allowing for larger sample sizes and more accurate confidence levels. This enhancement improves the reliability of indicator calculations. This plan is ideal for more active traders looking to refine their strategies with better data.
Premium Plan
The Premium Plan grants access to extensive historical data, enabling the largest sample sizes and the highest confidence levels. This plan provides the most reliable data for accurate calculations, with up to 20,000 historical bars available for analysis. It is designed for serious traders who need comprehensive data for in-depth market analysis.
PRO+ Plans
The PRO+ Plans offer the most extensive historical data, allowing for the largest sample sizes and the highest confidence levels. These plans are tailored for professional traders who require advanced features and significant historical data to support their trading strategies effectively.
For many traders, the Premium Plan offers a good balance of affordability and sufficient sample size for accurate confidence levels.
What is the HTF probability table and how does it work?
The HTF (Higher Time Frame) probability table is a feature that allows you to view buy and sellside probabilities and their status from timeframes higher than your current chart timeframe.
Here’s how it works:
Data Request: The table requests and retrieves data from user-defined higher timeframes (HTFs) that you select.
Probability Display: It displays the buy and sellside probabilities for each of these HTFs, providing insights into the likelihood of price movements based on higher timeframe data.
Detailed Tooltips: The table includes detailed tooltips for each timeframe, offering additional context and explanations to help you understand the data better.
What do the different colors in the HTF probability table indicate?
The colors in the HTF probability table provide visual cues about the expected value (EV) of trading setups based on higher timeframe probabilities:
Blue: Suggests that entering a long position from the HTF user-defined pivot point, targeting buyside liquidity, is likely to result in a positive expected value (EV) based on historical data and sample size.
Red: Indicates that entering a short position from the HTF user-defined pivot point, targeting sellside liquidity, is likely to result in a positive expected value (EV) based on historical data and sample size.
Gray: Shows that neither long nor short trades from the HTF user-defined pivot point are expected to generate positive EV, suggesting that trading these setups may not be favorable.
What machine learning techniques are used in Quantify?
Quantify offers two main machine learning approaches:
1. Adaptive Learning (Fixed Sample Size): The algorithm learns from the entire dataset without resampling, maintaining a stable model that adapts to the latest market conditions.
2. Bootstrap Resampling: This method creates multiple subsets of the historical data, allowing the model to train on varying sample sizes. This technique enhances the robustness of predictions by ensuring that the model is not overfitting to a single dataset.
How does machine learning affect the expected value calculations in Quantify?
Machine learning plays a key role in improving the accuracy of expected value (EV) calculations. By analyzing historical price action, liquidity hits, and market bias patterns, the model continuously adjusts its understanding of risk and reward, allowing the expected value to reflect the most likely market movements. This results in more precise EV predictions, helping traders focus on setups that maximize profitability.
What is the Kelly Criterion, and how does it work in Quantify?
The Kelly Criterion is a mathematical formula used to determine the optimal position size for each trade, maximizing long-term growth while minimizing the risk of large drawdowns. It calculates the percentage of your portfolio to risk on a trade based on the probability of winning and the expected payoff.
Quantify integrates this with user-defined inputs to dynamically calculate the most effective position size in percentage, aligning with the trader’s risk tolerance and desired exposure.
How does Quantify use the Kelly Criterion in practice?
Quantify uses the Kelly Criterion to optimize position sizing based on the following factors:
1. Confidence Level: The model assesses the confidence level in the trade setup based on historical data and sample size. A higher confidence level increases the suggested position size because the trade has a higher probability of success.
2. Max Allowed Drawdown (User-Defined): Traders can set their preferred maximum allowed drawdown, which dictates how much loss is acceptable before reducing position size or stopping trading. Quantify uses this input to ensure that risk exposure aligns with the trader’s risk tolerance.
3. Probabilities: Quantify calculates the probabilities of success for each trade setup. The higher the probability of a successful trade (based on historical price action and liquidity levels), the larger the position size suggested by the Kelly Criterion.
What is a trailing stoploss, and how does it work in Quantify?
A trailing stoploss is a dynamic risk management tool that moves with the price as the market trend continues in the trader’s favor. Unlike a fixed take profit, which stays at a set level, the trailing stoploss automatically adjusts itself as the market moves, locking in profits as the price advances.
In Quantify, the trailing stoploss is enhanced by incorporating market structure liquidity levels (explain above). This ensures that the stoploss adjusts intelligently based on key price levels, allowing the trader to stay in the trade as long as the trend remains intact, while also protecting profits if the market reverses.
Why would a trader prefer a trailing stoploss based on liquidity levels instead of a fixed take-profit level?
Traders who use trailing stoplosses based on liquidity levels prefer this method because:
1. Market-Driven Flexibility: The stoploss follows the market structure rather than being static at a pre-defined level. This means the stoploss is less likely to be hit by small market fluctuations or false reversals. The stoploss remains adaptive, moving as the market moves.
2. Riding the Trend: Traders can capture more profit during a sustained trend because the trailing stop will adjust only when the trend starts to reverse significantly, based on key liquidity levels. This allows them to hold positions longer without prematurely locking in profits.
3. Avoiding Premature Exits: Fixed stoploss levels may exit a trade too early in volatile markets, while liquidity-based trailing stoploss levels respect the natural flow of price action, preventing the trader from exiting too soon during pullbacks or minor retracements.
🎲 Becoming the House: Gaining an Edge Over the Market
In American roulette, the casino has a 5.26% edge due to the presence of the 0 and 00 pockets. On even-money bets, players face a 47.37% chance of winning, while true 50/50 odds would require a 50% chance. This edge—the gap between the payout odds and the true probabilities—ensures that, statistically, the casino will always win over time, even if individual players win occasionally.
From a Trader’s Perspective
In trading, your edge comes from identifying and executing setups with a positive expected value (EV). For example:
• If you identify a setup with a 55.48% chance of winning and a 1:1 risk-to-reward (RR) ratio, your trade has a statistical advantage over a neutral (50/50) probability.
This edge works in your favor when applied consistently across a series of trades, just as the casino’s edge ensures profitability across thousands of spins.
🎰 Applying the Concept to Trading
Like casinos leverage their mathematical edge in games of chance, you can achieve long-term success in trading by focusing on setups with positive EV and managing your trades systematically. Here’s how:
1. Probability Advantage: Prioritize trades where the probability of success (win rate) exceeds the breakeven rate for your chosen risk-to-reward ratio.
• Example: With a 1:1 RR, you need a win rate above 50% to achieve positive EV.
2. Risk-to-Reward Ratio (RR): Even with a win rate below 50%, you can gain an edge by increasing your RR (e.g., a 40% win rate with a 2:1 RR still has positive EV).
3. Consistency and Discipline: Just as casinos profit by sticking to their mathematical advantage over thousands of spins, traders must rely on their edge across many trades, avoiding emotional decisions or overleveraging.
By targeting favorable probabilities and managing trades effectively, you “become the house” in your trading. This approach allows you to leverage statistical advantages to enhance your overall performance and achieve sustainable profitability.
What Makes the Quantify Indicator Original?
1. Data-Driven Edge
Unlike traditional indicators that rely on static formulas, Quantify leverages probability-based analysis and machine learning. It calculates expected value (EV) and confidence levels to help traders identify setups with a true statistical edge.
2. Integration of Market Structure
Quantify uses market structure liquidity levels to dynamically adapt. It identifies key zones like swing highs/lows and liquidity traps, enabling users to align entries and exits with where the market is most likely to react. This bridges the gap between price action analysis and quantitative trading.
3. Sophisticated Risk Management
The Kelly Criterion implementation is unique. Quantify allows traders to input their maximum allowed drawdown, dynamically adjusting risk exposure to maintain optimal position sizing. This ensures risk is scientifically controlled while maximizing potential growth.
4. Multi-Timeframe and Liquidity-Based Trailing Stops
The indicator doesn’t just suggest fixed profit-taking levels. It offers market structure-based trailing stop-loss functionality, letting traders ride trends as long as liquidity and probabilities favor the position, which is rare in most tools.
5. Customizable Bias and Adaptive Learning
• Directional Bias: Traders can set a bullish or bearish bias, and the indicator recalculates probabilities to align with the trader’s market outlook.
• Adaptive Learning: The machine learning model adapts to changes in data (via resampling or bootstrap methods), ensuring that predictions stay relevant in evolving markets.
6. Positive EV Focus
The focus on positive EV setups differentiates it from reactive indicators. It shifts trading from chasing signals to acting on setups that statistically favor profitability, akin to how professional quant funds operate.
7. User Empowerment
Through features like customizable timeframes, real-time probability updates, and visualization tools, Quantify empowers users to make data-informed decisions.
Terms and Conditions | Disclaimer
Our charting tools are provided for informational and educational purposes only and should not be construed as financial, investment, or trading advice. They are not intended to forecast market movements or offer specific recommendations. Users should understand that past performance does not guarantee future results and should not base financial decisions solely on historical data.
Built-in components, features, and functionalities of our charting tools are the intellectual property of @Fractalyst use, reproduction, or distribution of these proprietary elements is prohibited.
By continuing to use our charting tools, the user acknowledges and accepts the Terms and Conditions outlined in this legal disclaimer and agrees to respect our intellectual property rights and comply with all applicable laws and regulations.
Salience Theory Crypto Returns (AiBitcoinTrend)The Salience Theory Crypto Returns Indicator is a sophisticated tool rooted in behavioral finance, designed to identify trading opportunities in the cryptocurrency market. Based on research by Bordalo et al. (2012) and extended by Cai and Zhao (2022), it leverages salience theory—the tendency of investors, particularly retail traders, to overemphasize standout returns.
In the crypto market, dominated by sentiment-driven retail investors, salience effects are amplified. Attention disproportionately focused on certain cryptocurrencies often leads to temporary price surges, followed by reversals as the market stabilizes. This indicator quantifies these effects using a relative return salience measure, enabling traders to capitalize on price reversals and trends, offering a clear edge in navigating the volatile crypto landscape.
👽 How the Indicator Works
Salience Measure Calculation :
👾 The indicator calculates how much each cryptocurrency's return deviates from the average return of all cryptos over the selected ranking period (e.g., 21 days).
👾 This deviation is the salience measure.
👾 The more a return stands out (salient outcome), the higher the salience measure.
Ranking:
👾 Cryptos are ranked in ascending order based on their salience measures.
👾 Rank 1 (lowest salience) means the crypto is closer to the average return and is more predictable.
👾 Higher ranks indicate greater deviation and unpredictability.
Color Interpretation:
👾 Green: Low salience (closer to average) – Trending or Predictable.
👾 Red/Orange: High salience (far from average) – Overpriced/Unpredictable.
👾 Text Gradient (Teal to Light Blue): Helps visualize potential opportunities for mean reversion trades (i.e., cryptos that may return to equilibrium).
👽 Core Features
Salience Measure Calculation
The indicator calculates the salience measure for each cryptocurrency by evaluating how much its return deviates from the average market return over a user-defined ranking period. This measure helps identify which assets are trending predictably and which are likely to experience a reversal.
Dynamic Ranking System
Cryptocurrencies are dynamically ranked based on their salience measures. The ranking helps differentiate between:
Low Salience Cryptos (Green): These are trending or predictable assets.
High Salience Cryptos (Red): These are overpriced or deviating significantly from the average, signaling potential reversals.
👽 Deep Dive into the Core Mathematics
Salience Theory in Action
Salience theory explains how investors, particularly in the crypto market, tend to prefer assets with standout returns (salient outcomes). This behavior often leads to overpricing of assets with high positive returns and underpricing of those with standout negative returns. The indicator captures these deviations to anticipate mean reversions or trend continuations.
Salience Measure Calculation
// Calculate the average return
avgReturn = array.avg(returns)
// Calculate salience measure for each symbol
salienceMeasures = array.new_float()
for i = 0 to array.size(returns) - 1
ret = array.get(returns, i)
salienceMeasure = math.abs(ret - avgReturn) / (math.abs(ret) + math.abs(avgReturn) + 0.1)
array.push(salienceMeasures, salienceMeasure)
Dynamic Ranking
Cryptos are ranked in ascending order based on their salience measures:
Low Ranks: Cryptos with low salience (predictable, trending).
High Ranks: Cryptos with high salience (unpredictable, likely to revert).
👽 Applications
👾 Trend Identification
Identify cryptocurrencies that are currently trending with low salience measures (green). These assets are likely to continue their current direction, making them good candidates for trend-following strategies.
👾 Mean Reversion Trading
Cryptos with high salience measures (red to light blue) may be poised for a mean reversion. These assets are likely to correct back towards the market average.
👾 Reversal Signals
Anticipate potential reversals by focusing on high-ranked cryptos (red). These assets exhibit significant deviation and are prone to price corrections.
👽 Why It Works in Crypto
The cryptocurrency market is dominated by retail investors prone to sentiment-driven behavior. This leads to exaggerated price movements, making the salience effect a powerful predictor of reversals.
👽 Indicator Settings
👾 Ranking Period : Number of bars used to calculate the average return and salience measure.
Higher Values: Smooth out short-term volatility.
Lower Values: Make the ranking more sensitive to recent price movements.
👾 Number of Quantiles : Divide ranked assets into quantile groups (e.g., quintiles).
Higher Values: More detailed segmentation (deciles, percentiles).
Lower Values: Broader grouping (quintiles, quartiles).
👾 Portfolio Percentage : Percentage of the portfolio allocated to each selected asset.
Enter a percentage (e.g., 20 for 20%), automatically converted to a decimal (e.g., 0.20).
Disclaimer: This information is for entertainment purposes only and does not constitute financial advice. Please consult with a qualified financial advisor before making any investment decisions.
Valuation MetricValuation Metric Indicator
The Valuation Metric Indicator provides a comprehensive tool for evaluating price dynamics in relation to a moving average and standard deviation. It combines the power of statistical analysis with clear visualizations to help traders assess market valuation levels and potential overbought or oversold conditions.
Key Features:
Z-Score Calculation:
Displays the Z-score of the price relative to the moving average, normalized by standard deviation.
Z-score is clamped within the range of -3 to +3 to focus on significant deviations.
Standard Deviation Bands:
Plots bands at 1x, 2x, and 3x standard deviations above and below the moving average.
Helps identify areas of extreme overvaluation or undervaluation.
Dynamic Valuation Table:
Displays the current Z-score and provides a textual assessment of the market's valuation:
Overvalued
Slightly Overvalued
Neutral
Slightly Undervalued
Undervalued
Background color dynamically changes based on the valuation.
Customizable Background Signals:
Optional background highlighting for "Top Signal" (overvaluation) and "Bottom Signal" (undervaluation).
Configurable Display:
Users can toggle the visibility of standard deviation bands and background signals to fit their preferences.
Color-Coded Visualization:
Uses gradient-based color coding for Z-scores and standard deviation bands, improving readability and decision-making.
Asset Correlation CheckThis indicator evaluates how your current chart symbol interacts with key markets such as stock indices NASDAQ:NDX SP:SPX AMEX:IWM XETR:DAX PEPPERSTONE:CN50 , commodities CAPITALCOM:GOLD CAPITALCOM:SILVER , bonds NASDAQ:TLT NASDAQ:SHY , and cryptocurrencies BINANCE:BTCUSD , and displays the results in a compact, interactive table. It allows you to adjust the analysis period and select one of three correlation calculation methods (Index, Relative, and Beta) to gain different perspectives on the relationships between assets.
Index Correlation
Advantages: Provides a classic statistical correlation value, making it easy to understand overall directional alignment.
Drawbacks: Less reliable for highly volatile or short-term conditions, as temporary spikes can distort the correlation.
When to use: Ideal if you want a clear overview of whether two markets generally move together, for example to assess diversification effects.
Relative Correlation
Advantages: Focuses on percentage changes rather than absolute prices, offering a more dynamic view of short-term shifts.
Drawbacks: More prone to noise due to emphasizing daily or intra-period fluctuations.
When to use: Useful for timing-sensitive strategies, helping you quickly identify if one asset consistently outpaces or lags another in the short run.
Beta Correlation
Advantages: Examines how strongly one asset responds to changes in another, factoring in volatility and sensitivity, helpful for risk profiling.
Drawbacks: More abstract since it does not convey simple directional similarity but how intensely an asset reacts to market movements.
When to use: Ideal if you need to understand how a security may amplify or dampen broader market-level shifts, aiding in portfolio risk management.
Additionally, a Bull-Market Filter narrows the analysis to upward-trending phases, potentially delivering more meaningful insights. The indicator also computes average correlation values over your selected period, so you are not misled by brief fluctuations. It shows the percentage of positive versus negative readings to reveal if markets generally move in tandem or counter to each other.
For stock pickers, this tool is particularly valuable. It helps determine whether individual equities follow broader market forces, move with specific sectors, or behave independently. With this knowledge, you can refine stock selection, balance sector exposures, and seek opportunities that complement existing positions.
The indicator also facilitates the detection of patterns and anomalies, enabling early recognition of shifts in sentiment or new trend impulses. By visualizing how benchmarks, commodities, bonds, and digital assets relate, you gain deeper insight into key drivers that influence your investments.
Regarding rapid changes in correlation, keep in mind that correlation can frequently flip between positive and negative. Such volatility can create confusion if you rely on single readings. One moment, two assets may seem perfectly aligned; the next, they diverge. This does not necessarily indicate a lack of an underlying pattern; short-term factors can distort the picture. By looking at averages and the frequency of positive and negative occurrences, you confirm whether a correlation trend is genuine or simply a result of temporary noise. In other words, these additional metrics ensure that short-lived swings do not overshadow the true, longer-term relationship between the assets.
In essence, this indicator condenses complex intermarket analysis into a practical resource. By leveraging its insights, you can make data-driven decisions, adapt strategies to evolving market conditions, and lay a stronger foundation for long-term trading success.
Psychological Levels- Rounding Numbers Psychological Levels Indicator
Overview:
The Psychological Levels Indicator automatically identifies and plots significant price levels based on psychological thresholds, which are key areas where market participants often focus their attention. These levels act as potential support or resistance zones due to human behavioral tendencies to round off numbers. This indicator dynamically adjusts the levels based on the stock's price range and ensures seamless visibility across the chart.
Key Features:
Dynamic Step Sizes:
The indicator adjusts the levels dynamically based on the stock price:
For prices below 500: Levels are spaced at 10.
For prices between 500 and 3000: Levels are spaced at 50, 100, and 1000.
For prices between 3000 and 10,000: Levels are spaced at 100 and 1000.
For prices above 10,000: Levels are spaced at 500 and 1000.
Extended Visibility:
The plotted levels are extended across the entire chart for improved visualization, ensuring traders can easily monitor these critical zones over time.
Customization Options:
Line Color: Choose the color for the levels to suit your charting style.
Line Style: Select from solid, dashed, or dotted lines.
Line Width: Adjust the thickness of the lines for better clarity.
Clean and Efficient Design:
The indicator only plots levels relevant to the visible chart range, avoiding unnecessary clutter and ensuring a clean workspace.
How It Works:
It calculates the relevant step sizes based on the price:
Smaller step sizes for lower-priced stocks.
Larger step sizes for higher-priced stocks.
Primary, secondary, and (if applicable) tertiary levels are plotted dynamically:
Primary Levels: The most granular levels based on the stock price.
Secondary Levels: Higher-order levels for broader significance.
Tertiary Levels: Additional levels for lower-priced stocks to enhance detail.
These levels are plotted across the chart, allowing traders to visualize key psychological areas effortlessly.
Use Cases:
Day Trading: Identify potential intraday support and resistance levels.
Swing Trading: Recognize key price zones where trends may pause or reverse.
Long-Term Investing: Gain insights into significant price zones for entry or exit strategies.
AiTrend Pattern Matrix for kNN Forecasting (AiBitcoinTrend)The AiTrend Pattern Matrix for kNN Forecasting (AiBitcoinTrend) is a cutting-edge indicator that combines advanced mathematical modeling, AI-driven analytics, and segment-based pattern recognition to forecast price movements with precision. This tool is designed to provide traders with deep insights into market dynamics by leveraging multivariate pattern detection and sophisticated predictive algorithms.
👽 Core Features
Segment-Based Pattern Recognition
At its heart, the indicator divides price data into discrete segments, capturing key elements like candle bodies, high-low ranges, and wicks. These segments are normalized using ATR-based volatility adjustments to ensure robustness across varying market conditions.
AI-Powered k-Nearest Neighbors (kNN) Prediction
The predictive engine uses the kNN algorithm to identify the closest historical patterns in a multivariate dictionary. By calculating the distance between current and historical segments, the algorithm determines the most likely outcomes, weighting predictions based on either proximity (distance) or averages.
Dynamic Dictionary of Historical Patterns
The indicator maintains a rolling dictionary of historical patterns, storing multivariate data for:
Candle body ranges, High-low ranges, Wick highs and lows.
This dynamic approach ensures the model adapts continuously to evolving market conditions.
Volatility-Normalized Forecasting
Using ATR bands, the indicator normalizes patterns, reducing noise and enhancing the reliability of predictions in high-volatility environments.
AI-Driven Trend Detection
The indicator not only predicts price levels but also identifies market regimes by comparing current conditions to historically significant highs, lows, and midpoints. This allows for clear visualizations of trend shifts and momentum changes.
👽 Deep Dive into the Core Mathematics
👾 Segment-Based Multivariate Pattern Analysis
The indicator analyzes price data by dividing each bar into distinct segments, isolating key components such as:
Body Ranges: Differences between the open and close prices.
High-Low Ranges: Capturing the full volatility of a bar.
Wick Extremes: Quantifying deviations beyond the body, both above and below.
Each segment contributes uniquely to the predictive model, ensuring a rich, multidimensional understanding of price action. These segments are stored in a rolling dictionary of patterns, enabling the indicator to reference historical behavior dynamically.
👾 Volatility Normalization Using ATR
To ensure robustness across varying market conditions, the indicator normalizes patterns using Average True Range (ATR). This process scales each component to account for the prevailing market volatility, allowing the algorithm to compare patterns on a level playing field regardless of differing price scales or fluctuations.
👾 k-Nearest Neighbors (kNN) Algorithm
The AI core employs the kNN algorithm, a machine-learning technique that evaluates the similarity between the current pattern and a library of historical patterns.
Euclidean Distance Calculation:
The indicator computes the multivariate distance across four distinct dimensions: body range, high-low range, wick low, and wick high. This ensures a comprehensive and precise comparison between patterns.
Weighting Schemes: The contribution of each pattern to the forecast is either weighted by its proximity (distance) or averaged, based on user settings.
👾 Prediction Horizon and Refinement
The indicator forecasts future price movements (Y_hat) by predicting logarithmic changes in the price and projecting them forward using exponential scaling. This forecast is smoothed using a user-defined EMA filter to reduce noise and enhance actionable clarity.
👽 AI-Driven Pattern Recognition
Dynamic Dictionary of Patterns: The indicator maintains a rolling dictionary of N multivariate patterns, continuously updated to reflect the latest market data. This ensures it adapts seamlessly to changing market conditions.
Nearest Neighbor Matching: At each bar, the algorithm identifies the most similar historical pattern. The prediction is based on the aggregated outcomes of the closest neighbors, providing confidence levels and directional bias.
Multivariate Synthesis: By combining multiple dimensions of price action into a unified prediction, the indicator achieves a level of depth and accuracy unattainable by single-variable models.
Visual Outputs
Forecast Line (Y_hat_line):
A smoothed projection of the expected price trend, based on the weighted contribution of similar historical patterns.
Trend Regime Bands:
Dynamic high, low, and midlines highlight the current market regime, providing actionable insights into momentum and range.
Historical Pattern Matching:
The nearest historical pattern is displayed, allowing traders to visualize similarities
👽 Applications
Trend Identification:
Detect and follow emerging trends early using dynamic trend regime analysis.
Reversal Signals:
Anticipate market reversals with high-confidence predictions based on historically similar scenarios.
Range and Momentum Trading:
Leverage multivariate analysis to understand price ranges and momentum, making it suitable for both breakout and mean-reversion strategies.
Disclaimer: This information is for entertainment purposes only and does not constitute financial advice. Please consult with a qualified financial advisor before making any investment decisions.
Standard Deviation of Returns: DivergencePurpose:
The "Standard Deviation of Returns: Divergence" indicator is designed to help traders identify potential trend reversals or continuation signals by analyzing divergences between price action and the statistical volatility of returns. Divergences can signal weakening momentum in the prevailing trend, offering insight into potential buying or selling opportunities.
Key Components
1. Returns Calculation:
* The indicator uses logarithmic returns (log(close / close )) to measure relative price changes in a normalized manner.
* Log returns are more effective than simple price differences when analyzing data across varying price levels, as they account for percentage-based changes.
2. Standard Deviation of Returns:
* The script computes the standard deviation of returns over a user-defined lookback period (ta.stdev(returns, lookback)).
* Standard deviation measures the dispersion of returns around their average, effectively quantifying market volatility.
* A higher standard deviation indicates increased volatility, while lower standard deviation reflects a calmer market.
3. Price Action:
* Detects higher highs (new peaks in price) and lower lows (new troughs in price) over the lookback period.
* Price trends are compared to the behavior of the standard deviation.
4. Divergence Detection:
A divergence occurs when price action (higher highs or lower lows) is not confirmed by a corresponding movement in standard deviation:
Bullish Divergence: Price makes a lower low, but the standard deviation does not, signaling potential upward momentum.
Bearish Divergence: Price makes a higher high, but the standard deviation does not, signaling potential downward momentum.
5. Visual Cues:
The script highlights divergence regions directly on the chart:
Green Background: Indicates a bullish divergence (potential buy signal).
Red Background: Indicates a bearish divergence (potential sell signal).
How It Works
Inputs:
* The user specifies the lookback period (lookback) for calculating the standard deviation and detecting divergences.
Calculation:
* Each bar’s returns are computed and used to calculate the standard deviation over the specified lookback period.
* The indicator evaluates price highs/lows and compares these with the highest and lowest values of the standard deviation within the same lookback period.
Highlight of Divergences:
When divergences are detected:
Bullish Divergence: The background of the chart is shaded green.
Bearish Divergence: The background of the chart is shaded red.
Trading Application
Bullish Divergence:
* Occurs when the market is oversold, or downward momentum is weakening.
* Suggests a potential reversal to an uptrend, signaling a buying opportunity.
Bearish Divergence:
* Occurs when the market is overbought, or upward momentum is weakening.
* Suggests a potential reversal to a downtrend, signaling a selling opportunity.
Contextual Use:
* Use this indicator in conjunction with other technical tools like RSI, MACD, or moving averages to confirm signals.
* Effective in volatile or ranging markets to help anticipate shifts in momentum.
Summary
The "Standard Deviation of Returns: Divergence" indicator is a robust tool for spotting divergences that can signal weakening market trends. It combines statistical volatility with price action analysis to highlight key areas of potential reversals. By integrating this tool into your trading strategy, you can gain additional confirmation for entries or exits while keeping a close watch on momentum shifts.
Disclaimer: This is not a financial advise; please consult your financial advisor for personalized advice.
Stochastic Oscillator-Time & Frequency StatsThe Stochastic Oscillator Time & Frequency Statistics indicator is a tool designed to enhance your trading decisions by combining the traditional Stochastic Oscillator with additional metrics and visual aids. Although the Stochastic Oscillator is typically used to indicate trend direction and overbought/oversold conditions, the %K and %D lines can cross over and under multiple times while in the critical zones. The statistics added to this indicator allow traders to assess the probability of multiple crossover signals occurring on an asset or within various time frames. Signal levels and definitions of critical zones can be adjusted while the statistics are automatically updated to the relevant ticker, time frame and thresholds. Visual preferences such as colors and signal shapes can also be customized.
The Stochastic Oscillator is a commonly used momentum indicator developed by George Lane. It measures the position of the current closing price relative to the asset's recent high-low range over a set period. This advanced version calculates various probability and frequency statistics to better understand the oscillator’s behaviour and guide our strategies and risk management. Some key questions that this indicator intends to address are:
How long does the average momentum last in a trend?; How long does the oscillator remain in the critical zones?; How many times could one expect crossovers/unders' to occur in critical zones before momentum changes?; And, at what price does the candle need to close for the k & d lines to cross and signal a momentum shift?
Statistics & Probabilities:
The indicator calculates important time and frequency-based metrics that provide deeper insight into the behavior of the Stochastic Oscillator. These are displayed in a text box on the indicator panel, including:
Avg Long: The average number of bars between the last long signal before exiting the critical oversold zone and the next short signal in the overbought critical zone, including the standard deviation and the sample size within the relevant time frame.
Avg Short: The average number of bars between the last short signal in the overbought critical zone and the next long signal in the oversold critical zone, including the standard deviation and the sample size within the relevant time frame.
Time in Oversold: The average time (in bars/candle sticks) that the Stochastic Oscillator's %K & %D lines both spend in the oversold region (below the buy signal level) after entering and before departing the oversold region, along with the standard deviation.
Time in Overbought: The average time (in bars/candle sticks) that the Stochastic Oscillator's %K & %D lines both spend in the overbought region (above the sell signal level), after entering and before departing the overbought region, along with the standard deviation.
Signal Frequency: It calculates the percentage of long or short signals that occur consecutively within the critical zone before the opposing signal occurs (e.g., 1Long: 40.54%, 2 Long: 28.55%, 3Long: 17.4%, >3 Long: 13.51%, 1Short: 36.15%, 2Short: 30.41%, 3Short: 17.57%, >3Short: 15.88%). This is calculated for 1 through 6 consecutive occurrences and summarised for more than 6 consecutive signals
Key Features:
Oversold: Typically When the Stochastic Oscillator is below 20, it indicates that the asset may be oversold, potentially signalling a buying opportunity. The threshold for "overbought" and "oversold" extreme regions can be adjusted
Overbought: When the Stochastic Oscillator is above 80, it suggests the asset may be overbought, and a downturn might be near.
Stochastic Slope: The slope of the Stochastic Oscillator indicates the prominent trend direction within the selected time period.
Customizable Buy/Sell Signal Levels: The indicator allows customizable levels for detecting oversold (typically below 20-25) and overbought (typically above 75-80) conditions, helping one spot potential reversal zones for initiating long or short trades.
Crossover Alerts: The indicator tracks crossovers between the %K and %D lines, generating:
Long signals: When a crossover occurs below the buy signal level (indicating oversold conditions).
Short signals: when a crossunder occurs above the sell signal level (indicating overbought conditions).
The signals are visualized as labels on the chart:
- **L** for potential long (buy) signals: Marked below the bars when the %K line crosses above the %D line.
- **S** for potential short (sell) signals: Marked above the bars when the %K line crosses below the %D line.
Disclaimers:
No Guarantees: The indicator is provided "as-is" without any warranties or guarantees of accuracy, completeness, or fitness for a particular purpose. The outcomes or performance of trades executed using this indicator are not guaranteed to be successful or profitable.
User Responsibility: You are solely responsible for any trading decisions you make based on the use of this indicator. All trading and investment activities involve risk, and it is essential to conduct your own research, analysis, and due diligence before making any financial decisions.
No Liability: The creator of this indicator is not responsible for any financial losses, direct or indirect, incurred as a result of using this indicator. This includes, but is not limited to, loss of profits, loss of capital, or any other negative financial outcomes.
Market Risks: Markets are volatile, and prices may fluctuate significantly. Trading and investing carry inherent risks, and there is always the potential for loss. You should only trade with capital that you can afford to lose.
Independent Advice: This indicator and the content generated by its creator does not constitute financial advice and is for entertainment purposes only. It is strongly recommended that you seek independent financial advice from a qualified and licensed professional before making any trading or investment decisions based on the use of this indicator.
By using this indicator, you acknowledge that you fully understand and accept the risks involved, and you agree to indemnify and hold harmless the creator of this indicator from any claims, damages, or liabilities arising from its use.
The author of this script has made every effort to ensure that the code is an original interpretation and application of the open-source **Stochastic Oscillator**, as developed by George Lane. The script reflects a unique adaptation aimed at enhancing trading strategies through advanced statistical analysis and trade management features. The author does not claim any proprietary rights over the foundational concepts of the **Stochastic Oscillator** and does not intend to infringe upon any existing copyrights. Should any copyright infringement be identified, the author commits to removing the indicator immediately and forfeits any rights to further or intended financial gain from its use.
Crypto Sectors Performance [Daveatt]IMPORTANT
⚠️ This script must be used on the Daily timeframe only.
OVERVIEW
This indicator brings the powerful sector analysis capabilities from velo.xyz/market's
Sector Performance chart to TradingView.
It enables traders to track and compare performance across the crypto market's major sectors, providing essential insights for sector rotation strategies and market analysis.
CALCULATION METHOD
The indicator calculates performance across six key crypto sectors: DeFi, Gaming, Layer 1s, Layer 2s, AI, and Memecoins.
For each sector, it computes a rolling percentage performance by averaging the performance of multiple representative tokens.
All sector performances are rebased to 0% at the start of each period, making relative comparisons clear and intuitive.
VISUALIZATION MODES
The script features two distinct visualization methods:
Plots Mode:
Displays continuous performance lines for each sector over time, ideal for tracking relative strength trends and sector momentum. Each sector has its own color-coded line with performance values clearly marked.
Bars Mode:
Presents current sector performance as vertical bars, offering an immediate visual comparison of sector gains and losses.
The bars are color-coded and labeled with exact percentage values for precise analysis.
For the "Bars Mode", I used the box.new() function
SECTOR COMPOSITION
Each sector comprises carefully selected representative tokens:
- DeFi: AAVE, 1INCH, JUP, MKR, UNI
- Gaming: GALA, AXS, RONIN, SAND
- Layer 1: BTC, ETH, AVAX, APT, SOL, BNB, SUI
- Layer 2: ARB, OP, ZK, POL, STRK, MNT
- AI: FET, NEAR, RENDER, TAO
- Memecoins: PEPE, BONK, SHIB, DOGE, WIFU, POPCAT
PERFORMANCE TRACKING
The indicator implements a rolling window approach for performance calculations.
Starting from 0% at the beginning of each period, it tracks relative performance with positive values indicating outperformance and negative values showing underperformance.
Multiple timeframe options (1W, 1M, 3M, 6M, and 1Y) allow for both short-term and long-term analysis.
APPLICATIONS
This tool proves invaluable for:
- Sector rotation analysis
- Identifying trending sectors
- Comparing relative strength
- Gauging market sentiment
- Understanding market structure through sector performance
Thanks for reading and for the support
Daveatt
linreg-gridbotLinreg-GridBot
>release note version 1<
Introduction
This script is a powerful trading strategy tool designed to help users identify market reversal points and make smarter trading decisions using grid thinking.
Background
Traditional grid/martingale strategies have several drawbacks: inefficient use of capital, premature grid boundaries, and trading at fixed intervals, all of which significantly reduce profitability. Since, there is not a gridbot can trail-stop at each level, stay close with the trend, and do better capital usage, tradalive has created this advanced gridbot to address these issues, and enhance the profitability.
How does it work?
Imagine plotting closes on a graph, where the x-axis represents the time-intervals and the y-axis represents the price. Linear regression would fit a straight line through these points that best represents the trend of the data.
In this script utilize the built-in to find consecutive slopes at each moment, and combine them to a smooth trend line. When turning point censored, an entry is placed right after the next bar. Then the gridbot starts working, the upper limit and lower limit is calculated by built-in , for example 3 ATRs above and under the entry price.
There is a 0.2 trailing stop for each step level. Also, when built-in VWMA is rising, this script uses built-in ROC to find the average change of lookback length, then move the grid upwards accordingly.
Size trading is crucial, in gridbot all-in when beginning the trade is risky, because turning point does not guarantee a reversal market upcoming. As a grid trader, we believe the price is relatively cheap near the lower limit, and the price is relatively expensive near the upper limit. Properly sized orders help prevent overexposure and reduce the potential for significant losses.
Features
Trend Detection: Utilizes linear regression to differentiate between upward and downward trends, displaying them as (orange) trend lines on the chart.
Signal Generation: Provides buy or sell signals at reversal points, helping users trade at optimal times.
Adjustable Parameters: Allows users to customize different indicator parameters to fit various trading strategies.
Backtested Device Parameters (see appendix)
Grid Parameters
🔃: Cyclic Trading
💰: Capital Turnover Ratio (Grid capital difference per level: 0.5 to 2)
⬆️ / ⬇️ Expected Number of Upward and Downward Grids.
The minimum number of grids is three: one level above and below the current price.
The maximum number of grids is seven: three levels above and below the current price.
🧭: Trade Signal: Controls the trading direction, long or short;
📏: Linear regression length value.
⏳⌛Backtest Period: Set the time range for users to analyze the performance of the strategy over different periods.
Analytic Toolbox (upper right corner) :
Usage Instructions
Add this script to your TradingView account.
Apply the script to your chart.
Adjust the parameters to fit your trading needs.
Make trading decisions based on the buy and sell signals.
Manually place orders on your trading platform using the parameters provided.
Enter grid parameters according to the highest and lowest prices.
Fill in the number of grid levels (the number of grids equals the number of upward grids plus the number of downward grids plus one).
Set stop-loss and take-profit values.
Alternatively, use a webhook to connect to your trading platform for automated trading.
Important Notes
This script currently only supports 4-hour and daily charts!
This script relies on historical data for calculations and may not be suitable for all market conditions.
Trading carries risks, so please use this script cautiously for trading decisions.
User has to update the backtest period, or else the strategy might not be seen.
Demostration
Phase one, the orange line is about to turn up.
Phase two, the reversal point is located, and right after the next bar start an entry of gridbot.
Phase Three, the gridbot operates, once level touches, then a 0.2ATR trailing stop is applied on each step.
Phase four, when vwma rises, the grid window follows it by the rate of change of lookback price. If vwma does not move up, then the grid boundaries remain.
Phase five, either side when the current price breaks through the white limits, the gridbot stops. And the trading strategy is done for this round.
ATR SL Band (No-Repaint, Multi-Timeframe) + Risk per ContractThis indicator draws a non-repainting band for ATR-based Stoploss placement.
If used on Futures, it shows the distance + risk from the previous candle close, as well as from the current price.
The risk value is automatically calculated for the following symbols:
(Micro) ES (S&P 500)
(Micro) NQ (NASDAQ 100)
(Micro) YM (Dow Jones Industrial Average / US30)
The timeframe can be set individually. It is not recommended to use a lower timeframe than the chart timeframe as values differ from the actual timeframe's ATR SL in this case.
[blackcat] L2 Guppy Swing Trader for Stocks 1D█ OVERVIEW
The script is an indicator designed for use on daily charts (1D) to identify swing trading opportunities in stocks. It calculates a series of exponential moving averages (EMAs) based on a custom "winner ratio" and plots these moving averages to help traders identify potential crossovers and swing points.
█ LOGICAL FRAMEWORK
The script is structured into several main sections:
1 — Custom Functions: Defines functions for calculating the exponential moving average (EMA) and the "winner ratio."
2 — Main Calculation Function: calculate_and_plot_guppy_trader which computes the EMA series based on the winner ratio.
3 — Input Parameters: Allows users to select the price type and period for the calculations.
4 — Data Mapping: Maps the selected price type to the corresponding price series.
5 — Execution and Plotting: Calls the main calculation function, plots the resulting EMAs, and adds labels for crossover signals.
The logical flow starts with the user-defined inputs, then the price type is mapped to the appropriate price series. The custom functions are used to compute the necessary intermediate values, and the main calculation function generates the EMA series. Finally, the EMA series are plotted, and crossover signals are labeled.
█ CUSTOM FUNCTIONS
1 — xda(src, coeff): Calculates an exponential moving average (EMA) for a given source (src) and smoothing coefficient (coeff). It uses a recursive formula to compute the EMA.
2 — winner(price, res): Computes a "winner ratio" based on the price and a specified resolution (res). It fetches historical price data, calculates a win ratio based on price comparisons, and applies an EMA to the win ratio using the historical share outstanding and volume data.
█ KEY POINTS AND TECHNIQUES
• Exponential Moving Averages (EMA): The script uses multiple EMAs to smooth the "winner ratio" and identify trends.
• Winner Ratio Calculation: The "winner ratio" is a custom metric that adjusts based on historical price data and trading volume, providing a unique insight into price momentum.
• Security Function: Utilizes the security function to fetch historical data at different resolutions, which is crucial for calculating the winner ratio.
• Labeling Crossovers: The script uses label.new to visually indicate when the moving averages cross each other, aiding in identifying potential trade signals.
█ EXTENDED KNOWLEDGE AND APPLICATIONS
• Modifications: The script could be modified to include additional EMAs or adjust the winner ratio calculation to incorporate more factors such as volatility or RSI.
• NOTE: Similar techniques could NOT be applied to other timeframes or asset classes, such as forex or cryptocurrencies because they lack of financial data required in this indicator, by adjusting the input parameters and possibly the resolution used in the security function.
• Related Concepts: Understanding the security function in Pine Script is crucial for fetching historical data at different resolutions. Additionally, knowledge of EMA calculations and custom function design in Pine Script would be beneficial for enhancing this script.
Hybrid Adaptive Double Exponential Smoothing🙏🏻 This is HADES (Hybrid Adaptive Double Exponential Smoothing) : fully data-driven & adaptive exponential smoothing method, that gains all the necessary info directly from data in the most natural way and needs no subjective parameters & no optimizations. It gets applied to data itself -> to fit residuals & one-point forecast errors, all at O(1) algo complexity. I designed it for streaming high-frequency univariate time series data, such as medical sensor readings, orderbook data, tick charts, requests generated by a backend, etc.
The HADES method is:
fit & forecast = a + b * (1 / alpha + T - 1)
T = 0 provides in-sample fit for the current datum, and T + n provides forecast for n datapoints.
y = input time series
a = y, if no previous data exists
b = 0, if no previous data exists
otherwise:
a = alpha * y + (1 - alpha) * a
b = alpha * (a - a ) + (1 - alpha) * b
alpha = 1 / sqrt(len * 4)
len = min(ceil(exp(1 / sig)), available data)
sig = sqrt(Absolute net change in y / Sum of absolute changes in y)
For the start datapoint when both numerator and denominator are zeros, we define 0 / 0 = 1
...
The same set of operations gets applied to the data first, then to resulting fit absolute residuals to build prediction interval, and finally to absolute forecasting errors (from one-point ahead forecast) to build forecasting interval:
prediction interval = data fit +- resoduals fit * k
forecasting interval = data opf +- errors fit * k
where k = multiplier regulating intervals width, and opf = one-point forecasts calculated at each time t
...
How-to:
0) Apply to your data where it makes sense, eg. tick data;
1) Use power transform to compensate for multiplicative behavior in case it's there;
2) If you have complete data or only the data you need, like the full history of adjusted close prices: go to the next step; otherwise, guided by your goal & analysis, adjust the 'start index' setting so the calculations will start from this point;
3) Use prediction interval to detect significant deviations from the process core & make decisions according to your strategy;
4) Use one-point forecast for nowcasting;
5) Use forecasting intervals to ~ understand where the next datapoints will emerge, given the data-generating process will stay the same & lack structural breaks.
I advise k = 1 or 1.5 or 4 depending on your goal, but 1 is the most natural one.
...
Why exponential smoothing at all? Why the double one? Why adaptive? Why not Holt's method?
1) It's O(1) algo complexity & recursive nature allows it to be applied in an online fashion to high-frequency streaming data; otherwise, it makes more sense to use other methods;
2) Double exponential smoothing ensures we are taking trends into account; also, in order to model more complex time series patterns such as seasonality, we need detrended data, and this method can be used to do it;
3) The goal of adaptivity is to eliminate the window size question, in cases where it doesn't make sense to use cumulative moving typical value;
4) Holt's method creates a certain interaction between level and trend components, so its results lack symmetry and similarity with other non-recursive methods such as quantile regression or linear regression. Instead, I decided to base my work on the original double exponential smoothing method published by Rob Brown in 1956, here's the original source , it's really hard to find it online. This cool dude is considered the one who've dropped exponential smoothing to open access for the first time🤘🏻
R&D; log & explanations
If you wanna read this, you gotta know, you're taking a great responsability for this long journey, and it gonna be one hell of a trip hehe
Machine learning, apprentissage automatique, машинное обучение, digital signal processing, statistical learning, data mining, deep learning, etc., etc., etc.: all these are just artificial categories created by the local population of this wonderful world, but what really separates entities globally in the Universe is solution complexity / algorithmic complexity.
In order to get the game a lil better, it's gonna be useful to read the HTES script description first. Secondly, let me guide you through the whole R&D; process.
To discover (not to invent) the fundamental universal principle of what exponential smoothing really IS, it required the review of the whole concept, understanding that many things don't add up and don't make much sense in currently available mainstream info, and building it all from the beginning while avoiding these very basic logical & implementation flaws.
Given a complete time t, and yet, always growing time series population that can't be logically separated into subpopulations, the very first question is, 'What amount of data do we need to utilize at time t?'. Two answers: 1 and all. You can't really gain much info from 1 datum, so go for the second answer: we need the whole dataset.
So, given the sequential & incremental nature of time series, the very first and basic thing we can do on the whole dataset is to calculate a cumulative , such as cumulative moving mean or cumulative moving median.
Now we need to extend this logic to exponential smoothing, which doesn't use dataset length info directly, but all cool it can be done via a formula that quantifies the relationship between alpha (smoothing parameter) and length. The popular formulas used in mainstream are:
alpha = 1 / length
alpha = 2 / (length + 1)
The funny part starts when you realize that Cumulative Exponential Moving Averages with these 2 alpha formulas Exactly match Cumulative Moving Average and Cumulative (Linearly) Weighted Moving Average, and the same logic goes on:
alpha = 3 / (length + 1.5) , matches Cumulative Weighted Moving Average with quadratic weights, and
alpha = 4 / (length + 2) , matches Cumulative Weighted Moving Average with cubic weghts, and so on...
It all just cries in your shoulder that we need to discover another, native length->alpha formula that leverages the recursive nature of exponential smoothing, because otherwise, it doesn't make sense to use it at all, since the usual CMA and CMWA can be computed incrementally at O(1) algo complexity just as exponential smoothing.
From now on I will not mention 'cumulative' or 'linearly weighted / weighted' anymore, it's gonna be implied all the time unless stated otherwise.
What we can do is to approach the thing logically and model the response with a little help from synthetic data, a sine wave would suffice. Then we can think of relationships: Based on algo complexity from lower to higher, we have this sequence: exponential smoothing @ O(1) -> parametric statistics (mean) @ O(n) -> non-parametric statistics (50th percentile / median) @ O(n log n). Based on Initial response from slow to fast: mean -> median Based on convergence with the real expected value from slow to fast: mean (infinitely approaches it) -> median (gets it quite fast).
Based on these inputs, we need to discover such a length->alpha formula so the resulting fit will have the slowest initial response out of all 3, and have the slowest convergence with expected value out of all 3. In order to do it, we need to have some non-linear transformer in our formula (like a square root) and a couple of factors to modify the response the way we need. I ended up with this formula to meet all our requirements:
alpha = sqrt(1 / length * 2) / 2
which simplifies to:
alpha = 1 / sqrt(len * 8)
^^ as you can see on the screenshot; where the red line is median, the blue line is the mean, and the purple line is exponential smoothing with the formulas you've just seen, we've met all the requirements.
Now we just have to do the same procedure to discover the length->alpha formula but for double exponential smoothing, which models trends as well, not just level as in single exponential smoothing. For this comparison, we need to use linear regression and quantile regression instead of the mean and median.
Quantile regression requires a non-closed form solution to be solved that you can't really implement in Pine Script, but that's ok, so I made the tests using Python & sklearn:
paste.pics
^^ on this screenshot, you can see the same relationship as on the previous screenshot, but now between the responses of quantile regression & linear regression.
I followed the same logic as before for designing alpha for double exponential smoothing (also considered the initial overshoots, but that's a little detail), and ended up with this formula:
alpha = sqrt(1 / length) / 2
which simplifies to:
alpha = 1 / sqrt(len * 4)
Btw, given the pattern you see in the resulting formulas for single and double exponential smoothing, if you ever want to do triple (not Holt & Winters) exponential smoothing, you'll need len * 2 , and just len * 1 for quadruple exponential smoothing. I hope that based on this sequence, you see the hint that Maybe 4 rounds is enough.
Now since we've dealt with the length->alpha formula, we can deal with the adaptivity part.
Logically, it doesn't make sense to use a slower-than-O(1) method to generate input for an O(1) method, so it must be something universal and minimalistic: something that will help us measure consistency in our data, yet something far away from statistics and close enough to topology.
There's one perfect entity that can help us, this is fractal efficiency. The way I define fractal efficiency can be checked at the very beginning of the post, what matters is that I add a square root to the formula that is not typically added.
As explained in the description of my metric QSFS , one of the reasons for SQRT-transformed values of fractal efficiency applied in moving window mode is because they start to closely resemble normal distribution, yet with support of (0, 1). Data with this interesting property (normally distributed yet with finite support) can be modeled with the beta distribution.
Another reason is, in infinitely expanding window mode, fractal efficiency of every time series that exhibits randomness tends to infinitely approach zero, sqrt-transform kind of partially neutralizes this effect.
Yet another reason is, the square root might better reflect the dimensional inefficiency or degree of fractal complexity, since it could balance the influence of extreme deviations from the net paths.
And finally, fractals exhibit power-law scaling -> measures like length, area, or volume scale in a non-linear way. Adding a square root acknowledges this intrinsic property, while connecting our metric with the nature of fractals.
---
I suspect that, given analogies and connections with other topics in geometry, topology, fractals and most importantly positive test results of the metric, it might be that the sqrt transform is the fundamental part of fractal efficiency that should be applied by default.
Now the last part of the ballet is to convert our fractal efficiency to length value. The part about inverse proportionality is obvious: high fractal efficiency aka high consistency -> lower window size, to utilize only the last data that contain brand new information that seems to be highly reliable since we have consistency in the first place.
The non-obvious part is now we need to neutralize the side effect created by previous sqrt transform: our length values are too low, and exponentiation is the perfect candidate to fix it since translating fractal efficiency into window sizes requires something non-linear to reflect the fractal dynamics. More importantly, using exp() was the last piece that let the metric shine, any other transformations & formulas alike I've tried always had some weird results on certain data.
That exp() in the len formula was the last piece that made it all work both on synthetic and on real data.
^^ a standalone script calculating optimal dynamic window size
Omg, THAT took time to write. Comment and/or text me if you need
...
"Versace Pip-Boy, I'm a young gun coming up with no bankroll" 👻
∞