US-Stocks Database (v2)

Jim, who is a long term AmiBroker user, regularly provides an updated template that automatically sets up a database of all US stocks available from Yahoo!Finance.

The stocks are initially categorized by Market and then as Stocks, Indexes or Funds at the Group level. They are also organized into Sectors, using the Hemscott classification system.

A link to the latest message from Jim is available at AmiBrokerYahooGroup message # 119057 - "AmiBroker/Yahoo Database File":  http://finance.groups.yahoo.com/group/amibroker/message/119057

Or link directly to the site to obtain the download:

http://www.icc-az.com

Go to Links >> AmiBroker at that site (instructions are available at the download page).

After the database is setup, use AmiQuote to download data from the Yahoo Historical server (allow approximately 1/2 - 1 hour download time, using a mid speed broadband connection, per year of history).

The length of back history available varies with each symbol (the author has downloaded up to 10 years history using this template).

Typically the ticker list, as setup, will contain a couple of hundred redundant symbols (symbols that return an error message when attempting to download historical data for them). Most of the redundant symbols are .OB (over the counter stock) and are not relevant to the majority of traders. Users can elect to delete them from the database or go to the Yahoo site, or other sites, to find the cause of the ‘download error’ e.g. the stock may have been de-listed or undergone a name change .

Instructions on how to find and delete the redundant (NoQuotes) symbols can be found in the UKB post >> Setup A Custom Database - Nasdaq

Information, or discussion, on the pros and cons of using Yahoo data is included in articles in the Yahoo sub-category at the Users’ Knowledge Base:

http://www.amibroker.org/userkb/?cat=99

Further information, about using the US-Stocks database, can be obtained by searching the AmiBrokerYahooGroup message board (use an Advanced Search and enter Subject contains "US-Stocks" OR "AmiBroker/Yahoo Database" as the search criteria .

 

Version 2 - Feb 02/2008 - by Brian_z - written using Windows Live Writer - updated links to current message and new download site

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5 out of 5)
Loading ... Loading ...

ASCII Import - Standard and Poor’s Global 1200

Objective 

The objective, for this post, is to outline a basic method for setting up a custom database, using ASCII importation to install the categorized structure.

A Global 1200 database, suitable for use with Yahoo data, is used as the example.

Note: it is an outline only and the procedure is not taken to completion i.e. it is not set-up as a working database (interested readers can complete that task for themselves).

 Pre-Requisites

It is assumed that readers are familiar with earlier posts in the UKB >> Database Management series (the basic skills introduced there are not recapped in this post) and also the ASCII Importer Reference (from the Users Guide).

http://www.amibroker.com/guide/d_ascii.html

 Introduction

"American Standard Code for Information Interchange (ASCII) allows digital devices to communicate with each other and to process, store, and communicate character-oriented information" 1.

It is the format used to import data into AmiBroker, via AmiQuote, or manually, via the ASCII Import function.

In this example, a list of the Global 1200 constituents, including Market and Sector categorization, is downloaded from the Standard and Poors (US) site and pre-conditioned into an ASCII compliant format, before importing it into AmiBroker.

Note: the example is a basic one, but, users can easily extend the method to more complex databases.

Preparation

Step1

A constituent list, in Comma Separated Value (CSV) format, can be downloaded from the Standard and Poors Homesite (US):

http://www2.standardandpoors.com/portal/site/sp/en/us/page.home/home/0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0.html

Go to Indices >>  + Equity Indices >> S and P Global Indices >> S and P Global 1200

OR follow the link below to go directly to the page:

http://www2.standardandpoors.com/portal/site/sp/en/us/page.topic/indices_gbl1200/2,3,2,1,0,0,0,0,0,0,3,0,0,0,0,0.html

 

Step 2

Click on Download Table, at the top of the page, to save a local copy of the Constituent List (save it in a spreadsheet compliant format)

ASC001

Note: not all of the Countries, with stocks in the Global 1200, are supported by Yahoo!Finance (refer to the following link for a list of Yahoo’s international exchanges  - http://finance.yahoo.com/exchanges)

 

Step 3

Prepare the file for ASCII Import, using the spreadsheet functions:

a) Trim excess ‘whitespace’ from the symbols, manually enter Yahoo exchange suffixes and append them to the symbols, sort by Market (Country) and manually add a column for the Market ID (0-23).

b) Delete symbols that are from unsupported exchanges, sort by Sector and manually add a column for the Sector ID’s (0-9).

c) Copy the Fullname, Ticker, Market ID and Sector ID columns to a separate Global1200.CSV file, ready for importing.

Note: Refer to the attached files 24-March-2008_GBL1200.xls and Global1200.xls (the Global1200 file is attached in .xls format as the UKB does not permit uploading of .csv files).

 

Step 4

Prepare a broker.industries and broker.sector file, using the template in the 24-March-2008_GBL1200.xls file, and save them in the root of the Programs/AmiBroker directory (overwrite the existing broker.industries and broker.sector files).

 

Step 5

Prepare an ASCII formats file and save it in the Programs/AmiBroker/Formats folder.

The file, for this example, needs to be in the following format (the file can be written in a plain text editor, like NotePad, and saved as Global1200.format):

ASC002

Note: The file name will be automatically added to the import.types list, which is also in the Programs/AmiBroker/Formats folder.

 

Step 6

Create a new EOD database, called Data_Global1200

Go to File >> Import ASCII and elect to Open the Global1200.csv file as file type Global1200(*.*)

Note: the import.types (formats file) list will be the default Files of type list in the file browser window that opens.

ASC003

The symbol list and database structure, as defined in the Global1200.csv file, will now be set-up in the current database.

