Indicator · Pine Script v4 · Own pane

Matrix functions and operations - test

by JorisDuyck

This script provides test functions for 2D matrix operations in Pine Script arrays.

View on GitHub

GitHub stars2on the repository
Pine versionv4older, still runs
Lines of code295
Settings2inputs
LicenceMIT
Last update5 years ago25 Feb 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 indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

295 lines of Pine Script v4 from Matrix functions and operations - test.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

Matrix functions and operations - test.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Joris Duyck

//@version=4
study("Matrix functions and operations -  test")

/// MATRIX INFO FUNCTIONS ///
//{
// OK! function to get total number of columns from a 2D matrix
//{
f_array2D_get_columns(_m) =>
    _columns = int(array.get(_m, 0))
    _columns
//}

// OK! function to get total number of rows from a 2D matrix
//{
f_array2D_get_rows(_m) =>
    _rows    = int(array.get(_m, 1))
    _rows
//}

// OK! function to get total number of columns and rows from a 2D matrix
//{
f_array2D_get_size(_m) =>
    _columns = int(array.get(_m, 0))
    _rows    = int(array.get(_m, 1))
    [_columns, _rows]
//}
//}

/// INITIALISATION AND SET FUNCTIONS ///
//{
// OK! 2D matrix init function, builds 2D matrix with dimensional metadata in first two values //
//{
f_array2D_init(_x, _y, _fill) =>
    _size  = int(_x * _y)
    _m     = array.new_float(_size + 2, _fill)
    array.set(_m, 0, _x), array.set(_m, 1, _y)
    _m
//}

// OK! function to set values in 2D matrix with (x, y) (index for x and y both starts at 0 !!)
//{
f_array2D_set(_m, _x, _y, _val) =>
    _columns = f_array2D_get_columns(_m)
    array.set(_m, 2 + int(_x + (_y * _columns)), _val)
//}
//}


/// GET FUNCTIONS ///
//{
// OK! function to get values from 2D matrix with (x, y) (index for x and y both starts at 0 !!)
//{
f_array2D_get(_m, _x, _y) =>
    _columns = f_array2D_get_columns(_m)
    _val     = array.get(_m, 2 + int(_x + (_y * _columns)))
    _val
//}

// OK! function to cut of the metadata header and return the array body
//{
f_array_get_body(_m) =>
    _array_body = array.copy(_m)
    for i = 0 to 1
        array.remove(_array_body, 0)
    _array_body
//}

/// 1D - 2D COORDINATE CONVERSION FUNCTIONS (handy with for loop indexes) /// SHOULD ROWS/RECORDS BE X OR SHOULD COLUMNS BE X????
//{
// OK! function to get x coordinate from 2D matrix from 1D index (index for x and y both starts at 0 !!)
//{
f_array2D_get_x(_m, _index) =>
    _columns = f_array2D_get_columns(_m)
    _x       = _index % _columns
    _x
//}

// OK! function to get y coordinate in 2D matrix from 1D index (index for x and y both starts at 0 !!)
//{
f_array2D_get_y(_m, _index) =>
    _columns = f_array2D_get_columns(_m)
    _y       = floor(_index / _columns)
    _y
//}

// OK! function to get( x, y) coordinates in 2D matrix from 1D index (index starts at 0 and does not include the header!!)
//{
f_array2D_get_xy(_m, _index) =>
    _columns = f_array2D_get_columns(_m)
    _x = (_index % _columns)
    _y = floor(_index / _columns)
    [_x, _y]
//}

// OK! function to 1D index from ( x, y) coordinates in 2D matrix (index for x and y both starts at 0 !! Index starts at 0 and does not include the header!!)
//{
f_array2D_get_index(_m, _x, _y) =>
    _columns = f_array2D_get_columns(_m)
    _index   = _x + _y * _columns
//}
//}
//}

/// MANIPULATION FUNCTIONS ///
//{
// OK! function to remove one or more rows/records from a 2D matrix (if from_row = to_row, only this row is removed)
//{
f_array2D_remove_rows(_m, _from_row, _to_row) =>
    [_columns, _rows] = f_array2D_get_size(_m)
    if not(_from_row == 0 and _to_row == _rows - 1) and not(_to_row < _from_row)
        _start_remove_index = 2 + _from_row * _columns
        for i = 1 to (min(_rows - 1, _to_row) - _from_row + 1) * _columns
            array.remove(_m, max(_start_remove_index, 2))
        array.set(_m, 1, _rows - (min(_rows - 1, _to_row) - _from_row) - 1)
    _m
//}

// OK! function to remove one or more columns from a 2D matrix (if from_row = to_row, only this row is removed)
//{
f_array2D_remove_columns(_m, _from_column, _to_column) =>
    [_columns, _rows] = f_array2D_get_size(_m)
    if not(_from_column == 0 and _to_column == _columns - 1) and not(_to_column < _from_column)
        for _y = (_rows - 1)  to 0
            _start_remove_index = 2 + _y * _columns + _from_column
            for i = _from_column to _to_column
                array.remove(_m, max(_start_remove_index, 2))
        array.set(_m, 0, _columns - (min(_columns, _to_column) - _from_column) - 1)
    _m
