# Amibroker coding



## Jack-the-stockman (24 June 2018)

hi, i recently purchased amibroker.  the coding that you need will take a long time to learn.
i have tried to use some from the  afl library and they dont seem to be much good
written a couple of basic ones where im using ma crossovers and in back testing im getting some decent results.  using only ma's is not really using amibroker to it full potential.
im looking at having a system where i trade medium term and hold a max of 10 positions

i would love some advice from people or some codes to play around with

thanks


----------



## Skate (24 June 2018)

Amibroker FAQ have been light on recently but *aussiestockforum* is awash with knowledgeable Amibroker users - some are very handy coders.

Amibroker FAQ - FOUND HERE: https://www.aussiestockforums.com/threads/amibroker-faq.1679/
*Search the forum* (use magnifying glass 
	

		
			
		

		
	



	

		
			
		

		
	
in upper right corner) to find already existing Amibroker posts.


The Amibroker forum is the go to place for Amibroker help. 
FOUND HERE: https://forum.amibroker.com/

If you want a good code to play with -  read this POST: S&C Magazine Jan 2018 Traders Tips
POST FOUND HERE: https://forum.amibroker.com/t/s-c-magazine-jan-2018-traders-tips/3875

Forum member: "beppe" posted a profitable code with comments - his code requires version 6.20 or higher (it's a great code to start your Amibroker journey)

Respected forum member: "portfoliobuilder" said: *"very nice job. Interestingly it makes money without any modifications"
*
skate


----------



## Wyatt (24 June 2018)

Hi Jack,

Here is a handy bit of code I found on the interwebs for 10 day high/low stocks. You can change the lookback period to what you like.

_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("Color", colorBlack ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() );

HI = Close > Ref(HHV(High,10),-1);
LW = Close < Ref(LLV(Low,10),-1);

Filter = HI OR LW;

AddColumn( High > Ref(HHV(High,10),-1), "10 Day High", 1 );
AddColumn( Low < Ref(LLV(Low,10),-1), "10 Day Low", 1 );
AddColumn( C, "Close", 1.2 );

_SECTION_END();

After doing a scan for the day you want, hit the explore button and then hit the 10 day high/low header to align your results.
Create a new watchlist through the symbols tab and watch list - new watch list, so you can shift arrow down and then right click on the portion of the exploration list you want to populate your new watch list.

http://www.asxmarketwatch.com/ is a good place to start and when you get up to speed doing backtests beware of survivorship bias  https://www.thechartist.com.au/Technical-Analysis/survivorship-bias.html
In fact Nick Radge @The Chartist is a fantastic resource for Amibroker, His book Unholy Grails is a great read if you can get your hands on one.

Best of luck with your journey


----------



## Jack-the-stockman (25 June 2018)

thanks for that,


----------



## lenny (25 June 2018)

Hi Jack,

Might be worth having a look at https://jbmarwood.com/

He sells some Amibroker system code starting at $95, which might be another way to get access to professional coded systems to wet your feet.

Hope this helps.


----------



## Habakkuk (25 June 2018)

Jack-the-stockman said:


> hi, i recently purchased amibroker.  the coding that you need will take a long time to learn.
> i have tried to use some from the  afl library and they dont seem to be much good
> written a couple of basic ones where im using ma crossovers and in back testing im getting some decent results.  using only ma's is not really using amibroker to it full potential.
> im looking at having a system where i trade medium term and hold a max of 10 positions
> ...




Some advice: unless you want to learn coding for educational or entertainment purposes only, you will need to find an edge to trade profitably. Moving averages have no edge as such, nor do any of the other indicators. Trailing stops or any other stops have no edge either. In fact I think it's impossible to code an exit that has an actual edge. Obviously, I can't prove that, it being a negative. Money management has no edge, although it's a very important component in trading systems. But at this point you can ignore it entirely, just use fixed dollar amount position sizing.

So that leaves you with entries. Play around with simple logic conditions (minimise use of indicators) and take the next day's Close as an exit. Use this quasi-Monte-Carlo code rather than just single-run back tests:

// goes at the beginning of system code, then run "optimize"
 Optimize("MC run #", 10, 1, 100, 1);
 PositionScore = Random();

Once you have identified a possible edge, see how long it lasts (in days) using this code:

// goes at the end
 Sell = 0;
 SellPrice = Close;
 ApplyStop(stopTypeNBar, stopModeBars, 5, 1, 1);   // first parameter is number of days held

Note: signals almost always have a short life-span, strongest on first day, only half strength on the second, maybe ok up to a week, and after 2 weeks you're down to 2 basis points per day that you can get with random stocks and random entries. So when you are talking of trading "medium term", keep this in mind. Excess returns showing in trading systems with holding times of months or years are statistically meaningless and mostly indistinguishable from random.

The exit will determine the return distribution only - it's not producing excess profits. With your exit logic you set the desired win rate, win/loss amounts and the skew of the distribution. This is not obvious to most people.

Amibroker is unbeatable for figuring this out and requires only relatively simple coding, a few lines, typically. It should take weeks or months, not years to learn those basics.


----------



## captain black (26 June 2018)

Great post @Habakkuk,

Particularly this:


Habakkuk said:


> The exit will determine the return distribution only - it's not producing excess profits. With your exit logic you set the desired win rate, win/loss amounts and the skew of the distribution. This is not obvious to most people.




And this:


Habakkuk said:


> Amibroker is unbeatable for figuring this out and requires only relatively simple coding, a few lines, typically. It should take weeks or months, not years to learn those basics.


----------



## captain black (26 June 2018)

Habakkuk said:


> Note: signals almost always have a short life-span




I have 2 momentum systems set up for the ASX (currently working on a 3rd) and just to reinforce what @Habakkuk wrote here I checked the holding period stats. 4.7 days on one and 5.05 days on the other.


----------



## Gringotts Bank (26 June 2018)

@Habakkuk, I don't understand what you mean by 'short life span'.  Do you mean the optimal exit (in terms of profitability) is usually <3-5 days?

Also could you please this sentence in more detail?  I don't follow.  

"The exit will determine the return distribution only - it's not producing excess profits".


----------



## Habakkuk (26 June 2018)

Gringotts Bank said:


> @Habakkuk, I don't understand what you mean by 'short life span'.  Do you mean the optimal exit (in terms of profitability) is usually <3-5 days?
> 
> Also could you please this sentence in more detail?  I don't follow.
> 
> "The exit will determine the return distribution only - it's not producing excess profits".





'short life span' means that the signal strength 'wears off', e.g. an entry signal is good as soon as it is triggered, because by tomorrow or the next day it will typically have lost most of its validity - if it had any in the first place. The trade will (should) have moved in the right direction by then and some of the profit potential is gone. I hope that makes sense.

This might be controversial, especially for Fundamental Analysts who forecast stock performance several years ahead. But for the OP who wants to design a mechanical trading system it's sensible.

It doesn't mean that there is an 'optimal' trade duration. That depends on several variables, just off the top of my head:
- system type, trend following obviously as long as it's your friend, momentum a bit shorter, mean reversion only a few days
- are there entry signals available for the trading capital?, if not you might consider letting it run for another day
- brokerage and spread; if you exit on the same day or the next, it can be expensive

I spent some time last year importing the 260 trades from peter2's thread into Amibroker, looking for a single mechanical logic exit that would perform as well as his discretionary ones, all 7 of them ... He was considering switching between 2* and 3*ATR trailing stops at that time.

From memory his average edge from entry until the next day's close was 1.5%. That's something I can only dream about. It then drops off very rapidly and is (on average) down to just a few basis points per day after 2 weeks or so. Some trades trended much longer than that, of course.


The trade exit determines the shape of the return distribution. Take the standard trend-following exit of "cut your losses short and let your profits run". You get a typical Win percentage of  maybe 40% with av. profit/loss ratio 2:1 or better. The distribution has a long right tail, some very big winners, hopefully.

Let's do the exact opposite, "grab any profit when it's there and let your losses run". You won't find that in any trading book. The way it works is to look at the end of each day: if it was an 'UP' day, close the trade, regardless of whether it is in profit. If it was a 'DOWN' day, keep it open.

You will probably think that's sheer lunacy, but what you get is a win rate of typically > 60% and almost 1:1 profit/loss. The annoying thing is the long left tail, the occasional big loss.

In Amibroker it looks like this:
Sell = Close > Ref(Close, -1);
SellPrice = Close;
There are many other possibilities like > Open or > MA(something)

The important thing is to realise that the obvious, sensible, approved trend following exit has no edge - it is neutral. Therefore, logically, doing the opposite is also neutral. Most people would say "you're going to lose ALL YOUR MONEY".

I believe that mechanical exits don't/can't have an edge because they are *forced* to make a prediction every day. There is no such requirement for the entry logic. Entry can wait until the right condition arrives.
See if you can prove me wrong using random entry and a logic exit.


----------



## Gringotts Bank (26 June 2018)

Habakkuk said:


> 'short life span' means that the signal strength 'wears off', e.g. an entry signal is good as soon as it is triggered, because by tomorrow or the next day it will typically have lost most of its validity - if it had any in the first place. The trade will (should) have moved in the right direction by then and some of the profit potential is gone. I hope that makes sense.
> 
> This might be controversial, especially for Fundamental Analysts who forecast stock performance several years ahead. But for the OP who wants to design a mechanical trading system it's sensible.  One of my better systems has almost no pop on day one which is interesting.
> 
> ...



Thanks for all the detail here.

First part I understand.  A good edge means it should really pop on the next bar (or asap), which means you're positioning your entry as perfectly as possible.

The second part I'm still reading over a few more times.  Not quite clear yet.


----------



## Gringotts Bank (27 June 2018)

ok got it...good stuff.  I agree with the trailing stops too - they look like they should help profitability, but they always detract.


----------



## Wyatt (27 June 2018)

Habakkuk said:


> 'short life span' means that the signal strength 'wears off', e.g. an entry signal is good as soon as it is triggered, because by tomorrow or the next day it will typically have lost most of its validity - if it had any in the first place. The trade will (should) have moved in the right direction by then and some of the profit potential is gone. I hope that makes sense.
> 
> This might be controversial, especially for Fundamental Analysts who forecast stock performance several years ahead. But for the OP who wants to design a mechanical trading system it's sensible.
> 
> ...




Not sure if this proves anyone wrong, but food for thought regarding random entries.


----------



## Habakkuk (27 June 2018)

Wyatt said:


> Not sure if this proves anyone wrong, but food for thought regarding random entries.




I've played the www.asxmarketwatch.com videos years ago, not sure if this particular one was there as it's from 2016. It makes a good introduction to Amibroker. Here is something that is fully disclosed, even down to .afl code and every mouse click, so there is no excuse for not trying it. It would make a valuable learning exercise getting right into the details (that's where the devil always lives).

Do you know *why* it works? Just kidding.
Seriously though, I don't think many people here will know why this is bogus. Also try to figure out why Van Tharp and Tom Basso were fooled by randomness. Well, Van Tharp maybe, not too surprising given that the story was first published in his 1999 book with the foreword by David Mobley Sr. of Maricopa fame.

The Clenow video is based on his second book. I haven't actually watched it but have read the book and it's legit as far as it goes. Reasonable, random stocks, equally weighted, rebalanced monthly should outperform buy-and-hold in the long term. But again, the devil is in the details. For this particular outperformance he is *liquidating the entire portfolio every month* and creating a new random one. Trading friction (brokerage and spread) and taxation would make it a deal breaker for most Australian investors. And tracking error would be a concern for hedge funds. So it sounds plausible, but the outperformance comes at a cost.


----------



## Wyatt (27 June 2018)

Damn...........Fooled by randomness again!

Hopefully the collective actions by the masses is less random than a coin toss, at least some of the time to create trends which can be potentially exploited into the future. Although trend following is said to be misery at times when it goes out of sync with the market, prolly just enough time for most to lose interest. 

From my very limited experience a % trailing stop tends to hurt performance below about 25% in a trend following concept, so could be argued as being worthless over the longer run.

//   amount = 40; // 10% loss (trailing)
//   ApplyStop( stopTypeTrailing, stopModePercent, amount, True );

It also seems that you can increase win% to maybe 40-45% by trading weekly and even higher if you trade monthly, particularly first few days or last few days of month. Although there could possibly be a strong relationship with drawdown in the detail.


----------



## Wysiwyg (2 July 2018)

Jack-the-stockman said:


> i would love some advice from people or some codes to play around with
> thanks



Skip the backtest dreaming and try this. Create your signal and then plot a shape on the chart whenever the signal criteria is met. This way you get a visualisation of what price action ensued the signal/s. Flip through chart histories and pretty soon you will know what usually happens after the signal. Saves a lot of time.

Remember -- 
price trends up, price trends down and price ranges.
support and resistance levels are places where the majority of money agrees.
news moves price.


----------



## qldfrog (27 November 2019)

Amibroker question:
I would like to run a weekly system daily
I mean on monday run in weekly mode and get buy sell signals for the monday to friday defined weeko
On Tuesday run...based on Tuesday to monday week, etc
I can do this manually by putting my config in weekly mode and adding proper offset for week start definition
But i can not backtest like that
Anyone has a programmatic way to handle this?
Thanks in advance


----------



## qldfrog (27 November 2019)

So would the solution be to move to daily, and ensure any average, max  etc used in the weekly code is now using 5x weekly bar numbers and so on
Basically transforming code...


----------



## Trav. (27 November 2019)

I found this via the Amibroker Forum

http://www.amibroker.com/kb/2015/02/14/choosing-first-day-of-the-week-for-weekly-compression/

Hopefully it helps


----------



## qldfrog (28 November 2019)

Trav. said:


> I found this via the Amibroker Forum
> 
> http://www.amibroker.com/kb/2015/02/14/choosing-first-day-of-the-week-for-weekly-compression/
> 
> Hopefully it helps



Thanks Trav but i wanted to do it automatically in Coding to understand its effect in back test
I tried my system weekly fir each week definition using the setting above, now i would like to backtest it running a different week definition each day...


----------



## Trav. (28 November 2019)

I am struggling to see to what you want from the system.

If I understand what you want correctly I would run a backtest for each First Day of Week setting and put it in spreadsheet as per the below snip, then compare which day works best.

Then run exploration for the system with the preferred day selected each week.

You could probably do the below in a custom backtest format but I am struggling to understand why when the below can be done in 5 minutes. Saying that I know the CBT is pretty powerful and would like to dabble more with it.

If this is what you want you would probably need to know the setoption command for the First Day of Week setting, then step it through....so is this the desired outcome ? if so I will have a look around as I do not know the answer but always keen to learn.


----------



## qldfrog (29 November 2019)

https://forum.amibroker.com/t/weekly-backtest-start-day/9376/6
I think will give me what I want
I will try to explain what/why  I want when I have a bit more time @trav
Have to run


----------



## Trav. (3 December 2019)

@qldfrog I have been thinking about this and I think that we have 1 option for you to try.

It may not be the complete answer for you but will help us dig a little deeper into this and maybe one of the experts might chime in 

Ok so the code below is pretty simple.

1. Strategy MA cross over direct from AmiBroker files
2. Sets time frame to weekly so we can use the weekly close array
3. Restores time frame to normal daily mode as we are using EOD data
4. Buy / Sell lines use the weekly close data but decompressed on the day that we run the backtest (in daily mode)
5. Some basic code just for the looks
6. Plot - Weekly MA plotted on Daily chart for visual checking of cross over



```
PositionSize = 10000; // Fixed value for each position in BackTesting
Quantity = PositionSize / BuyPrice; // Quantity of shares to purchase

/* Time Frame Change:--------------------------------------------------------------*/
// Here we set the time frame to weekly and use the weekly close price for the moving average calculation
// You would put you code in here to get weekly array data

TimeFrameSet(inWeekly);
maW = MA( Close, 20 );     // simple moving average using weekly close
CW = C;                    // Close in weekly
TimeFrameRestore(inDaily);

Buy = Cross(Close, TimeFrameExpand (maW, inWeekly, expandLast)); // Buys in Daily backtest mode but using MA from weekly Time Frame to detect cross
Sell = Cross(TimeFrameExpand (maW, inWeekly, expandLast), Close); // Sells in Daily backtest mode but using MA from weekly Time Frame to detect cross

Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);

/* Exploration: --------------------------------------------------------------*/

Filter = Buy OR Sell AND StrLen( Name () ) == 3;
SetSortColumns( 2 );
AddColumn( IIf(Buy, 'B', IIf( Sell, 'S', 'N') ), "Signal", formatchar, IIf( Buy, colorGreen, IIf( Sell, colorRed, colorBlue)) );
AddColumn( IIf(Buy, PositionSize, Null), "Position Size", 1);
AddColumn( IIf(Buy, Quantity, Null), "Qty", 1);

/* Charting: --------------------------------------------------------------*/

SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open= %g High= %g Low= %g Close= %g (%.1f%%) Volume= " + WriteVal( V/1, 1.0 ) +
"\n"+"{{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 )) ));
Plot( C, "Close", ParamColor("Color", colorPaleTurquoise ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() );
Plot( TimeFrameExpand (maW, inWeekly, expandLast), "maW", colorAqua, styleLine ); // Plots weekly MA on daily chart

/* Plot Buy and Sell Signal Arrows */
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45);

PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);
PlotShapes(IIf(Sell, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);
```

Some backtest results for comparison. 
1. Normal MA system unmodified run in 2 time frame settings
2. Modified Weekly MA system run in 2 time frame settings

You will notice the green shaded areas match up which in my mind proves the weekly data is fine ( not corrupted ) in the compress / expand parts of the program

3. you can look at a chart say westpac and the backtest would have given you an earlier exit which I think you are looking for.







Have a look / play and see what you think. Maybe 1 step forward ??


----------



## qldfrog (3 December 2019)

Trav. said:


> @qldfrog I have been thinking about this and I think that we have 1 option for you to try.
> 
> It may not be the complete answer for you but will help us dig a little deeper into this and maybe one of the experts might chime in
> 
> ...



Much thanks, sounds very promising.i think it Is what I am trying to achieve.
Doing a short consulting job today and busy yesterday
Hopefully can work on this tomorrow
Much appreciated


----------



## qldfrog (3 December 2019)

actually still keen to use the weekly but shifted, but the same principle should work I can compress uncompress with the shift..i think..will try to work more on this,I believe that compress uncompress is the key indeed
you lead me in the right direction


----------

