Library · Pine Script v5 · Library

MathComplexArray

by ricardosantos79· code credited to RicardoSantos

MathComplexArray is a Pine Script v5 utility library that provides array functions for managing complex numbers.

View on GitHub

GitHub stars261on the repository
Pine versionv5runs as is
Lines of code118
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

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

MathComplexArray.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 Array methods to handle complex number arrays.
library(title='MathComplexArray')


// Complex numbers prototype: {
//     description:
//         A set of utility functions to handle complex numbers.
//     references:
//         https://en.wikipedia.org/wiki/Complex_number
//         js: https://rosettacode.org/wiki/Fast_Fourier_transform
//         https://github.com/trekhleb/javascript-algorithms/blob/477f30b0bdac6024874d2976de1eca7afe0176dd/src/algorithms/math/complex-number/ComplexNumber.js#L3
//         https://github.com/infusion/Complex.js/

// required imports:
import RicardoSantos/MathComplexCore/1 as complex

// @function Prototype to initialize a array of complex numbers.
// @param size size of the array.
// @param initial_complex Complex number to be used as default value, in the form of array [real, imaginary].
// @returns float array, pseudo complex Array in the form of a array [0:real, 1:imaginary, 2:real, 3:imaginary,...]
export new (int size=0, float[] initial_complex) => //{
    if size > 0
        float _init_real = array.get(id=initial_complex, index=0)
        float _init_imaginary = array.get(id=initial_complex, index=1)
    
        float[] _complex_array = array.new_float(0)
        for _i = 0 to size-1
            array.push(id=_complex_array, value=_init_real)
            array.push(id=_complex_array, value=_init_imaginary)
        _complex_array
    else
        array.new_float(0)
//}

// @function Get the complex number in a array, in the form of a array [real, imaginary]
// @param id float array, ID of the array.
// @param index int, Index of the complex number.
// @returns float array, pseudo complex number in the form of a array [real, imaginary]
export get(float[] id, int index) => //{
    int _size = math.round(array.size(id) / 2)
    int _index = index * 2
    if index > -1 and index < _size
        complex.new(array.get(id, _index), array.get(id, _index + 1))
    else
        complex.new(0.0, 0.0)
//}

// @function Sets the values complex number in a array.
// @param id float array, ID of the array.
// @param index int, Index of the complex number.
// @param complex_number float array, Complex number, in the form: [real, imaginary].
// @returns Void, updates array id.
export set (float[] id, int index, float[] complex_number) => //{
    float _re = complex.get_real(complex_number)
    float _im = complex.get_imaginary(complex_number)
    int _size = array.size(id)-1
    int _index = index * 2
    if index > -1 and _index < _size
        array.set(id, _index, _re)
        array.set(id, _index + 1, _im)
//}

// @function Push the values into a complex number array.
// @param id float array, ID of the array.
// @param complex_number float array, Complex number, in the form: [real, imaginary].
// @returns Void, updates array id.
export push (float[] id, float[] complex_number) => //{
    if not complex.is_complex(complex_number)
        runtime.error('MathComplexArray -> push(): "complex_number" has the wrong size.')
    else
        float _re = complex.get_real(complex_number)
        float _im = complex.get_imaginary(complex_number)
        array.push(id, _re)
        array.push(id, _im)
//}

// @function Pop the values from a complex number array.
// @param id float array, ID of the array.
// @param complex_number float array, Complex number, in the form: [real, imaginary].
// @returns Void, updates array id.
export pop (float[] id) => //{
    int _size = array.size(id)
    if _size < 2
        runtime.error(str.format('MathComplexArray -> pop(): "id" has the wrong size. {0}', _size))
        array.new_float(na)
    else
        complex.new(array.pop(id), array.pop(id))
//}

// @function Reads a array of complex numbers into a string, of the form: "[ [a+bi], ... ]""
// @param id float array, ID of the array.
// @param format string, format of the number conversion, default='#.##########'.
// @returns string, translated complex array into string.
export to_string (float[] id, string format='#.##########') => //{
    int _size = math.round(array.size(id) / 2)
    string _str = '[ '
    if _size > 0
        for _i = 0 to _size-1
            _str := _str + '[ ' + complex.to_string(get(id, _i), format) + ' ]'
            if _i >= _size-1
                _str := _str + ' ]'
            else
                _str := _str + ', '
    _str
//}


if barstate.ishistory[1] and (barstate.isrealtime or barstate.islast)
    a = new(1, complex.new(0.0, 0.0))
    string _text = to_string(a, '#.##')
    b = new(2, complex.new(1.0, 2.0))
    _text += '\n' + to_string(b, '#.##')
    label.new(x=bar_index, y=0.0, text=_text, style=label.style_label_left, textalign=text.align_left)

Overview

MathComplexArray represents complex arrays as flat float arrays storing interleaved real and imaginary components. The library includes functions to instantiate complex arrays, retrieve complex numbers by index, set specific elements, and perform push or pop operations. It produces no plots on the chart and serves as a helper for mathematical script development.

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