AmiBroker's OLE Automation Object Model

Important note about OLE automation:

OLE automation interface is provided to control AmiBroker from the OUTSIDE process (such as windows scripting host). While it is possible to access Broker.Application and underlying objects from AFL formulas you should be very careful NOT to touch any user interface objects (Documents, Document, Windows, Window , Analysis object) from AFL formula because doing so, you will be likely "Sawing Off the Branch You're Sitting On". Especially things like switching chart tabs from currently running chart formula are totally forbidden. Changing user interface objects via OLE from AFL that is currently running within those user interface parts is recipe for disaster. You have been warned.

AmiBroker object model hierarchy. V5.50

Index of objects


(1) - Analysis object is obsolete as of 5.50. It is left here for backward compatibility and accesses Old Automatic Analysis window only
(2) - AnalysisDoc object and AnalysisDocs collection are new objects introduced in v5.50 and allow to control New Analysis window

 

ADQuotation

Properties:

Description:

ADQuotation class keeps one bar of advance/decline information

ADQuotations

Methods:

Properties:

Description:

ADQuotations is a collection of ADQuotation objects

Analysis

This object is obsolete. It is provided only to maintain compatibility with old code. Analysis object always accesses OLD Automatic Analysis.

Properties:

Methods:

Properties:

Description:

Analysis object provides programmatic control of automatic analysis window

Notes:

Analysis.Backtest( Type = 2 ); - runs backtest
Type parameter can be one of the following values:
0 : portfolio backtest/optimize
1 : individual backtest/optimize
2 : old backtest/optimize

IT IS IMPORTANT TO NOTE THAT FOR BACKWARD COMPATIBILITY REASONS THE DEFAULT BACKTESTER MODE
IS "OLD" BACKTEST. THEREFORE YOU MUST SPECIFY TYPE = 0 IF YOU WANT TO GET PORTFOLIO BACKTEST.

Analysis.Optimize(Type = 2 ); - runs optimization
Type parameter can be one of the following values:
0 : portfolio backtest/optimize
1 : individual backtest/optimize
2 : old backtest/optimize
3 : walk-forward test (AmiBroker version 5.11.0 or higher)

Analysis.Report( FileName: String ) - saves report to the file or displays it if FileName = ""

Analysis.ApplyTo - defines apply to mode: 0 - all stocks, 1 - current stock, 2 - use filter
Analysis.RangeMode - defines range mode: 0 - all quotes, 1 - n last quotes, 2 - n last days, 3 - from-to date
Analysis.RangeN - defines N (number of bars/days to backtest)
Analysis.RangeFromDate - defines "From" date
Analysis.RangeToDate - defines "To" date
Analysis.Filter( nType: short, Category : String ) - sets/retrieves filter setting
nType argument defines type of filter 0 - include, 1 - exclude
Category argument defines filter category:
"index", "favorite", "market", "group", "sector", "index", "watchlist"

AnalysisDoc

AnalysisDoc is a new object introduced in version 5.50. It allows to access New Analysis project documents (apx extension) and perform multithreaded scans/explorations/backtests/optimizations in New Analysis window in asynchronous way. Asynchronous means that Run() method only starts the process and returns immediatelly. To wait for completion you must check IsBusy flag periodically (such as every second) in your own code.

Properties:

Methods:

Description:

AnalysisDoc object provides programmatic control of New Analysis document/window.

IsBusy property allows to check whenever Analysis window is busy doing analysis. You must check this flag periodically if you want to wait for completion. Take care NOT to call this too often as it will decrease performance. For best results check it every one second. Also you need to check this flag if you are not sure whenever Analysis window is busy before trying to call Export() or Run(), otherwise these calls would fail if analysis is in progress.

Close( ) method closes Analysis document/window. If there is any operation in progress it will be terminated. To prevent premature termination, check IsBusy property.

Export( pszFileName, whatToExport) method allows to export analysis result list to either .HTML or .CSV file. Returns 1 on success (successfull export) or 0 on failure (for example if analysis window is busy). WhatToExport decides what data should be exported: whatToExport = 0 - exports result list (the default behavior when this parameter is not provided), whatToExport = 1 - exports walkforward tab.

Run( Action ) method allows to run asynchronously scan/explorations/backtest/optimizations.
Action parameter can be one of the following values:
0 : Scan
1 : Exploration
2 : Portfolio Backtest
3 : Individual Backtest
4 : Portfolio Optimization
5 : Individual Optimization (supported starting from v5.69)
6 : Walk Forward Test

It is important to understand that Run method just starts the process and returns immediatelly. It does NOT wait for completion.
To wait for completion you need to query IsBusy flag periodically (such as every one second).

Run() returns 1 on success (successfully starting process) or 0 on failure (for example if analysis window is busy)

The procedure to run automated backtest involves opening previously saved Analysis project (it includes all settings that are necessary to perform any action), call Run() and wait for completion.

Since currently you can have multiple analysis projects running, there is an AnalysisDocs collection that represents all open Analysis documents and allow you to open previously saved files (that contain formula, settings and everything needed to run).

