Home » Color Functions » Understanding color.from_gradient() Function in Pine Script

Understanding color.from_gradient() Function in Pine Script

Photo of author
Published on

In this article, we will explore the color.from_gradient() function in Pine Script, used for creating color gradients in trading indicators. We’ll analyze two examples where this function plays a crucial role, enhancing the visual appeal and informational value of the Commodity Channel Index (CCI) indicator.

Example 1: Basic Gradient on CCI Indicator

//@version=5
indicator(title="CCI line gradient", precision=2, timeframe="")
var color GOLD_COLOR   = #CCCC00
var color VIOLET_COLOR = #AA00FF
var color BEIGE_COLOR  = #9C6E1B
float srcInput = input.source(close, title="Source")
int   lenInput = input.int(20, "Length", minval = 5)
color bullColorInput = input.color(GOLD_COLOR,   "Bull")
color bearColorInput = input.color(BEIGE_COLOR, "Bear")
float signal = ta.cci(srcInput, lenInput)
color signalColor = color.from_gradient(signal, -200, 200, bearColorInput, bullColorInput)
plot(signal, "CCI", signalColor)
bandTopPlotID = hline(100,  "Upper Band", color.silver, hline.style_dashed)
bandBotPlotID = hline(-100, "Lower Band", color.silver, hline.style_dashed)
fill(bandTopPlotID, bandBotPlotID, color.new(BEIGE_COLOR, 90), "Background")
Basic Gradient on CCI Indicator

Code Walkthrough

  1. Indicator Setup:
    • indicator() defines the script as an indicator with specific properties like title, precision, and timeframe.
    • var color lines define constant colors used later in the script.
  2. User Inputs:
    • input.source() and input.int() gather user inputs for the source (typically the closing price) and length of the CCI calculation.
    • input.color() gathers user inputs for bull and bear colors.
  3. CCI Calculation:
    • ta.cci(srcInput, lenInput) computes the CCI based on user inputs.
  4. Gradient Color Calculation:
    • color.from_gradient() is used to create a gradient color for the CCI line. It takes the CCI value (signal), a range (-200 to 200), and colors for the extremes of this range.
  5. Plotting:
    • plot() draws the CCI line with the gradient color.
    • Horizontal lines (hline()) and the fill between them (fill()) represent the overbought and oversold areas.

Key Points:

  • Gradient Colors: The gradient color depends on the CCI value, changing as the CCI moves within the -200 to 200 range.
  • Extremes Handling: If CCI goes beyond this range, it uses the extreme colors defined.
  • Color Progression: The progression between colors is linear.

Example 2: Enhanced CCI Indicator with Gradient Background

//@version=5
indicator(title="CCI line gradient", precision=2, timeframe="")
var color GOLD_COLOR     = #CCCC00
var color VIOLET_COLOR   = #AA00FF
var color GREEN_BG_COLOR = color.new(color.green, 70)
var color RED_BG_COLOR   = color.new(color.maroon, 70)
float srcInput      = input.source(close, "Source")
int   lenInput      = input.int(20, "Length", minval = 5)
int   stepsInput    = input.int(50, "Gradient levels", minval = 1)
color bullColorInput   = input.color(GOLD_COLOR, "Line: Bull", inline = "11")
color bearColorInput   = input.color(VIOLET_COLOR, "Bear", inline = "11")
color bullBgColorInput = input.color(GREEN_BG_COLOR, "Background: Bull", inline = "12")
color bearBgColorInput = input.color(RED_BG_COLOR, "Bear", inline = "12")

// Plot colored signal line.
float signal = ta.cci(srcInput, lenInput)
color signalColor = color.from_gradient(signal, -200, 200, color.new(bearColorInput, 0), color.new(bullColorInput, 0))
plot(signal, "CCI", signalColor, 2)

// Detect crosses of the centerline.
bool signalX = ta.cross(signal, 0)
int gradientStep = math.min(stepsInput, nz(ta.barssince(signalX)))
color endColor = signal > 0 ? bullBgColorInput : bearBgColorInput
color bandColor = color.from_gradient(gradientStep, 0, stepsInput, na, endColor)
bandTopPlotID = hline(100,  "Upper Band", color.silver, hline.style_dashed)
bandBotPlotID = hline(-100, "Lower Band", color.silver, hline.style_dashed)
fill(bandTopPlotID, bandBotPlotID, bandColor, title = "Band")
Enhanced CCI Indicator with Gradient Background

