Need Help with trading another symbol if first symbol has no entry

Hello, purchased AB a couple months ago and learning to code. I am new to coding so I am still trying to figure out a lot of the terms. I have been able to code a few simple strategies but having a real hard time with this one.

The code should always check if the price of SPY is above the 20MA first. if this is true than buy SPY and exit when the price of SPY is below the 20MA. If the price of SPY is not above the 20MA, Then TLT should be checked. If the price of TLT is above its 14MA then buy TLT and exit when the price of TLT is below 14MA.. I tried to use SetForeign, but I don't think that's the right command to select the symbol to trade. Here is the code I came up with and I know it's very wrong due to my results. I would appreciate any help, thank you for your time.

SetOption("AllowSameBarExit",False);					
SetOption( "MaxOpenPositions", 1 );
SetTradeDelays(1,1,0,0); 	

spyClose = Foreign( "SPY", "C" );
tltClose = Foreign( "TLT", "C" );

spyAboveMA = spyClose > MA( spyClose, 20 );


if( spyAboveMA = True )
{
SetForeign ("SPY");
	movingAv20 = MA(C, 20);					
	movingAvAbove20 = C > movingAv20 ; 		
	movingAvBelow20 = C < movingAv20 ; 		


	BuyLevel = llV(movingAvAbove20,1);		
	SellLevel = llV(movingAvBelow20,1);		
	BuySignal = BuyLevel; 	

	Buy = BuySignal;				
	BuyPrice = Close;	

Sell = SellLevel;						
SellPrice = Close;						
}
else
 if( spyAboveMA = False )
{
    SetForeign ("TLT");
	movingAv14 = MA(C,14);					
	movingAvAbove14 = C > movingAv14 ; 		
	movingAvBelow14 = C < movingAv14 ; 		


	BuyLevel = llV(movingAvAbove14,1);		
	SellLevel = llV(movingAvBelow14,1);		
	BuySignal = BuyLevel ;	

	Buy = BuySignal;				
	BuyPrice = Close;	


Sell = SellLevel;						
SellPrice = Close;			
}

Something along these lines...

/// @link https://forum.amibroker.com/t/need-help-with-trading-another-symbol-if-first-symbol-has-no-entry/26860/2
SetOption("AllowSameBarExit",False);					
SetOption( "MaxOpenPositions", 1 );
SetTradeDelays(1,1,1,1); 	

spyClose = Foreign( "SPY", "C" );
spyAboveMA = spyClose > MA( spyClose, 20 );

movingAv = MA(C, IIf(Name() == "SPY", 20, 14));					
movingAvAbove = C > movingAv; 		
movingAvBelow = NOT movingAvAbove; 	
	
BuySignal = movingAvAbove;
SellSignal = movingAvBelow;	

if ( Name() == "SPY" ) 
{
	SetPositionSize(1, spsShares);

	Buy = BuySignal AND spyAboveMA;				
	BuyPrice = Close;	

	Sell = SellSignal /*OR NOT spyAboveMA*/;						
	SellPrice = Close;	
}

if( Name() == "TLT" )
{
	SetPositionSize(1, spsShares);

	Buy = BuySignal AND NOT spyAboveMA;				
	BuyPrice = Close;

	Sell = SellSignal OR spyAboveMA;						
	SellPrice = Close;			
}


There is another code about SPY and TLT here

I was able to adjust the code you provided to get the results I was looking for. It also helped me understand the concept of IIF(). Thank you again for your time.

1 Like

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