New AnalysisDoc object does not allow you to read/write settings for the purpose - you are not supposed to manipulate UI while new Analysis window is running. Correct way of using New Analysis window is to open existing project file and run. If you want to modify the settings, you should write/modify existing project file. The analysis project file (.apx extension) is human-readable self-explanatory XML-format file that can be written/edited/modified from any language / any text editor.

The following JScript example
a) opens analysis project from C:\Analysis1.apx file
b) starts backtest (asynchronously)
c) waits for completion
d) exports results
e) closes analysis document

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

try
{
    NewA = AB.AnalysisDocs.Open(
"C:\\analysis1.apx" ); // opens previously saved analysis project file
    // NewA represents the instance of New Analysis document/window

    
if ( NewA )
    {
         NewA.Run(
2 ); // start backtest asynchronously

        
while ( NewA.IsBusy ) WScript.Sleep( 500 ); // check IsBusy every 0.5 second

         NewA.Export(
"test.html" ); // export result list to HTML file

         WScript.echo(
"Completed" );

         NewA.Close();
// close new Analysis
     }
}
catch ( err )
{
     WScript.echo(
"Exception: " + err.message ); // display error that may occur
}

Abort( ) method will abort any running Analysis scan/exploration/backtest

AnalysisDocs

AnalysisDocs is a new object introduced in version 5.50. It is a collection of AnalysisDoc objects. Allows to Add new Analysis, Open existing analysis project, and iterate thru analysis objects.

Methods:

Properties:

Description:

AnalysisDocs is a collection of AnalysisDoc objects.

Add method creates new Analysis document/window. The method returns AnalysisDoc object.

Close method closes all open Analysis documents/windows. If any analysis project is running it will be terminated immediatelly

Open method allows to open existing Analysis project file (.apx). The method returns AnalysisDoc object.

Item property allows to access Index-th element of collection. The property returns AnalysisDoc object.

Count property gives number of open analysis documents.

Both Application and Parent properties point to Broker.Application object

For example usage, see AnalysisDoc object description.

Application

Methods:

Properties:

Description:

Application object is main OLE automation object for AmiBroker. You have to create it prior to accesing any other objects. To create Application object use the following code:

JScript:

AB = new ActiveXObject("Broker.Application");

VB/VBScript:

AB = CreateObject("Broker.Application")

AFL:

AB = CreateObject("Broker.Application");

Window

Methods:

Properties:

Description:

Window object provides programmatic control over charting window.

Windows

Methods:

Properties:

Description:

Windows is a collection of Window objects.

Commentary

Methods:

Description:

Commentary object gives programmatic control over guru commentary window.

Document

Methods:

Properties:

Description:

Document object represents active document (of 'chart' type). In document-view architecture each document can have multiple windows (views) connected. Name property defines currently selected symbol for the document.

Name is a ticker symbol, Interval is a chart interval in seconds.

Documents

Methods:

Properties:

Description:

Documents is a collection of document objects.

Market

Properties:

Description:

Market represents market category and its related data (i.e. per-market advance/decline information)

Markets

Properties:

Description:

Markets is a collection of Market objects

Quotation

Properties:

Description:

Quotation class represents one bar of price data

Quotations

Methods:

Properties:

Description:

Quotations is a collection of Quotation objects. It represents all quotations available for given symbol. Quotations collection is available as a property of Stock object.

Stock

Properties:

Description:

Stock class represents single symbol data. For historical reasons the name of the object is Stock, but it can hold any kind of instrument (including futures, forex, etc).

Stocks

Methods:

Properties:

Description:

Stocks is a collection of Stock objects. It is available as a property of Application object.

Notes:

Stock.WatchListBits (long) - each bit 0..31 represents assignment to one of 32 watch lists to add a stock to nth watch list write (JScript example):
Stock.WatchListBits |= 1 << nth;

Stock.WatchListBits2 (long) - each bit 0..31 represents assignment to one of watch lists numbered from 32..63 to add a stock to nth watch list write (JScript example):
Stock.WatchListBits2 |= 1 << ( nth - 32 );

Stock.DataSource ( 0 - default, 1 - local only )
Stock.DataLocalMode ( 0 - default, 1 - store locally, 2 - don't store locally)

Practical Examples:

Example 1: Running simple backtest

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

try
{
    NewA = AB.AnalysisDocs.Open(
"C:\\analysis1.apx" ); // opens previously saved analysis project file
    // NewA represents the instance of New Analysis document/window

    
if ( NewA )
    {
         NewA.Run(
2 ); // start backtest asynchronously

        
while ( NewA.IsBusy ) WScript.Sleep( 500 ); // check IsBusy every 0.5 second

         NewA.Export(
"test.html" ); // export result list to HTML file

         WScript.echo(
"Completed" );

         NewA.Close();
// close new Analysis
     }
}
catch ( err )
{
     WScript.echo(
"Exception: " + err.message ); // display error that may occur
}



Example 2: Execute commentary

AB = new ActiveXObject("Broker.Application");
AB.Commentary.LoadFormula(
"C:\\Program Files\\AmiBroker\\AFL\\MACD_c.afl");
AB.Commentary.Apply();
AB.Commentary.Save(
"Test.txt");
AB.Commentary.SaveFormula(
"MACDTest.afl");
//AB.Commentary.Close();