Code Walkthrough

In this enhanced version of the Commodity Channel Index (CCI) indicator, we introduce a dynamic gradient background in addition to the gradient-colored CCI line. This enhancement provides a visual representation of the duration for which the CCI has been in either bull or bear territory. Let’s break down the script to understand each component:

Script Setup and Inputs

//@version=5
indicator(title="CCI line gradient", precision=2, timeframe="")
var color GOLD_COLOR     = #CCCC00
var color VIOLET_COLOR   = #AA00FF
var color GREEN_BG_COLOR = color.new(color.green, 70)
var color RED_BG_COLOR   = color.new(color.maroon, 70)
float srcInput      = input.source(close, "Source")
int   lenInput      = input.int(20, "Length", minval = 5)
int   stepsInput    = input.int(50, "Gradient levels", minval = 1)
color bullColorInput   = input.color(GOLD_COLOR, "Line: Bull", inline = "11")
color bearColorInput   = input.color(VIOLET_COLOR, "Bear", inline = "11")
color bullBgColorInput = input.color(GREEN_BG_COLOR, "Background: Bull", inline = "12")
color bearBgColorInput = input.color(RED_BG_COLOR, "Bear", inline = "12")
  1. Color Variables: Sets up color variables for both the CCI line and the background.
  2. User Inputs: Gathers user inputs for the source and length of the CCI calculation, as well as the number of steps for the gradient and color choices for bull and bear conditions.

CCI Calculation and Line Plotting

float signal = ta.cci(srcInput, lenInput)
color signalColor = color.from_gradient(signal, -200, 200, color.new(bearColorInput, 0), color.new(bullColorInput, 0))
plot(signal, "CCI", signalColor, 2)
  1. Signal Calculation: Calculates the CCI value based on user-defined source and length.
  2. Gradient Color for CCI Line: Uses color.from_gradient() to assign a color to the CCI line, transitioning between bear and bull colors based on the CCI value.
  3. Plotting the CCI Line: Plots the CCI line with the gradient color and a thicker line width for better visibility.

Background Gradient Calculation

bool signalX = ta.cross(signal, 0)
int gradientStep = math.min(stepsInput, nz(ta.barssince(signalX)))
color endColor = signal > 0 ? bullBgColorInput : bearBgColorInput
color bandColor = color.from_gradient(gradientStep, 0, stepsInput, na, endColor)
bandTopPlotID = hline(100,  "Upper Band", color.silver, hline.style_dashed)
bandBotPlotID = hline(-100, "Lower Band", color.silver, hline.style_dashed)
fill(bandTopPlotID, bandBotPlotID, bandColor, title = "Band")
  1. Centerline Cross Detection: Detects when the CCI crosses its centerline (0).
  2. Gradient Step Calculation:
    • ta.barssince(signalX) counts the number of bars since the last centerline cross.
    • math.min(stepsInput, nz(...)) ensures that the count doesn’t exceed the maximum number of gradient steps set by the user.
  3. Background Color Determination:
    • endColor is set based on whether the CCI is above (bull) or below (bear) the centerline.
    • color.from_gradient() is used to create a gradient for the background fill, starting from transparent (na) and moving towards the endColor.
  4. Plotting the Background:
    • Horizontal lines (hline()) define the upper and lower bands of the CCI.
    • fill() creates a gradient fill between these bands, providing a visual indication of the time spent in bull/bear territory.

Key Insights

  • Dynamic Visualization: The gradient background dynamically reflects the duration of bull/bear conditions, adding a layer of information to the CCI indicator.
  • User Customization: Users have the flexibility to customize colors for both the CCI line and the background, enhancing the user experience and readability of the chart.
  • Enhanced Interpretability: The combination of gradient-colored line and background provides a richer, more nuanced view of market conditions, facilitating better decision-making for traders.

Leave a Comment