Library · Pine Script v5 · Library

HLevel

by stupenkov· code credited to stupean

HLevel is a Pine Script v5 utility library designed to manage horizontal price levels for cryptocurrency charts.

View on GitHub

GitHub stars14on the repository
Pine versionv5runs as is
Lines of code304
Settings0inputs
LicenceNone statedfile: MPL-2.0
Last update3 years ago31 Aug 2023

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

304 lines of Pine Script v5 from Indicator/HLevel.lib.pinescript, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

HLevel.lib.pinescript
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Author: Anton Stupenkov
// Email: stupean@gmail.com
// Screener: https://t.me/LazyScalp
// © stupean

//@version=5

// @description v1.2.0
library("HLevel", true)

//#region CONSTANTS ============================================
string SIDE_HIGH = "SIDE_HIGH"
string SIDE_LOW = "SIDE_LOW"
int LOCAL_PERIOD = 0
int MIDDLE_PERIOD = 1
int GLOBAL_PERIOD = 2
int BREAK_PERIOD = 3
//#endregion

//#region CLASS Pivots ============================================
export type pivot
    int period
    int legBars
    float hPrice
    float lPrice

export type pivotsList
    int secondsInCurrentPeriod
    array<pivot> pivots

export method init(pivotsList this, int secondsInCurrentPeriod) =>
    this.pivots := array.new<pivot>()
    this.secondsInCurrentPeriod := secondsInCurrentPeriod

export method add(pivotsList this, int period, int legSeconds) =>
    int legBars = math.ceil(legSeconds * 1.5 / this.secondsInCurrentPeriod)
    pivot p = pivot.new(
      period = period,
      legBars = legBars,
      hPrice = ta.pivothigh(high, legBars, legBars),
      lPrice = ta.pivotlow(low, legBars, legBars))
    this.pivots.push(p)
    p

export method size(pivotsList this) =>
    this.pivots.size()

export method get(pivotsList this, int index) =>
    this.pivots.get(index)
//#endregion

//#region CLASS Levels ============================================
export type level
    string side
    int barIndex
    int crossBarIndex = -1
    float price
    line lineId
    int period
    bool hasNearLevel
    bool isHide
    label priceLableId

method time(level this) =>
    int bars = bar_index - this.barIndex
    timeframe.in_seconds(timeframe.period) * bars

export type levelsClass
    int maxBars
    int minNearLevels
    array<int> lifetimes
    array<level> levels

method resetNearLevels(levelsClass this) =>
    if this.levels.size() > 0
        for i = 0 to this.levels.size() - 1
            level lvl = this.levels.get(i)
            lvl.hasNearLevel := false

export method init(levelsClass this, int minNearLevels, int maxBars = 4000) =>
    this.levels := array.new<level>()
    this.lifetimes := array.new<int>(10, -1)
    this.maxBars := maxBars
    this.minNearLevels := minNearLevels

export method addLifetime(levelsClass this, int period, int lifetimeBars) =>
    this.lifetimes.set(period, lifetimeBars)

export method size(levelsClass this) =>
    this.levels.size()

export method getAll(levelsClass this) =>
    this.levels

export method get(levelsClass this, int index) =>
    this.levels.get(index)

export method delete(levelsClass this, int index) =>
    level lvl = this.levels.get(index)
    if not na(lvl.lineId)
        lvl.lineId.delete()
    if not na(lvl.priceLableId)
        lvl.priceLableId.delete()
    this.levels.remove(index)

export method isLifetimeExpired(levelsClass this, level lvl) =>
    int lifetime = this.lifetimes.get(lvl.period)
    if lifetime == 0
        false
    else if lvl.barIndex < bar_index - lifetime
        true
    else
        false

