# Return Previous Value until new Signal

Hi All,

I am very new to AFL, I am not a programmer but I use google to my advantage to write up some simple programs. I am trying to code an indicator for one of my trading systems I hope if someone can help me.

The system is
If EMA9 crosses above/below EMA20 while both EMA lines are Under/Over VWMA50 then throw a long or short signal. I am using a histogram to return a value of +1 if it is a long signal and value of -1 if it is a short signal.

The challenge I am facing is that I want the signal to show up on next bars as well until I get an opposite signal. For example EMA9 Crosses Over EMA20 then the value would be +1 I would like the value of +1 to appear on every bar until I get an opposite signal of -1. I am not having any luck to get this working.

I have tried LastValue function and Cum function but no luck. I am getting a feeling I might have to use for loop function which I struggle to understand.

Below is my code

``````_SECTION_BEGIN("MACrossSignal");
SlowMA = 9 ;
FastMA = 20 ;
VolMA = 50 ;

MA9 = EMA(C,SlowMA);
MA20 = EMA(C, FastMA);
VWMA = MA(C*V,VolMA)/MA(V,VolMA);

Value1  = MA9-MA20;
Value2 = MA9-VWMA;
Value3 = Ma20-VWMA;

LongCond1 = Cross(Value1,0);
LongCond2 = Value2<0;
LongCond3 = Value3<0;

ShortCond1 = Cross(0,Value1);
ShortCond2 = Value2>0;
ShortCond3 = Value3>0;

Direction = iif(LongCond1 AND LongCond2 AND LongCond3,1,IIf(ShortCond1 AND ShortCond2 AND ShortCond3,-1,0));

Value = IIf(Direction==0,LastValue(Ref(Direction,-1)),Direction);

Plot(Value, _DEFAULT_NAME(),
IIf( Value==1, colorGreen, IIf(Value==-1,colorRed,Null)),
ParamStyle( "Style", styleHistogram | styleThick, maskHistogram  ) );
_SECTION_END();

``````

I would very much appreciate if you could advise me on this.

Thank you.

LastValue retunrs element which is last value of array.
It does not return array being previous value.
https://www.amibroker.com/guide/h_understandafl.html
http://www.amibroker.com/guide/afl/lastvalue.html

You an use Flip() function similar to

So,...

``````_SECTION_BEGIN("MACrossSignal");
SlowMA = 9 ;
FastMA = 20 ;
VolMA = 50 ;

MA9 = EMA(C,SlowMA);
MA20 = EMA(C, FastMA);
VWMA = MA(C*V,VolMA)/MA(V,VolMA);

Value1  = MA9-MA20;
Value2 = MA9-VWMA;
Value3 = Ma20-VWMA;

LongCond1 = Cross(Value1,0);
LongCond2 = Value2<0;
LongCond3 = Value3<0;

ShortCond1 = Cross(0,Value1);
ShortCond2 = Value2>0;
ShortCond3 = Value3>0;

/// "fix"
long_cond = LongCond1 AND LongCond2 AND LongCond3;
short_cond = ShortCond1 AND ShortCond2 AND ShortCond3;

Direction1 = Flip(long_cond, short_cond);
Direction2 = Flip(short_cond, long_cond);
Value = Direction1 - Direction2;

Plot(Value, _DEFAULT_NAME(), IIf(Value==1, colorGreen, IIf(Value==-1,colorRed,-1)),
ParamStyle( "Style", styleHistogram | styleThick, maskHistogram  ) );
_SECTION_END();
`````` 1 Like

Thank you, this is excellent! I did not know that function.

I will read the docs again you have listed.