Histograms are a powerful visual tool in technical analysis, providing insights into momentum, volume distribution, and volatility. As a Pine Script developer, mastering their creation allows you to build more intuitive and informative indicators.
Introduction to Histograms in TradingView Pine Script
What is a Histogram and its Use in Trading?
A histogram is a bar chart where the height of each bar represents the frequency or magnitude of a specific value within a given range or over a period. In trading, histograms are widely used to visualize:
- Momentum: Indicators like MACD or Awesome Oscillator use histograms to show the strength and direction of price momentum.
- Volume: Volume histograms display the amount of trading activity over discrete time periods.
- Distribution: While less common for standard indicators, histograms can represent the distribution of price levels (Volume Profile, although this is a different concept than indicator histograms) or indicator values.
The key utility lies in their ability to clearly show divergences, crossovers, and shifts in magnitude that might be less apparent in line plots.
Why Use Pine Script for Creating Histograms?
Pine Script is TradingView’s proprietary scripting language, designed specifically for creating custom indicators, strategies, and alerts. Its syntax is relatively simple yet powerful, making it an ideal environment for developing custom histograms because:
- It provides built-in functions (
plot,plotshape) specifically designed for plotting various data types, including histograms. - It offers extensive control over visual elements like color, style, and size.
- Integration with TradingView’s charting platform is seamless, allowing instant application and backtesting.
- Access to a wide range of built-in variables (close, volume, etc.) and functions simplifies indicator calculations.
Creating a histogram in Pine Script allows traders to visualize the specific data they deem important, tailored to their unique trading strategies.
Basic Syntax and Structure for Plotting Histograms
The primary function for plotting a standard histogram in Pine Script is plot(). You achieve the histogram style by setting the style argument to plot.style_histogram.
The basic syntax looks like this:
//@version=5
indicator("My Basic Histogram", overlay=false)
// Calculate a value you want to plot as a histogram
// Example: Difference between two moving averages
fast_ma = ta.sma(close, 10)
slow_ma = ta.sma(close, 30)
ma_diff = fast_ma - slow_ma
// Plot the difference as a histogram
plot(ma_diff, title="MA Difference", style=plot.style_histogram)
In this example, ma_diff is the series of values calculated on each bar. plot() takes this series and renders it as a histogram. The overlay=false argument in indicator() is crucial because histograms often represent values not directly on the price scale (like MACD, RSI values), and plotting them on a separate pane is standard practice.
The plotshape Function for Plotting Histograms in Pine Script
While plot with style=plot.style_histogram is the standard way to draw the histogram bars themselves, the plotshape function serves a different but related purpose. It’s used to draw shapes (like arrows, circles, squares) on the chart at specific bar locations where a condition is met. You might use plotshape in conjunction with a histogram to mark specific points of interest derived from the histogram’s value.
Understanding the plotshape Function Parameters
plotshape has several parameters, but the most important for marking points based on histogram values are:
series: A boolean series (trueorfalse) that determines when the shape is plotted. A shape is drawn only when this series istrueon a given bar.title: A name for the plot.style: The type of shape to plot (e.g.,shape.arrowup,shape.circledot,shape.xcross).color: The color of the shape.location: Where to plot the shape relative to the bar (e.g.,location.belowbar,location.abovebar,location.top,location.bottom,location.absolute).size: The size of the shape (size.tiny,size.small,size.normal,size.large,size.huge).
Customizing the Appearance: Color, Style, and Size
Customization is key to making a histogram readable and informative. The plot function offers extensive options:
color: Set a static color (color=color.blue) or a dynamic color based on conditions (color=ma_diff >= 0 ? color.green : color.red). This is common for showing positive vs. negative values.style: Alwaysplot.style_histogramfor a standard histogram.linewidth: Controls the thickness of the histogram bar outlines (typically 1 or 2).transp: Sets transparency (0 for opaque, 100 for fully transparent).show_last: Plot only the last N bars.trackprice: Show the exact value on the price scale tooltip.
Combining these allows for clear visual distinctions. For instance, a MACD histogram is often colored based on whether it’s above or below the zero line, and sometimes based on whether the current bar is higher or lower than the previous bar (indicating acceleration or deceleration).
Plotting Different Types of Histograms
The plot(..., style=plot.style_histogram) approach is versatile. Any calculated numerical series can be plotted this way. Examples include:
- Difference Series: Like the MACD histogram (MACD line minus Signal line) or the difference between two moving averages.
- Rate of Change: Plotting the bar-to-bar change in an indicator value.
- Normalized Values: An indicator’s value normalized to a range (e.g., 0-100) and plotted as a histogram.
- Oscillator Values: RSI minus 50, Stochastics difference, etc.
The type of histogram depends entirely on the calculation you provide as the series argument to the plot() function.
Plotting Histograms Based on Price Action
Histograms are frequently used to visualize aspects derived from price action, such as volume or momentum calculated from prices.
Volume Histograms: Visualizing Trading Activity
The simplest and most direct histogram from price action is the volume histogram. Pine Script provides the built-in volume variable for this.
//@version=5
indicator("Volume Histogram", overlay=false)
// Plot volume as a histogram
plot(volume, title="Volume", style=plot.style_histogram,
color=volume >= ta.sma(volume, 20) ? color.teal : color.gray,
transp=30)
This code plots the raw volume for each bar as a histogram. A common addition is coloring the bars based on whether volume is increasing, decreasing, or above/below its average, as shown in the example.
RSI Histograms: Identifying Overbought and Oversold Conditions
While RSI itself is typically plotted as a line, you can create a histogram to highlight its relationship to key levels (like 50, 70, 30) or visualize its momentum. A simple approach is to plot RSI - 50 or color bars based on RSI zones.
//@version=5
indicator("RSI Deviation Histogram", overlay=false)
rsi_length = input.int(14, "RSI Length")
rsi_value = ta.rsi(close, rsi_length)
// Plot RSI deviation from 50 as a histogram
// Positive values above 50, negative below 50
plot(rsi_value - 50, title="RSI Dev", style=plot.style_histogram,
color=(rsi_value > 50 ? color.green : color.red),
transp=20)
// Optionally plot horizontal lines for 0 (RSI 50), 20 (RSI 70), -20 (RSI 30)
hline(0, "50 Level", color=color.gray)
hline(20, "70 Level", color=color.gray, linestyle=hline.style_dashed)
hline(-20, "30 Level", color=color.gray, linestyle=hline.style_dashed)
This histogram clearly shows when RSI is in bullish (above 0 line) or bearish (below 0 line) territory relative to the 50 level, and the magnitude indicates strength.
MACD Histograms: Spotting Momentum Changes
The MACD histogram is one of the most popular momentum indicators, representing the difference between the MACD line and the Signal line. Pine Script has a built-in ta.macd() function that returns the MACD line, Signal line, and the Histogram series.
//@version=5
indicator("MACD Histogram", overlay=false)
fast_len = input.int(12, "Fast Length")
slow_len = input.int(26, "Slow Length")
signal_len = input.int(9, "Signal Length")
[macd_line, signal_line, hist_line] = ta.macd(close, fast_len, slow_len, signal_len)
// Plot the built-in histogram series
plot(hist_line, title="MACD Histogram", style=plot.style_histogram,
color=hist_line >= 0 ? (hist_line > hist_line[1] ? color.green : color.red) : (hist_line < hist_line[1] ? color.maroon : color.lime),
transp=0)
// Optional: plot MACD and Signal lines
// plot(macd_line, title="MACD Line", color=color.blue)
// plot(signal_line, title="Signal Line", color=color.orange)
// Plot zero line
hline(0, "Zero Line", color=color.gray)
This example uses the hist_line directly from the ta.macd tuple. The coloring logic is a common way to show not just positive/negative momentum but also accelerating/decelerating momentum (color changing shade based on current vs. previous bar).
Advanced Histogram Techniques and Customization
Going beyond basic plotting allows for more dynamic and informative histograms.
Adding Alerts and Conditions to Histograms
You can trigger alerts based on the values or behavior of your histogram using the alertcondition() and alert() functions.
// ... (previous MACD Histogram code) ...
// Define alert conditions based on histogram
// Alert when histogram crosses above zero
alertcondition(ta.crossover(hist_line, 0), "MACD Hist Cross Above Zero", "MACD Histogram crossed above zero")
// Alert when histogram peaks (higher than prev 2 bars and lower than next 2 bars - simplified)
// Note: Cannot use forward-looking index [i+1], need alternative logic or simpler conditions
// Example: Alert on a potential peak/trough (simplified: current bar is highest/lowest in a small window)
is_peak = hist_line > hist_line[1] and hist_line[1] > hist_line[2] and hist_line[1] > hist_line[3]
is_trough = hist_line < hist_line[1] and hist_line[1] < hist_line[2] and hist_line[1] < hist_line[3]
alertcondition(is_peak, "MACD Hist Peak", "MACD Histogram potential peak")
alertcondition(is_trough, "MACD Hist Trough", "MACD Histogram potential trough")
// To trigger an alert from a strategy or specific logic:
// if (strategy.position_size == 0 and ta.crossover(hist_line, 0))
// alert("MACD Histogram buy signal", alert.freq_once_per_bar_close)
alertcondition defines the trigger visible in the TradingView ‘Alerts’ menu. alert is used within strategy code or indicator logic (often requiring alert.freq_once_per_bar or alert.freq_once_per_bar_close) to send a message.
Combining Multiple Histograms for Deeper Analysis
Pine Script allows plotting multiple series on the same pane or overlaid. You can plot two related histograms or a histogram and a line plot together.
//@version=5
indicator("Dual MACD Histograms", overlay=false)
// Standard MACD
[macd1_line, signal1_line, hist1_line] = ta.macd(close, 12, 26, 9)
// Faster MACD
[macd2_line, signal2_line, hist2_line] = ta.macd(close, 6, 13, 5)
// Plot slower MACD histogram
plot(hist1_line, title="Slow MACD Hist", style=plot.style_histogram, color=color.blue, transp=0)
// Plot faster MACD histogram (can be overlaid if values are comparable or on different y-axes if needed - though different y-axes for histograms on the same pane is tricky)
// A common approach is to plot on different sub-panes or use color/transparency to distinguish
plot(hist2_line, title="Fast MACD Hist", style=plot.style_histogram, color=color.purple, transp=50)
hline(0, "Zero Line", color=color.gray)
Plotting histograms with different transparency levels or slightly offset can help visualize relationships, though careful color choice and pane management are needed to avoid clutter.
Creating Interactive Histograms with User Inputs
Using input() allows users to customize the parameters of your histogram indicator directly from the indicator’s settings menu.
//@version=5
indicator("Customizable MACD Histogram", overlay=false)
// User Inputs for lengths
fast_len = input.int(12, title="Fast Length", minval=1)
slow_len = input.int(26, title="Slow Length", minval=1)
signal_len = input.int(9, title="Signal Length", minval=1)
bar_colors = input.bool(true, title="Color Bars Based on Momentum?")
[macd_line, signal_line, hist_line] = ta.macd(close, fast_len, slow_len, signal_len)
// Dynamic color based on input setting
hist_color = if bar_colors
if hist_line >= 0
hist_line > hist_line[1] ? color.green : color.red
else
hist_line < hist_line[1] ? color.maroon : color.lime
else
color.blue // Default color if bar coloring is off
plot(hist_line, title="MACD Histogram", style=plot.style_histogram,
color=hist_color,
transp=0)
hline(0, "Zero Line", color=color.gray)
Inputs make your indicators flexible, allowing traders to optimize parameters without editing the source code. You can add inputs for lengths, colors, boolean toggles for features, etc.
Practical Examples and Code Snippets
Let’s look at a few more specific examples.
Example 1: Simple Moving Average Histogram
This plots the difference between two SMAs, indicating divergence and convergence.
//@version=5
indicator("SMA Difference Histogram", overlay=false)
short_len = input.int(20, "Short SMA Length", minval=1)
long_len = input.int(50, "Long SMA Length", minval=1)
short_sma = ta.sma(close, short_len)
long_sma = ta.sma(close, long_len)
sma_diff = short_sma - long_sma
// Plot the difference
plot(sma_diff, title="SMA Difference", style=plot.style_histogram,
color=sma_diff >= 0 ? color.teal : color.orange,
transp=20)
// Zero line
hline(0, "Zero", color=color.gray)
Example 2: Volume Profile Histogram Proxy (Simplified)
Note: True Volume Profile requires aggregating volume per price level over a range of bars, which is complex. This example simply plots standard volume bars styled as a histogram, colored based on price movement, a common way to visualize volume’s relation to bullish/bearish activity.
//@version=5
indicator("Colored Volume Histogram", overlay=false)
// Color volume bars based on closing price relative to opening price
vol_color = close > open ? color.green : (close < open ? color.red : color.gray)
plot(volume, title="Volume", style=plot.style_histogram,
color=vol_color, transp=20)
// Optional: Add average volume line
avg_vol_len = input.int(20, "Avg Volume Length", minval=1)
avg_vol = ta.sma(volume, avg_vol_len)
plot(avg_vol, title="Avg Volume", color=color.blue, style=plot.style_line)
This visualizes volume magnitude and associates it with the direction of the bar, which is sometimes referred to loosely in the context of volume analysis.
Example 3: Dynamically Adjusted Histogram based on Timeframe
This example fetches a higher timeframe MACD histogram and plots it on the current chart’s pane. This is useful for understanding higher timeframe momentum context.
//@version=5
indicator("Higher Timeframe MACD Hist", shorttitle="HTF MACD", overlay=false)
// User Inputs for lengths and HTF
fast_len = input.int(12, title="Fast Length", minval=1)
slow_len = input.int(26, title="Slow Length", minval=1)
signal_len = input.int(9, title="Signal Length", minval=1)
htf = input.timeframe("60", title="Higher Timeframe") // Example: "60" for 1-hour, "D" for daily
// Fetch data from the higher timeframe
[htf_macd_line, htf_signal_line, htf_hist_line] = request.security(syminfo.tickerid, htf, ta.macd(close, fast_len, slow_len, signal_len), lookahead=barmerge.lookahead_on)
// Plot the higher timeframe histogram
plot(htf_hist_line, title=htf + " MACD Hist", style=plot.style_histogram,
color=htf_hist_line >= 0 ? color.blue : color.red,
transp=0)
hline(0, "Zero Line", color=color.gray)
Using request.security allows you to access data from any valid TradingView timeframe, enabling multi-timeframe histogram analysis on a single chart.
Mastering histogram plotting in Pine Script allows for creating sophisticated visual tools that can significantly enhance your analysis and strategy development process. By leveraging the plot function with style=plot.style_histogram and its numerous customization options, you can build indicators that provide clear, actionable insights.