//}

// OK! function to insert an array of rows/records at a certain row number in a 2D matrix
//{
f_array2D_insert_array_rows(_m, _insert_array, _from_row) =>
    [_columns, _rows] = f_array2D_get_size(_m)
    [_columns_insert_array, _rows_insert_array] = f_array2D_get_size(_insert_array)
    _size_insert_array = _columns_insert_array * _rows_insert_array
    if _columns == _columns_insert_array
        _insert_array_body  = f_array_get_body(_insert_array)
        _start_insert_index = 2 + _from_row * _columns
        for index = (_size_insert_array - 1) to 0
            array.insert(_m, _start_insert_index, array.get(_insert_array_body, index))
        array.set(_m, 1, _rows + _rows_insert_array)
    _m
//}

// OK! function to insert an array of columns at a certain column number in a 2D matrix
//{
f_array2D_insert_array_columns(_m, _insert_array, _from_column) =>
    [_columns, _rows] = f_array2D_get_size(_m)
    [_columns_insert_array, _rows_insert_array] = f_array2D_get_size(_insert_array)
    _size_insert_array = _columns_insert_array * _rows_insert_array
    if _rows == _rows_insert_array
        _insert_array_body  = f_array_get_body(_insert_array)
        _start_insert_index = 2 + _columns * (_rows - 1)
        for _y = 0 to (_rows - 1)
            for index = 0 to (_columns_insert_array - 1)
                array.insert(_m, _start_insert_index - (_y * _columns) + _from_column, array.get(_insert_array_body, (_start_insert_index - 2) - (_y * _columns) + index))
        array.set(_m, 0, _columns + _columns_insert_array)
    _m
//}

// OK! function to append/add an array of rows/records to the bottom of a 2D matrix
//{
f_array2D_append_array_rows(_m, _append_array) =>
    [_columns, _rows] = f_array2D_get_size(_m)
    [_columns_append_array, _rows_append_array] = f_array2D_get_size(_append_array)
    if _columns == _columns_append_array
        _append_array_body = f_array_get_body(_append_array)
        array.concat(_m, _append_array_body)
        array.set(_m, 1, _rows + _rows_append_array)
    _m
//}

// OK! function to append/add an array of columns to the side of a 2D matrix
//{
f_array2D_append_array_columns(_m, _append_array) =>
    [_columns, _rows] = f_array2D_get_size(_m)
    [_columns_append_array, _rows_append_array] = f_array2D_get_size(_append_array)
    if _rows == _rows_append_array
        _append_array_body  = f_array_get_body(_append_array)
        _start_append_index = 2 + _columns * (_rows - 1)
        for _y = 0 to (_rows - 1)
            for index = 0 to (_columns_append_array - 1)
                array.insert(_m, _start_append_index - (_y * _columns) + _columns_append_array, array.get(_append_array_body, (_start_append_index - 2) - (_y * _columns) + index))
        array.set(_m, 0, _columns + _columns_append_array)
    _m
//}
//}

/// CALCULATION FUNCTIONS ///
//{
// OK! function for multiplication of 2D matrices, returns matrix c //
//{
f_array2D_mult(_a, _b) =>
    // get matrix metadata //
    _a_x = int(array.get(_a, 0)), _a_y = int(array.get(_a, 1)), _a_size = _a_x * _a_y
    _b_x = int(array.get(_b, 0)), _b_y = int(array.get(_b, 1)), _b_size = _b_x * _b_y
    _c_x = _b_x                 , _c_y = _a_y                , _c_size = _b_x * _a_y
    _c   = f_array2D_init(_b_x, _a_y, 0)
    // error check //
    if _a_x != _b_y
        array.fill(_c, 0)
    // multiplication //
    else
        row_nr = 0
        for i = 0 to (_c_x -1)
            i_val = 0.0
            row_nr := floor(i % _b_x)
            // row_nr := row_nr + ((i % _b_x) == 0 ? 1 : 0)
            for j = 0 to (_a_x - 1)
                i_val := i_val + (i % 2 == 0 ? 1 : -1) * array.get(_a, 2 + j + (row_nr * _a_x)) * array.get(_b, 2 + (i % _b_x) + j * _b_x)
            array.set(_c, 2 + i, i_val)
    // return //
    _c
//}
//}

// OK! function to print matrix
//{
f_array2D_print(_m) =>
    _text = "(" + tostring(array.get(_m, 0)) + "x" + tostring(array.get(_m, 1)) + ")"
    _text := _text + "\n" + "\n"+"["
    for i = 2 to array.size(_m) - 1 
        _text := _text + (i == 2 ? "" : ((i -2) % array.get(_m, 0)) == 0 ? "]" + "\n" + "[" : " ") + tostring(array.get(_m, i))
    _text := _text + "]"
