Delta Volume Columns Pro [LucF]█ OVERVIEW
This indicator displays volume delta information calculated with intrabar inspection on historical bars, and feed updates when running in realtime. It is designed to run in a pane and can display either stacked buy/sell volume columns or a signal line which can be calculated and displayed in many different ways.
Five different models are offered to reveal different characteristics of the calculated volume delta information. Many options are offered to visualize the calculations, giving you much leeway in morphing the indicator's visuals to suit your needs. If you value delta volume information, I hope you will find the time required to master Delta Volume Columns Pro well worth the investment. I am confident that if you combine a proper understanding of the indicator's information with an intimate knowledge of the volume idiosyncrasies on the markets you trade, you can extract useful market intelligence using this tool.
█ WARNINGS
1. The indicator only works on markets where volume information is available,
Please validate that your symbol's feed carries volume information before asking me why the indicator doesn't plot values.
2. When you refresh your chart or re-execute the script on the chart, the indicator will repaint because elapsed realtime bars will then recalculate as historical bars.
3. Because the indicator uses different modes of calculation on historical and realtime bars, it's critical that you understand the differences between them. Details are provided further down.
4. Calculations using intrabar inspection on historical bars can only be done from some chart timeframes. See further down for a list of supported timeframes.
If the chart's timeframe is not supported, no historical volume delta will display.
█ CONCEPTS
Chart bars
Three different types of bars are used in charts:
1. Historical bars are bars that have already closed when the script executes on them.
2. The realtime bar is the current, incomplete bar where a script is running on an open market. There is only one active realtime bar on your chart at any given time.
The realtime bar is where alerts trigger.
3. Elapsed realtime bars are bars that were calculated when they were realtime bars but have since closed.
When a script re-executes on a chart because the browser tab is refreshed or some of its inputs are changed, elapsed realtime bars are recalculated as historical bars.
Why does this indicator use two modes of calculation?
Historical bars on TradingView charts contain OHLCV data only, which is insufficient to calculate volume delta on them with any level of precision. To mine more detailed information from those bars we look at intrabars , i.e., bars from a smaller timeframe (we call it the intrabar timeframe ) that are contained in one chart bar. If your chart Is running at 1D on a 24x7 market for example, most 1D chart bars will contain 24 underlying 1H bars in their dilation. On historical bars, this indicator looks at those intrabars to amass volume delta information. If the intrabar is up, its volume goes in the Buy bin, and inversely for the Sell bin. When price does not move on an intrabar, the polarity of the last known movement is used to determine in which bin its volume goes.
In realtime, we have access to price and volume change for each update of the chart. Because a 1D chart bar can be updated tens of thousands of times during the day, volume delta calculations on those updates is much more precise. This precision, however, comes at a price:
— The script must be running on the chart for it to keep calculating in realtime.
— If you refresh your chart you will lose all accumulated realtime calculations on elapsed realtime bars, and the realtime bar.
Elapsed realtime bars will recalculate as historical bars, i.e., using intrabar inspection, and the realtime bar's calculations will reset.
When the script recalculates elapsed realtime bars as historical bars, the values on those bars will change, which means the script repaints in those conditions.
— When the indicator first calculates on a chart containing an incomplete realtime bar, it will count ALL the existing volume on the bar as Buy or Sell volume,
depending on the polarity of the bar at that point. This will skew calculations for that first bar. Scripts have no access to the history of a realtime bar's previous updates,
and intrabar inspection cannot be used on realtime bars, so this is the only to go about this.
— Even if alerts only trigger upon confirmation of their conditions after the realtime bar closes, they are repainting alerts
because they would perhaps not have calculated the same way using intrabar inspection.
— On markets like stocks that often have different EOD and intraday feeds and volume information,
the volume's scale may not be the same for the realtime bar if your chart is at 1D, for example,
and the indicator is using an intraday timeframe to calculate on historical bars.
— Any chart timeframe can be used in realtime mode, but plots that include moving averages in their calculations may require many elapsed realtime bars before they can calculate.
You might prefer drastically reducing the periods of the moving averages, or using the volume columns mode, which displays instant values, instead of the line.
Volume Delta Balances
This indicator uses a variety of methods to evaluate five volume delta balances and derive other values from those balances. The five balances are:
1 — On Bar Balance : This is the only balance using instant values; it is simply the subtraction of the Sell volume from the Buy volume on the bar.
2 — Average Balance : Calculates a distinct EMA for both the Buy and Sell volumes, and subtracts the Sell EMA from the Buy EMA.
3 — Momentum Balance : Starts by calculating, separately for both Buy and Sell volumes, the difference between the same EMAs used in "Average Balance" and
an SMA of double the period used for the "Average Balance" EMAs. The difference for the Sell side is subtracted from the difference for the Buy side,
and an RSI of that value is calculated and brought over the −50/+50 scale.
4 — Relative Balance : The reference values used in the calculation are the Buy and Sell EMAs used in the "Average Balance".
From those, we calculate two intermediate values using how much the instant Buy and Sell volumes on the bar exceed their respective EMA — but with a twist.
If the bar's Buy volume does not exceed the EMA of Buy volume, a zero value is used. The same goes for the Sell volume with the EMA of Sell volume.
Once we have our two intermediate values for the Buy and Sell volumes exceeding their respective MA, we subtract them. The final "Relative Balance" value is an ALMA of that subtraction.
The rationale behind using zero values when the bar's Buy/Sell volume does not exceed its EMA is to only take into account the more significant volume.
If both instant volume values exceed their MA, then the difference between the two is the signal's value.
The signal is called "relative" because the intermediate values are the difference between the instant Buy/Sell volumes and their respective MA.
This balance flatlines when the bar's Buy/Sell volumes do not exceed their EMAs, which makes it useful to spot areas where trader interest dwindles, such as consolidations.
The smaller the period of the final value's ALMA, the more easily you will see the balance flatline. These flat zones should be considered no-trade zones.
5 — Percent Balance : This balance is the ALMA of the ratio of the "On Bar Balance" value, i.e., the volume delta balance on the bar (which can be positive or negative),
over the total volume for that bar.
From the balances and marker conditions, two more values are calculated:
1 — Marker Bias : It sums the up/down (+1/‒1) occurrences of the markers 1 to 4 over a period you define, so it ranges from −4 to +4, times the period.
Its calculation will depend on the modes used to calculate markers 3 and 4.
2 — Combined Balances : This is the sum of the bull/bear (+1/−1) states of each of the five balances, so it ranges from −5 to +5.
█ FEATURES
The indicator has two main modes of operation: Columns and Line .
Columns
• In Columns mode you can display stacked Buy/Sell volume columns.
• The buy section always appears above the centerline, the sell section below.
• The top and bottom sections can be colored independently using eight different methods.
• The EMAs of the Buy/Sell values can be displayed (these are the same EMAs used to calculate the "Average Balance").
Line
• Displays one of seven signals: the five balances or one of two complementary values, i.e., the "Marker Bias" or the "Combined Balances".
• You can color the line and its fill using independent calculation modes to pack more information in the display.
You can thus appraise the state of 3 different values using the line itself, its color and the color of its fill.
• A "Divergence Levels" feature will use the line to automatically draw expanding levels on divergence events.
Default settings
Using the indicator's default settings, this is the information displayed:
• The line is calculated on the "Average Balance".
• The line's color is determined by the bull/bear state of the "Percent Balance".
• The line's fill gradient is determined by the advances/declines of the "Momentum Balance".
• The orange divergence dots are calculated using discrepancies between the polarity of the "On Bar Balance" and the chart's bar.
• The divergence levels are determined using the line's level when a divergence occurs.
• The background's fill gradient is calculated on advances/declines of the "Marker Bias".
• The chart bars are colored using advances/declines of the "Relative Balance". Divergences are shown in orange.
• The intrabar timeframe is automatically determined from the chart's timeframe so that a minimum of 50 intrabars are used to calculate volume delta on historical bars.
Alerts
The configuration of the marker conditions explained further is what determines the conditions that will trigger alerts created from this script. Note that simply selecting the display of markers does not create alerts. To create an alert on this script, you must use ALT-A from the chart. You can create multiple alerts triggering on different conditions from this same script; simply configure the markers so they define the trigger conditions for each alert before creating the alert. The configuration of the script's inputs is saved with the alert, so from then on you can change them without affecting the alert. Alert messages will mention the marker(s) that triggered the specific alert event. Keep in mind, when creating alerts on small chart timeframes, that discrepancies between alert triggers and markers displayed on your chart are to be expected. This is because the alert and your chart are running two distinct instances of the indicator on different servers and different feeds. Also keep in mind that while alerts only trigger on confirmed conditions, they are calculated using realtime calculation mode, which entails that if you refresh your chart and elapsed realtime bars recalculate as historical bars using intrabar inspection, markers will not appear in the same places they appeared in realtime. So it's important to understand that even though the alert conditions are confirmed when they trigger, these alerts will repaint.
Let's go through the sections of the script's inputs.
Columns
The size of the Buy/Sell columns always represents their respective importance on the bar, but the coloring mode for tops and bottoms is independent. The default setup uses a standard coloring mode where the Buy/Sell columns are always in the bull/bear color with a higher intensity for the winning side. Seven other coloring modes allow you to pack more information in the columns. When choosing to color the top columns using a bull/bear gradient on "Average Balance", for example, you will have bull/bear colored tops. In order for the color of the bottom columns to continue to show the instant bar balance, you can then choose the "On Bar Balance — Dual Solid Colors" coloring mode to make those bars the color of the winning side for that bar. You can display the averages of the Buy and Sell columns. If you do, its coloring is controlled through the "Line" and "Line fill" sections below.
Line and Line fill
You can select the calculation mode and the thickness of the line, and independent calculations to determine the line's color and fill.
Zero Line
The zero line can display dots when all five balances are bull/bear.
Divergences
You first select the detection mode. Divergences occur whenever the up/down direction of the signal does not match the up/down polarity of the bar. Divergences are used in three components of the indicator's visuals: the orange dot, colored chart bars, and to calculate the divergence levels on the line. The divergence levels are dynamic levels that automatically build from the line's values on divergence events. On consecutive divergences, the levels will expand, creating a channel. This implementation of the divergence levels corresponds to my view that divergences indicate anomalies, hesitations, points of uncertainty if you will. It precludes any attempt to identify a directional bias to divergences. Accordingly, the levels merely take note of divergence events and mark those points in time with levels. Traders then have a reference point from which they can evaluate further movement. The bull/bear/neutral colors used to plot the levels are also congruent with this view in that they are determined by the line's position relative to the levels, which is how I think divergences can be put to the most effective use. One of the coloring modes for the line's fill uses advances/declines in the line after divergence events.
Background
The background can show a bull/bear gradient on six different calculations. As with other gradients, you can adjust its brightness to make its importance proportional to how you use it in your analysis.
Chart bars
Chart bars can be colored using seven different methods. You have the option of emptying the body of bars where volume does not increase, as does my TLD indicator, and you can choose whether you want to show divergences.
Intrabar Timeframe
This is the intrabar timeframe that will be used to calculate volume delta using intrabar inspection on historical bars. You can choose between four modes. The three "Auto-steps" modes calculate, from the chart's timeframe, the intrabar timeframe where the said number of intrabars will make up the dilation of chart bars. Adjustments are made for non-24x7 markets. "Fixed" mode allows you to select the intrabar timeframe you want. Checking the "Show TF" box will display in the lower-right corner the intrabar timeframe used at any given moment. The proper selection of the intrabar timeframe is important. It must achieve maximal granularity to produce precise results while not unduly slowing down calculations, or worse, causing runtime errors. Note that historical depth will vary with the intrabar timeframe. The smaller the timeframe, the shallower historical plots you will be.
Markers
Markers appear when the required condition has been confirmed on a closed bar. The configuration of the markers when you create an alert is what determines when the alert will trigger. Five markers are available:
• Balances Agreement : All five balances are either bullish or bearish.
• Double Bumps : A double bump is two consecutive up/down bars with +/‒ volume delta, and rising Buy/Sell volume above its average.
• Divergence confirmations : A divergence is confirmed up/down when the chosen balance is up/down on the previous bar when that bar was down/up, and this bar is up/down.
• Balance Shifts : These are bull/bear transitions of the selected signal.
• Marker Bias Shifts : Marker bias shifts occur when it crosses into bull/bear territory.
Periods
Allows control over the periods of the different moving averages used to calculate the balances.
Volume Discrepancies
Stock exchanges do not report the same volume for intraday and daily (or higher) resolutions. Other variations in how volume information is reported can also occur in other markets, namely Forex, where volume irregularities can even occur between different intraday timeframes. This will cause discrepancies between the total volume on the bar at the chart's timeframe, and the total volume calculated by adding the volume of the intrabars in that bar's dilation. This does not necessarily invalidate the volume delta information calculated from intrabars, but it tells us that we are using partial volume data. A mechanism to detect chart vs intrabar timeframe volume discrepancies is provided. It allows you to define a threshold percentage above which the background will indicate a difference has been detected.
Other Settings
You can control here the display of the gray dot reminder on realtime bars, and the display of error messages if you are using a chart timeframe that is not greater than the fixed intrabar timeframe, when you use that mode. Disabling the message can be useful if you only use realtime mode at chart timeframes that do not support intrabar inspection.
█ RAMBLINGS
On Volume Delta
Volume is arguably the best complement to interpret price action, and I consider volume delta to be the most effective way of processing volume information. In periods of low-volatility price consolidations, volume will typically also be lower than normal, but slight imbalances in the trend of the buy/sell volume balance can sometimes help put early odds on the direction of the break from consolidation. Additionally, the progression of the volume imbalance can help determine the proximity of the breakout. I also find volume delta and the number of divergences very useful to evaluate the strength of trends. In trends, I am looking for "slow and steady", i.e., relatively low volatility and pauses where price action doesn't look like world affairs are being reassessed. In my personal mythology, this type of trend is often more resilient than high-volatility breakouts, especially when volume balance confirms the general agreement of traders signaled by the low-volatility usually accompanying this type of trend. The volume action on pauses will often help me decide between aggressively taking profits, tightening a stop or going for a longer-term movement. As for reversals, they generally occur in high-volatility areas where entering trades is more expensive and riskier. While the identification of counter-trend reversals fascinates many traders to no end, they represent poor opportunities in my view. Volume imbalances often precede reversals, but I prefer to use volume delta information to identify the areas following reversals where I can confirm them and make relatively low-cost entries with better odds.
On "Buy/Sell" Volume
Buying or selling volume are misnomers, as every unit of volume transacted is both bought and sold by two different traders. While this does not keep me from using the terms, there is no such thing as “buy only” or “sell only” volume. Trader lingo is riddled with peculiarities.
Divergences
The divergence detection method used here relies on a difference between the direction of a signal and the polarity (up/down) of a chart bar. When using the default "On Bar Balance" to detect divergences, however, only the bar's volume delta is used. You may wonder how there can be divergences between buying/selling volume information and price movement on one bar. This will sometimes be due to the calculation's shortcomings, but divergences may also occur in instances where because of order book structure, it takes less volume to increase the price of an asset than it takes to decrease it. As usual, divergences are points of interest because they reveal imbalances, which may or may not become turning points. To your pattern-hungry brain, the divergences displayed by this indicator will — as they do on other indicators — appear to often indicate turnarounds. My opinion is that reality is generally quite sobering and I have no reliable information that would tend to prove otherwise. Exercise caution when using them. Consequently, I do not share the overwhelming enthusiasm of traders in identifying bullish/bearish divergences. For me, the best course of action when a divergence occurs is to wait and see what happens from there. That is the rationale underlying how my divergence levels work; they take note of a signal's level when a divergence occurs, and it's the signal's behavior from that point on that determines if the post-divergence action is bullish/bearish.
Superfluity
In "The Bed of Procrustes", Nassim Nicholas Taleb writes: To bankrupt a fool, give him information . This indicator can display lots of information. While learning to use a new indicator inevitably requires an adaptation period where we put it through its paces and try out all its options, once you have become used to it and decide to adopt it, rigorously eliminate the components you don't use and configure the remaining ones so their visual prominence reflects their relative importance in your analysis. I tried to provide flexible options for traders to control this indicator's visuals for that exact reason — not for window dressing.
█ LIMITATIONS
• This script uses a special characteristic of the `security()` function allowing the inspection of intrabars — which is not officially supported by TradingView.
It has the advantage of permitting a more robust calculation of volume delta than other methods on historical bars, but also has its limits.
• Intrabar inspection only works on some chart timeframes: 3, 5, 10, 15 and 30 minutes, 1, 2, 3, 4, 6, and 12 hours, 1 day, 1 week and 1 month.
The script’s code can be modified to run on other resolutions.
• When the difference between the chart’s timeframe and the intrabar timeframe is too great, runtime errors will occur. The Auto-Steps selection mechanisms should avoid this.
• All volume is not created equally. Its source, components, quality and reliability will vary considerably with sectors and instruments.
The higher the quality, the more reliably volume delta information can be used to guide your decisions.
You should make it your responsibility to understand the volume information provided in the data feeds you use. It will help you make the most of volume delta.
█ NOTES
For traders
• The Data Window shows key values for the indicator.
• While this indicator displays some of the same information calculated in my Delta Volume Columns ,
I have elected to make it a separate publication so that traders continue to have a simpler alternative available to them. Both code bases will continue to evolve separately.
• All gradients used in this indicator determine their brightness intensities using advances/declines in the signal—not their relative position in a pre-determined scale.
• Volume delta being relative, by nature, it is particularly well-suited to Forex markets, as it filters out quite elegantly the cyclical volume data characterizing the sector.
If you are interested in volume delta, consider having a look at my other "Delta Volume" indicators:
• Delta Volume Realtime Action displays realtime volume delta and tick information on the chart.
• Delta Volume Candles builds volume delta candles on the chart.
• Delta Volume Columns is a simpler version of this indicator.
For coders
• I use the `f_c_gradientRelativePro()` from the PineCoders Color Gradient Framework to build my gradients.
This function has the advantage of allowing begin/end colors for both the bull and bear colors. It also allows us to define the number of steps allowed for each gradient.
I use this to modulate the gradients so they perform optimally on the combination of the signal used to calculate advances/declines,
but also the nature of the visual component the gradient applies to. I use fewer steps for choppy signals and when the gradient is used on discrete visual components
such as volume columns or chart bars.
• I use the PineCoders Coding Conventions for Pine to write my scripts.
• I used functions modified from the PineCoders MTF Selection Framework for the selection of timeframes.
█ THANKS TO:
— The devs from TradingView's Pine and other teams, and the PineCoders who collaborate with them. They are doing amazing work,
and much of what this indicator does could not be done without their recent improvements to Pine.
— A guy called Kuan who commented on a Backtest Rookies presentation of their Volume Profile indicator using a `for` loop.
This indicator started from the intrabar inspection technique illustrated in Kuan's snippet.
— theheirophant , my partner in the exploration of the sometimes weird abysses of `security()`’s behavior at intrabar timeframes.
— midtownsk8rguy , my brilliant companion in mining the depths of Pine graphics.
스크립트에서 "mtf"에 대해 찾기
ATA v4 StrategyAta strategy is include 3 different time frame = MTF
2 different moving average =MA
Oversold/overbought for relative strength index =RSI
Strategy exit for trailing stop loss %2 =TSL
MTF like 1 day, 4h and 5 min, between 2 moving averages like fibo numbers 21 and 34. Also strategy test for oversold up to 60 and overbought under the 25 with RSI. Stratefy exit include trailing stop loss %2 persantage for max. gain. It was created by XMAXPRO. This system is open to development.
EMA FAST-SLOWThis indicator has the following
ema fast (length 3 and 8 ) based on 240 min
ema slow (length 3 and 8 ) based on daily MTF
The reason for the two length in each EMA is to give us the the insight of shorter trend in larger trend
so the large trend is when ema fast 240 min is above the daily ema slow this is shown in the bullish or bearish zones
the smaler trend for each MTF is shown in different color (lime:red) for ema fast 240 min , and (green:orange) for the slow daily EMA
when we this setting on smaller time frame so it more easy to see where the asset is going this the basic idea
you can change the setting as you wish in oreder to find the best one for your time frame
Crypto Indicators #u9tusA set of low timeframe (LTF), medium timeframe (MTF), and high timeframe (HTF) indicators for use in crypto currencies / bitcoin.
Traditionally the 10, 20, 50, 100, and 200 SMAs are used in TA. With cryptos, I've found that the 8 EMA, 21, 55, and 128 SMAs backtest better, while no change in length was necessary for the 200. I wanted to combine all these into one indicator to easily add them to a chart layout, hence this script.
You can customize the length of each MA to your liking in the settings, or accept the defaults.
LTF Indicators:
8 EMA in blue hues, medium line stroke.
MTF Indicators:
21, 55 SMA in purple hues, medium line stroke.
HTF Indicators:
128, 200 SMA in yellow hues, thick line stroke.
Defaults are for daily timeframes and lower; suggest changing up the intervals for weekly and monthly to:
21 -> 30
55 -> 50
128 -> 100
$BTC, $ETH, #ALTS
twitter.com
(c) @jhaurawachsman 20190515
X system v1Similar to X system but here I use the super trend with MTF function
the sell option depend on the % channel sell seen in red as bearish rule (so both need to agree)
the buy option depend only on the MTF which is set on 2 hour on 1 hour candles. you can try to modify if you want shorter times to see if it better
if you want it sell more just remove the and bearish rule from t green for buy in the code
try to make it better and I hope it can help you :)
Donochian CCISo this indicator have the following:
1. MTF CCI
2. donochian channel MTF both non repaint mode
buliish and bearish zone determine by ratio of the the donochian cahnnel
enter or exit can be either the bullish or bearish change of color or by cross over or under of the CCI
or combination of both
The high max and low max of the donochian channel show in hilated bar
Donochian zonesThis indicator give the ratio between the high and low of donochian channel and if we take ratio and add it to each other then we can calculate if it + meaning bullish trend or negative meaning bearish trend
using non repainting MTF we can see the zone of the channel at different time set
we can use this indicator to filter bad signal or make it stand alone
here example of amazon stock with 360 min mtf over one hour graph
here facebook 240min over 15 min graph
linreg-areas (like fib system just more accurate) So this system is a different approach to form a daily fib like system.
Its based on linear regression and its slope , we calculate the slope of the line and we put it in MTF format that is without security and non repainting (int2=1440 min)
As you in graph the coin in this case BTC has cycle from low to high similar to the fibs system.
the lowest level is bellow -0.2 , next level is -0.1 ,0,0.1 and above 0.2 is consider the highest
with this system its easy to find the highs and the lows as the coin go between the levels either up or down like the fibs system.
one can use this together with fibs system in order to make analysis more accurate.
also it easy to set signals once the slope go between levels either up or down . another advantage for this system compare to fibs system is the ability to reduce the MTF to lower frame let say 4 hour or even less and then by the same logic to create system of high and lows to the most smaller frames (but if you do that you need in code to change the levels setting numbers so it fit the best )
follow the direction of the slope and you will find the road that you wish:))
Moving Average Stop and Reverse alertsNothing fancy here , the main study is this one
so all credit to him. I change the MTF settings (int2 is contol of that ) and adds alerts
So in basic its a better SAR with MTF function
DEMARSIV1 alerts and take profitThis version is the same as DEMARSI with following differences
I add take profit to short and long when DEMA MTF 1 is crossing DEMA MTF 2 (they are calculated different that why when you increase int2 in min to longer time the difference between them increse)
if you want the TP to be on signal of fast and slow DEMA RSI 2 (just change the code inside) by putting the long cond to be as the buy cond
for any questions please ask
BSP-colorsIts MTF of the BSP model. here i need to warn you that this model can repaint. so I did not create any signals to it. On the other hand since its design for this mistake. you can use it to see the bullish or bearish zones in easy way.
So the basic idea here is to see the zones of buy and sell of weis model in mTF format.
Inverse Fisher-rsi-crudeSo this is a crude version just to show the idea. I use the code of capissoimo, www.tradingview.com
together with my older code and I just change few things. in next version I will try make it more correct, but this is just to show the idea of the MTF reverse fisher RSI
this is setting for 30 min graph with MTF of 120 min
so have fun
Gomoku_V2I tried to improve the one - step equilibrium table.
Since the original glance consisted of the middle line of the Hiroo band, something is calculated from the upper and lower lines.
Leading span A = Double the width of the HiLo band (Green 2) * (1-75 (≒ 76.4% return)), the central complex clouds only changed the expression at a glance.
It is unified to shift all lines at first glance by 25. The old lagging span was renamed to the preceding price span.
You can use the first line of conversion line and reference line with the combination of the preceding conversion line, the preceding reference line and the preceding price span.
The part surrounded by the preceding conversion line and the preceding reference line is defined as rain cloud.
The leading span B is the interpretation of the rain cloud and the effective value of the cloud.
(the width of the reference line and the leading span A) ÷ The width of the rain cloud is like the intensity of the cloud.
Rain clouds have the same properties as clouds, and the twisted parts are weak.
When the type of cloud and rain cloud are different, it is countervailing and resistance seems to be weak.
Even when the width of the leading span A and the leading reference line is narrow, the resistance seems to be weak.
It seems there are clouds above and below as well because it was the motivation for development so there are two clouds each above and below. The clouds are five (although it is actually six) so it is the fifth grade.
It should normally be bounced back in the green zone.
There is a red zone for abnormal price fluctuations.
It seems that the upper and lower clouds only bounce back toward the center.
If you are not satisfied with price movements overall it seems that you are in the range market, often breaking through for the passage of time.
Update Ver 2.0
integrate MTF amagumo
Devices of color arrangement
The resistance is strong where the cloud color is thin.
It should be weak as the force is canceled as much as it is black.
Batch display option for each part
Specealthanks
Ichimoku kinkou hyou
KazmaxFAN Club # Place for technical discussion
一目均衡表を改良してみました。
元の一目はハイローバンドの中線から構成されていたので、上下の線から何かを算出しています。
先行スパンA=ハイローバンドの幅の2倍(Green2)*(1-75(≒76.4%戻し)) という発見により、中央の複雑な雲は一目の表現を変えるだけにしました。
一目の線は全て25前にずらすのに統一です。旧遅行スパンは先行価格スパンに改名しました。
先行転換線と先行基準線と先行価格スパンの組み合わせで一目の転換線と基準線の使い方が出来ます。
先行転換線と先行基準線で囲まれた部分は雨雲と定義。
先行スパンBは雨雲と雲の実効値という解釈です。
(基準線と先行スパンAの幅)÷雨雲の幅が雲の強度という感じです。
雨雲も雲と同じ性質を持っていて、ねじれた部分は弱いぽいです。
雲と雨雲の種類が異なる時は打ち消しあって抵抗が弱いようです。
先行スパンAと先行基準線の幅が狭い時も抵抗が弱いようです。
上下にも雲があるように思えたのが開発の動機だったので上下に各2本雲があります。雲が5本(本当は6本ですが)だから五目です。
通常はグリーンゾーンで跳ね返されるはずです。
異常な価格変動用にレッドゾーンがあります。
上下の雲は中央に向けて跳ね返すくらいしかしないようです。
全体的に価格移動に困ればレンジ相場になって、時間の経過で強行突破することが多いように見えます。
Update Ver2.0
MTF amagumoを統合
配色を工夫
雲の色が薄い所は抵抗が強いです。
黒い所ほど力が打ち消しあって弱いはずです。
各パーツごとに一括表示オプション
Specealthanks
一目均衡表
KazmaxFAN倶楽部 #テクニカル議論の場
SpatialIndexYou can start using this now by inserthing this at the top of your indicator/strategy/library.
import ArunaReborn/SpatialIndex/1 as SI
Overview
SpatialIndex is a high-performance Pine Script library that implements price-bucketed spatial indexing for efficient proximity queries on large datasets. Instead of scanning through hundreds or thousands of items linearly (O(n)), this library provides O(k) bucket lookup where k is typically just a handful of buckets, dramatically improving performance for price-based filtering operations.
This library works with any data type through index-based references, making it universally applicable for support/resistance levels, pivot points, order zones, pattern detection points, Fair Value Gaps, and any other price-based data that needs frequent proximity queries.
Why This Library Exists
The Problem
When building advanced technical indicators that track large numbers of price levels (support/resistance zones, pivot points, order blocks, etc.), you often need to answer questions like:
- *"Which levels are within 5% of the current price?"*
- *"What zones overlap with this price range?"*
- *"Are there any significant levels near my entry point?"*
The naive approach is to loop through every single item and check its price. For 500 levels across multiple timeframes, this means 500 comparisons every bar . On instruments with thousands of historical bars, this quickly becomes a performance bottleneck that can cause scripts to time out or lag.
The Solution
SpatialIndex solves this by organizing items into price buckets —like filing cabinets organized by price range. When you query for items near $50,000, the library only looks in the relevant buckets (e.g., $49,000-$51,000 range), ignoring all other price regions entirely.
Performance Example:
- Linear scan: Check 500 items = 500 comparisons per query
- Spatial index: Check 3-5 buckets with ~10 items each = 30-50 comparisons per query
- Result: 10-16x faster queries
Key Features
Core Capabilities
- ✅ Generic Design : Works with any data type via index references
- ✅ Multiple Index Strategies : Fixed bucket size or ATR-based dynamic sizing
- ✅ Range Support : Index items that span price ranges (zones, gaps, channels)
- ✅ Efficient Queries : O(k) bucket lookup instead of O(n) linear scan
- ✅ Multiple Query Types : Proximity percentage, fixed range, exact price with tolerance
- ✅ Dynamic Updates : Add, remove, update items in O(1) time
- ✅ Batch Operations : Efficient bulk removal and reindexing
- ✅ Query Caching : Optional caching for repeated queries within same bar
- ✅ Statistics & Debugging : Built-in stats and diagnostic functions
### Advanced Features
- ATR-Based Bucketing : Automatically adjusts bucket sizes based on volatility
- Multi-Bucket Spanning : Items that span ranges are indexed in all overlapping buckets
- Reindexing Support : Handles array removals with automatic index shifting
- Cache Management : Configurable query caching with automatic invalidation
- Empty Bucket Cleanup : Automatically removes empty buckets to minimize memory
How It Works
The Bucketing Concept
Think of price space as divided into discrete buckets, like a histogram:
```
Price Range: $98-$100 $100-$102 $102-$104 $104-$106 $106-$108
Bucket Key: 49 50 51 52 53
Items:
```
When you query for items near $103:
1. Calculate which buckets overlap the $101.50-$104.50 range (keys 50, 51, 52)
2. Return items from only those buckets:
3. Never check items in buckets 49 or 53
Bucket Size Selection
Fixed Size Mode:
```pine
var SI.SpatialBucket index = SI.newSpatialBucket(2.0) // $2 per bucket
```
- Good for: Instruments with stable price ranges
- Example: For stocks trading at $100, 2.0 = 2% increments
ATR-Based Mode:
```pine
float atr = ta.atr(14)
var SI.SpatialBucket index = SI.newSpatialBucketATR(1.0, atr) // 1x ATR per bucket
SI.updateATR(index, atr) // Update each bar
```
- Good for: Instruments with varying volatility
- Adapts automatically to market conditions
- 1.0 multiplier = one bucket spans one ATR unit
Optimal Bucket Size:
The library includes a helper function to calculate optimal size:
```pine
float optimalSize = SI.calculateOptimalBucketSize(close, 5.0) // For 5% proximity queries
```
This ensures queries span approximately 3 buckets for optimal performance.
Index-Based Architecture
The library doesn't store your actual data—it only stores indices that point to your external arrays:
```pine
// Your data
var array levels = array.new()
var array types = array.new()
var array ages = array.new()
// Your index
var SI.SpatialBucket index = SI.newSpatialBucket(2.0)
// Add a level
array.push(levels, 50000.0)
array.push(types, "support")
array.push(ages, 0)
SI.add(index, array.size(levels) - 1, 50000.0) // Store index 0
// Query near current price
SI.QueryResult result = SI.queryProximity(index, close, 5.0)
for idx in result.indices
float level = array.get(levels, idx)
string type = array.get(types, idx)
// Work with your actual data
```
This design means:
- ✅ Works with any data structure you define
- ✅ No data duplication
- ✅ Minimal memory footprint
- ✅ Full control over your data
---
Usage Guide
Basic Setup
```pine
// Import library
import username/SpatialIndex/1 as SI
// Create index
var SI.SpatialBucket index = SI.newSpatialBucket(2.0)
// Your data arrays
var array supportLevels = array.new()
var array touchCounts = array.new()
```
Adding Items
Single Price Point:
```pine
// Add a support level at $50,000
array.push(supportLevels, 50000.0)
array.push(touchCounts, 1)
int levelIdx = array.size(supportLevels) - 1
SI.add(index, levelIdx, 50000.0)
```
Price Range (Zones/Gaps):
```pine
// Add a resistance zone from $51,000 to $52,000
array.push(zoneBottoms, 51000.0)
array.push(zoneTops, 52000.0)
int zoneIdx = array.size(zoneBottoms) - 1
SI.addRange(index, zoneIdx, 51000.0, 52000.0) // Indexed in all overlapping buckets
```
Querying Items
Proximity Query (Percentage):
```pine
// Find all levels within 5% of current price
SI.QueryResult result = SI.queryProximity(index, close, 5.0)
if array.size(result.indices) > 0
for idx in result.indices
float level = array.get(supportLevels, idx)
// Process nearby level
```
Fixed Range Query:
```pine
// Find all items between $49,000 and $51,000
SI.QueryResult result = SI.queryRange(index, 49000.0, 51000.0)
```
Exact Price with Tolerance:
```pine
// Find items at exactly $50,000 +/- $100
SI.QueryResult result = SI.queryAt(index, 50000.0, 100.0)
```
Removing Items
Safe Removal Pattern:
```pine
SI.QueryResult result = SI.queryProximity(index, close, 5.0)
if array.size(result.indices) > 0
// IMPORTANT: Sort descending to safely remove from arrays
array sorted = SI.sortIndicesDescending(result)
for idx in sorted
// Remove from index
SI.remove(index, idx)
// Remove from your data arrays
array.remove(supportLevels, idx)
array.remove(touchCounts, idx)
// Reindex to maintain consistency
SI.reindexAfterRemoval(index, idx)
```
Batch Removal (More Efficient):
```pine
// Collect indices to remove
array toRemove = array.new()
for i = 0 to array.size(supportLevels) - 1
if array.get(touchCounts, i) > 10 // Remove old levels
array.push(toRemove, i)
// Remove in descending order from data arrays
array sorted = array.copy(toRemove)
array.sort(sorted, order.descending)
for idx in sorted
SI.remove(index, idx)
array.remove(supportLevels, idx)
array.remove(touchCounts, idx)
// Batch reindex (much faster than individual reindexing)
SI.reindexAfterBatchRemoval(index, toRemove)
```
Updating Items
```pine
// Update a level's price (e.g., after refinement)
float newPrice = 50100.0
SI.update(index, levelIdx, newPrice)
array.set(supportLevels, levelIdx, newPrice)
// Update a zone's range
SI.updateRange(index, zoneIdx, 51000.0, 52500.0)
array.set(zoneBottoms, zoneIdx, 51000.0)
array.set(zoneTops, zoneIdx, 52500.0)
```
Query Caching
For repeated queries within the same bar:
```pine
// Create cache (persistent)
var SI.CachedQuery cache = SI.newCachedQuery()
// Cached query (returns cached result if parameters match)
SI.QueryResult result = SI.queryProximityCached(
index,
cache,
close,
5.0, // proximity%
1 // cache duration in bars
)
// Invalidate cache when index changes significantly
if bigChangeDetected
SI.invalidateCache(cache)
```
---
Practical Examples
Example 1: Support/Resistance Finder
```pine
//@version=6
indicator("S/R with Spatial Index", overlay=true)
import username/SpatialIndex/1 as SI
// Data storage
var array levels = array.new()
var array types = array.new() // "support" or "resistance"
var array touches = array.new()
var array ages = array.new()
// Spatial index
var SI.SpatialBucket index = SI.newSpatialBucket(close * 0.02) // 2% buckets
// Detect pivots
bool isPivotHigh = ta.pivothigh(high, 5, 5)
bool isPivotLow = ta.pivotlow(low, 5, 5)
// Add new levels
if isPivotHigh
array.push(levels, high )
array.push(types, "resistance")
array.push(touches, 1)
array.push(ages, 0)
SI.add(index, array.size(levels) - 1, high )
if isPivotLow
array.push(levels, low )
array.push(types, "support")
array.push(touches, 1)
array.push(ages, 0)
SI.add(index, array.size(levels) - 1, low )
// Find nearby levels (fast!)
SI.QueryResult nearby = SI.queryProximity(index, close, 3.0) // Within 3%
// Process nearby levels
for idx in nearby.indices
float level = array.get(levels, idx)
string type = array.get(types, idx)
// Check for touch
if type == "support" and low <= level and low > level
array.set(touches, idx, array.get(touches, idx) + 1)
else if type == "resistance" and high >= level and high < level
array.set(touches, idx, array.get(touches, idx) + 1)
// Age and cleanup old levels
for i = array.size(ages) - 1 to 0
array.set(ages, i, array.get(ages, i) + 1)
// Remove levels older than 500 bars or with 5+ touches
if array.get(ages, i) > 500 or array.get(touches, i) >= 5
SI.remove(index, i)
array.remove(levels, i)
array.remove(types, i)
array.remove(touches, i)
array.remove(ages, i)
SI.reindexAfterRemoval(index, i)
// Visualization
for idx in nearby.indices
line.new(bar_index, array.get(levels, idx), bar_index + 10, array.get(levels, idx),
color=array.get(types, idx) == "support" ? color.green : color.red)
```
Example 2: Multi-Timeframe Zone Detector
```pine
//@version=6
indicator("MTF Zones", overlay=true)
import username/SpatialIndex/1 as SI
// Store zones from multiple timeframes
var array zoneBottoms = array.new()
var array zoneTops = array.new()
var array zoneTimeframes = array.new()
// ATR-based spatial index for adaptive bucketing
var SI.SpatialBucket index = SI.newSpatialBucketATR(1.0, ta.atr(14))
SI.updateATR(index, ta.atr(14)) // Update bucket size with volatility
// Request higher timeframe data
= request.security(syminfo.tickerid, "240", )
// Detect HTF zones
if not na(htf_high) and not na(htf_low)
float zoneTop = htf_high
float zoneBottom = htf_low * 0.995 // 0.5% zone thickness
// Check if zone already exists nearby
SI.QueryResult existing = SI.queryRange(index, zoneBottom, zoneTop)
if array.size(existing.indices) == 0 // No overlapping zones
// Add new zone
array.push(zoneBottoms, zoneBottom)
array.push(zoneTops, zoneTop)
array.push(zoneTimeframes, "4H")
int idx = array.size(zoneBottoms) - 1
SI.addRange(index, idx, zoneBottom, zoneTop)
// Query zones near current price
SI.QueryResult nearbyZones = SI.queryProximity(index, close, 2.0) // Within 2%
// Highlight nearby zones
for idx in nearbyZones.indices
box.new(bar_index - 50, array.get(zoneBottoms, idx),
bar_index, array.get(zoneTops, idx),
bgcolor=color.new(color.blue, 90))
```
### Example 3: Performance Comparison
```pine
//@version=6
indicator("Spatial Index Performance Test")
import username/SpatialIndex/1 as SI
// Generate 500 random levels
var array levels = array.new()
var SI.SpatialBucket index = SI.newSpatialBucket(close * 0.02)
if bar_index == 0
for i = 0 to 499
float randomLevel = close * (0.9 + math.random() * 0.2) // +/- 10%
array.push(levels, randomLevel)
SI.add(index, i, randomLevel)
// Method 1: Linear scan (naive approach)
int linearCount = 0
float proximityPct = 5.0
float lowBand = close * (1 - proximityPct/100)
float highBand = close * (1 + proximityPct/100)
for i = 0 to array.size(levels) - 1
float level = array.get(levels, i)
if level >= lowBand and level <= highBand
linearCount += 1
// Method 2: Spatial index query
SI.QueryResult result = SI.queryProximity(index, close, proximityPct)
int spatialCount = array.size(result.indices)
// Compare performance
plot(result.queryCount, "Items Examined (Spatial)", color=color.green)
plot(linearCount, "Items Examined (Linear)", color=color.red)
plot(spatialCount, "Results Found", color=color.blue)
// Spatial index typically examines 10-50 items vs 500 for linear scan!
```
API Reference Summary
Initialization
- `newSpatialBucket(bucketSize)` - Fixed bucket size
- `newSpatialBucketATR(atrMultiplier, atrValue)` - ATR-based buckets
- `updateATR(sb, newATR)` - Update ATR for dynamic sizing
Adding Items
- `add(sb, itemIndex, price)` - Add item at single price point
- `addRange(sb, itemIndex, priceBottom, priceTop)` - Add item spanning range
Querying
- `queryProximity(sb, refPrice, proximityPercent)` - Query by percentage
- `queryRange(sb, priceBottom, priceTop)` - Query fixed range
- `queryAt(sb, price, tolerance)` - Query exact price with tolerance
- `queryProximityCached(sb, cache, refPrice, pct, duration)` - Cached query
Removing & Updating
- `remove(sb, itemIndex)` - Remove item
- `update(sb, itemIndex, newPrice)` - Update item price
- `updateRange(sb, itemIndex, newBottom, newTop)` - Update item range
- `reindexAfterRemoval(sb, removedIndex)` - Reindex after single removal
- `reindexAfterBatchRemoval(sb, removedIndices)` - Batch reindex
- `clear(sb)` - Remove all items
Utilities
- `size(sb)` - Get item count
- `isEmpty(sb)` - Check if empty
- `contains(sb, itemIndex)` - Check if item exists
- `getStats(sb)` - Get debug statistics string
- `calculateOptimalBucketSize(price, pct)` - Calculate optimal bucket size
- `sortIndicesDescending(result)` - Sort for safe removal
- `sortIndicesAscending(result)` - Sort ascending
Performance Characteristics
Time Complexity
- Add : O(1) for single point, O(m) for range spanning m buckets
- Remove : O(1) lookup + O(b) bucket cleanup where b = buckets item spans
- Query : O(k) where k = buckets in range (typically 3-5) vs O(n) linear scan
- Update : O(1) removal + O(1) addition = O(1) total
Space Complexity
- Memory per item : ~8 bytes for index reference + map overhead
- Bucket overhead : Proportional to price range coverage
- Typical usage : For 500 items with 50 active buckets ≈ 4-8KB total
Scalability
- ✅ 100 items : ~5-10x faster than linear scan
- ✅ 500 items : ~10-15x faster
- ✅ 1000+ items : ~15-20x faster
- ⚠️ Performance degrades if bucket size is too small (too many buckets)
- ⚠️ Performance degrades if bucket size is too large (too many items per bucket)
Best Practices
Bucket Size Selection
1. Start with 2-5% of asset price for percentage-based queries
2. Use ATR-based mode for volatile assets or multi-symbol scripts
3. Test bucket size using `calculateOptimalBucketSize()` function
4. Monitor with `getStats()` to ensure reasonable bucket count
Memory Management
1. Clear old items regularly to prevent unbounded growth
2. Use age tracking to remove stale data
3. Set maximum item limits based on your needs
4. Batch removals are more efficient than individual removals
Query Optimization
1. Use caching for repeated queries within same bar
2. Invalidate cache when index changes significantly
3. Sort results descending before removal iteration
4. Batch operations when possible (reindexing, removal)
Data Consistency
1. Always reindex after removal to maintain index alignment
2. Remove from arrays in descending order to avoid index shifting issues
3. Use batch reindex for multiple simultaneous removals
4. Keep external arrays and index in sync at all times
Limitations & Caveats
Known Limitations
- Not suitable for exact price matching : Use tolerance with `queryAt()`
- Bucket size affects performance : Too small = many buckets, too large = many items per bucket
- Memory usage : Scales with price range coverage and item count
- Reindexing overhead : Removing items mid-array requires index shifting
When NOT to Use
- ❌ Datasets with < 50 items (linear scan is simpler)
- ❌ Items that change price every bar (constant reindexing overhead)
- ❌ When you need ALL items every time (no benefit over arrays)
- ❌ Exact price level matching without tolerance (use maps instead)
When TO Use
- ✅ Large datasets (100+ items) with occasional queries
- ✅ Proximity-based filtering (% of price, ATR-based ranges)
- ✅ Multi-timeframe level tracking
- ✅ Zone/range overlap detection
- ✅ Price-based spatial filtering
---
Technical Details
Bucketing Algorithm
Items are assigned to buckets using integer division:
```
bucketKey = floor((price - basePrice) / bucketSize)
```
For ATR-based mode:
```
effectiveBucketSize = atrValue × atrMultiplier
bucketKey = floor((price - basePrice) / effectiveBucketSize)
```
Range Indexing
Items spanning price ranges are indexed in all overlapping buckets to ensure accurate range queries. The midpoint bucket is designated as the "primary bucket" for removal operations.
Index Consistency
The library maintains two maps:
1. `buckets`: Maps bucket keys → IntArray wrappers containing item indices
2. `itemToBucket`: Maps item indices → primary bucket key (for O(1) removal)
This dual-mapping ensures both fast queries and fast removal while maintaining consistency.
Implementation Note: Pine Script doesn't allow nested collections (map containing arrays directly), so the library uses an `IntArray` wrapper type to hold arrays within the map structure. This is an internal implementation detail that doesn't affect usage.
---
Version History
Version 1.0
- Initial release
Credits & License
License : Mozilla Public License 2.0 (TradingView default)
Library Type : Open-source educational resource
This library is designed as a public domain utility for the Pine Script community. As per TradingView library rules, this code can be freely reused by other authors. If you use this library in your scripts, please provide appropriate credit as required by House Rules.
Summary
SpatialIndex is a specialized library that solves a specific problem: fast proximity queries on large price-based datasets . If you're building indicators that track hundreds of levels, zones, or price points and need to frequently filter by proximity to current price, this library can provide 10-20x performance improvements over naive linear scanning.
The index-based architecture makes it universally applicable to any data type, and the ATR-based bucketing ensures it adapts to market conditions automatically. Combined with query caching and batch operations, it provides a complete solution for spatial data management in Pine Script.
Use this library when speed matters and your dataset is large.
Timeframe Continuity BarsTimeframe Continuity Bars is a script that is extremely simple for good reason
So please, do not remove this post because it seems 'simple'
Now that's over with. Lets dive in to understand what timeframe continuity IS and what this indicator does.
Timeframe continuity is defined by 4 or more timeframes and it is the relationship of the last price traded to those 4 opening prices. Standard timeframe continuity would be using the M,W,D,60min timeframes.
The reason we use MTF analysis is because of the truth of what price is and how it works.
Price movement is SOLELY caused due to aggressive buying / selling. Some may attempt to refute this however at the end of the day. If the price is at 100.00 it is because a buyer is willing to buy there and a seller is willing to sell there. If those market participants did not want to buy or sell at 100.00 price would go up or down to meet the more aggressive participant.
So what does this look like you may ask...
If an aggressive buyer takes the offer we will see prices go up if they were willing to pay more than the last guy who took the offer.
So price may go from 100.00 to 100.01 because you decided to invest in that stock that day at that time with a market order
This same thing occurs when every other institution creates, adds, reduces, or exits a position. They have to buy or sell and they have to either do it aggressively or do it passively by sitting on the bid / ask and waiting.
So since this is true, we know that the relationship to the opening price is extremely important. This is because if price is above it's open that means buyers were willing to take the offer and buy at higher prices. If price is below it's open it means that sellers were willing to sell at the bid and they sold at lower prices.
So any candlestick chart is simply an aggregation of this aggressive buying/selling that is taking place at all times.
By using the timeframe continuity bars indicator we can measure the distance from the current open across 4 or more timeframes.
By doing this we can identify monthly participation groups, weekly participation groups, daily participation groups, and 60min participation groups.
When all those groups align green or red this is considered full timeframe continuity. Where the monthly weekly daily 60min groups are all taking the offer and buying, or all selling at the bid!
When this aligns this is when price is for CERTAIN going in one direction.
However, It is subject to change every 60 minutes as the 60min determines if those monthly weekly daily buyers are present RIGHT NOW.
So if the 60min changes we go into direct conflict against the month/week/day groups.
If we see the 60min and day align we go into direct conflict against the month/week
if the 60min day and week are red we over-take the monthly group for control. At the time of the week day and 60 being red we have ZERO evidence of the previous monthly buyer/seller that was present.
Now that you understand a little bit about continuity.. Check it out on the chart!
P.S Here is some tips
1) it is not about just all timeframes aligning, we want to see long green / red bars!
2) The opens reset on a cyclical basis. Each day, each week, each month... When the new timeframes open we will see timeframes have the SAME open. When the opens are the same price we have LESS evidence versus having all opens seperate.
3) Investors can use the Y Q M W as their 4 timeframes to see when institutional buying is occurring [go do a case study on AMEX:GLD and AMEX:SLV weekly timeframe with these settings]
4) You need to add 4 separate indicators and change the timeframes. It is ideal to then save this layout!
5) The best way to do price analysis is using #TheStrat across all 4 timeframes instead of one timeframe with this indicator. This is soley a tool we use to show changing of control between participation groups!
TimeframeAlignTHE PROBLEM THIS LIBRARY SOLVES
When you use `request.security()` to get data from a Higher Timeframe (HTF) and try to draw objects like boxes, lines, or labels, they appear at the wrong horizontal position . This is the "floating in space" problem.
Why does this happen?
The `bar_index` in Pine Script refers to where data was RECEIVED , not where the event OCCURRED .
Consider this scenario:
• You're on a 5-minute chart
• You request 1-hour data for drawing an FVG (Fair Value Gap)
• A 1H candle spans 12 chart bars (60min / 5min = 12)
• But your code draws at `bar_index - 1` or `bar_index - 3`
• The result: your FVG box is only 2-3 bars wide instead of spanning the correct 12-36 bars
This library solves that by tracking where HTF bars actually start and end on your chart timeframe.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
HOW TO USE THIS LIBRARY
Step 1: Import the Library
```
import ArunaReborn/TimeframeAlign/1 as tfa
```
Step 2: Create a Tracker for Each HTF
```
var tfa.HTFTracker tracker1H = tfa.createTracker("60")
```
Step 3: Update the Tracker Every Bar
```
tfa.updateTracker(tracker1H, "60")
```
Step 4: Use Synced Drawing Functions
```
if tfa.htfBarChanged(tracker1H)
tfa.syncedBox(tracker1H, 3, 1, topPrice, bottomPrice, color.new(color.green, 80))
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
EXPORTED TYPES
TimeframePair
Stores metadata about the relationship between source and chart timeframes.
• sourceTimeframe - The HTF/LTF being compared
• chartTimeframe - Current chart timeframe
• isHTF - True if source is higher than chart
• isLTF - True if source is lower than chart
• barRatio - Chart bars per source bar
• secondsRatio - Time ratio between timeframes
MTFEventData
Stores synchronized event data with correct bar positions.
• price - Price level of the event
• eventTime - Unix timestamp of the event
• chartBarStart - Chart bar_index where event's TF bar started
• chartBarEnd - Chart bar_index where event's TF bar ended
• htfOffset - The HTF offset used
• isValid - True if synchronization succeeded
HTFTracker
Tracks HTF bar boundaries. Create one per timeframe you need to track.
• htfTimeframe - The timeframe being tracked
• currentStartBar - Where current HTF bar started
• currentEndBar - Where current HTF bar ends (provisional)
• startHistory - Array of historical start positions
• endHistory - Array of historical end positions
• lastUpdateBar - Last bar_index when updated
• barJustChanged - True if HTF bar changed on this chart bar (set by updateTracker)
SyncedBox
Managed box with synchronization metadata.
• bx - The Pine Script box object
• htfTimeframe - Source timeframe
• leftHtfOffset / rightHtfOffset - HTF offsets for edges
• topPrice / bottomPrice - Price boundaries
• extendRight - Auto-extend flag
SyncedLine
Managed line with synchronization metadata.
• ln - The Pine Script line object
• htfTimeframe - Source timeframe
• htfOffset - Anchor offset
• price - Price level (horizontal lines)
• isHorizontal - Line orientation
• extendRight - Auto-extend flag
SyncedLabel
Managed label with synchronization metadata.
• lbl - The Pine Script label object
• htfTimeframe - Source timeframe
• htfOffset - Anchor offset
• price - Price level
• anchorPoint - "start", "end", or "middle"
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
EXPORTED FUNCTIONS
━━ CORE FUNCTIONS ━━
getTimeframeInfo(sourceTimeframe)
Analyzes relationship between a source TF and chart TF.
Returns: TimeframePair with comparison metadata
createTracker(htfTimeframe)
Creates a new HTF tracker. Call once per timeframe, store with `var`.
Returns: HTFTracker instance
updateTracker(tracker, htfTimeframe, historyDepth)
Updates tracker with current bar data. Call on every bar.
• htfTimeframe: The timeframe string (must match createTracker)
• historyDepth: Max HTF bars to track (default 500)
Returns: Updated tracker
getStartBar(tracker, htfOffset)
Gets chart bar_index where a specific HTF bar started.
• htfOffset: 0=current, 1=previous, 2=two bars ago, etc.
Returns: bar_index or na
getEndBar(tracker, htfOffset)
Gets chart bar_index where a specific HTF bar ended.
Returns: bar_index or na
htfBarChanged(tracker)
Detects when HTF bar just changed.
Returns: True on first chart bar of new HTF bar
findBarAtTime(timestamp, maxLookback)
Searches backward to find chart bar containing a timestamp.
• maxLookback: How far back to search (default 500)
Returns: bar_index or na
syncEventToChart(tracker, eventPrice, eventTime, anchorPoint)
Generic sync function mapping any event to correct chart position.
• anchorPoint: "start", "end", or "middle"
Returns: MTFEventData
━━ DRAWING CREATION FUNCTIONS ━━
syncedBox(tracker, leftHtfOffset, rightHtfOffset, topPrice, bottomPrice, bgcolor, ...)
Creates a box at correct HTF-aligned position.
• leftHtfOffset: HTF bars back for left edge
• rightHtfOffset: HTF bars back for right edge
• extendRight: Auto-extend to current bar
Returns: SyncedBox or na
syncedHLine(tracker, htfOffset, price, lineColor, lineStyle, lineWidth, extendRight)
Creates horizontal line anchored to HTF bar start.
• extendRight: If true, extends to current bar (default true)
Returns: SyncedLine or na
syncedVLine(tracker, htfOffset, atStart, lineColor, lineStyle, lineWidth)
Creates vertical line at HTF bar boundary.
• atStart: True=start of HTF bar, False=end
Returns: SyncedLine or na
syncedLabel(tracker, htfOffset, price, labelText, anchorPoint, ...)
Creates label at correct HTF-aligned position.
• anchorPoint: "start", "end", or "middle"
Returns: SyncedLabel or na
syncedPlotValue(tracker, value, htfOffset)
Returns value for plotting only at synced positions.
Returns: value if current bar is within HTF range, otherwise na
━━ UPDATE FUNCTIONS ━━
updateSyncedBox(syncedBox, extendToCurrentBar)
Extends existing box's right edge to current bar.
Returns: Updated SyncedBox
updateSyncedLine(syncedLine, extendToCurrentBar)
Extends existing horizontal line to current bar.
Returns: Updated SyncedLine
updateSyncedLabel(syncedLabel, tracker, newText, newPrice)
Updates label text/price while maintaining sync.
Returns: Updated SyncedLabel
━━ CONVENIENCE FUNCTIONS ━━
htfBarStartIndex(htfTimeframe, htfOffset, historyDepth)
Simple function to get HTF bar start without explicit tracker.
⚠️ Only tracks ONE timeframe. For multiple TFs, use createTracker pattern.
Returns: bar_index or na
htfBarEndIndex(htfTimeframe, htfOffset, historyDepth)
Simple function to get HTF bar end without explicit tracker.
⚠️ Only tracks ONE timeframe. For multiple TFs, use createTracker pattern.
Returns: bar_index or na
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
COMPLETE USAGE EXAMPLES
Example 1: FVG Box with Auto-Extend
```
//@version=6
indicator("FVG with Synced Drawing", overlay=true)
import ArunaReborn/TimeframeAlign/1 as tfa
htfInput = input.timeframe("60", "HTF for FVG")
// Create tracker for chosen timeframe
var tfa.HTFTracker fvgTracker = tfa.createTracker(htfInput)
tfa.updateTracker(fvgTracker, htfInput)
// Get FVG data from HTF (confirmed bars with offset)
= request.security(syminfo.tickerid, htfInput,
[low , high , low > high ],
lookahead=barmerge.lookahead_off)
// Store managed box
var tfa.SyncedBox fvgBox = na
// Create synced box when FVG detected
if fvgDetected and tfa.htfBarChanged(fvgTracker)
fvgBox := tfa.syncedBox(fvgTracker, 3, 1, fvgTop, fvgBot,
color.new(color.green, 85), color.green, 1, "FVG", color.white, true)
// Extend box to current bar each tick
if not na(fvgBox)
tfa.updateSyncedBox(fvgBox, true)
```
Example 2: HTF Support/Resistance Lines
```
//@version=6
indicator("HTF S/R Lines", overlay=true)
import ArunaReborn/TimeframeAlign/1 as tfa
htfInput = input.timeframe("240", "HTF for S/R")
// Create and update tracker
var tfa.HTFTracker srTracker = tfa.createTracker(htfInput)
tfa.updateTracker(srTracker, htfInput)
// Get HTF high/low (confirmed with offset)
= request.security(syminfo.tickerid, htfInput,
[high , low ], lookahead=barmerge.lookahead_off)
// Track lines
var tfa.SyncedLine resistanceLine = na
var tfa.SyncedLine supportLine = na
// Create new lines when HTF bar changes
if tfa.htfBarChanged(srTracker)
resistanceLine := tfa.syncedHLine(srTracker, 1, htfHigh, color.red, line.style_solid, 2, true)
supportLine := tfa.syncedHLine(srTracker, 1, htfLow, color.green, line.style_solid, 2, true)
// Auto-extend lines each bar
if not na(resistanceLine)
tfa.updateSyncedLine(resistanceLine, true)
if not na(supportLine)
tfa.updateSyncedLine(supportLine, true)
```
Example 3: Multiple Timeframes
```
//@version=6
indicator("Multi-TF Boxes", overlay=true)
import ArunaReborn/TimeframeAlign/1 as tfa
// Create separate tracker for each timeframe
var tfa.HTFTracker tracker1H = tfa.createTracker("60")
var tfa.HTFTracker tracker4H = tfa.createTracker("240")
var tfa.HTFTracker trackerD = tfa.createTracker("1D")
// Update ALL trackers every bar (pass the same TF string)
tfa.updateTracker(tracker1H, "60")
tfa.updateTracker(tracker4H, "240")
tfa.updateTracker(trackerD, "1D")
// Now use each tracker independently for drawing
// Each tracker maintains its own separate boundary history
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
NON-REPAINTING COMPLIANCE
To ensure non-repainting behavior, always use this pattern with request.security:
```
= request.security(syminfo.tickerid, htfTimeframe,
[value1 , value2 ], // Use offset for confirmed data
lookahead=barmerge.lookahead_off) // Never use lookahead_on
```
The ` ` offset ensures you're using the previous completed HTF bar, not the current forming bar.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
HISTORY DEPTH PARAMETER
The `historyDepth` parameter controls how many HTF bars are tracked:
• Default: 500 HTF bars
• Maximum: Limited by Pine Script's array constraints
• Higher values = more historical accuracy but more memory usage
• Lower values = less memory but may return `na` for older offsets
Adjust based on your needs:
```
tfa.updateTracker(tracker, 100) // Track 100 HTF bars (light)
tfa.updateTracker(tracker, 1000) // Track 1000 HTF bars (heavier)
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
IMPORTANT NOTES
1. One Tracker Per Timeframe : If you need multiple HTFs, create separate trackers for each. The convenience functions (htfBarStartIndex, htfBarEndIndex) only track one TF.
2. Update Every Bar : Always call updateTracker() unconditionally on every bar, not inside conditionals.
3. HTF Only : This library is designed for Higher Timeframe data. For LTF aggregation, use findBarAtTime() for time-based lookups.
4. Drawing Limits : Pine Script has limits on drawing objects. Use box.delete(), line.delete(), label.delete() to clean up old objects.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
TROUBLESHOOTING
Q: My boxes/lines still appear at wrong positions
A: Make sure you're calling updateTracker() on every bar (not inside an if statement) and using the correct htfOffset values.
Q: Functions return na
A: The htfOffset might be larger than available history. Increase historyDepth or use a smaller offset.
Q: Multiple timeframes don't work correctly
A: Don't use the convenience functions for multiple TFs. Create separate HTFTracker instances with createTracker() for each timeframe.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
CHANGELOG
v1 - Initial release
• HTFTracker pattern for reliable multi-TF tracking
• Synced drawing functions for boxes, lines, labels
• Update functions for extending drawings
• Convenience functions for simple single-TF use cases
200W SMA Dynamic Extension Bands (MTF, Auto Asset)Summary
200W SMA Dynamic Extension Bands is a multi-timeframe TradingView indicator that plots extension bands (multiples) around the 200-week simple moving average. It’s designed to work on any chart timeframe (1m → 1D → 1W) while anchoring the bands to the latest confirmed weekly data, so the long-term reference is consistent and non-repainting across timeframes.
This is a macro “valuation/temperature gauge” style tool: it helps you quickly see when the price is cheap vs. the 200W mean and when it is extended/expensive.
What it plots
The indicator always computes:
200-week SMA (weekly)
Band m2
Band m3
Band m4
Bands are defined as:
Bandk(t)=SMA200W(t)⋅mk
Where the multipliers mk are chosen automatically depending on the asset type (or manually via input).
Key features
Works on any timeframe: weekly SMA is fetched via request.security(..., "W", ...).
Non-repainting weekly anchor: uses barmerge.lookahead_off to avoid peeking into future weekly bars.
Auto asset presets:
Crypto: wider extensions (bigger cycles)
Gold: moderate extensions
Equities: tighter than crypto
FX: very tight extensions
Futures: moderate fallback
Zone coloring (optional):
Cheap zone (below 1×)
Fair zone (1× → m2)
Hot zone (m2 → m3)
Expensive zone (m3 → m4)
Info table (optional): shows selected preset, current multiple, and % extension vs 200W SMA.
Alerts (optional): “entered cheap” and “entered expensive” style triggers.
Presets (default multipliers)
These are intentionally conservative templates (tune to your market):
Crypto: 1.0,1.5,2.0,3.0
Gold: 1.0,1.2,1.5,2.0
Equities: 1.0,1.15,1.30,1.60
FX: 1.0,1.05,1.10,1.20
Futures: 1.0,1.25,1.50,2.00
Auto mode uses syminfo.type plus a simple heuristic for Gold tickers containing XAU / GOLD (because some platforms classify XAUUSD as forex).
How to use (practical)
Macro context / cycle temperature
Price below 1× (200W SMA): historically “cheap zone” for highly cyclical assets (especially BTC).
Price above m3: often “expensive/extended” and higher risk of mean reversion.
Not a standalone trading system
Use with trend confirmation (market structure), volume, and risk management.
Extensions can persist in strong trends—treat bands as regime context, not precise reversal points.
Settings you can change
SMA Length (Weeks): default 200
Band preset: Auto / Crypto / Gold / Equities / FX / Futures
Toggle:
Zone fills
Info table
Alerts
Included alertconditions:
Cross below 1× (entered cheap zone)
Cross above m3 (entered expensive zone)
High level guideline:
Green Zone: BUY (Below 1.0× - Undervalued)
Yellow Zone: HOLD (1.0× - 1.5× - Fair Value)
Orange Zone: CAUTION (1.5× - 2.0× - Getting Hot)
Red Zone: SELL (2.0× - 3.0× - Overvalued)
Notes / limitations
The “cheap/expensive” zones are heuristics. They do not guarantee future returns.
Auto classification is best-effort; if your symbol is unusual, set the preset manually.
For newly listed assets with limited weekly history, the 200W SMA may be na until enough data exists.
Trinity 4 EMA MTF IndicatorThis is a 5mins scalping indicator based on the daily, 1hr, 15mins and 5 mins TF. Go long or short when all EMA are aligned.
EMA values and timeframe can be customized
EMA colors can also be customized
Evidenzia Data Specifica DinamicaSpecific Date Highlighter
Descrizione (Italiano)
Questo indicatore semplice ma estremamente efficace permette di evidenziare graficamente un'intera giornata specifica selezionata dall'utente. È lo strumento ideale per chi ha bisogno di analizzare il comportamento del prezzo durante eventi macroeconomici passati, date di earnings, o particolari sessioni storiche.
Caratteristiche principali:
Selettore Calendario Intuitivo: Grazie all'input di tipo time, puoi selezionare la data esatta tramite un calendario pop-up senza dover inserire manualmente numeri per giorno, mese e anno.
Compatibilità Multi-Timeframe: L'indicatore funziona su qualsiasi timeframe. Se sei su grafici intraday (1m, 5m, 1h), colorerà lo sfondo di tutte le candele appartenenti a quel giorno. Su grafici Daily, evidenzierà la singola candela selezionata.
Colore Personalizzabile: Puoi scegliere il colore dello sfondo e la sua opacità direttamente dalle impostazioni per adattarlo al tuo tema (Light o Dark).
Data Dinamica: Lo script è progettato per riconoscere automaticamente la data odierna come punto di partenza, facilitando l'analisi rapida dell'ultima sessione.
Casi d'uso:
Backtesting visivo: Evidenzia i giorni di rilascio dei dati CPI o decisioni FOMC per studiare la volatilità.
Journaling: Segna i giorni in cui hai effettuato trade importanti per ritrovarli facilmente nello storico.
Analisi Ciclica: Identifica rapidamente date specifiche in cui si sono verificati minimi o massimi storici.
Description (English)
This lightweight and effective tool allows you to highlight a specific full day on your chart. It is perfect for traders who need to visually isolate price action during macroeconomic events, earnings dates, or key historical sessions.
Key Features:
Calendar Picker: Easily select your target date using a built-in calendar input.
MTF Ready: Works seamlessly across all timeframes. On intraday charts, it highlights every bar within the 24-hour period. On daily charts, it highlights the specific daily candle.
Fully Customizable: Change the background color and transparency to match your chart layout.
Smart Default: The script is optimized to handle time logic correctly, ensuring the highlight starts exactly at 00:00 and ends at 23:59.
How to use: Go to settings, click on "Select Date", pick your day from the calendar, and the chart will instantly move the focus to that specific session.
Ale tonkis Swing failure + 5MIndicator Description: Ale Tonkis Swing Failure (SFP)
This script is an advanced Swing Failure Pattern (SFP) and Change in State of Delivery (CISD) indicator. It is designed to identify liquidity sweeps and market structure shifts across multiple timeframes simultaneously.
Key Features
Pivot Detection: Automatically identifies high and low pivot points based on a user-defined lookback period.
Liquidity Sweep Analysis: Detects when the price "sweeps" (goes beyond) a previous pivot high or low without closing significantly past it, signaling a potential reversal.
CISD (Change in State of Delivery): Tracks internal market structure shifts to confirm the SFP signal.
Multi-Timeframe (MTF) Dashboard: A real-time table in the top-right corner monitors the trend state across four different timeframes: M1, M3, M5, and M15.
Visual Alerts: The script uses dynamic bar coloring and labels (▲/▼) to signal entry points directly on the chart.
Technical Updates (M5 Integration)
The code has been specifically modified to include the 5-minute (M5) timeframe within the Multi-Timeframe logic:
Data Fetching: A new request.security call was added to retrieve the sfp_trend_state from the 5-minute interval.
Table Expansion: The display table was resized from 4 rows to 5 rows to accommodate the new data without overlapping.
UI Alignment: The M5 state is now positioned between M3 and M15, providing a smoother transition for traders analyzing mid-range scalping opportunities.
How to Read the Dashboard
LONG (Green): Indicates a bullish SFP has occurred and the trend remains positive on that timeframe.
SHORT (Red): Indicates a bearish SFP has occurred and the trend remains negative.
Empty/Black: No active SFP trend is currently detected on that specific timeframe.
CURRY HEDGEFUND PRO (MTF/VWAP/ADX + Tight Trail) [no ta.adx]Improved HedgeFund Pro Script by Tony Curry for momentum and reversal trading. Primarily focused on ADX and directional movement.
BB Scoreboard MTF1. The Concept: Harmony Across TimeframesThe Musical Score Visual: This indicator transforms absolute price into a relative "score" based on standard deviations ($\sigma$). It displays the positions of Short-Term (15m), Mid-Term (1H), and Long-Term (4H) prices on a single grid, similar to a musical staff.Syncing the "Breath" of the Market: By aligning three different timeframes, you can instantly see if the entire market is "breathing" in the same direction.
2. Trading Logic: The Power of ConvergencePerfect Order (Bullish): When the Short, Mid, and Long-term lines are all above the Middle (0) line, it indicates a strong, synchronized uptrend. This is the highest probability zone for "Buy on Dip" strategies.Perfect Order (Bearish): Conversely, when all lines are below the Middle line, the market is in a synchronized downtrend, making "Sell on Rally" the dominant strategy.Overextension (The Limits): When all three lines hit the $+3\sigma$ or $-3\sigma$ levels simultaneously, the market is extremely overextended, signaling an imminent correction or exhaustion.
3. Synergizing with "Volume-Wall" (FVG)To achieve the Ultimate Scalping Setup:Alignment: Wait for all three lines on the "Scoreboard" to point in the same direction (e.g., all above 0).The Anchor: Price returns to a Strong FVG (Volume-Wall).The Trigger: Enter the trade when the Short-term line bounces off a lower $\sigma$ level and heads back toward the $+1\sigma$ or $+2\sigma$ area.
Money Flow Index (MFI) w/ Multi Time Frame DivergencesBack color MTF
Money Flow Index (MFI) w/ Multi Time Frame Divergences






















