PINE LIBRARY

Color

2 072
█ OVERVIEW


This library is a Pine Script® programming tool for advanced color processing. It provides a comprehensive set of functions for specifying and analyzing colors in various color spaces, mixing and manipulating colors, calculating custom gradients and schemes, detecting contrast, and converting colors to or from hexadecimal strings.



█ CONCEPTS


Color

Color refers to how we interpret light of different wavelengths in the visible spectrum. The colors we see from an object represent the light wavelengths that it reflects, emits, or transmits toward our eyes. Some colors, such as blue and red, correspond directly to parts of the spectrum. Others, such as magenta, arise from a combination of wavelengths to which our minds assign a single color.

The human interpretation of color lends itself to many uses in our world. In the context of financial data analysis, the effective use of color helps transform raw data into insights that users can understand at a glance. For example, colors can categorize series, signal market conditions and sessions, and emphasize patterns or relationships in data.


Color models and spaces

A color model is a general mathematical framework that describes colors using sets of numbers. A color space is an implementation of a specific color model that defines an exact range (gamut) of reproducible colors based on a set of primary colors, a reference white point, and sometimes additional parameters such as viewing conditions.

There are numerous different color spaces — each describing the characteristics of color in unique ways. Different spaces carry different advantages, depending on the application. Below, we provide a brief overview of the concepts underlying the color spaces supported by this library.

RGB
RGB is one of the most well-known color models. It represents color as an additive mixture of three primary colors — red, green, and blue lights — with various intensities. Each cone cell in the human eye responds more strongly to one of the three primaries, and the average person interprets the combination of these lights as a distinct color (e.g., pure red + pure green = yellow).

The sRGB color space is the most common RGB implementation. Developed by HP and Microsoft in the 1990s, sRGB provided a standardized baseline for representing color across CRT monitors of the era, which produced brightness levels that did not increase linearly with the input signal. To match displays and optimize brightness encoding for human sensitivity, sRGB applied a nonlinear transformation to linear RGB signals, often referred to as gamma correction. The result produced more visually pleasing outputs while maintaining a simple encoding. As such, sRGB quickly became a standard for digital color representation across devices and the web. To this day, it remains the default color space for most web-based content.

TradingView charts and Pine Script `color.*` built-ins process color data in sRGB. The red, green, and blue channels range from 0 to 255, where 0 represents no intensity, and 255 represents maximum intensity. Each combination of red, green, and blue values represents a distinct color, resulting in a total of 16,777,216 displayable colors.

CIE XYZ and xyY
The XYZ color space, developed by the International Commission on Illumination (CIE) in 1931, aims to describe all color sensations that a typical human can perceive. It is a cornerstone of color science, forming the basis for many color spaces used today. XYZ, and the derived xyY space, provide a universal representation of color that is not tethered to a particular display. Many widely used color spaces, including sRGB, are defined relative to XYZ or derived from it.

The CIE built the color space based on a series of experiments in which people matched colors they perceived from mixtures of lights. From these experiments, the CIE developed color-matching functions to calculate three components — X, Y, and Z — which together aim to describe a standard observer's response to visible light. X represents a weighted response to light across the color spectrum, with the highest contribution from long wavelengths (e.g., red). Y represents a weighted response to medium wavelengths (e.g., green), and it corresponds to a color's relative luminance (i.e., brightness). Z represents a weighted response to short wavelengths (e.g., blue).

From the XYZ space, the CIE developed the xyY chromaticity space, which separates a color's chromaticity (hue and colorfulness) from luminance. The CIE used this space to define the CIE 1931 chromaticity diagram, which represents the full range of visible colors at a given luminance. In color science and lighting design, xyY is a common means for specifying colors and visualizing the supported ranges of other color spaces.

CIELAB and Oklab
The CIELAB (L*a*b*) color space, derived from XYZ by the CIE in 1976, expresses colors based on opponent process theory. The L* component represents perceived lightness, and the a* and b* components represent the balance between opposing unique colors. The a* value specifies the balance between green and red, and the b* value specifies the balance between blue and yellow.

The primary intention of CIELAB was to provide a perceptually uniform color space, where fixed-size steps through the space correspond to uniform perceived changes in color. Although relatively uniform, the color space has been found to exhibit some non-uniformities, particularly in the blue part of the color spectrum. Regardless, modern applications often use CIELAB to estimate perceived color differences and calculate smooth color gradients.

