RAINBOW AVERAGES - INDICATOR - (AS) - 1/3
-INTRODUCTION:
This is the first of three scripts I intend to publish using rainbow indicators. This script serves as a groundwork for the other two. It is a RAINBOW MOVING AVERAGES indicator primarily designed for trend detection. The upcoming script will also be an indicator but with overlay=false (below the chart, not on it) and will utilize RAINBOW BANDS and RAINBOW OSCILLATOR. The third script will be a strategy combining all of them.
RAINBOW moving averages can be used in various ways, but this script is mainly intended for trend analysis. It is meant to be used with overlay=true, but if the user wishes, it can be viewed below the chart. To achieve this, you need to change the code from overlay=true to false and turn off the first switch that plots the rainbow on the chart (or simply move the indicator to a new pane below). By doing this, you will be able to see how all four conditions used to detect trends work on the chart. But let's not get ahead of ourselves.
-WHAT IS IT:
In its simplest form, this indicator uses 10 moving averages colored like a rainbow. The calculation is as follows:
MA0: This is the main moving average and can be defined with the type (SMA, EMA, RMA, WMA, SINE), length, and price source. However, the second moving average (MA1) is calculated using MA0 as its source, MA2 uses MA1 as the data source, and so on, until the last one, MA9. Hence, there are 10 moving averages. The first moving average is special as all the others derive from it. This indicator has many potential uses, such as entry/exit signals, volatility indication, and stop-loss placement, but for now, we will focus on trend detection.
-TREND DETECTION:
The indicator offers four different background color options based on the user's preference:
0-NONE: No background color is applied as no trend detection tools is being used (boring)
1-CHANGE: The background color is determined by summing the changes of all 10 moving averages (from two bars). If the sum is positive and not falling, the background color is GREEN. If the sum is negative and not rising, the background color is RED. From early testing, it works well for the beginning of a movement but not so much for a lasting trend.
2-RAINBW: The background color is green when all the moving averages are in ascending order, indicating a bullish trend. It is red when all the moving averages are in descending order, indicating a bearish trend. For example, if MA1>MA2>MA3>MA4..., the background color is green. If MA1 threshold, and red indicates width < -threshold.
4-DIRECT: The background color is determined by counting the number of moving averages that are either above or below the input source. If the specified number of moving averages is above the source, the background color is green. If the specified number of moving averages is below the source, the background color is red. If all ten MAs are below the price source, the indicator will show 10, and if all ten MAs are above, it will show -10. The specific value will be set later in the settings (same for 3-TSHOLD variant). This method works well for lasting trends.
Note: If the indicator is turned into a below-chart version, all four color options can be seen as separate indicators.
-PARAMETERS - SETTINGS:
The first line is an on/off switch to plot the skittles indicator (and some info in the tooltip). The second line has already been discussed, which is the background color and the selection of the source (only used for MA0!).
The line "MA1: TYP/LEN" is where we define the parameters of MA0 (important). We choose from the types of moving averages (SMA, EMA, RMA, WMA, SINE) and set the length.
Important Note: It says MA1, but it should be MA0!.
The next line defines whether we want to smooth MA1 (which is actually MA0) and the period for smoothing. When smoothing is turned on, MA0 will be smoothed using a 3-pole super smoother. It's worth noting that although this only applies to MA0, as the other MAs are derived from it, they will also be smoothed.
In the line below, we define the type and length of MAs for MA2 (and other MAs except MA0). The same type and length are used for MA1 to MA9. It's important to remember that these values should be smaller. For example, if we set 55, it means that MA1 is the average of 55 periods of MA0, MA2 will be 55 periods of MA1, and so on. I encourage trying different combinations of MA types as it can be easily adjusted for ur type of trading. RMA looks quirky.
Moving on to the last line, we define some inputs for the background color:
TSH: The threshold value when using 3-TSHOLD-BGC. It's a good idea to change the chart to a pane below for easier adjustment. The default values are based on EURUSD-5M.
BG_DIR: The value that must be crossed or equal to the MA score if using 4-DIRECT-BGC. There are 10 MAs, so the maximum value is also 10. For example, if you set it to 9, it means that at least 9 MAs must be below/above the price for the script to detect a trend. Higher values are recommended as most of the time, this indicator oscillates either around the maximum or minimum value.
-SUMMARY OF SETTINGS:
L1 - PLOT MAs and general info tooltip
L2 - Select the source for MA0 and type of trend detection.
L3 - Set the type and length of MA0 (important).
L4 - Turn smoothing on/off for MA0 and set the period for super smoothing.
L5 - Set the type and length for the rest of the MAs.
L6 - Set values if using 4-DIRECT or 3-TSHOLD for the trend detection.
-OTHERS:
To see trend indicators, you need to turn off the plotting of MAs (first line), and then choose the variant you want for the background color. This will plot it on the chart below.
Keep in mind that M1 int settings stands for MA0 and MA2 for all of the 9 MAs left.
Yes, it may seem more complicated than it actually is. In a nutshell, these are 10 MAs, and each one after MA0 uses the previous one as its source. Plus few conditions for range detection. rest is mainly plots and colors.
There are tooltips to help you with the parameters.
I hope this will be useful to someone. If you have any ideas, feedback, or spot errors in the code, LET ME KNOW.
Stay tuned for the remaining two scripts using skittles indicators and check out my other scripts.
-ALSO:
I'm always looking for ideas for interesting indicators and strategies that I could code, so if you don't know Pinescript, just message me, and I would be glad to write your own indicator/strategy for free, obviously.
-----May the force of the market be with you, and until we meet again,
Cerca negli script per "10年期国债+交易单位+价格"
True Trend Average BandsThis is the indicator I am most proud of. After reading Glenn Neely's book "Mastering Eliott Waves" / "Neowave" and chatting with @timwest who got acknowledged by Neely, we came up with the idea of an moving average which does calculate the real average price since a trend started. Addionally I adapted a method from Neely Neowave and Tim Wests TimeAtMode to not force a timeframe on a chart but instead let the charts data decide which timeframe to use, to then calculate the real average price since the trend started.
It took me a while to get this right and coded, so take a moment and dive deeper and you might learn something new.
We assume that the price is in multiple trends on multiple timeframes, this is caused by short term traders, long term traders and investors who trade on different timeframes. To find out in which timeframe the important trends are, we have to look out for significant lows and highs. Then we change the timeframe in the chart to a value so that we have 10 to 20 bars since the significant low/high. While new bars are printed, and we reach more than 20 bars, we have to switch to a higher timeframe so we have 10 to 20 bars again. In the chart you see two significant trends: a downtrend on the 3 week timeframe and an uptrend from the 2 month timeframe. Based on the logic I have described, these are the two important timeframes to watch right now for the spx (there is another uptrend in the yearly chart, which is not shown here).
Now that we understand how to find the important timeframes, let's look what the magic in this script is that tells us the real average price since a trend started.
I developed a new type of moving average, which includes only the prices since a trend started. The difference to the regular sma is that it will not include prices which happened before the significant low or high happened. For example, if a top happened in a market 10 days ago, the regular sma20 would be calculated by 10 bars which happened before the top and 10 bars which happened after the top. If we want to know the average price of the last 10 bars we manually have to change the ma20 to the ma10 which is annoying manual work, additionally even if we use the ma10 in this case, and we look at yesterday's bar the ma10 will include 9 bars from after the top and one bar before the top, so the ma10 would only show the real average price for the current bar which is not what we want.
To come up with a solution to this problem, the True Trend Average searches for the lowest/highest bar in a given period (20 bars). Then starts to calculate the average value since the low/high. For example: if the price reaches a new 20 day high and then trades below it, the day of the high will be the sma1, the day after it's the sma2, ... up to the maximum look back length.
This way, we always know what the average price would have been if someone sold/bought a little bit every bar of his investment since the high/low.
Why is this even important? Let's assume we missed selling the top or buying the low, and think it would have been at least better to buy/sell a little bit since the new trend started. Once the price reaches the true trend average again, we can buy/sell, and it would be as good as selling/buying a little bit every day. We find prices to buy the dip and sell the bounce, which are as good as scaling in/out.
There is a lot more we can learn from these price levels but I think it is better to let you figure out yourself what you can learn from the information given by this indicator. Think about how market participants who accumulate or distribute feel when prices are above or below certain levels.
Now that we understand this new type of moving average, let's look into the lines we see in the chart:
The upper red band line shows the true trend average high price since the last significant top within 20 bars.
The lower red band line shows the true trend average hl2 price since the last significant top within 20 bars.
The lower green band line shows the true trend average low price since the last significant low within 20 bars.
The upper green band line shows the true trend average hl2 price since the last significant low within 20 bars.
The centerline is the average between the upper red band and the lower green band.
The teal lines show 1 standard deviation from the outer bands.
Before today only a few people had access to this indicator, now that it is public and open source, I am curious if you will find it useful and what you will do with it. Please share your findings.
/edit: The chart only shows the 3week timeframe so here are the other two trends from the 2month and 1year timeframe
[blackcat] L1 Old Duck HeadLevel 1
Background
The old duck head is a classic form formed by a series of behaviors such as bankers opening positions, washing dishes, and pulling over the top of the duck head.
Function
A form of stock candles:
(1) Moving averages using 5, 10 and 60 parameters. When the 5-day and 10-day moving averages crossed the 60-day moving average, a duck neck was formed.
(2) The high point when the stock price fell back formed a duck head.
(3) When the stock price fell back soon, the 5-day and 10-day moving averages again turned up to form a duckbill.
(4) Duck nose refers to the hole formed when the 5-day moving average crosses the 10-day moving average and the two lines cross again.
Market significance:
(1) When the dealer starts to collect chips, the stock price rises slowly, and the 5-day and 10-day moving averages cross the 60-day moving average, forming a duck neck.
(2) When the stock price of the banker shakes the position and starts to pull back, the high point of the stock price forms the top of the duck's head.
(3) When the dealer builds a position again to collect chips, the stock price rises again, forming a duck bill.
Operation method:
(1) Buy when the 5-day and 10-day moving averages cross the 60-day moving average and form a duck neck.
(2) Buy on dips near the sesame point of trading volume near the duckbill.
(3) Intervene when the stock price crosses the top of the duck's head in heavy volume.
The top of the duck’s head should be a little far away from the 60-day moving average, otherwise it means that the dealer is not willing to open a position at this old duck’s head, and the bottom of the old duck’s head must be heavy. Small is better, nothing is the strongest! There must be a lot of sesame dots under the nostrils of the duck, otherwise it means that the dealer has poor control. There must be ventilation under the duck bill, the higher the ventilation, the better!
Remarks
Feedbacks are appreciated.
Variety N-Tuple Moving Averages w/ Variety Stepping [Loxx]Variety N-Tuple Moving Averages w/ Variety Stepping is a moving average indicator that allows you to create 1- 30 tuple moving average types; i.e., Double-MA, Triple-MA, Quadruple-MA, Quintuple-MA, ... N-tuple-MA. This version contains 2 different moving average types. For example, using "50" as the depth will give you Quinquagintuple Moving Average. If you'd like to find the name of the moving average type you create with the depth input with this indicator, you can find a list of tuples here: Tuples extrapolated
Due to the coding required to adapt a moving average to fit into this indicator, additional moving average types will be added as they are created to fit into this unique use case. Since this is a work in process, there will be many future updates of this indicator. For now, you can choose from either EMA or RMA.
This indicator is also considered one of the top 10 forex indicators. See details here: forex-station.com
Additionally, this indicator is a computationally faster, more streamlined version of the following indicators with the addition of 6 stepping functions and 6 different bands/channels types.
STD-Stepped, Variety N-Tuple Moving Averages
STD-Stepped, Variety N-Tuple Moving Averages is the standard deviation stepped/filtered indicator of the following indicator
Last but not least, a big shoutout to @lejmer for his help in formulating a looping solution for this streamlined version. this indicator is speedy even at 50 orders deep. You can find his scripts here: www.tradingview.com
How this works
Step 1: Run factorial calculation on the depth value,
Step 2: Calculate weights of nested moving averages
factorial(depth) / (factorial(depth - k) * factorial(k); where depth is the depth and k is the weight position
Examples of coefficient outputs:
6 Depth: 6 15 20 15 6
7 Depth: 7 21 35 35 21 7
8 Depth: 8 28 56 70 56 28 8
9 Depth: 9 36 34 84 126 126 84 36 9
10 Depth: 10 45 120 210 252 210 120 45 10
11 Depth: 11 55 165 330 462 462 330 165 55 11
12 Depth: 12 66 220 495 792 924 792 495 220 66 12
13 Depth: 13 78 286 715 1287 1716 1716 1287 715 286 78 13
Step 3: Apply coefficient to each moving average
For QEMA, which is 5 depth EMA , the calculation is as follows
ema1 = ta. ema ( src , length)
ema2 = ta. ema (ema1, length)
ema3 = ta. ema (ema2, length)
ema4 = ta. ema (ema3, length)
ema5 = ta. ema (ema4, length)
In this new streamlined version, these MA calculations are packed into an array inside loop so Pine doesn't have to keep all possible series information in memory. This is handled with the following code:
temp = array.get(workarr, k + 1) + alpha * (array.get(workarr, k) - array.get(workarr, k + 1))
array.set(workarr, k + 1, temp)
After we pack the array, we apply the coefficients to derive the NTMA:
qema = 5 * ema1 - 10 * ema2 + 10 * ema3 - 5 * ema4 + ema5
Stepping calculations
First off, you can filter by both price and/or MA output. Both price and MA output can be filtered/stepped in their own way. You'll see two selectors in the input settings. Default is ATR ATR. Here's how stepping works in simple terms: if the price/MA output doesn't move by X deviations, then revert to the price/MA output one bar back.
ATR
The average true range (ATR) is a technical analysis indicator, introduced by market technician J. Welles Wilder Jr. in his book New Concepts in Technical Trading Systems, that measures market volatility by decomposing the entire range of an asset price for that period.
Standard Deviation
Standard deviation is a statistic that measures the dispersion of a dataset relative to its mean and is calculated as the square root of the variance. The standard deviation is calculated as the square root of variance by determining each data point's deviation relative to the mean. If the data points are further from the mean, there is a higher deviation within the data set; thus, the more spread out the data, the higher the standard deviation.
Adaptive Deviation
By definition, the Standard Deviation (STD, also represented by the Greek letter sigma σ or the Latin letter s) is a measure that is used to quantify the amount of variation or dispersion of a set of data values. In technical analysis we usually use it to measure the level of current volatility .
Standard Deviation is based on Simple Moving Average calculation for mean value. This version of standard deviation uses the properties of EMA to calculate what can be called a new type of deviation, and since it is based on EMA , we can call it EMA deviation. And added to that, Perry Kaufman's efficiency ratio is used to make it adaptive (since all EMA type calculations are nearly perfect for adapting).
The difference when compared to standard is significant--not just because of EMA usage, but the efficiency ratio makes it a "bit more logical" in very volatile market conditions.
See how this compares to Standard Devaition here:
Adaptive Deviation
Median Absolute Deviation
The median absolute deviation is a measure of statistical dispersion. Moreover, the MAD is a robust statistic, being more resilient to outliers in a data set than the standard deviation. In the standard deviation, the distances from the mean are squared, so large deviations are weighted more heavily, and thus outliers can heavily influence it. In the MAD, the deviations of a small number of outliers are irrelevant.
Because the MAD is a more robust estimator of scale than the sample variance or standard deviation, it works better with distributions without a mean or variance, such as the Cauchy distribution.
For this indicator, I used a manual recreation of the quantile function in Pine Script. This is so users have a full inside view into how this is calculated.
Efficiency-Ratio Adaptive ATR
Average True Range (ATR) is widely used indicator in many occasions for technical analysis . It is calculated as the RMA of true range. This version adds a "twist": it uses Perry Kaufman's Efficiency Ratio to calculate adaptive true range
See how this compares to ATR here:
ER-Adaptive ATR
Mean Absolute Deviation
The mean absolute deviation (MAD) is a measure of variability that indicates the average distance between observations and their mean. MAD uses the original units of the data, which simplifies interpretation. Larger values signify that the data points spread out further from the average. Conversely, lower values correspond to data points bunching closer to it. The mean absolute deviation is also known as the mean deviation and average absolute deviation.
This definition of the mean absolute deviation sounds similar to the standard deviation (SD). While both measure variability, they have different calculations. In recent years, some proponents of MAD have suggested that it replace the SD as the primary measure because it is a simpler concept that better fits real life.
For Pine Coders, this is equivalent of using ta.dev()
Bands/Channels
See the information above for how bands/channels are calculated. After the one of the above deviations is calculated, the channels are calculated as output +/- deviation * multiplier
Signals
Green is uptrend, red is downtrend, yellow "L" signal is Long, fuchsia "S" signal is short.
Included:
Alerts
Loxx's Expanded Source Types
Bar coloring
Signals
6 bands/channels types
6 stepping types
Related indicators
3-Pole Super Smoother w/ EMA-Deviation-Corrected Stepping
STD-Stepped Fast Cosine Transform Moving Average
ATR-Stepped PDF MA
Tendies Heist Auto Compounding ExampleThis is an example of how we can use compounding to control our position size. This example shows how we can automatically add and reduce position size based on account equity. The "initial capital" in properties is the starting account equity. At default its set to 100,000. If our max position size is set to 25 then the very first position that's taken has a position size of 10, IF our leverage is set to 10,000. Account equity divided by leverage equals position size. So in that example 100,000 divided by 10,000 in leverage gives us a max position size of 10. However the max position size was set to 25 meaning we would need 250k in equity for it to open a position size of 25 with the leverage set at 10k. Now if the initial capital was set to 100,000 and the max position size was set to 5 and leverage remained at 10,000, all though 100,000 divided by 10,000 equals 10 it will ONLY open a position size of 5, because the max position size in this example was set at 5. Since this works for strategies you may look through the trade log on the posted back test and check out the position size, you can see in this back test the default 100k is used for the initial capital and the default 10k was used for the leverage. You will be able to see as this logic loses money it takes contracts away and as it gains money it adds contracts. I'm using trading view's basic strategy logic example to provide an example of how the compounding logic works.
Note, don't forget to add the syntax below to your strategy.entry call for this logic to work.
qty = size
Tendies Heist LLC 2021
Combo Backtest 123 Reversal & D_Three Ten OscThis is combo strategies for get a cumulative signal.
First strategy
This System was created from the Book "How I Tripled My Money In The
Futures Market" by Ulf Jensen, Page 183. This is reverse type of strategies.
The strategy buys at market, if close price is higher than the previous close
during 2 days and the meaning of 9-days Stochastic Slow Oscillator is lower than 50.
The strategy sells at market, if close price is lower than the previous close price
during 2 days and the meaning of 9-days Stochastic Fast Oscillator is higher than 50.
Second strategy
TradeStation does not allow the user to make a Multi Data Chart with
a Tick Bar Chart and any other type a chart. This indicator allows the
user to plot a daily 3-10 Oscillator on a Tick Bar Chart or any intraday interval.
Walter Bressert's 3-10 Oscillator is a detrending oscillator derived
from subtracting a 10 day moving average from a 3 day moving average.
The second plot is an 16 day simple moving average of the 3-10 Oscillator.
The 16 period moving average is the slow line and the 3/10 oscillator is
the fast line.
For more information on the 3-10 Oscillator see Walter Bressert's book
"The Power of Oscillator/Cycle Combinations"
WARNING:
- For purpose educate only
- This script to change bars colors.
Combo Backtest 123 Reversal & D_Three Ten Osc This is combo strategies for get a cumulative signal.
First strategy
This System was created from the Book "How I Tripled My Money In The
Futures Market" by Ulf Jensen, Page 183. This is reverse type of strategies.
The strategy buys at market, if close price is higher than the previous close
during 2 days and the meaning of 9-days Stochastic Slow Oscillator is lower than 50.
The strategy sells at market, if close price is lower than the previous close price
during 2 days and the meaning of 9-days Stochastic Fast Oscillator is higher than 50.
Second strategy
TradeStation does not allow the user to make a Multi Data Chart with
a Tick Bar Chart and any other type a chart. This indicator allows the
user to plot a daily 3-10 Oscillator on a Tick Bar Chart or any intraday interval.
Walter Bressert's 3-10 Oscillator is a detrending oscillator derived
from subtracting a 10 day moving average from a 3 day moving average.
The second plot is an 16 day simple moving average of the 3-10 Oscillator.
The 16 period moving average is the slow line and the 3/10 oscillator is
the fast line.
For more information on the 3-10 Oscillator see Walter Bressert's book
"The Power of Oscillator/Cycle Combinations"
WARNING:
- For purpose educate only
- This script to change bars colors.
D_Three Ten Osc Strategy Backtest This indicator allows the user to plot a daily 3-10 Oscillator on a Tick Bar Chart or any intraday interval.
Walter Bressert's 3-10 Oscillator is a detrending oscillator derived
from subtracting a 10 day moving average from a 3 day moving average.
The second plot is an 16 day simple moving average of the 3-10 Oscillator.
The 16 period moving average is the slow line and the 3/10 oscillator is
the fast line.
For more information on the 3-10 Oscillator see Walter Bressert's book
"The Power of Oscillator/Cycle Combinations"
You can change long to short in the Input Settings
Please, use it only for learning or paper trading. Do not for real trading.
D_Three Ten Osc Strategy This indicator allows the user to plot a daily 3-10 Oscillator on a Tick Bar
Chart or any intraday interval.
Walter Bressert's 3-10 Oscillator is a detrending oscillator derived
from subtracting a 10 day moving average from a 3 day moving average.
The second plot is an 16 day simple moving average of the 3-10 Oscillator.
The 16 period moving average is the slow line and the 3/10 oscillator is
the fast line.
For more information on the 3-10 Oscillator see Walter Bressert's book
"The Power of Oscillator/Cycle Combinations"
Sladkaya BulochkaAccording to the statistics of Thomas Bulkovski collected over several years on the 1-minute chart (21 million candles), there is a statistically significant periods, where the higher the probability of reversal rates on short-term timeframe.
By reversal, on average, had in mind the movement to 5 candles.
This three periods, they remain unchanged, depending on the hour:
- the first minute of each hour (10:01, 11:01, etc.)
- the first minute after the hour (10:31, 11:31)
- 51 minutes each hour (10:51, 11:51)
------------------------------------------------------
По статистике Томаса Булковски, собранной за несколько лет на 1-минутном графике (21 миллион свечей), есть статистически значимые периоды, где более высока вероятность разворота цены на краткосрочных ТФ.
Под разворотом, в среднем, имелось в виду движение на 5 свечей.
Это три периода, они неизменны в зависимости от часа:
- первая минута каждого часа (10:01, 11:01 и т.д.)
- первая минута после получаса (10:31, 11:31)
- каждая 51 минута часа (10:51, 11:51)
HL BREAKOUTThe base of the indicator is the breakout of historic High and lows.
There are 3 basic configurations
1° The High length that measure the latest 10 bars and make the "higher high"
2° The Low length taht measure the latest 10 bars and make the "lower low"
3° The Breakout PIPs administrator that defines how much pips are needed from the latest higher high to be defined as a level breakout.
So the strategy is super easy. The indicators show you the 10...20.. or whatever you need old bars high and lows.
When a breakout of that levels occurs and the candle "close" above or below and the close are more than "X" amount of PIPs a marker show up. The marker are the signals of buy and sell
I test some configurations, and work in all timeframes but.
I suggest
10, 10, 0.0003 for timeframes from 1m to 15m
and 10, 10, 0.0005 for timeframes higher than 15m
Maybe you need to test other configurations for 4h 1 day, etc the basics are the same in all timeframes, the main difference is the amount of pips that will be considered as "breakout" the higher timeframe the higher amount you need to prevent false positives.
Last words: 0.000X are for the PIPs for currencies that have 4 or 5 decimals like euro and other, if you use in YEN change it to a configuration of 2 digits decimal. Just that.
Have "fun" !
D_Three Ten Osc on the IntradayHi
Let me introduce my D_Three Ten Osc script.
This indicator allows the
user to plot a daily 3-10 Oscillator on a Tick Bar Chart or any intraday interval.
Walter Bressert's 3-10 Oscillator is a detrending oscillator derived
from subtracting a 10 day moving average from a 3 day moving average.
The second plot is an 16 day simple moving average of the 3-10 Oscillator.
The 16 period moving average is the slow line and the 3/10 oscillator is
the fast line.
For more information on the 3-10 Oscillator see Walter Bressert's book
"The Power of Oscillator/Cycle Combinations"
D_Three Ten Osc on the DailyHi
Let me introduce my D_Three Ten Osc script.
This indicator allows the
user to plot a daily 3-10 Oscillator on a Tick Bar Chart or any intraday interval.
Walter Bressert's 3-10 Oscillator is a detrending oscillator derived
from subtracting a 10 day moving average from a 3 day moving average.
The second plot is an 16 day simple moving average of the 3-10 Oscillator.
The 16 period moving average is the slow line and the 3/10 oscillator is
the fast line.
For more information on the 3-10 Oscillator see Walter Bressert's book
"The Power of Oscillator/Cycle Combinations"
Price Action Concepts [StratifyTrade]// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) creativecommons.org
// © StratifyTrade - formerly know as HunterAlgos
//@version=5
indicator("Price Action Concepts ", shorttitle = "Price Action Concepts ", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500, max_bars_back = 500, max_polylines_count = 100)
//-----------------------------------------------------------------------------{
//Boolean set
//-----------------------------------------------------------------------------{
s_BOS = 0
s_CHoCH = 1
i_BOS = 2
i_CHoCH = 3
i_pp_CHoCH = 4
green_candle = 5
red_candle = 6
s_CHoCHP = 7
i_CHoCHP = 8
boolean =
array.from(
false
, false
, false
, false
, false
, false
, false
, false
, false
)
//-----------------------------------------------------------------------------{
// User inputs
//-----------------------------------------------------------------------------{
show_swing_ms = input.string ("All" , "Swing " , inline = "1", group = "MARKET STRUCTURE" , options = )
show_internal_ms = input.string ("All" , "Internal " , inline = "2", group = "MARKET STRUCTURE" , options = )
internal_r_lookback = input.int (5 , "" , inline = "2", group = "MARKET STRUCTURE" , minval = 2)
swing_r_lookback = input.int (50 , "" , inline = "1", group = "MARKET STRUCTURE" , minval = 2)
ms_mode = input.string ("Manual" , "Market Structure Mode" , inline = "a", group = "MARKET STRUCTURE" , tooltip = " Use selected lenght\n Use automatic lenght" ,options = )
show_mtf_str = input.bool (true , "MTF Scanner" , inline = "9", group = "MARKET STRUCTURE" , tooltip = "Display Multi-Timeframe Market Structure Trend Directions. Green = Bullish. Red = Bearish")
show_eql = input.bool (false , "Show EQH/EQL" , inline = "6", group = "MARKET STRUCTURE")
plotcandle_bool = input.bool (false , "Plotcandle" , inline = "3", group = "MARKET STRUCTURE" , tooltip = "Displays a cleaner colored candlestick chart in place of the default candles. (requires hiding the current ticker candles)")
barcolor_bool = input.bool (false , "Bar Color" , inline = "4", group = "MARKET STRUCTURE" , tooltip = "Color the candle bodies according to market strucutre trend")
i_ms_up_BOS = input.color (#089981 , "" , inline = "2", group = "MARKET STRUCTURE")
i_ms_dn_BOS = input.color (#f23645 , "" , inline = "2", group = "MARKET STRUCTURE")
s_ms_up_BOS = input.color (#089981 , "" , inline = "1", group = "MARKET STRUCTURE")
s_ms_dn_BOS = input.color (#f23645 , "" , inline = "1", group = "MARKET STRUCTURE")
lvl_daily = input.bool (false , "Day " , inline = "1", group = "HIGHS & LOWS MTF")
lvl_weekly = input.bool (false , "Week " , inline = "2", group = "HIGHS & LOWS MTF")
lvl_monthly = input.bool (false , "Month" , inline = "3", group = "HIGHS & LOWS MTF")
lvl_yearly = input.bool (false , "Year " , inline = "4", group = "HIGHS & LOWS MTF")
css_d = input.color (color.blue , "" , inline = "1", group = "HIGHS & LOWS MTF")
css_w = input.color (color.blue , "" , inline = "2", group = "HIGHS & LOWS MTF")
css_m = input.color (color.blue , "" , inline = "3", group = "HIGHS & LOWS MTF")
css_y = input.color (color.blue , "" , inline = "4", group = "HIGHS & LOWS MTF")
s_d = input.string ('⎯⎯⎯' , '' , inline = '1', group = 'HIGHS & LOWS MTF' , options = )
s_w = input.string ('⎯⎯⎯' , '' , inline = '2', group = 'HIGHS & LOWS MTF' , options = )
s_m = input.string ('⎯⎯⎯' , '' , inline = '3', group = 'HIGHS & LOWS MTF' , options = )
s_y = input.string ('⎯⎯⎯' , '' , inline = '4', group = 'HIGHS & LOWS MTF' , options = )
ob_show = input.bool (true , "Show Last " , inline = "1", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Display volumetric order blocks on the chart \n\n Ammount of volumetric order blocks to show")
ob_num = input.int (5 , "" , inline = "1", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Orderblocks number", minval = 1, maxval = 10)
ob_metrics_show = input.bool (true , "Internal Buy/Sell Activity" , inline = "2", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Display volume metrics that have formed the orderblock")
css_metric_up = input.color (color.new(#089981, 50) , " " , inline = "2", group = "VOLUMETRIC ORDER BLOCKS")
css_metric_dn = input.color (color.new(#f23645 , 50) , "" , inline = "2", group = "VOLUMETRIC ORDER BLOCKS")
ob_swings = input.bool (false , "Swing Order Blocks" , inline = "a", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Display swing volumetric order blocks")
css_swing_up = input.color (color.new(color.gray , 90) , " " , inline = "a", group = "VOLUMETRIC ORDER BLOCKS")
css_swing_dn = input.color (color.new(color.silver, 90) , "" , inline = "a", group = "VOLUMETRIC ORDER BLOCKS")
ob_filter = input.string ("None" , "Filtering " , inline = "d", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Filter out volumetric order blocks by BOS/CHoCH/CHoCH+", options = )
ob_mitigation = input.string ("Absolute" , "Mitigation " , inline = "4", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Trigger to remove volumetric order blocks", options = )
ob_pos = input.string ("Precise" , "Positioning " , inline = "k", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Position of the Order Block\n Cover the whole candle\n Cover half candle\n Adjust to volatility\n Same as Accurate but more precise", options = )
use_grayscale = input.bool (false , "Grayscale" , inline = "6", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Use gray as basic order blocks color")
use_show_metric = input.bool (true , "Show Metrics" , inline = "7", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Show volume associated with the orderblock and his relevance")
use_middle_line = input.bool (true , "Show Middle-Line" , inline = "8", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Show mid-line order blocks")
use_overlap = input.bool (true , "Hide Overlap" , inline = "9", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Hide overlapping order blocks")
use_overlap_method = input.string ("Previous" , "Overlap Method " , inline = "Z", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = " Preserve the most recent volumetric order blocks\n\n Preserve the previous volumetric order blocks", options = )
ob_bull_css = input.color (color.new(#089981 , 90) , "" , inline = "1", group = "VOLUMETRIC ORDER BLOCKS")
ob_bear_css = input.color (color.new(#f23645 , 90) , "" , inline = "1", group = "VOLUMETRIC ORDER BLOCKS")
show_acc_dist_zone = input.bool (false , "" , inline = "1", group = "Accumulation And Distribution")
zone_mode = input.string ("Fast" , "" , inline = "1", group = "Accumulation And Distribution" , tooltip = " Find small zone pattern formation\n Find bigger zone pattern formation" ,options = )
acc_css = input.color (color.new(#089981 , 60) , "" , inline = "1", group = "Accumulation And Distribution")
dist_css = input.color (color.new(#f23645 , 60) , "" , inline = "1", group = "Accumulation And Distribution")
show_lbl = input.bool (false , "Show swing point" , inline = "1", group = "High and Low" , tooltip = "Display swing point")
show_mtb = input.bool (false , "Show High/Low/Equilibrium" , inline = "2", group = "High and Low" , tooltip = "Display Strong/Weak High And Low and Equilibrium")
toplvl = input.color (color.red , "Premium Zone " , inline = "3", group = "High and Low")
midlvl = input.color (color.white , "Equilibrium Zone" , inline = "4", group = "High and Low")
btmlvl = input.color (#089981 , "Discount Zone " , inline = "5", group = "High and Low")
fvg_enable = input.bool (false , " " , inline = "1", group = "FAIR VALUE GAP" , tooltip = "Display fair value gap")
what_fvg = input.string ("FVG" , "" , inline = "1", group = "FAIR VALUE GAP" , tooltip = "Display fair value gap", options = )
fvg_num = input.int (5 , "Show Last " , inline = "1a", group = "FAIR VALUE GAP" , tooltip = "Number of fvg to show")
fvg_upcss = input.color (color.new(#089981, 80) , "" , inline = "1", group = "FAIR VALUE GAP")
fvg_dncss = input.color (color.new(color.red , 80) , "" , inline = "1", group = "FAIR VALUE GAP")
fvg_extend = input.int (10 , "Extend FVG" , inline = "2", group = "FAIR VALUE GAP" , tooltip = "Extend the display of the FVG.")
fvg_src = input.string ("Close" , "Mitigation " , inline = "3", group = "FAIR VALUE GAP" , tooltip = " Use the close of the body as trigger\n\n Use the extreme point of the body as trigger", options = )
fvg_tf = input.timeframe ("" , "Timeframe " , inline = "4", group = "FAIR VALUE GAP" , tooltip = "Timeframe of the fair value gap")
t = color.t (ob_bull_css)
invcol = color.new (color.white , 100)
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - UDT }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
type bar
float o = open
float c = close
float h = high
float l = low
float v = volume
int n = bar_index
int t = time
type Zphl
line top
line bottom
label top_label
label bottom_label
bool stopcross
bool sbottomcross
bool itopcross
bool ibottomcross
string txtup
string txtdn
float topy
float bottomy
float topx
float bottomx
float tup
float tdn
int tupx
int tdnx
float itopy
float itopx
float ibottomy
float ibottomx
float uV
float dV
type FVG
box box
line ln
bool bull
float top
float btm
int left
int right
type ms
float p
int n
float l
type msDraw
int n
float p
color css
string txt
bool bull
type obC
float top
float btm
int left
float avg
float dV
float cV
int wM
int blVP
int brVP
int dir
float h
float l
int n
type obD
box ob
box eOB
box blB
box brB
line mL
type zone
chart.point points
float p
int c
int t
type hqlzone
box pbx
box ebx
box lbx
label plb
label elb
label lbl
type ehl
float pt
int t
float pb
int b
type pattern
string found = "None"
bool isfound = false
int period = 0
bool bull = false
type alerts
bool chochswing = false
bool chochplusswing = false
bool swingbos = false
bool chochplus = false
bool choch = false
bool bos = false
bool equal = false
bool ob = false
bool swingob = false
bool zone = false
bool fvg = false
bool obtouch = false
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - End }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - General Setup }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
bar b = bar.new()
var pattern p = pattern.new()
alerts blalert = alerts.new()
alerts bralert = alerts.new()
if p.isfound
p.period += 1
if p.period == 50
p.period := 0
p.found := "None"
p.isfound := false
p.bull := na
switch
b.c > b.o => boolean.set(green_candle, true)
b.c < b.o => boolean.set(red_candle , true)
f_zscore(src, lookback) =>
(src - ta.sma(src, lookback)) / ta.stdev(src, lookback)
var int iLen = internal_r_lookback
var int sLen = swing_r_lookback
vv = f_zscore(((close - close ) / close ) * 100,iLen)
if ms_mode == "Dynamic"
switch
vv >= 1.5 or vv <= -1.5 => iLen := 10
vv >= 1.6 or vv <= -1.6 => iLen := 9
vv >= 1.7 or vv <= -1.7 => iLen := 8
vv >= 1.8 or vv <= -1.8 => iLen := 7
vv >= 1.9 or vv <= -1.9 => iLen := 6
vv >= 2.0 or vv <= -2.0 => iLen := 5
=> iLen
var msline = array.new(0)
iH = ta.pivothigh(high, iLen, iLen)
sH = ta.pivothigh(high, sLen, sLen)
iL = ta.pivotlow (low , iLen, iLen)
sL = ta.pivotlow (low , sLen, sLen)
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - End }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - ARRAYS }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
hl () =>
= request.security(syminfo.tickerid , 'D' , hl() , lookahead = barmerge.lookahead_on)
= request.security(syminfo.tickerid , 'W' , hl() , lookahead = barmerge.lookahead_on)
= request.security(syminfo.tickerid , 'M' , hl() , lookahead = barmerge.lookahead_on)
= request.security(syminfo.tickerid , '12M', hl() , lookahead = barmerge.lookahead_on)
lstyle(style) =>
out = switch style
'⎯⎯⎯' => line.style_solid
'----' => line.style_dashed
'····' => line.style_dotted
mtfphl(h, l ,tf ,css, pdhl_style) =>
var line hl = line.new(
na
, na
, na
, na
, xloc = xloc.bar_time
, color = css
, style = lstyle(pdhl_style)
)
var line ll = line.new(
na
, na
, na
, na
, xloc = xloc.bar_time
, color = css
, style = lstyle(pdhl_style)
)
var label lbl = label.new(
na
, na
, xloc = xloc.bar_time
, text = str.format('P{0}L', tf)
, color = invcol
, textcolor = css
, size = size.small
, style = label.style_label_left
)
var label hlb = label.new(
na
, na
, xloc = xloc.bar_time
, text = str.format('P{0}H', tf)
, color = invcol
, textcolor = css
, size = size.small
, style = label.style_label_left
)
hy = ta.valuewhen(h != h , h , 1)
hx = ta.valuewhen(h == high , time , 1)
ly = ta.valuewhen(l != l , l , 1)
lx = ta.valuewhen(l == low , time , 1)
if barstate.islast
extension = time + (time - time ) * 50
line.set_xy1(hl , hx , hy)
line.set_xy2(hl , extension , hy)
label.set_xy(hlb, extension , hy)
line.set_xy1(ll , lx , ly)
line.set_xy2(ll , extension , ly)
label.set_xy(lbl, extension , ly)
if lvl_daily
mtfphl(pdh , pdl , 'D' , css_d, s_d)
if lvl_weekly
mtfphl(pwh , pwl , 'W' , css_w, s_w)
if lvl_monthly
mtfphl(pmh , pml, 'M' , css_m, s_m)
if lvl_yearly
mtfphl(pyh , pyl , '12M', css_y, s_y)
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - End }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - Market Structure }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
method darkcss(color css, float factor, bool bull) =>
blue = color.b(css) * (1 - factor)
red = color.r(css) * (1 - factor)
green = color.g(css) * (1 - factor)
color.rgb(red, green, blue, 0)
method f_line(msDraw d, size, style) =>
var line id = na
var label lbl = na
id := line.new(
d.n
, d.p
, b.n
, d.p
, color = d.css
, width = 1
, style = style
)
if msline.size() >= 250
line.delete(msline.shift())
msline.push(id)
lbl := label.new(
int(math.avg(d.n, b.n))
, d.p
, d.txt
, color = invcol
, textcolor = d.css
, style = d.bull ? label.style_label_down : label.style_label_up
, size = size
, text_font_family = font.family_monospace
)
structure(bool mtf) =>
msDraw drw = na
bool isdrw = false
bool isdrwS = false
var color css = na
var color icss = na
var int itrend = 0
var int trend = 0
bool bull_ob = false
bool bear_ob = false
bool s_bull_ob = false
bool s_bear_ob = false
n = bar_index
var ms up = ms.new(
array.new()
, array.new< int >()
, array.new()
)
var ms dn = ms.new(
array.new()
, array.new< int >()
, array.new()
)
var ms sup = ms.new(
array.new()
, array.new< int >()
, array.new()
)
var ms sdn = ms.new(
array.new()
, array.new< int >()
, array.new()
)
switch show_swing_ms
"All" => boolean.set(s_BOS , true ), boolean.set(s_CHoCH, true ) , boolean.set(s_CHoCHP, true )
"CHoCH" => boolean.set(s_BOS , false), boolean.set(s_CHoCH, true ) , boolean.set(s_CHoCHP, false )
"CHoCH+" => boolean.set(s_BOS , false), boolean.set(s_CHoCH, false) , boolean.set(s_CHoCHP, true )
"BOS" => boolean.set(s_BOS , true ), boolean.set(s_CHoCH, false) , boolean.set(s_CHoCHP, false )
"None" => boolean.set(s_BOS , false), boolean.set(s_CHoCH, false) , boolean.set(s_CHoCHP, false )
=> na
switch show_internal_ms
"All" => boolean.set(i_BOS, true ), boolean.set(i_CHoCH, true ), boolean.set(i_CHoCHP, true )
"CHoCH" => boolean.set(i_BOS, false), boolean.set(i_CHoCH, true ), boolean.set(i_CHoCHP, false)
"CHoCH+" => boolean.set(i_BOS, false), boolean.set(i_CHoCH, false ), boolean.set(i_CHoCHP, true )
"BOS" => boolean.set(i_BOS, true ), boolean.set(i_CHoCH, false ), boolean.set(i_CHoCHP, false)
"None" => boolean.set(i_BOS, false), boolean.set(i_CHoCH, false ), boolean.set(i_CHoCHP, false)
=> na
switch
iH =>
up.p.unshift(b.h )
up.l.unshift(b.h )
up.n.unshift(n )
iL =>
dn.p.unshift(b.l )
dn.l.unshift(b.l )
dn.n.unshift(n )
sL =>
sdn.p.unshift(b.l )
sdn.l.unshift(b.l )
sdn.n.unshift(n )
sH =>
sup.p.unshift(b.h )
sup.l.unshift(b.h )
sup.n.unshift(n )
// INTERNAL BULLISH STRUCTURE
if up.p.size() > 0 and dn.l.size() > 1
if ta.crossover(b.c, up.p.first())
bool CHoCH = na
string txt = na
if itrend < 0
CHoCH := true
switch
not CHoCH =>
txt := "BOS"
css := i_ms_up_BOS
blalert.bos := true
if boolean.get(i_BOS) and mtf == false and na(drw)
isdrw := true
drw := msDraw.new(
up.n.first()
, up.p.first()
, i_ms_up_BOS
, txt
, true
)
CHoCH =>
dn.l.first() > dn.l.get(1) ? blalert.chochplus : blalert.choch
txt := dn.l.first() > dn.l.get(1) ? "CHoCH+" : "CHoCH"
css := i_ms_up_BOS.darkcss(0.25, true)
if (dn.l.first() > dn.l.get(1) ? boolean.get(i_CHoCHP) : boolean.get(i_CHoCH)) and mtf == false and na(drw)
isdrw := true
drw := msDraw.new(
up.n.first()
, up.p.first()
, i_ms_up_BOS.darkcss(0.25, true)
, txt
, true
)
if mtf == false
switch
ob_filter == "None" => bull_ob := true
ob_filter == "BOS" and txt == "BOS" => bull_ob := true
ob_filter == "CHoCH" and txt == "CHoCH" => bull_ob := true
ob_filter == "CHoCH+" and txt == "CHoCH+" => bull_ob := true
itrend := 1
up.n.clear()
up.p.clear()
// INTERNAL BEARISH STRUCTURE
if dn.p.size() > 0 and up.l.size() > 1
if ta.crossunder(b.c, dn.p.first())
bool CHoCH = na
string txt = na
if itrend > 0
CHoCH := true
switch
not CHoCH =>
bralert.bos := true
txt := "BOS"
css := i_ms_dn_BOS
if boolean.get(i_BOS) and mtf == false and na(drw)
isdrw := true
drw := msDraw.new(
dn.n.first()
, dn.p.first()
, i_ms_dn_BOS
, txt
, false
)
CHoCH =>
if up.l.first() < up.l.get(1)
bralert.chochplus := true
else
bralert.choch := true
txt := up.l.first() < up.l.get(1) ? "CHoCH+" : "CHoCH"
css := i_ms_dn_BOS.darkcss(0.25, false)
if (up.l.first() < up.l.get(1) ? boolean.get(i_CHoCHP) : boolean.get(i_CHoCH)) and mtf == false and na(drw)
isdrw := true
drw := msDraw.new(
dn.n.first()
, dn.p.first()
, i_ms_dn_BOS.darkcss(0.25, false)
, txt
, false
)
if mtf == false
switch
ob_filter == "None" => bear_ob := true
ob_filter == "BOS" and txt == "BOS" => bear_ob := true
ob_filter == "CHoCH" and txt == "CHoCH" => bear_ob := true
ob_filter == "CHoCH+" and txt == "CHoCH+" => bear_ob := true
itrend := -1
dn.n.clear()
dn.p.clear()
// SWING BULLISH STRUCTURE
if sup.p.size() > 0 and sdn.l.size() > 1
if ta.crossover(b.c, sup.p.first())
bool CHoCH = na
string txt = na
if trend < 0
CHoCH := true
switch
not CHoCH =>
blalert.swingbos := true
txt := "BOS"
icss := s_ms_up_BOS
if boolean.get(s_BOS) and mtf == false and na(drw)
isdrwS := true
drw := msDraw.new(
sup.n.first()
, sup.p.first()
, s_ms_up_BOS
, txt
, true
)
CHoCH =>
if sdn.l.first() > sdn.l.get(1)
blalert.chochplusswing := true
else
blalert.chochswing := true
txt := sdn.l.first() > sdn.l.get(1) ? "CHoCH+" : "CHoCH"
icss := s_ms_up_BOS.darkcss(0.25, true)
if (sdn.l.first() > sdn.l.get(1) ? boolean.get(s_CHoCHP) : boolean.get(s_CHoCH)) and mtf == false and na(drw)
isdrwS := true
drw := msDraw.new(
sup.n.first()
, sup.p.first()
, s_ms_up_BOS.darkcss(0.25, true)
, txt
, true
)
if mtf == false
switch
ob_filter == "None" => s_bull_ob := true
ob_filter == "BOS" and txt == "BOS" => s_bull_ob := true
ob_filter == "CHoCH" and txt == "CHoCH" => s_bull_ob := true
ob_filter == "CHoCH+" and txt == "CHoCH+" => s_bull_ob := true
trend := 1
sup.n.clear()
sup.p.clear()
// SWING BEARISH STRUCTURE
if sdn.p.size() > 0 and sup.l.size() > 1
if ta.crossunder(b.c, sdn.p.first())
bool CHoCH = na
string txt = na
if trend > 0
CHoCH := true
switch
not CHoCH =>
bralert.swingbos := true
txt := "BOS"
icss := s_ms_dn_BOS
if boolean.get(s_BOS) and mtf == false and na(drw)
isdrwS := true
drw := msDraw.new(
sdn.n.first()
, sdn.p.first()
, s_ms_dn_BOS
, txt
, false
)
CHoCH =>
if sup.l.first() < sup.l.get(1)
bralert.chochplusswing := true
else
bralert.chochswing := true
txt := sup.l.first() < sup.l.get(1) ? "CHoCH+" : "CHoCH"
icss := s_ms_dn_BOS.darkcss(0.25, false)
if (sup.l.first() < sup.l.get(1) ? boolean.get(s_CHoCHP) : boolean.get(s_CHoCH)) and mtf == false and na(drw)
isdrwS := true
drw := msDraw.new(
sdn.n.first()
, sdn.p.first()
, s_ms_dn_BOS.darkcss(0.25, false)
, txt
, false
)
if mtf == false
switch
ob_filter == "None" => s_bear_ob := true
ob_filter == "BOS" and txt == "BOS" => s_bear_ob := true
ob_filter == "CHoCH" and txt == "CHoCH" => s_bear_ob := true
ob_filter == "CHoCH+" and txt == "CHoCH+" => s_bear_ob := true
trend := -1
sdn.n.clear()
sdn.p.clear()
= structure(false)
if isdrw
f_line(drw, size.small, line.style_dashed)
if isdrwS
f_line(drw, size.small, line.style_solid)
= request.security("", "15" , structure(true))
= request.security("", "60" , structure(true))
= request.security("", "240" , structure(true))
= request.security("", "1440" , structure(true))
if show_mtf_str
var tab = table.new(position = position.top_right, columns = 10, rows = 10, bgcolor = na, frame_color = color.rgb(54, 58, 69, 0), frame_width = 1, border_color = color.rgb(54, 58, 69, 100), border_width = 1)
table.cell(tab, 0, 1, text = "15" , text_color = color.silver, text_halign = text.align_center, text_size = size.normal, bgcolor = chart.bg_color, text_font_family = font.family_monospace, width = 2)
table.cell(tab, 0, 2, text = "1H" , text_color = color.silver, text_halign = text.align_center, text_size = size.normal, bgcolor = chart.bg_color, text_font_family = font.family_monospace, width = 2)
table.cell(tab, 0, 3, text = "4H" , text_color = color.silver, text_halign = text.align_center, text_size = size.normal, bgcolor = chart.bg_color, text_font_family = font.family_monospace, width = 2)
table.cell(tab, 0, 4, text = "1D" , text_color = color.silver, text_halign = text.align_center, text_size = size.normal, bgcolor = chart.bg_color, text_font_family = font.family_monospace, width = 2)
table.cell(tab, 1, 1, text = itrend15 == 1 ? "BULLISH" : itrend15 == -1 ? "BEARISH" : na , text_halign = text.align_center, text_size = size.normal, text_color = itrend15 == 1 ? i_ms_up_BOS.darkcss(-0.25, true) : itrend15 == -1 ? i_ms_dn_BOS.darkcss(0.25, false) : color.gray, bgcolor = chart.bg_color, text_font_family = font.family_monospace)
table.cell(tab, 1, 2, text = itrend1H == 1 ? "BULLISH" : itrend1H == -1 ? "BEARISH" : na , text_halign = text.align_center, text_size = size.normal, text_color = itrend1H == 1 ? i_ms_up_BOS.darkcss(-0.25, true) : itrend1H == -1 ? i_ms_dn_BOS.darkcss(0.25, false) : color.gray, bgcolor = chart.bg_color, text_font_family = font.family_monospace)
table.cell(tab, 1, 3, text = itrend4H == 1 ? "BULLISH" : itrend4H == -1 ? "BEARISH" : na , text_halign = text.align_center, text_size = size.normal, text_color = itrend4H == 1 ? i_ms_up_BOS.darkcss(-0.25, true) : itrend4H == -1 ? i_ms_dn_BOS.darkcss(0.25, false) : color.gray, bgcolor = chart.bg_color, text_font_family = font.family_monospace)
table.cell(tab, 1, 4, text = itrend1D == 1 ? "BULLISH" : itrend1D == -1 ? "BEARISH" : na , text_halign = text.align_center, text_size = size.normal, text_color = itrend1D == 1 ? i_ms_up_BOS.darkcss(-0.25, true) : itrend1D == -1 ? i_ms_dn_BOS.darkcss(0.25, false) : color.gray, bgcolor = chart.bg_color, text_font_family = font.family_monospace)
table.cell(tab, 0, 5, text = "Detected Pattern", text_halign = text.align_center, text_size = size.normal, text_color = color.silver, bgcolor = chart.bg_color, text_font_family = font.family_monospace)
table.cell(tab, 0, 6, text = p.found, text_halign = text.align_center, text_size = size.normal, text_color = na(p.bull) ? color.white : p.bull ? i_ms_up_BOS.darkcss(-0.25, true) : p.bull == false ? i_ms_dn_BOS.darkcss(0.25, false) : na, bgcolor = chart.bg_color, text_font_family = font.family_monospace)
table.merge_cells(tab, 0, 5, 1, 5)
table.merge_cells(tab, 0, 6, 1, 6)
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - End }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - Strong/Weak High/Low And Equilibrium }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
var phl = Zphl.new(
na
, na
, label.new(na , na , color = invcol , textcolor = i_ms_dn_BOS , style = label.style_label_down , size = size.tiny , text = "")
, label.new(na , na , color = invcol , textcolor = i_ms_up_BOS , style = label.style_label_up , size = size.tiny , text = "")
, true
, true
, true
, true
, ""
, ""
, 0
, 0
, 0
, 0
, high
, low
, 0
, 0
, 0
, 0
, 0
, 0
, na
, na
)
zhl(len)=>
upper = ta.highest(len)
lower = ta.lowest(len)
var float out = 0
out := b.h > upper ? 0 : b.l < lower ? 1 : out
top = out == 0 and out != 0 ? b.h : 0
btm = out == 1 and out != 1 ? b.l : 0
= zhl(sLen)
= zhl(iLen)
upphl(trend) =>
var label lbl = label.new(
na
, na
, color = invcol
, textcolor = toplvl
, style = label.style_label_down
, size = size.small
)
if top
phl.stopcross := true
phl.txtup := top > phl.topy ? "HH" : "HL"
if show_lbl
topl = label.new(
b.n - swing_r_lookback
, top
, phl.txtup
, color = invcol
, textcolor = toplvl
, style = label.style_label_down
, size = size.small
)
line.delete(phl.top )
phl.top := line.new(
b.n - sLen
, top
, b.n
, top
, color = toplvl)
phl.topy := top
phl.topx := b.n - sLen
phl.tup := top
phl.tupx := b.n - sLen
if itop
phl.itopcross := true
phl.itopy := itop
phl.itopx := b.n - iLen
phl.tup := math.max(high, phl.tup)
phl.tupx := phl.tup == high ? b.n : phl.tupx
phl.uV := phl.tup != phl.tup ? b.v : phl.uV
if barstate.islast
line.set_xy1(
phl.top
, phl.tupx
, phl.tup
)
line.set_xy2(
phl.top
, b.n + 50
, phl.tup
)
label.set_x(
lbl
, b.n + 50
)
label.set_y(
lbl
, phl.tup
)
dist = math.abs(phl.uV / (phl.uV + phl.dV)) * 100
label.set_text (lbl, trend < 0
? "Strong High | " + str.tostring(phl.uV, format.volume) + " (" + str.tostring(math.round(dist,0)) + "%)"
: "Weak High | " + str.tostring(phl.uV, format.volume) + " (" + str.tostring(math.round(dist,0)) + "%)")
dnphl(trend) =>
var label lbl = label.new(
na
, na
, color = invcol
, textcolor = btmlvl
, style = label.style_label_up
, size = size.small
)
if btm
phl.sbottomcross := true
phl.txtdn := btm > phl.bottomy ? "LH" : "LL"
if show_lbl
btml = label.new(
b.n - swing_r_lookback
, btm, phl.txtdn
, color = invcol
, textcolor = btmlvl
, style = label.style_label_up
, size = size.small
)
line.delete(phl.bottom )
phl.bottom := line.new(
b.n - sLen
, btm
, b.n
, btm
, color = btmlvl
)
phl.bottomy := btm
phl.bottomx := b.n - sLen
phl.tdn := btm
phl.tdnx := b.n - sLen
if ibtm
phl.ibottomcross := true
phl.ibottomy := ibtm
phl.ibottomx := b.n - iLen
phl.tdn := math.min(low, phl.tdn)
phl.tdnx := phl.tdn == low ? b.n : phl.tdnx
phl.dV := phl.tdn != phl.tdn ? b.v : phl.dV
if barstate.islast
line.set_xy1(
phl.bottom
, phl.tdnx
, phl.tdn
)
line.set_xy2(
phl.bottom
, b.n + 50
, phl.tdn
)
label.set_x(
lbl
, b.n + 50
)
label.set_y(
lbl
, phl.tdn
)
dist = math.abs(phl.dV / (phl.uV + phl.dV)) * 100
label.set_text (lbl, trend > 0
? "Strong Low | " + str.tostring(phl.dV, format.volume) + " (" + str.tostring(math.round(dist,0)) + "%)"
: "Weak Low | " + str.tostring(phl.uV, format.volume) + " (" + str.tostring(math.round(dist,0)) + "%)")
midphl() =>
avg = math.avg(phl.bottom.get_y2(), phl.top.get_y2())
var line l = line.new(
y1 = avg
, y2 = avg
, x1 = b.n - sLen
, x2 = b.n + 50
, color = midlvl
, style = line.style_solid
)
var label lbl = label.new(
x = b.n + 50
, y = avg
, text = "Equilibrium"
, style = label.style_label_left
, color = invcol
, textcolor = midlvl
, size = size.small
)
if barstate.islast
more = (phl.bottom.get_x1() + phl.bottom.get_x2()) > (phl.top.get_x1() + phl.top.get_x2()) ? phl.top.get_x1() : phl.bottom.get_x1()
line.set_xy1(l , more , avg)
line.set_xy2(l , b.n + 50, avg)
label.set_x (lbl , b.n + 50 )
label.set_y (lbl , avg )
dist = math.abs((l.get_y2() - close) / close) * 100
label.set_text (lbl, "Equilibrium (" + str.tostring(math.round(dist,0)) + "%)")
hqlzone() =>
if barstate.islast
var hqlzone dZone = hqlzone.new(
box.new(
na
, na
, na
, na
, bgcolor = color.new(toplvl, 70)
, border_color = na
)
, box.new(
na
, na
, na
, na
, bgcolor = color.new(midlvl, 70)
, border_color = na
)
, box.new(
na
, na
, na
, na
, bgcolor = color.new(btmlvl, 70)
, border_color = na
)
, label.new(na, na, text = "Premium" , color = invcol, textcolor = toplvl, style = label.style_label_down, size = size.small)
, label.new(na, na, text = "Equilibrium", color = invcol, textcolor = midlvl, style = label.style_label_left, size = size.small)
, label.new(na, na, text = "Discount" , color = invcol, textcolor = btmlvl, style = label.style_label_up , size = size.small)
)
dZone.pbx.set_lefttop(int(math.max(phl.topx, phl.bottomx)) , phl.tup)
dZone.pbx.set_rightbottom(b.n + 50 , 0.95 * phl.tup + 0.05 * phl.tdn)
dZone.ebx.set_lefttop(int(math.max(phl.topx, phl.bottomx)), 0.525 * phl.tup + 0.475 * phl.tdn)
dZone.ebx.set_rightbottom(b.n + 50 , 0.525 * phl.tdn + 0.475 * phl.tup)
dZone.lbx.set_lefttop(int(math.max(phl.topx, phl.bottomx)), 0.95 * phl.tdn + 0.05 * phl.tup)
dZone.lbx.set_rightbottom(b.n + 50 , phl.tdn)
dZone.plb.set_xy( int(math.avg(math.max(phl.topx, phl.bottomx), int(b.n + 50))) , phl.tup)
dZone.elb.set_xy( int(b.n + 50) , math.avg(phl.tup, phl.tdn))
dZone.lbl.set_xy( int(math.avg(math.max(phl.topx, phl.bottomx), int(b.n + 50))) , phl.tdn)
if show_mtb
upphl (trend)
dnphl (trend)
hqlzone()
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - End }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - Volumetric Order Block }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
method eB(box b, bool ext, color css, bool swing) =>
b.unshift(
box.new(
na
, na
, na
, na
, xloc = xloc.bar_time
, text_font_family = font.family_monospace
, extend = ext ? extend.right : extend.none
, border_color = swing ? color.new(css, 0) : color.new(color.white,100)
, bgcolor = css
, border_width = 1
)
)
method eL(line l, bool ext, bool solid, color css) =>
l.unshift(
line.new(
na
, na
, na
, na
, width = 1
, color = css
, xloc = xloc.bar_time
, extend = ext ? extend.right : extend.none
, style = solid ? line.style_solid : line.style_dashed
)
)
method drawVOB(bool cdn, bool bull, color css, int loc, bool swing) =>
= request.security(
syminfo.tickerid
, ""
,
, lookahead = barmerge.lookahead_off
)
var obC obj = obC.new(
array.new()
, array.new()
, array.new< int >()
, array.new()
, array.new()
, array.new()
, array.new< int >()
, array.new< int >()
, array.new< int >()
, array.new< int >()
, array.new()
, array.new()
, array.new< int >()
)
var obD draw = obD.new(
array.new()
, array.new()
, array.new()
, array.new()
, array.new()
)
if barstate.isfirst
for i = 0 to ob_num - 1
draw.mL .eL(false, false, use_grayscale ? color.new(color.gray, 0) : color.new(css,0))
draw.ob .eB(false, use_grayscale ? color.new(color.gray, 90) : css, swing)
draw.blB.eB(false, css_metric_up , swing)
draw.brB.eB(false, css_metric_dn , swing)
draw.eOB.eB(true , use_grayscale ? color.new(color.gray, 90) : css, swing)
float pos = ob_pos == "Full"
? (bull ? high : low)
: ob_pos == "Middle"
? ohlc4
: ob_pos == "Accurate"
? hl2
: hl2
if cdn
obj.h.clear()
obj.l.clear()
obj.n.clear()
for i = 1 to math.abs((loc - b.n)) - 1
obj.h.push(hH )
obj.l.push(lL )
obj.n.push(b.t )
// obj.h.reverse()
// obj.l.reverse()
int iU = obj.l.indexof(obj.l.min()) + 1
int iD = obj.h.indexof(obj.h.max()) + 1
obj.dir.unshift(
bull
? (b.c > b.o ? 1 : -1)
: (b.c > b.o ? 1 : -1)
)
obj.top.unshift(
bull
? pos
: obj.h.max()
)
obj.btm.unshift(
bull
? obj.l.min()
: pos
)
obj.left.unshift(
bull
? obj.n.get(obj.l.indexof(obj.l.min()))
: obj.n.get(obj.h.indexof(obj.h.max()))
)
obj.avg.unshift(
math.avg(obj.top.first(), obj.btm.first())
)
obj.cV.unshift(
bull
? b.v
: b.v
)
if ob_pos == "Precise"
switch bull
true =>
if obj.avg.get(0) < (b.c < b.o ? b.c : b.o ) and obj.top.get(0) > hlcc4
obj.top.set(0, obj.avg.get(0))
obj.avg.set(0, math.avg(obj.top.first(), obj.btm.first()))
false =>
if obj.avg.get(0) > (b.c < b.o ? b.o : b.c ) and obj.btm.get(0) < hlcc4
obj.btm.set(0, obj.avg.get(0))
obj.avg.set(0, math.avg(obj.top.first(), obj.btm.first()))
obj.blVP.unshift ( 0 )
obj.brVP.unshift ( 0 )
obj.wM .unshift ( 1 )
if use_overlap
int rmP = use_overlap_method == "Recent" ? 1 : 0
if obj.avg.size() > 1
if bull
? obj.btm.first() < obj.top.get(1)
: obj.top.first() > obj.btm.get(1)
obj.wM .remove(rmP)
obj.cV .remove(rmP)
obj.dir .remove(rmP)
obj.top .remove(rmP)
obj.avg .remove(rmP)
obj.btm .remove(rmP)
obj.left .remove(rmP)
obj.blVP .remove(rmP)
obj.brVP .remove(rmP)
if barstate.isconfirmed
for x = 0 to ob_num - 1
tg = switch ob_mitigation
"Middle" => obj.avg
"Absolute" => bull ? obj.btm : obj.top
for in tg
if (bull ? cC < pt : cC > pt)
obj.wM .remove(idx)
obj.cV .remove(idx)
obj.dir .remove(idx)
obj.top .remove(idx)
obj.avg .remove(idx)
obj.btm .remove(idx)
obj.left .remove(idx)
obj.blVP .remove(idx)
obj.brVP .remove(idx)
if barstate.islast
if obj.avg.size() > 0
// Alert
if bull
? ta.crossunder(low , obj.top.get(0))
: ta.crossover (high, obj.btm.get(0))
switch bull
true => blalert.obtouch := true
false => bralert.obtouch := true
float tV = 0
obj.dV.clear()
seq = math.min(ob_num - 1, obj.avg.size() - 1)
for j = 0 to seq
tV += obj.cV.get(j)
if j == seq
for y = 0 to seq
obj.dV.unshift(
math.floor(
(obj.cV.get(y) / tV) * 100)
)
obj.dV.reverse()
for i = 0 to math.min(ob_num - 1, obj.avg.size() - 1)
dmL = draw.mL .get(i)
dOB = draw.ob .get(i)
dblB = draw.blB.get(i)
dbrB = draw.brB.get(i)
deOB = draw.eOB.get(i)
dOB.set_lefttop (obj.left .get(i) , obj.top.get(i))
deOB.set_lefttop (b.t , obj.top.get(i))
dOB.set_rightbottom (b.t , obj.btm.get(i))
deOB.set_rightbottom(b.t + (b.t - b.t ) * 100 , obj.btm.get(i))
if use_middle_line
dmL.set_xy1(obj.left.get(i), obj.avg.get(i))
dmL.set_xy2(b.t , obj.avg.get(i))
if ob_metrics_show
dblB.set_lefttop (obj.left.get(i), obj.top.get(i))
dbrB.set_lefttop (obj.left.get(i), obj.avg.get(i))
dblB.set_rightbottom(obj.left.get(i), obj.avg.get(i))
dbrB.set_rightbottom(obj.left.get(i), obj.btm.get(i))
rpBL = dblB.get_right()
rpBR = dbrB.get_right()
dbrB.set_right(rpBR + (b.t - b.t ) * obj.brVP.get(i))
dblB.set_right(rpBL + (b.t - b.t ) * obj.blVP.get(i))
if use_show_metric
txt = switch
obj.cV.get(i) >= 1000000000 => str.tostring(math.round(obj.cV.get(i) / 1000000000,3)) + "B"
obj.cV.get(i) >= 1000000 => str.tostring(math.round(obj.cV.get(i) / 1000000,3)) + "M"
obj.cV.get(i) >= 1000 => str.tostring(math.round(obj.cV.get(i) / 1000,3)) + "K"
obj.cV.get(i) < 1000 => str.tostring(math.round(obj.cV.get(i)))
deOB.set_text(
str.tostring(
txt + " (" + str.tostring(obj.dV.get(i)) + "%)")
)
deOB.set_text_size (size.auto)
deOB.set_text_halign(text.align_left)
deOB.set_text_color (use_grayscale ? color.silver : color.new(css, 0))
if ob_metrics_show and barstate.isconfirmed
if obj.wM.size() > 0
for i = 0 to obj.avg.size() - 1
switch obj.dir.get(i)
1 =>
switch obj.wM.get(i)
1 => obj.blVP.set(i, obj.blVP.get(i) + 1), obj.wM.set(i, 2)
2 => obj.blVP.set(i, obj.blVP.get(i) + 1), obj.wM.set(i, 3)
3 => obj.brVP.set(i, obj.brVP.get(i) + 1), obj.wM.set(i, 1)
-1 =>
switch obj.wM.get(i)
1 => obj.brVP.set(i, obj.brVP.get(i) + 1), obj.wM.set(i, 2)
2 => obj.brVP.set(i, obj.brVP.get(i) + 1), obj.wM.set(i, 3)
3 => obj.blVP.set(i, obj.blVP.get(i) + 1), obj.wM.set(i, 1)
var hN = array.new(1, b.n)
var lN = array.new(1, b.n)
var hS = array.new(1, b.n)
var lS = array.new(1, b.n)
if iH
hN.pop()
hN.unshift(int(b.n ))
if iL
lN.pop()
lN.unshift(int(b.n ))
if sH
hS.pop()
hS.unshift(int(b.n ))
if sL
lS.pop()
lS.unshift(int(b.n ))
if ob_show
bull_ob.drawVOB(true , ob_bull_css, hN.first(), false)
bear_ob.drawVOB(false, ob_bear_css, lN.first(), false)
if ob_swings
s_bull_ob.drawVOB(true , css_swing_up, hS.first(), true)
s_bear_ob.drawVOB(false, css_swing_dn, lS.first(), true)
if bull_ob
blalert.ob := true
if bear_ob
bralert.ob := true
if s_bull_ob
blalert.swingob := true
if s_bear_ob
blalert.swingob := true
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - End }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - FVG | VI | OG }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
ghl() => request.security(syminfo.tickerid, fvg_tf, [high , low , close , open ])
tfG() => request.security(syminfo.tickerid, fvg_tf, )
cG(bool bull) =>
= ghl()
= tfG()
var FVG draw = FVG.new(
array.new()
, array.new()
)
var FVG cords = array.new()
float pup = na
float pdn = na
bool cdn = na
int pos = 2
cc = timeframe.change(fvg_tf)
if barstate.isfirst
for i = 0 to fvg_num - 1
draw.box.unshift(box.new (na, na, na, na, border_color = color.new(color.white, 100), xloc = xloc.bar_time))
draw.ln.unshift (line.new(na, na, na, na, xloc = xloc.bar_time, width = 1, style = line.style_solid))
switch what_fvg
"FVG" =>
pup := bull ? gl : l
pdn := bull ? h : gh
cdn := bull ? gl > h and cc : gh < l and cc
pos := 2
"VI" =>
pup := bull
? (gc > go
? go
: gc)
: (gc > go
? go
: gc )
pdn := bull
? (gc > go
? gc
: go )
: (gc > go
? gc
: go)
cdn := bull
? go > gc and gh > gl and gc > gc and go > go and gh < math.min(gc, go) and cc
: go < gc and gl < gh and gc < gc and go < go and gl > math.max(gc, go) and cc
pos := 1
"OG" =>
pup := bull ? b.l : gl
pdn := bull ? gh : gh
cdn := bull ? gl > gh and cc : gh < gl and cc
pos := 1
if not na(cdn) and cdn
cords.unshift(
FVG.new(
na
, na
, bull
? true
: false
, pup
, pdn
, b.t - (b.t - b.t ) * pos
, b.t + (b.t - b.t ) * fvg_extend)
)
if bull
blalert.fvg := tru
Frahm FactorIntended Usage of the Frahm Factor Indicator
The Frahm Factor is designed to give you a rapid, at-a-glance assessment of how volatile the market is right now—and how large the average candle has been—over the most recent 24-hour window. Here’s how to put it to work:
Gauge Volatility Regimes
Volatility Score (1–10)
A low score (1–3, green) signals calm seas—tight ranges, low risk of big moves.
A mid score (4–6, yellow) warns you that volatility is picking up.
A high score (7–10, red) tells you to prepare for disorderly swings or breakout opportunities.
How to trade off it
In low-volatility periods, you might favor mean-reversion or range-bound strategies.
As the score climbs into the red zone, consider widening stops, scaling back position size, or switching to breakout momentum plays.
Monitor Average Candle Size
Avg Candle (ticks) cell shows you the mean true-range of each bar over that 24h window in ticks.
When candles are small, you know the market is consolidating and liquidity may be thin.
When candles are large, momentum and volume are driving strong directional bias.
The optional dynamic color ramp (green→yellow→red) immediately flags when average bar size is unusually small or large versus its own 24h history.
Customize & Stay Flexible
Timeframes: Works on any intraday chart—from 1-minute scalping to 4-hour swing setups—because it always looks back exactly 24 hours.
Toggles:
Show or hide the Volatility and Avg-Candle cells to keep your screen uncluttered.
Turn on the dynamic color ramp only when you want that extra visual cue.
Alerts: Built-in alerts fire automatically at meaningful thresholds (Volatility ≥ 8 or ≤ 3), so you’ll never miss regime shifts, even if you step away.
Real-World Applications
Risk Management: Automatically adjust your stop-loss distances or position sizing based on the current volatility band.
Strategy Selection: Flip between range-trading and momentum strategies as the volatility regime changes.
Session Analysis: Pinpoint when during the day volatility typically ramps—perfect for doorway sessions like London opening or the US midday news spikes.
Bottom line: the Frahm Factor gives you one compact dashboard to see the pulse of the market—so you can make choices with conviction, dial your risk in real time, and never be caught off guard by sudden volatility shifts.
Logic Behind the Frahm Factor Indicator
24-Hour Rolling Window
On every intraday bar, we append that bar’s True Range (TR) and timestamp to two arrays.
We then prune any entries older than 24 hours, so the arrays always reflect exactly the last day of data.
Volatility Score (1–10)
We count how many of those 24 h TR values are less than or equal to the current bar’s TR.
Dividing by the total array size gives a percentile (0–1), which we scale and round into a 1–10 score.
Average Candle Size (ticks)
We sum all TR values in the same 24 h window, divide by array length to get the mean TR, then convert that price range into ticks.
Optionally, a green→yellow→red ramp highlights when average bar size is unusually small, medium or large versus its own 24 h history.
Color & Alerts
The Volatility cell flips green (1–3), yellow (4–6) or red (7–10) so you see regime shifts at a glance.
Built-in alertcondition calls fire when the score crosses your high (≥ 8) or low (≤ 3) thresholds.
Modularity
Everything—table location, which cells to show, dynamic coloring—is controlled by simple toggles, so you can strip it back or layer on extra visual cues as needed.
That’s the full recipe: a true 24 h look-back, a percentile-ranked volatility gauge, and a mean-bar-size meter, all wrapped into one compact dashboard.
Timeframe LoopThe Timeframe Loop publication aims to visualize intrabar price progression in a new, different way.
🔶 CONCEPTS and USAGE
I got inspiration from the Pressure/Volume loop, which is used in Mechanical Ventilation with Critical Care patients to visualize pressure/volume evolution during inhalation/exhalation.
The main idea is that intrabar prices are visualized by a loop, going to the right during the first half and returning to the left towards its closing point. Here, the main chart timeframe (CTF) is 4 hours, and we see the movements of eight 30-minute lower timeframe (LTF) periods, highlighted by four yellow dots/lines (first 2 hours -> "Right") and four blue dots/lines (last 2 hours <- "Left"):
🔹 BTF
If "Show Lowest TF" is enabled, the LTF is split into another lower TF (BTF - "Base TF"); in this case, the 30-minute LTF is split into 10 parts of 3 minutes (BTF):
Enabling "Loop Lowest TF" will enable the BTF to react similarly to the largest loop; from halfway, it will return to its startpoint:
Here is a more detailed example:
🔹 Mini-Candles
The included option "Mini-Candles" will bring even more detail, showing the LTF as Japanese candlesticks with user-defined colors and adjustable body width; in this example, the mini-candles associated with the first half (yellow lines/dots) are green/red, while blue/fuchsia in the second half (blue lines/dots):
CTF 10 minutes, LTF 1 minute, BTF 5 seconds
One can see the detailed intrabar price progression in one glance.
CTF 5 minutes, LTF 1 minute, BTF 5 seconds
If the LTF/BTF ratio, divided by two, results in a non-integer number, the right side will be a vertical line instead of just a turning point. In that case, the smaller, most right blue loop will be situated at the right of that line.
10 minutes / 1 minute = 10 -> 10 / 2 = 5 parts
5 minutes / 1 minute = 5 -> 5 / 2 = 2.5 parts
🔶 SETTINGS
🔹 Timeframes
Lower Timeframe 1
Lower Timeframe 2
No need to worry about the order of both timeframes; BTF will be the lowest TF of the 2, LTF the highest; both have to be lower than the main chart TF (CTF); otherwise, it will result in the error: "`Lower Timeframes` should be lower than current chart timeframe".
The ratio LTF / BTF should be equal or higher than 2; otherwise, this error will show: "`Lower Timeframe` should minimally be twice the `Base (smallest) Timeframe`"
Lastly, the ratio CTF / BTF should be lower than 500; otherwise, this error will pop up: "`Current Chart timeframe` / `Lower Timeframe` should be less than 500."
I have tried to capture runtime errors as best I could. If one should be triggered (red exclamation mark next to the title), it is best to increase the lowest TF.
🔹 Options
Show Lowest TF: Show BTF progression.
Loop Lowest TF: Enabling will let the BTF line return halfway.
Show Mini-Candles
Show Steps
"Show Steps" can be useful to see how the script works, where the location of the current price is compared against the position of the left (L) and right (R) labels:
🔹 Style
MTF RSI MA System + Adaptive BandsMTF RSI MA System + Adaptive Bands
Overview
MTF RSI MA System + Adaptive Bands is a highly customizable Pine Script indicator for traders seeking a versatile tool for multi-timeframe (MTF) analysis. Unlike traditional RSI, it focuses on the Moving Average of RSI (RSI MA), delivering smoother and more flexible trading signals. The main screenshot displays the indicator in two panels to showcase its diverse capabilities.
Important: Timeframes do not adjust automatically – users must manually set them to match the chart’s timeframe.
Features
Core Component: Built around RSI MA, not raw RSI, for smoother trend signals.
Multi-Timeframe: Analyze RSI MA across three customizable timeframes (default: 4H, 8H, 12H).
Adaptive Bands: Three band calculation methods (Fixed, Percent, StdDev) for dynamic signals.
Flexible Signals: Generated via RSI MA crossovers, band interactions, or directional alignment across timeframes.
Background Coloring: Highlights when RSI MAs across timeframes move in the same direction, aiding trend confirmation.
Screenshot Panels Configuration
Upper Panel: Shows RSI, RSI MA, and fixed bands for reversal strategies (RSI crossing bands).
Lower Panel: Displays three RSI MAs (Alligator-style) for trend-following, with background coloring for directional alignment.
Band Calculation Methods
The indicator offers three ways to calculate bands around RSI MA, each with unique characteristics:
Fixed Bands
Set at a fixed point value (default: 10) above and below RSI MA.
Example: If RSI MA = 50, band value = 10 → upper band = 60, lower = 40.
Use Case: Best for stable markets or fixed-range preferences.
Tip: Adjust the band value to widen or narrow the range based on asset volatility.
Percent Bands
Calculated as a percentage of RSI MA (default: 10%).
Example: If RSI MA = 50, band value = 10% → upper band = 55, lower = 45.
Use Case: Ideal for assets with varying volatility, as bands scale with RSI MA.
Tip: Experiment with percentage values to match typical price swings.
Standard Deviation Bands (StdDev)
Based on RSI’s standard deviation over the MA period, multiplied by a user-defined factor (default: 10).
Example: If RSI MA = 50, standard deviation = 5, factor = 2 → upper band = 60, lower = 40.
Important: The default value (10) may produce wide bands. Reduce to 1–2 for tighter, practical bands.
Use Case: Best for dynamic markets with fluctuating volatility.
Configuration Options
RSI Length: Set RSI calculation period (default: 20).
MA Length: Set RSI MA period (default: 20).
MA Type: Choose SMA or EMA for RSI MA (default: EMA).
Timeframes: Configure three timeframes (default: 4H, 8H, 12H) for MTF analysis.
Overbought/Oversold Levels: Optionally display fixed levels (default: 70/30).
Background Coloring: Enable/disable for each timeframe to highlight directional alignment.
How to Use
Add Indicator: Load it onto your TradingView chart.
Setup:
Reversals: Configure like the upper panel (RSI, RSI MA, bands) and watch for RSI crossing bands.
Trends: Configure like the lower panel (three RSI MAs) and look for fastest MA crossovers and background coloring.
Adjust Timeframes: Manually set tf1, tf2, tf3 (e.g., 1H, 2H, 4H on a 1H chart) to suit your strategy.
Adjust Bands: Choose band type (Fixed, Percent, StdDev) and value. For StdDev, reduce to 1–2 for tighter bands.
Experiment: Test settings to match your trading style, whether scalping, swing trading, or long-term.
Notes
Timeframes: Always match tf1, tf2, tf3 to your chart’s needs, as they don’t auto-adjust.
StdDev Bands: Lower the default value (10) to avoid overly wide bands.
Versatility: Works across markets (stocks, forex, crypto).
Golden Key: Opening Channel DashboardGolden Key: Opening Channel Dashboard
Complementary to the original Golden Key – The Frequency
Upgrade of 10 Monday's 1H Avg Range + 30-Day Daily Range
This indicator provides a structured dashboard to monitor the opening channel range and related metrics on 15m and 5m charts. Built to work alongside the Golden Key methodology, it focuses on pip precision, average volatility, and SL sizing.
What It Does
Detects first 4 candles of the session:
15m chart → first 4 Monday candles (1 hour)
5m chart → first 4 candles of each day (20 minutes)
Calculates pip range of the opening move
Stores and averages the last 10 such ranges
Calculates daily range average over 10 or 30 days
Generates SL size based on your multiplier setting
Auto-adjusts for FX, JPY, and XAUUSD pip sizes
Displays all values in a clean table in the top-right
How to Use It
Add to a 15m or 5m chart
Compare the current opening range to the average
Use the daily average to assess broader volatility
Define SL size using the opening range x multiplier
Customize display colors per table row
About This Script
This is not a visual box-style indicator. It is designed to complement the original “Golden Key – The Frequency” by focusing on metric output. It is also an upgraded version of the earlier "10 Monday’s 1H Avg Range" script, now supporting multi-timeframe logic and additional customization.
Disclaimer
This is a technical analysis tool. It does not provide trading advice. Use it in combination with your own research and strategy.
Codigo Trading 1.0📌Codigo Trading 1.0
This indicator strategically combines SuperTrend, multiple Exponential Moving Averages (EMAs), the Relative Strength Index (RSI), and the Average True Range (ATR) to offer clear entry and exit signals, as well as an in-depth view of market trends. Ideal for traders looking to optimize their operations with an all-in-one tool.
🔩How the Indicator Works:
This indicator relies on the interaction and confirmation of several key components to generate signals:
SuperTrend: Determines the primary trend direction. An uptrend SuperTrend signal (green line) indicates an upward trend, while a downtrend (red line) signals a downward trend. It also serves as a guide for setting Stop Loss and Take Profit levels.
EMAs: Includes EMAs of 10, 20, 55, 100, 200, and 325 periods. The relationship between the EMA 10 and EMA 20 is fundamental for confirming the strength and direction of movements. An EMA 10 above the EMA 20 suggests an uptrend, and vice versa. Longer EMAs act as dynamic support and resistance levels, offering a broader view of the market structure.
RSI: Used to identify overbought (RSI > 70/80) and oversold (RSI < 30/20) conditions, generating "Take Profit" alerts for potential trade closures.
ATR: Monitors market volatility to help you manage exits. ATR exit signals are triggered when volatility changes direction, indicating a possible exhaustion of the movement.
🗒️Entry and Exit Signals:
I designed specific alerts based on all the indicators I use in conjunction:
Long Entries: When SuperTrend is bullish and EMA 10 crosses above EMA 20.
Short Entries: When SuperTrend is bearish and EMA 10 crosses below EMA 20.
RSI Exits (Take Profit): Indicated by "TP" labels on the chart, when the RSI reaches extreme levels (overbought for longs, oversold for shorts).
EMA 20 Exits: When the price closes below EMA 20 (for longs) or above EMA 20 (for shorts).
ATR Exits: When the ATR changes direction, signaling a possible decrease in momentum.
📌Key Benefits:
Clarity in Trend: Quickly identifies market direction with SuperTrend and EMA alignment.
Strategic Entry and Exit Signals: Receive timely alerts to optimize your entry and exit points.
Assisted Trade Management: RSI and ATR help you consider when to take profits or exit a position.
Intuitive Visualization: Arrows, labels, and colored lines make analysis easy to interpret.
Disclaimer:
Trading in financial markets carries significant risks. This indicator is an analysis tool and should not be considered financial advice. Always conduct your own research and trade at your own risk.
Ergodic Market Divergence (EMD)Ergodic Market Divergence (EMD)
Bridging Statistical Physics and Market Dynamics Through Ensemble Analysis
The Revolutionary Concept: When Physics Meets Trading
After months of research into ergodic theory—a fundamental principle in statistical mechanics—I've developed a trading system that identifies when markets transition between predictable and unpredictable states. This indicator doesn't just follow price; it analyzes whether current market behavior will persist or revert, giving traders a scientific edge in timing entries and exits.
The Core Innovation: Ergodic Theory Applied to Markets
What Makes Markets Ergodic or Non-Ergodic?
In statistical physics, ergodicity determines whether a system's future resembles its past. Applied to trading:
Ergodic Markets (Mean-Reverting)
- Time averages equal ensemble averages
- Historical patterns repeat reliably
- Price oscillates around equilibrium
- Traditional indicators work well
Non-Ergodic Markets (Trending)
- Path dependency dominates
- History doesn't predict future
- Price creates new equilibrium levels
- Momentum strategies excel
The Mathematical Framework
The Ergodic Score combines three critical divergences:
Ergodic Score = (Price Divergence × Market Stress + Return Divergence × 1000 + Volatility Divergence × 50) / 3
Where:
Price Divergence: How far current price deviates from market consensus
Return Divergence: Momentum differential between instrument and market
Volatility Divergence: Volatility regime misalignment
Market Stress: Adaptive multiplier based on current conditions
The Ensemble Analysis Revolution
Beyond Single-Instrument Analysis
Traditional indicators analyze one chart in isolation. EMD monitors multiple correlated markets simultaneously (SPY, QQQ, IWM, DIA) to detect systemic regime changes. This ensemble approach:
Reveals Hidden Divergences: Individual stocks may diverge from market consensus before major moves
Filters False Signals: Requires broader market confirmation
Identifies Regime Shifts: Detects when entire market structure changes
Provides Context: Shows if moves are isolated or systemic
Dynamic Threshold Adaptation
Unlike fixed-threshold systems, EMD's boundaries evolve with market conditions:
Base Threshold = SMA(Ergodic Score, Lookback × 3)
Adaptive Component = StDev(Ergodic Score, Lookback × 2) × Sensitivity
Final Threshold = Smoothed(Base + Adaptive)
This creates context-aware signals that remain effective across different market environments.
The Confidence Engine: Know Your Signal Quality
Multi-Factor Confidence Scoring
Every signal receives a confidence score based on:
Signal Clarity (0-35%): How decisively the ergodic threshold is crossed
Momentum Strength (0-25%): Rate of ergodic change
Volatility Alignment (0-20%): Whether volatility supports the signal
Market Quality (0-20%): Price convergence and path dependency factors
Real-Time Confidence Updates
The Live Confidence metric continuously updates, showing:
- Current opportunity quality
- Market state clarity
- Historical performance influence
- Signal recency boost
- Visual Intelligence System
Adaptive Ergodic Field Bands
Dynamic bands that expand and contract based on market state:
Primary Color: Ergodic state (mean-reverting)
Danger Color: Non-ergodic state (trending)
Band Width: Expected price movement range
Squeeze Indicators: Volatility compression warnings
Quantum Wave Ribbons
Triple EMA system (8, 21, 55) revealing market flow:
Compressed Ribbons: Consolidation imminent
Expanding Ribbons: Directional move developing
Color Coding: Matches current ergodic state
Phase Transition Signals
Clear entry/exit markers at regime changes:
Bull Signals: Ergodic restoration (mean reversion opportunity)
Bear Signals: Ergodic break (trend following opportunity)
Confidence Labels: Percentage showing signal quality
Visual Intensity: Stronger signals = deeper colors
Professional Dashboard Suite
Main Analytics Panel (Top Right)
Market State Monitor
- Current regime (Ergodic/Non-Ergodic)
- Ergodic score with threshold
- Path dependency strength
- Quantum coherence percentage
Divergence Metrics
- Price divergence with severity
- Volatility regime classification
- Strategy mode recommendation
- Signal strength indicator
Live Intelligence
- Real-time confidence score
- Color-coded risk levels
- Dynamic strategy suggestions
Performance Tracking (Left Panel)
Signal Analytics
- Total historical signals
- Win rate with W/L breakdown
- Current streak tracking
- Closed trade counter
Regime Analysis
- Current market behavior
- Bars since last signal
- Recommended actions
- Average confidence trends
Strategy Command Center (Bottom Right)
Adaptive Recommendations
- Active strategy mode
- Primary approach (mean reversion/momentum)
- Suggested indicators ("weapons")
- Entry/exit methodology
- Risk management guidance
- Comprehensive Input Guide
Core Algorithm Parameters
Analysis Period (10-100 bars)
Scalping (10-15): Ultra-responsive, more signals, higher noise
Day Trading (20-30): Balanced sensitivity and stability
Swing Trading (40-100): Smooth signals, major moves only Default: 20 - optimal for most timeframes
Divergence Threshold (0.5-5.0)
Hair Trigger (0.5-1.0): Catches every wiggle, many false signals
Balanced (1.5-2.5): Good signal-to-noise ratio
Conservative (3.0-5.0): Only extreme divergences Default: 1.5 - best risk/reward balance
Path Memory (20-200 bars)
Short Memory (20-50): Recent behavior focus, quick adaptation
Medium Memory (50-100): Balanced historical context
Long Memory (100-200): Emphasizes established patterns Default: 50 - captures sufficient history without lag
Signal Spacing (5-50 bars)
Aggressive (5-10): Allows rapid-fire signals
Normal (15-25): Prevents clustering, maintains flow
Conservative (30-50): Major setups only Default: 15 - optimal trade frequency
Ensemble Configuration
Select markets for consensus analysis:
SPY: Broad market sentiment
QQQ: Technology leadership
IWM: Small-cap risk appetite
DIA: Blue-chip stability
More instruments = stronger consensus but potentially diluted signals
Visual Customization
Color Themes (6 professional options):
Quantum: Cyan/Pink - Modern trading aesthetic
Matrix: Green/Red - Classic terminal look
Heat: Blue/Red - Temperature metaphor
Neon: Cyan/Magenta - High contrast
Ocean: Turquoise/Coral - Calming palette
Sunset: Red-orange/Teal - Warm gradients
Display Controls:
- Toggle each visual component
- Adjust transparency levels
- Scale dashboard text
- Show/hide confidence scores
- Trading Strategies by Market State
- Ergodic State Strategy (Primary Color Bands)
Market Characteristics
- Price oscillates predictably
- Support/resistance hold
- Volume patterns repeat
- Mean reversion dominates
Optimal Approach
Entry: Fade moves at band extremes
Target: Middle band (equilibrium)
Stop: Just beyond outer bands
Size: Full confidence-based position
Recommended Tools
- RSI for oversold/overbought
- Bollinger Bands for extremes
- Volume profile for levels
- Non-Ergodic State Strategy (Danger Color Bands)
Market Characteristics
- Price trends persistently
- Levels break decisively
- Volume confirms direction
- Momentum accelerates
Optimal Approach
Entry: Breakout from bands
Target: Trail with expanding bands
Stop: Inside opposite band
Size: Scale in with trend
Recommended Tools
- Moving average alignment
- ADX for trend strength
- MACD for momentum
- Advanced Features Explained
Quantum Coherence Metric
Measures phase alignment between individual and ensemble behavior:
80-100%: Perfect sync - strong mean reversion setup
50-80%: Moderate alignment - mixed signals
0-50%: Decoherence - trending behavior likely
Path Dependency Analysis
Quantifies how much history influences current price:
Low (<30%): Technical patterns reliable
Medium (30-50%): Mixed influences
High (>50%): Fundamental shift occurring
Volatility Regime Classification
Contextualizes current volatility:
Normal: Standard strategies apply
Elevated: Widen stops, reduce size
Extreme: Defensive mode required
Signal Strength Indicator
Real-time opportunity quality:
- Distance from threshold
- Momentum acceleration
- Cross-validation factors
Risk Management Framework
Position Sizing by Confidence
90%+ confidence = 100% position size
70-90% confidence = 75% position size
50-70% confidence = 50% position size
<50% confidence = 25% or skip
Dynamic Stop Placement
Ergodic State: ATR × 1.0 from entry
Non-Ergodic State: ATR × 2.0 from entry
Volatility Adjustment: Multiply by current regime
Multi-Timeframe Alignment
- Check higher timeframe regime
- Confirm ensemble consensus
- Verify volume participation
- Align with major levels
What Makes EMD Unique
Original Contributions
First Ergodic Theory Trading Application: Transforms abstract physics into practical signals
Ensemble Market Analysis: Revolutionary multi-market divergence system
Adaptive Confidence Engine: Institutional-grade signal quality metrics
Quantum Coherence: Novel market alignment measurement
Smart Signal Management: Prevents clustering while maintaining responsiveness
Technical Innovations
Dynamic Threshold Adaptation: Self-adjusting sensitivity
Path Memory Integration: Historical dependency weighting
Stress-Adjusted Scoring: Market condition normalization
Real-Time Performance Tracking: Built-in strategy analytics
Optimization Guidelines
By Timeframe
Scalping (1-5 min)
Period: 10-15
Threshold: 0.5-1.0
Memory: 20-30
Spacing: 5-10
Day Trading (5-60 min)
Period: 20-30
Threshold: 1.5-2.5
Memory: 40-60
Spacing: 15-20
Swing Trading (1H-1D)
Period: 40-60
Threshold: 2.0-3.0
Memory: 80-120
Spacing: 25-35
Position Trading (1D-1W)
Period: 60-100
Threshold: 3.0-5.0
Memory: 100-200
Spacing: 40-50
By Market Condition
Trending Markets
- Increase threshold
- Extend memory
- Focus on breaks
Ranging Markets
- Decrease threshold
- Shorten memory
- Focus on restores
Volatile Markets
- Increase spacing
- Raise confidence requirement
- Reduce position size
- Integration with Other Analysis
- Complementary Indicators
For Ergodic States
- RSI divergences
- Bollinger Band squeezes
- Volume profile nodes
- Support/resistance levels
For Non-Ergodic States
- Moving average ribbons
- Trend strength indicators
- Momentum oscillators
- Breakout patterns
- Fundamental Alignment
- Check economic calendar
- Monitor sector rotation
- Consider market themes
- Evaluate risk sentiment
Troubleshooting Guide
Too Many Signals:
- Increase threshold
- Extend signal spacing
- Raise confidence minimum
Missing Opportunities
- Decrease threshold
- Reduce signal spacing
- Check ensemble settings
Poor Win Rate
- Verify timeframe alignment
- Confirm volume participation
- Review risk management
Disclaimer
This indicator is for educational and informational purposes only. It does not constitute financial advice. Trading involves substantial risk of loss and is not suitable for all investors. Past performance does not guarantee future results.
The ergodic framework provides unique market insights but cannot predict future price movements with certainty. Always use proper risk management, conduct your own analysis, and never risk more than you can afford to lose.
This tool should complement, not replace, comprehensive trading strategies and sound judgment. Markets remain inherently unpredictable despite advanced analysis techniques.
Transform market chaos into trading clarity with Ergodic Market Divergence.
Created with passion for the TradingView community
Trade with insight. Trade with anticipation.
— Dskyz , for DAFE Trading Systems
Lyapunov Market Instability (LMI)Lyapunov Market Instability (LMI)
What is Lyapunov Market Instability?
Lyapunov Market Instability (LMI) is a revolutionary indicator that brings chaos theory from theoretical physics into practical trading. By calculating Lyapunov exponents—a measure of how rapidly nearby trajectories diverge in phase space—LMI quantifies market sensitivity to initial conditions. This isn't another oscillator or trend indicator; it's a mathematical lens that reveals whether markets are in chaotic (trending) or stable (ranging) regimes.
Inspired by the meditative color field paintings of Mark Rothko, this indicator transforms complex chaos mathematics into an intuitive visual experience. The elegant simplicity of the visualization belies the sophisticated theory underneath—just as Rothko's seemingly simple color blocks contain profound depth.
Theoretical Foundation (Chaos Theory & Lyapunov Exponents)
In dynamical systems, the Lyapunov exponent (λ) measures the rate of separation of infinitesimally close trajectories:
λ > 0: System is chaotic—small changes lead to dramatically different outcomes (butterfly effect)
λ < 0: System is stable—trajectories converge, perturbations die out
λ ≈ 0: Edge of chaos—transition between regimes
Phase Space Reconstruction
Using Takens' embedding theorem , we reconstruct market dynamics in higher dimensions:
Time-delay embedding: Create vectors from price at different lags
Nearest neighbor search: Find historically similar market states
Trajectory evolution: Track how these similar states diverged over time
Divergence rate: Calculate average exponential separation
Market Application
Chaotic markets (λ > threshold): Strong trends emerge, momentum dominates, use breakout strategies
Stable markets (λ < threshold): Mean reversion dominates, fade extremes, range-bound strategies work
Transition zones: Market regime about to change, reduce position size, wait for confirmation
How LMI Works
1. Phase Space Construction
Each point in time is embedded as a vector using historical prices at specific delays (τ). This reveals the market's hidden attractor structure.
2. Lyapunov Calculation
For each current state, we:
- Find similar historical states within epsilon (ε) distance
- Track how these initially similar states evolved
- Measure exponential divergence rate
- Average across multiple trajectories for robustness
3. Signal Generation
Chaos signals: When λ crosses above threshold, market enters trending regime
Stability signals: When λ crosses below threshold, market enters ranging regime
Divergence detection: Price/Lyapunov divergences signal potential reversals
4. Rothko Visualization
Color fields: Background zones represent market states with Rothko-inspired palettes
Glowing line: Lyapunov exponent with intensity reflecting market state
Minimalist design: Focus on essential information without clutter
Inputs:
📐 Lyapunov Parameters
Embedding Dimension (default: 3)
Dimensions for phase space reconstruction
2-3: Simple dynamics (crypto/forex) - captures basic momentum patterns
4-5: Complex dynamics (stocks/indices) - captures intricate market structures
Higher dimensions need exponentially more data but reveal deeper patterns
Time Delay τ (default: 1)
Lag between phase space coordinates
1: High-frequency (1m-15m charts) - captures rapid market shifts
2-3: Medium frequency (1H-4H) - balances noise and signal
4-5: Low frequency (Daily+) - focuses on major regime changes
Match to your timeframe's natural cycle
Initial Separation ε (default: 0.001)
Neighborhood size for finding similar states
0.0001-0.0005: Highly liquid markets (major forex pairs)
0.0005-0.002: Normal markets (large-cap stocks)
0.002-0.01: Volatile markets (crypto, small-caps)
Smaller = more sensitive to chaos onset
Evolution Steps (default: 10)
How far to track trajectory divergence
5-10: Fast signals for scalping - quick regime detection
10-20: Balanced for day trading - reliable signals
20-30: Slow signals for swing trading - major regime shifts only
Nearest Neighbors (default: 5)
Phase space points for averaging
3-4: Noisy/fast markets - adapts quickly
5-6: Balanced (recommended) - smooth yet responsive
7-10: Smooth/slow markets - very stable signals
📊 Signal Parameters
Chaos Threshold (default: 0.05)
Lyapunov value above which market is chaotic
0.01-0.03: Sensitive - more chaos signals, earlier detection
0.05: Balanced - optimal for most markets
0.1-0.2: Conservative - only strong trends trigger
Stability Threshold (default: -0.05)
Lyapunov value below which market is stable
-0.01 to -0.03: Sensitive - quick stability detection
-0.05: Balanced - reliable ranging signals
-0.1 to -0.2: Conservative - only deep stability
Signal Smoothing (default: 3)
EMA period for noise reduction
1-2: Raw signals for experienced traders
3-5: Balanced - recommended for most
6-10: Very smooth for position traders
🎨 Rothko Visualization
Rothko Classic: Deep reds for chaos, midnight blues for stability
Orange/Red: Warm sunset tones throughout
Blue/Black: Cool, meditative ocean depths
Purple/Grey: Subtle, sophisticated palette
Visual Options:
Market Zones : Background fields showing regime areas
Transitions: Arrows marking regime changes
Divergences: Labels for price/Lyapunov divergences
Dashboard: Real-time state and trading signals
Guide: Educational panel explaining the theory
Visual Logic & Interpretation
Main Elements
Lyapunov Line: The heart of the indicator
Above chaos threshold: Market is trending, follow momentum
Below stability threshold: Market is ranging, fade extremes
Between thresholds: Transition zone, reduce risk
Background Zones: Rothko-inspired color fields
Red zone: Chaotic regime (trending)
Gray zone: Transition (uncertain)
Blue zone: Stable regime (ranging)
Transition Markers:
Up triangle: Entering chaos - start trend following
Down triangle: Entering stability - start mean reversion
Divergence Signals:
Bullish: Price makes low but Lyapunov rising (stability breaking down)
Bearish: Price makes high but Lyapunov falling (chaos dissipating)
Dashboard Information
Market State: Current regime (Chaotic/Stable/Transitioning)
Trading Bias: Specific strategy recommendation
Lyapunov λ: Raw value for precision
Signal Strength: Confidence in current regime
Last Change: Bars since last regime shift
Action: Clear trading directive
Trading Strategies
In Chaotic Regime (λ > threshold)
Follow trends aggressively: Breakouts have high success rate
Use momentum strategies: Moving average crossovers work well
Wider stops: Expect larger swings
Pyramid into winners: Trends tend to persist
In Stable Regime (λ < threshold)
Fade extremes: Mean reversion dominates
Use oscillators: RSI, Stochastic work well
Tighter stops: Smaller expected moves
Scale out at targets: Trends don't persist
In Transition Zone
Reduce position size: Uncertainty is high
Wait for confirmation: Let regime establish
Use options: Volatility strategies may work
Monitor closely: Quick changes possible
Advanced Techniques
- Multi-Timeframe Analysis
- Higher timeframe LMI for regime context
- Lower timeframe for entry timing
- Alignment = highest probability trades
- Divergence Trading
- Most powerful at regime boundaries
- Combine with support/resistance
- Use for early reversal detection
- Volatility Correlation
- Chaos often precedes volatility expansion
- Stability often precedes volatility contraction
- Use for options strategies
Originality & Innovation
LMI represents a genuine breakthrough in applying chaos theory to markets:
True Lyapunov Calculation: Not a simplified proxy but actual phase space reconstruction and divergence measurement
Rothko Aesthetic: Transforms complex math into meditative visual experience
Regime Detection: Identifies market state changes before price makes them obvious
Practical Application: Clear, actionable signals from theoretical physics
This is not a combination of existing indicators or a visual makeover of standard tools. It's a fundamental rethinking of how we measure and visualize market dynamics.
Best Practices
Start with defaults: Parameters are optimized for broad market conditions
Match to your timeframe: Adjust tau and evolution steps
Confirm with price action: LMI shows regime, not direction
Use appropriate strategies: Chaos = trend, Stability = reversion
Respect transitions: Reduce risk during regime changes
Alerts Available
Chaos Entry: Market entering chaotic regime - prepare for trends
Stability Entry: Market entering stable regime - prepare for ranges
Bullish Divergence: Potential bottom forming
Bearish Divergence: Potential top forming
Chart Information
Script Name: Lyapunov Market Instability (LMI) Recommended Use: All markets, all timeframes Best Performance: Liquid markets with clear regimes
Academic References
Takens, F. (1981). "Detecting strange attractors in turbulence"
Wolf, A. et al. (1985). "Determining Lyapunov exponents from a time series"
Rosenstein, M. et al. (1993). "A practical method for calculating largest Lyapunov exponents"
Note: After completing this indicator, I discovered @loxx's 2022 "Lyapunov Hodrick-Prescott Oscillator w/ DSL". While both explore Lyapunov exponents, they represent independent implementations with different methodologies and applications. This indicator uses phase space reconstruction for regime detection, while his combines Lyapunov concepts with HP filtering.
Disclaimer
This indicator is for research and educational purposes only. It does not constitute financial advice or provide direct buy/sell signals. Chaos theory reveals market character, not future prices. Always use proper risk management and combine with your own analysis. Past performance does not guarantee future results.
See markets through the lens of chaos. Trade the regime, not the noise.
Bringing theoretical physics to practical trading through the meditative aesthetics of Mark Rothko
Trade with insight. Trade with anticipation.
— Dskyz , for DAFE Trading Systems
ETI IndicatorThe Ensemble Technical Indicator (ETI) is a script that combines multiple established indicators into one single powerful indicator. Specifically, it takes a number of technical indicators and then converts them into +1 to represent a bullish trend, or a -1 to represent a bearish trend. It then adds these values together and takes the running sum over the past 20 days.
The ETI is composed of the following indicators and converted to +1 or -1 using the following criteria:
Simple Moving Average (10 days) : When the price is above the 10-day simple moving averaging, +1, when below -1
Weighted Moving Average (10 days) : Similar to the SMA 10, when the the price is above the 10-day weighted moving average, +1, when below -1
Stochastic K% : If the current Stochastic K% is greater than the previous value, then +1, else -1.
Stochastic D% : Similar to the Stochastic K%, when the current Stochastic D% is greater than the previous value, +1, else -1.
MACD Difference : First subtract the MACD signal (i.e. the moving average) from the MACD value and if the current value is higher than the previous value, then +1, else -1.
William's R% : If the current William's R% is greater than the previous one, then +1, else -1.
William's Accumulation/Distribution : If the current William's AD value is greater than the previous value, then +1, else -1.
Commodity Channel Index : If the Commodity Channel Index is greater than 200 (overbought), then -1, if it is less than -200 (oversold) then +1. When it is between those values, if the current value is greater than the previous value then +1, else -1.
Relative Strength Index : If the Relative Strength Index is over 70 (overbought) then -1 and if under 30 (oversold) then +1. If the Relative Strength Indicator is between those values then if the current value is higher than the previous value +1, else -1.
Momentum (9 days) : If the momentum value is greater than 0, then +1, else -1.
Again, once these values have been calculated and converted, they are added up to produce a single value. This single value is then summed across the previous 20 candles to produce a running sum.
By coalescing multiple technical indicators into a single value across time, traders can better understand how multiple inter-related indicators are behaving at once; high scores indicate that numerous indicators are showing bullish signals indicating a potential or ongoing uptrend (and vice-versa with low scores).
Additional Features
Numerous smoothing transformations have also been added (e.g. gaussian smoothing) to remove some of the noise might exist.
Suggested Use
It is recommended that stocks are shorted when the cross below 0, and are bought when the ETI crosses above -40. Arrows can be shown on the indicator to show these points. However feel free to use levels that work best for you.
Traditionally, I have treated values above +50 as overbought and below -40 as undersold (with -80 indicating extremely oversold); however these levels could also indicate either upwards and downwards momentum so taking a position based on where the ETI is (rather than crossing levels) should be done with caution.
ICT Macro Zone Boxes w/ Individual H/L Tracking v3.1ICT Macro Zones (Grey Box Version
This indicator dynamically highlights key intraday time-based macro sessions using a clean, minimalistic grey box overlay, helping traders align with institutional trading cycles. Inspired by ICT (Inner Circle Trader) concepts, it tracks real-time highs and lows for each session and optionally extends the zone box after the session ends — making it a precision tool for intraday setups, order flow analysis, and macro-level liquidity sweeps.
### 🔍 **What It Does**
- Plots **six predefined macro sessions** used in Smart Money Concepts:
- AM Macro (09:50–10:10)
- London Close (10:50–11:10)
- Lunch Macro (11:30–13:30)
- PM Macro (14:50–15:10)
- London SB (03:00–04:00)
- PM SB (15:00–16:00)
- Each zone:
- **Tracks high and low dynamically** throughout the session.
- **Draws a consistent grey shaded box** to visualize price boundaries.
- **Displays a label** at the first bar of the session (optional).
- **Optionally extends** the box to the right after the session closes.
### 🧠 **How It Works**
- Uses Pine Script arrays to define each session’s time window, label, and color.
- Detects session entry using `time()` within a New York timezone context.
- High/Low values are updated per bar inside the session window.
- Once a session ends, the box is optionally closed and fixed in place.
- All visual zones use a standardized grey tone for clarity and consistency across charts.
### 🛠️ **Settings**
- **Shade Zone High→Low:** Enable/disable the grey macro box.
- **Extend Box After Session:** Keep the zone visible after it ends.
- **Show Entry Label:** Display a label at the start of each session.
### 🎯 **Why This Script is Unique**
Unlike basic session markers or colored backgrounds, this tool:
- Focuses on **macro moments of liquidity and reversal**, not just open/close times.
- Uses **per-session logic** to individually track price behavior inside key time windows.
- Supports **real-time high/low tracking and clean zone drawing**, ideal for Smart Money and ICT-style strategies.
Perfect — based on your list, here's a **bundle-style description** that not only explains the function of each script but also shows how they **work together** in a Smart Money/ICT workflow. This kind of cross-script explanation is exactly what TradingView wants to see to justify closed-source mashups or interdependent tools.
---
📚 ICT SMC Toolkit — Script Integration Guide
This set of advanced Smart Money Concept (SMC) tools is designed for traders who follow ICT-based methodologies, combining liquidity theory, time-based precision, and engineered confluences for high-probability trades. Each indicator is optimized to work both independently and synergistically, forming a comprehensive trading framework.
---
First FVG Custom Time Range
**Purpose:**
Plots the **first Fair Value Gap (FVG)** that appears within a defined session (e.g., NY Kill Zone, Custom range). Includes optional retest alerts.
**Best Used With:**
- Use with **ICT Macro Zones (Grey Box Version)** to isolate FVGs during high-probability times like AM Macro or PM SB.
- Combine with **Liquidity Levels** to assess whether FVGs form near swing points or liquidity voids.
---
ICT SMC Liquidity Grabs and OB s
**Purpose:**
Detects **liquidity grabs** (stop hunts above/below swing highs/lows) and **bullish/bearish order blocks**. Includes optional Fibonacci OTE levels for sniper entries.
**Best Used With:**
- Use with **ICT Turtle Soup (Reversal)** for confirmation after a liquidity grab.
- Combine with **Macro Zones** to catch order blocks forming inside timed macro windows.
- Match with **Smart Swing Levels** to confirm structure breaks before entry.
ICT SMC Liquidity Levels (Smart Swing Lows)
**Purpose:**
Automatically marks swing highs/lows based on user-defined lookbacks. Tracks whether those levels have been breached or respected.
**Best Used With:**
- Combine with **Turtle Soup** to detect if a swing level was swept, then reversed.
- Use with **Liquidity Grabs** to confirm a grab occurred at a meaningful structural point.
- Align with **Macro Zones** to understand when liquidity events occur within macro session timing.
ICT Turtle Soup (Liquidity Reversal)
**Purpose:**
Implements the classic ICT Turtle Soup model. Looks for swing failure and quick reversals after a liquidity sweep — ideal for catching traps.
Best Used With:
- Confirm with **Liquidity Grabs + OBs** to identify institutional activity at the reversal point.
- Use **Liquidity Levels** to ensure the reversal is happening at valid previous swing highs/lows.
- Amplify probability when pattern appears during **Macro Zones** or near the **First FVG**.
ICT Turtle Soup Ultimate V2
**Purpose:**
An enhanced, multi-layer version of the Turtle Soup setup that includes built-in liquidity checks, OTE levels, structure validation, and customizable visual output.
**Best Used With:**
- Use as an **entry signal generator** when other indicators (e.g., OBs, liquidity grabs) are aligned.
- Pair with **Macro Zones** for high-precision timing.
- Combine with **First FVG** to anticipate price rebalancing before explosive moves.
---
## 🧠 Workflow Example:
1. **Start with Macro Zones** to focus only on institutional trading windows.
2. Look for **Liquidity Grabs or Swing Sweeps** around key highs/lows.
3. Check for a **Turtle Soup Reversal** or **Order Block Reaction** near that level.
4. Confirm confluence with a **Fair Value Gap**.
5. Execute using the **OTE level** from the Liquidity Grabs + OB script.
---
Let me know which script you want to publish first — I’ll tailor its **individual TradingView description** and flag its ideal **“Best Used With” partners** to help users see the value in your ecosystem.