Evolving RThe "Evolving R" script is a script that allows to calculate a dynamic reward-to-risk ratio at any given point of time during the trade. Its fundamentals are based on Tom Dante's concept of an evolving reward-to-risk. The script requires a user to input their preferred stop loss price and the target price for a specific asset, and calculates the ratio between two differences: (a) the absolute difference between the target price and the current price and (b) the absolute difference between the stop loss price and the current price.
The output of the script displays the ratio discussed as a value called "Evolving R" in the table. In order to use it successfully, the user of the script has to input:
(a) Stop loss price for the asset
(b) Target price for the asset
Theoretically, as long as the evolving R value holds above or equal to 0.25, the trade is worth holding. However, if the evolving R value drops below 0.25, the table turns red and signifies that such a trade possesses more risk than there is a reward remaining: this alerts the user to possibly take profits prematurely without risking their unrealized gains for a minor amount of additional gain.
The graphics of the script are represented by green and red areas: the green area indicates the area between the current price and the target price, while the red area shows the distance between the current price and the stop loss price. This visual representation allows users to understand the relative reward-to-risk ratio graphically in addition to the given evolving R value output.
The script is used for any type of trading: whether trend-trading or in a ranging market, it doesn't suggest a user which market conditions they should use.
Statistics
FunctionDiscreteCosineTransformLibrary "FunctionDiscreteCosineTransform"
Discrete Cosine Transform (DCT)
The Discrete Cosine Transform (DCT) is a mathematical algorithm that converts a series of samples of a signal, typically in the time domain, into another domain called the frequency or spectral domain. It's commonly used for data compression and image/video coding applications such as JPEG and MPEG standards.
The DCT works by multiplying the input sequence with specific cosine functions that are pre-defined and then summing up these products to obtain a new series of values, which represent the frequency components of the original signal. The main advantage of the DCT over other transforms like Fourier Transform is its ability to handle non-stationary signals (i.e., signals with varying statistical properties) more effectively due to its localized basis functions.
In simple terms, the DCT can be thought of as a way to break down an image or video into different frequency components and then compress them without losing too much information. This compression technique is essential for efficient transmission and storage of digital media files over the internet or on devices with limited memory capacity.
~Mixtral4x7b
___
Reference:
lcamtuf.substack.com
dct(data, len)
Discrete Cosine Transform.
Parameters:
data (array) : Data source.
len (int) : Length of the sampling window.
Returns: List with frequency domain transformed information.
dct(data, len)
Discrete Cosine Transform.
Parameters:
data (float) : Data source.
len (int) : Length of the sampling window.
Returns: List with frequency domain transformed information.
idct(data, len)
Inverse Discrete Cosine Transform.
Parameters:
data (array) : Data source.
len (int) : Length of the sampling window.
Returns: List with time domain transformed information.
idct(data, len)
Inverse Discrete Cosine Transform.
Parameters:
data (float) : Data source.
len (int) : Length of the sampling window.
Returns: List with time domain transformed information.
Kalman Hull Supertrend [BackQuant]Kalman Hull Supertrend
At its core, this indicator uses a Kalman filter of price, put inside of a hull moving average function (replacing the weighted moving averages) and then using that as a price source for the supertrend instead of the normal hl2 (high+low/2).
Therefore, making it more adaptive to price and also sensitive to recent price action.
PLEASE Read the following, knowing what an indicator does at its core before adding it into a system is pivotal. The core concepts can allow you to include it in a logical and sound manner.
1. What is a Kalman Filter
The Kalman Filter is an algorithm renowned for its efficiency in estimating the states of a linear dynamic system amidst noisy data. It excels in real-time data processing, making it indispensable in fields requiring precise and adaptive filtering, such as aerospace, robotics, and financial market analysis. By leveraging its predictive capabilities, traders can significantly enhance their market analysis, particularly in estimating price movements more accurately.
If you would like this on its own, with a more in-depth description please see our Kalman Price Filter.
2. Hull Moving Average (HMA) and Its Core Calculation
The Hull Moving Average (HMA) improves on traditional moving averages by combining the Weighted Moving Average's (WMA) smoothness and reduced lag. Its core calculation involves taking the WMA of the data set and doubling it, then subtracting the WMA of the full period, followed by applying another WMA on the result over the square root of the period's length. This methodology yields a smoother and more responsive moving average, particularly useful for identifying market trends more rapidly.
3. Combining Kalman Filter with HMA
The innovative combination of the Kalman Filter with the Hull Moving Average (KHMA) offers a unique approach to smoothing price data. By applying the Kalman Filter to the price source before its incorporation into the HMA formula, we enhance the adaptiveness and responsiveness of the moving average. This adaptive smoothing method reduces noise more effectively and adjusts more swiftly to price changes, providing traders with clearer signals for market entries or exits.
The calculation is like so:
KHMA(_src, _length) =>
f_kalman(2 * f_kalman(_src, _length / 2) - f_kalman(_src, _length), math.round(math.sqrt(_length)))
4. Integration with Supertrend
Incorporating this adaptive price smoothing technique into the Supertrend indicator further enhances its efficiency. The Supertrend, known for its proficiency in identifying the prevailing market trend and providing clear buy or sell signals, becomes even more powerful with an adaptive price source. This integration allows the Supertrend to adjust more dynamically to market changes, offering traders more accurate and timely trading signals.
5. Application in a Trading System
In a trading system, the Kalman Hull Supertrend indicator can serve as a critical component for identifying market trends and generating signals for potential entry and exit points. Its adaptiveness and sensitivity to price changes make it particularly useful for traders looking to minimize lag in signal generation and improve the accuracy of their market trend analysis. Whether used as a standalone tool or in conjunction with other indicators, its dynamic nature can significantly enhance trading strategies.
6. Core Calculations and Benefits
The core of this indicator lies in its sophisticated filtering and averaging techniques, starting with the Kalman Filter's predictive adjustments, followed by the adaptive smoothing of the Hull Moving Average, and culminating in the trend-detecting capabilities of the Supertrend. This multi-layered approach not only reduces market noise but also adapts to market volatility more effectively. Benefits include improved signal accuracy, reduced lag, and the ability to discern trend changes more promptly, offering traders a competitive edge.
Thus following all of the key points here are some sample backtests on the 1D Chart
Disclaimer: Backtests are based off past results, and are not indicative of the future.
INDEX:BTCUSD
INDEX:ETHUSD
BINANCE:SOLUSD
QuarterCandlesChanges candle color when close is within the top 25% or bottom 25% of candle range (High - Low) on the last candle update.
Due to limitations of barcolor command, I'd suggest that you turn OFF the candle borders (chart settings--> right click on chart --> settings -->symbol and uncheck the border option) to ensure that the bar color is easily identifiable.
Smart Money Concept + Strategy Backtesting Toolkit [Shah]This indicator, primarily designed for strategy backtest. It’s important to emphasize that the orders generated by this indicator are in the form of stop-limit orders .
For Long setup , When lower lows and lower highs form, after price moving up from the last higher high, a “change of character” occurs. Entry will takes place in the golden zone.
This the Long setup:
And this is the Long setup Example on chart:
For Short setup , When higher lows and higher highs form after the price moves down from the last higher low, a “change of character” occurs. Entry will take place within the golden zone.
This the Short setup:
And this is the Short setup Example on chart:
Key Features:
Date Period:
Users can customize the date period during which the strategy is tested, allowing for a more granular analysis of performance over specific timeframes.
DCA Entry:
Entry is based on Fibonacci level between the Lower Low and Higher High pivots for Long deals .
Entry is based on Fibonacci level between the Higher High and Lower Low pivots for Short deals .
Allowing a second entry with a specified position size
Entering at a different price based on a Percent or ATR change.
There is a feature that If the risk-to-reward ratio is below the specified input (rr), the trading deal wont initiate, and the signal alert wont be triggered.
Stop Loss:
Adjustable based on Fibonacci levels , Percent and ATR.
The percent and ATR is calculate from LL pivot point for Long and HH pivot point for short (not Entry price)’
Targets:
Adjustable based on Source, Fibonacci levels , Percent and ATR.
Source indicates the maximum (minimum) value between the open and close of the candle where the Higher High (Lower Low) pivot point was formed for Long (Short) deals.
Percent and ATR calculates from Entry 1 Price
There is a feature that closes the part of the position size at Target 1 based on a percentage, leaving the rest to close at Target 2, entry, exit price, or stop loss.
Plots:
The visual representation of the indicator includes the key plots:
Reset Deal Calculation Fibonacci Level
Alert Fire Fibonacci Level
Entry 1
Entry 2
Entry Average
Stop Loss
Target 1
Target 2
Labels:
Displays informative labels upon trade open and close, providing details about each transaction like gain and equity and etc.
Risk Management:
Allows setting initial capital, risk per trade, and commission for each transaction.
Score Table:
Provides statistical information for Regular deals (refers to deals that closed in Target price or Stop loss price) and Exited deals (representing deals that didn’t touch the stop loss or targets.):
Number of trades
Win rate
Profit factor
Average Risk to Reward ratio
Total Profit and Loss (PnL)
Commission paid
Live equity
It should note that Winrate calculated based on closed deals at target or stop loss. (Exited trades doesn’t into account in calculation of Winrate)
Exit Methods :
The goal is to offer users a diverse set of exits before the price touches the target or stop loss.
1. Pending Entry Time-out
cancel pending entry based on candle counting since alert fired. (before deal started)
2. Break Even
If Target 2 is reached, the stop loss automatically adjusts to the entry price.
3. Active Deal Reverse
If a deal (long or short position) is currently open, and the reverse signal is emitted, the script will close the existing deal.
4. Reverse Deal Exit
If a deal (long or short position) is currently open, and the reverse signal is emitted, the script will automatically close the existing deal.
5. Move Exit
With this method, if Entry 2 is triggered, the deal will be closed when the price touches the Entry price.
6. Candle Counting Exit
This exit type is based on the number of candles since the deal started.
7. Profit Zone Shield Exit
Once a deal enters profit, the Exit level moves to the entry level after reaching a Fibonacci level between TP1 and Entry 1.
Deep Backtesting Table:
It includes:
Time period of the backtest
Pair name and timeframe
Count the long and short trades
Win streak and loss streak
Total deal chances and missed chances
Count the deals goes directly from entry 1 to tp1 and entry 2 to tp1
Count the deals that touched entry 2 and entry 2 filled percent
Count the number of each exit type
Other statistics such as CAGR, Sharpe, Kurtosis, Skewness, and Max Drawdown.
Spot Martingale KuCoin - The Quant ScienceINTRODUCTION
Backtesting software of the Spot Martingale algorithm offered by the KuCoin exchange.
This script replicates the logic used by the KuCoin bot and is useful for analyzing strategy on any cryptocurrency historical series.
It's not intended as an automatic trading algorithm and does not offer the possibility of automatic order execution.
The trader will use this software exclusively to research the best parameters with which to work on KuCoin.
LOGIC OF EXECUTION
The execution of orders is composed as follows:
1) Start Martingale: initial order
2) Martingale-Number: orders following Start Martingale
(A) The software is designed and developed to replicate trading without taking into account technical indicators or particular market conditions. The Initial Order (Start Martingale) will be executed immediately the close of the previous Martingale when the balance of market orders is zero. It will use the capital set in the Properties section for the initial order.
(B) After the first order, the software will open new orders as the price decreases. For orders following Start Martingale, the initial capital, multiplier, and number of orders in the exponential growth context are considered. The multiplier is the factor that determines the proportional increase in capital with each new order. The number of orders, indicates how many times the multiplier is applied to increase the investment.
Example
To find out the capital used in Martingale order number 5, with a Multiple For Position Increase equal to 2 and a starting capital of $100, the formula will be as follows:
Martingale Order = ($100 * (2 * 2 * 2 * 2 * 2)) = $100 * 32 = $3.200
(C) A multiplier is used for each new order that will increase the quantity purchased.
(D) All previously open orders are closed once the take profit is reached.
USER MANUAL
The user interface consists of two main sections:
1. Settings
Percentage Drop for Position Increase (0.1-15%) : percentage distance between Martingale orders. For example, if you set 5% each new order will be opened after a 5% price decrease from the previous one.
Max Position Increases (1-15) : number of Martingale orders to be executed after Start Martingale. For example, if you set 10, up to10 orders will be opened after Start Martingale.
Multiple For Position Increase (1-2x) : capital multiplier. For example, if you set 2 each for each new order, the capital involved will be doubled, order by order.
Take Profit Percentage (0.5-1000%) : percentage take profit, calculated on the average entry price.
2. Date Range Backtesting
The Date Range Backtesting section adjusts the analysis period. The user can easily adjust the UI parameters, and automatically the software will update the data.
LIMITATIONS OF THE MODEL
Although the Martingale model is widely used in position management, even this model has limitations and is subject to real risks during particular market conditions. Knowing these conditions will help you understand which asset is best to use the strategy on.
The main risks in adopting this automatic strategy are 2:
1) The price falls below our last order.
It happens during periods of strong bear-market in which the price collapses abruptly without experiencing any pullback. In this case the algorithm will enter a drawdown phase and the strategy will become a loser. The trader will then have to consider whether to wait for a price recovery or to incur a loss by manually closing the algorithm.
2) The price increases quickly.
It happens during periods of strong bull-market in which the price rises abruptly without experiencing any pullback. In this case the algorithm will not optimize order execution, working only with Start Martingale in the vast majority of trades. Given the exponential nature of the investment, the algorithm will in this case generate a profit that is always less than that of the reference market.
The best market conditions to use this strategy are characterized by high volatility such as correction phases during a bull run and/or markets that exhibit sideways price trends (such as areas of accumulation or congestion where price will generate many false signals).
FEATURES
This script was developed by including features to optimize the user experience.
Includes a dashboard at launch that allows the user to intuitively enter backtesting parameters.
Includes graphical indicator that helps the user analyze the behavior of the strategy.
Includes a date period backtesting feature that allows the user to adjust and choose custom historical periods.
DISCLAIMER
This script was released using parameters researched solely for the BTC/USDT pair, 4H timeframe, traded on the KuCoin Exchange (2017-present). Do not consider this combination of parameters as universal and usable on all assets and timeframes.
Trade-o-Scope: Plot Custom DataTrade-o-Scope team presents the "Plot Custom Data" indicator.
"Plot Custom Data" is designed to help you bring the custom timeseries data and plot it on the chart.
Motivation:
In the fast-evolving landscape of markets, traders often find themselves analyzing a plethora of data sources, specialized market information, various metrics, etc. While TradingView offers a rich catalog of instruments and market data, there are cases where traders rely on unique data sources, custom calculations, bespoke metrics, or refined analytics that demand visualization.
In some cases, traditional visualization approaches for custom data like plotting in Excel or other platforms may suffice for some. still, we really adore all the great features TradingView supercharts have - native scaling and scrolling, drawing, combining data, applying indicators and strategies on top of any series, etc. The ability to play with custom data on TradingView charts is just a whole new level compared to any alternatives.
With this indicator, we aim to empower traders to effortlessly bring their custom data to the familiar and friendly interface of the TradingView chart.
Basic Features:
Easy Data Input : Simply paste your numerical timeseries data, whether it's a column from Excel, Google Sheets, CSV file, or multiline text from any text editor.
Flexible Configuration : Define the order of values, starting date, and timeframe to match the specifications of your data.
Custom appearance : Personalize your chart by assigning a title to your data and selecting colors for the plot.
Advanced Features:
Value Multiplier : Set a multiplier for the provided values to adjust their scale as needed.
Formatting Options : Customize the display format of values on the chart, whether as price, percentage, or volume.
Conditional Coloring : Define conditions for changing the plot color based on a specific threshold.
Plot Style Selection : Choose from various plot styles such as line, histogram, area, columns, and more, to best visualize your data.
Additional Visual References : Enhance data analysis by activating fixed horizontal lines to aid in visual interpretation.
Leverage TradingView Capabilities : Seamlessly apply various indicators from the TradingView catalog, such as Bollinger Bands or RSI, onto your custom data chart for comprehensive analysis.
Chart Example:
On the chart above, you can observe several "Plot Custom Data" indicators added to demonstrate what your custom data can look like and how multiple indicators can be combined, as well as the indicator configuration screen.
How it works:
The "Plot Custom Data" indicator processes the list of values provided on the configuration form and converts it into data points to be plotted on the chart. To determine the timing of plotting each value, the indicator uses the configured 'starting date' and 'timeframe'. This means the indicator will always plot each subsequent value from your list at the distance of one timeframe from the previous one.
Limitations and Best Practices:
1) The way timeseries data is inputted on the "Plot Custom Data" indicator configuration page, leverages a standard input text field. This input type has a limited character capacity, approximately 4000-4400 symbols. Therefore, the timeseries data cannot exceed this limit.
Let's illustrate this with an example.
Suppose you have a column in Excel that you wish to plot using the indicator. Consider the first 5 rows of values in your column:
| -123.45
| -43.5
| 3.12
| 9.6
| 146.78
To calculate the total symbols used, we need to account for the minus sign, numbers, decimal point, and two invisible symbols at the end of each line, which helps structure the text into multiple lines. So, in total, these 5 rows will use:
row_1 + row_2 + row_3 + row_4 + row_5 = 9 + 7 + 6 + 5 + 8 = 35 symbols or 7 symbols per row on avarage.
If we assume the remaining data follows a similar format, we can estimate the number of rows that can be inputted on the indicator configuration page:
from ~4000 / 7 = 571 rows
to ~4400 / 7 = 628 rows
The right approach to overcome this limitation is to reduce the number of symbols representing each value as much as possible. In our example, consider dropping all decimals, which would lead to an average of 5.4 symbols per row and allow for up to ~800 rows to be accepted by the input field.
If your data primarily consists of large values such as thousands or millions, consider dividing it by a multiplier like x1000 and activating the same multiplier in the indicator settings.
For example, instead of storing values like 5,620,000 in your list, store the value 562 and activate an x10,000 multiplier in the configuration to display the original value on the chart.
It is also possible to combine multiple indicators on one chart and split a larger list of values between them. If you need to display significantly more custom data on charts, you may contact us in DM to find\develop a proper solution.
2) Another important consideration is to ensure that all your data aligns with the selected timeframe in the indicator configuration.
Remember, you provide only the values to the indicator without corresponding dates. Dates are calculated automatically by the indicator based on the configured starting date and chosen timeframe. This means the indicator will always plot each subsequent value from your list at the distance of one timeframe from the previous one.
Here's an example:
Suppose you have a timeseries with 'date' and 'value' columns and a timeframe of 30 minutes:
# | date | value
--|---------------------------|---------
1 | 2024-01-01 11:30:00 | -241.45
2 | 2024-01-01 12:02:13 | -11.56
3 | 2024-01-01 13:00:00 | 21.87
..
..
6 | 2024-01-01 14:30:00 | 19.6
7 | 2024-01-01 15:00:00 |
8 | 2024-01-01 15:30:00 | 46.78
Rows 1-3 represent bad practice:
Row 2 is not precisely aligned with the timeframe, as it has a time of 12:02:13 instead of the expected 12:00:00. This won't cause errors, but the plot will show this value at 12:00:00.
Row 3 has a 1-hour difference from Row 2, which poses a real problem. As the indicator doesn't know the actual dates, it expects Row 3 to be 30 minutes later than Row 2, so it will plot 21.87 at 12:30:00 instead of the actual 13:00:00. And the rest of the values from your list will have offset on the chart as well.
Rows 6-7 represent the correct approach to overcome gaps in your data:
If, for some reason, there is no value for 15:00:00 in the original dataset, adding an empty Row 7 ensures each subsequent row is located 30 minutes from the previous one. The indicator will treat the empty row correctly, not plotting anything at this date on the chart, but will plot a line connecting the value of 19.6 from Row 6 with the value of 46.78 from Row 8.
How to use:
1) Add the "Plot Custom Data" indicator to the chart.
Voila! You'll see the plot based on the default timeseries values list and settings.
2) Paste your numerical timeseries data.
Define the order of values, starting date, and timeframe.
Assign a title to your data and select colors for the plot.
Voila! You'll see the plot based on your timeseries values list and settings.
3) Customize the indicator's settings:
Set a values multiplier if needed.
Specify the appropriate format for the values (price, percentage, or volume).
Choose whether to change the plot color based on conditions.
Select the plot style.
Add horizontal lines.
4) Explore your data, apply additional indicators and strategies from the TradingView catalog, or develop your own scripts using Pine.
TradeDots - Buy Sell SignalsThe TradeDots Buy Sell Indicator is a sophisticated multi-strategy analytics tool designed to discern market direction and identify potential trading opportunities.
The TradeDots indicator utilizes a trend-following strategy that initially identifies the long-term market trend, whether bullish or bearish, at a macro level. It then zooms in on pullback and reversal price action patterns within this broader trend. These patterns are confirmed by a micro-level candlestick analysis, which leads to the issuance of a "buy" alert. This process ensures both macro and micro elements of the market are considered before entering a trade.
How Does It Work?
In more detail, the procedure begins at the macro level where the advanced indicator applies an Exponential Moving Average (EMA) within the current timeframe. This EMA is then cross-verified with another EMA of the same length from a higher timeframe, ensuring a reliable assessment of long-term market trends. This approach helps establish whether the market situation favors long or short positions.
Following this, a complex mathematical model uses a designated window of candlesticks to calculate price action changes, storing all significant reversal patterns for subsequent comparison. The algorithm then identifies similar repeated reversal patterns in the chart, pinpointing potential market turning points.
For precision and reliability, the confirmation of these reversal patterns involves further refinement and filtering at a micro level. By calculating market momentum in tandem with an exhaustive analysis, e.g. Average True Value (ATR), candlestick body and wick data, the algorithm can affirm the reversal. Finally, the buy or sell signals are plotted on the chart in real-time.
The indicator includes 4 distinct entry strategies for both "Long" and "Short" orders. Each strategy represents different levels of rigorousness in their analysis rules. For instance, a "Weak Buy" signal represents a lighter pullback strength compared to a "Strong Buy" signal, with "Reversal Buy" exhibiting the robust pullback strength based on the change in price action value.
Each type of order comes with its minimum threshold and conditions for profit-taking to prevent excessive trading activity that could lead to high commission costs. Once these conditions are met and coupled with a reversal signal — generated with the same concepts as mentioned earlier but in the opposite direction — a sell signal is then triggered in real time. It's a systematic process that ensures an optimal balance between timely entries and exits in the market.
Generating Trading Ideas Catering To Traders Of All Kinds
TradeDots Buy Sell Indicator includes multiple strategies and many features:
4+ Types of Trading Alerts: Strong, Weak, Reversal, and Breakout for different market conditions (Should not be followed blindly).
2+ Trading Styles: Buy and Hold, Swing Trading (Should not be followed blindly).
Facilitates both "Long" and "Short" trades.
+ more. (Check the changelog below for current features)
HOW TO USE
⭐️ TRADING STRATEGY
Buy and Hold: An approach suitable for long-term investments or as an alternative to a dollar-cost averaging strategy by identifying only the undervalued positions in markets with long-term growth potential like stocks and indices.
Note: This strategy does not provide an exit strategy.
Swing Trading: This method targets buying low and selling high, adapted for traders looking to make the most of short to mid-term market volatility.
⭐️ ORDER DIRECTION
Order direction is for “Swing trading” strategy and other strategies that comes with an exit strategy. It is to choose the direction of the market that you wish to place your order on.
Long: Primarily targeting markets that exhibit a left-skewed trend (more often it rises than falls), this strategy focuses on "long" trading opportunities, avoiding "short" market actions.
Short: Apt for markets displaying a right-skewed trend (more often it falls than rises), this approach targets "short" opportunities exclusively, refraining from "long" market actions.
Long and Short: This comprehensive strategy identifies trading opportunities for both "long" and "short" market actions, facilitating increased opportunities for volatile assets.
⭐️ ALERT TYPES
Strong: These alerts designate high risk/reward return opportunities with a reasonable win rate. They tend to appear near previous support pivots where a Change in Character (CoCh) may often occur, typically coupled with a tight stop-loss strategy.
Weak: Indicative of opportunities balancing risk/reward return and win-rate, these alerts often appear during strong momentum markets.
Reversal: These signals identify potential reversals by highlighting extreme oversold or overbought states, thus revealing markets that are underpriced or overpriced for swift trading actions.
Breakout: They are to identify a change in trend and market breakout by gaps created post earnings or significant economic events, purposed for "Buy high, sell higher" strategies.
⭐️ STOP LOSS
The stop-loss feature offers customization options, enabling users to close a position upon reaching a predefined percentage drawdown. As volatility varies across different timeframes and markets, tuning this feature in accordance with the market allows optimal usage of this indicator.
CONCLUSION
While technical indicators are certainly vital in trading analysis, they are just one part of the equation. The individual trader's style and mindset significantly influence their trading outcomes, making them equally crucial in the process. Therefore, relying solely on indicators for a successful trading outcome may not be the most effective strategy.
Understanding and leveraging these indicators requires substantial time and significant effort from traders. They need to deeply engage with these tools to truly grasp their behavior and functionality. Taking this into consideration, our aim is to create highly advanced, customizable, and user-friendly technical indicators. This tool is designed to illuminate the fundamental role that technical indicators play as a supportive decision-making apparatus, aiding traders to more swiftly embark on their journey towards successful trading.
See Author's instructions below to get instant access to this indicator.
RISK DISCLAIMER
Trading entails substantial risk, and most day traders incur losses. All content, tools, scripts, articles, and education provided by TradeDots serve purely informational and educational purposes. Past performances are not definitive predictors of future results.
Trade-o-Scope: Multi-Asset Price TrackerTrade-o-Scope team presents the "Multi-Asset Price Tracker" indicator.
"Multi-Asset Price Tracker" is designed to help analyze price changes across multiple assets within time intervals you define.
Motivation:
Most screeners on the market track price changes over predefined periods, like 1H\4H\12H\1D\3D\7D\etc. Typically, they compare initial and current prices.
But what if you want to analyze assets' performance over arbitrary historical intervals?
Perhaps you want to spot which assets dropped most within 7 hours after a specific industry announcement? Or do you want to check which asset grew the most in January last year?
This is where the "Multi-Asset Price Tracker" shines. It lets you define arbitrary intervals and track price changes for selected assets.
Overview and functionality:
Define arbitrary time intervals in history for analyzing price changes.
Create up to 10 lists, each with up to 40 symbols to track. Populate lists with data from text files, Excel, or CSV. Lists are just multiline text strings, each line representing an individual symbol.
Switch between lists, with one active list at a time.
Specify up to 3 fixed symbols for additional analysis alongside active list symbols. You may use them as reference points to compare price changes of the symbols in the List.
Customize table appearance and position.
Set sorting criteria and direction for displayed values.
View the results in a table on the chart.
How it works:
"Multi-Asset Price Tracker" will track the symbol's price during the interval you define.
The indicator identifies each symbol's Start, Max, Min, and End prices during the interval. It then calculates relative changes: Start-to-Max, Start-to-Min, and Start-to-End.
The list of relative changes is ordered by the column chosen in settings and displayed on the chart.
List example (up to 10 Lists):
BINANCE:WLDUSDT.P
BINANCE:WOOUSDT.P
BINANCE:XEMUSDT.P
...
...
(up to 40 symbols per List)
Calculation example:
Symbol Start-price = $100
Symbol Max-price = $150
Symbol Min-price = $75
Symbol End-price = $110
Start-to-Max = 100% * (Max-price - Start-price) / Start-price = 100% * ($150 - $100) / $100 = 50%
Start-to-Min = 100% * (Min-price - Start-price) / Start-price = 100% * ($75 - $100) / $100 = -25%
Start-to-End = 100% * (End-price - Start-price) / Start-price = 100% * ($110 - $100) / $100 = 10%
Chart example:
In the provided chart, you can observe an example with a table generated by the indicator, along with manually added arrows and labels explaining the calculation process for an individual symbol from the list.
How to use:
1) Add "Multi-Asset Price Tracker" indicator to the chart
2) The indicator will ask you to define the start and the end of the interval using the mouse on the chart.
Voila! You'll see the table with sorted relative price changes based on default list values and settings.
3) Customize the indicator's settings:
Define the interval Start and End datetime.
Optionally, change the interval Start and End by clicking on the indicator name and dragging the vertical mark at the edges of the interval to a new position.
Define the Start and End price sources.
Choose a color to highlight the interval on the chart's background.
Set the table position, size, text size, and border size.
Specify the column for sorting and its direction.
Choose whether to sort chart symbols and fixed symbols together with list symbols or display them at the top of the table irrespective of their relative price change.
Enable fixed symbols if needed, and define up to 3 fixed symbols.
Define symbol lists, with up to 10 lists and 40 symbols each.
Select which List to make active - symbols from the active list will be calculated and displayed.
Inflation CorrelationHeyo fellas,
In today’s dynamic economic landscape, understanding the relationship of market prices to other economical factors like inflation rate is crucial. The Inflation Correlation Indicator is designed to provide traders with a clear visualization of this relationship. By correlating average inflation rates from selected countries with market closing prices, this indicator offers a unique perspective on potential market movements influenced by inflationary trends.
Features:
Country Selection: Choose from the European Union (EU), Germany (DE), or the United States (US) to tailor the correlation analysis to your specific market interest.
Correlation Length Customization: Adjust the correlation length to refine the sensitivity of the indicator to recent inflation data.
Visual Clarity: The correlation histogram changes color based on the direction of the correlation, providing an intuitive understanding of the inflation correlation.
Whether you’re a fundamental analyst seeking to incorporate macroeconomic indicators into your strategy or a trader looking for an edge in inflation-sensitive markets, the Inflation Correlation Indicator is an indispensable tool in your TradingView arsenal.
Thanks for checking this out!
Best regards,
simwai
LSMA Z-Score [BackQuant]LSMA Z-Score
Main Features and Use in the Trading Strategy
- The indicator normalizes the LSMA into a detrended Z-Score, creating an oscillator with standard deviation levels to indicate trend strength.
- Adaptive coloring highlights the rate of change and potential reversals, with different colors for positive and negative changes above and below the midline.
- Extreme levels with adaptive coloring indicate the probability of a reversion, providing strategic entry or exit points.
- Alert conditions for crossing the midline or significant shifts in trend direction enhance its utility within a trading strategy.
1. What is an LSMA?
The Least Squares Moving Average (LSMA) is a technical indicator that smoothens price data to help identify trends. It uses the least squares regression method to fit a straight line through the selected price points over a specified period. This approach minimizes the sum of the squares of the distances between the line and the price points, providing a more statistically grounded moving average that can adapt more smoothly to price changes.
2. What is a Z-Score?
A Z-Score is a statistical measurement that describes a value's relationship to the mean of a group of values, measured in terms of standard deviations from the mean. If a Z-Score is 0, it indicates that the data point's score is identical to the mean score. A Z-Score helps in understanding if a data point is typical for a given data set or if it is atypical. In finance, a Z-Score is often used to measure how far a piece of data is from the average of a set, which can be helpful in identifying outliers or unusual data points.
3. Why Turning LSMA into a Z-Score is Innovative and Its Benefits
Converting LSMA into a Z-Score is innovative because it combines the trend identification capabilities of the LSMA with the statistical significance testing of Z-Scores. This transformation normalizes the LSMA, creating a detrended oscillator that oscillates around a mean (zero line), with standard deviation levels to show trend strength. This method offers several benefits:
Enhanced Trend Detection:
- By normalizing the LSMA, traders can more easily identify when the price is deviating significantly from its trend, which can signal potential trading opportunities.
Standardization:
- The Z-Score transformation allows for comparisons across different assets or time frames, as the score is standardized.
Objective Measurement of Trend Strength:
- The use of standard deviation levels provides an objective measure of trend strength and volatility.
4. How It Can Be Used in the Context of a Trading System
This indicator can serve as a versatile tool within a trading system for a range of things:
Trend Confirmation:
- A positive Z-Score can confirm an uptrend, while a negative Z-Score can confirm a downtrend, providing traders with signals to enter or exit trades.
Oversold/Overbought Conditions:
- Extreme Z-Score levels can indicate overbought or oversold conditions, suggesting potential reversals or pullbacks.
Volatility Assessment:
- The standard deviation levels can help traders assess market volatility, with wider bands indicating higher volatility.
5. How It Can Be Used for Trend Following
For trend following strategies, this indicator can be particularly useful:
Trend Strength Indicator:
- By monitoring the Z-Score's distance from zero, traders can gauge the strength of the current trend, with larger absolute values indicating stronger trends.
Directional Bias:
- Positive Z-Scores can be used to establish a bullish bias, while negative Z-Scores can establish a bearish bias, guiding trend following entries and exits.
Color-Coding for Trend Changes :
- The adaptive coloring of the indicator based on the rate of change and extreme levels provides visual cues for potential trend reversals or continuations.
Thus following all of the key points here are some sample backtests on the 1D Chart
Disclaimer: Backtests are based off past results, and are not indicative of the future.
This is using the Midline Crossover:
INDEX:BTCUSD
INDEX:ETHUSD
BINANCE:SOLUSD
Fractional Differentiation█ Description
This Pine Script indicator implements fractional differentiation, a mathematical operation that extends the concept of differentiation to non-integer orders. Fractional differentiation is particularly significant in financial analysis, as it enables analysts to uncover underlying patterns in price series that are not evident with traditional integer-order differentiation. The motivation behind fractional differencing lies in its ability to balance the trade-off between retaining data/feature memory and ensuring stationarity.
█ Significance
Fractional differentiation offers a nuanced view of market data, allowing for the adjustment of the differentiation order to balance between signal clarity and noise reduction. This is especially useful in financial markets, where the choice of differentiation order can highlight long-term trends or short-term price movements without completely smoothing out the valuable market noise.
█ Approximations Used
The implementation relies on the Gamma function for the computation of coefficients in the fractional differentiation formula. Given the complexity of the Gamma function, this script uses an approximation method based on the Lanczos approximation for the logarithm of the Gamma function, as detailed in "An Analysis Of The Lanczos Gamma Approximation" by Glendon Ralph Pugh (2004). This approximation strikes a balance between computational efficiency and accuracy, making it suitable for real-time market analysis in Pine Script.
█ Limitations
While this script opens new avenues for market analysis, it comes with inherent limitations:
- The approximation of the Gamma function, although accurate, is not exact. The precision of the fractional differentiation result may vary slightly, especially for higher-order differentiations.
- The script's performance is subject to Pine Script's execution environment, with a default loop limit set to 100 iterations for practicality. Users might need to adjust this limit based on their specific use case, balancing between computational load and the desired depth of historical data analysis.
█ Credits
This script makes use of the `MathSpecialFunctionsGamma` library, authored by Ricardo Santos . This library provides essential mathematical functions, including an approximation of the Gamma function, which is crucial for the fractional differentiation calculation.
I also extend my sincere gratitude to
Dr. Marcos López de Prado for his seminal work, Advances in Financial Machine Learning (2018). Dr. López de Prado's insights have significantly influenced our approach to developing sophisticated analytical tools.
Dr. Ernie Chan for his freely and generously sharing valuable insights via discourse on quantitative trading strategies through his talks and publications.
Z Score & Trend FollowingIntroduction:
The Z Score & Trend Following indicator is a tool used in financial markets to assess the standard deviation of a data point from its mean value over a specified period. It calculates the Z score, which is a measure of how many standard deviations an element is from the mean. This indicator also incorporates trend-following characteristics, allowing traders to visualize trends based on the Z score.
Indicator Parameters:
Standard Deviation Length: Determines the length of the standard deviation calculation.
Average Length: Specifies the length of the moving average used for the mean calculation.
Calculation Type: Allows users to choose between different types of moving averages (SMA, EMA, WMA, VMA, TMA).
Standard Deviations: Sets the number of standard deviations to be used for trend analysis.
Bar Color: Option to enable or disable bar coloring based on trend conditions.
Calculations:
Z Score Calculation: The Z score is calculated as the difference between the source data point and the moving average divided by the standard deviation.
zscore = (src - (getMA(src, length))) / ta.stdev(src, slength)
Plots:
Z Score Plot: Plots the Z score values, typically in green.
Inverted Z Score Plot: Plots the inverted Z score values (multiplied by -1), typically in red.
Lines:
Zero Line: A horizontal dotted line indicating zero.
Upper Threshold Line: A dotted line representing the upper threshold defined by the number of standard deviations.
Lower Threshold Line: A dotted line representing the lower threshold defined by the negative number of standard deviations.
Bar Color:
The bar color changes based on the Z score values and the predefined standard deviation thresholds. Green bars indicate values above the upper threshold, red bars indicate values below the lower threshold, lime bars indicate positive Z scores, and maroon bars indicate negative Z scores. Neutral values are represented by black bars.
Conclusion:
The Z Score & Trend Following indicator combines the statistical concept of Z score with trend-following characteristics to provide traders with insights into market trends and potential reversal points. By visualizing Z scores alongside trend analysis, traders can make more informed decisions regarding market entry and exit points.
AWR - Chris - V3Calculates the AWR based on Dr. Coles formula. Takes the last 12 weeks (not including the current one) highs and lows, adds them and then divides by twelve, give the average weekly range. Then takes the AWR and show the playing field based on the high and low of the current weekly candle. Must be used on the weekly chart to get the data needed then manually plot your lines on the required charts.
Bitcoin Regression Price BoundariesTLDR
DCA into BTC at or below the blue line. DCA out of BTC when price approaches the red line. There's a setting to toggle the future extrapolation off/on.
INTRODUCTION
Regression analysis is a fundamental and powerful data science tool, when applied CORRECTLY . All Bitcoin regressions I've seen (Rainbow Log, Stock-to-flow, and non-linear models), have glaring flaws ... Namely, that they have huge drift from one cycle to the next.
Presented here, is a canonical application of this statistical tool. "Canonical" meaning that any trained analyst applying the established methodology, would arrive at the same result. We model 3 lines:
Upper price boundary (red) - Predicted the April 2021 top to within 1%
Lower price boundary (green)- Predicted the Dec 2022 bottom within 10%
Non-bubble best fit line (blue) - Last update was performed on Feb 28 2024.
NOTE: The red/green lines were calculated using solely data from BEFORE 2021.
"I'M INTRUIGED, BUT WHAT EXACTLY IS REGRESSION ANALYSIS?"
Quite simply, it attempts to draw a best-fit line over some set of data. As you can imagine, there are endless forms of equations that we might try. So we need objective means of determining which equations are better than others. This is where statistical rigor is crucial.
We check p-values to ensure that a proposed model is better than chance. When comparing two different equations, we check R-squared and Residual Standard Error, to determine which equation is modeling the data better. We check residuals to ensure the equation is sufficiently complex to model all the available signal. We check adjusted R-squared to ensure the equation is not *overly* complex and merely modeling random noise.
While most people probably won't entirely understand the above paragraph, there's enough key terminology in for the intellectually curious to research.
DIVING DEEPER INTO THE 3 REGRESSION LINES ABOVE
WARNING! THIS IS TECHNICAL, AND VERY ABBREVIATED
We prefer a linear regression, as the statistical checks it allows are convenient and powerful. However, the BTCUSD dataset is decidedly non-linear. Thus, we must log transform both the x-axis and y-axis. At the end of this process, we'll use e^ to transform back to natural scale.
Plotting the log transformed data reveals a crucial visual insight. The best fit line for the blowoff tops is different than for the lower price boundary. This is why other models have failed. They attempt to model ALL the data with just one equation. This causes drift in both the upper and lower boundaries. Here we calculate these boundaries as separate equations.
Upper Boundary (in red) = e^(3.24*ln(x)-15.8)
Lower Boundary (green) = e^(0.602*ln^2(x) - 4.78*ln(x) + 7.17)
Non-Bubble best fit (blue) = e^(0.633*ln^2(x) - 5.09*ln(x) +8.12)
* (x) = The number of days since July 18 2010
Anyone familiar with Bitcoin, knows it goes in cycles where price goes stratospheric, typically measured in months; and then a lengthy cool-off period measured in years. The non-bubble best fit line methodically removes the extreme upward deviations until the residuals have the closest statistical semblance to normal data (bell curve shaped data).
Whereas the upper/lower boundary only gets re-calculated in hindsight (well after a blowoff or capitulation occur), the Non-Bubble line changes ever so slightly with each new datapoint. The last update to this line was made on Feb 28, 2024.
ENOUGH NERD TALK! HOW CAN I APPLY THIS?
In the simplest terms, anything below the blue line is a statistical buying opportunity. The closer you approach the green line (the lower boundary) the more statistically strong that opportunity is. As price approaches the red line, is a growing statistical likelyhood/danger of an imminent blowoff top.
So a wise trader would DCA (dollar cost average) into Bitcoin below the blue line; and would DCA out of Bitcoin as it approaches the red line. Historically, you may or may not have a large time-window during points of maximum opportunity. So be vigilant! Anything within 10-20% of the boundary should be regarded as extreme opportunity.
Note: You can toggle the future extrapolation of these lines in the settings (default on).
CLOSING REMARKS
Keep in mind this is a pure statistical analysis. It's likely that this model is probing a complex, real economic process underlying the Bitcoin price. Statistical models like this are most accurate during steady state conditions, where the prevailing fundamentals are stable. (The astute observer will note, that the regression boundaries held despite the economic disruption of 2020).
Thus, it cannot be understated: Should some drastic fundamental change occur in the underlying economic landscape of cryptocurrency, Bitcoin itself, or the broader economy, this model could drastically deviate, and become significantly less accurate.
Furthermore, the upper/lower boundaries cross in the year 2037. THIS MODEL WILL EVENTUALLY BREAK DOWN. But for now, given that Bitcoin price moves on the order of 2000% from bottom to top, it's truly remarkable that, using SOLELY pre-2021 data, this model was able to nail the top/bottom within 10%.
NSE Option Straddle Candle Chart
'NSE Option Straddle Candle Chart' plot a straddle chart of the mentioned strike.
Straddle means combine price of a call price and a put price.
User has 4 inputs :
1 : Spot Symbol
2 : Expiry date
3 : Straddle Strikes
4 : Ema Length
5 : Supertrend Inputs
How to use :
1 : Trade need to know first what is a straddle. If ATM straddle price is 405, than it means market is likely to close within 405 points up or down at the expiry.
2 : Straddle is traded on pairs only
3 : If trader sells a straddle than , straddle price should move down. For there reference supertrend and moving average is plotted on chart
4 : Both this indicators helps trade to identify the trend , hence predict market.
5 : Options are dying assite , so is straddle , so prefer selling straddle instead of buying.
Prepare Targets, Stop Loss, Position Size and calculate PnL You are watching the price action of your favorite coin. Then the price changes quickly and you know you could start a good trade now.
But how much should you buy, where should you set your Target for Profit Taking and your Stop Loss? How much money do you want to risk, how much money would you win if the trade is succesfull?
This indicator helps you to set up your trade in a quick way, no need to do some calculations by hand.
How does it work?
Just enter the prices where you want to take Profit and where your Stopp Loss should be.
Enter the number of coins and wether you buy or sell/go long or short.
These targets are then shown in the chart, move them around to see if your stopp loss is positioned well. See directly what your profit or loss would be.
See some Screenshots with more explanations for what is possible and how to set up everything.
General Overview:
How to set up the Trade:
Formatting and Extras:
Let me know if you like it!
Price Scenarios - The Quant ScienceGENERAL OVERVIEW
Price Scenarios - The Quant Science is a quantitative statistical indicator that provides a forecast probability about future prices moving using the mathematical-statistical formula of statistical probability and expected value.
HOW TO USE
The indicator displays arrow-shaped signals that represent the probable future price movement calculated by the indicator, including the current percentage probability. Additionally, the candlesticks are colored based on the predicted direction to facilitate visual analysis. By default, green is used for bullish movements and red for bearish movements. The trader can set the analysis period (default value is 200) and the percentage threshold of probability to consider (default value is greater than 0.50 or 50%) through the user interface.
USER INTERFACE
Lenght analysis: with this features you can handle the length of the dataset to be used for estimating statistical probabilities.
Expected value: with this feature you can handle the threshold of the expected value to filter, only probabilities greater than this threshold will be considered by the model. By default, it is set to 0.50, which is equivalent to 50%.
Design Settings: modify the colors of your indicator with just a few clicks by managing this function.
We recommend disabling 'Wick' and 'Border' from the settings panel for a smoother and more efficient user experience.
NSE Option Chain
This Indicator show Options Data on signal dashboard , that help trader to analyse the market.
Options data consist of two things , Call and Put.
Every Strike has its Call and Put price.
So if user Opens any chart which is traded in options , dashboard will show total 16 Call and 16 Put strikes
8 Above from ATM and 8 Below from ATM.
On left hand side of dashboard there is Call data and on right side there is Put data.
Call side datas are , Call LTP which is latest price of that call strike , Call Chg which is change in points from previous day close and third is Call % which is % change from previous day close.
Same is on put side.
Color code is done based on positive or negative of data. If change or % is negative then color is red else green.
ATM strike data is plotted in bold
Inputs :
Spot Symbol Input for Option dashboard
Expiry date of that option contract
Strike interval between 2 strikes
Reference ATM strike ( user should keep this input as current ATM strike )
How to Use :
If dashboard shows call side is negative and put side is positive then that means market Bearish , because falling market leads to falling price of call and increase in price of Put.
Similarly if put is negative and call is positive then market is bullish.
This dashboard give trend conformation , trader should take other conformation also before taking trade.
Statistics • Chi Square • P-value • SignificanceThe Statistics • Chi Square • P-value • Significance publication aims to provide a tool for combining different conditions and checking whether the outcome is significant using the Chi-Square Test and P-value.
🔶 USAGE
The basic principle is to compare two or more groups and check the results of a query test, such as asking men and women whether they want to see a romantic or non-romantic movie.
–––––––––––––––––––––––––––––––––––––––––––––
| | ROMANTIC | NON-ROMANTIC | ⬅︎ MOVIE |
–––––––––––––––––––––––––––––––––––––––––––––
| MEN | 2 | 8 | 10 |
–––––––––––––––––––––––––––––––––––––––––––––
| WOMEN | 7 | 3 | 10 |
–––––––––––––––––––––––––––––––––––––––––––––
|⬆︎ SEX | 10 | 10 | 20 |
–––––––––––––––––––––––––––––––––––––––––––––
We calculate the Chi-Square Formula, which is:
Χ² = Σ ( (Observed Value − Expected Value)² / Expected Value )
In this publication, this is:
chiSquare = 0.
for i = 0 to rows -1
for j = 0 to colums -1
observedValue = aBin.get(i).aFloat.get(j)
expectedValue = math.max(1e-12, aBin.get(i).aFloat.get(colums) * aBin.get(rows).aFloat.get(j) / sumT) //Division by 0 protection
chiSquare += math.pow(observedValue - expectedValue, 2) / expectedValue
Together with the 'Degree of Freedom', which is (rows − 1) × (columns − 1) , the P-value can be calculated.
In this case it is P-value: 0.02462
A P-value lower than 0.05 is considered to be significant. Statistically, women tend to choose a romantic movie more, while men prefer a non-romantic one.
Users have the option to choose a P-value, calculated from a standard table or through a math.ucla.edu - Javascript-based function (see references below).
Note that the population (10 men + 10 women = 20) is small, something to consider.
Either way, this principle is applied in the script, where conditions can be chosen like rsi, close, high, ...
🔹 CONDITION
Conditions are added to the left column ('CONDITION')
For example, previous rsi values (rsi ) between 0-100, divided in separate groups
🔹 CLOSE
Then, the movement of the last close is evaluated
UP when close is higher then previous close (close )
DOWN when close is lower then previous close
EQUAL when close is equal then previous close
It is also possible to use only 2 columns by adding EQUAL to UP or DOWN
UP
DOWN/EQUAL
or
UP/EQUAL
DOWN
In other words, when previous rsi value was between 80 and 90, this resulted in:
19 times a current close higher than previous close
14 times a current close lower than previous close
0 times a current close equal than previous close
However, the P-value tells us it is not statistical significant.
NOTE: Always keep in mind that past behaviour gives no certainty about future behaviour.
A vertical line is drawn at the beginning of the chosen population (max 4990)
Here, the results seem significant.
🔹 GROUPS
It is important to ensure that the groups are formed correctly. All possibilities should be present, and conditions should only be part of 1 group.
In the example above, the two top situations are acceptable; close against close can only be higher, lower or equal.
The two examples at the bottom, however, are very poorly constructed.
Several conditions can be placed in more than 1 group, and some conditions are not integrated into a group. Even if the results are significant, they are useless because of the group formation.
A population count is added as an aid to spot errors in group formation.
In this example, there is a discrepancy between the population and total count due to the absence of a condition.
The results when rsi was between 5-25 are not included, resulting in unreliable results.
🔹 PRACTICAL EXAMPLES
In this example, we have specific groups where the condition only applies to that group.
For example, the condition rsi > 55 and rsi <= 65 isn't true in another group.
Also, every possible rsi value (0 - 100) is present in 1 of the groups.
rsi > 15 and rsi <= 25 28 times UP, 19 times DOWN and 2 times EQUAL. P-value: 0.01171
When looking in detail and examining the area 15-25 RSI, we see this:
The population is now not representative (only checking for RSI between 15-25; all other RSI values are not included), so we can ignore the P-value in this case. It is merely to check in detail. In this case, the RSI values 23 and 24 seem promising.
NOTE: We should check what the close price did without any condition.
If, for example, the close price had risen 100 times out of 100, this would make things very relative.
In this case (at least two conditions need to be present), we set 1 condition at 'always true' and another at 'always false' so we'll get only the close values without any condition:
Changing the population or the conditions will change the P-value.
In the following example, the outcome is evaluated when:
close value from 1 bar back is higher than the close value from 2 bars back
close value from 1 bar back is lower/equal than the close value from 2 bars back
Or:
close value from 1 bar back is higher than the close value from 2 bars back
close value from 1 bar back is equal than the close value from 2 bars back
close value from 1 bar back is lower than the close value from 2 bars back
In both examples, all possibilities of close against close are included in the calculations. close can only by higher, equal or lower than close
Both examples have the results without a condition included (5 = 5 and 5 < 5) so one can compare the direction of current close.
🔶 NOTES
• Always keep in mind that:
Past behaviour gives no certainty about future behaviour.
Everything depends on time, cycles, events, fundamentals, technicals, ...
• This test only works for categorical data (data in categories), such as Gender {Men, Women} or color {Red, Yellow, Green, Blue} etc., but not numerical data such as height or weight. One might argue that such tests shouldn't use rsi, close, ... values.
• Consider what you're measuring
For example rsi of the current bar will always lead to a close higher than the previous close, since this is inherent to the rsi calculations.
• Be careful; often, there are na -values at the beginning of the series, which are not included in the calculations!
• Always keep in mind considering what the close price did without any condition
• The numbers must be large enough. Each entry must be five or more. In other words, it is vital to make the 'population' large enough.
• The code can be developed further, for example, by splitting UP, DOWN in close UP 1-2%, close UP 2-3%, close UP 3-4%, ...
• rsi can be supplemented with stochRSI, MFI, sma, ema, ...
🔶 SETTINGS
🔹 Population
• Choose the population size; in other words, how many bars you want to go back to. If fewer bars are available than set, this will be automatically adjusted.
🔹 Inputs
At least two conditions need to be chosen.
• Users can add up to 11 conditions, where each condition can contain two different conditions.
🔹 RSI
• Length
🔹 Levels
• Set the used levels as desired.
🔹 Levels
• P-value: P-value retrieved using a standard table method or a function.
• Used function, derived from Chi-Square Distribution Function; JavaScript
LogGamma(Z) =>
S = 1
+ 76.18009173 / Z
- 86.50532033 / (Z+1)
+ 24.01409822 / (Z+2)
- 1.231739516 / (Z+3)
+ 0.00120858003 / (Z+4)
- 0.00000536382 / (Z+5)
(Z-.5) * math.log(Z+4.5) - (Z+4.5) + math.log(S * 2.50662827465)
Gcf(float X, A) => // Good for X > A +1
A0=0., B0=1., A1=1., B1=X, AOLD=0., N=0
while (math.abs((A1-AOLD)/A1) > .00001)
AOLD := A1
N += 1
A0 := A1+(N-A)*A0
B0 := B1+(N-A)*B0
A1 := X*A0+N*A1
B1 := X*B0+N*B1
A0 := A0/B1
B0 := B0/B1
A1 := A1/B1
B1 := 1
Prob = math.exp(A * math.log(X) - X - LogGamma(A)) * A1
1 - Prob
Gser(X, A) => // Good for X < A +1
T9 = 1. / A
G = T9
I = 1
while (T9 > G* 0.00001)
T9 := T9 * X / (A + I)
G := G + T9
I += 1
G *= math.exp(A * math.log(X) - X - LogGamma(A))
Gammacdf(x, a) =>
GI = 0.
if (x<=0)
GI := 0
else if (x
Chisqcdf = Gammacdf(Z/2, DF/2)
Chisqcdf := math.round(Chisqcdf * 100000) / 100000
pValue = 1 - Chisqcdf
🔶 REFERENCES
mathsisfun.com, Chi-Square Test
Chi-Square Distribution Function
Simple SSRThis indicator shows "SSR" on the chart when SSR "Short Sale Restriction" is activated on the ticker.
SSR "Short Sale Restriction" or "alternative uptick rule" is a rule introduced by the SEC that prohibits shorting on the bid when a stock has dropped more than 10% from the prior days close in the regular trading hours.
It will stay activated for the day it has triggered and the following day through regular and extended market hours.
Since this rule only applies to the US stock market it checks for the exchange and only displays it for US stocks.
Fourier Adjusted Volume Zone Oscillator [BackQuant]Fourier Adjusted Volume Zone Oscillator
Welcome to BackQuant's FSVZO, Primarily we decided to combine the Fourier analysis to a leading indicator concept. Since in concept it can be beneficial.
We also decided to add in the momentum velocity indicator as a point of confluence.
Which will be discussed later in how it can be used in a trading system. For now onto the boring stuff, please read all of this and enjoy!
Fourier ? What and Why:
Fourier transforms are a mathematical technique used for transforming signals between time and frequency domains. In the context of financial markets, this allows analysts to deconstruct price movements into constituent sinusoidal waves. By isolating these waves, traders can identify the dominant market cycles and trends hidden within the 'noise' of short-term price fluctuations.
Empirical Evidence and Benefits:
Cycle Identification: Empirical studies have shown that markets exhibit cyclical behaviors due to various economic, geopolitical, and psychological factors. Fourier filtering helps in pinpointing these cycles, even in seemingly random market movements.
Trend Detection: By highlighting dominant frequencies, traders can more accurately determine the prevailing trend direction, aiding in trend-following or contrarian strategies.
Volatility Clarity: Filtering out noise enhances the visibility of true market volatility, crucial for risk management and strategy adjustment.
Why the Volume Zone Oscillator (VZO) and Origins + Advantages:
The VZO was developed by Walid Khalil and David Steckler and introduced in the "Stocks & Commodities" magazine in 2009. It integrates volume with price movements to gauge the flow of buying and selling pressure. Unlike traditional volume indicators that solely quantify trading volume, the VZO interprets volume's impact on price direction, offering insights into the strength or weakness of a price trend.
Empirical Evidence and Benefits:
Market Sentiment: Volume is a key indicator of market sentiment. High volume accompanying price movements indicates strong sentiment, whereas low volume suggests a lack of conviction. The VZO makes this analysis quantifiable.
Overbought/Oversold Conditions: By quantifying where the current volume-weighted price is within its range, the VZO helps identify potential reversals, providing actionable signals for entering or exiting trades.
Trend Confirmation: The VZO's ability to confirm price trends with volume adds an extra layer of validation to trading signals, reducing the likelihood of false breakouts or breakdowns.
Why we Decided to Combine Them
The integration of Fourier filtering with the VZO offers a comprehensive view of the market by combining the geometric clarity of price movements with the psychological insights provided by volume analysis. This synergy allows for a more nuanced understanding of market dynamics.
Enhanced Signal Accuracy: The combination reduces the chances of false signals. Fourier filtering's trend and cycle identification, combined with the VZO's volume-based confirmation, can significantly enhance trading decision accuracy.
Market Turns and Continuations: Fourier analysis can indicate potential turning points or continuation patterns, which, when confirmed with volume analysis through the VZO, provides a robust signal for traders to act upon.
Adaptability: Both tools adapt well to various market conditions, making this combination versatile across different trading instruments and timeframes.
Empirical Evidence:
While specific empirical studies directly analyzing the combined effectiveness of Fourier filtering and VZO might be scarce, the foundational research supporting each method individually provides strong evidence of their validity. Academic and practical applications in financial markets have demonstrated the value of both Fourier analysis for cycle detection and volume-based oscillators like the VZO for assessing market strength and sentiment. Together, they offer a compelling toolkit for traders aiming to refine their market analysis and strategy execution.
USER INPUTS
Momentum Velocity Group
Show Confluence Momentum Velocity?: This toggle allows users to decide whether they want to display the momentum velocity indicator on their chart. It's designed to show the momentum of price movements, potentially indicating acceleration or deceleration in price trends.
Calculation Source: This setting lets users select the price data used for calculating the momentum velocity. Common options include the close, open, high, low, or an average of these prices. The choice depends on what aspect of price action the trader wishes to analyze.
Lookback Period: Determines the number of bars used to calculate the momentum. A longer period may smooth out the indicator, reducing sensitivity to recent price changes, while a shorter period may make the indicator more responsive to new information.
Use Adaptive Filtering?: Enables the use of adaptive filtering for the momentum calculation. This feature adjusts the indicator's sensitivity based on recent market volatility, potentially improving the indicator's responsiveness to market changes.
Adaptive Lookback Period: Specifies the period for the adaptive filter. This setting fine-tunes how rapidly the filter adjusts to changes in market conditions.
FSVZO Group
Show FSVZO?: This input controls whether the Fourier Smoothed Volume Zone Oscillator is displayed on the chart. It's the main feature of the script, combining Fourier analysis with volume data to provide insights into market dynamics.
Calculation Source for FSVZO: Similar to the momentum velocity calculation source, this setting allows users to choose the price data (close, open, high, low, or an average) that will be used for FSVZO calculations.
Calculation Period: Defines the length of the window for Fourier analysis and VZO calculation. This period can affect the sensitivity and smoothing of the indicator.
Show FSVZO Band Filler? (Ribbon): When enabled, this feature displays a filled area or ribbon on the chart, making it easier to visualize the oscillator's movement and trends.
Show FSVZO Moving Average (Ema)?: This toggle allows the display of an Exponential Moving Average (EMA) of the FSVZO, which can help smooth out its movements and provide a clearer trend direction.
MA Period: Specifies the length of the moving average applied to the FSVZO. Adjusting this period can affect the smoothness and lag of the trend indication.
Smooth VZO (Reduces noise, but increases its accuracy): Enables smoothing of the Volume Zone Oscillator to reduce noise and potentially increase the accuracy of its signals.
Smooth Period: Defines the smoothing period for the VZO, affecting how much noise reduction is applied.
UI Settings Group
Show Static Overbought and Oversold Levels?: Enables the display of predetermined levels that indicate overbought or oversold conditions, helping traders identify potential reversal points.
Show Adaptive Levels?: Allows the use of dynamic, market-condition-adjusted levels for overbought and oversold indicators, offering a more nuanced view of market extremes.
Show Detected Trend Shifts?: This setting controls the display of markers or indications when the script detects potential shifts in market trends, based on the oscillator's movements.
Trendshift Shader?: When enabled, this feature visually highlights areas on the chart where trend shifts are detected, improving the visibility of these important signals.
DIVERGENCES Group
Show Detected Divergences?: This option toggles the display of divergences between price action and the oscillator, which can signal potential reversals.
Use extra filtering when detecting divergences?: Enables additional criteria for identifying divergences, potentially improving the reliability of these signals.
Paint bars when Divergences are detected?: This feature changes the color of price bars when divergences are identified, making them stand out on the chart.
How to calculate divergences: Allows users to choose the method for calculating divergences, affecting the sensitivity and types of divergences that are identified.
Only calculate divergences on values absolutely greater than this: Sets a threshold for divergence calculation, focusing on more significant divergences and reducing noise.
Each input is designed to offer flexibility and control to the user, enabling a highly customizable experience tailored to individual trading strategies and market conditions.
How Can it Be Used in a Trading System
There are a few key ways it can be used, the main way is going to be the trend of the band/ ribbon. As that denotes the primary trend. Thus, if it were to trend up and reach the static overbought zone, there is a high probability of a reversion. This will also work well when it is in an extreme zone and there is a divergence.
Other ways of using it, it taking profit when there is an extreme background hue. Or potentially starting to get ready to buy on a higher timeframe if there is a extreme oversold background hue.
For more clear trends out of the FSVZO you may choose to use the moving average crossing the midline in confluence with the momentum velocity.
Please use with caution, nothing BackQuant or associated entities do are financial advice. please do not use this or any other indicator alone, they are not meant to be used in isolation.
Thus following all of the key points here are some sample backtests on the 1D Chart
Disclaimer: Backtests are based off past results, and are not indicative of the future.
This is using the Midline Crossover of the FSVZO:
INDEX:BTCUSD
INDEX:ETHUSD
BINANCE:SOLUSD
Historical Correlation [LuxAlgo]The Historical Correlation tool aims to provide the historical correlation coefficients of up to 10 pairs of user-defined tickers starting from a user-defined point in time.
Users can choose to display the historical values as lines or the most recent correlation values as a heat map.
🔶 USAGE
This tool provides historical correlation coefficients, the correlation coefficient between two assets highlight their linear relationship and is always within the range (-1, 1).
It is a simple and easy to use statistical tool, with the following interpretation:
Positive correlation (values close to +1.0): the two assets move in sync, they rise and fall at the same time.
Negative correlation (values close to -1.0): the two assets move in opposite directions: when one goes up, the other goes down and vice versa.
No correlation (values close to 0): the two assets move independently.
The user must confirm the selection of the anchor point in order for the tool to be executed; this can be done directly on the chart by clicking on any bar, or via the date field in the settings panel.
For the parameter Anchor period , the user can choose between the following values NONE, HOURLY, DAILY, WEEKLY, MONTHLY, QUARTERLY and YEARLY. If NONE is selected, there will be no resetting of the calculations, otherwise the calculations will start from the first bar of the new period.
There is a wide range of trading strategies that make use of correlation coefficients between assets, some examples are:
Pair Trading: Traders may wish to take advantage of divergences in the price movements of highly positively correlated assets; even highly positively correlated assets do not always move in the same direction; when assets with a correlation close to +1.0 diverge in their behavior, traders may see this as an opportunity to buy one and sell the other in the expectation that the assets will return to the likely same price behavior.
Sector rotation: Traders may want to favor some sectors that are expected to perform in the next cycle, tracking the correlation between different sectors and between the sector and the overall market.
Diversification: Traders can aim to have a diversified portfolio of uncorrelated assets. From a risk management perspective, it is useful to know the correlation between the assets in your portfolio, if you hold equal positions in positively correlated assets, your risk is tilted in the same direction, so if the assets move against you, your risk is doubled. You can avoid this increased risk by choosing uncorrelated assets so that they move independently.
Hedging: Traders may want to hedge positions with correlated assets, from a hedging perspective, if you are long an asset, you can hedge going long a negative correlated asset or going short a positive correlated asset.
Traders generally need to develop awareness, a key point is to be aware of the relationships between the assets we hold or trade, the historical correlation is an invaluable tool in our arsenal which allows us to make better informed decisions.
On this chart we have an example of historical correlations for several futures markets.
We can clearly see how positively correlated the Nasdaq100 and Dow30 are with the SP500 over the whole period, or how the correlation between the Euro and the SP500 falls from almost +85% to almost -4% since 2021.
As we can see, correlations, like everything else in the market, are not static and vary over time depending on many factors, from macro to technical and everything in between.
🔹 Heatmap
The chart above shows the tool with the default settings and the Drawing Mode set to 'HEATMAP'.
We can see the current correlation between the assets, in this case the FX pairs.
The highest positive correlation is +90% (+0.90) between EURUSD and GBPUSD.
The highest negative correlation is -78% (-0.78) between EURUSD and USDJPY.
The pair with no correlation is AUDUSD and EURCAD with 1% (0.01)
On the above chart we can see the current correlations for the futures markets.
Currently, the assets that are less correlated to the SP500 are NaturalGas and the Euro, the more positive correlations are Nasdaq100 and Dow20, and the more negative correlations are the Yen, Treasury Bonds and 10-Year Notes.
🔶 DETAILS
🔹 Anchor Period
This chart shows the standard FX correlations with the Anchor Period set to `MONTHLY`.
We can clearly see how the calculations restart with the new month, in this case we can clearly see the differences between the correlations from month to month.
Let us look at the correlation coefficient between GBPUSD and USDJPY
In January, their correlation started at close to -100%, rose to close to +50%, only to fall to close to 0% and remain there for the second half of the month.
In February it was -90% in the first few days of the month and is now around -57%.
And between AUDUSD and EURCAD
Last month their correlation was negative for most of the month, reaching -70% and ending around -14%.
This month their correlation has never gone below +21% and at the time of writing is close to +53%.
🔶 SETTINGS
Anchor point: Starting point from which the tool is executed
Anchor period: At the beginning of each new period, the tool will reset the calculations
Pairs from 1 to 10: For each pair of tickers, you can: enable/disable the pair, select the color and specify the two tickers from which you wish to obtain the correlation
🔹 Style
Drawing Mode: Output style, `LINES` will show the historical correlations as lines, `HEATMAP` will show the current correlations with a color gradient from green for correlations near 1 to red for correlations near -1.