In 2020, a new LAB-oriented color space, Oklab, was introduced by Björn Ottosson as an attempt to rectify the non-uniformities of other perceptual color spaces. Similar to CIELAB, the L value in Oklab represents perceived lightness, and the a and b values represent the balance between opposing unique colors. Oklab has gained widespread adoption as a perceptual space for color processing, with support in the latest CSS Color specifications and many software applications.

Cylindrical models
A cylindrical-coordinate model transforms an underlying color model, such as RGB or LAB, into an alternative expression of color information that is often more intuitive for the average person to use and understand.

Instead of a mixture of primary colors or opponent pairs, these models represent color as a hue angle on a color wheel, with additional parameters that describe other qualities such as lightness and colorfulness (a general term for concepts like chroma and saturation). In cylindrical-coordinate spaces, users can select a color and modify its lightness or other qualities without altering the hue.

The three most common RGB-based models are HSL (Hue, Saturation, Lightness), HSV (Hue, Saturation, Value), and HWB (Hue, Whiteness, Blackness). All three define hue angles in the same way, but they define colorfulness and lightness differently. Although they are not perceptually uniform, HSL and HSV are commonplace in color pickers and gradients.

For CIELAB and Oklab, the cylindrical-coordinate versions are CIELCh and Oklch, which express color in terms of perceived lightness, chroma, and hue. They offer perceptually uniform alternatives to RGB-based models. These spaces create unique color wheels, and they have more strict definitions of lightness and colorfulness. Oklch is particularly well-suited for generating smooth, perceptual color gradients.


Alpha and transparency

Many color encoding schemes include an alpha channel, representing opacity. Alpha does not help define a color in a color space; it determines how a color interacts with other colors in the display. Opaque colors appear with full intensity on the screen, whereas translucent (semi-opaque) colors blend into the background. Colors with zero opacity are invisible.

In Pine Script, there are two ways to specify a color's alpha:

 • Using the `transp` parameter of the built-in `color.*()` functions. The specified value represents transparency (the opposite of opacity), which the functions translate into an alpha value.
 • Using eight-digit hexadecimal color codes. The last two digits in the code represent alpha directly.

A process called alpha compositing simulates translucent colors in a display. It creates a single displayed color by mixing the RGB channels of two colors (foreground and background) based on alpha values, giving the illusion of a semi-opaque color placed over another color. For example, a red color with 80% transparency on a black background produces a dark shade of red.


Hexadecimal color codes

A hexadecimal color code (hex code) is a compact representation of an RGB color. It encodes a color's red, green, and blue values into a sequence of hexadecimal (base-16) digits. The digits are numerals ranging from `0` to `9` or letters from `a` (for 10) to `f` (for 15). Each set of two digits represents an RGB channel ranging from `00` (for 0) to `ff` (for 255).

Pine scripts can natively define colors using hex codes in the format `#rrggbbaa`. The first set of two digits represents red, the second represents green, and the third represents blue. The fourth set represents alpha. If unspecified, the value is `ff` (fully opaque). For example, `#ff8b00` and `#ff8b00ff` represent an opaque orange color. The code `#ff8b0033` represents the same color with 80% transparency.


Gradients

A color gradient maps colors to numbers over a given range. Most color gradients represent a continuous path in a specific color space, where each number corresponds to a mix between a starting color and a stopping color. In Pine, coders often use gradients to visualize value intensities in plots and heatmaps, or to add visual depth to fills.

The behavior of a color gradient depends on the mixing method and the chosen color space. Gradients in sRGB usually mix along a straight line between the red, green, and blue coordinates of two colors. In cylindrical spaces such as HSL, a gradient often rotates the hue angle through the color wheel, resulting in more pronounced color transitions.


Color schemes

A color scheme refers to a set of colors for use in aesthetic or functional design. A color scheme usually consists of just a few distinct colors. However, depending on the purpose, a scheme can include many colors.

A user might choose palettes for a color scheme arbitrarily, or generate them algorithmically. There are many techniques for calculating color schemes. A few simple, practical methods are:

 • Sampling a set of distinct colors from a color gradient.
 • Generating monochromatic variants of a color (i.e., tints, tones, or shades with matching hues).
 • Computing color harmonies — such as complements, analogous colors, triads, and tetrads — from a base color.

This library includes functions for all three of these techniques. See below for details.



█ CALCULATIONS AND USE


Hex string conversion

