Australian (ASX) Stock Market Forum

Amibroker FAQ

Allan you could maybe look at the linear regression of slope function in AB instead of ROC?

LinRegSlope
- linear regression slope Statistical functions
(AFL 1.4)


SYNTAX LinRegSlope( ARRAY, periods )
RETURNS ARRAY
FUNCTION Calculates linear regression line slope from the ARRAY using periods range. The function accepts periods parameter that can be constant as well as time-variant (array).
EXAMPLE x = Cum(1);
lastx = LastValue( x ); Daysback = 10; aa = LastValue( LinRegIntercept( Close, Daysback) );
bb = LastValue( LinRegSlope( Close, Daysback ) );

y = Aa + bb * ( x - (Lastx - DaysBack) ); Plot( Close, "Close", colorBlack, styleCandle );
Plot( IIf( x >= (lastx - Daysback), y, -1e10 ), "LinReg", colorRed );



Cheers

Thanks for the suggestion. I'll have a look over it tomorrow and learn more about how it works.
 
Hi Trash hope your doin well...

I haven't got the jscript going yet I am happy for now doing one exploration in norgate DB then the next one in IB DB. Let me know if this needs to be done now( is it effecting the coding I'm writing?).

I have noted IYO there is no need to sync watclist's. Thanks for that I will of course double check this whilst testing/ paper trading.

In the norgate explore I have saved the list of symbols to a watchlist in norgate DB using the code below( I did all this before your above reply).


Code:
if( LastValue( filter) )
// sends results to selected watchlist # listnum
{
 CategoryAddSymbol( "", categoryWatchlist, listnum ); 
 }


this saves the .tls file to " C:\premium data alpha test\WatchLists" on my hard drive.

Had this coding at start of both explorations to erase watchlist's so got the empty watcklists sorted..

Code:
function EraseWatchlist( listnum )
{
// retrive comma-separated list of symbols in watch list
list = CategoryGetSymbols( categoryWatchlist, listnum );
//iterate through watchlist members and remove
for( i = 0; ( sym = StrExtract( list, i ) ) != ""; i++ )
{
CategoryRemoveSymbol( sym, categoryWatchlist, Listnum );
}
}
//erase watchlist
if( Status("stocknum") == 0 )//if ordinal number(stocknum) of currently analysed symbol equals 0 (at the start) then wipe watchlist
EraseWatchlist( listnum ); //executes the function above called"erasewatchlist"


So now I'm up to retrieving the the symbol list from norgate DB stored in " C:\premium data alpha test\WatchLists" on my hard drive.

With your generously supplied coding below do I need to point out the path to the watchlist or am I getting off track?


Code:
procedure AddToWatchlist( listnum, List )
{   
    //iterate through symbol list and add to WL
    for ( i = 0; ( sym = StrExtract( list, i ) ) != ""; i++ )
    {
        CategoryAddSymbol( sym, categoryWatchlist, listnum );
    }
}

List = ... your saved comma separated list of wl members of Norgate DB ...;[COLOR="#006400"][COLOR="#FF0000"]// do I need to point the path to the norgate DB watchlist because "list" isn't a persistent var?[/COLOR][/COLOR]

//sample use in Exploration
if ( Status( "stocknum" ) == 0 )
{
    AddToWatchlist( WL = 0, List );
}

Filter = Status( "lastbarinrange" );
SetOption("RefreshWhenCompleted", True);

Yet again thanks for your time mate..:)

Cheers

First of all code tags are these [ code ]blah[ /code ] without spaces.


As for getting symbol lists transported from one DB to another I would use AFL export procedure in your Norgate code from within AB after using mysymbols = CategoryGetSymbols(...) function to get comma separated list of symbols as watchlist tls files are available/updated in that mentioned Watchlist folder only after saving or closing a database. So if WL membership changes while DB is still open you have to save DB first to update that file (within AB it updates in realtime of course and new members are callable in realtime too). So IMO export of list is better.

But of course if you still want to go route of OLE you can save DB via OLE programmatically but MS OLE is not multi threading friendly (and slow in general) so don't use it within AFL but from outside via shellexecute function call to an external script.
 
I'm back with another question.

I've been testing a system based on Nick Radge's Weekend Trend Trader. I'm OK with the basic code and have run some back-testing so I can see that the code is working.

One thing I can see is that there are times where the maximum positions (20 stocks) are all used. This means that no new positions can be taken until I exit some positions. Currently the only way I'm exiting is if the stop loss is exceeded which is triggered by either a 40% or 10% decline depending on the direction of the index.

What I'd like to look at is the option of selling positions when I've hit my max position size so I can free up capital to take up new positions. From looking at some charts I can see that some stocks have a good run that then flattens out. The stop loss condition isn't met so there's no sale, but the stock isn't increasing at the rate it once was. However, a new stock comes up on the radar that (potentially) could have better growth over the short term. I'd prefer to purchase this new stock and sell the existing, slower-moving one.

However, if there's no new 'buy' signals for the week, keep holding all the stocks. I'll assume that even a slow growth rate could be better than a cash return.

I know I can do this manually, but I want it as part of the system so I can back test it and see if it makes any difference.

So what I'm trying to understand, is how do I code the following:
  • If maximum positions are taken up AND there's a new 'buy'
  • Find the stock that the portfolio is currently holding that has the lowest Rate Of Change over the past 30 days.
  • Sell that stock
  • Use the sale proceeds to purchase the new 'buy'.

Hopefully this isn't a silly question and there's a way to do it.

Thanks in advance for your help.

http://www.amibroker.com/kb/2006/03/06/re-balancing-open-positions/
 
First of all code tags are these [ code ]blah[ /code ] without spaces.


As for getting symbol lists transported from one DB to another I would use AFL export procedure in your Norgate code from within AB after using mysymbols = CategoryGetSymbols(...) function to get comma separated list of symbols as watchlist tls files are available/updated in that mentioned Watchlist folder only after saving or closing a database. So if WL membership changes while DB is still open you have to save DB first to update that file (within AB it updates in realtime of course and new members are callable in realtime too). So IMO export of list is better.

But of course if you still want to go route of OLE you can save DB via OLE programmatically but MS OLE is not multi threading friendly (and slow in general) so don't use it within AFL but from outside via shellexecute function call to an external script.





Hey Trash thanks for that I have made good progress tonight, I've no questions for a change mate!!

Cheers
 
I have just updated my trial to a paid licence.

Before I go any further I would like to set-up my data base for the ASX.

I have found this site through an earlier post in this forum

http://www.amibroker.org/3rdparty/ASX_Setup/

It has been last updated in 2010 - is this still a suitable process - or is there another way of setting up the database with GICS etc etc
 
I have just updated my trial to a paid licence.

Before I go any further I would like to set-up my data base for the ASX.

I have found this site through an earlier post in this forum

http://www.amibroker.org/3rdparty/ASX_Setup/

It has been last updated in 2010 - is this still a suitable process - or is there another way of setting up the database with GICS etc etc

Hi - I have gone down the path of getting data for Amibroker.

There was Yahoo data (free) which I was happy to use while on the trail.

However once going on the Amibroker lic it was a toss up between Norgate & Bohdi. Both paid providers.

Both have trials that you can download from their websites and try out for a couple of weeks before deciding who to go with. Note: the trial is limited regarding historical data..... From memory I think it goes back 12 months.

Regards,

Tradezy
 
Hi - I have gone down the path of getting data for Amibroker.

There was Yahoo data (free) which I was happy to use while on the trail.

However once going on the Amibroker lic it was a toss up between Norgate & Bohdi. Both paid providers.

Both have trials that you can download from their websites and try out for a couple of weeks before deciding who to go with. Note: the trial is limited regarding historical data..... From memory I think it goes back 12 months.

Regards,

Tradezy

I have downloaded Norgate data under a three week trial. I have now identified that the Yahoo data was picking up "adjusted" close - so the results of my simulations are now totally different.:mad:

I will now need to reconsider the conclusions I had reached on simulations using the Yahoo data.
 
I have downloaded Norgate data under a three week trial. I have now identified that the Yahoo data was picking up "adjusted" close - so the results of my simulations are now totally different.:mad:

I will now need to reconsider the conclusions I had reached on simulations using the Yahoo data.

Hi CNH --

If you are using Yahoo data, you probably DO want to use adjusted data. Adjusted data reflects splits and distributions, as you probably prefer. Norgate is a good choice. Wear just one watch -- then you are certain what time it is.

Best regards,
Howard
 
Hi CNH --

If you are using Yahoo data, you probably DO want to use adjusted data. Adjusted data reflects splits and distributions, as you probably prefer. Norgate is a good choice. Wear just one watch -- then you are certain what time it is.

Best regards,
Howard


Hi Howard bought your book "Quantitative Trading Systems, 2nd Edition" last Friday from Amazon.
Eagerly awaiting for it to arrive, but the post is soooo sloooow and I'm just like an impatient kid waiting for Christmas morning to arrive!!

Cheers
 
First of all code tags are these [ code ]blah[ /code ] without spaces.


As for getting symbol lists transported from one DB to another I would use AFL export procedure in your Norgate code from within AB after using mysymbols = CategoryGetSymbols(...) function to get comma separated list of symbols as watchlist tls files are available/updated in that mentioned Watchlist folder only after saving or closing a database. So if WL membership changes while DB is still open you have to save DB first to update that file (within AB it updates in realtime of course and new members are callable in realtime too). So IMO export of list is better.

But of course if you still want to go route of OLE you can save DB via OLE programmatically but MS OLE is not multi threading friendly (and slow in general) so don't use it within AFL but from outside via shellexecute function call to an external script.


Hey Trash and all, I'm back cup in hand asking for more help..
First question possibly leads to the second one.

Question one:
My IBliveDB scan I am executing in AA. I am cycling it continuously by having auto repeat turned on with AR interval of 5 sec.
Is AA happy to rescan for hours on end( a whole trading day)?
Can I scan my watchlist repeatedly from inside my afl coding via looping or can I invoke AA from inside my formula what is your opinion Trash should I bother? I am happy to load AA window and project file each trading morning if that's the way to go.

Question 2:
My Strategy requires a maximum of 5 or 6 open positions. I am referencing this via the variable "numopenpos" in the "for" loop in my live scan

openpossymbollist = ibc.GetPositionList();// gets comma seperated symbol list of open positions from IB
for( numopenpos = 0; ( symbol = StrExtract(openpossymbollist , numopenpos ) ) != ""; numopenpos++ )
{
printf("Position " + numopenpos + "\tSymbol: " + symbol + "\tSize: " + ibc.GetPositionSize( symbol ) + "\n" );
}


When "numopenpos" = 5 how do I get? (in order of my christmas wishlist):
1) Cancel any pending orders. // this ones easy use ibc.cancelallpendingorders?
2) IBC to shut down (close IBC window)
3) Amibroker to shut down
And now I'm really wishing!!
4) TWS to shut down
5) Computer to shut down...

That's bout it mate as usual really do appreciate your volunteer responses wouldn't have got his far without ya.

Cheers and ave a good weekend.
 
You can shut down AB via external OLE script

jscript:
Code:
AB = new ActiveXObject( "Broker.Application" ); // creates AmiBroker object

AB.SaveDataBase();

AB.Quit();

TWS I dunno. Some makro.
Computer shutdown ... do a google search.
 
You can also use it in your C# application. Here is console application example with timer. You need .NET 4.0

source code
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CloseAB
{
    class Program
    {
        static void Main(string[] args)
        {
            // Object model can be found at: http://www.amibroker.com/guide/objects.html
            // http://groups.yahoo.com/neo/groups/amibroker/conversations/messages/179763
            // You will need to compile using minimum .NET 4.0 because of the introduction to dynamic keyword!    
           
            Type broker = Type.GetTypeFromProgID("Broker.Application");
            dynamic AB = Activator.CreateInstance(broker);

            AB.SaveDatabase();

            for (int a = 5; a >= 0; a--) 
            {
                Console.Write("\rClosing AmiBroker in {0}", a); 
                System.Threading.Thread.Sleep(1000);                
            }

            AB.Quit();
        
        }
    }
}

.exe attached
 

Attachments

  • CloseAB.zip
    2.6 KB · Views: 9
Hi CNH --

If you are using Yahoo data, you probably DO want to use adjusted data. Adjusted data reflects splits and distributions, as you probably prefer. Norgate is a good choice. Wear just one watch -- then you are certain what time it is.

Best regards,
Howard

Can you tell me how I would go about populating the Norgate database with .ax in the alias box, for example BHP to have BHP.AX in the alias.

I am thinking that at this stage I will probably use Yahoo EOD data rather than a paid subscription.
 
Can you tell me how I would go about populating the Norgate database with .ax in the alias box, for example BHP to have BHP.AX in the alias.

Hi CNH --

Norgate maintains the database. BHP shows up several times in the US database. BHP for the ADR, BHP.asx, and two not-very-liquid classes.

Best,
Howard
 
You can shut down AB via external OLE script

jscript:
Code:
AB = new ActiveXObject( "Broker.Application" ); // creates AmiBroker object

AB.SaveDataBase();

AB.Quit();

TWS I dunno. Some makro.
Computer shutdown ... do a google search.


Thanks for the 2 replies trash,

My IBliveDB scan I am executing in AA. I am cycling it continuously by having auto repeat turned on with AR interval of 5 sec.
Is AA happy to rescan for hours on end( a whole trading day)?

So there isn't a way of stopping the auto repeat scan via AFL coding once I have my 5 open positions?
And is there no way to shut down IBC controller via AFL eg. IBC=closetradinginterface("IB")?
Cheers mate I'm learning Jscript now as well as AFL hoping to be able to script AB to open, preform scans then shutdown...
 
Thanks for the 2 replies trash,

My IBliveDB scan I am executing in AA. I am cycling it continuously by having auto repeat turned on with AR interval of 5 sec.
Is AA happy to rescan for hours on end( a whole trading day)?

So there isn't a way of stopping the auto repeat scan via AFL coding once I have my 5 open positions?

Why should AA care how often it is running? Do you think AA is gonna cry out loudly because of a helluva headaches and other pain? ;)

But if you wanna run it just a few times then as mentioned use OLE script run via some task scheduler.
https://www.amibroker.com/guide/objects.html
https://www.aussiestockforums.com/f...=1679&page=106&p=838501&viewfull=1#post838501

And is there no way to shut down IBC controller via AFL eg. IBC=closetradinginterface("IB")?

Code:
if ( /*your condition*/ )
{  
    ShellExecute( "cmd", "/c taskkill /f /im BrokerIB.exe", "", 0 ); // kill process    
}

http://technet.microsoft.com/en-us/library/bb491009.aspx
http://www.tech-recipes.com/rx/446/xp_kill_windows_process_command_line_taskkill/
 
My IBliveDB scan I am executing in AA. I am cycling it continuously by having auto repeat turned on with AR interval of 5 sec.
Is AA happy to rescan for hours on end( a whole trading day)?


Why should AA care how often it is running? Do you think AA is gonna cry out loudly because of a helluva headaches and other pain?

Ha ha I knew when I was writing that I was opening myself up!! But the amount of time I have spent with AB and AA lately one might think its my second wife, and you know the saying "Happy wife - Happy life":)

Cheers
 
I'm starting my journey with AmiBroker having bought a licence a couple of weeks ago and about to get into Howard bandy's book.

I have been looking at the following "contrarian" trading system and backtesting on 50 symbols I am seeing good results, other than through the GFC.

Is it possible to put an index filter in to turn off buying, say when the 50 EMA drops below the 200 EMA.

I have tried various codes but they haven't worked and at this stage my AFL skills are insufficient.

I also understand that possibly I will not be able to put in an index filter.

The system I am testing is:

Code:
// Simple example of rotational trading system
// This is contrarian strategy - 
// it buys 4 "worst" stocks - the ones that suffered the most in last year
// (4 stocks having worst 252-bar rate-of-change)
// 
// 4 positions
MaxPositions = 4;
SetOption("MaxOpenPositions", MaxPositions  );
SetOption("WorstRankHeld", MaxPositions + 2 );
SetPositionSize( 100 / MaxPositions, spsPercentOfEquity ); 

// trade on next day open
SetTradeDelays( 1, 1, 1, 1 );
BuyPrice = Open;

SetBacktestMode( backtestRotational );

// offsetting by large positive number 
// makes sure that our score is always positive and we don't enter short trades
PositionScore = 10000 - ROC( C, 252 );

Any suggestions will be appreciates as I get my journey underway.
 
I'm starting my journey with AmiBroker having bought a licence a couple of weeks ago and about to get into Howard bandy's book.

I have been looking at the following "contrarian" trading system and backtesting on 50 symbols I am seeing good results, other than through the GFC.

Is it possible to put an index filter in to turn off buying, say when the 50 EMA drops below the 200 EMA.

I have tried various codes but they haven't worked and at this stage my AFL skills are insufficient.

I also understand that possibly I will not be able to put in an index filter.

The system I am testing is:

Code:
// Simple example of rotational trading system
// This is contrarian strategy - 
// it buys 4 "worst" stocks - the ones that suffered the most in last year
// (4 stocks having worst 252-bar rate-of-change)
// 
// 4 positions
MaxPositions = 4;
SetOption("MaxOpenPositions", MaxPositions  );
SetOption("WorstRankHeld", MaxPositions + 2 );
SetPositionSize( 100 / MaxPositions, spsPercentOfEquity ); 

// trade on next day open
SetTradeDelays( 1, 1, 1, 1 );
BuyPrice = Open;

SetBacktestMode( backtestRotational );

// offsetting by large positive number 
// makes sure that our score is always positive and we don't enter short trades
PositionScore = 10000 - ROC( C, 252 );

Any suggestions will be appreciates as I get my journey underway.

http://www.amibroker.com/guide/afl/setforeign.html


Code:
.
.
.

SetForeign("^GSPC" );
Filter = Cross( MACD(), Signal());
RestorePriceArrays();

PositionScore = Iif( Filter, 10000 - ROC( C, 252 ), 0 );
 
http://www.amibroker.com/guide/afl/setforeign.html


Code:
.
.
.

SetForeign("^GSPC" );
Filter = Cross( MACD(), Signal());
RestorePriceArrays();

PositionScore = Iif( Filter, 10000 - ROC( C, 252 ), 0 );

Okay I have modified my code using the XAO as the filter code.

Code:
MaxPositions = 4;
SetOption("MaxOpenPositions", MaxPositions  );
SetOption("WorstRankHeld", MaxPositions + 2 );
SetPositionSize( 100 / MaxPositions, spsPercentOfEquity ); 

// trade on next day open
SetTradeDelays( 1, 1, 1, 1 );
BuyPrice = Open;

SetBacktestMode( backtestRotational );

// offsetting by large positive number 
// makes sure that our score is always positive and we don't enter short trades

SetForeign("XAO");
Filter = Cross( EMA(C,180), EMA(C,50));
RestorePriceArrays();

PositionScore = Iif( Filter, 10000 - ROC( C, 252 ), 0 );

The results are not as I have expected.

It has made a correct entry point [when condition TRUE on Filter = Cross( EMA(C,180), EMA(C,50));]

but closes the position unexpectedly [no negative crossover FALSE on Filter = Cross( EMA(C,180), EMA(C,50));] a few days later,

then makes a new entry a month or so later - at a time when no positive cross [TRUE] has occurred and then closes again without a negative crossover.

Hopefully what I have explained is somewhat clear.
 
Top