Multiple Buy Conditions but only one executing

I have a simple script with 2 independent buy signals, Buy1 and Buy2. However, only Buy1 gets executed, Buy2 never gets executed. I think I am using the { } incorrectly or need to use "else" but cannot figure out how to do this correct.

Thanks,

Mike

TLT_Close = Foreign("TLT", "C");

SPY_Close = Foreign("SPY", "C");

LongTerm=ROC(TLT_Close,3);
ShortTerm=ROC(SPY_Close,3);

Buy1=ShortTerm > Longterm   ;
Buy2=ShortTerm < Longterm   ;

Sell1=ShortTerm < Longterm   ;
Sell2=ShortTerm > Longterm   ;

BuyPrice=SellPrice=C;
n = Name();

for( i = 0; i < BarCount; i++ ) { 
if(n=="SPY" && Buy1[i]) {
	Buy = Buy1 ;
    SetPositionSize(30,spsPercentOfEquity);
    Sell = Sell1 ;
    }
 if (n=="SPY" && Buy2[i]) {
	Buy = Buy2  ;
    SetPositionSize(70,spsPercentOfEquity);
    Sell = Sell2;
	}
if(n=="QQQ" && Buy1[i]) {
	Buy = Buy1 ;
    SetPositionSize(70,spsPercentOfEquity);
    Sell = Sell1 ;
    }
 if (n=="QQQ" && Buy2[i]) {
	Buy = Buy2  ;
    SetPositionSize(30,spsPercentOfEquity);
    Sell = Sell2;
	}	
}

ApplyStop( stopTypeNBar, stopModeBars, 1);

These lines are not right. You are replacing an entire Array in a Barcount loop for each iteration so only the last executed ith value will be in Buy Array.

Ok, so how do I edit it so that the entire Array is not in the Barcount loop?

Use loop element Buy[i] = ...;

SetPositionSize should be called Unconditionally.

PositionSize is also an Array system variable, so you can create an Array and update the position for each bar ie. 30 or 70 and then pass that array to SetPositionSize() as Michael suggested once unconditionally.

@reds,

The correct way to apply dynamic position sizing I have already provided to you in a recent previous thread.

SPY_close = Foreign("SPY", "C");
SPY_trendup = SPY_close > MA(SPY_close, 200);

SetPositionSize(IIf(SPY_trendup, 10, 5), spsPercentOfEquity);
2 Likes

You have to first READ about array processing. Everything in AmIBroker is array based

SetPositionSize is an array function. You should NOT call it for everybar. You call it ONCE for ALL bars.

SetPositionSize must be called OUTSIDE the loop. Currently you are doing loop for all bars and it is wrong.

Proper code should be OUTSIDE the loop.

n = Name();
if(n=="SPY" )  SetPositionSize( IIF( Buy1, 30, 70 ),spsPercentOfEquity);
if(n=="QQQ" )  SetPositionSize( IIF( Buy1, 70, 30 ),spsPercentOfEquity);
2 Likes

@reds,

Apologies, I said SetPositionSize should be called unconditionally – I should have said must be called outside the loop.

1 Like

I want to thank everyone for their advice & expertise. I am trying to keep this example short and straightforward so I can understand and hopefully extrapolate to more advanced coding.

Thanks again,

Mike

1 Like

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