Library · Pine Script v6 · Library

Color

by Electrified-Trading

Color is a Pine Script utility library designed for advanced color manipulation and comparison within scripts.

View on GitHub

GitHub stars2on the repository
Pine versionv6current
Lines of code193
Settings0inputs
LicenceMPL-2.0
Last update1 year ago7 Jul 2025

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new library, select all of the template text and paste. Press Save and give it a name.
  4. 4Publish or import itA library draws nothing. Publish it from the editor, then import its functions in your own scripts.

Source Code

193 lines of Pine Script v6 from Color.pine, published under MPL-2.0. Keep the author's credit and licence lines when you reuse it.

Color.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Electrified (electrifiedtrading)

// @version=6
// @description Utility for working with colors.
library('Color', true)

//////////////////////////////////////////////////
// @function Determines if two colors are equal.
// @param a The first color to compare.
// @param b The second color to compare.
// @returns True if both colors are equal, false otherwise.
export method equals(color a, color b) =>
    if na(a)
        na(b)
    else if na(b)
        false
    else if color.r(a) != color.r(b)
        false
    else if color.g(a) != color.g(b)
        false
    else if color.b(a) != color.b(b)
        false
    else
        color.t(a) == color.t(b)
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// @function Calculates the luminosity of a color using the given red, green, and blue values.
// @param r The red value of the color, from 0 to 255.
// @param g The green value of the color, from 0 to 255.
// @param b The blue value of the color, from 0 to 255.
// @returns The luminosity of the color, a float between 0 and 1.
export luminosity(float r, float g, float b) =>
    (0.299 * r + 0.587 * g + 0.114 * b) / 255
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// @function Calculates the luminosity of a color using its red, green, and blue values.
// @param c The color to calculate the luminosity for.
// @returns The luminosity of the color, a float between 0 and 1.
export method luminosity(color c) =>
    na(c) ? na : luminosity(color.r(c), color.g(c), color.b(c))
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// @function Returns a color that is either black or white depending on the luminosity of the given background color. If the background color is na, returns gray.
// @param bgColor The background color to determine the contrast color for.
// @param keepNa When true and the value of bgColor is na the return value will be na; otherwise the if bgColor is na the return will be gray.
// @returns A color that provides high contrast with the given background color.
export method getContrastColor(color bgColor, bool keepNa = false) =>
    (na(bgColor) ? true : color.t(bgColor)==100) ? (keepNa ? na : color.rgb(128, 128, 128)) :
      luminosity(bgColor) > 0.5 ? color.rgb(0, 0, 0) : color.rgb(255, 255, 255)
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// @function Converts a color value to a string in the "rgbt(r,g,b,t)" format.
// @param color The color to convert.
// @returns The color value as a string.
export method tostringRGBT(color color) =>
    na(color) ? "na" : (
      "rgbt("+
      str.tostring(color.r(color))+","+
      str.tostring(color.g(color))+","+
      str.tostring(color.b(color))+","+
      str.tostring(color.t(color))+")")
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// @function Converts an integer between 0 and 15 to its hex equivalent character.
// @param n The integer value to convert.
export toHexChar(int n) =>
    if na(n)
        runtime.error("Cannot convert na to hex.")
    if n < 0
        runtime.error("Value of (n) must be at least zero. Actual: "+str.tostring(n))
    if n > 15
        runtime.error("Value of (n) must be less than 16. Actual: "+str.tostring(n))

    // Convert the integer to a hex character
    switch n
        10 => 'A'
        11 => 'B'
        12 => 'C'
        13 => 'D'
        14 => 'E'
        15 => 'F'
        => str.tostring(n)
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// @function Converts an integer from 0 to 255 to a 2-character hex string.
// @param n The integer value to convert.
export byteToHex(float n) =>
    if na(n)
        runtime.error("Cannot convert na to hex.")
    if n < 0
        runtime.error("Value of (n) must be at least zero. Actual: "+str.tostring(n))
    if n > 255
        runtime.error("Value of (n) must be less than 255. Actual: "+str.tostring(n))

    // Calculate the hex value for the tens place
    tens = math.floor(n / 16)

    // Calculate the hex value for the ones place
    ones = math.floor(n % 16)

    // Convert the tens and ones values to hex characters
    tens_char = toHexChar(tens)
    ones_char = toHexChar(ones)

    // Return the hex string
    tens_char + ones_char
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// @function Converts a color to its hex string (#FFFFFF).
// @param n The color to convert.
// @returns The six digit hex string.
export method toHex(color color) =>
    na(color) ? "na" : "#" + byteToHex(color.r(color)) + byteToHex(color.r(color)) + byteToHex(color.r(color))
//////////////////////////////////////////////////

