Hi. A beginner coder here, looking for some guidance on a piece of code I'm trying to write.
I'd like to write a function that uses the previous day's value of a variable to calculate today's variable (for several variables). Even though I have 6 or 7 variables, it only needs to look back 1 day so I searched here and found what seems to be the simplest solution which is to declare global variables and then use getBarState() to store the T-1 values (rather than use ref() or some array solution). Here's a snippet of the code I wrote:
As it stands the function returns nothing on the chart. I have tested it and the function returns values correctly for c0, c1 and c2. It also returns a value if I take out the (i1_1) value in the final calculation of i1. So this led me to believe that either I have the getBarState() function wrong or some kind of null/recursive error in calculating i_1.
Can anyone give some pointers? Also if anyone can suggest a more elegant way of doing the null checks (or for the entire setup of the script for that matter), I would be most grateful. Thank you.
I'd like to write a function that uses the previous day's value of a variable to calculate today's variable (for several variables). Even though I have 6 or 7 variables, it only needs to look back 1 day so I searched here and found what seems to be the simplest solution which is to declare global variables and then use getBarState() to store the T-1 values (rather than use ref() or some array solution). Here's a snippet of the code I wrote:
PHP Code:
function preMain() {
setStudyTitle("test");
setCursorLabelName("test", 0);
}
var i1;
var i1_1;
var i2;
var i2_1;
function main(constA, constB) {
if (constA == null) {
constA = 10;
}
if (constB == null) {
constB = 1;
}
if ( isNull(i1) ) {
i1 = 0;
}
if ( isNull(i2) ) {
i2 = 0;
}
if ( isNull(i1_1) ) {
i1_1 = 0;
}
if ( isNull(i2_1) ) {
i2_1 = 0;
}
if ( getBarState() == BARSTATE_NEWBAR ) {
i1_1 = i1;
i2_1 = i2;
}
//Const Variables
var c0 = (constA - 1.0) * constB + 1.0;
var c1 = 2 / (c0 + 1.0);
var c2 = 1 + c1;
//Calc
if ( close(0) > 0 ) {
i1 = c1 * close(0) + c2 * i1_1 ;
i2 = c1 * i1 + c2 * i2_1;
}
return new Array (i1, i2)
}
Can anyone give some pointers? Also if anyone can suggest a more elegant way of doing the null checks (or for the entire setup of the script for that matter), I would be most grateful. Thank you.
Comment