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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With