method markStrongLevels(levelsClass this, level lvl, int nextLevelIndex, distanceBetweenNearLevels) =>
    array<level> strongLevels = array.new<level>()
    strongLevels.push(lvl)
    if nextLevelIndex < this.levels.size() and lvl.crossBarIndex == -1 and not lvl.isHide 
        for int i = nextLevelIndex to this.levels.size() - 1
            level secondLvl = this.levels.get(i)
            if secondLvl.crossBarIndex == -1 and math.abs(lvl.price - secondLvl.price) <= distanceBetweenNearLevels and not secondLvl.isHide
                strongLevels.push(secondLvl)
    if strongLevels.size() > 0 and strongLevels.size() >= this.minNearLevels 
        for int i = 0 to strongLevels.size() - 1
            level _level = strongLevels.get(i)
            _level.hasNearLevel := true
 
export method update(levelsClass this, pivotsList pivots, float priceRange, float distanceBetweenNearLevels) =>
    pivot p = pivots.get(0)
    if not na(p.hPrice) 
        level newLevel = level.new(
          side = SIDE_HIGH,
          barIndex = bar_index - p.legBars,
          price = p.hPrice,
          period = p.period)
        this.levels.unshift(newLevel)

    if not na(p.lPrice)
        level newLevel = level.new(
          side = SIDE_LOW,
          barIndex = bar_index - p.legBars,
          price = p.lPrice,
          period = p.period)
        this.levels.unshift(newLevel)

    this.resetNearLevels()

    int counter = 0
    while counter < this.levels.size()
        level lvl = this.levels.get(counter)
        // delete old level
        if (lvl.barIndex < bar_index - this.maxBars)
            this.delete(counter)
            continue

        // mark cross level
        bool isCross = lvl.side == SIDE_HIGH ? lvl.price < high : lvl.price > low
        if isCross and lvl.crossBarIndex == -1
            lvl.crossBarIndex := bar_index

        // delete crossed level
        if lvl.crossBarIndex != -1 and lvl.crossBarIndex < bar_index - this.lifetimes.get(BREAK_PERIOD)
            this.delete(counter)
            continue

        // define senior levels
        for pivotIndex = pivots.size() - 1 to 1
            pivot piv = pivots.get(pivotIndex) 
            if (lvl.side == SIDE_HIGH and lvl.price == piv.hPrice) or (lvl.side == SIDE_LOW and lvl.price == piv.lPrice)
                lvl.period := piv.period
                lvl.isHide := false
                break
      
        // hide far levels
        float maxPrice = close + priceRange
        float minPrice = close - priceRange
        if (lvl.side == SIDE_HIGH and lvl.price > maxPrice) or (lvl.side == SIDE_LOW and lvl.price < minPrice )
            lvl.isHide := true
        else if lvl.isHide
            lvl.isHide := false    

        // hide expired levels
        if this.isLifetimeExpired(lvl)
            lvl.isHide := true

        // mark nearly levels
        int nextLevelIndex = counter + 1 
        this.markStrongLevels(lvl, nextLevelIndex, distanceBetweenNearLevels)
        
        counter += 1

export method getNearStrongLevels(levelsClass this) =>
    level highLevel = na
    level lowLevel = na
    if this.size() > 0
        for i = 0 to this.size() - 1
            level lvl = this.get(i)
            if not lvl.hasNearLevel
                continue
            if lvl.side == SIDE_HIGH 
                if na(highLevel)
                    highLevel := lvl
                else if lvl.price < highLevel.price
                    highLevel := lvl
            else if lvl.side == SIDE_LOW 
                if na(lowLevel)
                    lowLevel := lvl
                else if lvl.price > lowLevel.price
                    lowLevel := lvl

    [highLevel, lowLevel] 
//#endregion

//#region CLASS Drawer ============================================
export type lineStyle
    int width = 1
    color lineColor
    string style = line.style_solid

export type levelDrawerClass
    array<lineStyle> styles
    color roundPriceColor
    color defaultPriceColor
    string priceShowOptions
    float transparent
    bool showLevelTime

