Help needed with MS formula

nitinsy

Active Member
#1
Hi,
I am trying to code this logic (essentially an X day range switch indicator)

1. Buy when close of today is higher than highs of last X days
2. Sell when close of today is lower than low of last X days

This indicator will always be in trade. I have coded it in MS as an expert advisor. Problem is, I get multiple buy signals one after another when price is moving up on a day-to-day basis.

I need to only signal a buy when this condition occurs for the first time (change in bias from short position). Thereafter it is in buy mode until #2 occurs (change in bias from long position).

Vice-versa for sell trades

Couldn't figure out how to do it in MS. I know its possible because I have a password protected implementation of this indicator. I am trying to improve on this system.

Any help will be appreciated

Thanks in advance
Nitin
 

skarpio

Active Member
#2
use a boolean variable. call it buyOn.
Code:
1. at the begining, set buyOn = false
2. if (C(today) > HH(close, X) and !buyOn)
      a. set buyOn = true
      b. plot buy signal
3. if (C(today) < LL(close, X) and buyOn)
      a. set buyOn = false
      b. plot sell signal
Note: I am not familiar with MS syntax. This is only a pseudo code. Moreover, if booleans are not available in MS, use an integer variable with states 0 and 1.
 

nitinsy

Active Member
#3
Thanks Skarpio. I understand this logic very well. I just don't know how to maintain a variable across multiple bar calculations in Metastock.

From what I understand, variables have local scope

Nitin
 
U

uasish

Guest
#4
Use Barssince function for buyOn (as skarpio mentioned) > Barssince sellOn & vice versa.
 

oxusmorouz

Well-Known Member
#5
{Input}
a:= 30; {Look back period}

{Variable}
b:= HHV(C,a);
d:= LLV(C,a);

{Prelimary condition}
f:= C = b;
g:= C = d;

{Binary}
i:= BarsSince(f) < BarsSince(g);
i
 

nitinsy

Active Member
#7
Thanks everyone. BarsSince works quite well in this situation.

On a general note, how can I handle this situation

1. On 12th July bar, I calculated some expression and stored its value in a variable
2. On 13th July (next bar), I want to use the result of #1 above and calcuate a new result - which is then stored in the same variable
3. On 14th July, I want to use data from #2 above to recalculate new value of expression

Thanks
Nitin
 

Similar threads