Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Change global variable from function in pine script?

Tags:

pine-script

i am trying to write a script to get gann square of 9 levels. I have done it another languages but cant understand the pine script here it says Cannot modify global variable in function. Is there any solution to get the value here is my script

//@version=4
study(title="Volume-weighted average example", max_bars_back=5000, overlay=true)
timeDiff = time - time[4]

// Translate that time period into seconds
diffSeconds = timeDiff / 1000

// Output calculated time difference
//plot(series=diffSeconds)
var ln = 0
var wdvaltrg = 0.0

WdGann(price) =>
    for i = 1 to 8
        wdvaltrg := (ln+(1/i))*(ln+(1/i))
        if wdvaltrg >= price
            break
    if wdvaltrg < price
        ln := ln+1
        WdGann(price)

var vwap0935 = 0.0
v = vwap
if hour == 9 and minute == 35
    vwap0935 := v



plot(vwap0935)
like image 828
Mijanur Rahaman Avatar asked Mar 28 '20 17:03

Mijanur Rahaman


Video Answer


1 Answers

Since September 10, 2020 arrays are available in pine. And using that you can store values created in function in global scope.

This works, because writing array elements does not alter the actual array variable's reference. So you just use the global array and modify its content as you would do outside of your function.

Arrays are opened a lot of possibilities in pine script.

A simple example:

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © wallneradam
//@version=4
study("Global variables", overlay=false)

// Declare constants to access global variables
IDX_STOCH = 0
IDX_RSI = 1

// Initialize an empty array to store variables
global = array.new_float(2)

// This is the modify the array
calculate(period) =>
    v_stoch = stoch(close, high, low, period)
    v_rsi = rsi(close, period)
    array.set(global, IDX_STOCH, v_stoch)
    array.set(global, IDX_RSI, v_rsi)
     
// Call the function any times you want
calculate(14)
// Plot the results
plot(array.get(global, IDX_STOCH), color=color.red)
plot(array.get(global, IDX_RSI), color=color.yellow)
// Call the function any times you want
calculate(14 * 5)
// Plot the results
plot(array.get(global, IDX_STOCH), color=color.maroon)
plot(array.get(global, IDX_RSI), color=color.olive)
like image 123
Adam Wallner Avatar answered Oct 24 '22 11:10

Adam Wallner