Skip to content

Variables

In Navi Stream we have 3 keywords to store value: let, var and varip.

The syntax of variable declarations is:

[<declaration_mode>] :[<type>] <identifier> = <expression>

where:

  • declaration_mode - is the variable mode, we can use let, var, varip 3 kinds.
  • type - used to declare the variable type, such as number, string (optional parameter).
  • identifier - variable name.
  • expression - the value of the variable, can be any expression.

let

let for define a mutable variable. Like let in JavaScript.

INFO

We don't have mutable and inmutable types in Navi Stream, so you can change the value of a variable at any time.

nvs
let b = 8;
let a = 1 + b;
// Now `a` value is 9

a += 2;
// Now `a` value is 11

You can assignment a new value to a variable at any time.

nvs
let a = 1;
a = 2;
a = 3;

var

var use for stream processing, it's like let but it's reset to the initial value at the end of each period.

TIP

var is a periodic let, its value is only fixed at the end of each period, and other times it is reset to the value at the beginning of the period.

The following example shows how to use var to calculate the current period:

nvs
var bar = 0;

bar += 1;

After run the code, we can get the following result:

idxbar
10
20
30
40
51
61
71
81
91
102

The result is consistent with the 5m periodic rule, you can see that the value of var variable is only determined at the end of the last 5m.

The following diagram shows the change of the var variable:

varip

varip use for stream processing, ensure that the value of each period is independent.

Use case

idxtimepricevolume
110:00100.25300
210:01100.50200
310:02100.75100
410:03101.00300
510:04101.25200
610:05101.50100
710:06101.75300
810:07102.00200
910:08102.25100
1010:09102.50300
1110:10102.75200

Now, we use varip to calculate the total amount of each period (5m):

nvs
varip total_amount = 0;

total_amount += trade.volume;

If we calculate it, we can get:

idxtotal_amount
1300
2500
3600
4900
51100
61200
71500
81700
91800
102100
112300

barstate.is_confirmed

WARNING

Navi Stream's calculation cycle is a little special, the last data in each cycle (period) will be calculated twice, the last data will be calculated once in confirmed mode.

When in the last data of the period, barstate.is_confirmed is true, so we need to judge it to avoid total_amount being calculated twice.

We expected to output data only at the end of each period, so we can write like this:

nvs
varip total_amount = 0;

if (barstate.is_confirmed) {
  alert(`total_amount: {total_amount}`);
} else {
  total_amount += trade.volume;
}

Then Navi Stream well send alert like this:

idxtotal_amount
5"total_amount 1100"
11"total_amount 2300"