Can I ask how do I get my IF statement to work?

Customer’s question:

Can I ask how do I get my IF statement to work? I am trying to get a trade activated only IF the closing price is above the 100D Simple MA.

So I did the following:

X1 = CalcMA( Close, 100);

If (Close > X1)

But it doesn’t seem to work? It compiles and runs but no trades at all.


Do not use IF. It does not work as expected most of time.

The result of IF should be TRUE or FALSE.

One value.

But your “If (Close > X1)” compares all bars. All Close and X1 values.
Say you have a time range one year. So it compares all values within a year. It means we have about 260 TRUEs or FALSEs.
Which is the “correct one”? It does not make sense.

Use Cross(Close,X1) for your purposes.

It returns a vector of FALSEs for almost all bars. Just in bars where Close crosses an MA(100) line up, it is TRUE.

So if you use Buy = Cross(Close,X1);, you will Buy in moments where Close goes above MA(100).

Try the following code for MSFT. See Exploration and Charts too.

// Set initial capital 

// Positions sizes: use 25% of the current portfolio equity. (It means max. 4 open positions.)
SetPositionSize( 25, spsPercentOfEquity );

// Round a number of shares to 100. 

X1 = CalcMA( Close, 100); 

// Buy where Close crosses MA(100) up
Buy = Cross(Close,X1);      
// Sell where Close crosses MA(100) down
Sell = Cross(X1,Close);

// Show Buy signals in Exploration
Filter = Buy; 

// Uncomment next two lines to show Buy and Sell in Exploration
//  Filter = Buy OR Sell; 
// AppendColumn(Sell,"Sell",format=1.0);

// Show charts