How do i shorten this code - page 2

 
Renz Carillo:
It is originally in my condition for a buy/sell signal, i only incorporated sell signal in my code above so it would be alot easier to help me

Then think about what your code is doing and modify it.

 
Renz Carillo:

I've got it now, i was all confused with loops but i managed to get through it with your provided codes. Thank you very much! 

I'm going to leave the solution here 

As I said, think about what your code is doing.

You are executing a loop with 3 possible outcomes, buy trend, sell trend and no trend

yet you are using a bool which can only be true or false.

3 into 2 don't go!

 
Keith Watford:

As I said, think about what your code is doing.

You are executing a loop with 3 possible outcomes, buy trend, sell trend and no trend

yet you are using a bool which can only be true or false.

3 into 2 don't go!

I now changed my code into string from bool, and i can't still figure it out why it doesn't work.

Basically what i wanted is every piece of (emaTrend>High) from the last 10 candles to be true for a sell signal and vice versa for a buy signal.

Here is the code: 

string trend()
{
string status;
int i;
for (i=0; i<10; i++)
{
double emaTrend = iMA (NULL,0,200,0,MODE_EMA,PRICE_CLOSE,i);
    if (emaTrend > High[i]) //sell signal
    {
    status = "downtrend"; break;
    } 
    else if (emaTrend < Low[i]) // buy signal
    {
    status = "uptrend"; break;
    } 
}
return status;
}
 

I repeat once again,  think about what your code is doing.

if MA[0] > High[0], the first pass through the loop what does your function return?

Where does it check the rest of the MA values?

 
Keith Watford:

I repeat once again,  think about what your code is doing.

if MA[0] > High[0], the first pass through the loop what does your function return?

Where does it check the rest of the MA values?

to be perfectly honest i still don't get it, this is driving me nuts 🤦🏼‍♂️
 
    if (emaTrend > High[i]) //sell signal
    {
    status = "downtrend"; break;
    } 

if this is true with the first pass, the loop will break and the function will return "Downtrend", it will not check the other bars.


Normally, I would not use 2 loops where 1 will do.

In this case i think that you would be better to use 2 loops. 1 to check for a buy trend and another for sell.

That way you can adapt the first code example that I gave you.