MathHelpersLibrary "MathHelpers"
Overview
A collection of helper functions for designing indicators and strategies.
calculateATR(length, log)
Calculates the Average True Range (ATR) or Log ATR based on the 'log' parameter. Sans Wilder's Smoothing
Parameters:
length (simple int)
log (simple bool)
Returns: float The calculated ATR value. Returns Log ATR if `log` is true, otherwise returns standard ATR.
CDF(z)
Computes the Cumulative Distribution Function (CDF) for a given value 'z', mimicking the CDF function in "Statistically Sound Indicators" by Timothy Masters.
Parameters:
z (simple float)
Returns: float The CDF value corresponding to the input `z`, ranging between 0 and 1.
logReturns(lookback)
Calculates the logarithmic returns over a specified lookback period.
Parameters:
lookback (simple int)
Returns: float The calculated logarithmic return. Returns `na` if insufficient data is available.
Mathematics
Exponential Smoothing FilterThe digital exponential filter, in finance known as Exponential Moving Average (EMA) , can be used as a technical indicator for chart analysis to visualize uptrends and downtrends in the market. Unlike the classic simple moving average, the EMA requires only two values for its calculation: the last calculated exponential average price and the current price. This is a simple and fast calculation - even for wide smoothing windows. For further details and the math please refer to the "exponential smoothing" article on Wikipedia.
Here are some additional key points about the exponential moving average:
The EMA can react more quickly to price changes because it can give more weight to current prices - depending on your parameter settings.
Short-term, disruptive price fluctuations are smoothed out well, making prevailing trends more visible.
Despite good smoothing properties, it delays the input values slightly, so it can follow sudden trend changes well.
The EMA is well suited to dynamic markets and trading strategies.
The filter is a good basis for further processing such as gradient analysis.
How to use
When you add the script to your charts, you'll immediately see a thin orange line across your time series, smoothing out price fluctuations.
There are only two parameters to set
smoothing factor between 0.0000 = no smoothing and 0.9999 = strong smoothing
input source : open, high, low, close hl2, etc.
Chart output
In the example chart above, you can see that the orange line follows the highs and lows better than the blue line , which is a simple moving average (SMA).
Additionally, the orange line has a shorter lag, or reacts faster when the trend of the original price data suddenly changes. These characteristics are critical for buying and selling decisions: quickly reacting and tracking highs and lows while providing a smooth line that filters out distracting noise.
Trend AngleThe "Trend Angle" indicator serves as a tool for traders to decipher market trends through a methodical lens. It quantifies the inclination of price movements within a specified timeframe, making it easy to understand current trend dynamics.
Conceptual Foundation:
Angle Measurement: The essence of the "Trend Angle" indicator is its ability to compute the angle between the price trajectory over a defined period and the horizontal axis. This is achieved through the calculation of the arctangent of the percentage price change, offering a straightforward measure of market directionality.
Smoothing Mechanisms: The indicator incorporates options for "Moving Average" and "Linear Regression" as smoothing mechanisms. This adaptability allows for refined trend analysis, catering to diverse market conditions and individual preferences.
Functional Versatility:
Source Adaptability: The indicator affords the flexibility to select the desired price source, enabling users to tailor the angle calculation to their analytical framework and other indicators.
Detrending Capability: With the detrending feature, the indicator allows for the subtraction of the smoothing line from the calculated angle, highlighting deviations from the main trend. This is particularly useful for identifying potential trend reversals or significant market shifts.
Customizable Period: The 'Length' parameter empowers traders to define the observation window for both the trend angle calculation and its smoothing, accommodating various trading horizons.
Visual Intuition: The optional colorization enhances interpretability, with the indicator's color shifting based on its relation to the smoothing line, thereby providing an immediate visual cue regarding the trend's direction.
Interpretative Results:
Market Flatness: An angle proximate to 0 suggests a flat market condition, indicating a lack of significant directional movement. This insight can be pivotal for traders in assessing market stagnation.
Trending Market: Conversely, a relatively high angle denotes a trending market, signifying strong directional momentum. This distinction is crucial for traders aiming to capitalize on trend-driven opportunities.
Analytical Nuance vs. Simplicity:
While the "Trend Angle" indicator is underpinned by mathematical principles, its utility lies in its simplicity and interpretative clarity. However, it is imperative to acknowledge that this tool should be employed as part of a comprehensive trading strategy , complemented by other analytical instruments for a holistic market analysis.
In essence, the "Trend Angle" indicator exemplifies the harmonization of simplicity and analytical rigor. Its design respects the complexity of market behaviors while offering straightforward, actionable insights, making it a valuable component in the arsenal of both seasoned and novice traders alike.
Trig-Log Scaled Momentum OscillatorTaylor Series Approximations for Trigonometry:
1. The indicator starts by calculating sine and cosine values of the close price using Taylor Series approximations. These approximations use polynomial terms to estimate the values of these trigonometric functions.
Mathematical Component Formation:
2. The calculated sine and cosine values are then multiplied together. This gives us the primary mathematical component, termed as the 'trigComponent'.
Smoothing Process:
3. To ensure that our indicator is less susceptible to market noise and more reactive to genuine price movements, this 'trigComponent' undergoes a smoothing process using a simple moving average (SMA). The length of this SMA is defined by the user.
Logarithmic Transformation:
4. With our smoothed value, we apply a natural logarithm approximation. Again, this approximation is based on the Taylor expansion. This step ensures that all resultant values are positive and offers a different scale to interpret the smoothed component.
Dynamic Scaling:
5. To make our indicator more readable and comparable over different periods, the logarithmically transformed values are scaled between a range. This range is determined by the highest and lowest values of the transformed component over the user-defined 'lookback' period.
ROC (Rate of Change) Direction:
6. The direction of change in our scaled value is determined. This offers a quick insight into whether our mathematical component is increasing or decreasing compared to the previous value.
Visualization:
7. Finally, the indicator plots the dynamically scaled and smoothed mathematical component on the chart. The color of the plotted line depends on its direction (increasing or decreasing) and its boundary values.
Normal Distribution CurveThis Normal Distribution Curve is designed to overlay a simple normal distribution curve on top of any TradingView indicator. This curve represents a probability distribution for a given dataset and can be used to gain insights into the likelihood of various data levels occurring within a specified range, providing traders and investors with a clear visualization of the distribution of values within a specific dataset. With the only inputs being the variable source and plot colour, I think this is by far the simplest and most intuitive iteration of any statistical analysis based indicator I've seen here!
Traders can quickly assess how data clusters around the mean in a bell curve and easily see the percentile frequency of the data; or perhaps with both and upper and lower peaks identify likely periods of upcoming volatility or mean reversion. Facilitating the identification of outliers was my main purpose when creating this tool, I believed fixed values for upper/lower bounds within most indicators are too static and do not dynamically fit the vastly different movements of all assets and timeframes - and being able to easily understand the spread of information simplifies the process of identifying key regions to take action.
The curve's tails, representing the extreme percentiles, can help identify outliers and potential areas of price reversal or trend acceleration. For example using the RSI which typically has static levels of 70 and 30, which will be breached considerably more on a less liquid or more volatile asset and therefore reduce the actionable effectiveness of the indicator, likewise for an asset with little to no directional volatility failing to ever reach this overbought/oversold areas. It makes considerably more sense to look for the top/bottom 5% or 10% levels of outlying data which are automatically calculated with this indicator, and may be a noticeable distance from the 70 and 30 values, as regions to be observing for your investing.
This normal distribution curve employs percentile linear interpolation to calculate the distribution. This interpolation technique considers the nearest data points and calculates the price values between them. This process ensures a smooth curve that accurately represents the probability distribution, even for percentiles not directly present in the original dataset; and applicable to any asset regardless of timeframe. The lookback period is set to a value of 5000 which should ensure ample data is taken into calculation and consideration without surpassing any TradingView constraints and limitations, for datasets smaller than this the indicator will adjust the length to just include all data. The labels providing the percentile and average levels can also be removed in the style tab if preferred.
Additionally, as an unplanned benefit is its applicability to the underlying price data as well as any derived indicators. Turning it into something comparable to a volume profile indicator but based on the time an assets price was within a specific range as opposed to the volume. This can therefore be used as a tool for identifying potential support and resistance zones, as well as areas that mark market inefficiencies as price rapidly accelerated through. This may then give a cleaner outlook as it eliminates the potential drawbacks of volume based profiles that maybe don't collate all exchange data or are misrepresented due to large unforeseen increases/decreases underlying capital inflows/outflows.
Thanks to @ALifeToMake, @Bjorgum, vgladkov on stackoverflow (and possibly some chatGPT!) for all the assistance in bringing this indicator to life. I really hope every user can find some use from this and help bring a unique and data driven perspective to their decision making. And make sure to please share any original implementaions of this tool too! If you've managed to apply this to the average price change once you've entered your position to better manage your trade management, or maybe overlaying on an implied volatility indicator to identify potential options arbitrage opportunities; let me know! And of course if anyone has any issues, questions, queries or requests please feel free to reach out! Thanks and enjoy.
Source CorrelationIn this small indicator I make it possible for the user to set two different input sources. Then, the indicator displays the correlation of these two input sources. It's a very small script, but I think it could be helpful to somebody to find uncorrelated indicators for his trading strategy. To use uncorrelated indicators is in general recommended.
Enjoy this small, but powerful tool. 🧙♂️
Mad_MATHLibrary "MAD_MATH"
This is a mathematical library where I store useful kernels, filters and selectors for the different types of computations.
This library also contains opensource code from other scripters.
Future extensions are very likely, there are some functions I would like to add, but I have to wait for approvals so i can include them.
Ehlers_EMA(_src, _length)
Calculates the Ehlers Exponential Moving Average (Ehlers_EMA)
Parameters:
_src (float) : The source series for calculation
_length (simple int) : The length for the Ehlers EMA
Returns: The Ehlers EMA value
Ehlers_Gaussian(_src, _length)
Calculates the Ehlers Gaussian Filter
Parameters:
_src (float) : The source series for calculation
_length (simple int) : The length for the Ehlers Gaussian Filter
Returns: The Ehlers Gaussian Filter value
Ehlers_supersmoother(_src, _length)
Calculates the Ehlers Supersmoother
Parameters:
_src (float) : The source series for calculation
_length (simple int) : The length for the Ehlers Supersmoother
Returns: The Ehlers Supersmoother value
Ehlers_SMA_fast(_src, _length)
Calculates the Ehlers Simple Moving Average (SMA) Fast
Parameters:
_src (float) : The source series for calculation
_length (simple int) : The length for the Ehlers SMA Fast
Returns: The Ehlers SMA Fast value
Ehlers_EMA_fast(_src, _length)
Calculates the Ehlers Exponential Moving Average (EMA) Fast
Parameters:
_src (float) : The source series for calculation
_length (simple int) : The length for the Ehlers EMA Fast
Returns: The Ehlers EMA Fast value
Ehlers_RSI_fast(_src, _length)
Calculates the Ehlers Relative Strength Index (RSI) Fast
Parameters:
_src (float) : The source series for calculation
_length (simple int) : The length for the Ehlers RSI Fast
Returns: The Ehlers RSI Fast value
Ehlers_Band_Pass_Filter(_src, _length)
Calculates the Ehlers BandPass Filter
Parameters:
_src (float) : The source series for calculation
_length (simple int) : The length for the Ehlers BandPass Filter
Returns: The Ehlers BandPass Filter value
Ehlers_Butterworth(_src, _length)
Calculates the Ehlers Butterworth Filter
Parameters:
_src (float) : The source series for calculation
_length (simple int) : The length for the Ehlers Butterworth Filter
Returns: The Ehlers Butterworth Filter value
Ehlers_Two_Pole_Gaussian_Filter(_src, _length)
Calculates the Ehlers Two-Pole Gaussian Filter
Parameters:
_src (float) : The source series for calculation
_length (simple int) : The length for the Ehlers Two-Pole Gaussian Filter
Returns: The Ehlers Two-Pole Gaussian Filter value
Ehlers_Two_Pole_Butterworth_Filter(_src, _length)
Calculates the Ehlers Two-Pole Butterworth Filter
Parameters:
_src (float) : The source series for calculation
_length (simple int) : The length for the Ehlers Two-Pole Butterworth Filter
Returns: The Ehlers Two-Pole Butterworth Filter value
Ehlers_Band_Stop_Filter(_src, _length)
Calculates the Ehlers Band Stop Filter
Parameters:
_src (float) : The source series for calculation
_length (simple int) : The length for the Ehlers Band Stop Filter
Returns: The Ehlers Band Stop Filter value
Ehlers_Smoother(_src)
Calculates the Ehlers Smoother
Parameters:
_src (float) : The source series for calculation
Returns: The Ehlers Smoother value
Ehlers_High_Pass_Filter(_src, _length)
Calculates the Ehlers High Pass Filter
Parameters:
_src (float) : The source series for calculation
_length (simple int) : The length for the Ehlers High Pass Filter
Returns: The Ehlers High Pass Filter value
Ehlers_2_Pole_High_Pass_Filter(_src, _length)
Calculates the Ehlers Two-Pole High Pass Filter
Parameters:
_src (float) : The source series for calculation
_length (simple int) : The length for the Ehlers Two-Pole High Pass Filter
Returns: The Ehlers Two-Pole High Pass Filter value
pr(_src, _length)
pr Calculates the percentage rank (PR) of a value within a range.
Parameters:
_src (float) : The source value for which the percentage rank is calculated. It represents the value to be ranked within the range.
_length (simple int) : The _length of the range over which the percentage rank is calculated. It determines the number of bars considered for the calculation.
Returns: The percentage rank (PR) of the source value within the range, adjusted by adding 50 to the result.
smma(_src, _length)
Calculates the SMMA (Smoothed Moving Average)
Parameters:
_src (float) : The source series for calculation
_length (simple int)
Returns: The SMMA value
hullma(_src, _length)
Calculates the Hull Moving Average (HullMA)
Parameters:
_src (float) : The source series for calculation
_length (simple int) : The _length of the HullMA
Returns: The HullMA value
tma(_src, _length)
Calculates the Triple Moving Average (TMA)
Parameters:
_src (float) : The source series for calculation
_length (simple int) : The _length of the TMA
Returns: The TMA value
dema(_src, _length)
Calculates the Double Exponential Moving Average (DEMA)
Parameters:
_src (float) : The source series for calculation
_length (simple int) : The _length of the DEMA
Returns: The DEMA value
tema(_src, _length)
Calculates the Triple Exponential Moving Average (TEMA)
Parameters:
_src (float) : The source series for calculation
_length (simple int) : The _length of the TEMA
Returns: The TEMA value
w2ma(_src, _length)
Calculates the Normalized Double Moving Average (N2MA)
Parameters:
_src (float) : The source series for calculation
_length (simple int) : The _length of the N2MA
Returns: The N2MA value
wma(_src, _length)
Calculates the Normalized Moving Average (NMA)
Parameters:
_src (float) : The source series for calculation
_length (simple int) : The _length of the NMA
Returns: The NMA value
nma(_open, _close, _length)
Calculates the Normalized Moving Average (NMA)
Parameters:
_open (float) : The open price series
_close (float) : The close price series
_length (simple int) : The _length for finding the highest and lowest values
Returns: The NMA value
lma(_src, _length)
Parameters:
_src (float)
_length (simple int)
zero_lag(_src, _length, gamma1, zl)
Calculates the Zero Lag Moving Average (ZeroLag)
Parameters:
_src (float) : The source series for calculation
_length (simple int) : The length for the moving average
gamma1 (simple int) : The coefficient for calculating 'd'
zl (simple bool) : Boolean flag for applying Zero Lag
Returns: An array containing the ZeroLag Moving Average and a boolean flag indicating if it's flat
copyright HPotter, thanks for that great function
chebyshevI(src, len, ripple)
Calculates the Chebyshev Type I Filter
Parameters:
src (float) : The source series for calculation
len (int) : The length of the filter
ripple (float) : The ripple factor for the filter
Returns: The output of the Chebyshev Type I Filter
math from Pafnuti Lwowitsch Tschebyschow (1821–1894)
Thanks peacefulLizard50262 for the find and translation
chebyshevII(src, len, ripple)
Calculates the Chebyshev Type II Filter
Parameters:
src (float) : The source series for calculation
len (int) : The length of the filter
ripple (float) : The ripple factor for the filter
Returns: The output of the Chebyshev Type II Filter
math from Pafnuti Lwowitsch Tschebyschow (1821–1894)
Thanks peacefulLizard50262 for the find
wavetrend(_src, _n1, _n2)
Calculates the WaveTrend indicator
Parameters:
_src (float) : The source series for calculation
_n1 (simple int) : The period for the first EMA calculation
_n2 (simple int) : The period for the second EMA calculation
Returns: The WaveTrend value
f_getma(_type, _src, _length, ripple)
Calculates various types of moving averages
Parameters:
_type (simple string) : The type of indicator to calculate
_src (float) : The source series for calculation
_length (simple int) : The length for the moving average or indicator
ripple (simple float)
Returns: The calculated moving average or indicator value
f_getfilter(_type, _src, _length)
Calculates various types of filters
Parameters:
_type (simple string) : The type of indicator to calculate
_src (float) : The source series for calculation
_length (simple int) : The length for the moving average or indicator
Returns: The filtered value
f_getoszillator(_type, _src, _length)
Calculates various types of Deviations and other indicators
Parameters:
_type (simple string) : The type of indicator to calculate
_src (float) : The source series for calculation
_length (simple int) : The length for the moving average or indicator
Returns: The calculated moving average or indicator value
Premium Linear Regression - The Quant ScienceThis script calculates the average deviation of the source data from the linear regression. When used with the indicator, it can plot the data line and display various pieces of information, including the maximum average dispersion around the linear regression.
The code includes various user configurations, allowing for the specification of the start and end dates of the period for which to calculate linear regression, the length of the period to use for the calculation, and the data source to use.
The indicator is designed for multi-timeframe use and to facilitate analysis for traders who use regression models in their analysis. It displays a green linear regression line when the price is above the line and a red line when the price is below. The indicator also highlights areas of dispersion around the regression using circles, with bullish areas shown in green and bearish areas shown in red.
Quantitative Price Forecasting - The Quant ScienceThis script is a quantitative price forecasting indicator that forecasts price changes for a given asset.
The model aims to forecast future prices by analyzing past data within a selected time period. Mathematical probability is used to calculate whether starting from time X can lead to reaching prices Y1 and Y2. In this context, X represents the current selected time period, Y1 represents the selected percentage decrease, and Y2 represents the selected percentage increase. The probabilities are estimated using the simple average.
The simple average is displayed on the chart, showing in red the periods where the price is below the average and in green the periods where the price is above the average.
This powerful tool not only provides forecasts of future prices but also calculates the distribution of variations around the average. It then takes this information and creates an estimate of the average price variation around the simple average.
Using a mean-reverting logic, buying and selling opportunities are highlighted.
We recommend turning off the display of bars on your chart for a better experience when using this indicator.
Unlock the full potential of your trading strategy with our powerful indicator. By analyzing past price data, it provides accurate forecasts and calculates the probability of reaching specific price targets. Its mean-reverting logic highlights buying and selling opportunities, while the simple moving average displayed on the chart shows periods where the price is above or below the average. Additionally, it estimates the average variation of price around the simple average, giving you valuable insights into price movements. Don't miss out on this valuable tool that can take your trading to the next level
Reinforced RSI - The Quant Science This strategy was designed and written with the goal of showing and motivating the community how to integrate our 'Probabilities' module with their own script.
We have recreated one of the simplest strategies used by many traders. The strategy only trades long and uses the overbought and oversold levels on the RSI indicator.
We added stop losses and take profits to offer more dynamism to the strategy. Then the 'Probabilities' module was integrated to create a probabilistic reinforcement on each trade.
Specifically, each trade is executed, only if the past probabilities of making a profitable trade is greater than or equal to 51%. This greatly increased the performance of the strategy by avoiding possible bad trades.
The backtesting was calculated on the NASDAQ:TSLA , on 15 minutes timeframe.
The strategy works on Tesla using the following parameters:
1. Lenght: 13
2. Oversold: 40
3. Overbought: 70
4. Lookback: 50
5. Take profit: 3%
6. Stop loss: 3%
Time period: January 2021 to date.
Our Probabilities Module, used in the strategy example:
xor logical operatorLibrary "xor"
xor(a, b)
xor: Exclusive or, or exclusive disjunction is a logical operation that is true if and only if its arguments differ (one is true, the other is false).
Parameters:
a : first argument
b : second argument
Returns: returns xor (true only if a and b are true, but not both)
Example:
true xor true = false
true xor false = true
false xor true = true
false xor false = false
iCryptoScalperHi everyone!
In this post I would like to present my personal indicator for short-term strategies on cryptocurrencies called iCryptoScalper , but let me first introduce myself:
I am a theoretical physicist with a deep passion for trading and mathematical modelling of the financial markets.
I started trading cryptocurrencies more than 4 years ago and, throughout this period, I got more and more involved in trying to describe the mechanisms governing
the price action at lower timeframes like 1, 5 and 15 minutes.
As a beginner, I started with the usual "buy and hold" strategy, the safest but also boring option. Afterthat, I tried to get more involved on speed trading
and scalping and, as it happens to all the beginners, I went through many mistakes.
At the beginning, trying to find the best scalping strategy, was a very difficult task and I barely managed to perform well, mostly because every trade were overwhelmed
by my emotional approach and the fear of missing the right entry point and/or exit point. However, thanks to these difficulties, I understood that I needed
an algorithmic procedure to improve my performances and overtake the emotional approach, with a more technical approach: a mathematical guide that precisely tells me how to behave in the best way possible to be profitable.
To achieve this goal, I put all my efforts in trying to write a consistent mathematical model able to give me all the statistical informations I needed to reach
the best performances and, of course, the best possible profits.
The iCryptoScalper is an explicit mathematical tool to be used for scalping strategies and optimized for different cryptocurrency pairs on 15/30 min timeframes.
The script gives you many useful informations and details regarding the current and subsequent trade, accompanied with a detailed overview on both the last 20 short
and long trade results.
Let us have a look to all the detailed informations the script shows to you:
CHART
- Lines: The script plots for you the Entry price (yellow line), the Stop Loss price (red line) and a series of 8 Take Profit levels (green lines).
- Background: The green background color indicates that the script is in a long position, viceversa, the red background color indicates that the script is in a short position.
- Labels: The blue labels indicate the maximum achieved profit for each trade.
- Alerts: The script shows two types of alerts, the "prepare to #" one and the true entry one. The prepare alert is very useful to understand when the strategy is going
to enter a specific trade, thus giving you the possibility to set up all the necessary Entry/SL/TP levels on your favorite trading platform.
- Crosses: The green and red crosses are precisely located at the corresponding long and short entry price for the next trade, thus giving you a preview on the target price
that has to be reached for the indicator to enter. They are computed thanks to a mathematical model I set up and optimized for each cryptocurrency pair.
PANEL
- Overview: This part shows you two probability tables for the last 20 long and short trades each. The first table indicates the set of probabilities of reaching the corresponding TP level, whereas the second table shows the conditional probability , namely the probability of reaching a certain profit level once the previous one has been achieved.
Below the tables you can find three quantities again referring to the last 20 long and short trades: the Average Maximum Profit , the Average Maximum Drawdown and the Average Risk/Reward Ratio .
Last but not least, the correlation between the current asset and BTC is displayed together with the current BTC status.
- Active Trade: This part collects all the data related to the current trade status.
- Next Trade: This part collects all the data related to the next trade status.
ATTENTION!
Please notice that the equity line you see in the "Strategy Tester" section of TradingView is unreliable compared to the real performances of the script. This is due to the
fact that the TradingView engine is designed for backtesting automatic trading strategies and not real-time trading bots.
An example is the following: Bob buys 1 BTC-PERP contract at 10000$, setting the Stop Loss at 9000$. The price of the perpetual then goes to 12000$ and then go back hitting the Stop Loss. For the TradingView Engine this is a
trade with a permanent loss of 1000$. However, for the iCryptoScalper users, the trade is perfectly fine thanks to the numerous TP levels (and corresponding probabilities) given by the script within the trade window.
STDev BandsReally simple script for dynamic support and resistance. Takes means over last 1440 bars (1440 minutes in a day) and calculates seven stdevs up and down.
LibraryPrivateUsage001This is a public library that include the functions explained below. The libraries are considered public domain code and permission is not required from the author if you reuse these functions in your open-source scripts
Prime Number CheckerThis is not a foolproof method for finding every prime number but will work well on assets $10 to $100. I will be working on something more robust with scaling for all assets. If you want a main pane indicator with just the background coloring keep the indicator as it is. If you want a lower pane indicator get rid of the current study function and replace with the commented out study function by deleting the //. Also comment in line 28 also by deleting the //. Prime numbers are an excellent natural mathematical site of reversal and you will begin to see this as you work with them.
Any questions don't be scared to ask.
Eliza.
Pinbar-Rejection-IndicatorThis indicator allows you to filter noisy pin bar chart, with pin bars which have been rejected from dynamic support/resistance level also named as 21 Moving Average.
I would consider to work only on higher time frames like 1H and higher, so you really can find only best entries.
Have fun, write your feedback in the comments section:)
P.S This is the first version of the indicator, so be free to contribute, and soon I'm going to improve this indicator.
Matrix Library (Linear Algebra, incl Multiple Linear Regression)What's this all about?
Ever since 1D arrays were added to Pine Script, many wonderful new opportunities have opened up. There has been a few implementations of matrices and matrix math (most notably by TradingView-user tbiktag in his recent Moving Regression script: ). However, so far, no comprehensive libraries for matrix math and linear algebra has been developed. This script aims to change that.
I'm not math expert, but I like learning new things, so I took it upon myself to relearn linear algebra these past few months, and create a matrix math library for Pine Script. The goal with the library was to make a comprehensive collection of functions that can be used to perform as many of the standard operations on matrices as possible, and to implement functions to solve systems of linear equations. The library implements matrices using arrays, and many standard functions to manipulate these matrices have been added as well.
The main purpose of the library is to give users the ability to solve systems of linear equations (useful for Multiple Linear Regression with K number of independent variables for example), but it can also be used to simulate 2D arrays for any purpose.
So how do I use this thing?
Personally, what I do with my private Pine Script libraries is I keep them stored as text-files in a Libraries folder, and I copy and paste them into my code when I need them. This library is quite large, so I have made sure to use brackets in comments to easily hide any part of the code. This helps with big libraries like this one.
The parts of this script that you need to copy are labeled "MathLib", "ArrayLib", and "MatrixLib". The matrix library is dependent on the functions from these other two libraries, but they are stripped down to only include the functions used by the MatrixLib library.
When you have the code in your script (pasted somewhere below the "study()" call), you can create a matrix by calling one of the constructor functions. All functions in this library start with "matrix_", and all constructors start with either "create" or "copy". I suggest you read through the code though. The functions have very descriptive names, and a short description of what each function does is included in a header comment directly above it. The functions generally come in the following order:
Constructors: These are used to create matrices (empy with no rows or columns, set shape filled with 0s, from a time series or an array, and so on).
Getters and setters: These are used to get data from a matrix (like the value of an element or a full row or column).
Matrix manipulations: These functions manipulate the matrix in some way (for example, functions to append columns or rows to a matrix).
Matrix operations: These are the matrix operations. They include things like basic math operations for two indices, to transposing a matrix.
Decompositions and solvers: Next up are functions to solve systems of linear equations. These include LU and QR decomposition and solvers, and functions for calculating the pseudo-inverse or inverse of a matrix.
Multiple Linear Regression: Lastly, we find an implementation of a multiple linear regression, including all the standard statistics one can expect to find in most statistical software packages.
Are there any working examples of how to use the library?
Yes, at the very end of the script, there is an example that plots the predictions from a multiple linear regression with two independent (explanatory) X variables, regressing the chart data (the Y variable) on these X variables. You can look at this code to see a real-world example of how to use the code in this library.
Are there any limitations?
There are no hard limiations, but the matrices uses arrays, so the number of elements can never exceed the number of elements supported by Pine Script (minus 2, since two elements are used internally by the library to store row and column count). Some of the operations do use a lot of resources though, and as a result, some things can not be done without timing out. This can vary from time to time as well, as this is primarily dependent on the available resources from the Pine Script servers. For instance, the multiple linear regression cannot be used with a lookback window above 10 or 12 most of the time, if the statistics are reported. If no statistics are reported (and therefore not calculated), the lookback window can usually be extended to around 60-80 bars before the servers time out the execution.
Hopefully the dev-team at TradingView sees this script and find ways to implement this functionality diretly into Pine Script, as that would speed up many of the operations and make things like MLR (multiple linear regression) possible on a bigger lookback window.
Some parting words
This library has taken a few months to write, and I have taken all the steps I can think of to test it for bugs. Some may have slipped through anyway, so please let me know if you find any, and I'll try my best to fix them when I have time to do so. This library is intended to help the community. Therefore, I am releasing the library as open source, in the hopes that people may improving on it, or using it in their own work. If you do make something cool with this, or if you find ways to improve the code, please let me know in the comments.
[JRL] Murrey Math LinesMurrey Math Lines are support and resistance lines based on geometric mathematical formulas developed by T.
H. Murrey. MM lines are a derivation of the observations of W.D. Gann. Murrey's geometry facilitate the use of Gann's theories in a somewhat easier application. According to Gann's theory, price tends to trend and retrace in 1/8th intervals. The most important MM line levels are the 0/8, 4/8 and 8/8 levels, which typically provide strong support and resistance points. The 3/8 and 5/8 levels represent the low and high of the typical trading range. When price is above the typical trading range, it is considered overbought, and when it is below it is considered oversold. The 2/8 and 6/8 levels provide strong pivot points.
Some of the other Murrey Math indicators on TradingView use different formulas and therefore produce varying results. I've checked my indicator against MM indicators on other platforms and it is consistent with those indicators.
This indicator also allows users to switch to alternative timeframes for analysis and it includes labels for the MM lines. If you have any suggestions or comments, please leave them below.
Cheers!
Newton Force and MomentumThis indicator is meant to show the Force of price, based on Newton's Second Law of Motion; and the momentum of price. Force is the value on the left, and momentum on the right.
Originally this was supposed to only be an indicator looking at Force, but because the already popular indicator called "Momentum" does not calculate the momentum of price, but rather the change of price depending on how far back you want to look; I decided to add the Momentum aspect to the indicator.
*BTW if you find this script useful thank and follow @overttherainbow, because they are the one who gave me the idea for this script.*