Use DateNum to buy and sell on specific dates

I’m trying to make a simple AFL to buy and sell on specific dates through a number of years. I was able to use the Datenum() function to do that for one specific period, but when I repeat it for different dates, it only buys and sells for the last date specified.

This works to buy and sell once:
Buy = DateNum()==1010705 ;
Sell = DateNum()==1020104;

Then if I repeat it for other dates like this, I was hoping to see two trades, but I only get the last trade:
Buy = DateNum()==1010705 ;
Sell = DateNum()==1020104;
Buy = DateNum()==1020730 ;
Sell = DateNum()==1020815;

Try this instead:

Buy = DateNum()==1010705 OR DateNum()==1020730 ;

Sell = DateNum()==1020104 OR DateNum()==1020815;
4 Likes

Do you remember anything from Math 101 (elementary school?)

x = 5; 

is an ASSIGNMENT. It assigns x the value of 5.

Now if you do another assignment, it OVERWRITES previous value:

x = 5; 
// now x is equal 5
x = 7;
// but now it is equal 7

That is why when you write:

Buy = DateNum()==1010705 ; 
// now you get a buy ONLY on 2001-07-05
Buy = DateNum()==1020730 ;
// BUT NOW ONLY on 2002-07-30 because you OVERWROTE previous values

As @mradtke told you if you want to COMBINE different dates you need to OR them.

dn = DateNum();
Buy = ( dn == 1010705 ) OR
      ( dn == 1020730 ) OR
      ( dn == 1030207 ); // ... so on ... so on 

You really have to read this (possibly MANY times until it sinks)
http://www.amibroker.com/guide/h_understandafl.html

4 Likes