Reputation: 379
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)
Upvotes: 11
Views: 15085
Reputation: 908
you can use an object to hold a variable that can be changed.
type MyGlobalVar
float value
var myGlobalVar = MyGlobalVar.new(1.0)
modify() =>
myGlobalVar.value := 5.0
modify()
Upvotes: 2
Reputation: 84
Here is one way, where a custom type is used to hold the state.
//@version=5
library("MyLib", overlay=true)
export type MyLib
int i
export init() =>
MyLib.new(0)
export foo(MyLib this) =>
this.i += 1
Usage example:
if barstate.isfirst:
state = MyLib.init()
log.info("{0}", MyLib.foo(state))
Upvotes: 0
Reputation: 2412
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 have opened many 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)
Upvotes: 19