Delta Volume Candles [LucF]

This indicator plots replacement candles colored using delta volume information calculated with intrabar inspection. It can also help visualize delta volume by appending top and bottom segments to candles and plotting their averages.

TradingView has good built-in Volume Profile tools to view volume information in price layers, but there is no powerful tool on the platform to visualize bar-by-bar buy/sell volume . This is what "Delta Volume Candles" attempts to realize. It uses the same intrabar inspection technique my "Delta Volume Columns" indicator uses but presents the information on the chart. Intrabar inspection means the indicator looks at lower timeframe bars making up a given chart bar to gather a finer level of detail on its constituent volume , dividing it into buy/sell/neutral categories by looking at price movement during intrabars.

The indicator plots three components on the chart:
1 — Candles
2 — Candle tops/bottoms
3 — A moving average of tops and bottoms

1 — Disable normal candles from your chart. Because this indicator plots its own candles, you will need to disable the standard candles from your chart.
  You can use one of three methods to do this:
  a) You can click the "Hide" icon to the right of the symbol's name on the chart.
  b) If you normally use candlesticks , you can disable them by going to "Chart Settings/Symbol" and unchecking the "Bodies", "Borders" and "Wick" checkboxes.
  c) If you prefer to keep your normal candlestick configuration intact for instances when you will not be using this indicator,
   you may instead disable the display of another type of chart (e.g., Line) and choose that type of chart when using "Delta Volume Candles".
2 — Select your chart's background color, your preferred candle colors, coloring method, and how to display divergences on candle bodies.
3 — Choose if you want to display the delta volume candle tops and bottoms, their divergences and the coloring method for both.
4 — Configure the display of the MAs for the tops and bottoms.
5 — Voilà!

Volume Balance
As its name implies, the focus in this indicator is on the balance between buying and selling volume—not the representation of total volume such as can be viewed on normal volume bars you'll see at the bottom of charts. We will refer to "volume balance" as the relative importance of buy/sell volume . Three types of calculation methods are used to determine volume balance in "Delta Volume Candles":
1 — Volume Balance on Bar: Uses the relative importance of buy/sell volume as a percentage of the bar's total volume .
2 — Volume Balance Average: Uses the difference between the value of the buy volume EMA and the sell volume EMA .
3 — Volume Balance Momentum: Starts by calculating, separately for both buy and sell volumes, the difference between the same EMAs used in the previous mode and an SMA of double the period used for the EMA . These differences are then aggregated and finally, a bounded momentum of that aggregate is calculated using RSI so that a +/- percentage around the 50 center line can be derived.

A different type of divergence is calculated for each of the three volume balance calculation methods. Divergences occur whenever the bull/bear bias of the method used diverges with the bar's price direction.

1 — Candles
• Select the body coloring mode among seven possibilities, including two with progressive gradient schemes.
• You can select your bull and bear body colors and their brightness.
• The control of borders and wicks is independent from the body settings. Candle borders and wicks are always colored using the bar's price information.
• You control the display of divergences with independent color and brightness.
• You can empty the bodies of bars when volume is not increasing. As with my TLD indicator, this decreases the visual importance of candles whose price movement is not supported by volume , as they tend to be less significant.

2 — Candle Tops/Bottoms
• Display supplemental top and bottom segments on candles using:
  a) Volume Balance on Bar: The height is determined by the relative value of buy/sell volume expressed as a percentage of the candle's body size.
  b) Volume Balance Momentum: The height is determined by the relative value of momentum in its scale, expressed as a percentage of the candle's body size.
   Note that since momentum is either bullish or bearish , only one (top or bottom) segment is plotted in this mode.
• You choose your own bull/bear colors, which can be independent of candle colors. You can thus make the delta volume information more or less prominent.
• You can vary the brightness of the dominant top/bottom fill.
• You also control the display of divergences with independent color and brightness. The type of divergence will depend on the calculation mode of the tops/bottoms.

3 — Moving Averages of Tops/Bottoms
• Displays EMAs for the volume tops/bottoms. When no top/bottom exists for a candle, its high/low is used instead.
• You can select the calculation mode used, and the color and brightness of the EMAs.

4 — Intrabar Resolution
You can choose between three modes. Two of them are automatic and one is manual.
  a) Fast Auto-Steps: Optimized for speed.
  b) More Precise Auto-Steps: Uses finer intrabar resolution, so will be slower.
  c) FIxed: Uses the fixed resolution of your choice.
You can also choose to view the intrabar resolution currently used to calculate delta volume .
The proper selection of the intrabar resolution is important. It must achieve maximal granularity to produce precise results while not unduly slowing down calculations, or worse, causing runtime errors.

5 — Total Volume Discrepancies
Stock exchanges do not report the same volume for intraday and daily (or higher) resolutions. This will often cause discrepancies between the total volume calculated using intraday and daily bars. Unless the additional volume information available on daily charts changes the delta volume balance, this will not invalidate the information displayed by the indicator. A mechanism to detect intraday and daily volume discrepancies is nonetheless provided. It allows you to define a threshold percentage above which the background will indicate a difference has been detected.

6 — Markers
Four markers are available:
Bumps: A bump up is defined as an up bar with increasing bullish volume balance higher than its EMA .
Double Bumps: Two bumps in a row, accompanied by successive closes in the same direction as the two bumps.
Divergences: One of the three types of volume balance calculations can be used to detect divergences with price.
Volume Balance Shifts: These are bull/bear transitions of either the Volume Balance Average or the Volume Balance Momentum states.
Markers appear when the required condition has been confirmed on the previous bar. They will not repaint.

7 — Settings
The Settings section of the indicator's Inputs allows control over the periods of the different moving averages used in calculations.

• This script uses a special characteristic of the `security()` function allowing intrabar inspection which is not officially supported by TradingView. It has the advantage of permitting a more robust calculation of delta volume , but it also has its limits.
• The method used does not work on the realtime bar—only on historical bars. As no delta volume information can be gathered during the realtime bar, the candle will be just like a normal one until that bar closes and becomes a historical bar.
• The indicator only works on some chart resolutions: 5, 10, 15 and 30 minutes, 1, 2, 4, 6, and 12 hours, 1 day, 1 week and 1 month. The script’s code can be modified to run on other resolutions, but chart resolutions must be divisible by the lower resolution used for intrabars and the stepping mechanism could require adaptation.
• On daily data reported by exchanges, the volume information for block, spread, and market trades are included, but these are typically not included in intraday bars as the information is not yet available then. This will cause some discrepancies between total volume calculated using intraday and daily bars. Note that this does not jeopardize the indicator's capacity to calculate delta volume , but it may cause discrepancies between the total volume numbers. This indicator does not display total volume , so the impact should be limited.
• When the difference between the chart’s resolution and the intrabar resolution is too great, runtime errors will occur. The Auto-Steps selection mechanisms should avoid this most of the time.
• The script only plots information that is reliable in the realtime bar, i.e., total volume and markers. All other plots are set to `na` to prevent misleading traders.
• The display of "Delta Volume Candles" is not as fast as regular candles, but given the amount of data crunching happening behind the scenes, its speed is tolerable. TradingView's server-side execution of Pine scripts is truly awesome.
• Alerts do not work reliably when `security()` is used at intrabar resolutions. No alerts are configured in the indicator.
• Not all markets have volume information. Without it, this indicator is useless. 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 delta volume 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 delta volume information.

On Delta Volume
Volume is arguably the best complement to interpret price action. In periods of low-volatility price consolidations, volume will typically also be lower than normal. Even so, 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 balance 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 reversals fascinates many traders to no end, they represent poor opportunities in my view. Volume imbalances often precede reversals, but I prefer to use delta volume 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 2 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.
Without access to order book information, traders work with the assumption that when price moves up during a bar, there was more buying pressure than selling pressure. The built-in volume indicator available on TradingView uses this logic to color the volume columns green or red. While this script’s numbers are more precise because it analyses a number of intrabars to calculate its information, it uses the exact same imperfect logic.
Until Pine scripts can have access to how much volume was transacted at the bid/ask prices, our delta volume information will be a mere proxy.

You may wonder how there can be divergences between buying/selling volume information and price movement. This will sometimes be due to the methodology’s shortcomings we have just discussed, 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. I do not share the overwhelming enthusiasm traders have for divergences. 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.

In "The Bed of Procrustes", Nassim Nicholas Taleb writes: To bankrupt a fool, give him information. "Delta Volume Candles" can display much more information than normal candlesticks , and 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 "Delta Volume Candles" and decide to adopt it, rigorously eliminate the information you don't use and configure the remaining information's display so that its visual prominence reflects its relative importance in your analysis.

— A guy called Kuan who commented on a Backtest Rookies presentation of their Volume Profile indicator using a `for` loop.
 The heart of my Delta Volume Candles indicator is code borrowed from Kuan; I just built a hopefully useful wrapper around it.
alexgrover for his Dekidaka-Ashi indicator. His volume plots on candles were the inspiration for my top/bottom plots.
theheirophant, my partner in the exploration of the sometimes weird abysses of `security()`’s behavior at lower resolutions.
Versionshinweise: Updated comments.
Versionshinweise: Tidied up comments and code.
Versionshinweise: I added a new marker: #5. It sums the bull/bear occurrences of the 4 other markers over a user-defined period (the default is 10). This forms the Markers Bias. The new marker uses its bull/bear transitions. The Markers Bias can also be used to color either the space between the MAs or the background, using a gradient calculated on the advances/declines of the bias, and its bull/bear state. The fill uses the same colors as the MAs. Note that your choice of the calculation method for markers 3 and 4 is used when calculating the Markers Bias, even if those markers are not being shown on the chart.
Versionshinweise: Version 1.4 & 1.5 Changes

Chart Background Color
I have eliminated the need to define the chart background color. It was used to hollow out candle bodies when the volume didn't increase on that bar (when the corresponding option was selected, as it is by default). Instead, I don't use any color on the bodies now, which makes them see-through. It has the slight disadvantage of showing what's behind the body, but it allows the indicator to show decreasing volume bars on any chart background.

Divergence display on candle bodies
I have increased the priority of the display of divergences on bodies when they occur on decreasing volume bars and the option to empty bodies on decreasing volume is also selected. Before this update, emptying the body had precedence over showing divergences. Now, divergences have priority, so they will always show, even when volume is decreasing on the bar where they occur.

Divergence Levels
I have added a new component, which automatically builds dynamic levels based on divergences.

1 — Select the "Mode" to determine which of the 3 types of divergence you want the levels to be calculated on.
  One type of divergence corresponds to each of the 3 types of "volume balances" the indicator can use.
  It will be easier to follow the levels logic if your candle bodies use the same type of divergence (determined by the "Mode" you use for the candles).
2 — Choose the "Hi/Lo levels" you want to use to define the divergence levels. "Full Range" refers to the total height of candles, including the volume tops/bottoms,
  which may or may not be higher/lower than the candle's high/low. You can also choose Tops/Bottoms, High/Low or Open/Close.
  When a new divergence level is created, this setting determines which value the indicator will use to create it.
3 — Specify the "Breach Reference", i.e., what condition is used to determine when a divergence level has been breached.
  When a range is selected, the whole range must be outside the levels for the breach condition to be true.
  When a level is used, only one of the levels needs to breach the divergence levels.
4 — Three colors and a common brightness are associated to the possible states for the levels: Bull means the breach reference is higher than the levels,
  Bear means it's lower, and Neutral means the breach reference level(s) is between the levels.
5 — Choose if you want to fill the levels.

How it works:
• When a divergence occurs, the user-defined hi/lo levels determine where a new set of levels starts.
• Until there is a breach, levels will expand with each new divergence that is found, if the hi/lo levels on that bar are higher/lower than the current divergence levels.
• When a breach is detected, levels enter a mode where they will reset (rather than expand) on a new divergence. If that divergence happens to be on the bar where the breach occurs,
 they will reset immediately, but a new divergence may also only happen after 10 bars. Until that happens, the levels will remain unchanged.
• After a breach has occurred, the brightness of the levels will increase to its maximum. This is the only visual clue signaling a breach has occurred (other than the candle itself),
 so in order for you to see the difference, it's best to use a normal brightness level that will allow you to easily distinguish both brightnesses if you want to monitor breaches.
Versionshinweise: Version 1.4 & 1.5 Changes (continued)

The behavior of the divergence levels is heavily dependent on 3 parameters:
1— The "Mode" which determines the type of divergence that is detected. There are 3.
2— The "Hi/Lo levels" used to position levels. There are 4.
3— The "Breach Reference" used to determine when a breach occurs. There are 7.
Different permutations will produce drastically different behavior, from slow to very jumpy resets of the levels. It is up to you to figure out which combination suits your needs the best. When resets are slow, the levels will perform very well in identifying consolidation areas. A more jumpy mode will benefit traders looking for faster signals.

This implementation of the divergence levels corresponds to my view that divergences indicate anomalies, hesitations, points of uncertainty if you will. It excludes the association of a bullish/bearish bias to divergences. Accordingly, the levels merely take note of divergence events and mark those points in time with levels, so traders have a reference point from which they can evaluate further price movement. The bull/bear/neutral colors used to plot the levels are also congruent with this view in that they are determined by price's position relative to the levels, which is how I think divergences can be put to the most effective use. Again, as I stated in the script's original description, my interpretation of divergences is based on random observation; I do not have hard numbers to justify it.

Changes to the script's Inputs will sometimes require ~20 seconds to materialize on the chart. Be patient. Luckily, response time is much faster when only changing symbols or the chart's timeframe.
Versionshinweise: v7.0
• The problem where the indicator no longer plotted was fixed.
• Markers are now displayed as labels, which entails that only the last 500 markers will show.
• The script does not yet create alert events, but a coming update that will produce more reliable results in realtime will also allow you to create alerts on the five different marker conditions.
• Markers only appear at the close of the realtime bar.
Open-source Skript

Ganz im Sinne von TradingView hat der Autor dieses Skripts es als Open-Source veröffentlicht, damit Trader es verstehen und überprüfen können. Ein Hoch auf den Autor! Sie können es kostenlos verwenden, aber die Wiederverwendung dieses Codes in einer Publikation unterliegt den Hausregeln. Sie können das Skript den Favoriten hinzufügen, um es auf dem Chart zu verwenden.

Möchten Sie dieses Skript auf einem Chart verwenden?
"The stock market is a device for transferring money from the impatient to the patient."
— Buffet

Tools and ideas for all Pine coders: