Australian (ASX) Stock Market Forum

Amibroker coding

Joined
16 January 2018
Posts
3
Reactions
0
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
 
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 mag.pngin 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
 
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
 
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.
 
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

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.
 
Great post @Habakkuk,

Particularly this:
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:
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.
 
@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, 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.
 
'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.

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.
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.
 
Last edited:
ok got it...good stuff. I agree with the trailing stops too - they look like they should help profitability, but they always detract.
 
'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.

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



 
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.
 
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.
 
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.
 
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
 
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...
 
Top