Debug Code - unexpected result

I have an analysis project that is giving a result that I do not understand. I was hoping to see whether someone could see why.

My code is:

//Settings
SetOption("InitialEquity",100000);
SetOption("CommissionMode",2);/* set commissions AND costs as $ per trade*/
SetOption("CommissionAmount",9.50); /* commissions AND cost */
SetTradeDelays( 0, 1, 1, 1 );
SetBacktestMode( backtestRegular );
  
Totalpositions = 20;
SetOption("MaxOpenPositions", Totalpositions );
PositionSize = -100 / Totalpositions ;
 
Tradeday = Month() != Ref(Month(), 1);	//	Rotate only at monthly close	

FallingN = Optimize("Falling",3,2,5,1); 
n = -FallingN;

EMA10opt = Optimize("OM_10",2,2,11,1); 
EMA50OPT = Optimize("OM-50",19,12,23,1); 
EMA150OPT = Optimize("OM_150",32,24,34,1); 



EMA10 = EMA(C,EMA10opt);
EMA50 = EMA(C,EMA50opt);
EMA150 = EMA(C,EMA150opt);


EMACondition = Round(EMA10*100)>Round(Ref(EMA10,n)*100) AND Round(EMA50*100)>Round(Ref(EMA50,n)*100) AND Round(EMA150*100)>Round(Ref(EMA150,n)*100);


BuyPrice = Open;
SellPrice = Open;

//n =-10;
ED2 = 1191231;  // Long end date for symbols


Filter = 1; // show all bars
AddColumn(C,"Close", 1.2);
AddColumn(EMA10,"EMA10",1.4);
AddColumn(EMA50,"EMA50",1.4);
AddColumn(EMA150,"EMA150",1.4);




//This is ilter to try and filter out low volume stocks

VolA = Volume * C;
MAVol = MA( VolA, 90 );
AddColumn(MAVol, "90day$MAVOL",1.0);
AddColumn(VolA, "$VOL",1.0);





 
dn = DateNum();
switch( Name() ) {
    case "APE": enddate1  = 1140303; Reentry = 1150716; enddate2 = 1170227;  datecond = ( dn >= 1121018 AND dn < enddate1 ) OR  ( dn >= reentry AND dn < enddate2 ); exitdatecond1 = dn >= enddate1 AND dn < reentry; exitdatecond2 = dn >= enddate2; exitdatecond = exitdatecond1 OR exitdatecond2; break;
  
		default:
		datecond = true;
		exitdatecond = false;
		
		break;
}

Buy = (C>EMA10) AND (C>EMA50) AND (C>EMA150) AND datecond AND MAVol >500000 AND (EMACondition);
Sell = (EMA50> C)  OR Sell = exitdatecond;

AddColumn( IIf( Buy, 66, 83 ), "Signal", formatChar );
AddColumn( Buy, "Buy", 1 );
AddColumn( Sell, "Sell", 1 );


//buy = ExRem( buy, sell );
//sell = ExRem( sell, buy ); 

PlotShapes( Buy*shapeUpArrow, colorGreen, 0, Low ); 
PlotShapes( Sell*shapeDownArrow, colorRed, 0, High ); 

SetCustomBacktestProc("");
if( Status("action") == actionPortfolio )
{
bo = GetBacktesterObject();
bo.Backtest();
AddToComposite( bo.EquityArray,
"~~~MY_EQUITY_SDT", "X",
atcFlagDeleteValues | atcFlagEnableInPortfolio );
}

I have edited the code to show only one stock, That being APE.ax [AP Eagers listed on the Australian stock exchange]

I am running the code on a Monthly Periodicity set in the settings. I commencing period being 1 July 2015 to present.

When the analysis is run I am getting a Buy and sell in the same month [July 2015]. Then there is a new buy in August 2015 which continues through to October 2016. [as per attached image]
APE

What I cannot identify is why I get a buy and sell in July 2015. I guess I am doing something daft but can't see what.

Any help would be appreciated.

Start by looking at your Sell statement.

//Sell = (EMA50> C)  OR Sell = exitdatecond; // Wrong - "OR  Sell = " redefines Sell
Sell = (EMA50> C)  OR exitdatecond; // Maybe this is what you are after?

Also see How do I debug my formula?

Hi MacAllan,

Thanks for your input re the Sell condition. I have made that change but this has not fixed the problem.

I will have a look at debugging. I have tried but at this point not properly - I will need to do some more education here.

First of all, you have future leak at entry.
You have zero delay at entry but entry price being at Open and entry rule having Close and EMA10.

Then as for Sell on July 2015... it is selling there because your date condition says so

Reentry = 1150716;
exitdatecond1 = dn >= enddate1 AND dn < reentry;

So it says if date is less than July 16 then exit.

Since you have set monthly periodicity it is does not look intra-bar for day information. Monthly bar does not have day info. It is just one bar with one time OHLCV... each and single date. So it exits in July since your date is part of July 2015 monthly bar. Also you have sell delay of 1 bar so the signal is at end of June but exit at July monthly bar Open (see your SellPrice). It shows end of bar date because of Tools-Preferences-Intraday -> "Override:..." setting.

If you want to check exact day then go opposite way... use Time Frame functions and go to shorter interval than Monthly and compress price/volume data to monthly there (Price-EMA condition and MA volume check). For date check you may use shorter interval data.

2 Likes

Hi fxshrat,

I appreciate your help here.

Firstly I understand your advice re "entry dates" and comments on delays.

I am struggling on Time Frame functions. I will continue to plod though, but at this point it is doing my head in.

What I am trying to achieve is to run my backtest on the last day of the month, for instance on 30 June 2015 and for this to indicate buy/sells to execute on open 1 July 2015. However when I have run my code with a backtest for 30 June 2015 I am not getting any selections. The best I am getting is running it from 1 July 2015 to 31 July 2015 which then shows me what I should of bought on 1 July 2015, but that is in hindsight. [For clarification, I am running this backtest on a watchlist and not purely on one code "APE" that was shown in the original post]

Forgive me if I am daft, because I probably am. I will keep working on it, but will have to leave it for today as "my paid job" is demanding my attention :smiley:

TimeFrameSet(inMonthly); // calculates EMA on Monthly Basis

FallingN = Optimize("Falling",3,2,5,1); 
n = -FallingN;

EMA10Opt = Optimize("OM_10",2,2,11,1); 
EMA50OPT = Optimize("OM-50",19,12,23,1); 
EMA150OPT = Optimize("OM_150",32,24,34,1); 

EMA10 = EMA(C,EMA10Opt);
EMA50 = EMA(C,EMA50Opt);
EMA150 = EMA(C,EMA150Opt);

TimeFrameRestore();

EMACondition = TimeFrameExpand(Round(EMA10*100)>Round(Ref(EMA10,n)*100), inMonthly ) AND TimeFrameExpand(Round(EMA50*100)>Round(Ref(EMA50,n)*100), inMonthly ) AND TimeFrameExpand(Round(EMA150*100)>Round(Ref(EMA150,n)*100), inMonthly );

Here is quick fix (only written in formula editor so untested).

// possible fix version 1.0
// https://forum.amibroker.com/t/debug-code-unexpected-result/15628/7
//Settings
SetOption("InitialEquity",100000);
SetOption("CommissionMode",2);/* set commissions AND costs as $ per trade*/
SetOption("CommissionAmount",9.50); /* commissions AND cost */
SetTradeDelays( 0, 0, 0, 0); // we use Ref() instead
SetBacktestMode( backtestRegular );
  
Totalpositions = 20;
SetOption("MaxOpenPositions", Totalpositions );
PositionSize = -100 / Totalpositions;
 
new_month = Month() != Ref(Month(), -1);	

FallingN = Optimize("Falling",3,2,5,1); 
n = -FallingN;

EMA10opt = Optimize("OM_10",2,2,11,1); 
EMA50OPT = Optimize("OM-50",19,12,23,1); 
EMA150OPT = Optimize("OM_150",32,24,34,1); 

tmfrm = inMonthly;
TimeFrameSet( tmfrm );
	EMA10 = EMA(C,EMA10opt);
	EMA50 = EMA(C,EMA50opt);
	EMA150 = EMA(C,EMA150opt);

	EMACondition = Round( EMA10 * 100 ) > Round( Ref( EMA10, n ) * 100 ) AND
				   Round( EMA50 * 100 ) > Round( Ref( EMA50, n ) * 100 ) AND
				   Round( EMA150 * 100 ) > Round( Ref( EMA150, n ) * 100 );		
	
	//This is ilter to try and filter out low volume stocks			   
	VolA = Volume * C;
	MAVol = MA( VolA, 90 );			   		  
TimeFrameRestore();

expandmode = expandLast;
EMA10 = TimeFrameExpand( EMA10, tmfrm, expandmode );
EMA50 = TimeFrameExpand( EMA50, tmfrm, expandmode );
EMA150 = TimeFrameExpand( EMA150, tmfrm, expandmode );
EMACondition = TimeFrameExpand( EMACondition, tmfrm, expandmode );

MAVol = TimeFrameExpand( MAVol, tmfrm, expandmode );
MAVol = TimeFrameExpand( VolA, tmfrm, expandmode );

price = TimeFrameGetPrice("C", tmfrm, 0, expandmode);

dn = DateNum();
switch( Name() )
{
case "APE":
    enddate1  = 1140303;
    Reentry = 1150716;
    enddate2 = 1170227;
    datecond = ( dn >= 1121018 AND dn < enddate1 ) OR( dn >= reentry AND dn < enddate2 );
    exitdatecond1 = dn >= enddate1 AND dn < reentry;
    exitdatecond2 = dn >= enddate2;
    exitdatecond = exitdatecond1 OR exitdatecond2;
    break;

default:
    datecond = true;
    exitdatecond = false;
    break;
}

BuyPrice = Open;
SellPrice = Open;

Buy = (price>EMA10) AND (price>EMA50) AND (price>EMA150) AND datecond AND MAVol >500000 AND EMACondition;
Buy = Ref(Buy, -1) AND new_month;

Sell = EMA50> price;
Sell = (new_month AND Ref(Sell,-1)) OR exitdatecond;

Short = Cover = 0;

Filter = new_month OR exitdatecond; // show start of month only
AddColumn(price,"Close", 1.2);
AddColumn(EMA10,"EMA10",1.4);
AddColumn(EMA50,"EMA50",1.4);
AddColumn(EMA150,"EMA150",1.4);

AddColumn(MAVol, "90day$MAVOL",1.0);
AddColumn(VolA, "$VOL",1.0);
AddColumn( IIf( Buy, 66, 83 ), "Signal", formatChar );
AddColumn( Buy, "Buy", 1 );
AddColumn( Sell, "Sell", 1 );


//buy = ExRem( buy, sell );
//sell = ExRem( sell, buy ); 

PlotShapes( Buy*shapeUpArrow, colorGreen, 0, Low ); 
PlotShapes( Sell*shapeDownArrow, colorRed, 0, High ); 

SetCustomBacktestProc("");

if( Status( "action" ) == actionPortfolio )
{
    bo = GetBacktesterObject();
    bo.Backtest();
    AddToComposite( bo.EquityArray,
                    "~~~MY_EQUITY_SDT", "X",
                    atcFlagDeleteValues | atcFlagEnableInPortfolio );
}

1 Like

Hi, thanks very much for that. I will have a look and see how far that get's me.

In fact I think I was getting there. I had taken my code onto a chart so that I could see what was happening. Anyway I will see what I can do tonight.

Again, thanks for your great input :smiley:

Hi fxshrat,

I have now had time to look at your suggested code. From what I have seen it is working a treat.

Thank you very much for your time and effort, whilst I was getting towards a solution, I was certainly floundering around.

1 Like

Hi fxshrat,

Can I ask for more help please.

I note your comment re "SetTradeDelays( 0, 0, 0, 0); // we use Ref() instead"