Note: the Markets and Groups categories will remain as the default settings (they can only be renamed manually via Symbol >> Categories).

ASC005

Step 7

Data can now be downloaded, for the database, from the Yahoo historical server.

On downloading some symbols will return a 404 error.

In some cases the errors can be repaired by ‘researching’ via the Yahoo sites e.g. Hong Kong stocks use four digits and require leading zeros, which are not included in the symbols used by Standard and Poors.

In other cases there are multiple exchanges, supported by Yahoo, for a given country, so the ticker may need an alternative suffix (for this example the author assumed all tickers included in the Global 1200 were listed on the constituent countries major exchange).

 

ATTACHED FILES:

24-mar-2008_gbl1200.xls
global1200.xls

Browse the spreadsheet files on line, or, right click and select Save As to download them as an editable version.

REFERENCES:

1 - http://en.wikipedia.org/wiki/ASCII

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5 out of 5)
Loading ... Loading ...

AmiBroker Supported Sites

 

This post contains a list of AmiBroker ’supported’ sites (most of the sites are officially supported by AmiBroker but some are not).

Search the main sites by using Google’s "Advanced Search" feature at http://www.google.com (search within a site, or domain, by using the URL address).

Alternatively visit any of the ’supported’ sites for categorized information on AmiBroker features, purchase, installation, testimonials, news, FAQ’s, downloads, documents, knowledge bases, tips, code and mailing lists.

For personal support please email - support [at] AmiBroker.com

1) AmiBroker’s Homesite

This site is searchable using the "Search" box in the top left corner of the "Welcome" page.

 

Links to specific pages at the AmiBroker Homesite

a) A downloadable PDF version of the Users’ Guide (Help Manual).

Note: the PDF version has superior search features compared to the other available versions.

http://www.amibroker.com/bin/UsersGuide.pdf

b) An online version of the Users’ Guide (Help Manual).

http://www.amibroker.com/guide/

c) FAQ’s.

http://www.amibroker.com/faq.html

d) AmiBroker Knowledge Base (KB).

The ‘official’ Knowledge Base site with tips & usage hints from AmiBroker.com

http://www.amibroker.com/kb/

e) AmiBroker Tips Newsletter.

http://www.amibroker.com/newsletter/

NOTE: The Newsletter has been now replaced by the AmiBroker Knowledge Base at: http://www.amibroker.com/kb/

f) AmiBroker support page.

The support page features additional documentation and videos.

http://www.amibroker.com/support.html

g) AFL Library.

The AFL on-line library provides a very convenient way to share formulas, including descriptions and comments, between AmiBroker users. You will not only  be able to get the formula you need here but also contribute your own ideas.

http://www.amibroker.com/library/

h) Members Area.

This provides additional material for registered AmiBroker users, including the newest issues of Stocks & Commodities Traders tips for AmiBroker

http://www.amibroker.com/login.html

i) The online version of the AFL Function Reference (searchable).

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

j) AmiBroker Development Log.

http://www.amibroker.com/devlog/

k) Feedback Centre.

You can submit your ideas and suggestions and see the list of features planned for the next few releases (registered users only).

http://www.amibroker.com/todo.html

 

2) AmiBroker User’s Knowledge Base (UKB)

This site is owned and operated by AmiBroker but its contents are entirely contributed by users.

It was was created to save you time, raise your productivity, aid you in your Amibroker Formula Language (AFL) learning experience, and help you become a more successful trader.

http://www.amibroker.org/userkb/

UKB features:

          Automated Trading, by Herman van den Bergen

          Intelligent Optimization, by Fred Tonetti.

 

3) AmiBroker third party site

An unstructured FTP site, sponsored by AmiBroker.com, to facilitate  file sharing between Amibroker users.

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

 

4) The AmiBroker mailing list

The list is provided to help Amibroker users to share ideas, tips and other related information. This is the place where you can meet other AmiBroker users, ask questions and share ideas (searchable archive and file uploading).

http://finance.groups.yahoo.com/group/amibroker/

 

5) The AmiBroker Trading Systems mailing list.

This group is for discussion on developing and testing trading systems, using AmiBroker (searchable archive and file uploading).

http://finance.groups.yahoo.com/group/amibroker-ts/

 

6) The AmiBroker Automated Trading mailing list.

This group is for discussion on Automated Trading, using AmiBroker (searchable archive and file uploading).

http://finance.groups.yahoo.com/group/AmiBroker-at/

1 Star2 Stars3 Stars4 Stars5 Stars (5 votes, average: 5 out of 5)
Loading ... Loading ...

Using a GFX Include file

Important note: The AmiBroker 5.09.0 Beta introduced the following new GFX functions:

Status(”pxchartleft”) - returns x-coordinate of top-left corner of chart area
Status(”pxcharttop”) - returns y-coordinate of top-left corner of chart area
Status(”pxchartright”) - returns x-coordinate of bottom-right corner of chart area
Status(”pxchartbottom”) - returns y-coordinate of bottom-right corner of chart area
Status(”pxchartwidth”) - returns width chart area (right-left)
Status(”pxchartheight”) - returns width chart area (bottom-top)

Since this release appeared after this post was published these functions are not used in the examples below. This post has been left unchanged for educational purposes. For examples using the new functions please see the 5.09.0 Read Me file.

=====

While the post Creating GFX Chart-Overlays (v2) may have clarified a few of the more important aspects of using GFX functions, it doesn’t really give you a “quick Start” template to get started. Using a GFXInclude file can remove some of the burden of having to define pixel and charting parameters. The Include file at the bottom of this post contains most definitions as well as these common functions that you may want to call from your GFX application:

1
2
3
4
5
GetVisualBarIndex( ); // Returns array containing index for visible bars
gfxPlotHLine( YPixels, Color ); // Plots horizontal line at level YPixels
gfxPlotVLine( XPixels, Color ); // plots vertical line at level XPixels
GetYPixels( Y ); // Convert a vertical price number to the pixel equivalent
GetXPixels( X ); // Convert a horizontal DateTime number value to the pixel equivalent

Of course you can, and should, add additional functions of your own. Here is an example of how to call the above functions to draw a GFX cross-hair cursor (Red in the capture):

gfxcrosshair.jpg

Here is the code that produced the above image:

1
2
3
4
5
6
7
8
9
10
11
12
13
GraphXSpace = 5; // See the AmiBroker help on how to init these variables
GfxSetBkMode( bkmode = 2 );
GfxSetOverlayMode( mode = 0 );
GfxSelectPen( colorRed );
 
Plot( C, "", colorBlack, styleLine ); // To define miny and maxy
#include <GFXInclude-001.afl> // Located in your default Include folder
 
// Example to draw cross-hair cursor
Yprice = GetCursorYPosition(0);
XIndex = SelectedValue(GetVisualBarIndex( ));
gfxPlotHLine( GetYPixels( YPrice ), colorRed );
gfxPlotVLine( GetXPixels( XIndex ), colorRed );

The include file listed below defines the following variables:

1
// pxwidth, pxheight, Miny, MinX, YRange, VisBarIndex, NumBarsVisible, pxPaneWidth, pxPaneheight, PixelsPerBar, PixelsPerPrice

You may want to copy the above comment line below the #include statement in your code to refresh your memory. You should copy the Include file to your default AmiBroker Include folder.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// GFXInclude-001.afl copy to default include folder
 
function gfxPlotHLine( YPixels, Color )
{
    global pxwidth;
    GfxSelectPen( Color ) ;
    GfxMoveTo( 0, YPixels );
    GfxLineTo( pxwidth, YPixels );
}
 
function gfxPlotVLine( XPixels, Color )
{
    global pxheight;
    GfxSelectPen( Color ) ;
    GfxMoveTo( XPixels, 0 );
    GfxLineTo( XPixels, pxheight );
}
 
function GetVisualBarIndex( )
{
    lvb = Status( "lastvisiblebar" );
    fvb = Status( "firstvisiblebar" );
    bi = BarIndex();
    StaticVarSet( "NumberbarsVisible", Lvb - fvb + 1 );
    return bi - bi[ 0 ] - fvb;
}
 
function GetYPixels( Y )
	{
	global PixelsPerPrice, pxTopArea, MaxY; 
	return (MaxY - Y) * PixelsPerPrice + pxTopArea;
	}
 
function GetXPixels( X )
	{
	global PixelsPerBar, pxLeftArea;
	return X * PixelsPerBar + pxLeftArea;
	}
 
_SECTION_BEGIN("GFX INITIALIZATION");
// These Parameters will change depending on screen layout/fonts
pxRightArea = Param( "Right Axis Area", 93, 0, 200, 1 ); // Depends on font
pxDateArea = Param( "Date Axis Area", 11, 0, 100, 1 ); // Depends on font
DateaxisOn = ParamToggle( "Date Axis", "HIDE|SHOW", 1 );
 
pxLeftArea = 5; 
pxTopArea = 5; 
pxBottomArea = 5; 
if ( DateaxisOn )
{
    pxBottomArea = pxDateArea + pxBottomArea;
    SetChartOptions( 2, chartShowDates );
}
else
    SetChartOptions( 3, chartShowDates );
 
pxwidth = Status( "pxwidth" );
pxheight = Status( "pxheight" );
 
// clalculate charting area width and height
Miny = Status( "axisminy" );
Maxy = Status( "axismaxy" );
YRange = MaxY - MinY;
VisBarIndex =  GetVisualBarIndex( );
NumBarsVisible = StaticVarGet( "NumberbarsVisible" );
 
// Calculate Pane width and height
pxPaneWidth = pxwidth - pxLeftArea - pxRightArea;
pxPaneHeight = pxHeight - pxTopArea - pxBottomArea;
 
// calculate conversion factors
PixelsPerBar 	= pxPaneWidth / NumBarsVisible;
PixelsPerPrice = pxPaneHeight / YRange;
_SECTION_END();

Edited by Al Venosa.

1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 5 out of 5)
Loading ... Loading ...

Creating GFX Chart-Overlays (v3)

Important note: The AmiBroker 5.09.0 Beta introduced the following new GFX functions:

Status(”pxchartleft”) - returns x-coordinate of top-left corner of chart area
Status(”pxcharttop”) - returns y-coordinate of top-left corner of chart area
Status(”pxchartright”) - returns x-coordinate of bottom-right corner of chart area
Status(”pxchartbottom”) - returns y-coordinate of bottom-right corner of chart area
Status(”pxchartwidth”) - returns width chart area (right-left)
Status(”pxchartheight”) - returns width chart area (bottom-top)

Since this release appeared after this post was published these functions are not used in the examples below. This post has been left unchanged for educational purposes. For examples using the new functions please see the 5.09.0 Read Me file.

=====

Creating an exact chart overlay using GFX functions can be a daunting task for the non-professional programmer. The solutions presented here were derived through experimentation; if there is a better way, please make a comment. Once the pixel layout is fully understood, GFX becomes an extremely powerful tool and may just give you an additional trading edge. The first and most important step in using GFX functions is to understand how pixels make up your display. In AmiBroker the width and height of your charting pane can be retrieved using the following two functions:

1
2
pxwidth = Status("pxwidth");
pxheight = Status("pxheight");

Horizontal pixels count left to right, 1 to pxwidth; vertical pixels count top to bottom, 1 to pxheight. The area covered by these two numbers is shown in Yellow below. For a high resolution monitor this area may cover about 2000 (H) x 1000 (V) pixels. This pixel area includes the areas used by the X and Y axis, and the blank top and bottom margins.

pixelarea.png

Next is the standard charting area, which is the area where your price charts are located. This area excludes the surrounding blank margins and the areas used for axis labeling. If you want to keep your overlay within the standard chart boundaries, you have to place your images within the above boundaries. This area is highlighted in Blue in the image below:

chartingarea.png

The boundaries for this area can be determined by running the example code listed in Finding Pixel Boundaries. Eight parameters must be known to create pixel overlays:

1
2
3
4
5
6
7
8
pxwidth = Status( "pxwidth" );
pxheight = Status( "pxheight" );
pxLeftArea = Param( "Left Blank Margin", 5, 0, 100, 1 ); // Constant
pxRightArea = Param( "Right Axis Area", 93, 0, 200, 1 ); // Depends on font
pxTopArea = Param( "Top Blank Margin", 5, 0, 100, 1 ); // Constant
pxDateArea = Param( "Date Axis Area", 11, 0, 100, 1 ); // Depends on font
pxBottomArea = Param( "Bottom Blank Margin", 5, 0, 100, 1 ); // Constant
DateaxisOn = ParamToggle( "Date Axis", "HIDE|SHOW", 1 );

Since adding date labels to your DateTime axis changes the size of your pixel plotting area, you need to compensate for this:

1
2
3
4
5
6
7
8
9
if( DateaxisOn ) 
	{
	pxBottomArea = pxDateArea + pxBottomArea;
	SetChartOptions(2,chartShowDates);
	}
else 
	{
	SetChartOptions(3,chartShowDates);
	}

The pixel plotting area’s width and height can now be calculated:

1
2
pxPaneWidth = pxwidth - pxLeftArea- pxRightArea;
pxPaneHeight = pxHeight - pxTopArea- pxBottomArea;

The dimension of the Blue area shown earlier changes when you resize AmiBroker, open additional windows or panes, change the fonts in your axis, or turn On/Off date labels. When this happens you will have to recalibrate the boundaries. To convert prices to pixels, so that you can create an exact overlay, you also need to define the width and height of your regular chart pane. These are expressed in DateTime and Price units. They will change when you zoom your chart. When you have at least one price plot displayed, so that the values for miny and maxy are defined, you can calculate these boundaries as follows:

1
2
3
4
5
Miny = Status("axisminy");
Maxy = Status("axismaxy");
YRange = MaxY - MinY
BarsVisible = Status("BarVisible");
NumBarsVisible = Cum(BarsVisible);

You now have all the information needed to calculate the Pixels/Price and Pixels/Bar conversion factors:

1
2
PixelsPerBar 	= pxPaneWidth / NumBarsVisible;
PixelsPerPrice = pxPaneHeight / YRange;

Putting it all together in a demo program (listed at the end of this post) produces the price-chart overlay shown below. The regular price plot is plotted using dots, so that the overlay is clearly visible. When you plot both traces in lines, you will see minor deviations that are probably due to rounding to the nearest pixel. The pixel price plot is shown in Red. The purpose of this exercise is to learn to work with pixels and be able to produce an exact overlay on the price chart. The Param window below the charts shows typical parameters; they will likely be different for your screen layout.

pricechartoverlay1.png

pricechartoverlayparam.png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
function gfxPlotHLine( YPixels, Color )
{
    global pxwidth;
    GfxSelectPen( Color ) ;
    GfxMoveTo( 0, YPixels );
    GfxLineTo( pxwidth, YPixels );
}
 
function gfxPlotVLine( XPixels, Color )
{
    global pxheight;
    GfxSelectPen( Color ) ;
    GfxMoveTo( XPixels, 0 );
    GfxLineTo( XPixels, pxheight );
}
 
function GetVisualBarIndex( )
{
    lvb = Status( "lastvisiblebar" );
    fvb = Status( "firstvisiblebar" );
    bi = BarIndex();
    StaticVarSet( "NumberbarsVisible", Lvb - fvb + 1 );
    return bi - bi[ 0 ] - fvb;
}
 
function GetYPixels( Y )
	{
	global PixelsPerPrice, pxTopArea, MaxY; 
	return (MaxY - Y) * PixelsPerPrice + pxTopArea;
	}
 
function GetXPixels( X )
	{
	global PixelsPerBar, pxLeftArea;
	return X * PixelsPerBar + pxLeftArea;
	}
 
GraphXSpace = 5;
SetChartOptions( 0, chartHideQuoteMarker );
 
pxwidth = Status( "pxwidth" );
pxheight = Status( "pxheight" );
 
// These Parameters will change depending on screen layout/fonts
pxRightArea = Param( "Right Axis Area", 93, 0, 200, 1 ); // Depends on font
pxDateArea = Param( "Date Axis Area", 11, 0, 100, 1 ); // Depends on font
DateaxisOn = ParamToggle( "Date Axis", "HIDE|SHOW", 1 );
 
// These Parameters appear constant and can probably be hardcoded
pxLeftArea = Param( "Left Blank Margin", 5, 0, 100, 1 ); // Constant
pxTopArea = Param( "Top Blank Margin", 5, 0, 100, 1 ); // Constant
pxBottomArea = Param( "Bottom Blank Margin", 5, 0, 100, 1 ); // Constant
 
if ( DateaxisOn ) // Size of bottom boundary depends on whether dates are shown
{
    pxBottomArea = pxDateArea + pxBottomArea;
    SetChartOptions( 2, chartShowDates );
}
else
    SetChartOptions( 3, chartShowDates );
 
// Test Plots to help line up boundary lines
Color = colorWhite;
gfxPlotVLine( pxLeftArea, color );
gfxPlotVLine( pxwidth - pxRightArea, color );
gfxPlotHLine( pxTopArea, color );
gfxPlotHLine( pxHeight - pxBottomArea, color );
 
// Calculate Pane width and height
pxPaneWidth = pxwidth - pxLeftArea - pxRightArea;
pxPaneHeight = pxHeight - pxTopArea - pxBottomArea;
 
// clalculate charting area width and height
Plot( C, "", 1, styleDots );
Miny = Status( "axisminy" );
Maxy = Status( "axismaxy" );
YRange = MaxY - MinY;
VisBarIndex =  GetVisualBarIndex( );
NumBarsVisible = StaticVarGet( "NumberbarsVisible" );
 
// calculate conversion factors
PixelsPerBar 	= pxPaneWidth / NumBarsVisible;
PixelsPerPrice = pxPaneHeight / YRange;
 
// For verification: Overlay pixel on price plot
FVB = Status( "firstvisiblebar" );
LVB = Status( "lastvisiblebar" );
GfxSelectPen( colorRed );
for ( b = FVB + 1; b <= LVB AND b < BarCount; b++ )
{
    PrevPixelY = GetYPixels( C[b-1] );
    PixelY = GetYPixels( C[b] );
 
    PrevPixelX = GetXPixels( VisBarIndex[b-1] );
    PixelX = GetXPixels( VisBarIndex[b] );
 
    GfxMoveTo( PrevPixelX, PrevPixelY );
    GfxLineTo( PixelX, PixelY );
}

Edited by Al Venosa.

1 Star2 Stars3 Stars4 Stars5 Stars (5 votes, average: 5 out of 5)
Loading ... Loading ...

Setting prices with your cursor

To place LMT or STP orders quickly is easiest done by moving the horizontal cursor-line over the desired price and making a left mouse click. The demo code below shows how you can lock in prices this way. To Chart-Trade additional code must be added to make the click perform one task of many, and only do so when required. When you Apply the code below to an indicator you will see a dashed line at the cursor price. This dashed line refreshes only once per second with a local database, however, it will speed up when your chart is refreshed more frequently when working with live data.

Suppose you want to place a LMT order at $60.00 on the chart below. To do this you move the dashed line over the $60.00 price and click the Left mouse button. This will place a stationary solid line. You can now move your cursor to another price and click again, the solid line will move to this new location. In actual trading you can follow the price in real time and adjust your Limit prices so that they stay exactly where you want them. The chart produced by this demo code looks like this:

placingline.png

In Chart-Trading the first click that places the solid line would also place your order on the TWS. Each subsequent click would modify the order to the new price. This way you can adjust several prices on your chart, setting and moving around Entries, Targets, Stops, etc.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
RequestTimedRefresh( 1 );
SetChartOptions( 2, chartHideQuoteMarker );
LButtonDown = GetCursorMouseButtons() == 9;
MousePrice = GetCursorYPosition();
 
if ( MousePrice )
{
    StaticVarSet( "MousePrice", MousePrice );
    if ( LButtonDown )
        StaticVarSet( "ClickedMousePrice", MousePrice );
}
 
LB = BarCount - 1;
MousePrice = Nz( StaticVarGet( "Mouseprice" ), Null );
ClickedMousePrice = StaticVarGet( "ClickedMousePrice" );
 
Plot( C, "", 1, 128 );
Plot( MousePrice, "", colorWhite, 1 | styleNoRescale | styleDashed | styleNoLabel, 0, 0, 2 );
PlotText( "CURSOR " + NumToStr( MousePrice[LB], 1.2 ), LB - 5, MousePrice[LB], colorBlack, colorWhite );
Plot( ClickedMousePrice, "", colorBlack, 1 | styleNoLabel | styleNoRescale, 0, 0, 2 );
PlotText( "ORDER PLACED $" + NumToStr( ClickedMousePrice[LB], 1.2 ), LB - 5, ClickedMousePrice[LB], colorBlack, colorWhite );
1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5 out of 5)
Loading ... Loading ...

Parsing TWS Error messages

Here is some simple code you can use to enable you to start developing your own error-parsing functions. In this example, error messages are hard-coded to facilitate code development, i.e. you don’t have to be live with IB to test it. I suggest that you inspect the IB list of error messages, copy the errors that are important to you, and add them to the hard-coded list. Since IB doesn’t list the error messages in the exact format you will receive them, you may have to place some orders with errors to see their exact format. When Applied to an Indicator, the code can be exercised by selecting the Error Message with the slider in the Param window. It will display the current error and parsing results in the Chart Title. Be sure to set Parameter properties to wrap the Title.

parsingerrors.png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
S = Param( "Example Error Msg", 0, 0, 10, 1 );
switch ( S )
{
case 0:
    TWSLastErrorMsg = "ID=15071. Error 135. Can't find order with id =:15071";
    break;
case 1:
    TWSLastErrorMsg = "ID=2094, Error 103, Duplicate ORder id";
    break;
case 2:
    TWSLastErrorMsg = "ID=-1, Error 1102, Connectivity between IB AND TWS Has been restored - data MAintained";
    break;
case 3:
    TWSLastErrorMsg = "ID=-1, Error 2100, New account data requested";
    break;
case 4:
    TWSLastErrorMsg = "ID=-1, Error 1100, Connectivity between IB AND TWS has been lost";
    break;
case 5:
    TWSLastErrorMsg = "Connection established OK, Next Order Id=2080";
    break;
case 6:
    TWSLastErrorMsg = "ID=6125. Error 202. Order Canceled - reason:";
    break;
default:
    TWSLastErrorMsg = "";
    break;
}
 
function GetErrorCode( TWSLastErrorMsg )
{
    p = StrFind( TWSLastErrorMsg, " Error " );
    ErrStr = StrMid( TWSLastErrorMsg, p + 6, 4 );
    ErrNum	= StrToNum( ErrStr );
    ErrStr	= NumToStr( ErrNum, 1.0, False );
    return ErrStr;
}
 
function ExtractErrorID( TWSLastErrorMsg )
{
    p = StrFind( TWSLastErrorMsg, "ID=" );
    IDStr = StrMid( TWSLastErrorMsg, p + 2, 5 );
    IDNum	= StrToNum( IDStr );
    IDStr	= NumToStr( IDNum, 1.0, False );
    return IDStr;
}
 
TWSErrorCode = GetErrorCode( TWSLastErrorMsg );
TWSErrorOrderID = ExtractErrorID( TWSLastErrorMsg );
Title = "\n" +
        "Extracting OrderIDs and Error codes from TWS Error Messages" + "\n" +
        "Example Error Msg: " + TWSLastErrorMsg + "\n" +
        "        Error Code: " + TWSErrorCode + "\n" +
        " TWS Error OrderID: " + TWSErrorOrderID;
1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 3.5 out of 5)
Loading ... Loading ...

Introduction to Real-Time Chart-Trading

IMPORTANT NOTE: DO NOT USE ANY OF THE PROGRAMS PRESENTED HERE TO TRADE REAL MONEY. Most of the programs presented will only work with live data, execution reports, and market conditions. They will NOT work using the AmiBroker Bar Replay or the IB eDemo account.

Traditional Day-Trading by looking at TWS prices may still work for experienced traders who, probably over a period of many years, developed rapid interpretation skills. However, for less experienced traders graphical representations are much easier to interpret than spreadsheets or tables. Setting prices by clicking on your chart is much faster than entering prices in little windows. Trailing the price with your cursor is much faster than entering and modifying parameters in a GUI. All this is especially true when you are trading in real-time, where every second counts.

Posts in this category will introduce techniques that you can use to create your own custom designed Chart-Trading GUI. If you Google Chart-Trading you will find many examples of the many ways you can layout your personal interface. If you aim for maximum simplicity and automation you will end up with the most efficient GUI. Tentative topics that will be covered are:

1) Laying out buttons and controls (Param() Or Button())
2) House keeping functions (AutoTrading, CancelAll, CloseAll, etc.)
3) Automating setup for different trading methodologies (minimizing setup procedure)
4) Auto placement of orders
5) Auto Modification of Orders
6) Displaying order and system status
7) Performance reporting (Profits, Wins, etc.)

1 Star2 Stars3 Stars4 Stars5 Stars (4 votes, average: 4.75 out of 5)
Loading ... Loading ...

AmiBroker Custom Backtester Interface

by Wayne (GP)

Introduction

From version 4.67.0, AmiBroker provides a custom backtester interface to allow customising the operation of the backtester’s second phase which processes the trading signals. This allows a range of special situations to be achieved that aren’t natively supported by the backtester. AmiBroker tends to refer to this as the Advanced Portfolio Backtester Interface, but as it seems to be more widely referred to as the Custom Backtester Interface, I will use this latter terminology.

Due to the object model used by the backtester interface, a higher level of programming knowledge is required than for simple AFL or looping. This document starts by discussing that model, so is aimed at AFL programmers who are already proficient and comfortable with basic AFL use, array indexing, and looping. If you don’t understanding looping, then you almost certainly won’t understand the custom backtester interface.

The Object Model

The modern programming paradigm is called object-oriented programming, with the system being developed modelled as a set of objects that interact. The custom backtester interface follows that model.

An object can be thought of as a self-contained black-box that has certain properties and can perform certain functions. Internally it’s a combination of code and variables, where both can be made either private to the internals of the object only or accessible from outside for the benefit of users of the object. The private code and variables are totally hidden from the outside world and are of no interest to users of the object. Only developers working on the object itself care about them. Users of the object are only interested in the code and variables made accessible for their use.

Any variable made accessible to an object’s user is called a property of the object. For example, the Backtester object has a property (variable) called “Equity”, which is the current value of the portfolio equity during a backtest. Properties can be read and written much the same as any other variable, just by using them in expressions and assigning values to them (although some properties may be read-only). However, the syntax is a little different due to the fact they’re properties of an object, not ordinary variables.

An object’s code is made accessible to its users by providing a set of functions that can be called in relation to the object. These functions are called methods of the object. They are essentially identical to ordinary functions, but perform operations that are relevant to the purpose of the object. For example, the Backtester object has methods (functions) that perform operations related to backtesting. Methods are called in much the same way as other functions, but again the syntax is a little different due to them being methods of an object rather than ordinary functions.

The aim of the object model is to view the application as a set of self-contained and reusable objects that can manage their own functionality and provide interfaces for other objects and code to use. Imagine it as being similar to a home entertainment system, where you buy a number of components (objects) like a TV, DVD player, surround-sound system, and karaoke unit (if you’re that way inclined!). Each of those components manages its own functionality and provides you with a set of connectors and cables to join them all together to create the final application: the home entertainment system. The beauty of that arrangement is that each component provides a standard interface (if you’re lucky) that will allow any brands of the other components to be connected, without those components having to know the details of how all the other components work internally, and considerable choice in the structure of the final entertainment system constructed. Similarly, software objects have standard interfaces in the form of methods and properties that allow them to be used and reused in any software.

Accessing Oject Properties And Methods

To access the properties and methods of an object, you need to know not only the name of the property or method, but also the name of the object. In AmiBroker AFL, you cannot define or create your own objects, only use objects already provided by AmiBroker. AmiBroker help details all its objects, methods, and properties in the section “Advanced portfolio backtester interface”.
To use real AFL examples, the first object detailed in the help is the Backtester object. AmiBroker provides a single Backtester object to perform backtests. To use the Backtester object, you first have to get a copy of it and assign that to your own variable:

bo = GetBacktesterObject();

The variable “bo” is your own variable, and you can call it whatever you like within the naming rules of AFL. However, to avoid a lot of verbose statements, it’s good to keep it nice and short. Previously you’ve only dealt with variables that are either single numbers, arrays of numbers, or strings. The variable “bo” is none of those, instead being a new type of variable called an object variable. In this case it holds the Backtester object (or really a reference to the Backtester object, but I don’t want to get into the complicated topic of references here). Now that you have the Backtester object in your own variable, you can access its properties and methods.

The syntax for referencing an object’s property is objectName.objectProperty, for example bo.InitialEquity,. That can then be used the same as any other variable (assuming it’s not a read-only property, which InitialEquity is not):

bo.InitialEquity = 10000;
capital = bo.InitialEquity;
gain = (capital - bo.InitialEquity) / bo.InitialEquity * 100;

From this you can see the advantage of keeping object variable names short. If you called the variable “myBacktesterObject”, then for the last example above you’d end up with:

gain = (capital - myBacktesterObject.InitialEquity) / myBacktesterObject.InitialEquity * 100;

===============
Here I’ve had to reduce the font size just to fit it all on a single line.
If a property is read-only, then you cannot perform any operation that would change its value. So, using the Equity property which is read-only:

currentEquity = bo.Equity;	//  This is fine

but:

bo.Equity = 50000;	//  This is an error!

The same syntax is used to access the methods of an object. The method name is preceded by the object name with a decimal point: objectName.objectMethod(). Any parameters are passed to the method in the same manner as to ordinary functions:

objectName.objectMethod(parm1, parm2, parm3).

For example, to call the Backtester object’s AddCustomMetric method and pass the two compulsory parameters Title and Value, a statement like this would be used:

bo.AddCustomMetric("myMetric", 1000);

AmiBroker help indicates that this method returns a value of type “bool”, which means boolean and thus can only take the values True and False. However, it doesn’t detail what this return value means. A good guess would be that it returns True if the custom metric was successfully added and False if for some reason it failed to be added. However, that’s only a guess, but a common reason for returning boolean values. For some of the other methods that return values of type “long”, it’s more difficult to guess what they might contain.
Another example with a return parameter:

sig = bo.GetFirstSignal(i);

Here the variable “sig” is another object variable, but this time of type Signal rather than Backtester. In other words, it holds a Signal object rather than a Backtester object. Unlike the single Backtester object, AmiBroker can have many different Signal objects created at the same time (one for each trading signal). As a Signal object holds the signal data for a particular symbol at a particular bar, the method needs to know the bar number, which would typically be specified using a loop index variable (’i’ above) inside a loop:

for (i = 0; i < BarCount; i++)
{
    . . . .
    sig = bo.GetFirstSignal(i);
    . . . .
}

Once a Signal object has been obtained, its properties and methods can be referenced:

sig.PosScore = 0;	//  Set position score to zero for this bar
if (sig.IsEntry())	//  If this bar's signal is entry (buy/short)
{
    . . . .
}

Note that the property sig.PosScore is a single number, not an array. While the AFL variable PositionScore is an array, the “sig” object only holds data for a single bar, so the property sig.PosScore is the position score value for that bar only, thus a single number.

Also note that AmiBroker help is not very clear on some topics. For example, the Signal object only has a few methods that indicate whether the current bar contains an entry, exit, long, or short signal, or has a scale in or out signal. However, it doesn’t indicate how you combine these to get the exact details. For example, how do you tell the difference between a scale-in and a scale-out? Is scaling in to a long position a combination of IsScale, IsEntry, and IsLong, or perhaps just IsScale and IsLong, or neither of those? In some cases you need to use trial and error and see what actually works (learn how to use the DebugView program with _TRACE statements: see Appendix B). Fortunately for this specific example, the Signal object also has a property called Type that indicates exactly what type the signal is.

Using The Custom Backtester Interface

