GKD-C Polynomial-Regression-Fitted Filter [Loxx]Giga Kaleidoscope GKD-C Polynomial-Regression-Fitted Filter is a Confirmation module included in Loxx's "Giga Kaleidoscope Modularized Trading System".
█ GKD-C Polynomial-Regression-Fitted Filter
Polynomial regression is a powerful tool in the field of data analysis, used to model the relationship between a dependent variable and one or more independent variables. In the case of a moving average, the aim is to smooth out fluctuations in time series data and reveal underlying trends. The following provides a thorough analysis of a polynomial regression function that calculates a moving average, delving into the intricacies of the code and explaining the steps involved in the process.
Function Overview
The polynomialRegressionMA(src, deg, len) function takes three input parameters: src, deg, and len. The src parameter represents the source data or time series, deg is the degree of the polynomial regression, and len is the length of the moving average window. Throughout the following description, we will discuss the various components of this function, explaining the role of each part in the overall process.
polynomialRegressionMA(src, deg, len)=>
float sumout = src
AX = matrix.new(12, 12, 0.)
float BX = array.new(12, 0.)
float ZX = array.new(12, 0.)
float Pow = array.new(12, 0.)
int Row = array.new(12, 0)
float CX = array.new(12, 0.)
for k = 1 to len
float YK = nz(src )
int XK = k
int Prod = 1
for j = 1 to deg + 1
array.set(BX, j, array.get(BX, j) + YK * Prod)
Prod *= XK
array.set(Pow, 0, len)
for k = 1 to len
int XK = k
int Prod = k
for j = 1 to 2 * deg
array.set(Pow, j, array.get(Pow, j) + Prod)
Prod *= XK
for j = 1 to deg + 1
for l = 1 to deg + 1
matrix.set(AX, j, l, array.get(Pow, j + l - 2))
for j = 1 to deg + 1
array.set(Row, j, j)
for i = 1 to deg
for k = i + 1 to deg + 1
if math.abs(matrix.get(AX, array.get(Row, k), i)) >
math.abs(matrix.get(AX, array.get(Row, i), i))
temp = array.get(Row, i)
array.set(Row, i, array.get(Row, k))
array.set(Row, k, temp)
for k = i + 1 to deg + 1
if matrix.get(AX, array.get(Row, i), i) != 0
matrix.set(AX, array.get(Row, k), i,
matrix.get(AX, array.get(Row, k), i) /
matrix.get(AX, array.get(Row, i), i))
for l = i + 1 to deg + 1
matrix.set(AX, array.get(Row, k), l,
matrix.get(AX, array.get(Row, k), l) -
matrix.get(AX, array.get(Row, k), i) *
matrix.get(AX, array.get(Row, i), l))
array.set(ZX, 1, array.get(BX, array.get(Row, 1)))
for k = 2 to deg + 1
float sum = 0.
for l = 1 to k - 1
sum += matrix.get(AX, array.get(Row, k), l) * array.get(ZX, l)
array.set(ZX, k, array.get(BX, array.get(Row, k)) - sum)
if matrix.get(AX, array.get(Row, deg + 1), deg + 1) != 0.
array.set(CX, deg + 1, array.get(ZX, deg + 1) / matrix.get(AX, array.get(Row, deg + 1), deg + 1))
for k = deg to 1
float sum = 0.
for l = k + 1 to deg + 1
sum += matrix.get(AX, array.get(Row, k), l) * array.get(CX, l)
array.set(CX, k, (array.get(ZX, k) - sum) / matrix.get(AX, array.get(Row, k), k))
sumout := array.get(CX, deg + 1)
for k = deg to 1
sumout := array.get(CX, k) + sumout * len
sumout
Variable Initialization
At the beginning of the function, several arrays and matrices are initialized: sumout, AX, BX, ZX, Pow, Row, and CX. These variables are used to store intermediate results and perform the necessary calculations.
sumout: This variable will store the final moving average result.
AX: A matrix that stores the coefficients of the system of linear equations representing the polynomial regression.
BX: An array that holds the values required for calculating the moving average.
ZX: An array used for storing intermediate results during the Gaussian elimination process.
Pow: An array containing the powers of the independent variable.
Row: An array that keeps track of the row order in the AX matrix.
CX: An array that stores the calculated coefficients of the polynomial regression.
Calculating the BX Array
The function begins by iterating through the length of the moving average window and the degree of the polynomial regression. The purpose of these nested loops is to calculate the values for the BX array. The outer loop iterates from 1 to len, while the inner loop iterates from 1 to deg + 1.
During each iteration, the YK variable is assigned the non-zero value of the source data at the index (len - k), and the XK variable is assigned the current value of k. The Prod variable is initialized with the value 1, and the inner loop calculates the product of YK and Prod. The value of Prod is then updated by multiplying it with XK.
After completing the inner loop, the BX array is updated by adding the product of YK and Prod to its current value at index j. This process continues until both loops are completed, and the BX array contains the necessary values for further calculations.
Calculating the Pow Array
Next, the function initializes the Pow array by setting its 0th element to the length of the moving average window. The Pow array will store the powers of the independent variable. The function then iterates through the length of the moving average window (from 1 to len) and calculates the values of the Pow array based on the polynomial degree.
During each iteration, the XK variable is assigned the current value of k, and the Prod variable is assigned the value of k. The loop then iterates from 1 to 2 * deg, updating the Pow array by adding the current value of Prod to the array element at index j. The value of Prod is updated by multiplying it with XK. Once the loop is complete, the Pow array contains the necessary values for initializing the AX matrix.
Initializing the AX Matrix
Following the calculation of the Pow array, the function initializes the AX matrix using the values from the Pow array. The AX matrix is a square matrix with dimensions (deg + 1) x (deg + 1) and is used to store the coefficients of the polynomial regression.
The function iterates through two nested loops, with the outer loop iterating from 1 to deg + 1 and the inner loop iterating from 1 to deg + 1 as well. During each iteration, the AX matrix is updated by setting the element at position (j, l) to the corresponding value from the Pow array at index (j + l - 2). This process continues until both loops are completed, and the AX matrix is fully populated with the necessary values.
Initializing the Row Array
The next part of the function initializes the Row array, which will be used later to keep track of the row order in the AX matrix. The function iterates through a loop that assigns each element of the array to its index (1 to deg + 1).
Gaussian Elimination
The function employs Gaussian elimination to solve the system of linear equations represented by the AX matrix. Gaussian elimination is an algorithm used to solve linear systems by transforming the system into a triangular matrix using a series of row operations, such as swapping rows, multiplying rows by constants, and adding or subtracting rows.
The function iterates through the deg elements, performing several nested loops that compare, swap, divide, and subtract the matrix elements accordingly. The outer loop iterates from 1 to deg, and the first inner loop iterates from i + 1 to deg + 1. This loop compares the absolute values of the matrix elements and swaps the rows when necessary. The process of comparing and swapping rows ensures that the matrix is in the proper format for Gaussian elimination.
The second inner loop iterates from i + 1 to deg + 1 and is responsible for dividing the matrix elements. If the matrix element at the position (array.get(Row, i), i) is not equal to 0, the matrix element at the position (array.get(Row, k), i) is divided by the matrix element at the position (array.get(Row, i), i).
The third inner loop iterates from i + 1 to deg + 1 and subtracts the matrix elements accordingly. This subtraction process eliminates the coefficients below the main diagonal, effectively transforming the AX matrix into an upper triangular matrix.
Back-substitution and Calculating the CX Array
The function proceeds to perform back-substitution to find the solution to the linear system. The ZX array is filled with the results from the BX array and the Row array. Then, the back-substitution process begins, and the CX array is filled with the calculated coefficients for the polynomial regression.
The function iterates from 1 to deg + 1 to update the ZX array. During each iteration, a sum variable is initialized to 0, and an inner loop iterates from 1 to k - 1. Inside this loop, the sum variable is incremented by the product of the AX matrix element at the position (array.get(Row, k), l) and the ZX array element at index l. After the inner loop, the ZX array is updated by subtracting the sum from the BX array element at the index array.get(Row, k).
Once the ZX array is updated, the function checks if the AX matrix element at the position (array.get(Row, deg + 1), deg + 1) is not equal to 0. If this condition is met, the CX array element at the index (deg + 1) is updated by dividing the ZX array element at the index (deg + 1) by the AX matrix element at the position (array.get(Row, deg + 1), deg + 1).
The function then iterates from deg to 1 in reverse order to update the CX array. A sum variable is initialized to 0, and an inner loop iterates from k + 1 to deg + 1. Inside this loop, the sum variable is incremented by the product of the AX matrix element at the position (array.get(Row, k), l) and the CX array element at index l. After the inner loop, the CX array element at index k is updated by dividing the difference between the ZX array element at index k and the sum by the AX matrix element at the position (array.get(Row, k), k). Once this process is completed, the CX array contains the calculated coefficients of the polynomial regression.
Calculating the Moving Average
The final step of the function is to calculate the moving average using the coefficients stored in the CX array. To do this, the function iterates through the degree of the polynomial regression in reverse order, starting with the highest degree and ending with the lowest. The result is stored in the sumout variable.
The loop iterates from deg to 1. During each iteration, the sumout variable is updated by adding the CX array element at index k to the product of the sumout variable and the length of the moving average window (len). This process continues until the loop is complete, and the sumout variable contains the final moving average value.
Returning the Moving Average
The function concludes by returning the sumout variable, which represents the moving average value at the current data point. The polyout variable is assigned the result of the polynomialRegressionMA(src, dgr, flen) function, and the sig variable is assigned the first element of the polyout array, indicating that the moving average value at the current data point is stored in the sig variable.
Conclusion
The provided code is a comprehensive implementation of a polynomial regression function that calculates the moving average of a given time series data set (src) using a specified polynomial degree (deg) and a specified moving average window length (len). The function employs Gaussian elimination and back-substitution techniques to solve the system of linear equations and find the coefficients for the polynomial regression. These coefficients are then used to compute the moving average.
In conclusion, we dissected the code of a polynomial regression function that creates a moving average, explaining each component's role in the overall process. The function demonstrates the power of polynomial regression in smoothing out fluctuations in time series data and revealing underlying trends, making it a valuable tool in the field of data analysis.
█ Giga Kaleidoscope Modularized Trading System
Core components of an NNFX algorithmic trading strategy
The NNFX algorithm is built on the principles of trend, momentum, and volatility. There are six core components in the NNFX trading algorithm:
1. Volatility - price volatility; e.g., Average True Range, True Range Double, Close-to-Close, etc.
2. Baseline - a moving average to identify price trend
3. Confirmation 1 - a technical indicator used to identify trends
4. Confirmation 2 - a technical indicator used to identify trends
5. Continuation - a technical indicator used to identify trends
6. Volatility/Volume - a technical indicator used to identify volatility/volume breakouts/breakdown
7. Exit - a technical indicator used to determine when a trend is exhausted
What is Volatility in the NNFX trading system?
In the NNFX (No Nonsense Forex) trading system, ATR (Average True Range) is typically used to measure the volatility of an asset. It is used as a part of the system to help determine the appropriate stop loss and take profit levels for a trade. ATR is calculated by taking the average of the true range values over a specified period.
True range is calculated as the maximum of the following values:
-Current high minus the current low
-Absolute value of the current high minus the previous close
-Absolute value of the current low minus the previous close
ATR is a dynamic indicator that changes with changes in volatility. As volatility increases, the value of ATR increases, and as volatility decreases, the value of ATR decreases. By using ATR in NNFX system, traders can adjust their stop loss and take profit levels according to the volatility of the asset being traded. This helps to ensure that the trade is given enough room to move, while also minimizing potential losses.
Other types of volatility include True Range Double (TRD), Close-to-Close, and Garman-Klass
What is a Baseline indicator?
The baseline is essentially a moving average, and is used to determine the overall direction of the market.
The baseline in the NNFX system is used to filter out trades that are not in line with the long-term trend of the market. The baseline is plotted on the chart along with other indicators, such as the Moving Average (MA), the Relative Strength Index (RSI), and the Average True Range (ATR).
Trades are only taken when the price is in the same direction as the baseline. For example, if the baseline is sloping upwards, only long trades are taken, and if the baseline is sloping downwards, only short trades are taken. This approach helps to ensure that trades are in line with the overall trend of the market, and reduces the risk of entering trades that are likely to fail.
By using a baseline in the NNFX system, traders can have a clear reference point for determining the overall trend of the market, and can make more informed trading decisions. The baseline helps to filter out noise and false signals, and ensures that trades are taken in the direction of the long-term trend.
What is a Confirmation indicator?
Confirmation indicators are technical indicators that are used to confirm the signals generated by primary indicators. Primary indicators are the core indicators used in the NNFX system, such as the Average True Range (ATR), the Moving Average (MA), and the Relative Strength Index (RSI).
The purpose of the confirmation indicators is to reduce false signals and improve the accuracy of the trading system. They are designed to confirm the signals generated by the primary indicators by providing additional information about the strength and direction of the trend.
Some examples of confirmation indicators that may be used in the NNFX system include the Bollinger Bands, the MACD (Moving Average Convergence Divergence), and the MACD Oscillator. These indicators can provide information about the volatility, momentum, and trend strength of the market, and can be used to confirm the signals generated by the primary indicators.
In the NNFX system, confirmation indicators are used in combination with primary indicators and other filters to create a trading system that is robust and reliable. By using multiple indicators to confirm trading signals, the system aims to reduce the risk of false signals and improve the overall profitability of the trades.
What is a Continuation indicator?
In the NNFX (No Nonsense Forex) trading system, a continuation indicator is a technical indicator that is used to confirm a current trend and predict that the trend is likely to continue in the same direction. A continuation indicator is typically used in conjunction with other indicators in the system, such as a baseline indicator, to provide a comprehensive trading strategy.
What is a Volatility/Volume indicator?
Volume indicators, such as the On Balance Volume (OBV), the Chaikin Money Flow (CMF), or the Volume Price Trend (VPT), are used to measure the amount of buying and selling activity in a market. They are based on the trading volume of the market, and can provide information about the strength of the trend. In the NNFX system, volume indicators are used to confirm trading signals generated by the Moving Average and the Relative Strength Index. Volatility indicators include Average Direction Index, Waddah Attar, and Volatility Ratio. In the NNFX trading system, volatility is a proxy for volume and vice versa.
By using volume indicators as confirmation tools, the NNFX trading system aims to reduce the risk of false signals and improve the overall profitability of trades. These indicators can provide additional information about the market that is not captured by the primary indicators, and can help traders to make more informed trading decisions. In addition, volume indicators can be used to identify potential changes in market trends and to confirm the strength of price movements.
What is an Exit indicator?
The exit indicator is used in conjunction with other indicators in the system, such as the Moving Average (MA), the Relative Strength Index (RSI), and the Average True Range (ATR), to provide a comprehensive trading strategy.
The exit indicator in the NNFX system can be any technical indicator that is deemed effective at identifying optimal exit points. Examples of exit indicators that are commonly used include the Parabolic SAR, the Average Directional Index (ADX), and the Chandelier Exit.
The purpose of the exit indicator is to identify when a trend is likely to reverse or when the market conditions have changed, signaling the need to exit a trade. By using an exit indicator, traders can manage their risk and prevent significant losses.
In the NNFX system, the exit indicator is used in conjunction with a stop loss and a take profit order to maximize profits and minimize losses. The stop loss order is used to limit the amount of loss that can be incurred if the trade goes against the trader, while the take profit order is used to lock in profits when the trade is moving in the trader's favor.
Overall, the use of an exit indicator in the NNFX trading system is an important component of a comprehensive trading strategy. It allows traders to manage their risk effectively and improve the profitability of their trades by exiting at the right time.
How does Loxx's GKD (Giga Kaleidoscope Modularized Trading System) implement the NNFX algorithm outlined above?
Loxx's GKD v1.0 system has five types of modules (indicators/strategies). These modules are:
1. GKD-BT - Backtesting module (Volatility, Number 1 in the NNFX algorithm)
2. GKD-B - Baseline module (Baseline and Volatility/Volume, Numbers 1 and 2 in the NNFX algorithm)
3. GKD-C - Confirmation 1/2 and Continuation module (Confirmation 1/2 and Continuation, Numbers 3, 4, and 5 in the NNFX algorithm)
4. GKD-V - Volatility/Volume module (Confirmation 1/2, Number 6 in the NNFX algorithm)
5. GKD-E - Exit module (Exit, Number 7 in the NNFX algorithm)
(additional module types will added in future releases)
Each module interacts with every module by passing data between modules. Data is passed between each module as described below:
GKD-B => GKD-V => GKD-C(1) => GKD-C(2) => GKD-C(Continuation) => GKD-E => GKD-BT
That is, the Baseline indicator passes its data to Volatility/Volume. The Volatility/Volume indicator passes its values to the Confirmation 1 indicator. The Confirmation 1 indicator passes its values to the Confirmation 2 indicator. The Confirmation 2 indicator passes its values to the Continuation indicator. The Continuation indicator passes its values to the Exit indicator, and finally, the Exit indicator passes its values to the Backtest strategy.
This chaining of indicators requires that each module conform to Loxx's GKD protocol, therefore allowing for the testing of every possible combination of technical indicators that make up the six components of the NNFX algorithm.
What does the application of the GKD trading system look like?
Example trading system:
Backtest: Strategy with 1-3 take profits, trailing stop loss, multiple types of PnL volatility, and 2 backtesting styles
Baseline: Hull Moving Average
Volatility/Volume: Hurst Exponent
Confirmation 1: Polynomial-Regression-Fitted Filter as shown on the chart above
Confirmation 2: Williams Percent Range
Continuation: Fisher Transform
Exit: Rex Oscillator
Each GKD indicator is denoted with a module identifier of either: GKD-BT, GKD-B, GKD-C, GKD-V, or GKD-E. This allows traders to understand to which module each indicator belongs and where each indicator fits into the GKD protocol chain.
Giga Kaleidoscope Modularized Trading System Signals (based on the NNFX algorithm)
Standard Entry
1. GKD-C Confirmation 1 Signal
2. GKD-B Baseline agrees
3. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
4. GKD-C Confirmation 2 agrees
5. GKD-V Volatility/Volume agrees
Baseline Entry
1. GKD-B Baseline signal
2. GKD-C Confirmation 1 agrees
3. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
4. GKD-C Confirmation 2 agrees
5. GKD-V Volatility/Volume agrees
6. GKD-C Confirmation 1 signal was less than 7 candles prior
Volatility/Volume Entry
1. GKD-V Volatility/Volume signal
2. GKD-C Confirmation 1 agrees
3. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
4. GKD-C Confirmation 2 agrees
5. GKD-B Baseline agrees
6. GKD-C Confirmation 1 signal was less than 7 candles prior
Continuation Entry
1. Standard Entry, Baseline Entry, or Pullback; entry triggered previously
2. GKD-B Baseline hasn't crossed since entry signal trigger
3. GKD-C Confirmation Continuation Indicator signals
4. GKD-C Confirmation 1 agrees
5. GKD-B Baseline agrees
6. GKD-C Confirmation 2 agrees
1-Candle Rule Standard Entry
1. GKD-C Confirmation 1 signal
2. GKD-B Baseline agrees
3. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
Next Candle:
1. Price retraced (Long: close < close or Short: close > close )
2. GKD-B Baseline agrees
3. GKD-C Confirmation 1 agrees
4. GKD-C Confirmation 2 agrees
5. GKD-V Volatility/Volume agrees
1-Candle Rule Baseline Entry
1. GKD-B Baseline signal
2. GKD-C Confirmation 1 agrees
3. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
4. GKD-C Confirmation 1 signal was less than 7 candles prior
Next Candle:
1. Price retraced (Long: close < close or Short: close > close )
2. GKD-B Baseline agrees
3. GKD-C Confirmation 1 agrees
4. GKD-C Confirmation 2 agrees
5. GKD-V Volatility/Volume Agrees
1-Candle Rule Volatility/Volume Entry
1. GKD-V Volatility/Volume signal
2. GKD-C Confirmation 1 agrees
3. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
4. GKD-C Confirmation 1 signal was less than 7 candles prior
Next Candle:
1. Price retraced (Long: close < close or Short: close > close)
2. GKD-B Volatility/Volume agrees
3. GKD-C Confirmation 1 agrees
4. GKD-C Confirmation 2 agrees
5. GKD-B Baseline agrees
PullBack Entry
1. GKD-B Baseline signal
2. GKD-C Confirmation 1 agrees
3. Price is beyond 1.0x Volatility of Baseline
Next Candle:
1. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
2. GKD-C Confirmation 1 agrees
3. GKD-C Confirmation 2 agrees
4. GKD-V Volatility/Volume Agrees
]█ Setting up the GKD
The GKD system involves chaining indicators together. These are the steps to set this up.
Use a GKD-C indicator alone on a chart
1. Inside the GKD-C indicator, change the "Confirmation Type" setting to "Solo Confirmation Simple"
Use a GKD-V indicator alone on a chart
**nothing, it's already useable on the chart without any settings changes
Use a GKD-B indicator alone on a chart
**nothing, it's already useable on the chart without any settings changes
Baseline (Baseline, Backtest)
1. Import the GKD-B Baseline into the GKD-BT Backtest: "Input into Volatility/Volume or Backtest (Baseline testing)"
2. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "Baseline"
Volatility/Volume (Volatility/Volume, Backte st)
1. Inside the GKD-V indicator, change the "Testing Type" setting to "Solo"
2. Inside the GKD-V indicator, change the "Signal Type" setting to "Crossing" (neither traditional nor both can be backtested)
3. Import the GKD-V indicator into the GKD-BT Backtest: "Input into C1 or Backtest"
4. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "Volatility/Volume"
5. Inside the GKD-BT Backtest, a) change the setting "Backtest Type" to "Trading" if using a directional GKD-V indicator; or, b) change the setting "Backtest Type" to "Full" if using a directional or non-directional GKD-V indicator (non-directional GKD-V can only test Longs and Shorts separately)
6. If "Backtest Type" is set to "Full": Inside the GKD-BT Backtest, change the setting "Backtest Side" to "Long" or "Short
7. If "Backtest Type" is set to "Full": To allow the system to open multiple orders at one time so you test all Longs or Shorts, open the GKD-BT Backtest, click the tab "Properties" and then insert a value of something like 10 orders into the "Pyramiding" settings. This will allow 10 orders to be opened at one time which should be enough to catch all possible Longs or Shorts.
Solo Confirmation Simple (Confirmation, Backtest)
1. Inside the GKD-C indicator, change the "Confirmation Type" setting to "Solo Confirmation Simple"
1. Import the GKD-C indicator into the GKD-BT Backtest: "Input into Backtest"
2. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "Solo Confirmation Simple"
Solo Confirmation Complex without Exits (Baseline, Volatility/Volume, Confirmation, Backtest)
1. Inside the GKD-V indicator, change the "Testing Type" setting to "Chained"
2. Import the GKD-B Baseline into the GKD-V indicator: "Input into Volatility/Volume or Backtest (Baseline testing)"
3. Inside the GKD-C indicator, change the "Confirmation Type" setting to "Solo Confirmation Complex"
4. Import the GKD-V indicator into the GKD-C indicator: "Input into C1 or Backtest"
5. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "GKD Full wo/ Exits"
6. Import the GKD-C into the GKD-BT Backtest: "Input into Exit or Backtest"
Solo Confirmation Complex with Exits (Baseline, Volatility/Volume, Confirmation, Exit, Backtest)
1. Inside the GKD-V indicator, change the "Testing Type" setting to "Chained"
2. Import the GKD-B Baseline into the GKD-V indicator: "Input into Volatility/Volume or Backtest (Baseline testing)"
3. Inside the GKD-C indicator, change the "Confirmation Type" setting to "Solo Confirmation Complex"
4. Import the GKD-V indicator into the GKD-C indicator: "Input into C1 or Backtest"
5. Import the GKD-C indicator into the GKD-E indicator: "Input into Exit"
6. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "GKD Full w/ Exits"
7. Import the GKD-E into the GKD-BT Backtest: "Input into Backtest"
Full GKD without Exits (Baseline, Volatility/Volume, Confirmation 1, Confirmation 2, Continuation, Backtest)
1. Inside the GKD-V indicator, change the "Testing Type" setting to "Chained"
2. Import the GKD-B Baseline into the GKD-V indicator: "Input into Volatility/Volume or Backtest (Baseline testing)"
3. Inside the GKD-C 1 indicator, change the "Confirmation Type" setting to "Confirmation 1"
4. Import the GKD-V indicator into the GKD-C 1 indicator: "Input into C1 or Backtest"
5. Inside the GKD-C 2 indicator, change the "Confirmation Type" setting to "Confirmation 2"
6. Import the GKD-C 1 indicator into the GKD-C 2 indicator: "Input into C2"
7. Inside the GKD-C Continuation indicator, change the "Confirmation Type" setting to "Continuation"
8. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "GKD Full wo/ Exits"
9. Import the GKD-E into the GKD-BT Backtest: "Input into Exit or Backtest"
Full GKD with Exits (Baseline, Volatility/Volume, Confirmation 1, Confirmation 2, Continuation, Exit, Backtest)
1. Inside the GKD-V indicator, change the "Testing Type" setting to "Chained"
2. Import the GKD-B Baseline into the GKD-V indicator: "Input into Volatility/Volume or Backtest (Baseline testing)"
3. Inside the GKD-C 1 indicator, change the "Confirmation Type" setting to "Confirmation 1"
4. Import the GKD-V indicator into the GKD-C 1 indicator: "Input into C1 or Backtest"
5. Inside the GKD-C 2 indicator, change the "Confirmation Type" setting to "Confirmation 2"
6. Import the GKD-C 1 indicator into the GKD-C 2 indicator: "Input into C2"
7. Inside the GKD-C Continuation indicator, change the "Confirmation Type" setting to "Continuation"
8. Import the GKD-C Continuation indicator into the GKD-E indicator: "Input into Exit"
9. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "GKD Full w/ Exits"
10. Import the GKD-E into the GKD-BT Backtest: "Input into Backtest"
Baseline + Volatility/Volume (Baseline, Volatility/Volume, Backtest)
1. Inside the GKD-V indicator, change the "Testing Type" setting to "Baseline + Volatility/Volume"
2. Inside the GKD-V indicator, make sure the "Signal Type" setting is set to "Traditional"
3. Import the GKD-B Baseline into the GKD-V indicator: "Input into Volatility/Volume or Backtest (Baseline testing)"
4. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "Baseline + Volatility/Volume"
5. Import the GKD-V into the GKD-BT Backtest: "Input into C1 or Backtest"
6. Inside the GKD-BT Backtest, change the setting "Backtest Type" to "Full". For this backtest, you must test Longs and Shorts separately
7. To allow the system to open multiple orders at one time so you can test all Longs or Shorts, open the GKD-BT Backtest, click the tab "Properties" and then insert a value of something like 10 orders into the "Pyramiding" settings. This will allow 10 orders to be opened at one time which should be enough to catch all possible Longs or Shorts.
Requirements
Inputs
Confirmation 1: GKD-V Volatility / Volume indicator
Confirmation 2: GKD-C Confirmation indicator
Continuation: GKD-C Confirmation indicator
Solo Confirmation Simple: GKD-B Baseline
Solo Confirmation Complex: GKD-V Volatility / Volume indicator
Solo Confirmation Super Complex: GKD-V Volatility / Volume indicator
Stacked 1: None
Stacked 2+: GKD-C, GKD-V, or GKD-B Stacked 1
Outputs
Confirmation 1: GKD-C Confirmation 2 indicator
Confirmation 2: GKD-C Continuation indicator
Continuation: GKD-E Exit indicator
Solo Confirmation Simple: GKD-BT Backtest
Solo Confirmation Complex: GKD-BT Backtest or GKD-E Exit indicator
Solo Confirmation Super Complex: GKD-C Continuation indicator
Stacked 1: GKD-C, GKD-V, or GKD-B Stacked 2+
Stacked 2+: GKD-C, GKD-V, or GKD-B Stacked 2+ or GKD-BT Backtest
Additional features will be added in future releases.
Statistics
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.
GKD-C RSX VDI w/ Confidence Bands [Loxx]Giga Kaleidoscope GKD-C RSX VDI w/ Confidence Bands is a Confirmation module included in Loxx's "Giga Kaleidoscope Modularized Trading System".
█ Giga Kaleidoscope Modularized Trading System
What is Loxx's "Giga Kaleidoscope Modularized Trading System"?
The Giga Kaleidoscope Modularized Trading System is a trading system built on the philosophy of the NNFX (No Nonsense Forex) algorithmic trading.
What is the NNFX algorithmic trading strategy?
The NNFX (No-Nonsense Forex) trading system is a comprehensive approach to Forex trading that is designed to simplify the process and remove the confusion and complexity that often surrounds trading. The system was developed by a Forex trader who goes by the pseudonym "VP" and has gained a significant following in the Forex community.
The NNFX trading system is based on a set of rules and guidelines that help traders make objective and informed decisions. These rules cover all aspects of trading, including market analysis, trade entry, stop loss placement, and trade management.
Here are the main components of the NNFX trading system:
1. Trading Philosophy: The NNFX trading system is based on the idea that successful trading requires a comprehensive understanding of the market, objective analysis, and strict risk management. The system aims to remove subjective elements from trading and focuses on objective rules and guidelines.
2. Technical Analysis: The NNFX trading system relies heavily on technical analysis and uses a range of indicators to identify high-probability trading opportunities. The system uses a combination of trend-following and mean-reverting strategies to identify trades.
3. Market Structure: The NNFX trading system emphasizes the importance of understanding the market structure, including price action, support and resistance levels, and market cycles. The system uses a range of tools to identify the market structure, including trend lines, channels, and moving averages.
4. Trade Entry: The NNFX trading system has strict rules for trade entry. The system uses a combination of technical indicators to identify high-probability trades, and traders must meet specific criteria to enter a trade.
5. Stop Loss Placement: The NNFX trading system places a significant emphasis on risk management and requires traders to place a stop loss order on every trade. The system uses a combination of technical analysis and market structure to determine the appropriate stop loss level.
6. Trade Management: The NNFX trading system has specific rules for managing open trades. The system aims to minimize risk and maximize profit by using a combination of trailing stops, take profit levels, and position sizing.
Overall, the NNFX trading system is designed to be a straightforward and easy-to-follow approach to Forex trading that can be applied by traders of all skill levels.
Core components of an NNFX algorithmic trading strategy
The NNFX algorithm is built on the principles of trend, momentum, and volatility. There are six core components in the NNFX trading algorithm:
1. Volatility - price volatility; e.g., Average True Range, True Range Double, Close-to-Close, etc.
2. Baseline - a moving average to identify price trend
3. Confirmation 1 - a technical indicator used to identify trends
4. Confirmation 2 - a technical indicator used to identify trends
5. Continuation - a technical indicator used to identify trends
6. Volatility/Volume - a technical indicator used to identify volatility/volume breakouts/breakdown
7. Exit - a technical indicator used to determine when a trend is exhausted
What is Volatility in the NNFX trading system?
In the NNFX (No Nonsense Forex) trading system, ATR (Average True Range) is typically used to measure the volatility of an asset. It is used as a part of the system to help determine the appropriate stop loss and take profit levels for a trade. ATR is calculated by taking the average of the true range values over a specified period.
True range is calculated as the maximum of the following values:
-Current high minus the current low
-Absolute value of the current high minus the previous close
-Absolute value of the current low minus the previous close
ATR is a dynamic indicator that changes with changes in volatility. As volatility increases, the value of ATR increases, and as volatility decreases, the value of ATR decreases. By using ATR in NNFX system, traders can adjust their stop loss and take profit levels according to the volatility of the asset being traded. This helps to ensure that the trade is given enough room to move, while also minimizing potential losses.
Other types of volatility include True Range Double (TRD), Close-to-Close, and Garman-Klass
What is a Baseline indicator?
The baseline is essentially a moving average, and is used to determine the overall direction of the market.
The baseline in the NNFX system is used to filter out trades that are not in line with the long-term trend of the market. The baseline is plotted on the chart along with other indicators, such as the Moving Average (MA), the Relative Strength Index (RSI), and the Average True Range (ATR).
Trades are only taken when the price is in the same direction as the baseline. For example, if the baseline is sloping upwards, only long trades are taken, and if the baseline is sloping downwards, only short trades are taken. This approach helps to ensure that trades are in line with the overall trend of the market, and reduces the risk of entering trades that are likely to fail.
By using a baseline in the NNFX system, traders can have a clear reference point for determining the overall trend of the market, and can make more informed trading decisions. The baseline helps to filter out noise and false signals, and ensures that trades are taken in the direction of the long-term trend.
What is a Confirmation indicator?
Confirmation indicators are technical indicators that are used to confirm the signals generated by primary indicators. Primary indicators are the core indicators used in the NNFX system, such as the Average True Range (ATR), the Moving Average (MA), and the Relative Strength Index (RSI).
The purpose of the confirmation indicators is to reduce false signals and improve the accuracy of the trading system. They are designed to confirm the signals generated by the primary indicators by providing additional information about the strength and direction of the trend.
Some examples of confirmation indicators that may be used in the NNFX system include the Bollinger Bands, the MACD (Moving Average Convergence Divergence), and the MACD Oscillator. These indicators can provide information about the volatility, momentum, and trend strength of the market, and can be used to confirm the signals generated by the primary indicators.
In the NNFX system, confirmation indicators are used in combination with primary indicators and other filters to create a trading system that is robust and reliable. By using multiple indicators to confirm trading signals, the system aims to reduce the risk of false signals and improve the overall profitability of the trades.
What is a Continuation indicator?
In the NNFX (No Nonsense Forex) trading system, a continuation indicator is a technical indicator that is used to confirm a current trend and predict that the trend is likely to continue in the same direction. A continuation indicator is typically used in conjunction with other indicators in the system, such as a baseline indicator, to provide a comprehensive trading strategy.
What is a Volatility/Volume indicator?
Volume indicators, such as the On Balance Volume (OBV), the Chaikin Money Flow (CMF), or the Volume Price Trend (VPT), are used to measure the amount of buying and selling activity in a market. They are based on the trading volume of the market, and can provide information about the strength of the trend. In the NNFX system, volume indicators are used to confirm trading signals generated by the Moving Average and the Relative Strength Index. Volatility indicators include Average Direction Index, Waddah Attar, and Volatility Ratio. In the NNFX trading system, volatility is a proxy for volume and vice versa.
By using volume indicators as confirmation tools, the NNFX trading system aims to reduce the risk of false signals and improve the overall profitability of trades. These indicators can provide additional information about the market that is not captured by the primary indicators, and can help traders to make more informed trading decisions. In addition, volume indicators can be used to identify potential changes in market trends and to confirm the strength of price movements.
What is an Exit indicator?
The exit indicator is used in conjunction with other indicators in the system, such as the Moving Average (MA), the Relative Strength Index (RSI), and the Average True Range (ATR), to provide a comprehensive trading strategy.
The exit indicator in the NNFX system can be any technical indicator that is deemed effective at identifying optimal exit points. Examples of exit indicators that are commonly used include the Parabolic SAR, the Average Directional Index (ADX), and the Chandelier Exit.
The purpose of the exit indicator is to identify when a trend is likely to reverse or when the market conditions have changed, signaling the need to exit a trade. By using an exit indicator, traders can manage their risk and prevent significant losses.
In the NNFX system, the exit indicator is used in conjunction with a stop loss and a take profit order to maximize profits and minimize losses. The stop loss order is used to limit the amount of loss that can be incurred if the trade goes against the trader, while the take profit order is used to lock in profits when the trade is moving in the trader's favor.
Overall, the use of an exit indicator in the NNFX trading system is an important component of a comprehensive trading strategy. It allows traders to manage their risk effectively and improve the profitability of their trades by exiting at the right time.
How does Loxx's GKD (Giga Kaleidoscope Modularized Trading System) implement the NNFX algorithm outlined above?
Loxx's GKD v1.0 system has five types of modules (indicators/strategies). These modules are:
1. GKD-BT - Backtesting module (Volatility, Number 1 in the NNFX algorithm)
2. GKD-B - Baseline module (Baseline and Volatility/Volume, Numbers 1 and 2 in the NNFX algorithm)
3. GKD-C - Confirmation 1/2 and Continuation module (Confirmation 1/2 and Continuation, Numbers 3, 4, and 5 in the NNFX algorithm)
4. GKD-V - Volatility/Volume module (Confirmation 1/2, Number 6 in the NNFX algorithm)
5. GKD-E - Exit module (Exit, Number 7 in the NNFX algorithm)
(additional module types will added in future releases)
Each module interacts with every module by passing data between modules. Data is passed between each module as described below:
GKD-B => GKD-V => GKD-C(1) => GKD-C(2) => GKD-C(Continuation) => GKD-E => GKD-BT
That is, the Baseline indicator passes its data to Volatility/Volume. The Volatility/Volume indicator passes its values to the Confirmation 1 indicator. The Confirmation 1 indicator passes its values to the Confirmation 2 indicator. The Confirmation 2 indicator passes its values to the Continuation indicator. The Continuation indicator passes its values to the Exit indicator, and finally, the Exit indicator passes its values to the Backtest strategy.
This chaining of indicators requires that each module conform to Loxx's GKD protocol, therefore allowing for the testing of every possible combination of technical indicators that make up the six components of the NNFX algorithm.
What does the application of the GKD trading system look like?
Example trading system:
Backtest: Strategy with 1-3 take profits, trailing stop loss, multiple types of PnL volatility, and 2 backtesting styles
Baseline: Hull Moving Average
Volatility/Volume: Hurst Exponent
Confirmation 1: RSX VDI w/ Confidence Bands as shown on the chart above
Confirmation 2: Williams Percent Range
Continuation: Fisher Transform
Exit: Rex Oscillator
Each GKD indicator is denoted with a module identifier of either: GKD-BT, GKD-B, GKD-C, GKD-V, or GKD-E. This allows traders to understand to which module each indicator belongs and where each indicator fits into the GKD protocol chain.
Giga Kaleidoscope Modularized Trading System Signals (based on the NNFX algorithm)
Standard Entry
1. GKD-C Confirmation 1 Signal
2. GKD-B Baseline agrees
3. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
4. GKD-C Confirmation 2 agrees
5. GKD-V Volatility/Volume agrees
Baseline Entry
1. GKD-B Baseline signal
2. GKD-C Confirmation 1 agrees
3. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
4. GKD-C Confirmation 2 agrees
5. GKD-V Volatility/Volume agrees
6. GKD-C Confirmation 1 signal was less than 7 candles prior
Volatility/Volume Entry
1. GKD-V Volatility/Volume signal
2. GKD-C Confirmation 1 agrees
3. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
4. GKD-C Confirmation 2 agrees
5. GKD-B Baseline agrees
6. GKD-C Confirmation 1 signal was less than 7 candles prior
Continuation Entry
1. Standard Entry, Baseline Entry, or Pullback; entry triggered previously
2. GKD-B Baseline hasn't crossed since entry signal trigger
3. GKD-C Confirmation Continuation Indicator signals
4. GKD-C Confirmation 1 agrees
5. GKD-B Baseline agrees
6. GKD-C Confirmation 2 agrees
1-Candle Rule Standard Entry
1. GKD-C Confirmation 1 signal
2. GKD-B Baseline agrees
3. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
Next Candle:
1. Price retraced (Long: close < close or Short: close > close )
2. GKD-B Baseline agrees
3. GKD-C Confirmation 1 agrees
4. GKD-C Confirmation 2 agrees
5. GKD-V Volatility/Volume agrees
1-Candle Rule Baseline Entry
1. GKD-B Baseline signal
2. GKD-C Confirmation 1 agrees
3. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
4. GKD-C Confirmation 1 signal was less than 7 candles prior
Next Candle:
1. Price retraced (Long: close < close or Short: close > close )
2. GKD-B Baseline agrees
3. GKD-C Confirmation 1 agrees
4. GKD-C Confirmation 2 agrees
5. GKD-V Volatility/Volume Agrees
1-Candle Rule Volatility/Volume Entry
1. GKD-V Volatility/Volume signal
2. GKD-C Confirmation 1 agrees
3. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
4. GKD-C Confirmation 1 signal was less than 7 candles prior
Next Candle:
1. Price retraced (Long: close < close or Short: close > close)
2. GKD-B Volatility/Volume agrees
3. GKD-C Confirmation 1 agrees
4. GKD-C Confirmation 2 agrees
5. GKD-B Baseline agrees
PullBack Entry
1. GKD-B Baseline signal
2. GKD-C Confirmation 1 agrees
3. Price is beyond 1.0x Volatility of Baseline
Next Candle:
1. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
2. GKD-C Confirmation 1 agrees
3. GKD-C Confirmation 2 agrees
4. GKD-V Volatility/Volume Agrees
]█ Setting up the GKD
The GKD system involves chaining indicators together. These are the steps to set this up.
Use a GKD-C indicator alone on a chart
1. Inside the GKD-C indicator, change the "Confirmation Type" setting to "Solo Confirmation Simple"
Use a GKD-V indicator alone on a chart
**nothing, it's already useable on the chart without any settings changes
Use a GKD-B indicator alone on a chart
**nothing, it's already useable on the chart without any settings changes
Baseline (Baseline, Backtest)
1. Import the GKD-B Baseline into the GKD-BT Backtest: "Input into Volatility/Volume or Backtest (Baseline testing)"
2. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "Baseline"
Volatility/Volume (Volatility/Volume, Backte st)
1. Inside the GKD-V indicator, change the "Testing Type" setting to "Solo"
2. Inside the GKD-V indicator, change the "Signal Type" setting to "Crossing" (neither traditional nor both can be backtested)
3. Import the GKD-V indicator into the GKD-BT Backtest: "Input into C1 or Backtest"
4. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "Volatility/Volume"
5. Inside the GKD-BT Backtest, a) change the setting "Backtest Type" to "Trading" if using a directional GKD-V indicator; or, b) change the setting "Backtest Type" to "Full" if using a directional or non-directional GKD-V indicator (non-directional GKD-V can only test Longs and Shorts separately)
6. If "Backtest Type" is set to "Full": Inside the GKD-BT Backtest, change the setting "Backtest Side" to "Long" or "Short
7. If "Backtest Type" is set to "Full": To allow the system to open multiple orders at one time so you test all Longs or Shorts, open the GKD-BT Backtest, click the tab "Properties" and then insert a value of something like 10 orders into the "Pyramiding" settings. This will allow 10 orders to be opened at one time which should be enough to catch all possible Longs or Shorts.
Solo Confirmation Simple (Confirmation, Backtest)
1. Inside the GKD-C indicator, change the "Confirmation Type" setting to "Solo Confirmation Simple"
1. Import the GKD-C indicator into the GKD-BT Backtest: "Input into Backtest"
2. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "Solo Confirmation Simple"
Solo Confirmation Complex without Exits (Baseline, Volatility/Volume, Confirmation, Backtest)
1. Inside the GKD-V indicator, change the "Testing Type" setting to "Chained"
2. Import the GKD-B Baseline into the GKD-V indicator: "Input into Volatility/Volume or Backtest (Baseline testing)"
3. Inside the GKD-C indicator, change the "Confirmation Type" setting to "Solo Confirmation Complex"
4. Import the GKD-V indicator into the GKD-C indicator: "Input into C1 or Backtest"
5. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "GKD Full wo/ Exits"
6. Import the GKD-C into the GKD-BT Backtest: "Input into Exit or Backtest"
Solo Confirmation Complex with Exits (Baseline, Volatility/Volume, Confirmation, Exit, Backtest)
1. Inside the GKD-V indicator, change the "Testing Type" setting to "Chained"
2. Import the GKD-B Baseline into the GKD-V indicator: "Input into Volatility/Volume or Backtest (Baseline testing)"
3. Inside the GKD-C indicator, change the "Confirmation Type" setting to "Solo Confirmation Complex"
4. Import the GKD-V indicator into the GKD-C indicator: "Input into C1 or Backtest"
5. Import the GKD-C indicator into the GKD-E indicator: "Input into Exit"
6. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "GKD Full w/ Exits"
7. Import the GKD-E into the GKD-BT Backtest: "Input into Backtest"
Full GKD without Exits (Baseline, Volatility/Volume, Confirmation 1, Confirmation 2, Continuation, Backtest)
1. Inside the GKD-V indicator, change the "Testing Type" setting to "Chained"
2. Import the GKD-B Baseline into the GKD-V indicator: "Input into Volatility/Volume or Backtest (Baseline testing)"
3. Inside the GKD-C 1 indicator, change the "Confirmation Type" setting to "Confirmation 1"
4. Import the GKD-V indicator into the GKD-C 1 indicator: "Input into C1 or Backtest"
5. Inside the GKD-C 2 indicator, change the "Confirmation Type" setting to "Confirmation 2"
6. Import the GKD-C 1 indicator into the GKD-C 2 indicator: "Input into C2"
7. Inside the GKD-C Continuation indicator, change the "Confirmation Type" setting to "Continuation"
8. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "GKD Full wo/ Exits"
9. Import the GKD-E into the GKD-BT Backtest: "Input into Exit or Backtest"
Full GKD with Exits (Baseline, Volatility/Volume, Confirmation 1, Confirmation 2, Continuation, Exit, Backtest)
1. Inside the GKD-V indicator, change the "Testing Type" setting to "Chained"
2. Import the GKD-B Baseline into the GKD-V indicator: "Input into Volatility/Volume or Backtest (Baseline testing)"
3. Inside the GKD-C 1 indicator, change the "Confirmation Type" setting to "Confirmation 1"
4. Import the GKD-V indicator into the GKD-C 1 indicator: "Input into C1 or Backtest"
5. Inside the GKD-C 2 indicator, change the "Confirmation Type" setting to "Confirmation 2"
6. Import the GKD-C 1 indicator into the GKD-C 2 indicator: "Input into C2"
7. Inside the GKD-C Continuation indicator, change the "Confirmation Type" setting to "Continuation"
8. Import the GKD-C Continuation indicator into the GKD-E indicator: "Input into Exit"
9. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "GKD Full w/ Exits"
10. Import the GKD-E into the GKD-BT Backtest: "Input into Backtest"
Baseline + Volatility/Volume (Baseline, Volatility/Volume, Backtest)
1. Inside the GKD-V indicator, change the "Testing Type" setting to "Baseline + Volatility/Volume"
2. Inside the GKD-V indicator, make sure the "Signal Type" setting is set to "Traditional"
3. Import the GKD-B Baseline into the GKD-V indicator: "Input into Volatility/Volume or Backtest (Baseline testing)"
4. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "Baseline + Volatility/Volume"
5. Import the GKD-V into the GKD-BT Backtest: "Input into C1 or Backtest"
6. Inside the GKD-BT Backtest, change the setting "Backtest Type" to "Full". For this backtest, you must test Longs and Shorts separately
7. To allow the system to open multiple orders at one time so you can test all Longs or Shorts, open the GKD-BT Backtest, click the tab "Properties" and then insert a value of something like 10 orders into the "Pyramiding" settings. This will allow 10 orders to be opened at one time which should be enough to catch all possible Longs or Shorts.
█ GKD-C RSX VDI w/ Confidence Bands
What is the VDI (Volatility Direction Index)?
The Volatility Direction Index Index (VDI) is a technical analysis indicator developed by Loxx. It is designed to help traders and investors identify potential trend reversals, confirm existing trends, and recognize overbought or oversold market conditions. VDI is a momentum oscillator that measures the volatility and price direction of an asset over a specified period.
Here's a step-by-step breakdown of how to calculate VDI:
Choose a period (n) over which to calculate the VDI, typically 8 or 10.
Calculate the true range for each day:
True Range = max
Calculate the directional bias for each day:
If (Today's High - Previous Close) > (Previous Close - Today's Low), the directional bias is positive.
If (Today's High - Previous Close) < (Previous Close - Today's Low), the directional bias is negative.
Calculate the VDI for each day with a positive directional bias:
VDI Positive = * 100
Calculate the VDI for each day with a negative directional bias:
VDI Negative = * 100
Calculate the n-day sum of positive VDI values (Sum_Positive_VDI) and the n-day sum of negative VDI values (Sum_Negative_VDI).
Calculate the final Volatility Direction Index Index value:
VDI = (Sum_Positive_VDI - Sum_Negative_VDI) / (Sum_Positive_VDI + Sum_Negative_VDI) * 100
This VDI value can then be plotted on a chart over time to help traders and investors visualize the momentum and volatility of the asset's price.
VDI oscillates between -100 and +100. Positive VDI values indicate bullishness, while negative VDI values suggest bearishness. Values near the extremes (+100 or -100) can be considered overbought or oversold, potentially signaling a trend reversal. Traders often use additional technical analysis tools and techniques to confirm signals generated by the VDI.
What are Confidence Bands?
Confidence bands are computed using the inverse normal CDF as calculated below:
RationalApproximation(float t): This function is an implementation of a rational approximation, which is a technique used to approximate a function using a ratio of two polynomial functions. The function provided here is specific to approximating a particular function, possibly related to the inverse of the cumulative distribution function (CDF) of the standard normal distribution. The function takes a float value t as input and returns an approximation based on the given coefficients.
NormalCDFInverse(float p): This function calculates the inverse of the cumulative distribution function (CDF) for the standard normal distribution (also known as the quantile function or percent-point function). The standard normal distribution is a normal distribution with a mean of 0 and a standard deviation of 1. The input to the function is a probability value p (0 < p < 1), and the output is the corresponding z-score (or standard score) at which the CDF has the value p.
The Normal CDF Inverse function relies on the RationalApproximation function to obtain an approximation of the inverse CDF value. If the probability p is less than 0.5, the function calculates the negative z-score, while for p greater than or equal to 0.5, it calculates the positive z-score. The final output is the z-score corresponding to the input probability p.
How to calculate RSX VDI confidence bands:
1. Set the Confidence Level by clamping the input Confidence Level between 0.0000000001 and 99.9999999999.
2. Set the Confidence Band Shift by taking the maximum of the input Confidence Band Shift and 1.
3. Calculate the Confidence Z-score, a z-score corresponding to the given confidence level, using the Normal CDF Inverse function.
4. Calculate va by checking if Confidence Band Shift is greater than or equal to 0. If it is, calculate the VALUE using the backwards XX many Confidence Band Shift bars. Otherwise, set VALUE to 0.
5. Finally, calculate MERROR, which is the measure of error or confidence interval, using Confidence Z-sore, VALUE, and input Period.
The result, MERROR, represents the confidence interval or bands for the RSX VDI, which can be used in technical analysis to assess the reliability of the indicator and potential price reversals.
What is the RSX?
The Jurik RSX is a technical indicator developed by Mark Jurik to measure the momentum and strength of price movements in financial markets, such as stocks, commodities, and currencies. It is an advanced version of the traditional Relative Strength Index (RSI), designed to offer smoother and less lagging signals compared to the standard RSI.
The main advantage of the Jurik RSX is that it provides more accurate and timely signals for traders and analysts, thanks to its improved calculation methods that reduce noise and lag in the indicator's output. This enables better decision-making when analyzing market trends and potential trading opportunities.
What is RSX VDI w/ Confidence Bands
This indicator calculates the RSX VDI and then wraps that calculation with upper and lower confidence level. There are three types of signals: Levels cross, dynamic middle cross, and signal cross. Levels cross only works if you adjust the Confidence Bands shift upward or adjust the confidence level downward as the likelihood of reaching the default setting of 95% confidence is very low.
Requirements
Inputs
Confirmation 1: GKD-V Volatility / Volume indicator
Confirmation 2: GKD-C Confirmation indicator
Continuation: GKD-C Confirmation indicator
Solo Confirmation Simple: GKD-B Baseline
Solo Confirmation Complex: GKD-V Volatility / Volume indicator
Solo Confirmation Super Complex: GKD-V Volatility / Volume indicator
Stacked 1: None
Stacked 2+: GKD-C, GKD-V, or GKD-B Stacked 1
Outputs
Confirmation 1: GKD-C Confirmation 2 indicator
Confirmation 2: GKD-C Continuation indicator
Continuation: GKD-E Exit indicator
Solo Confirmation Simple: GKD-BT Backtest
Solo Confirmation Complex: GKD-BT Backtest or GKD-E Exit indicator
Solo Confirmation Super Complex: GKD-C Continuation indicator
Stacked 1: GKD-C, GKD-V, or GKD-B Stacked 2+
Stacked 2+: GKD-C, GKD-V, or GKD-B Stacked 2+ or GKD-BT Backtest
Additional features will be added in future releases.
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!
[TTI] Minervini STEM Model📜 ––––HISTORY & CREDITS 🏦
Introducing the Minervini STEM Model, an innovative indicator developed by Mark Minervini, an experienced trader and author renowned for his expertise in gauging the quality of breakouts. The Stock Tactical Environment Model (STEM) is designed to assess the trading environment based on the performance and setup of stocks, helping traders navigate various market conditions with ease.
🎯 ––––WHAT IT DOES 💡
The Minervini STEM Model measures the quality of breakouts in the stock market and provides valuable insights into the trading environment. The model is subjective based on the performance of the Mark Minervini Focus List on a 5 day rolling basis.
• What is the Mark Minervini Focus List?
- This is a private weekly watchlist of all the best setups provided by Mark Minervini in his Private Access Group
• How is the quality of breakouts measured?
- This is the subjective part of the indicator. A good breakout is one that has definite clear of a pivot, with a good close and strong volume. From then on there are strong follow through buys (consecutive up days with new highs) again with good (above average) volume signatures. When stocks start moving in earnest and together and breakouts happen with quality technical characteristics and keep on holding the new highs, then we have a good quality breakouts, otherwise if there are 'pop and drops' (breakout met with subsequent selling on the next days) - we have a bad quality breakouts.
• What is the 5 day rolling basis?
- As part of the methodology, I have included, how are the watchlist (Focus List) is performing on subsequent on the next 5 days. This means if we have 10 stocks on Friday, how many did close up in the following 5 days, do we have improvement compared to the previous week and the week before that, is there an overall trend of stocks gaining value or not. This also measures the quality of the bearjouts
🚨IMPORTANT! The model is largely subjective based on the various factors. Largely, I look at Mark Minervini's focus list and determine how it is performing on a 5 day rolling basis. Depending on how many of the Focus List stocks are closing down for the 5 day period (e.g. less than 60%) and how are all cumulatively performing, I adjust the model. It generates three distinct color-coded signals to indicate the effectiveness of breakouts and the overall market condition:
Color meanings
🟩Green: Breakouts are working well, indicating an easy dollar environment.
🟨Orange: The market is selective or highly rotational, signalling a need for caution.
🟥Red: Breakouts are not working well, suggesting a hard penny environment and high risk.
This color-coded system allows traders to quickly assess the market's health and adjust their trading strategies accordingly.
🛠️ ––––HOW TO USE IT 🔧
To effectively use the Minervini STEM Model, follow these steps:
1.Load the Minervini STEM Model script into your preferred charting platform.
2.Observe the color-coded signals displayed on your chart.
Interpret the signals as follows:
🟩Green: Breakouts are working well. Consider aggressive trading and increasing exposure.
🟨Orange: The market is selective or highly rotational. Exercise caution when trading and be selective with your stock setups.
🟥Red: Breakouts are not working well, and risk is high. Adopt maximum caution and consider reducing exposure or staying small until you gain traction.
By incorporating the Minervini STEM Model into your trading strategy, you can better gauge the quality of breakouts and the overall market condition, enabling you to make informed decisions on your trades. Remember to use this tool in conjunction with other technical indicators and risk management practices to optimize your success.
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
Crypto Performance Index1. The Crypto Performance Index (CPI) estimates the price appreciation of a crypto asset relative to the overall crypto market performance. The indicator is calculated using a Sharpe Ratio principle enhanced with time-domain normalization and cumulative parametrization.
2. The CPI is based on the idea that the performance of an asset should be evaluated not only in terms of its absolute price movement, but also in terms of its risk-adjusted returns compared to the broader market. The Sharpe Ratio, which takes into account both the asset's return and its volatility, is a commonly used measure of risk-adjusted performance.
3. The CPI takes the Sharpe Ratio principle further by incorporating a time-domain normalization technique that adjusts for differences in volatility across different time periods. The cumulative parametrization ensures that the CPI considers the overall performance of the asset over a specified period of time.
4. To use the indicator, select a timeframe and set the standard deviation period (default is 20). The CPI line can be compared against various market benchmarks, including the total crypto market cap (white line), altcoins total market cap (blue line), low-cap altcoins (without ETH), and Bitcoin.
5. An upward slope of the CPI line indicates strong price performance of an asset, with a relatively high chance for the asset to continue growing faster than the market in the future. Conversely, a downward slope of the CPI line indicates weak price performance of an asset, with a relatively high chance for the asset to depreciate in price with respect to the rest of the market in the future.
6. Overall, the CPI provides a comprehensive measure of an asset's price performance, taking into account both its absolute return and its risk-adjusted return relative to the broader market. This makes it a valuable tool for investors looking to evaluate the performance of their crypto holdings and make informed decisions about buying, selling, or holding assets.
[pAulseperformance] PSStrategyX█ OVERVIEW
This script reduces the amount of time it takes to turn your indicator into a live trading bot.
It will convert your signals into alerts that will be sent to your exchange for trading.
The script features a broker connector to automate alert syntax and connect with third-party exchanges to live trade strategies with minimal setup.
It also includes an enhanced version of the built-in backtester with customizable options to speed up backtesting, trade-by-trade statistics, and a chart strategy summary to help traders make informed decisions.
The PSStrategyX trading tool is designed to provide traders with a range of benefits, including:
Increased confidence in their strategies.
Better understanding of the accuracy of indicator signals.
Simplified automated trading through third-party broker connections.
Reduced time to develop strategies by focusing on signal development only. No need to work with complicated strategy testing code and 3rd party automation.
█ FEATURES
Broker Connector
— Supports Autoview (More Connectors added in the future)
— Connects and auto trades with most exchanges
— No need for Webhooks (AutoView)
— Can forward test live strategies on Testnets before using real money.
Built in Backtester loaded with options to speed up backtesting
— Standard strategy features including stop loss, take profit, and various filters reduce the time and complexity involved in building a working strategy.
Trade By Trade Statistics
— Gain insight on every trade with additional trade-by-trade statistics.
Strategy Summary
— Get instant feedback on your chart of your strategies performance. Visual cues and feedback give you hints on where to look and what to improve.
Strategy Tester Enhancements
— Take the max trades allowed in the strategy tester without errors.
— Take the largest or smallest trade allowed without errors.
█ WHY?
The PSStrategyX tool was developed to solve a common problem faced by traders who use Pine Script on TradingView: the inability to integrate Pine Script with exchanges through TradingView.
Without this integration, traders need to go through several extra steps to live trade their Pine Script strategies on a real exchange with real money. This includes finding a broker, learning the new syntax for the broker, and placing that syntax correctly in the strategy.
These steps can be time-consuming and add complexity to the codebase.
The PSStrategyX tool simplifies this process by automatically configuring the correct alert syntax to connect to third-party exchanges, allowing traders to live trade their strategies with minimal setup. This saves traders time and effort, allowing them to focus on signal development rather than complicated strategy testing code and 3rd party automation.
Additionally, the tool was developed to address the time-consuming task of converting any one of the thousands of great free indicators on TradingView to strategies through hours of coding.
Overall, I built the PSStrategyX to streamline the auto trading process and make auto trading more accessible to traders of all levels.
█ HOW TO USE THIS?
Using the PSStrategyX trading tool is a straightforward process that requires a few key steps:
1 — Generate trading signals: You need a signal generator that can provide buy and sell signals for your preferred trading instrument(s).
You can use TradingView's indicators or create your own custom indicators using TradingView's Pine programming language.
2 — Connect trading signals to PSStrategyX: You will use 2 scripts on your chart. One generates buy/sell/exit signals, and the other is the PSStrategyX script executing those signals as trades.
To set this up you will need to make sure that your signal generator is an indicator, NOT a strategy.
Make sure the signals are being plotted buy = 1; sell = -1; exit = 0; signals in one plot. Exits are optional.
Example plot(buy ? 1 : sell ? -1 : exit ? 0 : na)
You will choose the plot with buy/sell/exit signals inside the PSStrategyX tool to execute trades. If you need help, check out the docs for more details.
3 — Set up the broker connector (optional): If you want to take live trades with this tool, you will need to set up a third party connecter. Once set up, everything is automated. See more details in the "authors instructions." at the bottom of this post.
4 — Set up an exchange account (optional): If you want to trade on an exchange, you will need to set up an account with the exchange you plan to use.
The Broker Connector supports a range of popular exchanges, including Binance, Bitfinex, Kraken, Oanda and more.
Once you have generated your trading signals, set up the Broker connecter (optional) and set up an exchange account (optional), you can start using the PSStrategyX trading tool to execute trades automatically based on your trading signals.
█ LIMITATIONS
Here are some important limitations to keep in mind when using the PSStrategyX trading tool:
General:
— Once the alert is sent, there is no way to monitor positions on any exchange. The order will be processed by the broker connector and sent to the exchange.
While this usually works fine, it's important to check the log for errors.
Sometimes the broker connector may fail to process the order, or the exchange may not process it for various reasons.
— The tool sends TP/SL orders with the entry order when possible to protect your order in case of errors or if you lose a connection.
However, not all exchanges accept TP/SL orders, and sometimes your entry order will be left unprotected.
FIFO:
— This tool DOES NOT support the First In First Out (FIFO) method for closing positions.
— Instead, it uses the ANY method. There currently is no way to make this variable.
█ FAQ
What does PSStrategyX do exactly?
PSStrategyX is a strategy enhancing, backtester, forwardtester, automation and simulation tool. It's NOT a signal generator, and does not produce buy/sell signals by itself. You provide buy/sell signals, and PSStrategyX will put those signals on steroids...basically.
PSStrategyX helps you figure out what indicators actually work. Without wasting time learning how to code.
Why did you choose AutoView for this tool?
AutoView offered the best integration I could find. They allow you to connect to test exchanges for free, which is great for practicing without using real money. They also work without using webhooks, which means you can live trade without paying for Tradingview pro. Additionally, AutoView supports many different exchanges. I don't work for AutoView, but if you sign up through my referral link and purchase a paid version, I earn a commission.
Why doesn't Tradingview automatically connect Pine Script to exchanges?
This is a great question, but unfortunately I don't have the answer. It would definitely be helpful if Tradingview provided this feature, but it might also put some brokers out of business.
How do I get access?
DON'T ask for access in the comments.
DO review the "Authors Instructions" on this page for details.
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:
Upper and Lower Candle Trend Counter [theEccentricTrader]█ OVERVIEW
This indicator counts the number of confirmed upper and lower 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.
█ FEATURES
Inputs
• Start Date
• End Date
• Position
• Text Size
Table
The table is colour coded, consists of seven columns and, as many as, sixty-two rows. Blue cells denote the multi-part trend scenarios, green cells denote the corresponding upper candle trend scenarios and red cells denote the corresponding lower candle trend scenarios.
The multi-part 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 candle trend scenarios as percentages of total 1-part candle trends. And columns four and seven display the total candle trend scenarios as percentages of the last, or preceding candle trend part. For example 4-part higher high trends as a percentages of 3-part higher high trends. This offers more insight into what might happen next at any given point in time.
Plots
For a visual aid to this indicator please use in conjunction with my Upper Candle Trends and Lower Candle Trends indicators which can both be found on my profile page under scripts, or in community scripts under the same names.
Green up-arrows, with the number of the trend part, denote higher high trends when above bar and higher low trends when below bar. Red down-arrows, with the number of the trend part, denote lower high trends when above bar and lower low trends when below bar.
█ HOW TO USE
This 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 upper or lower 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.
Double Trend Counter [theEccentricTrader]█ OVERVIEW
This indicator counts the number of confirmed double 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.
Swing Highs and Swing Lows
• A swing high is a green candle or series of consecutive green candles followed by a single red candle to complete the swing and form the peak.
• A swing low is a red candle or series of consecutive red candles followed by a single green candle to complete the swing and form the trough.
Peak and Trough Prices (Basic)
• The peak price of a complete swing high is the high price of either the red candle that completes the swing high or the high price of the preceding green candle, depending on which is higher.
• The trough price of a complete swing low is the low price of either the green candle that completes the swing low or the low price of the preceding red candle, depending on which is lower.
Historic Peaks and Troughs
The current, or most recent, peak and trough occurrences are referred to as occurrence zero. Previous peak and trough occurrences are referred to as historic and ordered numerically from right to left, with the most recent historic peak and trough occurrences being occurrence one.
Upper Trends
• A return line uptrend is formed when the current peak price is higher than the preceding peak price.
• A downtrend is formed when the current peak price is lower than the preceding peak price.
• A double-top is formed when the current peak price is equal to the preceding peak price.
Lower Trends
• An uptrend is formed when the current trough price is higher than the preceding trough price.
• A return line downtrend is formed when the current trough price is lower than the preceding trough price.
• A double-bottom is formed when the current trough price is equal to the preceding trough price.
Muti-Part Upper and Lower Trends
• A multi-part return line uptrend begins with the formation of a new return line uptrend and continues until a new downtrend ends the trend.
• A multi-part downtrend begins with the formation of a new downtrend and continues until a new return line uptrend ends the trend.
• A multi-part uptrend begins with the formation of a new uptrend and continues until a new return line downtrend ends the trend.
• A multi-part return line downtrend begins with the formation of a new return line downtrend and continues until a new uptrend ends the trend.
Double Trends
• A double uptrend is formed when the current trough price is higher than the preceding trough price and the current peak price is higher than the preceding peak price.
• A double downtrend is formed when the current peak price is lower than the preceding peak price and the current trough price is lower than the preceding trough price.
Muti-Part Double Trends
• A multi-part double uptrend begins with the formation of a new uptrend that proceeds a new return line uptrend, and continues until a new downtrend or return line downtrend ends the trend.
• A multi-part double downtrend begins with the formation of a new downtrend that proceeds a new return line downtrend, and continues until a new uptrend or return line uptrend ends the trend.
█ FEATURES
Inputs
• Start Date
• End Date
• Position
• Text Size
Table
The table is colour coded, consists of seven columns and, as many as, fifteen rows. Blue cells denote the multi-part trend scenarios, green cells denote the corresponding double uptrend scenarios and red cells denote the corresponding double downtrend scenarios.
The double 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 trend scenarios as percentages of total 1-part double trends. And columns four and seven display the total double trend scenarios as percentages of the last, or preceding double trend part. For example, 4-part double trends as percentages of 3-part double trends and so on.
Plots
For a visual aid to this indicator please use in conjunction with my Double Trends indicator which can be found on my profile page under scripts, or in community scripts under the same name.
Green up-arrows, with the number of the double trend part, denote double uptrends. Red down-arrows, with the number of the double trend part, denote double downtrends.
█ 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 trend will continue or fail, based on the current double trend scenario and what has happened in the past under similar circumstances. Such information can be very 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.
The green and red candle calculations are based solely on differences between open and close prices, as such I have made no attempt to account for green candles that gap lower and close below the close price of the preceding candle, or red candles that gap higher and close above the close price of the preceding candle. I can only recommend using 24-hour markets, if and where possible, as there are far fewer gaps and, generally, more data to work with. Alternatively, you can replace the scenarios with your own logic to account for the gap anomalies, if you are feeling up to the challenge.
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.
Rangemeter [theEccentricTrader]█ OVERVIEW
This indicator simply displays candle and peak to trough ranges in points or pips, depending on the symbol type, 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.
Open Green and Red Candles
• An open green candle is one that has a close price equal to or above the price it opened, but has not yet closed to confirm the condition.
• An open red candle is one that has a close price lower than the price it opened, but has not yet closed to confirm the condition.
Swing Highs and Swing Lows
• A swing high is a green candle or series of consecutive green candles followed by a single red candle to complete the swing and form the peak.
• A swing low is a red candle or series of consecutive red candles followed by a single green candle to complete the swing and form the trough.
Peak and Trough Prices (Basic)
• The peak price of a complete swing high is the high price of either the red candle that completes the swing high or the high price of the preceding green candle, depending on which is higher.
• The trough price of a complete swing low is the low price of either the green candle that completes the swing low or the low price of the preceding red candle, depending on which is lower.
Historic Peaks and Troughs
The current, or most recent, peak and trough occurrences are referred to as occurrence zero. Previous peak and trough occurrences are referred to as historic and ordered numerically from right to left, with the most recent historic peak and trough occurrences being occurrence one.
Range
The range is simply the difference between the current peak and current trough prices, generally expressed in terms of points or pips.
Open Range
An open range is here defined as one that is forming but has not yet completed. For example, a swing low that has an open green candle proceeding a red candle or series of red candles. Or a swing high that has an open red candle proceeding a green candle or series of green candles.
The table will only display the open range under the aforementioned circumstances, otherwise it will display the current, or previous, range.
█ FEATURES
Inputs
• Show Candle Ranges
• Show Largest and Smallest Candle Ranges
• Average Candle Range Lookback
• Show Ranges
• Show Largest and Smallest Ranges
• Average Range Lookback
• Position
• Text Size
█ HOW TO USE
The indicator can be used for strategy filtering and development, gauging current market conditions versus historic and helping to make more informed discretionary trading decisions. It can also be used like my Wavemeter indicator to objectively set the angle and projection ratio for my Fan Projections and Parallel Projections indicators.
█ 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 ensuring the lookback for the average range does not reach as far back as the start of the chart. If you are unsure about the candle count you can use my Candle Counter indicator to find out how many candles are displayed on the chart.
The green and red candle calculations are based solely on differences between open and close prices, as such I have made no attempt to account for green candles that gap lower and close below the close price of the preceding candle, or red candles that gap higher and close above the close price of the preceding candle. I can only recommend using 24-hour markets, if and where possible, as there are far fewer gaps and, generally, more data to work with. Alternatively, you can replace the scenarios with your own logic to account for the gap anomalies, if you are feeling up to the challenge.
It is also worth noting that the lookback 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.