Bar Move Probability (BMP)Hello fellow traders! I am excited to share with you my latest creation, the Bar Move Probability (BMP) indicator. This powerful tool is designed to give you a statistical edge in your trading by helping you understand the likelihood of price movements based on historical data. In this blog post, I'll give you an overview of the indicator, its features, and how it can help you make more informed trading decisions. Let's dive in!
What is the Bar Move Probability Indicator?
The Bar Move Probability (BMP) indicator is a unique tool that calculates the probability of a bar's price movement, either up or down, based on past occurrences of similar price movements. This can give you valuable insights into the potential direction of the market, allowing you to make better-informed trading decisions.
One of the key features of the BMP indicator is that it allows you to choose the price you want to determine the probability of. By inputting your desired price, the indicator will analyze historical data and provide you with the likelihood of reaching that price, offering a more personalized approach to trading.
How Does the BMP Indicator Work?
The BMP indicator calculates the probability of a bar's price movement by comparing the current price change (in percentage) to historical price changes. It does this by maintaining separate arrays for green (bullish) and red (bearish) price movements, as well as corresponding arrays for the count of each movement.
Whenever a new bar is formed, the indicator checks whether the price movement (in percentage) is already present in the respective array. If it is, the corresponding count is updated. Otherwise, a new entry is added to the array, with an initial count of 1.
After analyzing the historical data, the BMP indicator calculates the probability of each price movement by dividing the count of each movement by the sum of all counts. These probabilities are then stored in separate arrays for green and red movements.
Finally, the indicator displays the probability of the current price movement as a label on the chart. The label is color-coded, with green indicating a bullish price movement and red indicating a bearish price movement.
How Can the BMP Indicator Benefit Your Trading?
The primary benefit of the BMP indicator is its ability to provide you with a statistical edge in your trading. By analyzing historical price data, the indicator helps you understand the likelihood of a certain price movement occurring, allowing you to make more informed decisions about your trades.
The customizable nature of the BMP indicator, allowing you to input your desired price, makes it a valuable tool for traders with specific price targets in mind. By understanding the probability of reaching your target price, you can better manage your risk and optimize your trading strategy.
For example, suppose the BMP indicator shows a high probability of a bullish price movement towards your target price. In that case, you may consider entering a long position or tightening your stop loss on an existing short position. Conversely, if the indicator displays a high probability of a bearish price movement away from your target price, you may consider entering a short position or taking profit on an existing long position.
The BMP indicator can be used in conjunction with other technical analysis tools and indicators to further strengthen your trading strategy. For example, you can combine the BMP indicator with support and resistance levels, trend lines, and moving averages to better time your entries and exits.
Wrapping Up
In conclusion, the Bar Move Probability (BMP) indicator is a powerful and customizable tool that can help you gain a statistical edge in your trading. By analyzing historical price data and allowing you to input your desired price, the indicator provides valuable insights into the likelihood of price movements, enabling you to make better-informed trading decisions.
I hope you find the BMP indicator useful
Statistics
Arbitrary Price Point Probability (APPP)The "Arbitrary Price Point Probability" indicator is designed to calculate the probability of a given price point occurring within a certain range of prices. The indicator uses statistical analysis to determine the likelihood of a specific price point appearing based on the market data.
The indicator works by taking the input price, which is the price point for which the probability is being calculated. The indicator then calculates the mean and standard deviation of the prices over a certain period specified by the user. The length of the period for calculating the mean and standard deviation is also specified by the user.
Once the mean and standard deviation have been calculated, the indicator uses them to calculate the probability of the input price point occurring within the range of prices over the specified period. The indicator does this by calculating the z-score, which is the number of standard deviations between the input price point and the mean price. The z-score is then used to calculate the probability using a t-distribution probability density function.
The t-distribution probability density function used by the indicator is a mathematical function that describes the likelihood of obtaining a particular value from a t-distribution. A t-distribution is a statistical distribution used when the sample size is small, and the population standard deviation is unknown.
The indicator also uses a binary search algorithm to find the t-value for a given confidence level. The t-value is the number of standard deviations from the mean at which the confidence interval is set. The confidence level is set by the user, and the default value is 99%.
Overall, the "Arbitrary Price Point Probability" indicator is a useful tool for traders who want to determine the probability of a particular price point occurring within a certain range of prices. The indicator can be used in conjunction with other technical analysis tools to make more informed trading decisions.
Intrabar Run Count Indicator [tbiktag]• OVERVIEW
Introducing the Intrabar Run Count Indicator , a tool designed to detect potential non-randomness in intrabar price data. It utilizes the statistical runs test to examine the number of sequences ( runs ) of positive and negative returns in the analyzed price series. As deviations from random-walk behavior of returns may indicate market inefficiencies , the Intrabar Run Count Indicator can help traders gain a better understanding of the price dynamics inside each chart bar and make more informed trading decisions.
• USAGE
The indicator line expresses the deviation between the number of runs observed in the dataset and the expected number of runs under the hypothesis of randomness. Thus, it gauges the degree of deviation from random-walk behavior. If, for a given chart bar, it crosses above the critical value or crosses below the negative critical value, this may indicate non-randomness in the underlying intrabar returns. These instances are highlighted by on-chart signals and bar coloring. The confidence level that defines the critical value, as well as the number of intrabars used for analysis, are selected in the input settings.
It is important to note that the readings of the Intrabar Run Count Indicator do not convey directional information and cannot predict future asset performance. Rather, they help distinguish between random and potentially tradable price movements, such as breakouts, reversals, and gap fillings.
• DETAILS
The efficient-market hypothesis implies that the distribution of returns should be random, reflecting the idea that all available information is already priced into the asset. However, in practice, financial markets may not always be perfectly efficient due to factors such as market frictions, information asymmetry, and irrational behavior of market participants. As a result, inefficiency (non-randomness) can occur, potentially creating opportunities for trading strategies.
To search for potential inefficiencies, the Intrabar Run Count Indicator analyzes the distribution of the signs of returns. The central assumption underlying the indicator's logic is that if the asset price follows a random-walk pattern, then the probability of the next return being positive or negative (i.e., the next price value being larger or smaller than the current value) follows a binomial distribution. In this case, the number of runs is also a random variable, and, for a large sample, its conditional distribution is approximately normal with a well-defined mean and variance (see this link for the exact expressions). Thus, the observed number of runs in the price series is indicative of whether or not the time series can be regarded as random. In simple words, if there are too few runs or too many runs, it is unlikely a random time series. A trivial example is a series with all returns of the same sign.
Quantitatively, the deviation from randomness can be gauged by calculating the test statistic of the runs test (that serves as an indicator line ). It is defined as the absolute difference between the observed number of runs and the expected number of runs under the null hypothesis of randomness, divided by the standard deviation of the expected number of runs. If the test statistic is negative and exceeds the negative critical value (at a given confidence level), it suggests that there are fewer runs than expected for a random-walking time series. Likewise, if the test statistic exceeds the positive critical value, it is indicative of more runs than expected for a random series. The sign of the test statistic can also be informative, as too few runs can be sometimes indicative of mean-reverting behavior.
• CONCLUSION
The Intrabar Run Count Indicator can be a useful tool for traders seeking to exploit market inefficiencies and gain a better understanding of price action within each chart bar. However, it is important to note that the runs test only evaluates the distributional properties of the data and does not provide any information on the underlying causes of the non-randomness detected. Additionally, like any statistical test, it can sometimes produce false-positive signals. Therefore, this indicator should be used in conjunction with other analytical techniques as part of a trading strategy.
TradeBee Percent Gap AlertA simple script to enable adding a trigger when a stock reaches 'X' percent, the 'X' can be configured.
The script also displays current tickers gap %, this is particularly helpful when you have 2 or more panels on a chart
Strategy DesignerHello traders.
Thanks to the tool I have published, everyone who knows or does not know coding will be able to create strategies and see the results instantly on the screen. Yes it looks very nice :)
What does this script do?
Thanks to this tool, even if you don't know any coding, you will be able to create your own strategies. You can add and remove indicators.
Entrance
The first thing you need to do is to set a strategy in your mind.
Then you need to adjust the settings of the indicators installed in the system. Please set the indicators first, because later they are forgotten.
The screen for entering the parameters of the indicators will be as follows.
After entering the parameters there is an important part . In this section, we can adjust the strategy settings.
First we choose between which dates we want the strategy to run. We then choose whether we want the strategy results to be displayed in a table or not.
We choose how the Terms should be linked together. For example, if you have a condition that is expected to produce more than one receive signal, select whether these conditions are connected to each other with and or with the connector.
In this way, you can determine whether all or any of the rules in your strategy should apply.
Next, we choose whether our strategy will work in the spot market or in a bidirectional market. Yes, you can design a strategy for both spot and bidirectional trades :)
At the bottom of the above image, we see a screen where we can adjust the stop level and tp level. As a standard, adjustments are made according to the percentage level you enter. However, if you remove the tick next to the percent sign, the previous stop level and the next profit level are determined as much as the value you entered.
At the bottom is the trailing stop. When you open the trailing stop, the trailing stop becomes active in your strategy.
Very important, when the trailing stop and the stop are active at the same time, the trailing stop value is valid.
It's time to design our strategy. Each chapter that begins with an exclamation point is a separate fiction.
If you do not mark the Active button, that condition will not be included in the calculation.
Direction = It is the direction for which the fiction in this region is valid.
We came to the indicator setting screen. Here, there is a screen where we can select two different indicators on the right and left.
We choose the first indicator starting with 1.
Then we choose from the middle region how we want these two indicators to interact.
We choose our second indicator from the place starting with 2.
If you want an indicator to interact with any value, tick the box where it says Value and fill in the value in the blank. When Value is ticked, the second indicator does not work.
COT-index rangeA graph showing the commercials (part of COT-data) positioning in relation to its own range, X periods back. I usually choose the look-back period to equal approximately one year. This will be around 52 on a weekly chart and 250 on a daily chart.
In my opinion a high data-point for the commercials is bullish and vice versa. But instead of only looking att absolute values I now look more at how the commercials are positioned compared to the previous 12 och 6 months.
Example:
a) if COT-index range = 0.8, then the commercials are in the 80th percentile for this specific look-back period, i.e. the commercials has only been more bullish 20% of the time and more bearish 80% of the time.
b) a) if COT-index range = 0.5, then the commercials are in the 50th percentile for this specific look-back period, i.e. the commercials has been more bullish 50% of the time and more bearish 50% of the time.
c) if COT-index range = 0.2, then the commercials are in the 20th percentile for this specific look-back period, i.e. the commercials has been more bullish 80% of the time and more bearish 20% of the time.
In other words, a high reading is bullish and a low reading is bearish.
Global LiquidityThe "Global Liquidity" script is an indicator that calculates and displays the global liquidity value using a formula that takes into account the money supply of several major economies. The script utilizes data from various sources, such as the Federal Reserve Economic Data (FRED), Economics, and FX_IDC.
The indicator plots the global liquidity value as a candlestick chart and breaks it down into two categories: the Euro-Atlantic region (West) and the rest of the world (East). The values are denominated both in inflation-adjusted dollars and in trillions of dollars. The script also calculates the spread between the Euro-Atlantic region and the rest of the world.
Traders and investors can use this indicator to gauge the overall liquidity of the global economy and to identify potential investment opportunities or risks. By breaking down the liquidity value into different regions, traders can also gain insights into regional economic trends and dynamics.
Note that this script is subject to the terms of the Mozilla Public License 2.0 and was created by rodopacapital.
UtilityLibrary "Utility"
dema(src, length)
Parameters:
src (float)
length (simple int)
tema(src, length)
Parameters:
src (float)
length (simple int)
hma(src, length)
Parameters:
src (float)
length (int)
zlema(src, length)
Parameters:
src (float)
length (simple int)
stochRSI(src, lengthRSI, lengthStoch, smoothK, smoothD)
Parameters:
src (float)
lengthRSI (simple int)
lengthStoch (int)
smoothK (int)
smoothD (int)
slope(src, length)
Parameters:
src (float)
length (int)
Days in rangeThis script is a little widget that I made to do some homework on the VIX.
As you can see in the chart I was analyzing the 2008 market crash and the stats that followed it after until the market started to recover.
You can see that theory in my "Ideas" tab.
This is an interactive set of lines that you can use to count the the bars inside and outside of your chosen range, and the percentage outside that range.
You should initially enter the price range of your product in the menu and set some arbitrary dates that you can easily see on your chart.
Drag and drop the lines around to suit what price and the dates you are analyzing.
The table will display the bar count inside and outside of the range, the total bars, and the percentage outside that range.
I personally used this as a tool to study the overall average of the product, compared with the behavior during major market events.
It is currently my opinion that post 2020 analysis needs to take into account the behavior of any given product prior to 2020 when the
VIX was in its comfort zone. Not to say that a price valuation hasn't been set, but that the movement to that price was outside of "Normal Market Conditions,"
and the time factor to return to that value might be skewed. Other factors would need to be considered at that point pertaining to your specific product or corelating indicator.
I could see this tool being useful to Forex and commodities traders. But that isn't my field so that that for what it is. I do think it would perform best on something that is more
pegged to a price range. I personally would use it on product's, like the VIX, that I use as an indicator product. That is what it was designed for.
But I suppose it could be used for Mean price and time related analysis, maybe with a Vwap, SMA or other breakout style indicators.
Volume analysis might be pretty sporty. Possibly time patterns... the possibilities could be endless. Or... limited.
I am publishing this for my trade group so that it can be tinkered with to find other helpful ways to use it.
If anyone finds something interesting with other indicators, please drop a comment below and I could consider creating a script to integrate with this tool.
loxxfftLibrary "loxxfft"
This code is a library for performing Fast Fourier Transform (FFT) operations. FFT is an algorithm that can quickly compute the discrete Fourier transform (DFT) of a sequence. The library includes functions for performing FFTs on both real and complex data. It also includes functions for fast correlation and convolution, which are operations that can be performed efficiently using FFTs. Additionally, the library includes functions for fast sine and cosine transforms.
Reference:
www.alglib.net
fastfouriertransform(a, nn, inversefft)
Returns Fast Fourier Transform
Parameters:
a (float ) : float , An array of real and imaginary parts of the function values. The real part is stored at even indices, and the imaginary part is stored at odd indices.
nn (int) : int, The number of function values. It must be a power of two, but the algorithm does not validate this.
inversefft (bool) : bool, A boolean value that indicates the direction of the transformation. If True, it performs the inverse FFT; if False, it performs the direct FFT.
Returns: float , Modifies the input array a in-place, which means that the transformed data (the FFT result for direct transformation or the inverse FFT result for inverse transformation) will be stored in the same array a after the function execution. The transformed data will have real and imaginary parts interleaved, with the real parts at even indices and the imaginary parts at odd indices.
realfastfouriertransform(a, tnn, inversefft)
Returns Real Fast Fourier Transform
Parameters:
a (float ) : float , A float array containing the real-valued function samples.
tnn (int) : int, The number of function values (must be a power of 2, but the algorithm does not validate this condition).
inversefft (bool) : bool, A boolean flag that indicates the direction of the transformation (True for inverse, False for direct).
Returns: float , Modifies the input array a in-place, meaning that the transformed data (the FFT result for direct transformation or the inverse FFT result for inverse transformation) will be stored in the same array a after the function execution.
fastsinetransform(a, tnn, inversefst)
Returns Fast Discrete Sine Conversion
Parameters:
a (float ) : float , An array of real numbers representing the function values.
tnn (int) : int, Number of function values (must be a power of two, but the code doesn't validate this).
inversefst (bool) : bool, A boolean flag indicating the direction of the transformation. If True, it performs the inverse FST, and if False, it performs the direct FST.
Returns: float , The output is the transformed array 'a', which will contain the result of the transformation.
fastcosinetransform(a, tnn, inversefct)
Returns Fast Discrete Cosine Transform
Parameters:
a (float ) : float , This is a floating-point array representing the sequence of values (time-domain) that you want to transform. The function will perform the Fast Cosine Transform (FCT) or the inverse FCT on this input array, depending on the value of the inversefct parameter. The transformed result will also be stored in this same array, which means the function modifies the input array in-place.
tnn (int) : int, This is an integer value representing the number of data points in the input array a. It is used to determine the size of the input array and control the loops in the algorithm. Note that the size of the input array should be a power of 2 for the Fast Cosine Transform algorithm to work correctly.
inversefct (bool) : bool, This is a boolean value that controls whether the function performs the regular Fast Cosine Transform or the inverse FCT. If inversefct is set to true, the function will perform the inverse FCT, and if set to false, the regular FCT will be performed. The inverse FCT can be used to transform data back into its original form (time-domain) after the regular FCT has been applied.
Returns: float , The resulting transformed array is stored in the input array a. This means that the function modifies the input array in-place and does not return a new array.
fastconvolution(signal, signallen, response, negativelen, positivelen)
Convolution using FFT
Parameters:
signal (float ) : float , This is an array of real numbers representing the input signal that will be convolved with the response function. The elements are numbered from 0 to SignalLen-1.
signallen (int) : int, This is an integer representing the length of the input signal array. It specifies the number of elements in the signal array.
response (float ) : float , This is an array of real numbers representing the response function used for convolution. The response function consists of two parts: one corresponding to positive argument values and the other to negative argument values. Array elements with numbers from 0 to NegativeLen match the response values at points from -NegativeLen to 0, respectively. Array elements with numbers from NegativeLen+1 to NegativeLen+PositiveLen correspond to the response values in points from 1 to PositiveLen, respectively.
negativelen (int) : int, This is an integer representing the "negative length" of the response function. It indicates the number of elements in the response function array that correspond to negative argument values. Outside the range , the response function is considered zero.
positivelen (int) : int, This is an integer representing the "positive length" of the response function. It indicates the number of elements in the response function array that correspond to positive argument values. Similar to negativelen, outside the range , the response function is considered zero.
Returns: float , The resulting convolved values are stored back in the input signal array.
fastcorrelation(signal, signallen, pattern, patternlen)
Returns Correlation using FFT
Parameters:
signal (float ) : float ,This is an array of real numbers representing the signal to be correlated with the pattern. The elements are numbered from 0 to SignalLen-1.
signallen (int) : int, This is an integer representing the length of the input signal array.
pattern (float ) : float , This is an array of real numbers representing the pattern to be correlated with the signal. The elements are numbered from 0 to PatternLen-1.
patternlen (int) : int, This is an integer representing the length of the pattern array.
Returns: float , The signal array containing the correlation values at points from 0 to SignalLen-1.
tworealffts(a1, a2, a, b, tn)
Returns Fast Fourier Transform of Two Real Functions
Parameters:
a1 (float ) : float , An array of real numbers, representing the values of the first function.
a2 (float ) : float , An array of real numbers, representing the values of the second function.
a (float ) : float , An output array to store the Fourier transform of the first function.
b (float ) : float , An output array to store the Fourier transform of the second function.
tn (int) : float , An integer representing the number of function values. It must be a power of two, but the algorithm doesn't validate this condition.
Returns: float , The a and b arrays will contain the Fourier transform of the first and second functions, respectively. Note that the function overwrites the input arrays a and b.
█ Detailed explaination of each function
Fast Fourier Transform
The fastfouriertransform() function takes three input parameters:
1. a: An array of real and imaginary parts of the function values. The real part is stored at even indices, and the imaginary part is stored at odd indices.
2. nn: The number of function values. It must be a power of two, but the algorithm does not validate this.
3. inversefft: A boolean value that indicates the direction of the transformation. If True, it performs the inverse FFT; if False, it performs the direct FFT.
The function performs the FFT using the Cooley-Tukey algorithm, which is an efficient algorithm for computing the discrete Fourier transform (DFT) and its inverse. The Cooley-Tukey algorithm recursively breaks down the DFT of a sequence into smaller DFTs of subsequences, leading to a significant reduction in computational complexity. The algorithm's time complexity is O(n log n), where n is the number of samples.
The fastfouriertransform() function first initializes variables and determines the direction of the transformation based on the inversefft parameter. If inversefft is True, the isign variable is set to -1; otherwise, it is set to 1.
Next, the function performs the bit-reversal operation. This is a necessary step before calculating the FFT, as it rearranges the input data in a specific order required by the Cooley-Tukey algorithm. The bit-reversal is performed using a loop that iterates through the nn samples, swapping the data elements according to their bit-reversed index.
After the bit-reversal operation, the function iteratively computes the FFT using the Cooley-Tukey algorithm. It performs calculations in a loop that goes through different stages, doubling the size of the sub-FFT at each stage. Within each stage, the Cooley-Tukey algorithm calculates the butterfly operations, which are mathematical operations that combine the results of smaller DFTs into the final DFT. The butterfly operations involve complex number multiplication and addition, updating the input array a with the computed values.
The loop also calculates the twiddle factors, which are complex exponential factors used in the butterfly operations. The twiddle factors are calculated using trigonometric functions, such as sine and cosine, based on the angle theta. The variables wpr, wpi, wr, and wi are used to store intermediate values of the twiddle factors, which are updated in each iteration of the loop.
Finally, if the inversefft parameter is True, the function divides the result by the number of samples nn to obtain the correct inverse FFT result. This normalization step is performed using a loop that iterates through the array a and divides each element by nn.
In summary, the fastfouriertransform() function is an implementation of the Cooley-Tukey FFT algorithm, which is an efficient algorithm for computing the DFT and its inverse. This FFT library can be used for a variety of applications, such as signal processing, image processing, audio processing, and more.
Feal Fast Fourier Transform
The realfastfouriertransform() function performs a fast Fourier transform (FFT) specifically for real-valued functions. The FFT is an efficient algorithm used to compute the discrete Fourier transform (DFT) and its inverse, which are fundamental tools in signal processing, image processing, and other related fields.
This function takes three input parameters:
1. a - A float array containing the real-valued function samples.
2. tnn - The number of function values (must be a power of 2, but the algorithm does not validate this condition).
3. inversefft - A boolean flag that indicates the direction of the transformation (True for inverse, False for direct).
The function modifies the input array a in-place, meaning that the transformed data (the FFT result for direct transformation or the inverse FFT result for inverse transformation) will be stored in the same array a after the function execution.
The algorithm uses a combination of complex-to-complex FFT and additional transformations specific to real-valued data to optimize the computation. It takes into account the symmetry properties of the real-valued input data to reduce the computational complexity.
Here's a detailed walkthrough of the algorithm:
1. Depending on the inversefft flag, the initial values for ttheta, c1, and c2 are determined. These values are used for the initial data preprocessing and post-processing steps specific to the real-valued FFT.
2. The preprocessing step computes the initial real and imaginary parts of the data using a combination of sine and cosine terms with the input data. This step effectively converts the real-valued input data into complex-valued data suitable for the complex-to-complex FFT.
3. The complex-to-complex FFT is then performed on the preprocessed complex data. This involves bit-reversal reordering, followed by the Cooley-Tukey radix-2 decimation-in-time algorithm. This part of the code is similar to the fastfouriertransform() function you provided earlier.
4. After the complex-to-complex FFT, a post-processing step is performed to obtain the final real-valued output data. This involves updating the real and imaginary parts of the transformed data using sine and cosine terms, as well as the values c1 and c2.
5. Finally, if the inversefft flag is True, the output data is divided by the number of samples (nn) to obtain the inverse DFT.
The function does not return a value explicitly. Instead, the transformed data is stored in the input array a. After the function execution, you can access the transformed data in the a array, which will have the real part at even indices and the imaginary part at odd indices.
Fast Sine Transform
This code defines a function called fastsinetransform that performs a Fast Discrete Sine Transform (FST) on an array of real numbers. The function takes three input parameters:
1. a (float array): An array of real numbers representing the function values.
2. tnn (int): Number of function values (must be a power of two, but the code doesn't validate this).
3. inversefst (bool): A boolean flag indicating the direction of the transformation. If True, it performs the inverse FST, and if False, it performs the direct FST.
The output is the transformed array 'a', which will contain the result of the transformation.
The code starts by initializing several variables, including trigonometric constants for the sine transform. It then sets the first value of the array 'a' to 0 and calculates the initial values of 'y1' and 'y2', which are used to update the input array 'a' in the following loop.
The first loop (with index 'jx') iterates from 2 to (tm + 1), where 'tm' is half of the number of input samples 'tnn'. This loop is responsible for calculating the initial sine transform of the input data.
The second loop (with index 'ii') is a bit-reversal loop. It reorders the elements in the array 'a' based on the bit-reversed indices of the original order.
The third loop (with index 'ii') iterates while 'n' is greater than 'mmax', which starts at 2 and doubles each iteration. This loop performs the actual Fast Discrete Sine Transform. It calculates the sine transform using the Danielson-Lanczos lemma, which is a divide-and-conquer strategy for calculating Discrete Fourier Transforms (DFTs) efficiently.
The fourth loop (with index 'ix') is responsible for the final phase adjustments needed for the sine transform, updating the array 'a' accordingly.
The fifth loop (with index 'jj') updates the array 'a' one more time by dividing each element by 2 and calculating the sum of the even-indexed elements.
Finally, if the 'inversefst' flag is True, the code scales the transformed data by a factor of 2/tnn to get the inverse Fast Sine Transform.
In summary, the code performs a Fast Discrete Sine Transform on an input array of real numbers, either in the direct or inverse direction, and returns the transformed array. The algorithm is based on the Danielson-Lanczos lemma and uses a divide-and-conquer strategy for efficient computation.
Fast Cosine Transform
This code defines a function called fastcosinetransform that takes three parameters: a floating-point array a, an integer tnn, and a boolean inversefct. The function calculates the Fast Cosine Transform (FCT) or the inverse FCT of the input array, depending on the value of the inversefct parameter.
The Fast Cosine Transform is an algorithm that converts a sequence of values (time-domain) into a frequency domain representation. It is closely related to the Fast Fourier Transform (FFT) and can be used in various applications, such as signal processing and image compression.
Here's a detailed explanation of the code:
1. The function starts by initializing a number of variables, including counters, intermediate values, and constants.
2. The initial steps of the algorithm are performed. This includes calculating some trigonometric values and updating the input array a with the help of intermediate variables.
3. The code then enters a loop (from jx = 2 to tnn / 2). Within this loop, the algorithm computes and updates the elements of the input array a.
4. After the loop, the function prepares some variables for the next stage of the algorithm.
5. The next part of the algorithm is a series of nested loops that perform the bit-reversal permutation and apply the FCT to the input array a.
6. The code then calculates some additional trigonometric values, which are used in the next loop.
7. The following loop (from ix = 2 to tnn / 4 + 1) computes and updates the elements of the input array a using the previously calculated trigonometric values.
8. The input array a is further updated with the final calculations.
9. In the last loop (from j = 4 to tnn), the algorithm computes and updates the sum of elements in the input array a.
10. Finally, if the inversefct parameter is set to true, the function scales the input array a to obtain the inverse FCT.
The resulting transformed array is stored in the input array a. This means that the function modifies the input array in-place and does not return a new array.
Fast Convolution
This code defines a function called fastconvolution that performs the convolution of a given signal with a response function using the Fast Fourier Transform (FFT) technique. Convolution is a mathematical operation used in signal processing to combine two signals, producing a third signal representing how the shape of one signal is modified by the other.
The fastconvolution function takes the following input parameters:
1. float signal: This is an array of real numbers representing the input signal that will be convolved with the response function. The elements are numbered from 0 to SignalLen-1.
2. int signallen: This is an integer representing the length of the input signal array. It specifies the number of elements in the signal array.
3. float response: This is an array of real numbers representing the response function used for convolution. The response function consists of two parts: one corresponding to positive argument values and the other to negative argument values. Array elements with numbers from 0 to NegativeLen match the response values at points from -NegativeLen to 0, respectively. Array elements with numbers from NegativeLen+1 to NegativeLen+PositiveLen correspond to the response values in points from 1 to PositiveLen, respectively.
4. int negativelen: This is an integer representing the "negative length" of the response function. It indicates the number of elements in the response function array that correspond to negative argument values. Outside the range , the response function is considered zero.
5. int positivelen: This is an integer representing the "positive length" of the response function. It indicates the number of elements in the response function array that correspond to positive argument values. Similar to negativelen, outside the range , the response function is considered zero.
The function works by:
1. Calculating the length nl of the arrays used for FFT, ensuring it's a power of 2 and large enough to hold the signal and response.
2. Creating two new arrays, a1 and a2, of length nl and initializing them with the input signal and response function, respectively.
3. Applying the forward FFT (realfastfouriertransform) to both arrays, a1 and a2.
4. Performing element-wise multiplication of the FFT results in the frequency domain.
5. Applying the inverse FFT (realfastfouriertransform) to the multiplied results in a1.
6. Updating the original signal array with the convolution result, which is stored in the a1 array.
The result of the convolution is stored in the input signal array at the function exit.
Fast Correlation
This code defines a function called fastcorrelation that computes the correlation between a signal and a pattern using the Fast Fourier Transform (FFT) method. The function takes four input arguments and modifies the input signal array to store the correlation values.
Input arguments:
1. float signal: This is an array of real numbers representing the signal to be correlated with the pattern. The elements are numbered from 0 to SignalLen-1.
2. int signallen: This is an integer representing the length of the input signal array.
3. float pattern: This is an array of real numbers representing the pattern to be correlated with the signal. The elements are numbered from 0 to PatternLen-1.
4. int patternlen: This is an integer representing the length of the pattern array.
The function performs the following steps:
1. Calculate the required size nl for the FFT by finding the smallest power of 2 that is greater than or equal to the sum of the lengths of the signal and the pattern.
2. Create two new arrays a1 and a2 with the length nl and initialize them to 0.
3. Copy the signal array into a1 and pad it with zeros up to the length nl.
4. Copy the pattern array into a2 and pad it with zeros up to the length nl.
5. Compute the FFT of both a1 and a2.
6. Perform element-wise multiplication of the frequency-domain representation of a1 and the complex conjugate of the frequency-domain representation of a2.
7. Compute the inverse FFT of the result obtained in step 6.
8. Store the resulting correlation values in the original signal array.
At the end of the function, the signal array contains the correlation values at points from 0 to SignalLen-1.
Fast Fourier Transform of Two Real Functions
This code defines a function called tworealffts that computes the Fast Fourier Transform (FFT) of two real-valued functions (a1 and a2) using a Cooley-Tukey-based radix-2 Decimation in Time (DIT) algorithm. The FFT is a widely used algorithm for computing the discrete Fourier transform (DFT) and its inverse.
Input parameters:
1. float a1: an array of real numbers, representing the values of the first function.
2. float a2: an array of real numbers, representing the values of the second function.
3. float a: an output array to store the Fourier transform of the first function.
4. float b: an output array to store the Fourier transform of the second function.
5. int tn: an integer representing the number of function values. It must be a power of two, but the algorithm doesn't validate this condition.
The function performs the following steps:
1. Combine the two input arrays, a1 and a2, into a single array a by interleaving their elements.
2. Perform a 1D FFT on the combined array a using the radix-2 DIT algorithm.
3. Separate the FFT results of the two input functions from the combined array a and store them in output arrays a and b.
Here is a detailed breakdown of the radix-2 DIT algorithm used in this code:
1. Bit-reverse the order of the elements in the combined array a.
2. Initialize the loop variables mmax, istep, and theta.
3. Enter the main loop that iterates through different stages of the FFT.
a. Compute the sine and cosine values for the current stage using the theta variable.
b. Initialize the loop variables wr and wi for the current stage.
c. Enter the inner loop that iterates through the butterfly operations within each stage.
i. Perform the butterfly operation on the elements of array a.
ii. Update the loop variables wr and wi for the next butterfly operation.
d. Update the loop variables mmax, istep, and theta for the next stage.
4. Separate the FFT results of the two input functions from the combined array a and store them in output arrays a and b.
At the end of the function, the a and b arrays will contain the Fourier transform of the first and second functions, respectively. Note that the function overwrites the input arrays a and b.
█ Example scripts using functions contained in loxxfft
Real-Fast Fourier Transform of Price w/ Linear Regression
Real-Fast Fourier Transform of Price Oscillator
Normalized, Variety, Fast Fourier Transform Explorer
Variety RSI of Fast Discrete Cosine Transform
STD-Stepped Fast Cosine Transform Moving Average
comm_idxThis script displays information about the components of the Goldman Sachs Commodity Index. The index is based on futures contracts in the categories of agricultural products, softs commodities, livestock, energies, industrial metals, and precious metals. The statistics displayed in the table are:
change: 1-day % change
from ma: the % change from a moving average
corr idx: correlation of the contract to the GSCI
The lengths for the moving average and correlation statistic can be set using the inputs.
See the script source for the symbols used for each commodity. Although most of the symbols correspond to the actual futures contract used to compute the index, LME contracts are not available on tradingview. Hence, corresponding HKEX contracts are used for the industrial metals.
Murder Algo Stats: last portion of Indices closing hour (S&P)Stats regarding the 'murder algo' (last 10mins of the closing hour). Works on all sub-1hr timeframes. Best used on 5min, 10min 15min timeframe. Ideal use on 10min timeframe.
Can be applied to other user input sessions also
What i'm calling the 'Murder Algo' is the tendency of dynamic lower time frame price action in the final 10minutes of the S&P closing hour (or any of the three major US indices: S&P, Nasdaq, Dow).
If there are un-met liquidity targets (i.e. clean highs or lows) as we come into the last portion of the closing hour, price has a tendency to stretch up or down to reach these targets, swiftly.
These statisitics are somewhat experimental/research; trying to quantify this tendency. Please comment below if you think of some additions / modifications that may prove useful.
//Purpose:
-To get statistics of the tendency to 'reach' of the final bar (10minute bar in the above) of the closing hour in Indices (3pm - 4pm NY time).
-Specifically to see how often price reaches for HH or LL in the final bar of the closing hour (most of the time); and to see how far it reaches one way when it does (Mean, median, mode).
//Notes:
-Two sets of historical stats; one is based on the 'solo reach' of the last bar; the other is based on the reach of the last bar from the average price of the preceding bars of the session (purple line in the above)
-Works on any timeframe below hourly. Ideally used on 10min timeframe, but may be interesting to plot on 15min or 5min timeframe also.
-Should also work on custom user-defined session; though this indicator was explicly designed to investigate the 'murder algo': that final rush and/or whipsaw tendency of price in the last few minutes of Regular trading on Indices.
-For S&P, best used on SPX, which gives the longest history of all the S&P variants due to only showing Regular trading hours bars (500 days of history on 10min timeframe, for premium users)
-For most stats, i've rounded to ES1! mintick (i.e. rounded to nearest quarter dollar) =>> This allows more meaningful values for 'mode' statistical measure.
-I trade S&P; but this 'muder algo' phenomenon also obviously presents in Nasdaq and Dow.
//User Inputs:
-Session time input (defaults to closing hour 3pm - 4pm NY time)
-Average method (for the average of all the input session EXCEPT the final bar)
-Toggle on/off Average line.
-other formatting options: text color, table position, line color/style/size.
Example usage with annotations on SPX 500 chart 15m timeframe; using closing hour (3pm-4pm NY time) as our session:
Lorentzian Classification Strategy Based in the model of Machine learning: Lorentzian Classification by @jdehorty, you will be able to get into trending moves and get interesting entries in the market with this strategy. I also put some new features for better backtesting results!
Backtesting context: 2022-07-19 to 2023-04-14 of US500 1H by PEPPERSTONE. Commissions: 0.03% for each entry, 0.03% for each exit. Risk per trade: 2.5% of the total account
For this strategy, 3 indicators are used:
Machine learning: Lorentzian Classification by @jdehorty
One Ema of 200 periods for identifying the trend
Supertrend indicator as a filter for some exits
Atr stop loss from Gatherio
Trade conditions:
For longs:
Close price is above 200 Ema
Lorentzian Classification indicates a buying signal
This gives us our long signal. Stop loss will be determined by atr stop loss (white point), break even(blue point) by a risk/reward ratio of 1:1 and take profit of 3:1 where half position will be closed. This will be showed as buy.
The other half will be closed when the model indicates a selling signal or Supertrend indicator gives a bearish signal. This will be showed as cl buy.
For shorts:
Close price is under 200 Ema
Lorentzian Classification indicates a selling signal
This gives us our short signal. Stop loss will be determined by atr stop loss (white point), break even(blue point) by a risk/reward ratio of 1:1 and take profit of 3:1 where half position will be closed. This will be showed as sell.
The other half will be closed when the model indicates a buying signal or Supertrend indicator gives a bullish signal. This will be showed as cl sell.
Risk management
To calculate the amount of the position you will use just a small percent of your initial capital for the strategy and you will use the atr stop loss or last swing for this.
Example: You have 1000 usd and you just want to risk 2,5% of your account, there is a buy signal at price of 4,000 usd. The stop loss price from atr stop loss or last swing is 3,900. You calculate the distance in percent between 4,000 and 3,900. In this case, that distance would be of 2.50%. Then, you calculate your position by this way: (initial or current capital * risk per trade of your account) / (stop loss distance).
Using these values on the formula: (1000*2,5%)/(2,5%) = 1000usd. It means, you have to use 1000 usd for risking 2.5% of your account.
We will use this risk management for applying compound interest.
> In settings, with position amount calculator, you can enter the amount in usd of your account and the amount in percentage for risking per trade of the account. You will see this value in green color in the upper left corner that shows the amount in usd to use for risking the specific percentage of your account.
> You can also choose a fixed amount, so you will have to activate fixed amount in risk management for trades and set the fixed amount for backtesting.
Script functions
Inside of settings, you will find some utilities for display atr stop loss, break evens, positions, signals, indicators, a table of some stats from backtesting, etc.
You will find the settings for risk management at the end of the script if you want to change something or trying new values for other assets for backtesting.
If you want to change the initial capital for backtest the strategy, go to properties, and also enter the commisions of your exchange and slippage for more realistic results.
In risk managment you can find an option called "Use leverage ?", activate this if you want to backtest using leverage, which means that in case of not having enough money for risking the % determined by you of your account using your initial capital, you will use leverage for using the enough amount for risking that % of your acount in a buy position. Otherwise, the amount will be limited by your initial/current capital
I also added a function for backtesting if you had added or withdrawn money frequently:
Adding money: You can choose how often you want to add money (Monthly, yearly, daily or weekly). Then a fixed amount of money and activate or deactivate this function
Withdraw money: You can choose if you want to withdraw a fixed amount or a percentage of earnings. Then you can choose a fixed amount of money, the period of time and activate or deactivate this function. Also, the percentage of earnings if you choosed this option.
Some other assets where strategy has worked
BTCUSD 4H, 1D
ETHUSD 4H, 1D
BNBUSD 4H
SPX 1D
BANKNIFTY 4H, 15 min
Some things to consider
USE UNDER YOUR OWN RISK. PAST RESULTS DO NOT REPRESENT THE FUTURE.
DEPENDING OF % ACCOUNT RISK PER TRADE, YOU COULD REQUIRE LEVERAGE FOR OPEN SOME POSITIONS, SO PLEASE, BE CAREFULL AND USE CORRECTLY THE RISK MANAGEMENT
Do not forget to change commissions and other parameters related with back testing results!. If you have problems loading the script reduce max bars back number in general settings
Strategies for trending markets use to have more looses than wins and it takes a long time to get profits, so do not forget to be patient and consistent !
Please, visit the post from @jdehorty called Machine Learning: Lorentzian Classification for a better understanding of his script!
Any support and boosts will be well received. If you have any question, do not doubt to ask!
Market Relative Candle Ratio ComparatorIntroducing the Market Relative Candle Ratio Comparator, a visually captivating script that eases the way you compare two financial assets, such as cryptocurrencies and market indices. Leveraging a distinctive calculation method based on percentage changes and their averages, this tool presents a crystal-clear view of how your chosen assets perform in relation to each other, both for individual candles and over a range of previous candles.
Tailoring the script to your preferences is a walk in the park, as it allows you to easily adjust input symbols, moving average lengths, and other parameters to match your analytical approach. The visually arresting column chart it creates employs vivid red and green colors to underscore the differences between the two assets on each candle. Simultaneously, the lower-opacity columns depict the accumulated differences over a specified lookback period. This vibrant blend of colors and opacities results in a dynamic visual experience, enabling you to better grasp market trends relative to each other.
The reverse bool input is a handy feature that lets you invert the effect of the input symbol (DXY by default) in the comparison. When you set the reverse input to true, the script multiplies the calculated DXY percentage change by -1, effectively reversing the comparison. This is particularly useful when examining assets with an inverse relationship or when you'd like to analyze the input symbol's impact in the opposite direction.
For instance, if the input symbol represents a market index that generally moves in the opposite direction of the selected cryptocurrency, enabling the reverse input will help you better visualize and understand the relationship between the two assets by inverting the input symbol's effect on the comparison.
In the accompanying chart, you can observe the comparison of Bitcoin's movement relative to the Dollar, Gold, Bonds, and the S&P 500. The indicator reveals that in the last day, Bitcoin outperformed Bonds, Gold, and the Dollar but not the S&P 500!
Arbitrage SpreadThis indicator helps to find spreads between cryptocurrencies, assess their correlation, spread, z score and atr z score.
The graphs are plotted as a percentage. Because of the limitation in pine tradingview for 5000 bars a period was introduced (after which a new starting point of the graph construction will be started), if you want it can be disabled
The multiplier parameter affects only the construction of the joint diagram on which z score and atr z score are calculated (construction of the diagram is done by dividing one pair by another and multiplying by the multiplier parameter) is shown with a red line
To create a notification you have to specify the data for parameters other than zero which you want to monitor. For parameters z score and atr z score data are counted in both directions
The data can be tracked via the data window
Link to image of the data window prnt.sc
Oscillator: Which follows Normal Distribution?When doing machine learning using oscillators, it would be better if the oscillators were normally distributed.
So I analyzed the distribution of oscillators.
The value of the oscillator was divided into 50 groups each from 0 to 100.
ex) if rsi value is 45.43 -> group_44, 58.23 -> group_58
Ocscillators : RSI, Stoch, MFI, WT, RVI, etc....
Caution: The normal distribution was verified through an empirical formula.
[MiV] MA Screener v1.0In my trading I stick to the following strategy: I buy an asset above the 100/200 moving average and then sell it.
The most problematic thing in all this is to look for assets that are above the 100 or 200 moving average, and to assess how "far" the price is from that moving average.
In fact, to solve this problem I created this indicator.
It works with 30 different assets and displays the state of its two moving averages, whether the price is higher or not, and how much higher the price is from that level.
Multiple Moving Average ToolkitFeatures Overview:
Multiple Moving Averages: The script allows you to plot up to five different Moving Averages (MAs) on your chart at the same time. You can choose the type of MA (EMA, SMA, HMA, WMA, DEMA, VWMA, VWAP) and the length of each one.
Color Ribbon: You can turn the MAs into a color ribbon by selecting the "Turn into Color Ribbon?" option. This will make the area between the MAs colored and can help you identify trends more easily.
MA Value Table: You can draw a table on your chart that displays the current values of each MA, whether the trend is bullish or bearish along with the length of the MAs. The current ATR value is also shown in the last cell of the table. You can choose the location of the table (Top Left, Top Right, Bottom Left, Bottom Right) and the transparency of the background color.
Crosses: The script can detect when two MAs cross over each other (1st MA crosses 5th MA and vice versa), indicating a potential trend reversal. It will plot crosses on the chart at the point of the crossover and give an alert if the "Bullish Cross Detected" or "Bearish Cross Detected" condition is met.
How to use:
Once the script is added to your chart, you can customize the settings to fit your preferences. You can choose the type and length of each MA, whether to turn them into a color ribbon, whether to plot crosses, and whether to draw the MA Value Table.
The MA Value Table can be moved to a different location on the chart by selecting the "Location of Table" option and choosing Top Left, Top Right, Bottom Left, or Bottom Right.
Watch for MA crossovers and alerts to identify potential trend reversals. The script can help you identify bullish and bearish trends by color-coding the area between the MAs and displaying the current values of each MA in the table.
Breakdown of the script:
User Inputs
The first section of the script defines several user inputs that allows you to customize the indicator. These include options for turning the MAs into a color ribbon, plotting crosses when there is a bullish or bearish cross of the MAs, drawing a table of the MA values, and setting the transparency of the ribbon. You can also select the location of the MA value table and customize the settings for each individual MA.
Moving Average Calculation
The script defines a function called "getMA" that calculates the moving average for a given type and length. The function uses a switch statement to determine which type of moving average to use, such as an exponential moving average (EMA), simple moving average (SMA), Hull moving average (HMA), weighted moving average (WMA), double exponential moving average (DEMA), volume-weighted moving average (VWMA), or volume-weighted average price (VWAP).
The script then calls this function to calculate the values of up to five different MAs, depending on the user input. The ATR (average true range) is also calculated using the TA library.
Color Filter and Cross Detection
The script sets a color filter based on the relationship between the MAs. If the shorter-term MAs are above the longer-term MAs, the filter is set to green to indicate a bullish trend, and if the shorter-term MAs are below the longer-term MAs, the filter is set to red to indicate a bearish trend. You can adjust the transparency of the ribbon to make it more or less visible.
The script also detects when there is a bullish or bearish cross of the MAs and can generate alerts to notify you.
MA Plotting
The script plots up to five MAs on the chart, depending on the user input. The MAs are plotted as lines with different colors and thicknesses, and you can choose to turn them into a color ribbon if desired.
Cross Plotting
The script plots crosses on the chart when there is a bullish or bearish cross of the MAs. The crosses are plotted as X shapes at the location of the cross and are color-coded to indicate the direction of the cross.
MA Value Table
Finally, the script draws a table of the MA values on the chart, displaying the values of each MA as well as the current trend and the ATR. You can customize the location of the table, and the table is colored to match the color filter of the MAs.
Feel free to message me or comment on the post with any questions or issues!
Much more to come!
Thanks for reading, enjoy!
Employees by Population (Per Million)This script measures the number of employees a company has per million people in the US population, either by total or employed population.
*Backtesting System ⚉ OVERVIEW ⚉
One of the best Systems for Backtesting your Strategies.
Incredibly flexible, simple, fast and feature-rich system — will solve most of your queries without much effort.
Many systems for setting StopLoss, TakeProfit, Risk Management and advanced Filters.
All you need to do is plug in your indicator and start Backtesting .
I intentionally left the option to use my System on Full Power before you load your indicator into it.
The system uses the built-in simple and popular moving average crossover signal for this purpose. (EMA 50 & 200).
Also Highly Recommend that you Fully use ALL of the features of this system so that you understand how they work before you ask questions.
Also tried to leave TIPS for each feature everywhere, read Tips, activate them and see how they work.
But before you use this system, I Recommend you to read the following description in Full.
—————— How to connect your indicator in 2 steps:
Adapt your indicator by adding only 2 lines of code and then connect it to this Backtesting System.
Step 1 — Create your connector, For doing so:
• 1 — Find or create in your indicator where are the conditions printing the Long-Buy and Short-Sell signals.
• 2 — Create an additional plot as below
I'm giving an example with a Two moving averages cross.
Please replicate the same methodology for your indicator wether it's a MACD, RSI , Pivots, or whatever indicator with Clear Buy and Sell conditions.
//@version=5
indicator('Moving Average Cross', overlay = true)
MA200 = ta.𝚎𝚖𝚊(close, 200)
MA50 = ta.𝚎𝚖𝚊(close, 50)
// Generate Buy and Sell conditions
buy = ta.crossover (MA200, MA50)
sell = ta.crossunder (MA200, MA50)
plot(MA200, color=color.green)
plot(MA50 , color=color.red )
bgcolor(color = buy ? color.green : sell ? color.red : na, title='SIGNALS')
// ———————————————— SIGNAL FOR SYSTEM ————————————————
Signal = buy ? +1 : sell ? -1 : 0
plot(Signal, title='🔌Connector🔌', display = display.none)
// —————— 🔥 The Backtesting System expects the value to be exactly +1 for the 𝚋𝚞𝚕𝚕𝚒𝚜𝚑 signal, and -1 for the 𝚋𝚎𝚊𝚛𝚒𝚜𝚑 signal
Basically, I identified my Buy & Sell conditions in the code and added this at the bottom of my indicator code
Now you can connect your indicator to the Backtesting System using the Step 2
Step 2 — Connect the connector
• 1 — Add your updated indicator to a TradingView chart and Add the Backtesting System as well to the SAME chart
• 2 — Open the Backtesting System settings and in the External Source field select your 🔌Connector🔌 (which comes from your indicator)
_______________________________
⚉ MAIN SETTINGS ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
𝐄𝐱𝐭𝐞𝐫𝐧𝐚𝐥 𝐒𝐨𝐮𝐫𝐜𝐞 — Select your indicator. Add your indicator by following the 2 steps described above and select it in the menu. To familiarize yourself with the system until you select your indicator, you will have an in-built strategy of crossing the two moving EMA's of 50 and 200.
Long Deals — Enable/Disable Long Deals.
Short Deals — Enable/Disable Short Deals.
Wait End Deal — Enable/Disable waiting for a trade to close at Stop Loss/Take Profit. Until the trade closes on the Stop Loss or Take Profit, no new trade will open.
Reverse Deals — To force the opening of a trade in the opposite direction.
ReEntry Deal — Automatically open the same new deal after the deal is closed.
ReOpen Deal — Reopen the trade if the same signal is received. For example, if you are already in the long and a new signal is received in the long, the trade will reopen. * Does not work if Wait End Deal is enabled.
𝐓𝐚𝐤𝐞 𝐏𝐫𝐨𝐟𝐢𝐭:
None — Disables take profit. Useful if you only want to use dynamic stoplosses such as MA, Fast-Trailing, ATR Trail.
FIXED % — Fixed take profit in percent.
FIXED $ — Fixed Take in Money.
ATR — Fixed Take based on ATR.
R:R — Fixed Take based on the size of your stop loss. For example, if your stop is 10% and R:R=1, then the Take would be 10%. R:R=3 Take would be 30%, etc.
HH / LL — Fixed Take based on the previous maximum/minimum (extremum).
𝐒𝐭𝐨𝐩 𝐋𝐨𝐬𝐬:
None — Disables Stop Loss. Useful if you want to work without a stop loss. *Be careful if Wait End Deal is enabled, the trade may not close for a long time until it reaches the Take.
FIXED % — Fixed Stop in percent.
FIXED $ — Fixed Stop in Money.
TRAILING — Dynamic Trailing Stop like on the stock exchanges.
FAST TRAIL — Dynamic Fast Trailing Stop moves immediately in profit and stays in place if the price stands still or the price moves in loss.
ATR — Fixed Stop based on the ATR.
ATR TRAIL — Dynamic Trailing Stop based on the ATR.
LO / HI — A Fixed Stop based on the last Maximum/Minimum extemum. Allows you to place a stop just behind or above the low/high candle.
MA — Dynamic Stop based on selected Moving Average. * You will have 8 types of MA (EMA, SMA, HMA, etc.) to choose from, but you can easily add dozens of other MAs, which makes this type of stop incredibly flexible.
Add % — If true, then with the "𝗦𝘁𝗼𝗽 %" parameter you can add percentages to any of the current SL. Can be especially useful when using Stop - 𝗔𝗧𝗥 or 𝗠𝗔 or 𝗟𝗢/𝗛𝗜. For example with 𝗟𝗢/𝗛𝗜 to put a stop for the last High/Low and add 0.5% additional Stoploss.
Fixed R:R — If the stop loss is Dynamic (Trailing or MA) then if R:R true can also be made Dynamic * Use it carefully, the function is experimental.
_________________________________________
⚉ TAKE PROFIT LEVELS ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
A unique method of constructing intermediate Take Profit Levels will allow you to select up to 5 intermediate Take Profit Levels and one intermediate Stop Loss.
Intermediate Take Profit Levels are perfectly calculated into 5 equal parts in the form of levels from the entry point to the final Take Profit target.
All you need to do is to choose the necessary levels for fixing and how much you want to fix at each level as a percentage. For example, TP 3 will always be exactly between the entry point and the Take Profit target. And the value of TP 3 = 50 will close 50% of the amount of the remaining size of the position.
Note: all intermediate SL/TP are closed from the remaining position amount and not from the initial position size, as TV does by default.
SL 0 Position — works in the same way as TP 1-5 but it's Stop. With this parameter you can set the position where the intermediate stop will be set.
Breakeven on TP — When activated, it allows you to put the stop loss at Breakeven after the selected TP is reached. For this function to work as it should - you need to activate an intermediate Take. For example, if TP 3 is activated and Breakeven on TP = 3, then after the price reaches this level, the Stop loss will go to Breakeven.
* This function will not work with Dynamic Stoplosses, because it simply does not make sense.
CoolDown # Bars — When activated, allows you to add a delay before a new trade is opened. A new trade after CoolDown will not be opened until # bars pass and a new signal appears.
_____________________________
⚉ TIME FILTERS ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
Powerful time filter code that allows you to filter data based on specific time zones, dates, and session days. This code is ideal for those who need to analyze data from different time zones and weed out irrelevant data.
With Time Filter, you can easily set the starting and ending time zones by which you want to filter the data.
You can also set a start and end date for your data and choose which days of the week to include in the analysis. In addition, you can specify start and end times for a specific session, allowing you to focus your analysis on specific time periods.
_________________________________
⚉ SIGNAL FILTERS ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
Signal Filters — allows you to easily customize and optimize your trading strategies based on 10 filters.
Each filter is designed to help you weed out inaccurate signals to minimize your risks.
Let's take a look at their features:
__________________________________
⚉ RISK MANAGEMENT ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
Risk management tools that allow you to set the maximum number of losing trades in a row, a limit on the number of trades per day or week and other filters.
Loss Streak — Set Max number of consecutive loss trades.
Win Streak — Max Winning Streak Length.
Row Loss InDay — Max of consecutive days with a loss in a row.
DrawDown % — Max DrawDown (in % of strategy equity).
InDay Loss % — Set Max Intraday Loss.
Daily Trades — Limit the number of MAX trades per day.
Weekly Trades — Limit the number of MAX trades per week.
* 🡅 I would Not Recommend using these functions without understanding how they work.
Order Size — Position Size
• NONE — Use the default position size settings in Tab "Properties".
• EQUITY — The amount of the allowed position as a percentage of the initial capital.
• Use Net Profit — On/Off the use of profit in the following trades. *Only works if the type is EQUITY.
• SIZE — The size of the allowed position in monetary terms.
• Contracts — The size of the allowed position in the contracts. 1 Сontract = Сurrent price.
________________
⚉ NOTES ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
It is important to note that I have never worked with Backtesting and the functions associated with them before.
It took me about a month of slow work to build this system.
I want to say Big Thanks:
• The PineScripters🌲 group in Telegram , the guys suggested how to implement some features. Especially @allanster
• Thanks to all those people who share their developments for free on TV and not only.
• I also thank myself for not giving up and finishing the project, and not trying to monetize the system by selling it. * Although I really want the money :)
I tried hard to make it as fast and convenient as possible for everyone who will use my code.
That's why I didn't use any libraries and dozens of heavy functions, and I managed to fit in 8+-functions for the whole code.
Absolutely every block of code I tried to make full-fledged modular, that it was easy to import/edit for myself (you).
I have abused the Ternary Pine operator a little (a lot) so that the code was as compact as possible.
Nevertheless, I tried very hard to keep my code very understandable even for beginners.
At last I managed to write 500 lines of code, making it one of the fastest and most feature-rich systems out there.
I hope everyone enjoys my work.
Put comments and write likes.
HarmonicPatternTrackingLibrary "HarmonicPatternTracking"
Library contains few data structures and methods for tracking harmonic pattern trades via pinescript.
method draw(this)
Creates and draws HarmonicDrawing object for given HarmonicPattern
Namespace types: HarmonicPattern
Parameters:
this (HarmonicPattern) : HarmonicPattern object
Returns: current HarmonicPattern object
method addTrade(this)
calculates HarmonicTrade and sets trade object for HarmonicPattern
Namespace types: HarmonicPattern
Parameters:
this (HarmonicPattern) : HarmonicPattern object
Returns: bool true if pattern trades are valid, false otherwise
method delete(this)
Deletes drawing objects of HarmonicDrawing
Namespace types: HarmonicDrawing
Parameters:
this (HarmonicDrawing) : HarmonicDrawing object
Returns: current HarmonicDrawing object
method delete(this)
Deletes drawings of harmonic pattern
Namespace types: HarmonicPattern
Parameters:
this (HarmonicPattern) : HarmonicPattern object
Returns: current HarmonicPattern object
HarmonicDrawing
Drawing objects of Harmonic Pattern
Fields:
xa (series line) : xa line
ab (series line) : ab line
bc (series line) : bc line
cd (series line) : cd line
xb (series line) : xb line
bd (series line) : bd line
ac (series line) : ac line
xd (series line) : xd line
x (series label) : label for pivot x
a (series label) : label for pivot a
b (series label) : label for pivot b
c (series label) : label for pivot c
d (series label) : label for pivot d
xabRatio (series label) : label for XAB Ratio
abcRatio (series label) : label for ABC Ratio
bcdRatio (series label) : label for BCD Ratio
xadRatio (series label) : label for XAD Ratio
HarmonicTrade
Trade tracking parameters of Harmonic Patterns
Fields:
initialEntry (series float) : initial entry when pattern first formed.
entry (series float) : trailed entry price.
initialStop (series float) : initial stop when trade first entered.
stop (series float) : current stop updated as per trailing rules.
target1 (series float) : First target value
target2 (series float) : Second target value
target3 (series float) : Third target value
target4 (series float) : Fourth target value
status (series int) : Trade status referenced as integer
retouch (series bool) : Flag to show if the price retouched after entry
HarmonicProperties
Display and trade calculation properties for Harmonic Patterns
Fields:
fillMajorTriangles (series bool) : Display property used for using linefill for harmonic major triangles
fillMinorTriangles (series bool) : Display property used for using linefill for harmonic minor triangles
majorFillTransparency (series int) : transparency setting for major triangles
minorFillTransparency (series int) : transparency setting for minor triangles
showXABCD (series bool) : Display XABCD pivot labels
lblSizePivots (series string) : Pivot label size
showRatios (series bool) : Display Ratio labels
useLogScaleForScan (series bool) : Use log scale to determine fib ratios for pattern scanning
useLogScaleForTargets (series bool) : Use log scale to determine fib ratios for target calculation
base (series string) : base on which calculation of stop/targets are made.
entryRatio (series float) : fib ratio to calculate entry
stopRatio (series float) : fib ratio to calculate initial stop
target1Ratio (series float) : fib ratio to calculate first target
target2Ratio (series float) : fib ratio to calculate second target
target3Ratio (series float) : fib ratio to calculate third target
target4Ratio (series float) : fib ratio to calculate fourth target
HarmonicPattern
Harmonic pattern object to track entire pattern trade life cycle
Fields:
id (series int) : Pattern Id
dir (series int) : pattern direction
x (series float) : X Pivot
a (series float) : A Pivot
b (series float) : B Pivot
c (series float) : C Pivot
d (series float) : D Pivot
xBar (series int) : Bar index of X Pivot
aBar (series int) : Bar index of A Pivot
bBar (series int) : Bar index of B Pivot
cBar (series int) : Bar index of C Pivot
dBar (series int) : Bar index of D Pivot
przStart (series float) : Start of PRZ range
przEnd (series float) : End of PRZ range
patterns (bool ) : array representing the patterns
patternLabel (series string) : string representation of list of patterns
patternColor (series color) : color assigned to pattern
properties (HarmonicProperties) : HarmonicProperties object containing display and calculation properties
trade (HarmonicTrade) : HarmonicTrade object to track trades
drawing (HarmonicDrawing) : HarmonicDrawing object to manage drawings
Double Candle Trend Counter [theEccentricTrader]█ OVERVIEW
This indicator counts the number of confirmed double candle trend scenarios on any given candlestick chart and displays the statistics in a table, which can be repositioned and resized at the user's discretion.
█ CONCEPTS
Green and Red Candles
• A green candle is one that closes with a close price equal to or above the price it opened.
• A red candle is one that closes with a close price that is lower than the price it opened.
Upper Candle Trends
• A higher high candle is one that closes with a higher high price than the high price of the preceding candle.
• A lower high candle is one that closes with a lower high price than the high price of the preceding candle.
• A double-top candle is one that closes with a high price that is equal to the high price of the preceding candle.
Lower Candle Trends
• A higher low candle is one that closes with a higher low price than the low price of the preceding candle.
• A lower low candle is one that closes with a lower low price than the low price of the preceding candle.
• A double-bottom candle is one that closes with a low price that is equal to the low price of the preceding candle.
Muti-Part Upper and Lower Candle Trends
• A multi-part higher high trend begins with the formation of a new higher high and continues until a new lower high ends the trend.
• A multi-part lower high trend begins with the formation of a new lower high and continues until a new higher high ends the trend.
• A multi-part higher low trend begins with the formation of a new higher low and continues until a new lower low ends the trend.
• A multi-part lower low trend begins with the formation of a new lower low and continues until a new higher low ends the trend.
Double Candle Trends
• A double uptrend candle trend is formed when a candle closes with both a higher high and a higher low.
• A double downtrend candle trend is formed when a candle closes with both a lower high and a lower low.
Multi-Part Double Candle Trends
• A multi-part double uptrend candle trend begins with the formation of a new double uptrend candle trend and continues until a new lower high or lower low ends the trend.
• A multi-part double downtrend candle trend begins with the formation of a new double downtrend candle trend and continues until a new higher high or higher low ends the trend.
█ FEATURES
Inputs
• Start Date
• End Date
• Position
• Text Size
• Show Plots
Table
The table is colour coded, consists of seven columns and, as many as, thirty-two rows. Blue cells denote the multi-part trend scenarios, green cells denote the corresponding double uptrend candle trend scenarios and red cells denote the corresponding double downtrend candle trend scenarios.
The multi-part double candle trend scenarios are listed in the first column with their corresponding total counts to the right, in the second and fifth columns. The last row in column one, displays the sample period which can be adjusted or hidden via indicator settings.
The third and sixth columns display the double candle trend scenarios as percentages of total 1-part double candle trends. And columns four and seven display the total double candle trend scenarios as percentages of the last, or preceding double candle trend part. For example 4-part double uptrend candle trends as percentages of 3-part double uptrend candle trends.
Plots
I have added plots as a visual aid to the double candle trend scenarios. Green up-arrows, with the number of the trend part, denote double uptrend candle trends. Red down-arrows, with the number of the trend part, denote double downtrend candle trends.
█ HOW TO USE
This indicator is intended for research purposes, strategy development and strategy optimisation. I hope it will be useful in helping to gain a better understanding of the underlying dynamics at play on any given market and timeframe.
It can, for example, give you an idea of whether the current double candle trend will continue or fail, based on the current trend scenario and what has happened in the past under similar circumstances. Such information can be useful when conducting top down analysis across multiple timeframes and making strategic decisions.
What you do with these statistics and how far you decide to take your research is entirely up to you, the possibilities are endless.
█ LIMITATIONS
Some higher timeframe candles on tickers with larger lookbacks such as the DXY , do not actually contain all the open, high, low and close (OHLC) data at the beginning of the chart. Instead, they use the close price for open, high and low prices. So, while we can determine whether the close price is higher or lower than the preceding close price, there is no way of knowing what actually happened intra-bar for these candles. And by default candles that close at the same price as the open price, will be counted as green. You can avoid this problem by utilising the sample period filter.
It is also worth noting that the sample size will be limited to your Trading View subscription plan. Premium users get 20,000 candles worth of data, pro+ and pro users get 10,000, and basic users get 5,000. If upgrading is currently not an option, you can always keep a rolling tally of the statistics in an excel spreadsheet or something of the like.
Statistics: High & Low timings of custom session; 1yr historyGet statistics of the Session High and Session Low timings for any custom session; based on around 1yr of data.
//Purpose:
-To get data on the 'time of day' tendencies of an asset.
-Narrow in on a custom defined session and get statistics on that session.
//Notes:
-Input times are always in New York time (but changing the timezone after setting WILL adust both table stats and background highlight correctly.
-For particularly long sessions, make sure text size is set to 'tiny' (very long vertical table), or adjust table to display horizontally.
-You'll notice most assets show higher readings around NY equities open (9:30am NY time). Other assets will have 'hot-spots' at other times too.
-Timings represent the beginning of a 15m candle. i.e. reading for 15:45 represents a high occurring between 15:45 and 1600.
-Premium users should get 20k bars => around 1year's worth of data on a 15minute chart. Days of history is displayed in the top left corner of the table.
//Limitations
-only designed and working on 15minute timeframe (to gather a full year of meaningful/comparable % stats, need 15minute 'buckets' of time.
-sessions cannot cross through midnight, or start at midnight (00:15 is ok). 00:15 >> 23:45 is the max session length. On BTC, same applies but 01:00 instead of midnight (all in NY time).
-if your session crosses through 'dead time' (e.g. 17:00-18:00 S&P NY time); table will correctly omit these non-existent candles, but it will add on the missing hour before the start time.
//Cautionary note:
-Since markets are not uncommonly in a trending state when your defined session starts or ends, the high/low timings % readings for start and end of session may be misleadingly high. Try to look for unusually high readings that are not at the start/end of your session.
Wheat (ZW1!) 15min chart; Table displayed vertically:
Nasdaq (NQ1!) 15m chart; Table displayed horizontally and with smaller text to view a very long custom session: