Selecciones de los editoresOPEN-SOURCE SCRIPT

Delta Volume Candles [LucF]

Actualizado
█ OVERVIEW


This indicator plots on-chart volume delta information using candles that can replace your normal candles, tops and bottoms appended to normal candles, optional MAs of those tops and bottoms levels, a divergence channel and a chart background. The indicator calculates volume delta using intrabar analysis, meaning that it uses the lower timeframe bars constituting each chart bar.



█ CONCEPTS


Volume Delta

​The ​volume delta concept divides a bar's ​volume in "up" and "down" ​volumes. The delta is calculated by subtracting down ​volume from up ​volume. Many calculation techniques exist to isolate up and down ​volume within a bar. The simplest use the polarity of interbar price changes to assign their ​volume to up or down slots, e.g., On Balance Volume or the Klinger Oscillator. Others such as Chaikin Money Flow use assumptions based on a bar's OHLC values. The most precise calculation method uses tick data and assigns the ​volume of each tick to the up or down slot depending on whether the transaction occurs at the bid or ask price. While this technique is ideal, it requires huge amounts of data on historical bars, which considerably limits the historical depth of charts and the number of symbols for which tick data is available. Furthermore, historical tick data is not yet available on TradingView.

This indicator uses intrabar analysis to achieve a compromise between the simplest and most precise methods of calculating ​volume delta. It is currently the most precise method usable on TradingView charts. TradingView's Volume Profile built-in indicators use it, as do the CVD - Cumulative ​Volume Delta Candles and CVD - Cumulative Volume Delta (Chart) indicators published from the TradingView account. My Delta Volume Channels and Volume Delta Columns Pro indicators also use intrabar analysis. Other ​volume delta indicators such as my Realtime 5D Profile use realtime chart updates to calculate volume delta without intrabar analysis, but that type of indicator only works in real time; they cannot calculate on historical bars.

This is the logic I use to determine the polarity of intrabars, which determines the up or down slot where its ​volume is added:
 • If the intrabar's open and close values are different, their relative position is used.
 • If the intrabar's open and close values are the same, the difference between the intrabar's close and the previous intrabar's close is used.
 • As a last resort, when there is no movement during an intrabar, and it closes at the same price as the previous intrabar, the last known polarity is used.

Once all intrabars making up a chart bar have been analyzed and the up or down property of each intrabar's ​volume determined, the up volumes are added, and the down volumes subtracted. The resulting value is ​volume delta for that chart bar, which can be used as an estimate of the buying/selling pressure on an instrument. Not all markets have volume information. Without it, this indicator is useless.


Intrabar analysis

[I]Intrabars are chart bars at a lower timeframe than the chart's. The timeframe used to access intrabars determines the number of intrabars accessible for each chart bar. On a 1H chart, each chart bar of an active market will, for example, usually contain 60 bars at the lower timeframe of 1min, provided there was market activity during each minute of the hour.

This indicator automatically calculates an appropriate lower timeframe using the chart's timeframe and the settings you use in the script's "Intrabars" section of the inputs. As it can access lower timeframes as small as seconds when available, the indicator can be used on charts at relatively small timeframes such as 1min, provided the market is active enough to produce bars at second timeframes.

The quantity of intrabars analyzed in each chart bar determines:
 • The precision of calculations (more intrabars yield more precise results).
 • The chart coverage of calculations (there is a 100K limit to the quantity of intrabars that can be analyzed on any chart,
  so the more intrabars you analyze per chart bar, the less chart bars can be calculated by the indicator).

The information box displayed at the bottom right of the chart shows the lower timeframe used for intrabars, as well as the average number of intrabars detected for chart bars and statistics on chart coverage.


Balances

This indicator calculates five balances from volume delta values. The balances are oscillators with a zero centerline; positive values are bullish, and negative values are bearish. It is important to understand the balances as they can be used to:
 • Color candle bodies.
 • Calculate body and top and bottom divergences.
 • Color an EMA channel.
 • Color the chart's background.
 • Configure markers and alerts.

The five balances are:

1 — [I]Bar Balance: This is the only balance using instant values; it is simply the subtraction of the down volume​ from the up volume​ on the bar, so the instant volume delta for that bar.
2 — [I]Average Balance: Calculates a distinct EMA for both the up and down volumes, and subtracts the down EMA from the up EMA.
  The result is akin to MACD's histogram because it is the subtraction of two moving averages.
3 — [I]Momentum Balance: Starts by calculating, separately for both up and down volumes, the difference between the same EMAs used in "Average Balance" and
  an SMA of twice the period used for the "Average Balance" EMAs. The difference for the up side is subtracted from the difference for the down side,
  and an RSI of that value is calculated and brought over the −50/+50 scale.
4 — [I]Relative Balance: The reference values used in the calculation are the up and down EMAs used in the "Average Balance".
  From those, we calculate two intermediate values using how much the instant up and down volumes on the bar exceed their respective EMA — but with a twist.
  If the bar's up volume​ does not exceed the EMA of up volume​, a zero value is used. The same goes for the down volume​ with the EMA of down volume​.
  Once we have our two intermediate values for the up and down volumes exceeding their respective MA, we subtract them. The final value is an ALMA of that subtraction.
  The rationale behind using zero values when the bar's up/down 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 up/down volumes and their respective MA.
  This balance flatlines when the bar's up/down 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 it will flatline. These flat zones should be considered no-trade zones.
5 — [I]Percent Balance: This balance is the ALMA of the ratio of the "Bar Balance" over the total volume for that bar.

From the balances and marker conditions, two more values are calculated:
1 — [I]Marker Bias: This 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 — [I]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.

The periods for all of these balances can be configured in the "Periods" section at the bottom of the script's inputs. As you cannot see the balances on the chart, you can use my Volume Delta Columns Pro indicator in a pane; it can plot the same balances, so you will be able to analyze them.


Divergences

In the context of this indicator, a divergence is any bar where the bear/bull state of a balance (above/below its zero centerline) diverges from the polarity of a chart bar. No directional bias is assigned to divergences when they occur. Candle bodies and tops/bottoms can each be colored differently on divergences detected from distinct balances.


Divergence Channel

The divergence channel is the space between two levels (by default, the bar's open and close) saved when divergences occur. When price (by default the close) has breached a channel and a new divergence occurs, a new channel is created. Until that new channel is breached, bars where additional divergences occur will expand the channel's levels if the bar's price points are outside the channel.

Prices breaches of the divergence channel will change its state. Divergence channels can be in one of three different states:
 • Bull (green): Price has breached the channel to the upside.
 • Bear (red): Price has breached the channel to the downside.
 • Neutral (gray): The channel has not yet been breached.



█ HOW TO USE THE INDICATOR


I do not make videos to explain how to use my indicators. I do, however, try hard to include in their description everything one needs to understand what they do. From there, it's up to you to explore and figure out if they can be useful in your trading practice. Communicating in videos what this description and the script's tooltips contain would make for very long videos that would likely exceed the attention span of most people who find this description too long. There is no quick way to understand an indicator such as this one because it uses many different concepts and has quite a bit of settings one can use to modify its visuals and behavior — thus how one uses it. I will happily answer questions on the inner workings of the indicator, but I do not answer questions like "How do I trade using this indicator?" A useful answer to that question would require an in-depth analysis of who you are, your trading methodology and objectives, which I do not have time for. I do not teach trading.

Start by loading the indicator on an active chart containing volume information. See here if you need help.

The default configuration displays:
 • Normal candles where the bodies are only colored if the bar's volume has increased since the last bar.
  If you want to use this indicator's candles, you may want to disable your chart's candles by clicking the eye icon to the right of the symbol's name in the top left of the chart.
 • A top or bottom appended to the normal candles. It represents the difference between up and down volume for that bar
  and is positioned at the top or bottom, depending on its polarity. If up volume is greater than down volume, a top is displayed. If down volume is greater, a bottom is plotted.
  The size of tops and bottoms is determined by calculating a factor which is the proportion of volume delta over the bar's total volume.
  That factor is then used to calculate the top or bottom size relative to a baseline of the average candle body size of the last 100 bars.
 • An information box in the bottom right displaying intrabar and chart coverage information.
 • A light red background when the intrabar volume differs from the chart's volume by more than 1%.

The script's inputs contain tooltips explaining most of the fields. I will not repeat them here. Following is a brief description of each section of the indicator's inputs which will give you an idea of what the indicator can do:

Normal Candles is where you configure the replacement candles plotted by the script. You can choose from different coloring schemes for their bodies and specify a unique color for bodies where a divergence calculated using the method you choose occurs.

Volume Tops & Botttoms is where you configure the display of tops and bottoms, and their EMAs. The EMAs are calculated from the high point of tops and the low point of bottoms. They can act as a channel to evaluate price, and you can choose to color the channel using a gradient reflecting the advances/declines in the balance of your choice.

Divergence Channel is where you set up the appearance and behavior of the divergence channel. These areas represent levels where price and volume delta information do not converge. They can be interpreted as regions with no clear direction from where one will look for breaches. You can configure the channel to take into account one or both types of divergences you have configured for candle bodies and tops/bottoms.

Background allows you to configure a gradient background color that reflects the advances/declines in the balance of your choice. You can use this to provide context to the volume delta values from bars. You can also control the background color displayed on volume discrepancies between the intrabar and the chart's timeframe.

Intrabars is where you choose the calculation mode determining the lower timeframe used to access intrabars. The indicator uses the chart's timeframe and the type of market you are on to calculate the lower timeframe. Your setting there should reflect which compromise you prefer between the precision of calculations and chart coverage. This is also where you control the display of the information box in the lower right corner of the chart.

Markers allows you to control the plotting of chart markers on different conditions. Their configuration determines when alerts generated from the indicator will fire. Note that in order to generate alerts from this script, they must be created from your chart. See this Help Center page to learn how. Only the last 500 markers will be visible on the chart, but this will not affect the generation of alerts.

Periods is where you configure the periods for the balances and the EMAs used in the indicator.

The raw values calculated by this script can be inspected using the Data Window.



█ INTERPRETATION


Rightly or wrongly, volume delta is considered by many a useful complement to the interpretation of price action. I use it extensively in an attempt to find convergence between my read of volume delta and price movement — not so much as a predictor of future price movement. No system or person can predict the future. Accordingly, I consider people who speak or act as if they know the future with certainty to be dangerous to themselves and others; they are charlatans, imprudent or blissfully ignorant.

I try to avoid elaborate volume delta interpretation schemes involving too many variables and prefer to keep things simple:
 • Trends that have more chances of continuing should be accompanied by VD of the same polarity.
  In trends, I am looking for "slow and steady". I work from the assumption that traders and systems often overreact, which translates into unproductive volatility.
  Wild trends are more susceptible to overreactions.
 • I prefer steady VD values over wildly increasing ones, as large VD increases often come with increased price volatility, which can backfire.
  Large VD values caused by stopping volume will also often occur on trend reversals with abnormally high candles.
 • Prices escaping divergence channels may be leading a trend in that direction, although there is no telling how long that trend will last; could be just a few bars or hundreds.
  When price is in a channel, shifts in VD balances can sometimes give us an idea of the direction where price has the most chance of breaking.
 • Dwindling VD will often indicate trend exhaustion and predate reversals by many bars, but the problem is that mere pauses in a trend will often produce the same behavior in VD.
  I think it is too perilous to infer rigidly from VD decreases.


Divergence Channel

Here I have configured the divergence channels to be visible. First, I set the bodies to display divergences on the default Bar Balance. They are indicated by yellow bodies. Then I activated the divergence channels by choosing to draw levels on body divergences and checked the "Fill" checkbox to fill the channel with the same color as the levels. The divergence channel is best understood as a direction-less area from where a breach can be acted on if other variables converge with the breach's direction:
imagen


Tops and Bottoms EMAs

I find these EMAs rather interesting. They have no equivalent elsewhere, as they are calculated from the top and bottom values this indicator plots. The only similarity they have with volume-weighted MAs, including VWAP, is that they use price and volume. This indicator's Tops and Bottoms EMAs, however, use the price and volume delta. While the channel differs from other channels in how it is calculated, it can be used like others, as a baseline from which to evaluate price movement or, alternatively, as stop levels. Remember that you can change the period used for the EMAs in the "Periods" section of the inputs.

This chart shows the EMAs in action, filled with a gradient representing the advances/decline from the Momentum balance. Notice the anomaly in the chart's latest bars where the Momentum balance gradient has been indicating a bullish bias for some time, during which price was mostly below the EMAs. Price has just broken above the channel on positive VD. My interpretation of this situation would be that it is a risky opportunity for a long trade in the larger context where the market has been in a downtrend since the 5th. Intrepid traders choosing to enter here could do so with a "make or break" tight stop that will minimize their losses should the market continue its downtrend while hopefully preserving the potential upside of price continuing on the longer-term uptrend prevalent since the 28th:
imagen



█ NOTES


Volume

If you use indicators such as this one which depends on volume information, it is important to realize that the volume data they consume comes from data feeds, and that all data feeds are NOT created equally. Those who create the data feeds we use must make decisions concerning the nature of the transactions they tally and the way they are tallied in each feed, and these decisions affect the nature of our volume data. My Volume X-ray publication discusses some of the reasons why volume information from different timeframes, brokers/exchanges or sectors may vary considerably. I encourage you to read it. This indicator's display of a warning through a background color on volume discrepancies between the timeframe used to access intrabars and the chart's timeframe is an attempt to help you realize these variations in feeds. Don't take things for granted, and understand that the quality of a given feed's volume information affects the quality of the results this indicator calculates.


Markets as ecosystems

I believe it is perilous to think that behavioral patterns you discover in one market through the lens of this or any other indicator will necessarily port to other markets. While this may sometimes be the case, it will often not. Why is that? Because each market is its own ecosystem. As cities do, all markets share some common characteristics, but they also all have their idiosyncrasies. A proportion of a city's inhabitants is always composed of outsiders who come and go, but a core population of regulars and systems is usually the force that actually defines most of the city's observable characteristics. I believe markets work somewhat the same way; they may look the same, but if you live there for a while and pay attention, you will notice the idiosyncrasies. Some things that work in some markets will, accordingly, not work in others. Please keep that in mind when you draw conclusions.


On Up/Down or 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. 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, just as when buy market orders take out limit ask orders in the order book at successively higher levels. The built-in volume indicator available on TradingView uses this logic to color the volume columns green or red. While this script’s calculations are more precise because it analyses intrabars to calculate its information, it uses pretty much the same imperfect logic. Until Pine scripts can have access to how much volume was transacted at the bid/ask prices, our volume delta calculations will remain a mere proxy.


Repainting

 • The values calculated on the realtime bar will update as new information comes from the feed.
 • Historical values may recalculate if the historical feed is updated or when calculations start from a new point in history.
 • Markers and alerts will not repaint as they only occur on a bar's close. Keep this in mind when viewing markers on historical bars,
  where one could understandably and incorrectly assume they appear at the bar's open.

To learn more about repainting, see the Pine Script™ User Manual's page on the subject.


Superfluity

In "The Bed of Procrustes", Nassim Nicholas Taleb writes: [I]To bankrupt a fool, give him information. This indicator can display a lot of information. The inevitable adaptation period you will need to figure out how to use it should help you eliminate all the visuals you do not need. The more you eliminate, the easier it will be to focus on those that are the most useful to your trading practice. Don't be a fool.



█ THANKS


Thanks to alexgrover for his Dekidaka-Ashi indicator. His volume plots on candles were the inspiration for my top/bottom plots.

Kudos to PineCoders for their libraries. I use two of them in this script: Time and lower_tf.

The first versions of this script used functionality that I would not have known about were it not for these two guys:
— A guy called Kuan who commented on a Backtest Rookies presentation of their Volume Profile indicator.
theheirophant, my partner in the exploration of the sometimes weird abysses of request.security()’s behavior at lower timeframes.
Notas de prensa
Updated comments.
Notas de prensa
Tidied up comments and code.
Notas de prensa
  
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.
Notas de prensa
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.

Setup:
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.
Notas de prensa
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.

NOTE
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.
Notas de prensa
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.
Notas de prensa
v8
This is a major update; some of the default settings have changed, and functionality was vastly improved:
• Seconds timeframes can now be used to access intrabars when available,
 meaning the indicator can be used on chart timeframes as small as 1min or even seconds if market activity is sufficient to create enough intrabars.
• Gone are the limitations on chart timeframes where the indicator will work; it should work on the timeframe of your choice.
• Inputs have been completely redesigned, and verbose tooltips were added.
• Tops and bottoms can now be sized using the average size of the last 100 bodies, making it easier to evaluate their size relative to the tops and bottoms of other bars.
• The indicator now works in real time without the need to activate a special setting. The realtime bar will update on each chart update.
• The script's description was adapted and augmented to reflect its current functionality.
• Code was converted to Pine Script™ v5 and to use request.security_lower_tf(), significantly improving its performance.
balancecandlesdeltavolumedeltaVolume

Script de código abierto

Siguiendo fielmente el espíritu de TradingView, el autor de este script lo ha publicado en código abierto, permitiendo que otros traders puedan entenderlo y verificarlo. ¡Olé por el autor! Puede utilizarlo de forma gratuita, pero tenga en cuenta que la reutilización de este código en la publicación se rige por las Normas internas. Puede añadir este script a sus favoritos y usarlo en un gráfico.

¿Quiere utilizar este script en un gráfico?


"The stock market is a device for transferring money from the impatient to the patient."
— Buffet

tradingview.com/u/PineCoders/
tradingview.com/u/TradingView/
También en:

Exención de responsabilidad