The `getHexString()` function returns a string containing the eight-digit hexadecimal code corresponding to a "color" value or set of sRGB and transparency values. For example, `getHexString(255, 0, 0)` returns the string `"#ff0000ff"`, and `getHexString(color.new(color.red, 80))` returns `"#f2364533"`.

The `hexStringToColor()` function returns the "color" value represented by a string containing a six- or eight-digit hex code. The `hexStringToRGB()` function returns a tuple containing the sRGB and transparency values. For example, `hexStringToColor("#f23645")` returns the same value as color.red.

Programmers can use these functions to parse colors from "string" inputs, perform string-based color calculations, and inspect color data in text outputs such as Pine Logs and tables.


Color space conversion

All other `get*()` functions convert a "color" value or set of sRGB channels into coordinates in a specific color space, with transparency information included. For example, the tuple returned by `getHSL()` includes the color's hue, saturation, lightness, and transparency values.

To convert data from a color space back to colors or sRGB and transparency values, use the corresponding `*toColor()` or `*toRGB()` functions for that space (e.g., `hslToColor()` and `hslToRGB()`).

Programmers can use these conversion functions to process inputs that define colors in different ways, perform advanced color manipulation, design custom gradients, and more.

The color spaces this library supports are:

 • sRGB
 • Linear RGB (RGB without gamma correction)
 • HSL, HSV, and HWB
 • CIE XYZ and xyY
 • CIELAB and CIELCh
 • Oklab and Oklch


Contrast-based calculations

Contrast refers to the difference in luminance or color that makes one color visible against another. This library features two functions for calculating luminance-based contrast and detecting themes.

The `contrastRatio()` function calculates the contrast between two "color" values based on their relative luminance (the Y value from CIE XYZ) using the formula from version 2 of the Web Content Accessibility Guidelines (WCAG). This function is useful for identifying colors that provide a sufficient brightness difference for legibility.

The `isLightTheme()` function determines whether a specified background color represents a light theme based on its contrast with black and white. Programmers can use this function to define conditional logic that responds differently to light and dark themes.


Color manipulation and harmonies

The `negative()` function calculates the negative (i.e., inverse) of a color by reversing the color's coordinates in either the sRGB or linear RGB color space. This function is useful for calculating high-contrast colors.

The `grayscale()` function calculates a grayscale form of a specified color with the same relative luminance.

The functions `complement()`, `splitComplements()`, `analogousColors()`, `triadicColors()`, `tetradicColors()`, `pentadicColors()`, and `hexadicColors()` calculate color harmonies from a specified source color within a given color space (HSL, CIELCh, or Oklch). The returned harmonious colors represent specific hue rotations around a color wheel formed by the chosen space, with the same defined lightness, saturation or chroma, and transparency.


Color mixing and gradient creation

The `add()` function simulates combining lights of two different colors by additively mixing their linear red, green, and blue components, ignoring transparency by default. Users can calculate a transparency-weighted mixture by setting the `transpWeight` argument to `true`.

The `overlay()` function estimates the color displayed on a TradingView chart when a specific foreground color is over a background color. This function aids in simulating stacked colors and analyzing the effects of transparency.

The `fromGradient()` and `fromMultiStepGradient()` functions calculate colors from gradients in any of the supported color spaces, providing flexible alternatives to the RGB-based color.from_gradient() function. The `fromGradient()` function calculates a color from a single gradient. The `fromMultiStepGradient()` function calculates a color from a piecewise gradient with multiple defined steps. Gradients are useful for heatmaps and for coloring plots or drawings based on value intensities.


Scheme creation

Three functions in this library calculate palettes for custom color schemes. Scripts can use these functions to create responsive color schemes that adjust to calculated values and user inputs.

The `gradientPalette()` function creates an array of colors by sampling a specified number of colors along a gradient from a base color to a target color, in fixed-size steps.

The `monoPalette()` function creates an array containing monochromatic variants (tints, tones, or shades) of a specified base color. Whether the function mixes the color toward white (for tints), a form of gray (for tones), or black (for shades) depends on the `grayLuminance` value. If unspecified, the function automatically chooses the mix behavior with the highest contrast.

The `harmonyPalette()` function creates a matrix of colors. The first column contains the base color and specified harmonies, e.g., triadic colors. The columns that follow contain tints, tones, or shades of the harmonic colors for additional color choices, similar to `monoPalette()`.



█ EXAMPLE CODE


