You don't need static vars, was: Need guidance with Static Variable

I'm working on a system that uses RSI(14) as a trend indicator. When RSI(14) reaches 70 or higher, the condition is said to be "uptrend" and remains so until RSI(14) reaches 30 or lower when the condition then changes to "downtrend". From there, I am tinkering with mean reversion buy signals only such as RSI(2) < 20 that occur only when the condition is "uptrend".

I've read a number of posts regarding Static Variables but I'm still confused about their use, syntax, etc. Is that what I need to code the example I gave here? If so, does anyone have any example code using Static Variables that might be similar that I can use as a guide?

Many thanks for the assistance.

You don't need Static variables for that.

static variables(SV) are used to store state between formula runs because normal AFL variables dont do that. SV can also persist between AB open and exit.

The state you seem to want to retain can be achieved using Flip if I understand your need correctly.

rsi14 = RSI(14);
trend = Flip( cross( rsi14,70 ), cross( 30, rsi14 ) );

// iif( trend ==1, we are in uptrend, else trend changed)

Flip() will retain state after a condition has occurred, so it will return true for the period even if rsi goes below 70 but remains above 30. It will only return false when it goes below 30. Again it will retain false even when going above 30 until it crosses 70.

AFL Function Reference - FLIP (


@nsm51 advice is very good.
I would like to add one thing: It is important to understand that "state" may mean different things.

In this particular case "state" refers to what happens between bars in single array in single formula execution. These are signals in "state" form (like in C > MA( C, 15 ) as opposed to "impulse" form (like Cross( C, MA( C, 15 ) )). These are just different ways to view signals in time domain.
For that you don't need static variables and you should use @nsm51 advice.

The "state" in the meaning of Static variables refers to lifetime of variable BEYOND the single formula execution. Static variables live AFTER formula execution has ended.


Thanks so very much to you and to Tomasz.

I'm quite certain I never would have figured this out without your help. I was about to start tinkering more with static variables first before posting but decided that posting was the better plan.

Good trading to you all!

This topic was automatically closed 100 days after the last reply. New replies are no longer allowed.