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
Backtested
DEMA Adjusted Average True Range [BackQuant]The use of the Double Exponential Moving Average (DEMA) within your Adjusted Average True Range (ATR) calculation serves as a cornerstone for enhancing the indicator's responsiveness to market changes. To delve deeper into why DEMA is employed specifically in the context of your ATR calculation, let's explore the inherent qualities of DEMA and its impact on the ATR's performance.
DEMA and Its Advantages
As previously mentioned, DEMA was designed to offer a more responsive alternative to the traditional Exponential Moving Average (EMA). By giving more weight to recent price data, DEMA reduces the lag typically associated with moving averages. This reduction in lag is especially beneficial for short-term traders looking to capitalize on trend reversals and other market movements as swiftly as possible.
The calculation of DEMA involves the following steps:
Calculate EMA1: This is the Exponential Moving Average of the price.
Calculate EMA2: This is the Exponential Moving Average of EMA1, thus it is a smoothing of a smoothing, leading to a greater lag.
Formulate DEMA: The formula
EMA1 = EMA of price
EMA2 = EMA of EMA1
DEMA = (2 x EMA1) - EMA2
effectively doubles the weighting of the most recent data points by subtracting the lagged, double-smoothed EMA2 from twice the single-smoothed EMA1.
This process enhances the moving average's sensitivity to recent price movements, allowing the DEMA to adhere more closely to the price bars than either EMA1 or EMA2 alone.
Integration with ATR
In the context of your ATR calculation, the integration of DEMA plays a crucial role in defining the indicator's core functionality. Here's a detailed explanation of how DEMA affects the ATR calculation:
Initial Determination of DEMA : By applying the DEMA formula to the chosen source data (which can be adjusted to use Heikin Ashi candle close prices for an even smoother analysis), you set a foundation for a more reactive trend-following mechanism within the ATR framework.
Application to ATR Bands : The calculated DEMA serves as the central line from which the ATR bands are derived. The ATR value, multiplied by a user-defined factor, is added to and subtracted from the DEMA to form the upper and lower bands, respectively. This dynamic adjustment not only reflects the volatility based on the ATR but does so in a way that is closely aligned with the most recent price action, thanks to the utilization of DEMA.
Enhanced Signal Quality : The responsiveness of DEMA ensures that the ATR bands adjust more promptly to changes in market conditions. This quality is vital for traders who rely on the ATR bands to identify potential entry and exit points, trend reversals, or to assess market volatility.
By employing DEMA as the core component in calculating the Adjusted Average True Range, your indicator leverages DEMA's reduced lag and increased weight on recent data to provide a more timely and accurate measure of market volatility. This innovative approach enhances the utility of the ATR by making it not only a tool for assessing volatility but also a more reactive indicator for trend analysis and trading signal generation.
The main concept of combining these is to reduce lag, get a more robust signal and still capture clear trends over medium time horizons.
For me, this is best used in confluence with other indicators, it can be made faster in order to get fasters response time, or slower. This is all depending on the needs of you as a trader.
User Inputs:
The script offers several user-configurable inputs, such as the period lengths for DEMA and ATR calculations, the multiplication factor for the ATR, and options to use Heikin Ashi candles or standard price data. Additionally, it allows for the toggling of visual features, like the plotting of the DEMA ATR and its moving average, and the application of color-coded trends on price bars.
Additional Features:
Moving Average Confluence: Traders can opt to display a moving average of the DEMA ATR, choosing from various types (e.g., SMA, EMA, HMA). This feature provides a layer of confluence, aiding in the identification of trend direction and strength.
Trend Identification :
The script employs logical conditions to ascertain the trend direction based on the movement of the DEMA ATR. It assigns colors to represent bullish or bearish trends, which are reflected in the plotted lines and the coloring of price bars.
Alerts :
Customizable alert conditions for trend reversals enhance the utility of the indicator for active trading, notifying users of significant changes in trend direction.
1D Backtests
We include these backtests as a general proxy for how they work.
Please do your own calibrating to suit it to your own needs and backtest.
Past results don't = future results but they can help you understand how it functions.
INDEX:BTCUSD
INDEX:ETHUSD
BINANCE:SOLUSD
Session candles & reversals / quantifytools— Overview
Like traditional candles, session based candles are a visualization of open, high, low and close values, but based on session time periods instead of typical timeframes such as daily or weekly. Session candles are formed by fetching price at session start (open), highest price during session (high), lowest price during session (low) and price at session end (close). On top of candles, session based moving average is formed and session reversals detected. Session reversals are also backtested, using win rate and magnitude metrics to better understand what to expect from session reversals and which ones have historically performed the best.
By default, following session time periods are used:
Session #1: London (08:00 - 17:00, UTC)
Session #2: New York (13:00 - 22:00, UTC)
Session #3: Sydney (21:00 - 06:00, UTC)
Session #4: Tokyo (00:00 - 09:00, UTC)
Session time periods can be changed via input menu.
— Reversals
Session reversals are patterns that show a rapid change in direction during session. These formations are more familiarly known as wicks or engulfing candles. Following criteria must be met to qualify as a session reversal:
Wick up:
Lower high, lower low, close >= 65% of session range (0% being the very low, 100% being the very high) and open >= 40% of session range.
Wick down:
Higher high, higher low, close <= 35% of session range and open <= 60% of session range.
Engulfing up:
Higher high, lower low, close >= 65% of session range.
Engulfing down:
Higher high, lower low, close <= 35% of session range.
Session reversals are always based on prior corresponding session , e.g. to qualify as a NY session engulfing up, NY session must have a higher high and lower low relative to prior NY session , not just any session that has taken place in between. Session reversals should be viewed the same way wicks/engulfing formations are viewed on traditional timeframe based candles. Essentially, wick reversals (light green/red labels) tell you most of the motion during session was reversed. Engulfing reversals (dark green/red labels) on the other hand tell you all of the motion was reversed and new direction set.
— Backtesting
Session reversals are backtested using win rate and magnitude metrics. A session reversal is considered successful when next corresponding session closes higher/lower than session reversal close . Win rate is formed by dividing successful session reversal count with total reversal count, e.g. 5 successful reversals up / 10 reversals up total = 50% win rate. Win rate tells us what are the odds (historically) of session reversal producing a clean supporting move that was persistent enough to close that way too.
When a session reversal is successful, its magnitude is measured using percentage increase/decrease from session reversal close to next corresponding session high/low . If NY session closes higher than prior NY session that was a reversal up, the percentage increase from prior session close (reversal close) to current session high is measured. If NY session closes lower than prior NY session that was a reversal down, the percentage decrease from prior session close to current session low is measured.
Average magnitude is formed by dividing all percentage increases/decreases with total reversal count, e.g. 10 total reversals up with 1% increase each -> 10% net increase from all reversals -> 10% total increase / 10 total reversals up = 1% average magnitude. Magnitude metric supports win rate by indicating the depth of successful session reversal moves.
To better understand the backtesting calculations and more importantly to verify their validity, backtesting visuals for each session can be plotted on the chart:
All backtesting results are shown in the backtesting panel on top right corner, with highest win rates and magnitude metrics for both reversals up and down marked separately. Note that past performance is not a guarantee of future performance and session reversals as they are should not be viewed as a complete strategy for long/short plays. Always make sure reversal count is sufficient to draw reliable conclusions of performance.
— Session moving average
Users can form a session based moving average with their preferred smoothing method (SMA , EMA , HMA , WMA , RMA) and length, as well as choose which sessions to include in the moving average. For example, a moving average based on New York and Tokyo sessions can be formed, leaving London and Sydney completely out of the calculation.
— Visuals
By default, script hides your candles/bars, although in the case of candles borders will still be visible. Switching to bars/line will make your regular chart visuals 100% hidden. This setting can be turned off via input menu. As some sessions overlap, each session candle can be separately offsetted forward, clearing the overlaps. Users can also choose which session candles to show/hide.
Session periods can be highlighted on the chart as a background color, applicable to only session candles that are activated. By default, session reversals are referred to as L (London), N (New York), S (Sydney) and T (Tokyo) in both reversal labels and backtesting table. By toggling on "Numerize sessions", these will be replaced with 1, 2, 3 and 4. This will be helpful when using a custom session that isn't any of the above.
Visual settings example:
Session candles are plotted in two formats, using boxes and lines as well as plotcandle() function. Session candles constructed using boxes and lines will be clear and much easier on the eyes, but will apply only to first 500 bars due to Tradingview related limitations. Rest of the session candles go back indefinitely, but won't be as clean:
All colors can be customized via input menu.
— Timeframe & session time period considerations
As a rule of thumb, session candles should be used on timeframes at or below 1H, as higher timeframes might not match with session period start/end, leading to incorrect plots. Using 1 hour timeframe will bring optimal results as greatest amount historical data is available without sacrificing accuracy of OHLC values. If you are using a custom session that is not based on hourly period (e.g. 08:00 - 15:00 vs. 08.00 - 15.15) make sure you are using a timeframe that allows correct plots.
Session time periods applied by default are rough estimates and might be out of bounds on some charts, like NYSE listed equities. This is rarely a problem on assets that have extensive trading hours, like futures or cryptocurrency. If a session is out of bounds (asset isn't traded during the set session time period) the script won't plot given session candle and its backtesting metrics will be NA. This can be fixed by changing the session time periods to match with given asset trading hours, although you will have to consider whether or not this defeats the purpose of having candles based on sessions.
— Practical guide
Whether based on traditional timeframes or sessions, reversals should always be considered as only one piece of evidence of price turning. Never react to them without considering other factors that might support the thesis, such as levels and multi-timeframe analysis. In short, same basic charting principles apply with session candles that apply with normal candles. Use discretion.
Example #1 : Focusing efforts on session reversals at distinct support/resistance levels
A reversal against a level holds more value than a reversal by itself, as you know it's a placement where liquidity can be expected. A reversal serves as a confirming reaction for this expectation.
Example #2 : Focusing efforts on highest performing reversals and avoiding poorly performing ones
As you have data backed evidence of session reversal performance, it makes sense to focus your efforts on the ones that perform best. If some session reversal is clearly performing poorly, you would want to avoid it, since there's nothing backing up its validity.
Example #3 : Reversal clusters
Two is better than one, three is better than two and so on. If there are rapid changes in direction within multiple sessions consecutively, there's heavier evidence of a dynamic shift in price. In such case, it makes sense to hold more confidence in price halting/turning.
Easy Backtester PROWHAT IS EasyBacktester ?
EasyBacktester is a tool that helps you backtest trading strategies built by yourself with an included strategy builder and a multitude of options.
From within the parameters of the tool, you can specifically pick your entry settings across 12 most common indicators, such as "RSI", "MACD", "Moving Averages" etc... Then you can immediately visualise your setup's Stop-loss & Take Profit, your expected Profits & Loss and a lot of other statistics for your entry strategy. Once you are satisfied with your entry strategy, you are given a set of tools to optimize your setup using stop-loss rules, take profits rules, partial profits, trailing-stops, entry timing...
WHY IS THIS TOOL DIFFERENT ?
EasyBacktester is a backtesting engine with no coding skills required. TradingView allows for "Strategy Scripting" using PineScript, which is not an option for non-coder audience. EasyBacktester fills this gap and allow non-coders to get an idea of how their trading strategies may perform using mouse clicks only.
Some similar attempts have been made on TradingView, allowing some limited options, but none have the same capabilities EasyBacktester offers, for instance, as of April 2022 these features have not been seen in any other TradingView tools:
- partial take profits
- leverage simulation
- a multitude of trailing stop-loss possibilities including trail triggers and trail parameters
- visualisation of entries including stop-loss, take profits, partial take profits, and trailing stops. One can now visualize such complex setups.
- visualisation of Profits & Loss
- time in trade
- wait strategy after a signal: for example, when RSI is oversold, "WAIT until price retraces 100% of the original signal" amongst other possibilities
QUICK START GUIDE:
STEP 1: DEFINE YOUR SIGNAL STRATEGY
From the settings of the tool, find the "SIGNALS STRATEGY" section.
Select a type of entry you wish to simulate, for example "LONGs", and activate the checkbox right before "Simulate".
Right below, you will find 4 signal builder for you to play with and pick your strategy accordingly.
For example, to simulate a signal when RSI is oversold, follow these steps:
- On the 1st multiple choice box, select "RSI"
- On the 2nd multiple choice box, select "is below..."
- On the 3rd multiple choice box, select "OverSold level"
Don't forget to activate this rule by checking the checkbox in front of it.
After this first step, one should immediately see the chart affected with some plots. The dots represents the signal entry defined by the rule we just created, and the red/green boxes visually represent trades that could have been taken with this signal which, in this example, occurs "when RSI is below oversold level". Note that all specific parameters for RSI including its specific "oversold level" is customisable at the end of the tools settings along with all other indicators settings.
STEP 2: STATISTICS
By default, the "APPEARANCE" section only plots potential entry signals (materialized by dots) and actual entry boxes (materialized by red/green boxes).
But the user can easily add other precious statistics to the chart, and obviously the most important one for backtesting: Profits & Loss (P&L).
In the "STATISTICS" section please check the "P&L" box to see appear a chart of the simulated P&L for our example. You should immediately see a new graph below the chart representing the evolution of the P&L after each entry.
Other statistics are available to the user, including: Equity, Number of Trades, Time in Position, Number of trades Won, Number of trades Lost, Number of trades Stopped.
Play around with those to see them plotted on your chart.
STEP 3: OPTIMIZE YOUR ENTRY
Under the "ENTRY STRATEGY" section, one can pick how to enter AFTER the signal, which provides the user with an extensive flexibility to pick its timing.
Here there are a various set of choices offered, ranging from the default "Market Order at Next Candle Open", to "Limit Order: at signal's candle open" or even "Stop-Buy: at break of last candle high". As its name suggests, this option allows you to actually wait before randomly enter in trade.
It is important to also note that the user can totally prevent entry if the conditions are not filled after a customizable number of candles represented in "Max bars to wait for entry" (default being 1, meaning the engine will wait the condition to be filled during only 1 candle)
STEP 4: MANAGE YOUR RISK
Under the "RISK MANAGEMENT" section, the user is given a series of options to set the amount (s)he would like to risk.
This is extremely important to set, and is the result of a combination of customizable options including:
- the Initial Capital of the account
- the amount to risk per trade, and HOW to risk it: some fixed % the initial equity or adjust the stop-loss to the desired risk ?
- use of leverage or not
- initial stop-loss, as well as minimum and maximum
- trailing stop-loss: what should trigger the trailing ? and by how much should the engine trail ?
STEP 5: HAVE AN EXIT PLAN
Under the "EXIT STRATEGY", the user can define how to exit the trade.
For instance, here again a lot of options are given:
- Take Profit: exit at some level of profits defined by a multiple of the stop-loss, or a multiple of the ATR, or some % or points
- Partial Profit taking before exit
- Panic close position after some time spent on the trade
STEP 6: FURTHER OPTIMIZATIONS
Under the sections "Commissions" & "Calendar & Sessions", one can simulate real trading conditions by including commissions fees as well as filtering actual dates and trading sessions. These sections are straightforward for any user to use.
SETP 7: INDICATORS SETTINGS
Since EasyBacktester uses a predefined set of indicators to get started, those indicators are also customizable in the last section of the settings. Here, one can easily customize RSI periodicity, MACD lengths, Moving averages types & lengths, ATR, etc...
STEP 8: GOING FURTHER
This is only a start to give users an overview of how various options affect their trading performance. But of course, each trader has its special recipe and specific detailed setup that is not possible to embed in a single tool. For advanced simulation, EasyBacktester provides plug & play connectors for advanced users. Namely, there are 3 connectors:
- signal connector
- trail trigger connector
- exit connector
Each of these connectors are an opportunity to customize the engine signals, trail trigger and exit choices with the user's own options. This case does require a little bit of coding, but it can easily be implemented by copy-pasting existing resources or with a slight help of a professional. In fact, the only conditions to build a proper connector is to export a plot with the numbers 1 (for signals), 2 (for trigger trails) and 3 (for exits). Here is an example of custom SIGNAL connector compatible with EasyBacktester, to produce a signal when last RSI was below 30 and current RSI reads above 30:
============================================================
//@version=5
indicator("My custom RSI signal")
// when previous RSI 14 was below 30 and current RSI 14 is above 30, set "custom_signal" to 1, otherwise set "custom_signal" to 0
custom_signal = ta.rsi(close, 14) < 30 and ta.rsi(close, 14) > 30 ? 1 : 0
// Export a plot of "custom_signal", but do not display it
plot(custom_signal, title="my signal", display=display.none)
============================================================
Once this indicator has been built, the user only needs to connect it with EasyBacktester as follow:
1. Open a desired chart, and add both EasyBacktester indicator as well as the custom "My custom signal" we just created above.
2. Open EasyBacktester's settings, and in the first option, there is "Connect signals source" which by default is set to "close". In the multiple choices, find your custom signal which should be named something like "My custom RSI signal: my signal", generally speaking the name is built like this " : ".
3. Now the custom code is connected to EasyBacktester, but we need to indicate the engine we actually want to use it as custom signal.
4. Under the "SIGNALS STRATEGY" section, where we generally build signals rules, there is special rule for this specific connection named "Use external source as entry signal". Just check the checkbox to activate it and see how the chart took our custom signal into consideration.
That's it for the overview of EasyBacktester. Thank you for reading and happy trading :)
Backtest HelperAre you tired of being able to see the future while you're backtesting? Have you ever clicked to a higher timeframe in bar replay, only to realize you've just seen everything that's going to happen before you've had a chance to test it? If you've had this problem, Backtest Helper is here for YOU.
All you have to do is set a start date and time, then set your desired timeframe in minutes, then you're off to the races.
For example, if you're a scalper that uses the 15 minute as their higher timeframe, set your start time at the 14th minute of the session you're testing and set your line spacing at 15 minutes. This will mark off every 14th minute on the charts. Now you know the exact moment you can go up to the 15 minute timeframe!
On our 1 minute timeframe, this is how we'd look with the above settings. The Backtest Helper has marked off the 14th, 29th, 44th and 59th minute.
When we go up to our 15 minute, there's no issues. We're seeing the candle we want to see and not the next 15 minute candle.
You can use this for any timeframe. Just make sure you set your start time to at least 1 minute before the close of the candle and your line spacing to the higher timeframe (in minutes) you want to target.