Library · Pine Script v5 · Library

StringEvaluation

by ricardosantos79· code credited to RicardoSantos

This utility library evaluates mathematical expressions formatted as strings within Pine Script v5.

View on GitHub

GitHub stars261on the repository
Pine versionv5runs as is
Lines of code254
Settings0inputs
LicenceNone statedfile: MPL-2.0
Last update4 years ago13 Nov 2021

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

254 lines of Pine Script v5 from beta/libs/StringEvaluation.pinescript, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

StringEvaluation.pinescript
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RicardoSantos

//@version=5

// @description Methods to handle evaluation of strings.
library(title='StringEvaluation')

// imports:
import RicardoSantos/MathOperator/1 as op

// Helper Functions:

// @function Check if char is a comma ".".
// @param char string, 1 character string.
// @returns bool.
export is_comma (string char) => //{
    char == '.' ? true : false
//}

// @function Check if char is a operator.
// @param char string, 1 character string.
// @returns bool.
export is_op (string char) => //{
    switch char
        '+' => true
        '-' => true
        '*' => true
        '/' => true
        '^' => true
        '%' => true
        => false
//}

// @function convert a single char string into valid number.
// @param char string, 1 character string.
// @returns float.
export number (string char) => //{
    switch char
        '0' => 0
        '1' => 1
        '2' => 2
        '3' => 3
        '4' => 4
        '5' => 5
        '6' => 6
        '7' => 7
        '8' => 8
        '9' => 9
        => na
//}

// @function operation between left and right values.
// @param op string, operator string character.
// @param left float, left value of operation.
// @param right float, right value of operation.
export operator (string op, float left, float right) => //{
    switch op
        '+' => op.add(left, right)
        '-' => op.subtract(left, right)
        '*' => op.multiply(left, right)
        '/' => op.divide(left, right)
        '^' => math.pow(left, right)
        '%' => op.remainder(left, right)
        => na
//}

// @function level of precedence of operator.
// @param op string, operator 1 char string.
// @returns int.
export operator_precedence (string op) => //{
    switch op
        '+' => 2
        '-' => 2
        '*' => 3
        '/' => 3
        '^' => 4
        '%' => 3
        => 0
//}

// @function Evaluate a string to clean up and retrieve only used chars
// @param _str string, arithmetic operations in a string.
// @returns string array, evaluated array.
export cleanup (string _str) => //{
    // remove spaces:
    _unspaced = str.replace_all(source=_str, target=' ', replacement='')
    _T0 = str.split(_unspaced, '')
    // adds ( ) + - / * characters:
    // join digit sequences into 1 whole number:
    _T1 = array.new_string(0)
    string _saved_expression = ''
    for _i = 0 to array.size(id=_T0)-1
        _current = array.get(id=_T0, index=_i)
        if _current == '(' or _current == ')'
            if _saved_expression != ''
                array.push(id=_T1, value=_saved_expression)
            array.push(id=_T1, value=_current)
            _saved_expression := ''
        if not na(operator(_current, 1, 1))
            if _saved_expression != ''
                array.push(id=_T1, value=_saved_expression)
            array.push(id=_T1, value=_current)
            _saved_expression := ''
        if not na(number(_current)) or is_comma(_current)
            _saved_expression := _saved_expression + _current
    array.push(id=_T1, value=_saved_expression)
    _T1
//{ usage:
// if barstate.islastconfirmedhistory
//     label.new(bar_index, 0.0, str.tostring(cleanup('1+ 66* 7/2^2  %5 ')))
//}

// @function uses Shunting-Yard algorithm to generate a RPN (Reverse Polish notation)
//      array of strings from a array of strings containing arithmetic notation.
//      ex:.. '[3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3]'     -->     '[3 4 2 * 1 5 - 2 3 ^ ^ / +]'
// @param tokens string array, array with arithmetic notation.
// @returns 
export generate_rpn (string[] tokens)=> //{
    int _size = array.size(id=tokens)
    if _size < 1
        runtime.error('StringEvaluation -> generate_rpn(): "tokens" is empty.')
        string[] _S = array.new_string(na)
    else
        _opstack = array.new_string(size=0)
        _output = array.new_string(size=0)
        for _i = 0 to _size-1
            string _current_token = array.get(id=tokens, index=_i)
            _current_arrified = str.split(_current_token, '')
            int _current_size = array.size(id=_current_arrified)
            if not na(number(array.get(id=_current_arrified, index=0)))
                array.push(id=_output, value=_current_token)
            else if _current_token == '('
                array.push(id=_opstack, value=_current_token)
            else if _current_token == ')'
                int _size_stack = array.size(id=_opstack)
                if _size_stack > 0
                    for _j = _size_stack-1 to 0
                        string _op = array.pop(id=_opstack)
                        if _op == '('
                            break
                        else
                            array.push(id=_output, value=_op)
            else if is_op(_current_token)
                int _size_stack = array.size(id=_opstack)
                if _size_stack > 0
                    for _j = _size_stack-1 to 0
                        string _op = array.pop(id=_opstack)
                        int _op_precedence = operator_precedence(_op)
                        int _token_precedence = operator_precedence(_current_token)
                        if _op_precedence > _token_precedence or (_op_precedence == _token_precedence and _op != '^')
                            array.push(id=_output, value=_op)
                        else
                            array.push(id=_opstack, value=_op)
                            break
                array.push(id=_opstack, value=_current_token)
        int _size_stack = array.size(id=_opstack)
        if _size_stack > 0
            for _i = _size_stack-1 to 0
                string _op = array.pop(id=_opstack)
                if _op == '('
                    runtime.error('StringEvaluation -> generate_rpn(): mismatched parentesis!.')
                else
                    array.push(id=_output, value=_op)
        _output