//////////////////////////////////////////////////
brighten(float c, float ratio) =>
    ratio > 0 ?
      c + (255 - c) * ratio :
      c * (1 + ratio)
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// @function Proportionally adjusts the RGB values of a color. A value of positive (+) 100 will result in white. A value of negative (-) 100 will result in black.
// @param c The color to adjust.
// @param value The percent amount (-100 to +100) to adjust the color by.  Values less than -100 or greater than +100 will be clamped.
// @returns The resultant color.
export method brighten(color c, float value) =>
    if na(c) or nz(value, 0) == 0
        c
    else
        t = color.t(c)
        if value >= 100
            color.rgb(255, 255, 255, t)
        else if value <= -100
            color.rgb(0, 0, 0, t)
        else
            ratio = value / 100
            r = brighten(color.r(c), ratio)
            g = brighten(color.g(c), ratio)
            b = brighten(color.b(c), ratio)
            color.rgb(r,g,b,t)
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// @function Proportionally adjusts the RGB values of a color. A value of positive (+) 100 will result in black. A value of negative (-) 100 will result in white.
// @param c The color to adjust.
// @param value The percent amount (-100 to +100) to adjust the color by.  Values less than -100 or greater than +100 will be clamped.
// @returns The resultant color.
export method darken(color c, float value) =>
    brighten(c, -nz(value))
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// Color interpolation helper for smooth gradients
interpolate(float a, float b, float t) => a + (b - a) * t
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// @function Linear interpolation between two colors.
// @param color1 The first color.
// @param color2 The second color.
// @param t The interpolation factor (0.0 = color1, 1.0 = color2).
// @returns The interpolated color.
export lerp(color color1, color color2, float t) =>
    if na(color1) or na(color2) or na(t)
        na
    else
        clampedT = math.max(0.0, math.min(1.0, t))
        color.rgb(
          interpolate(color.r(color1), color.r(color2), clampedT),
          interpolate(color.g(color1), color.g(color2), clampedT),
          interpolate(color.b(color1), color.b(color2), clampedT),
          interpolate(color.t(color1), color.t(color2), clampedT))
//////////////////////////////////////////////////

//////////////////////////////////////////////////
// @function Blends this color with another color using linear interpolation.
// @param this The starting color.
// @param toColor The target color to blend with.
// @param t The blend factor (0.0 = this, 1.0 = toColor).
// @returns The blended color.
export method blendWith(color this, color toColor, float t) =>
    lerp(this, toColor, t)
//////////////////////////////////////////////////

Overview

Color provides helper methods to compare two color instances across RGB and transparency channels, calculate relative color luminosity, and determine high-contrast text or foreground colors against dynamic backgrounds. Additionally, it offers functions to format color structures into explicit string representations and convert integer values to hexadecimal notation. It executes strictly as a background calculation library without drawing visual elements on the chart.

Details

Published by

Electrified-Trading on GitHub

Draws

Library (no plots)

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

261 stars

AIActivationFunctionsBipolarSigmoid is a Pine Script library that provides mathematical implementations of the bipolar sigmoid activation function and its derivatives for machine learning algorithms. It calculates bipolar sigmoid values bounded between -1 and

Library v5 AI / machine learning
Updated 4 years ago · None stated GitHub repository of AIActivationFunctionsBipolarSigmoid

KernelFunctions

by artificial-intelligence-edge
75 stars

KernelFunctions is a Pine Script v5 library that exports kernel weight functions for Nadaraya-Watson style estimation. It calculates a Rational Quadratic kernel, a Gaussian kernel based on a radial basis function, and a periodic kernel that models repeating be

Library v5
Updated 4 days ago · MIT GitHub repository of KernelFunctions

Ta

by nersent
29 stars

This Pine Script v5 library exports thin wrappers around built-in technical analysis functions. It covers moving averages, momentum measures such as RSI and CCI, volatility tools including ATR and standard deviation, range extremes, cross detection, and runnin

Library v5
Updated 11 months ago · Custom licence GitHub repository of Ta

Bands

by heyphat
26 stars

This library exports a Band type and functions that build a simple-moving-average basis with upper and lower envelopes from standard deviation. It classifies a source as above, below, or inside those envelopes, measures band width, and scales an imported z-sco

Library v6 Volatility & bandsMoving averages
Updated 2 months ago · AGPL-3.0 GitHub repository of Bands

Mylib

by ferranbt
21 stars

This script serves as a minimal utility library written in Pine Script v6. It provides an exported helper function that calculates the sum of two numeric arguments. As a reusable code library, it produces no visual plots, charts, or trading signals, and it con

Library v6
Updated 7 weeks ago · MPL-2.0 GitHub repository of Mylib

HLevel

by stupenkov
14 stars

HLevel is a Pine Script v5 utility library designed to manage horizontal price levels for cryptocurrency charts. It defines custom types for pivots and levels, along with methods to initialize, add, track, and expire price levels based on pivot high and pivot

Library v5
Updated 3 years ago · None stated GitHub repository of HLevel

More libraries

Related on ForexR

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers