EMA MTF PlusI like trading the 1 minute and 3 minutes time-frames. I'm what is commonly called a "scalper". Long term investments yes, I have some, but for trading, I don't have neither the time,
nor the patience to wait hours or days for my trade to be complete.
This doesn't mean I discount the higher time-frames, no, I actually rely heavily on them. I found that EMAs do a decent job as support/resistance, sometimes to a tick level of precision. And this is important for a 1 minute trader.
As such, I made this script that tracks the higher time-frames EMAs and displays the last value as a line.
I do not need the whole EMA, I'm not interested in crossovers or crossunders, these are anyway late signals for me.
What's with the triangles? These are local tops/bottoms , candles that have a have decent size of the wick. These tops and bottoms are by no means "final", they are merely a rejection at certain levels of price. Due to markets complexities (and human erratic behaviors hehe) these levels could be breached at the very next candle. For a more "final" version (nothing is really final but..) I added Schaff Trend Cycle as filter, so a triangle will pop only when a trend is mature enough ( STC with a value near 0 or near 100).
Colored bars. When the body of the candle is big, it shows strength. Strong bars tend to have follow through, especially when breaking key levels. The script looks at the body of the candle and compares it with ATR (Average True Range), if it's at least 0.8 of ATR it changes the bar color to yellow (bull candles) or fuchsia(bear candles).
Range identifier. This code is copied from Lazy Bear (if there are any issues please let me know), it's very useful in conjunction with colored bars.
I look for breakout candles that go outside of the range as a signal for a trade.
There are many ways in which this script can be useful, like trading mean reversions or momentum trades (breakouts) or simply trend following trades.
I hope you guys find it useful, you can play with default values and change them as you like, these are what I found to be working best for me and my trading universe (mostly crypto).
Special thanks for the original work of:
LazyBear
everget
Jim8080
Mean
Pythagorean Means of Moving AveragesDESCRIPTION
Pythagorean Means of Moving Averages
1. Calculates a set of moving averages for high, low, close, open and typical prices, each at multiple periods.
Period values follow the Fibonacci sequence.
The "short" set includes moving average having the following periods: 5, 8, 13, 21, 34, 55, 89, 144, 233, 377.
The "mid" set includes moving average having the following periods: 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597.
The "long" set includes moving average having the following periods: 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181.
2. User selects the type of moving average: SMA, EMA, HMA, RMA, WMA, VWMA.
3. Calculates the mean of each set of moving averages.
4. User selects the type of mean to be calculated: 1) arithmetic, 2) geometric, 3) harmonic, 4) quadratic, 5) cubic. Multiple mean calculations may be displayed simultaneously, allowing for comparison.
5. Plots the mean for high, low, close, open, and typical prices.
6. User selects which plots to display: 1) high and low prices, 2) close prices, 3) open prices, and/or 4) typical prices.
7. Calculates and plots a vertical deviation from an origin mean--the mean from which the deviation is measured.
8. Deviation = origin mean x a x b^(x/y)/c.
9. User selects the deviation origin mean: 1) high and low prices plot, 2) close prices plot, or 3) typical prices plot.
10. User defines deviation variables a, b, c, x and y.
Examples of deviation:
a) Percent of the mean = 1.414213562 = 2^(1/2) = Pythagoras's constant (default).
b) Percent of the mean = 0.7071067812 = = = sin 45˚ = cos 45˚.
11. Displaces the plots horizontally +/- by a user defined number of periods.
PURPOSE
1. Identify price trends and potential levels of support and resistance.
CREDITS
1. "Fibonacci Moving Average" by Sofien Kaabar: two plots, each an arithmetic mean of EMAs of 1) high prices and 2) low prices, with periods 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181.
2. "Solarized" color scheme by Ethan Schoonover.
Keltner Channels BandsKeltner Channel Bands
Great indicator for mean reversion strategies.
Alerts you can set:
Crossover EMA
Crossunder EMA
Crossover upper band
Crossunder upper band
Crossover lower band
Crossunder lower band
Have fun!
level_statsThis script tells you the percentage of time an instrument's closing value is above and below a level of your choosing. The background color visually indicates periods where the instrument closed at or above the level (red) and below it (blue). For "stationary-ish" processes, you can get a loose feel for the mean, high, and low values. The historical information conveyed through the background coloring can help you plan derivatives trades. Try with your favorite pairs, commodities, or volatility indices.
Usage: pick a level of interest using the input.
Augmented Dickey–Fuller (ADF) mean reversion testThe augmented Dickey-Fuller test (ADF) is a statistical test for the tendency of a price series sample to mean revert .
The current price of a mean-reverting series may tell us something about the next move (as opposed, for example, to a geometric Brownian motion). Thus, the ADF test allows us to spot market inefficiencies and potentially exploit this information in a trading strategy.
Mathematically, the mean reversion property means that the price change in the next time period is proportional to the difference between the average price and the current price. The purpose of the ADF test is to check if this proportionality constant is zero. Accordingly, the ADF test statistic is defined as the estimated proportionality constant divided by the corresponding standard error.
In this script, the ADF test is applied in a rolling window with a user-defined lookback length. The calculated values of the ADF test statistic are plotted as a time series. The more negative the test statistic, the stronger the rejection of the hypothesis that there is no mean reversion. If the calculated test statistic is less than the critical value calculated at a certain confidence level (90%, 95%, or 99%), then the hypothesis of a mean reversion is accepted (strictly speaking, the opposite hypothesis is rejected).
Input parameters:
Source - The source of the time series being tested.
Length - The number of points in the rolling lookback window. The larger sample length makes the ADF test results more reliable.
Maximum lag - The maximum lag included in the test, that defines the order of an autoregressive process being implied in the model. Generally, a non-zero lag allows taking into account the serial correlation of price changes. When dealing with price data, a good starting point is lag 0 or lag 1.
Confidence level - The probability level at which the critical value of the ADF test statistic is calculated. If the test statistic is below the critical value, it is concluded that the sample of the price series is mean-reverting. Confidence level is calculated based on MacKinnon (2010) .
Show Infobox - If True, the results calculated for the last price bar are displayed in a table on the left.
More formal background:
Formally, the ADF test is a test for a unit root in an autoregressive process. The model implemented in this script involves a non-zero constant and zero time trend. The zero lag corresponds to the simple case of the AR(1) process, while higher order autoregressive processes AR(p) can be approached by setting the maximum lag of p. The null hypothesis is that there is a unit root, with the alternative that there is no unit root. The presence of unit roots in an autoregressive time series is characteristic for a non-stationary process. Thus, if there is no unit root, the time series sample can be concluded to be stationary, i.e., manifesting the mean-reverting property.
A few more comments:
It should be noted that the ADF test tells us only about the properties of the price series now and in the past. It does not directly say whether the mean-reverting behavior will retain in the future.
The ADF test results don't directly reveal the direction of the next price move. It only tells wether or not a mean-reverting trading strategy can be potentially applicable at the given moment of time.
The ADF test is related to another statistical test, the Hurst exponent. The latter is available on TradingView as implemented by balipour , QuantNomad and DonovanWall .
The ADF test statistics is a negative number. However, it can take positive values, which usually corresponds to trending markets (even though there is no statistical test for this case).
Rigorously, the hypothesis about the mean reversion is accepted at a given confidence level when the value of the test statistic is below the critical value. However, for practical trading applications, the values which are low enough - but still a bit higher than the critical one - can be still used in making decisions.
Examples:
The VIX volatility index is known to exhibit mean reversion properties (volatility spikes tend to fade out quickly). Accordingly, the statistics of the ADF test tend to stay below the critical value of 90% for long time periods.
The opposite case is presented by BTCUSD. During the same time range, the bitcoin price showed strong momentum - the moves away from the mean did not follow by the counter-move immediately, even vice versa. This is reflected by the ADF test statistic that consistently stayed above the critical value (and even above 0). Thus, using a mean reversion strategy would likely lead to losses.
Pythagorean Moving Averages (and more)When you think of the question "take the mean of this dataset", you'd normally think of using the arithmetic mean because usually the norm is equal to 1; however, there are an infinite number of other types of means depending on the function norm (p).
Pythagoras' is credited for the main types of means: his harmonic mean, his geometric mean, and his arithmetic mean:
Harmonic Average (p = -1):
- Take the reciprocal of all the numbers in the dataset, add them all together, divide by the amount of numbers added together, then take the reciprocal of the final answer.
Geometric Average (p = 0):
- Multiply all the numbers in the dataset, then take the nth root where n is equal to the amount of number you multiplied together.
Arithmetic Mean (p = 1):
- Add all the numbers in the dataset, then divide by the amount of numbers you added by.
A couple other means included in this script were the quadratic mean (p = 2) and the cubic mean (p = 3).
Quadratic Mean (p = 2):
- Square every number in the dataset, then divide by the amount of numbers your added by, then take the square root.
Cubic Mean (p = 3):
- Cube every number in the dataset, then divide by the amount of numbers you added by, then take the cube root.
There are an infinite number of means for every scenario of p, but they begin to follow a pattern after p = 3.
Read more:
www.cs.uni.edu
en.wikipedia.org
en.wikipedia.org
Note : I added the functions for the quadratic mean and cubic mean, but since market charts don't have those types of graphs, the functions don't usually work. It's the same reason why sometimes you'll see the harmonic average not working.
Disclaimer : This is not financial or mathematical advice, please look for someone certified before making any decisions.
Roc Mean Reversion (ValueRay)This Indicator shows the Absolute Rate of Change in correlation to its Moving Average.
Values over 3 (gray dotted line) can savely be considered as a breakout; values over 4.5 got a high mean-reverting chance (red dotted line).
This Indicator can be used in all timeframes, however, i recommend to use it <30m, when you want search for meaningful Mean-Reverting Signals.
Please like, share and subscribe. With your love, im encouraged to write and publish more Indicators.
Drift Study (Inspired by Monte Carlo Simulations with BM) [KL]Inspired by the Brownian Motion ("BM") model that could be applied to conducting Monte Carlo Simulations, this indicator plots out the Drift factor contributing to BM.
Interpretation : If the Drift value is positive, then prices are possibly moving in an uptrend. Vice versa for negative drifts.
Alpha Trading - Deviation Log Pro - Coder WolvesAlpha Trading - Deviation Log Pro
Here at Alpha Trading we love our indicators built on returns. In our view, the only way to play divergences in Trading is divergences between Returns based oscillators and Price.
The Alpha Trading Deviation Log Pro displays a mean of log returns, with returns and price both weighted using our proprietary root mean square (RMS) Z-Score.
We also show standard error and confidence intervals.
Within the indicator settings, you can apply alerts to the RMS Z Score, as well as an option to turn on triangle and square shapes to assist with showing potential buy/sell and get out of trade signals.
Things to Understand First
Standard Error
The term "standard error" is used to refer to the standard deviation of various sample statistics, such as the mean or median. For example, the "standard error of the mean" refers to the standard deviation of the distribution of sample means taken from a population. The smaller the standard error, the more representative the sample will be of the overall population.
The relationship between the standard error and the standard deviation is such that, for a given sample size, the standard error equals the standard deviation divided by the square root of the sample size. The standard error is also inversely proportional to the sample size; the larger the sample size, the smaller the standard error because the statistic will approach the actual value.
The standard error is considered part of inferential statistics. It represents the standard deviation of the mean within a dataset. This serves as a measure of variation for random variables, providing a measurement for the spread. The smaller the spread, the more accurate the dataset.
Confidence Interval
A confidence interval is a range of values where an unknown population parameter is expected to lie most of the time, if you were to repeat your study with new random samples.
With a 95% confidence level, 95% of all sample means will be expected to lie within a confidence interval of ± 1.96 standard errors of the sample mean.
Settings
• Confidence Intervals plotted with Green and Red Horizontal Lines
• Standard Error Mean - Plotted as a blue dots
• Standard Error Upper - Plotted as a grey line
• Standard Error Lower -Plotted as grey line
• RMS Z-Score Alerts shown as Red and Green Dots
• Potential Buy Signal Green Triangle Up
• Potential Sell Signal - Red Triangle Down
• Get out of Long Trade - White Square
• Get Out of Short Trade - White Square
The Chart below is showing the Divergences between Returns and Price Action over a long term trend of a time series, no matter the time frame.
Alpha Trading - Absolute Mean Entropy with A2 EPPAbsolute Mean Entropy with Alpha Squared Entropy Price Percentile
Entropy
The history of the word ―entropy can be traced back to 1865 when the German physicist Rudolf Clausius tried to give a new name to irreversible heat loss, what he previously called ―equivalent-value.
The word ―entropy was chosen because in Greek, “en+tropein” means “content transformative” or “transformation content”
Since then, entropy has played an important role in thermodynamics and many other scientific fields. Being defined as the sum of “heat supplied” divided by “temperature” it is central to the Second Law of Thermodynamics. It also helps measure the amount of order and disorder and/or chaos.
The application of entropy in finance can be regarded as an extension of “Information Entropy” and “Probability Entropy”
Entropy in Finance can be used in many ways such as Asset Selection, Asset Diversification, Measure an Assets Risk, inputs into Options pricing. While Entropy started in the field of Thermodynamics as aforementioned it has also found a home in Finance. However, studies with entropy in the field of Finance are still in their infancy.
• Entropy is a measure of randomness. Entropy is used to help model and represent the degree of uncertainty of a random variable.
• Entropy is used by financial analysts and market technicians to determine the chances of a specific type of behavior by a security or market.
• Entropy has long been a source of study and debate by market analysts and traders. It is used in quantitative analysis and can help predict the probability that a security will move in a certain direction or according to a certain pattern.
The concept of Entropy is explored in the book "A Random Walk Down Wall Street."
Entropy is plotted below the axis with negative values. Entropy can also colorize the candle color if selected.
R-squared (The Coefficient of Determination)
R-squared is a statistical measurement that examines how differences in one variable can be explained by the difference in a second variable, when predicting the outcome of a given event.
In other words, this coefficient, which is more commonly known as R-squared (or R2), assesses how strong the linear relationship is between two variables, and is heavily relied on by researchers when conducting trend analysis.
To cite an example of its application, this coefficient may contemplate the following question: if an indicator becomes pregnant on a certain day, what is the likelihood that this indicator would deliver a new indicator on a particular date in the future? In this scenario, this metric aims to calculate the correlation between two related events: conception of the indicator and the birth of the indicator.
• The coefficient of determination is a complex idea centered on the statistical analysis of models for data.
• The coefficient of determination is used to explain how much variability of one factor can be caused by its relationship to another factor.
• This coefficient is commonly known as R-squared (or R2) and is sometimes referred to as the "goodness of fit."
• This measure is represented as a value between 0.0 and 1.0, where a value of 1.0 indicates a perfect fit, and is thus a highly reliable model for future forecasts, while a value of 0.0 would indicate that the model fails to accurately model the data at all.
R2 and Price
The hypothesis that R2 is related to investors’ biases in processing information.
This theory motivates an empirical hypothesis that stocks with lower R2 should exhibit more pronounced overreaction-driven price momentum.
Alpha Trading AME/A2 EPP Settings
Settings for AME (Absolute Mean Entropy)
Length: Sample size.
Use as Barcolor: AME color as Price Action Candle color.
Show Entropy Flashes: If absolute value of entropy is very low, it gives yellow color for AME and Price Action Candle color if selected.
Band StdDev: (2 times) AME StdDev bands.1st and 2nd default.
Exponential Weighted Entropy: Weights the AME exponentially, is more reactive, but more noise.
Settings for EPP (Entropy Price Percentile)
Percentile Period: lookback for percentile range(relevant for flashes)
Background flashes: if EPP is below threshold default is below 10%, Flashes green in the background.
Std.err bands period: default 3 and multiplier 1.
EPP Column Meanings
Bright Green: Returns above the mean and increasing.
Dark Green: Returns above the mean and decreasing.
Bright Red: Returns below the mean and increasing.
Dark Red: Returns below the mean and decreasing.
Basic Trade Signal
Long – Value of AME is low, as you see EPP increasing with a coloration of green consider taking a long if you have confluence with other Alpha Trading Indicators.
Short – Value of AME is low, as you see EPP increasing with a coloration of red consider taking a short if you have confluence with other Alpha Trading Indicators.
The Chart below is showing Entries, Exponential Weighting input turned on, Percentile Period set to 30 instead of default 100, everything else is Default....
When using other Alpha Trading indicators in confluence, there are other entries available when the indicator isn't flashing and the indicator still supports the move.
References
www.investopedia.com
www.investopedia.com
www.wallstreetmojo.com
byjus.com
www.investopedia.com
en.wikipedia.org
papers.ssrn.com
Res/Sup With Concavity & Increasing / Decreasing Trend AnalysisPurple means the concavity is down blue means concavity is up which is good.
Yellow means increasing, Red means decreasing.
Sup = Green
Res = Red
Coefficient of variation (standard deviation over mean)Shows the coefficient of variation defined as standard deviation over mean (for the specified window).
Hurst ExponentMy first try to implement Full Hurst Exponent.
The Hurst exponent is used as a measure of long-term memory of time series. It relates to the autocorrelations of the time series and the rate at which these decrease as the lag between pairs of values increases
The Hurst exponent is referred to as the "index of dependence" or "index of long-range dependence". It quantifies the relative tendency of a time series either to regress strongly to the mean or to cluster in a direction.
In short, depending on the value you can spot the trending / reversing market.
Values 0.5 to 1 - market trending
Values 0 to 0.5 - market tend to mean revert
Hurst Exponent is computed using Rescaled range (R/S) analysis.
I split the lookback period (N) in the number of shorter samples (for ex. N/2, N/4, N/8, etc.). Then I calculate rescaled range for each sample size.
The Hurst exponent is estimated by fitting the power law. Basically finding the slope of log(samples_size) to log(RS).
You can choose lookback and sample sizes yourself. Max 8 possible at the moment, if you want to use less use 0 in inputs.
It's pretty computational intensive, so I added an input so you can limit from what date you want it to be calculated. If you hit the time limit in PineScript - limit the history you're using for calculations.
####################
Disclaimer
Please remember that past performance may not be indicative of future results.
Due to various factors, including changing market conditions, the strategy may no longer perform as good as in historical backtesting.
This post and the script don’t provide any financial advice.
Simple Hurst Exponent [QuantNomad]This is a simplified version of the Hurst Exponent indicator.
In the meantime, I'm working on the full version. It's computationally intensive, so it's a challenge to squeeze it to PineScript limits. It will require some time to optimize it, so I decided to publish a simplified version for now.
The Hurst exponent is used as a measure of long-term memory of time series. It relates to the autocorrelations of the time series, and the rate at which these decrease as the lag between pairs of values increases
The Hurst exponent is referred to as the "index of dependence" or "index of long-range dependence". It quantifies the relative tendency of a time series either to regress strongly to the mean or to cluster in a direction.
In short depend on value you can spot trending / reversing market.
Values 0.5 to 1 - market trending
Values 0 to 0.5 - market tend to mean revert
####################
Disclaimer
Please remember that past performance may not be indicative of future results.
Due to various factors, including changing market conditions, the strategy may no longer perform as good as in historical backtesting.
This post and the script don’t provide any financial advice.
B3 HL2MA Painter ~ Extremely Smooth Average & Bar PaintMy HL2MA is a 'proprietary' formula based on the idea that I never again want to see a jagged average line. I released a version of this a long time ago, but I wanted to update it to how I have it on my charts in other platforms. Here are some notes about this moving average script:
The default input value is 5, and I suggest the range of use 4-6 with the rare occasion of using 3 or 7.
For me 5 is what I use UNLESS I AM IN A TRADE, then I might switch to 4 if I have some profits to lock, or 6 if I want to stay in for a lengthier trade.
This average when kept within the above parameters is the smoothest MA in my arsenal, HL2 refers to the middle of the candles which further de-noises the line.
The colors are green/red for good movement with the confirmed trend.
The colors are gray for movement against the current trend (signaling a possible mean reversion)
The colors blue & yellow appear when signaling possible chop or trend exhaustion.
Carried forward from the last time I posted this, the bias for longs and shorts is depicted as the color of the average line green or maroon, and ALERTS are based on that overall bias created the line by itself.
Also carried from the last post, the green and maroon clouds depict the price deviance from the line; when the cloud stretches wide it may be time to take profits and enter back in closer to the line.
Thanks again for liking and following!!!!
This share is in response to my 10,000th like on TradingView!
Favorite this one, and enjoy :-)
Examples of Rolling Average Using Automated AnchoringIn this study, I present a method to expose NaN values to development environment.
This exposure allows NaN values to be used by methods in scripts.
I also show how to use values, even NaN values, as anchors from which statistics can be computed from.
I demonstrate how to do this with constants and variables in methods for computing the cumulative/rolling average of a series.
I also show how to calculate the cumulative/rolling average from the start of a ticker series using the aforementioned methods.
Each method has a description on how some of their parts work as well as their constraints.
Method #1 - Can only be used for computing the rolling average on the ticker series.
Method #2 - The simple moving average from the Pine Script reference.
- Can be used to calculate the rolling average of the ticker series and number values of a series.
- This method seems to cause an error when there are many bars in the series.
Method #3 - The most versatile method due to the use of computing the rolling average using an array.
- Timeout will occur when computing the rolling average of an entire ticker series which is long.
- Timeout has not occurred when computing a rolling average of a series from NaN or non-NaN anchor points even when the series is long.
This is an attempt to get around the constraints of the built-in sma(source, length) function in which length cannot be dynamically adjusted.
Other Pine Script functions have that constraint which we can get around by defining our own functions.
Study - Mean Reversion Index© fareidzulkifli
Disclaimer:
I always felt Pinescript is a very fast to type language with excellent visualization capabilities, so I've been using it as code-testing platform prior to actual coding in other platform.
Having said that, these study scripts was built only to test/visualize an idea to see its viability and if it can be used to optimize existing strategy.
While some of it are useful and most are useless, none of it should be use as main decision maker.
Indicator title : Mean Reversion Index
Description : This index is based on theory that suggests that asset prices and historical returns eventually will revert to the long-run mean or average level of the entire dataset.
Please note that this indicator are not intended to establish a trend bias. It only tells how far the closing price is from the mean price in terms of ATR multiples,
e.g. The green zone indicates that the price is within 3 ATR (default setting) from the mean price.
One way to use it is to determine a safe entry zone to enter current trend from a pullback.
For example, after a sharp retracement during an uptrend, as long as it does not retraced beyond the low of the green zone, Chances are, price is only retraced to its mean value and its not a start of a new downtrend and now ready to continue the uptrend.
More aggressive method to use this is as indicator approaching the higher limit of yellow zone,
prices is to far from the mean and not sustainable, and we can start to look for counter trend opportunity as price reverse to its mean value.
Mean ExtremeA simple script that shows the distance from a the mean, expressed as a percentage.
Simple Moving Average, in this case.
Informational only.
Z-Score 'Bollinger Bands'The following script is an application of the Z-Score (previous script).
Z-Scores can be used in place of standard deviation (sigma) in 'Bollinger Bands'.
The average of the sample (x-bar) over 21 days (N)
21 average trading days per month, fixed value
The average of the population (mu) over 63 days (n)
63 days per quarter, default is set to 63
Z-Score is calculated by formula in previous script, and the absolute value is taken of "Z".
Z-High = absolute value of Z + (x-bar).
Z-Low = absolute value of Z - (x-bar).
Will update with Z from mu and Z from avg (working on UX and visualization details).
Z-Score The z-score is a way of counting the number of standard deviations between a given data value and the mean of the data set.
Z-score = (x̄ - μ) / (σ / √ n)
x̄ = sample mean (using the array.avg function = array(a,close ), where i = 1 to 21)
μ = population mean ( = avg(close, n))
σ = standard deviation of the population ( = stdev(close,n))
n = number of 'close' or trading day closes
n = input
... Note: The previous indicator is part of a larger series of indicators