Need to take position on specific time on next day after the signal on Daily timeframe

Hello all,

I am new to AFL and have been trying to get this right for over a week now and just cannot find out how to do it. What I want to do is to plot two 10 Days EMAs on High and Low on Daily timeframe and I want to generate signals when price(close) crosses above or below them.
But then after the signal on DAILY candle, I want to to get into respective Buy/Sell Position at the exact price at 9:25 AM the NEXT day. The Indian market begins at 9:15 AM

I have so far tried timenum(),timeframeset/restore, timeframegetprice() but due to my lack of knowledge on AFL, could not get it to work properly. The Indian market begins at 9:15 AM,
So I logically thought of getting the Opening Price of 2nd 10 Minute Candle which is 9:25 AM. And tried to do it this way by playing with timeframe functions.

Please Help. How do I take position at exactly 9:25 AM on the next day after the signal in Daily Timeframe and backtest it? I will also upload my buggy code. I have put everything I have tried so far in comments so kindly ignore it if you want to.

/*
1.Plot Chart
2.Plot Ema on Highs and Lows
3.Plot buy/sell signals
4. Entry on specific time.
5.Apply Stoploss
6. Add Transaction cost
7. Set Trade Delay
*/
_SECTION_BEGIN("Price");
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("Y-Axis Price Color", colorDefault), styleThick | ParamStyle("Style") | GetPriceStyle() ); 
_SECTION_END();

_SECTION_BEGIN("EMAs");

	optiavg = Optimize("Average Optimization",10,10,200,5);
	Hema = EMA(H, optiavg);
	Lema = EMA(L, optiavg);
	

			tn = TimeNum();
			startTime = 093000; // start in HHMMSS format
			endTime = 151500;  // end in HHMMSS format
			timeOK = tn >= startTime AND tn <= endTime;
			
			TimeFrameSet(2 * in5Minute);
			bprice = ValueWhen(tn == starttime,Open,2);
			TimeFrameRestore();
		
	Plot(Hema,"Hema",colorOrange,styleLine);
	Plot(Lema,"Lema",colorYellow,styleLine);
			ConditionB =  C > Hema;
			ConditionS = C < Lema;
		
			
			/*tn = TimeNum();
			starttime = tn == 091500;
			endtime = 	tn == 033000;
			pricetime = tn == 093500;*/
			

		//tmp = TimeFrameGetPrice("open",2*in5Minute);
		//plotting = TimeFrameExpand(tmp,2*in5Minute);
		//Plot (plotting,"openingp",colorAqua,styleLine);
		
		
		
		Buy = ConditionB;
		Sell = ConditionS; 
		Short = ConditionS; 
		Cover = ConditionB;
		//ApplyStop(stopTypeLoss,stopModePoint,125);
		
		BuyPrice = bprice;
		sellPrice = bprice;
		shortPrice = bprice;
		coverPrice = bprice;
		
		
		Buy = ExRem(Buy,Sell);
		Sell = ExRem(Sell,Buy);
		Short = ExRem(Short,Cover);
		Cover = ExRem(Cover,Short);
	
/*
Kvhod = 130000;
ItsTime = Kvhod == TimeNum();
PriceAtTime = ValueWhen(ItsTime, Open);

		/*Entry = 092500;
		EntryTime = Entry == TimeNum();
		//PriceAtTime = ValueWhen(EntryTime, Open);
		//DayChange = Day() != Ref(Day(), 1); 
		
		TimeFrameSet(inDaily);
			ConditionB =  C > Hema;
			ConditionS = C < Lema;		
		TimeFrameRestore();
		
		
		
		/*
		TimeFrameSet(2*in5Minute);
		nextB = BarsSince(conditionB);
		nextS = BarsSince(conditionS);
			Buy = Ref(nextB,-1);
			Cover = Ref(nextB,-1);
			Sell = Ref(nextS,-1);
			Short = Ref(nextS,-1);
			
			Buy = ExRem(Buy,Sell);
			Sell = ExRem(Sell,Buy);
			Short = ExRem(Short,Cover);
			Cover = ExRem(Cover,Short);
			SetTradeDelays(1,1,1,1);
			
			/*BuyPrice = Open;
			ShortPrice = Open;
			CoverPrice =Open;
			SellPrice = Open;
			
		TimeFrameRestore();
		
		
		
	
		SetTradeDelays(1,1,1,1);
		BuyPrice = TimeFrameExpand(EntryPrice,inDaily);
		SellPrice = TimeFrameExpand(EntryPrice,inDaily);
		ShortPrice = TimeFrameExpand(EntryPrice,inDaily);
		CoverPrice = TimeFrameExpand(EntryPrice,inDaily);
		
		*/	
		
			
			
		PlotShapes(IIf(Buy, shapeUpArrow , shapeNone), colorWhite, 0,Low, Offset=-20);
		PlotShapes(IIf(Sell, shapeDownArrow, shapeNone), colorYellow, 0,High, Offset=-20);
		PlotShapes(IIf(Buy, shapeUpArrow , shapeNone), colorWhite, 0,Low, Offset=-20);
		PlotShapes(IIf(Sell, shapeDownArrow, shapeNone), colorYellow, 0,High, Offset=-20);
			
_SECTION_END();
		

Here's the screenshotScreenshot%20(13)

1 Like

Hello,
instead of coding you own solution, you can use Interactive Brokers GAT orders (Good After Time) so your order will be sent by IB at the specified time.
https://www.interactivebrokers.com/en/index.php?f=587
Regards

@jbequity

Hope this helps:
(You need 5min-data or lower (e.g. 1min))


Filter = 1;  //--> Exploration (bottom)

/*
1.Settings (Set Trade Delays etc.)
2.Plot Chart
3.Plot EMAs
4.Plot buy/sell signals  (Add e.g. Spread)
5.Apply Stoploss
6.Plot Trades
7.Set PositionSize
(8.Exploration)
*/


_SECTION_BEGIN("Settings");
delay = 0;
SetTradeDelays(delay, delay, delay, delay);
//SetOption("ActivateStopsImmediately", True);
//SetOption("PriceBoundChecking", False);
//SetOption("CommissionMode", ...);
// alternative: Analysis-settings  (e.g. for transaction costs too)
_SECTION_END();


_SECTION_BEGIN("Price");
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("Y-Axis Price Color", colorDefault), styleThick | ParamStyle("Style") | GetPriceStyle() ); 
_SECTION_END();


_SECTION_BEGIN("EMAs");
/// @link https://www.amibroker.com/guide/h_timeframe.html
	optiavg = Optimize("Average Optimization",10,10,200,5);
	
	TimeFrameSet(inDaily);
	Hema = EMA(H, optiavg) ;  // Ref( EMA(H, optiavg), -1);
	Lema = EMA(L, optiavg) ;  // Ref( EMA(L, optiavg), -1);
	DailyC = C ;              // Ref(C,-1);
	TimeFrameRestore() ;	
	Hema = TimeFrameExpand(Hema, inDaily, mode = expandLast) ;  // expandFirst
	Lema = TimeFrameExpand(Lema, inDaily, mode = expandLast) ;  // expandFirst
	DailyC = TimeFrameExpand(DailyC, inDaily, mode = expandLast) ;  // expandFirst
	
	Plot(Hema,"Hema",colorBrightGreen,styleLine);
	Plot(Lema,"Lema",colorOrange,styleLine);
	//Plot(DailyC, "Daily Close (Yesterday)", colorBlue, styleLine);
_SECTION_END();


_SECTION_BEGIN("Signals");
    ConditionB = DailyC > Hema;
    ConditionS = DailyC < Lema;
	tn = TimeNum();
	// HHMMSS format
	startTime = 91500; // 93000
	endTime = 151500;  
	timeOK = tn >= startTime AND tn <= endTime;
			
	entryTime = 92500;
	entryTimeOK = tn == entryTime;  // >=
						
	BuySig = ConditionB AND timeOK AND entryTimeOK;
	SellSig = ConditionS AND timeOK AND entryTimeOK; 		
		
		//Tradeprice
		Tprice_buy = Open;   // + Spread
		Tprice_sell = Open;  // - Spread
		 
		Buy = BuySig;
		BuyPrice = Tprice_buy;  

		Sell = SellSig; 
		SellPrice = Tprice_sell;
		
		Short = SellSig;
		ShortPrice = Tprice_sell;
		 
		Cover = BuySig;
		CoverPrice = Tprice_buy;
_SECTION_END();	
	
			
_SECTION_BEGIN("StopLoss");
		ApplyStop(stopTypeLoss, stopModePoint, 125, ExitAtStop = 1); 
		Equity(1);
		//Buy = ExRem(Buy,Sell);  // not needed --> Equity(1)
_SECTION_END();	


_SECTION_BEGIN("Visualize Trades");
		PlotShapes( IIf(Buy, shapeCircle, shapeNone), colorBrightGreen, 0, BuyPrice, 0 );
		PlotShapes( IIf(Sell >= 1, shapeCircle, shapeNone), colorOrange, 0, SellPrice, 0 );  
		PlotShapes( IIf(Buy, shapeUpArrow, shapeNone), colorGreen, 0, Low, -20 );
		PlotShapes( IIf(Sell >= 1, shapeDownArrow, shapeNone), colorRed, 0, High, -20 );
		// Short, Cover...
		
		/// @link https://www.amibroker.com/kb/2007/03/24/how-to-plot-a-trailing-stop-in-the-price-chart/comment-page-1/
		  // (be careful with multiple Equity() - Calls)	