export method init(levelDrawerClass this, string priceShowOptions, float transparent = 70, color roundPriceColor = color.green, color defaultPriceColor = color.white) =>
    this.styles := array.new<lineStyle>()
    this.roundPriceColor := roundPriceColor
    this.defaultPriceColor := defaultPriceColor
    this.priceShowOptions := priceShowOptions
    this.transparent := transparent

export method addStyle(levelDrawerClass this, lineStyle style) =>
    this.styles.push(style)

export method draw(levelDrawerClass this, levelsClass levelList) =>
    if levelList.size() > 0
        lineStyle breakStyle = this.styles.last()
        for i = 0 to levelList.size() - 1
            level lvl = levelList.get(i)
            lineStyle lStyle = this.styles.get(lvl.period)
            if lvl.isHide 
                if not na(lvl.lineId)
                    lvl.lineId.delete()
                if not na(lvl.priceLableId)
                    lvl.priceLableId.delete()
                continue

            float transparent = lvl.hasNearLevel ? 0 : this.transparent
            color lineColor = color.new(lStyle.lineColor, transparent)
            if na(lvl.lineId)
                lvl.lineId := line.new(
                  x1 = lvl.barIndex,
                  y1 = lvl.price,
                  x2 = lvl.barIndex + 1,
                  y2 = lvl.price,
                  extend = extend.right,
                  color = lineColor,
                  style = lStyle.style,
                  width = lStyle.width)  
                0
            else if lvl.crossBarIndex != -1
                lvl.lineId.set_color(breakStyle.lineColor) 
                lvl.lineId.set_style(breakStyle.style) 
                lvl.lineId.set_width(breakStyle.width) 
                lvl.lineId.set_x2(lvl.crossBarIndex + 10) 
                lvl.lineId.set_extend(extend.none) 
                0
            else
                lvl.lineId.set_color(lineColor) 
                lvl.lineId.set_style(lStyle.style) 
                lvl.lineId.set_width(lStyle.width) 

            if this.priceShowOptions != "none"
                color textColor = if math.round_to_mintick(lvl.price / 100) * 100 == lvl.price 
                    color.new(this.roundPriceColor, transparent)
                else
                    color.new(this.defaultPriceColor, transparent)

                string labelText = str.tostring(lvl.price)
                if this.showLevelTime
                    labelText += str.format("\n{0,number,#}h", lvl.time() / 3600)

                if na(lvl.priceLableId)
                    lvl.priceLableId := label.new(
                      x = lvl.barIndex,
                      y = 0,
                      text =  labelText,
                      size = this.priceShowOptions,
                      style = label.style_none,
                      textcolor = textColor,
                      yloc = lvl.side == SIDE_HIGH ? yloc.abovebar : yloc.belowbar)
                    0
                else if lvl.crossBarIndex != -1
                    lvl.priceLableId.set_textcolor(breakStyle.lineColor)
                    0
                else
                    lvl.priceLableId.set_textcolor(textColor)
                    lvl.priceLableId.set_text(labelText)
                    0
//#endregion

Overview

HLevel defines custom types for pivots and levels, along with methods to initialize, add, track, and expire price levels based on pivot high and pivot low calculations across customizable time periods. The library provides underlying logic to manage line objects, level lifetimes, and proximity checks, supporting automated scalping screeners and horizontal level analysis without drawing directly on the chart.

Details

Published by

stupenkov on GitHub

Code credit

stupean, as written in the script's header

Type

Library, Pine Script v5

Draws

Library (no plots)

Markets

Crypto

Timeframes

M1-M5, M15-H1

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.

Topics

cryptocurrencycrytocsharppinescripttradingview

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 2 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

Zignaly2Beta

by ruckard
13 stars

This library provides helper functions to format and build JSON webhook alert payloads for the Zignaly automated trading platform. It constructs formatted messages containing parameters such as trading pair, exchange, account type, leverage, margin mode, hedge

Library v5
Updated 1 year ago · None stated GitHub repository of Zignaly2Beta

More libraries

Trade Your Charts With a Regulated Broker

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

Compare brokers