On the sell condition:

When the exitdatecond is true this does a sell at the open of that day. What is required is a sell at the open of the next day. I am not sure how to effect this using Ref()

Thanks...

Try:

Sell = (new_month AND Ref(Sell,-1)) OR Ref(exitdatecond,-1);
1 Like

Hi Trendsurfer, yes that works. Thank you :smiley:

1 Like

Hi, I am trying to insert a Setforeign Filter to this code. With the current "GFC" {Global Fear of CoronasVirus} it is apparent that an emergency parachute is required. I have found some code that I had for a Gann trend system which works as a ribbon, what I have been unsuccessful in achieving is for this to set an immediate sell when the Foreign code, in this case XAO goes negative.

The code that I have inserted being:

//TRYING TO ESTABLISH A EMERGENCY FILTER

tmfrm = inWeekly; 

_SECTION_BEGIN("SetForeign"); 


TimeFrameSet( tmfrm );  
 
SetForeign( "XAO" );

GraphXSpace = 5;
_SECTION_BEGIN( "Gann Trend" );
Us = BarsSince(Sum(H>Ref(H,-1),2)==2);
Ds = BarsSince(Sum(L<Ref(L,-1),2)==2);
Hc = HighestSince(Us==0,H,1);
Lc = LowestSince(Ds==0,L,1);
Sd1 = IIf(Us==0,IIf((L!=Lc) AND (Ref(L,-1)!=Lc),1,0),IIf(Ds==0,IIf((H!=HC) AND (Ref(H,-1)!=Hc),-1,0),0));
Sd2 = IIf(Sd1==1, IIf(Ref(BarsSince(Sd1==1),-1) >Ref(BarsSince(Sd1==-1),-1),1,0), IIf(Sd1==-1,IIf(Ref(BarsSince(Sd1==1),-1) < Ref(BarsSince(Sd1==-1),-1),-1,0),0));
TD1 = ValueWhen(Sd2!=0,Sd2,1);

//{Gann-Trend 4/27/99}
Sd =  TD1 ;    					//
//{Swing Change High}
Sch = IIf(Sd==1 AND Ref(sd,-1)==-1,1,0);
//{Swing Change Low}
Scl = IIf(Sd==-1 AND Ref(Sd,-1)==1,1,0);
//{Peak Value}
Pv = IIf(Scl==1,HighestSince(Sch==1,H,1),0);
//{Trough Value}
Tv = IIf(Sch==1,LowestSince(Scl==1,L,1),0);
//{Trend Direction}
Td = IIf(H>ValueWhen(Pv>0,Pv,1),1,IIf(L<ValueWhen(Tv>0,Tv,1),-1,0));
//{UpTrend=1 DownTrend =-1}
Tdv=ValueWhen(Td!=0,Td,1);   				//value when TD is not equal to zero

Plot( 1, "", IIf(tdv == 1,colorDarkGreen, IIf(tdv < 1, colorDarkRed, 0)), styleOwnScale|styleArea|styleNoLabel, -0.1, 50 );
											// This is the plot bar on bottom of screen, "GREEN" is BUY, "RED" is SELL
											//== 	Equal to  
											//!= 	Not equal to
						
RestorePriceArrays();

TimeFrameRestore(); 


_SECTION_END();  

For clarity the full AFL is


//TRYING TO ESTABLISH A EMERGENCY FILTER

tmfrm = inWeekly; 

_SECTION_BEGIN("SetForeign"); 


TimeFrameSet( tmfrm );  
 
SetForeign( "XAO" );

GraphXSpace = 5;
_SECTION_BEGIN( "Gann Trend" );
Us = BarsSince(Sum(H>Ref(H,-1),2)==2);
Ds = BarsSince(Sum(L<Ref(L,-1),2)==2);
Hc = HighestSince(Us==0,H,1);
Lc = LowestSince(Ds==0,L,1);
Sd1 = IIf(Us==0,IIf((L!=Lc) AND (Ref(L,-1)!=Lc),1,0),IIf(Ds==0,IIf((H!=HC) AND (Ref(H,-1)!=Hc),-1,0),0));
Sd2 = IIf(Sd1==1, IIf(Ref(BarsSince(Sd1==1),-1) >Ref(BarsSince(Sd1==-1),-1),1,0), IIf(Sd1==-1,IIf(Ref(BarsSince(Sd1==1),-1) < Ref(BarsSince(Sd1==-1),-1),-1,0),0));
TD1 = ValueWhen(Sd2!=0,Sd2,1);

//{Gann-Trend 4/27/99}
Sd =  TD1 ;    					//
//{Swing Change High}
Sch = IIf(Sd==1 AND Ref(sd,-1)==-1,1,0);
//{Swing Change Low}
Scl = IIf(Sd==-1 AND Ref(Sd,-1)==1,1,0);
//{Peak Value}
Pv = IIf(Scl==1,HighestSince(Sch==1,H,1),0);
//{Trough Value}
Tv = IIf(Sch==1,LowestSince(Scl==1,L,1),0);
//{Trend Direction}
Td = IIf(H>ValueWhen(Pv>0,Pv,1),1,IIf(L<ValueWhen(Tv>0,Tv,1),-1,0));
//{UpTrend=1 DownTrend =-1}
Tdv=ValueWhen(Td!=0,Td,1);   				//value when TD is not equal to zero

Plot( 1, "", IIf(tdv == 1,colorDarkGreen, IIf(tdv < 1, colorDarkRed, 0)), styleOwnScale|styleArea|styleNoLabel, -0.1, 50 );
											// This is the plot bar on bottom of screen, "GREEN" is BUY, "RED" is SELL
											//== 	Equal to  
											//!= 	Not equal to
						
RestorePriceArrays();

TimeFrameRestore(); 


_SECTION_END();  
  
  

// possible fix version 1.0 
// https://forum.amibroker.com/t/debug-code-unexpected-result/15628/7 

//Settings 
SetOption("InitialEquity",300000); 
SetOption("CommissionMode",2);/* set commissions AND costs as $ per trade*/ 
SetOption("CommissionAmount",9.50); /* commissions AND cost */ 
SetTradeDelays( 0, 0, 0, 0); // we use Ref() instead 
SetBacktestMode( backtestRegular ); 
   
Totalpositions = 20; 
SetOption("MaxOpenPositions", Totalpositions ); 
PositionSize = -100 / Totalpositions; 
  

  
  
new_month = Month() != Ref(Month(), -1);	 
 
FallingN = Optimize("Falling",3,2,5,1);  
n = -FallingN; 
 
EMA10opt = Optimize("OM_10",11,2,11,1);  
EMA50OPT = Optimize("OM-50",18,12,23,1);  
EMA150OPT = Optimize("OM_150",24,24,34,1);  
 
tmfrm = inMonthly; 
TimeFrameSet( tmfrm ); 
	EMA10 = EMA(C,EMA10opt); 
	EMA50 = EMA(C,EMA50opt); 
	EMA150 = EMA(C,EMA150opt); 
 
	EMACondition = Round( EMA10 * 100 ) > Round( Ref( EMA10, n ) * 100 ) AND 
				   Round( EMA50 * 100 ) > Round( Ref( EMA50, n ) * 100 ) AND 
				   Round( EMA150 * 100 ) > Round( Ref( EMA150, n ) * 100 );		 
	 
	//This is filter to try and filter out low volume stocks			    
	VolA = Volume * C; 
	MAVol = MA( VolA, 90 );			   		   
TimeFrameRestore(); 
 
expandmode = expandLast; 
EMA10 = TimeFrameExpand( EMA10, tmfrm, expandmode ); 
EMA50 = TimeFrameExpand( EMA50, tmfrm, expandmode ); 
EMA150 = TimeFrameExpand( EMA150, tmfrm, expandmode ); 
EMACondition = TimeFrameExpand( EMACondition, tmfrm, expandmode ); 
 
MAVol = TimeFrameExpand( MAVol, tmfrm, expandmode ); 
MAVol = TimeFrameExpand( VolA, tmfrm, expandmode ); 
 
price = TimeFrameGetPrice("C", tmfrm, 0, expandmode); 
 
 
ED2 = 1251231;  // Long end date for symbols 
 
  
dn = DateNum(); 
switch( Name() ) { 
  
    case "CSL": 
		enddate1  = 1110217; 
		Reentry = 1110614; 
		enddate2 = 1160818; 
		enddate3 = ED2; 
		Reentry2 = 1170413;  
		datecond = ( dn >= 1060824 AND dn < enddate1 ) OR  ( dn >= reentry AND dn < enddate2 ) OR  ( dn >= reentry2 AND dn < enddate3 ); 
		exitdatecond1 = dn >= enddate1  AND dn < reentry; 
		exitdatecond2 = dn >= enddate2 AND dn < reentry2 ; 
		exitdatecond3 = dn >= enddate3; exitdatecond = exitdatecond1 OR exitdatecond2 OR exitdatecond3 ; 
		break; 
   
 
		default: 
		datecond = true; 
		exitdatecond = false; 
		 
		break; 
} 
 
BuyPrice = Open; 
SellPrice = Open; 
 
Buy = (price>EMA10) AND (price>EMA50) AND (price>EMA150) AND datecond AND MAVol >500000 AND EMACondition; 
Buy = Ref(Buy, -1) AND new_month; 
 
Sell = EMA50> price; 
Sell = (new_month AND Ref(Sell,-1)) OR Ref(exitdatecond,-1);
Sell = tdv<1; 

Short = Cover = 0; 
 
Filter = new_month OR exitdatecond; // show start of month only 
AddColumn(price,"Close", 1.2); 
AddColumn(EMA10,"EMA10",1.4); 
AddColumn(EMA50,"EMA50",1.4); 
AddColumn(EMA150,"EMA150",1.4); 
 
AddColumn(MAVol, "90day$MAVOL",1.0); 
AddColumn(VolA, "$VOL",1.0); 
AddColumn( IIf( Buy, 66, 83 ), "Signal", formatChar ); 
AddColumn( Buy, "Buy", 1 ); 
AddColumn( Sell, "Sell", 1 ); 
 
 
//buy = ExRem( buy, sell ); 
//sell = ExRem( sell, buy );  
 
PlotShapes( Buy*shapeUpArrow, colorGreen, 0, Low );  
PlotShapes( Sell*shapeDownArrow, colorRed, 0, High );  
 
SetCustomBacktestProc(""); 
 
if( Status( "action" ) == actionPortfolio ) 
{ 
    bo = GetBacktesterObject(); 
    bo.Backtest(); 
    AddToComposite( bo.EquityArray, 
                    "~~~MY_EQUITY_SDT", "X", 
                    atcFlagDeleteValues | atcFlagEnableInPortfolio ); 
} 


_SECTION_BEGIN("Price1");
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - " +   FullName() +   "  - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
Plot( C, "Close", ParamColor("Color", colorDefault ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); 
Plot(EMA10, "EMA_SHORT", ColorRed, styleNoTitle);
Plot(EMA50, "EMA_MEDIUM", ColorGreen, styleNoTitle);
Plot(EMA150, "EMA_LONG", ColorYellow, styleNoTitle);
PlotShapes( Buy*shapeUpArrow, colorGreen, 0, Low ); 
PlotShapes( Sell*shapeDownArrow, colorRed, 0, High ); 

_SECTION_END();

In the above code I have entered at row 139 the following:

Sell = tdv<1; 

Can someone identify where I am going wrong. Thanks

For clarity I am attaching an image of one share, CSL

Exploration

If I run the analysis from 1 July 2018, I have a buy from 2 July 2018 and an open position as of today. From the ribbon I am expecting sells to occur at the red spots on the ribbon, ie October 2018 and March 2020. However those sells haven't occurred.

I thought I'd simplify my question by doing a simpler buy sell code

//TRYING TO ESTABLISH A GTFOH FILTER
_SECTION_BEGIN("SetForeign"); 
tmfrm = inWeekly; 
TimeFrameSet( tmfrm );  
 
SetForeign( "XAO" );

 
GraphXSpace = 5;
_SECTION_BEGIN( "Gann Trend" );
Us = BarsSince(Sum(H>Ref(H,-1),2)==2);
Ds = BarsSince(Sum(L<Ref(L,-1),2)==2);
Hc = HighestSince(Us==0,H,1);
Lc = LowestSince(Ds==0,L,1);
Sd1 = IIf(Us==0,IIf((L!=Lc) AND (Ref(L,-1)!=Lc),1,0),IIf(Ds==0,IIf((H!=HC) AND (Ref(H,-1)!=Hc),-1,0),0));
Sd2 = IIf(Sd1==1, IIf(Ref(BarsSince(Sd1==1),-1) >Ref(BarsSince(Sd1==-1),-1),1,0), IIf(Sd1==-1,IIf(Ref(BarsSince(Sd1==1),-1) < Ref(BarsSince(Sd1==-1),-1),-1,0),0));
TD1 = ValueWhen(Sd2!=0,Sd2,1);



//{Gann-Trend 4/27/99}
Sd =  TD1 ;    					//
//{Swing Change High}
Sch = IIf(Sd==1 AND Ref(sd,-1)==-1,1,0);
//{Swing Change Low}
Scl = IIf(Sd==-1 AND Ref(Sd,-1)==1,1,0);
//{Peak Value}
Pv = IIf(Scl==1,HighestSince(Sch==1,H,1),0);
//{Trough Value}
Tv = IIf(Sch==1,LowestSince(Scl==1,L,1),0);
//{Trend Direction}
Td = IIf(H>ValueWhen(Pv>0,Pv,1),1,IIf(L<ValueWhen(Tv>0,Tv,1),-1,0));
//{UpTrend=1 DownTrend =-1}
Tdv=ValueWhen(Td!=0,Td,1);   				//value when TD is not equal to zero

Plot( 1, "", IIf(tdv == 1,colorDarkGreen, IIf(tdv < 1, colorDarkRed, 0)), styleOwnScale|styleArea|styleNoLabel, -0.1, 50 );
											// This is the plot bar on bottom of screen, "GREEN" is BUY, "RED" is SELL
											//== 	Equal to  
											//!= 	Not equal to
						

RestorePriceArrays();

TimeFrameRestore(); 


_SECTION_END();  

expandmode = expandLast; 
tdv = TimeFrameExpand( tdv, tmfrm, expandmode ); 
 

BuyPrice = Open;
SellPrice = Open;


Buy = C >MA(C,100);
Sell = C< MA(C,100) or tdv<1;

_SECTION_BEGIN("Price1");
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
Plot( C, "Close", ParamColor("Color", colorDefault ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); 
_SECTION_END();

PlotShapes( Buy*shapeUpArrow, colorGreen, 0, Low ); 
PlotShapes( Sell*shapeDownArrow, colorRed, 0, High ); 

Any thoughts on my query will be appreciated.

Please always explore the AB knowledge base/ AB help before forum to look for basics.

You have to place SetForeign differently (Also TimeframeRestore and RestorepriceArrays are equivalent so call either one only but not both) and it is described in detail here
http://www.amibroker.com/kb/2014/10/20/foreign-timeframeset/
Haven't scanned entire code but that's one main mistake.

Also there are lots of forum posts about use of SetForeign together with Timeframe functions. So if you do not find answer in KB or help then please use forum search next before.
https://forum.amibroker.com/search?q=timeframeset%20setforeign

Hi fxshrat,

Thanks for your response. I have been able to sort my code out with your directions.

Yes sometimes not enough patience in exploring, although more of an issue is that my "grey" cells don't fully compute what is written. However with some nudging I seem to get there.

Again, thanks for your time on this forum. My task now is to see whether the "parachute" is a help or a hindrance to the system. At this stage where I am, it is a hindrance, but I guess I now have some tools to work forward with.