//{ usage:
// if barstate.islastconfirmedhistory
//     label.new(bar_index, 0.0, str.tostring(generate_rpn(cleanup('1+ 66* 7/2^2  %5 '))))
//{ reference:
//     https://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm
//     https://en.wikipedia.org/wiki/Shunting-yard_algorithm
//     https://brilliant.org/wiki/shunting-yard-algorithm/
//}}}

// @function evaluate a RPN (Reverse Polish notation) array of strings.
//      ex:.. 3 4 2 * 1 5 - 2 3 ^ ^ / +
//| @param tokens string array, RPN ordered tokens, ex(['3', '4', '2', '1', '5', '2', '3', '*', '-', '^', '^', '/', '+']).
//| @returns float, solution.
export parse_rpn (string[] tokens) => //{
    int _size = array.size(id=tokens)
    if _size < 1
        runtime.error('StringEvaluation -> generate_rpn(): "tokens" is empty.')
        float(na)
    else
        float _solution = na
        _stack = array.new_float()
        for _i = 0 to _size-1
            string _token = array.get(id=tokens, index=_i)
            float _number = str.tonumber(_token)
            if not na(_number)//
                array.push(id=_stack, value=_number)
            else
                if array.size(id=_stack) > 1
                //     runtime.error('StringEvaluation -> generate_rpn(): insufficient operands!!.\n' + str.tostring(_stack))
                // else
                    o2 = array.pop(id=_stack)
                    o1 = array.pop(id=_stack)
                    if is_op(_token)
                        float _op = operator(_token, o1, o2)
                        array.push(id=_stack, value=_op)
                    else
                        runtime.error('StringEvaluation -> generate_rpn(): unrecognized operator: (' + _token + ' ).')
        _solution := array.pop(id=_stack)
        _solution
//{ usage:
// if barstate.islastconfirmedhistory
//     label.new(bar_index, 0.0, str.tostring(parse_rpn(generate_rpn(cleanup('((10+ 10 *30/20-50)%10)^2')))))
//{ reference:
//     https://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
//}}}

// @function evaluate a string with references to a array of arguments.
//| @param tokens string, arithmetic operations with references to indices in arguments, ex:"0+1*0+2*2+3" arguments[1, 2, 3]
//| @param arguments float array, arguments.
//| @returns float, solution.
export eval (string tokens, float[] arguments) => //{
    int _size_a = array.size(id=arguments)
    if _size_a < 1
        runtime.error('StringEvaluation -> generate_rpn(): "arguments" is empty.')
        float(na)
    else
        string[] _tokens = generate_rpn(cleanup(tokens))
        int _size_t = array.size(id=_tokens)
        if _size_t < 1
            runtime.error('StringEvaluation -> generate_rpn(): "tokens" is empty.')
            float(na)
        else
            // calculate solution:
            float _solution = na
            _stack = array.new_float()
            for _i = 0 to _size_t-1
                string _token = array.get(id=_tokens, index=_i)
                float _number = str.tonumber(_token)
                if not na(_number)//
                    array.push(id=_stack, value=array.get(id=arguments, index=int(_number)))
                else
                    if array.size(id=_stack) > 1
                    //     runtime.error('StringEvaluation -> generate_rpn(): insufficient operands!!.\n' + str.tostring(_stack))
                    // else
                        o2 = array.pop(id=_stack)
                        o1 = array.pop(id=_stack)
                        if is_op(_token)
                            float _op = operator(_token, o1, o2)
                            array.push(id=_stack, value=_op)
                        else
                            runtime.error('StringEvaluation -> generate_rpn(): unrecognized operator: (' + _token + ' ).')
            _solution := array.pop(id=_stack)
            _solution
//{ usage:
if barstate.islastconfirmedhistory
    label.new(bar_index, 0.0, str.tostring(eval('((0+ 0 *2/1-3)%0)^4', array.from(10.0, 20, 30, 50, 2))))
//{ reference:
//     https://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
//}}}

Overview

StringEvaluation parses raw input strings, removes whitespace, extracts operators and numeric values, and handles operator precedence. The code includes support for transforming arithmetic expressions into Reverse Polish Notation via the Shunting-Yard algorithm. As a helper library, it contains no trading strategies, entry or exit signals, or user-configurable input settings. It draws nothing on the chart or in separate panes, operating purely as a mathematical parser for other indicators and scripts.

Details

Published by

ricardosantos79 on GitHub

Code credit

RicardoSantos, as written in the script's header

Type

Library, Pine Script v5

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

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

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

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