//}

/// test section ///
// set test matrices
//{
a = array.new_float(8, 1)
array.set(a, 0, 2)
array.set(a, 1, 3)
array.set(a, 2, 1)
array.set(a, 3, 2)
array.set(a, 4, 3)
array.set(a, 5, 4)
array.set(a, 6, 5)
array.set(a, 7, 6)

b = array.copy(a)

append_array = array.new_float(8, 0)
array.set(append_array, 0, 2)
array.set(append_array, 1, 3)
array.set(append_array, 2, 10)
array.set(append_array, 3, 20)
array.set(append_array, 4, 30)
array.set(append_array, 5, 40)
array.set(append_array, 6, 50)
array.set(append_array, 7, 60)
//}


// parameters to check behavior of functions
x = input(0, title="from")
y = input(0, title="to")


// test function calls
// c = f_array2D_append_array_rows(a, append_array)
// f_array2D_append_array_rows(a, append_array)
// c = f_array2D_append_array_columns(a, append_array)
// f_array2D_append_array_columns(a, append_array)
// c = f_array2D_remove_row(a, x, y)
// f_array2D_remove_row(a, x, y)
// c= f_array2D_remove_column(a, x, y)
// _array2D_remove_column(a, x, y)
// c= f_array2D_insert_array_rows(a, append_array, x)
// f_array2D_insert_array_rows(a, append_array, x)
//c = f_array2D_insert_array_columns(a, append_array, x)
// f_array2D_insert_array_columns(a, append_array, x)
[e, c] = f_array2D_pop_column(a)

// plot matrices
//{
// copy of original matrix before "manipulation"
var label lbl_b = na, label.delete(lbl_b)
lbl_b := label.new(bar_index - 30, 0, text = f_array2D_print(b))

// "manipulation" matrix
var label lbl_append_array = na, label.delete(lbl_append_array)
lbl_append_array := label.new(bar_index - 20, 0, text = f_array2D_print(append_array))

// original matrix
var label lbl_a = na, label.delete(lbl_a)
lbl_a := label.new(bar_index - 10, 0, text = f_array2D_print(a))

// compy of resulting matrix
var label lbl_c = na, label.delete(lbl_c)
lbl_c := label.new(bar_index - 0, 0, text = f_array2D_print(c))
//}

Overview

Matrix functions and operations - test includes functions to initialize a 2D matrix with dimensions and fill values, set values at specific x-y coordinates, retrieve values by coordinates, get matrix size, remove rows, and convert between 1D indices and 2D coordinates. The functions store metadata in the first two array elements and operate on the remaining data.

Details

Published by

JorisDuyck on GitHub

Type

Indicator, Pine Script v4

Draws

Separate pane below the chart

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.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
fromint0x
toint0y
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

Asymmetrical RSI

by everget
948 stars

Asymmetrical RSI is an indicator that computes a custom relative strength index from the rate of change of a user-selected source. It plots the resulting ARSI line in a separate pane with color coding that turns green above the overbought level and red below t

Indicator v4 Oscillators & momentum
Updated 10 days ago · GPL-3.0 GitHub repository of Asymmetrical RSI

This indicator calculates momentum setups based on the Relative Strength Index (RSI) and plots in a separate pane. It offers multiple scanning modes such as Continuous Break, Continuous Retracement, Flip Break, Flip Retracement, and both regular and hidden div

Indicator v6 Oscillators & momentumDivergence Repaints
Updated 1 year ago · MPL-2.0 GitHub repository of Momentum Setup - RSI Directional Momentum Indicator
549 stars

Range Volume Change compares volume inside a chosen session window with the same window on the previous day and plots that change as a percentage. It accumulates volume during the window and, when enabled, volume outside it, drawing growing columns in a separa

Indicator v5 VolumeSessions & time Repaints
Updated 10 months ago · None stated GitHub repository of Range Volume Change

Beep Boop

by magic8bot
409 stars

This indicator calculates a modified MACD oscillator and signal line alongside a trend EMA filter, plotting the output as a stylized column histogram in a separate pane. Instead of plotting true MACD distance, it quantifies positive and negative histogram mome

Indicator v4 Oscillators & momentumTrend
Updated 3 years ago · MIT GitHub repository of Beep Boop

Mojito v3 Strategy

by namuan
318 stars

The Mojito v3 Strategy indicator evaluates volatility term structure by calculating the ratio between front-month and second-month VIX futures contracts. It smooths this ratio using a configurable median filter and compares the result against user-defined uppe

Indicator v5 Volatility & bands
Updated 2 months ago · MIT GitHub repository of Mojito v3 Strategy

More indicators

Trade Your Charts With a Regulated Broker

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

Compare brokers