To use your own custom backtest procedure, you first need to tell AmiBroker that you will be doing so. There are a few ways of doing this:

  1. By setting a path to the file holding the procedure in the Automatic Analysis Settings Portfolio page. This procedure will then be used with all backtests, if the “Enable custom backtest procedure” checkbox is checked.
  2. By specifying these same two settings in your AFL code using the functions SetOption(”UseCustomBacktestProc”, True) and SetCustomBacktestProc(” “). Note that path separators inside strings need to use two backslashes, for example “c:\\AmiBroker\\Formulas\\Custom\\Backtests\\MyProc.afl”. Although why is not important here, it’s because a single backslash is what’s called an escape character, meaning the character(s) after it can have special meaning rather than just being printable characters, so to actually have a printable backslash, you have to put two in a row.

  3. By putting the procedure in the same file as the other AFL code and using the statement SetCustomBacktestProc(”"). This tells AmiBroker that there is a custom backtest procedure but there’s no path for it, because it’s in the current file. This option will be used throughout the rest of this document.

The next thing that’s required in all backtest procedures is to ensure the procedure only runs during the second phase of the backtest. That’s achieved with the following conditional statement:

if (Status("action") == actionPortfolio)
{
    . . . . 
}

And finally, before anything else can be done, a copy of the Backtester object is needed:

bo = GetBacktesterObject();

So all custom backtest procedures, where they’re in the same file as the other AFL code, will have a template like this:

SetCustomBacktestProc("");
if (Status("action") == actionPortfolio)
{
    bo = GetBacktesterObject();
 
	//  Rest of procedure goes here
 
}

If the backtests were using a procedure in the file:

c:\AmiBroker\Formulas\Custom\Backtests\MyBacktest.afl

then the first line above in your system AFL code would be replaced with:

SetOption("UseCustomBacktestProc", True);
SetCustomBacktestProc("c:\\AmiBroker\\Formulas\\Custom\\Backtests\\MyBacktest.afl");

and the rest of the procedure would be in the specified file. Or, if the same values were specified in the Automatic Analysis settings, the two lines above would not be needed in your AFL code at all, and the procedure would be in the specified file.

Custom Backtester Levels

The AmiBroker custom backtester interface provides three levels of user customisation, simply called high-level, mid-level, and low-level. The high-level approach requires the least programming knowledge, and the low-level approach the most. These levels are just a convenient way of grouping together methods that can and need to be called for a customisation to work, and conversely indicate which methods cannot be called in the same customisation because their functionality conflicts. Some methods can be called at all levels, others only at higher levels, and others only at lower levels. AmiBroker help details which levels each method can be used with. Naturally, the higher the level and the simpler the programming, the less flexibility that’s available.

This document will not detail every single method and property available, so the rest of this document should be read in conjunction with the AmiBroker help sections “Advanced portfolio backtester interface” and “Adding custom backtest metrics”.

High-Level Interface

The high-level interface doesn’t allow any customising of the backtest procedure itself. It simply allows custom metrics to be defined for the backtester results display, and trade statistics and metrics to be calculated and examined. A single method call runs the whole backtest in one hit, the same as when the custom backtester interface isn’t used at all.

AmiBroker help has an example of using the high level interface to add a custom metric. See the section called “Adding custom backtest metrics”. In essence, the steps are:

  1. Start with the custom backtest template above
  2. Run the backtest
  3. Get the performance statistics or trade details
  4. Calculate your new metric
  5. Add your new metric to the results display

That would look something like this:

SetCustomBacktestProc("");
if (Status("action") == actionPortfolio)
{
    bo = GetBacktesterObject();	//  Get backtester object
    bo.Backtest();	//  Run backtests
    stats = bo.GetPerformanceStats(0);	//  Get Stats object for all trades
    myMetric = <calculation using stats>;	//  Calculate new metric
    bo.AddCustomMetric("MyMetric", myMetric);	//  Add metric to display
}

As well as just using the built-in statistics and metrics, obtained from the Stats object after the backtest has been run, it’s also possible to calculate your metric by examining all the trades using the Trade object. As some positions may still be open at the end of the backtest, you may need to iterate through both the closed trade and open position lists:

for (trade = bo.GetFirstTrade(); trade; trade = bo.GetNextTrade())
{
    . . . .
}
for (trade = bo.GetFirstOpenPos(); trade; trade = bo.GetNextOpenPos())
{
    . . . .
}

In this example, “trade” is an object variable of type Trade, meaning it holds a Trade object. As with the Signal object, AmiBroker can have many Trade objects created at the same time, one for each closed or open trade. The first for loop iterates through the closed trade list, and the second through the open position trade list. The continuation condition “trade” theoretically means while the trade object is not zero, but in fact “trade” will be Null when the end of the list is reached. However, any conditional involving a null value is always false, so this will still work. The five Backtester object methods GetFirstTrade, GetNextTrade, GetFirstOpenPos, GetNextOpenPos, and FindOpenPos all return Null when the end of the list is reached or if no trade or open position is found.

The for loops are a little different to normal for loops in that they don’t have a standard loop index variable like ‘i’ that gets incremented at the end of each pass. Instead they call a Backtester object method to get the initial value (the first Trade object) and then another member to get the next value (the next Trade object). So the for loop conditions here are just saying start from the first Trade object, at the end of each pass get the next Trade object, and keep doing that until there are no more Trade objects (ie. “trade” is Null). The loops are iterating through the list of trades, not the bars on a chart. Each Trade object holds the details for a single trade.

Putting that code inside the custom backtest template looks like this:

SetCustomBacktestProc("");
if (Status("action") == actionPortfolio)
{
    bo = GetBacktesterObject();	//  Get backtester object
    bo.Backtest();	//  Run backtests
    for (trade = bo.GetFirstTrade(); trade; trade = bo.GetNextTrade())
    {
        . . . .	//  Use Trade object here
    }
    for (trade = bo.GetFirstOpenPos(); trade; trade = bo.GetNextOpenPos())
    {
        . . . .	//  Use Trade object here
    }
    myMetric = <some result from Trade object calculations>;
    bo.AddCustomMetric("MyMetric", myMetric);	//  Add metric to display
}

As an example, say we want to calculate the average number of calendar days that winning trades were held for (there’s already a built-in Stats object value for number of bars, but we want number of calendar days). For that we’ll need a function that can calculate the number o