The example code at the end of the script generates and visualizes color schemes by processing user inputs. The code builds the scheme's palette based on the "Base color" input and the additional inputs in the "Settings/Inputs" tab:

 • "Palette type" specifies whether the palette uses a custom gradient, monochromatic base color variants, or color harmonies with monochromatic variants.
 • "Target color" sets the top color for the "Gradient" palette type.
 • The "Gray luminance" inputs determine variation behavior for "Monochromatic" and "Harmony" palette types. If "Auto" is selected, the palette mixes the base color toward white or black based on its brightness. Otherwise, it mixes the color toward the grayscale color with the specified relative luminance (from 0 to 1).
 • "Harmony type" specifies the color harmony used in the palette. Each row in the palette corresponds to one of the harmonious colors, starting with the base color.

The code creates a table on the first bar to display the collection of calculated colors. Each cell in the table shows the color's `getHexString()` value in a tooltip for simple inspection.



Look first. Then leap.



█ EXPORTED FUNCTIONS


Below is a complete list of the functions and overloads exported by this library.


getRGB(source)
  Retrieves the sRGB red, green, blue, and transparency components of a "color" value.

getHexString(r, g, b, t)
  (Overload 1 of 2) Converts a set of sRGB channel values to a string representing the corresponding color's hexadecimal form.

getHexString(source)
  (Overload 2 of 2) Converts a "color" value to a string representing the sRGB color's hexadecimal form.

hexStringToRGB(source)
  Converts a string representing an sRGB color's hexadecimal form to a set of decimal channel values.

hexStringToColor(source)
  Converts a string representing an sRGB color's hexadecimal form to a "color" value.

getLRGB(r, g, b, t)
  (Overload 1 of 2) Converts a set of sRGB channel values to a set of linear RGB values with specified transparency information.

getLRGB(source)
  (Overload 2 of 2) Retrieves linear RGB channel values and transparency information from a "color" value.

lrgbToRGB(lr, lg, lb, t)
  Converts a set of linear RGB channel values to a set of sRGB values with specified transparency information.

lrgbToColor(lr, lg, lb, t)
  Converts a set of linear RGB channel values and transparency information to a "color" value.

getHSL(r, g, b, t)
  (Overload 1 of 2) Converts a set of sRGB channels to a set of HSL values with specified transparency information.

getHSL(source)
  (Overload 2 of 2) Retrieves HSL channel values and transparency information from a "color" value.

hslToRGB(h, s, l, t)
  Converts a set of HSL channel values to a set of sRGB values with specified transparency information.

hslToColor(h, s, l, t)
  Converts a set of HSL channel values and transparency information to a "color" value.

getHSV(r, g, b, t)
  (Overload 1 of 2) Converts a set of sRGB channels to a set of HSV values with specified transparency information.

getHSV(source)
  (Overload 2 of 2) Retrieves HSV channel values and transparency information from a "color" value.

hsvToRGB(h, s, v, t)
  Converts a set of HSV channel values to a set of sRGB values with specified transparency information.

hsvToColor(h, s, v, t)
  Converts a set of HSV channel values and transparency information to a "color" value.

getHWB(r, g, b, t)
  (Overload 1 of 2) Converts a set of sRGB channels to a set of HWB values with specified transparency information.

getHWB(source)
  (Overload 2 of 2) Retrieves HWB channel values and transparency information from a "color" value.

hwbToRGB(h, w, b, t)
  Converts a set of HWB channel values to a set of sRGB values with specified transparency information.

hwbToColor(h, w, b, t)
  Converts a set of HWB channel values and transparency information to a "color" value.

getXYZ(r, g, b, t)
  (Overload 1 of 2) Converts a set of sRGB channels to a set of XYZ values with specified transparency information.

getXYZ(source)
  (Overload 2 of 2) Retrieves XYZ channel values and transparency information from a "color" value.

xyzToRGB(x, y, z, t)
  Converts a set of XYZ channel values to a set of sRGB values with specified transparency information

xyzToColor(x, y, z, t)
  Converts a set of XYZ channel values and transparency information to a "color" value.

getXYY(r, g, b, t)
  (Overload 1 of 2) Converts a set of sRGB channels to a set of xyY values with specified transparency information.

getXYY(source)
  (Overload 2 of 2) Retrieves xyY channel values and transparency information from a "color" value.

xyyToRGB(xc, yc, y, t)
  Converts a set of xyY channel values to a set of sRGB values with specified transparency information.

xyyToColor(xc, yc, y, t)
  Converts a set of xyY channel values and transparency information to a "color" value.

getLAB(r, g, b, t)
  (Overload 1 of 2) Converts a set of sRGB channels to a set of CIELAB values with specified transparency information.

getLAB(source)
  (Overload 2 of 2) Retrieves CIELAB channel values and transparency information from a "color" value.

labToRGB(l, a, b, t)
  Converts a set of CIELAB channel values to a set of sRGB values with specified transparency information.

labToColor(l, a, b, t)
  Converts a set of CIELAB channel values and transparency information to a "color" value.

getOKLAB(r, g, b, t)
  (Overload 1 of 2) Converts a set of sRGB channels to a set of Oklab values with specified transparency information.

getOKLAB(source)
  (Overload 2 of 2) Retrieves Oklab channel values and transparency information from a "color" value.

oklabToRGB(l, a, b, t)
  Converts a set of Oklab channel values to a set of sRGB values with specified transparency information.

oklabToColor(l, a, b, t)
  Converts a set of Oklab channel values and transparency information to a "color" value.

getLCH(r, g, b, t)
  (Overload 1 of 2) Converts a set of sRGB channels to a set of CIELCh values with specified transparency information.

getLCH(source)
  (Overload 2 of 2) Retrieves CIELCh channel values and transparency information from a "color" value.

lchToRGB(l, c, h, t)
  Converts a set of CIELCh channel values to a set of sRGB values with specified transparency information.

lchToColor(l, c, h, t)
  Converts a set of CIELCh channel values and transparency information to a "color" value.

getOKLCH(r, g, b, t)
  (Overload 1 of 2) Converts a set of sRGB channels to a set of Oklch values with specified transparency information.

getOKLCH(source)
  (Overload 2 of 2) Retrieves Oklch channel values and transparency information from a "color" value.

oklchToRGB(l, c, h, t)
  Converts a set of Oklch channel values to a set of sRGB values with specified transparency information.

oklchToColor(l, c, h, t)
  Converts a set of Oklch channel values and transparency information to a "color" value.

contrastRatio(value1, value2)
  Calculates the contrast ratio between two colors values based on the formula from version 2 of the Web Content Accessibility Guidelines (WCAG).

isLightTheme(source)
  Detects whether a background color represents a light theme or dark theme, based on the amount of contrast between the color and the white and black points.

grayscale(source)
  Calculates the grayscale version of a color with the same relative luminance (i.e., brightness).

negative(source, colorSpace)
  Calculates the negative (i.e., inverted) form of a specified color.

complement(source, colorSpace)
  Calculates the complementary color for a `source` color using a cylindrical color space.

analogousColors(source, colorSpace)
  Calculates the analogous colors for a `source` color using a cylindrical color space.

splitComplements(source, colorSpace)
  Calculates the split-complementary colors for a `source` color using a cylindrical color space.

triadicColors(source, colorSpace)
  Calculates the two triadic colors for a `source` color using a cylindrical color space.

tetradicColors(source, colorSpace, square)
  Calculates the three square or rectangular tetradic colors for a `source` color using a cylindrical color space.

pentadicColors(source, colorSpace)
  Calculates the four pentadic colors for a `source` color using a cylindrical color space.

hexadicColors(source, colorSpace)
  Calculates the five hexadic colors for a `source` color using a cylindrical color space.

add(value1, value2, transpWeight)
  Additively mixes two "color" values, with optional transparency weighting.

overlay(fg, bg)
  Estimates the resulting color that appears on the chart when placing one color over another.

fromGradient(value, bottomValue, topValue, bottomColor, topColor, colorSpace)
  Calculates the gradient color that corresponds to a specific value based on a defined value range and color space.

fromMultiStepGradient(value, steps, colors, colorSpace)
  Calculates a multi-step gradient color that corresponds to a specific value based on an array of step points, an array of corresponding colors, and a color space.

gradientPalette(baseColor, stopColor, steps, strength, model)
  Generates a palette from a gradient between two base colors.

monoPalette(baseColor, grayLuminance, variations, strength, colorSpace)
  Generates a monochromatic palette from a specified base color.

harmonyPalette(baseColor, harmonyType, grayLuminance, variations, strength, colorSpace)
  Generates a palette consisting of harmonious base colors and their monochromatic variants.


Feragatname

Bilgiler ve yayınlar, TradingView tarafından sağlanan veya onaylanan finansal, yatırım, işlem veya diğer türden tavsiye veya tavsiyeler anlamına gelmez ve teşkil etmez. Kullanım Şartları'nda daha fazlasını okuyun.