_SECTION_END();		


_SECTION_BEGIN("PositionSize");
		SetPositionSize(1, spsShares);   //SetPositionSize(...);		
_SECTION_END();	


_SECTION_BEGIN("Exploration");		
		// Exploration:
		AddColumn(Hema, "High Daily EMA", 1.2);
		AddColumn(Lema, "Low Daily EMA", 1.2);
		AddColumn(DailyC, "DailyC", 1.2);
		AddColumn(ConditionB, "Buy-Condition", 1.0, colorDefault, IIf(ConditionB, colorGreen, colorDefault));
		AddColumn(timeOK, "Time OK", 1.0, colorDefault, IIf(timeOK, colorYellow, colorDefault));		
		AddColumn(entryTimeOK, "EntryTime OK", 1.0, colorDefault, IIf(entryTimeOK, colorYellow, colorDefault));
		AddColumn(Buy, "Buy", 1.0, colorDefault, IIf(Buy, colorBrightGreen, colorDefault));
		
		AddColumn(ConditionS, "Sell-Condition", 1.0, colorDefault, IIf(ConditionS, colorOrange, colorDefault));
		AddColumn(Sell, "Sell", 1.0, colorDefault, IIf(Sell, colorRed, colorDefault));
_SECTION_END();	

Keep going. The beginning is hard, but after some months you will get better and better! :slight_smile:

4 Likes

Instead of TimeFrameSet() etc. you can also use TimeFrameGetPrice() ...

Thanks a lot for the reply mate. :smile:
I tried backtesting this code but it is not showing any results in Backtest window. But it shows the Explore results though and the entry time is still 9:16. I have also set trade delays. Is there anything more that I need to tweak before compiling? How can I modify it so that I can backtest it and get the actual entry exit points and profitability?

Screenshot%20(18)

Waiting for your response. :slight_smile:

As mentioned, you'll need e.g. 5min-data (Periodicity)

https://www.amibroker.com/guide/w_settings.html

But I need to backtest in daily timeframe. after the HL condition satisfies and Up/Down arrows appear in daily timeframe, I need to take position at 9:25 AM the next day. and not on the 5 minute timeframe. How do i proceed with this?

Regards.

Well. I'm not 100% sure I understood everything you want to accomplish...
In daily timeframe there is only OHLC of a day. So you have the Open of 9:15 if the market starts at 9:15.
You can access the Close-Price (and the High and the Low) too. But you can't check for the other Time-Conditions (e.g. if it's 9:25).
Therefore you need the lower timeframe...
If you want to plot Daily-Candles (on intraday timeframe) you can plot them too. Just search in the forum.

If you have intraday-data (<= 5min) try the Exploration. You will see much better how it works. :slight_smile:
(without intraday-data you can't backtest intra-day too...)

You see: thanks to the TimeFrame functions, the DailyClose switches at the last bar of a day to it's 5min-(Close)-Value. Over the whole next day (except the last bar), the Close-Price of the last day is stored. Thus you use yesterdays Close. The EMAs work the same way.
(A bit more precisely is for example the use of the Ref() function and expandfirst.
But essentially be careful with the use of expandfirst.)

I hope this solves your questions. :slight_smile:

1)

3 Likes

Thanks a lot for your help mate. I was able to get the desired results by tweaking a thing or two but more importantly I understood how to precisely use the TimeFrame Functions because of your code.
You're awesome ! :slight_smile:

Happy to see you found a solution @jbequity but I'm still not sure to get what was the problem here actually. A genuine question : for backtesting, why don't you modify/set 'day session start' at 09:25 in 'Intraday settings' of your database ? This way you don't need to use the 5min timeframe at all, you can backtest in daily, use the open price of next day as entry price, and your code would be simpler (and simply use GAT orders when you go live).
Regards.

Hi @alligator , Thanks for this insight. It really makes sense. :slight_smile:

But wouldn't it synchronize the data that I have to start from 9:25 and not really fetch me the price at 9:25? As in wouldn't it use the opening price of 9:15 on 9:25 and then continue to adjust the prices until 3:15 PM? Just a thought.

Quotes stored in databases are time-stamped, Amibroker never messes with them. It seems to me you're confused by the possibility of time shift. This may be useful when you live in a different timezone for instance.

As often (not to say almost always) you can find explanations in the manual and in the knowledge base.
https://www.amibroker.com/guide/w_dbsettings.html
https://www.amibroker.com/kb/2006/03/19/how-does-the-daily-time-compression-work/