Thursday, December 5, 2019

MQL5 -WebRequest

WebRequest

The function sends an HTTP request to a specified server. The function has two versions:
1. Sending simple requests of type "key=value" using the header Content-Type: application/x-www-form-urlencoded.
int  WebRequest(
   const string      method,           // HTTP method 
   const string      url,              // URL
   const string      cookie,           // cookie
   const string      referer,          // referer
   int               timeout,          // timeout
   const char        &data[],          // the array of the HTTP message body
   int               data_size,        // data[] array size in bytes
   char              &result[],        // an array containing server response data
   string            &result_headers   // headers of server response
   );
2. Sending a request of any type specifying the custom set of headers for a more flexible interaction with various Web services.
int  WebRequest(
   const string      method,           // HTTP method
   const string      url,              // URL
   const string      headers,          // headers 
   int               timeout,          // timeout
   const char        &data[],          // the array of the HTTP message body
   char              &result[],        // an array containing server response data
   string            &result_headers   // headers of server response
   );
Parameters
method
[in]  HTTP method.
url
[in]  URL.
headers
[in]  Request headers of type "key: value", separated by a line break "\r\n".
cookie
[in]  Cookie value.
referer
[in]  Value of the Referer header of the HTTP request.
timeout
[in]  Timeout in milliseconds.
data[]
[in]  Data array of the HTTP message body.
data_size
[in]  Size of the data[] array.
result[]
[out]  An array containing server response data.
result_headers
[out] Server response headers.
Return Value
HTTP server response code or -1 for an error.
Note
To use the WebRequest() function, add the addresses of the required servers in the list of allowed URLs in the "Expert Advisors" tab of the "Options" window. Server port is automatically selected on the basis of the specified protocol - 80 for "http://" and 443 for "https://".
The WebRequest() function is synchronous, which means its breaks the program execution and waits for the response from the requested server. Since the delays in receiving a response can be large, the function is not available for calls from indicators, because indicators run in a common thread shared by all indicators and charts on one symbol. Indicator performance delay on one of the charts of a symbol may stop updating of all charts of the same symbol.
The function can be called only from Expert Advisors and scripts, as they run in their own execution threads. If you try to call the function from an indicator, GetLastError() will return error 4014 – "Function is not allowed for call".
WebRequest() cannot be executed in the Strategy Tester.
Example:
void OnStart()
  {
   string cookie=NULL,headers;
   char   post[],result[];
   string url="https://finance.yahoo.com";
//--- To enable access to the server, you should add URL "https://finance.yahoo.com"
//--- to the list of allowed URLs (Main Menu->Tools->Options, tab "Expert Advisors"):
//--- Resetting the last error code
   ResetLastError();
//--- Downloading a html page from Yahoo Finance
   int res=WebRequest("GET",url,cookie,NULL,500,post,0,result,headers);
   if(res==-1)
     {
      Print("Error in WebRequest. Error code  =",GetLastError());
      //--- Perhaps the URL is not listed, display a message about the necessity to add the address
      MessageBox("Add the address '"+url+"' to the list of allowed URLs on tab 'Expert Advisors'","Error",MB_ICONINFORMATION);
     }
   else
     {
      if(res==200)
        {
         //--- Successful download
         PrintFormat("The file has been successfully downloaded, File size %d byte.",ArraySize(result));
         //PrintFormat("Server headers: %s",headers);
         //--- Saving the data to a file
         int filehandle=FileOpen("url.htm",FILE_WRITE|FILE_BIN);
         if(filehandle!=INVALID_HANDLE)
           {
            //--- Saving the contents of the result[] array to a file
            FileWriteArray(filehandle,result,0,ArraySize(result));
            //--- Closing the file
            FileClose(filehandle);
           }
         else
            Print("Error in FileOpen. Error code =",GetLastError());
        }
      else
         PrintFormat("Downloading '%s' failed, error code %d",url,res);
     }
  }

How to download and update quotes automatically in amibroker

IN THIS ISSUE
1 Welcome
Tip of the week: How to download and update quotes automatically
1 Welcome
Welcome to the 2nd issue of AmiBroker Tips newsletter in the 2001. In this issue I will describe my new little utility called "URLGet" and its use in automatic download and update of AmiBroker's quotation database.
Just a reminder: if you have any comments/suggestions or article ideas, please don't hesitate to drop a line to newsletter@amibroker.com
Tip of the week: How to download and update quotes automatically
In my previous articles on scripting (see 1/2000 and 4/2000 issues of the newsletter) I often used FileSystemObject to access local files. FileSystemObject is provided by Microsoft as a part of Windows Scripting Host platform. Unfortunatelly you can not access remote files using this object - therefore you can not use it to dowload the quotes from FTP or HTTP (Web) server.
In order to fix this situation I wrote a little command line program called URLGet - a simple utility that allows you to download any text file from HTTP (Web) or anonymous FTP server and store it to the local file. The program accepts two arguments: remote file URL and local file name (colours added only for clarity):
URLGet <URL_to_remote_file>  <local file name>
For example, to download free Australian Stock Exchange (ASX) data from www.australian-stockmarket.com site you need to type following command:
URLGet http://www.australian-stockmarket.com/updates/20001201.prn  c:\mydata\20001201.PRN
This will store the ASX data file from December 1st, 2000 to the local file 20001201.PRN located in C:\MyData directory (this file could be then imported to AmiBroker using "PRN with Ticker" importer). The destination directory must exist, of course, otherwise the download will fail. If download was successful URLGet program return value is 0, otherwise 1. One important note must be made: due to the way HTTP servers work if remote file does not exist you will often get "Error 404" file downloaded instead of empty one or just an error code. Some sites go even further, replacing standard "Error 404" page with something completely different. For example www.australian-stockmarket.com site sends you back home page if requested document was not found. This could be very annoying when you want to write a script with some error handling.
So we are now able to download the quotes using URLGet program... but how to call it from the script? Well, it is very simple:
/* first, create Shell object that allows us to run external programs */
WshShell = new ActiveXObject( "WScript.Shell" );

/* this handy function takes just URL and local file name and calls URLGet program to do the work */
function Download( URL, filename )
{

if( WshShell.Run( "URLGet " + URL + " " + filename, 0, true ) == 0 ) return true;
WScript.echo("Download of " + URL + " failed." );
return false; }

OK, so we know how to download the file from the web and how to store it locally in predefined folder. Could we then tell AmiBroker to import that data without manual intervention? Of course we can, and it is again pretty simple:
/* Create AmiBroker application object */
AmiBroker = new ActiveXObject( "Broker.Application" );

function Import( filename )
{

/* import the data using appropriate format definition file - in our case (PRN files with Ticker) this is prnn.format file */
AmiBroker.Import( 0, filename, "prnn.format" );
/* refresh ticker list and windows */
AmiBroker.RefreshAll();
}

These are two the most important building blocks of our automatic downloader/updater script. I guess you will find them useful also for your own scripts. Now I am going to present a complete solution for automatic download of quotes from free ASX data source (www.australian-stockmarket.com site) and another one for free WSE (Warsaw Stock Exchange) quotes provided by bossa.pl . Both sites use PRN format with Ticker so most parts of the script will be common.
Our real-world example will take care about following additional issues:
  • Detecting if correct database is loaded into AmiBroker, preventing from adding foreign stocks
  • Checking for last quotation date stored in AmiBroker database and calculating the number of days to download
  • Downloading all needed quotes (from last one stored to today)
  • Additional error handling
The first issue is important because you can work with different databases - for example I work with NYSE, Nasdaq and WSE databases - and don't want to import WSE stocks into NYSE database. To avoid such cases the script would check for one ticker name that identifies the database. In case of ASX this will be "XAO" - ASX All Ordinaries index, in case of WSE this will be "WIG20" index. If this ticker could not be found - the script should not attempt to update currently loaded database.
The second issue is that we may forget to update our database everyday, so we want the script to check the last date stored in AmiBroker database and to download all missing quotes from that date until today.
As you can guess the whole script is a little bit complicated so I won't include complete listing here but will focus on just the user definable stuff, so let's take a look at constants that could be changed by the user:
/* The ticker to check */
ChkTicker = "XAO";

/* The folder where the files will be downloaded */
DestDir = "C:\\ASX\\";

/* The name and the path to downloader program */
DownloaderPrg = "URLGet.exe";

/* Force download - if true causes downloading data file */
/* even if it exists on the local drive */

ForceDownloadFlag = false;

/* URL from where data are downloaded */
/* Note that australian-stockmarket site changed directory for 2001 quotes */

URLPrefix = "http://www.australian-stockmarket.com/updates/";
URLPrefix2001 = "http://www.australian-stockmarket.com/updates2001/";

/* extension of file name, YYYYMMDD will be prepended */
FileExt = ".prn";

/* max number of days to download when history is empty */
nMaxHistoryLen = 365;

One note about URLPrefix2001. This constant was added because guys at www.australian-stockmarket.com site decided to put 2001 quotes in a new directory called updates2001. The old quotes are available from updates folder. So the script checks the year and switches the URLs.
The script uses C:\ASX folder by default for downloaded data. If you don't want to modify the script you should create such folder and copy the URLGet program there. Other data and program locations could be defined by changing DestDir and DownloaderPrg constants. ForceDownloadFlag could be changed to true if you want to re-download the files that were downloaded wrong. This may happen quite often with www.australian-stockmarket.com site because of unavailable data and other delays.
As for Warsaw Stock Exchange data, a service called bossa.pl does a great job in providing free accurate data available everyday at 7:00PM Warsaw time. In order to enable the script to work with their service following changes are needed:
/* The ticker to check */
ChkTicker = "WIG20";

/* The folder where the files will be downloaded */
DestDir = "C:\\WSE\\";

/* The name and the path to downloader program */
DownloaderPrg = "URLGet.exe";

/* URL from where data are downloaded */URLPrefix = "http://bossa.pl/pub/metastock/";
URLPrefix2001 = "http://bossa.pl/pub/metastock/";

Now I suggest you to take a look at complete scripts available here: ASX downloader script and WSE downloader script. You will need also URLGet program available here.
.... and that's all for this week - hope you enjoyed reading

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.


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:

  • Date As Date
  • AdvIssues As Long
  • AdvVolume As Single
  • DecIssues As Long
  • DecVolume As Single
  • UncIssues As Long
  • UncVolume As Single

Description:

ADQuotation class keeps one bar of advance/decline information

ADQuotations

Methods:

  • Function Add(ByVal Date As Variant) As Object
  • Function Remove(ByVal Date As Variant) As Boolean

Properties:

  • Item(ByVal Date As Variant) As Object [r/o] [default]
  • Count As Long

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:

  • Property Filter(ByVal nType As Integer, ByVal pszCategory As String) As Long [r/w]

Methods:

  • Sub Backtest([ByVal Type As Variant])
  • Sub ClearFilters()
  • Sub Edit([ByVal bForceReload As Variant])
  • Sub Explore()
  • Function Export(ByVal pszFileName As String) As Boolean
  • Function LoadFormula(ByVal FileName As String) As Boolean
  • Function LoadSettings(ByVal pszFileName As String) As Boolean
  • Sub MoveWindow(ByVal Left As Long, ByVal Top As Long, ByVal Width As Long, ByVal Height As Long)
  • Sub Optimize([ByVal Type As Variant])
  • Function Report(ByVal pszFileName As String) As Boolean
  • Function SaveFormula(ByVal pszFileName As String) As Boolean
  • Function SaveSettings(ByVal pszFileName As String) As Boolean
  • Sub Scan()
  • Sub ShowWindow(ByVal nShowCmd As Long)
  • Sub SortByColumn(ByVal iColumn As Long, ByVal bAscending As Integer, ByVal bMultiMode As Integer)

Properties:

  • RangeMode As Long
  • RangeN As Long
  • RangeFromDate As Date
  • RangeToDate As Date
  • ApplyTo As Long

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:

  • Property IsBusy As Boolean [r]

Methods:

  • Sub Close()
  • Function Export(ByVal pszFileName As String, [ByVal WhatToExport As Variant] ) As Long
  • Function Run(ByVal Action As Long) As Long
  • Sub Abort() (new in 6.20)

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:

  • Function Add() As Object
  • Sub Close()
  • Function Open(ByVal FileName As String) As Object

Properties:

  • Item(ByVal Index As Long) As Object [r/o] [default]
  • Count As Long
  • Application As Object
  • Parent As Object

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:

  • Function Import(ByVal Type As Integer, ByVal FileName As String, [ByVal DefFileName As Variant]) As Long
  • Function LoadDatabase(ByVal Path As String) As Boolean
  • Function LoadLayout(ByVal pszFileName As String) As Boolean
  • Sub LoadWatchlists()
  • Function Log(ByVal Action As Integer) As Long
  • Sub Quit()
  • Sub RefreshAll()
  • Sub SaveDatabase()
  • Function SaveLayout(ByVal pszFileName As String) As Boolean

Properties:

  • ActiveDocument As Object
  • Stocks As Object
  • Version As String
  • Documents As Object
  • Markets As Object
  • DatabasePath As String
  • Analysis As Object
  • Commentary As Object
  • ActiveWindow As Object
  • Visible As Integer

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:

  • Sub Activate()
  • Sub Close()
  • Function ExportImage(ByVal FileName As String, [ByVal Width As Variant], [ByVal Height As Variant], [ByVal Depth As Variant]) As Boolean
  • Function LoadTemplate(ByVal lpszFileName As String) As Boolean
  • Function SaveTemplate(ByVal lpszFileName As String) As Boolean
  • Function ZoomToRange(ByVal From As Variant, ByVal To As Variant) As Boolean

Properties:

  • SelectedTab As Long
  • Document As Object

Description:

Window object provides programmatic control over charting window.

Windows

Methods:

  • Function Add() As Object

Properties:

  • Item(ByVal Index As Long) As Object [r/o] [default]
  • Count As Long

Description:

Windows is a collection of Window objects.

Commentary

Methods:

  • Sub Apply()
  • Sub Close()
  • Function LoadFormula(ByVal pszFileName As String) As Boolean
  • Function Save(ByVal pszFileName As String) As Boolean
  • Function SaveFormula(ByVal pszFileName As String) As Boolean

Description:

Commentary object gives programmatic control over guru commentary window.

Document

Methods:

  • Sub Activate()
  • Sub Close()
  • Sub ShowMessage(ByVal Text As String)

Properties:

  • Application As Object
  • Parent As Object
  • Name As String
  • ActiveWindow As Object
  • Windows As Object
  • Interval As Integer

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:

  • Function Add() As Object
  • Sub Close()
  • Function Open(ByVal Ticker As String) As Object

Properties:

  • Item(ByVal Index As Long) As Object [r/o] [default]
  • Count As Long
  • Application As Object
  • Parent As Object

Description:

Documents is a collection of document objects.

Market

Properties:

  • Name As String
  • ADQuotations As Object

Description:

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

Markets

Properties:

  • Item(ByVal Index As Integer) As Object [r/o] [default]
  • Count As Integer

Description:

Markets is a collection of Market objects

Quotation

Properties:

  • Date As Date
  • Close As Single
  • Open As Single
  • High As Single
  • Low As Single
  • Volume As Single
  • OpenInt As Single

Description:

Quotation class represents one bar of price data

Quotations

Methods:

  • Function Add(ByVal Date As Date) As Object
  • Function Remove(ByVal Item As Variant) As Boolean
  • Function Retrieve(ByVal Count As Long, ByRef Date As Variant, ByRef Open As Variant, ByRef High As Variant, ByRef Low As Variant, ByRef Close As Variant, ByRef Volume As Variant, ByRef OpenInt As Variant) As Long

Properties:

  • Item(ByVal Item As Variant) As Object [r/o] [default]
  • Count As Long

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:

  • Ticker As String
  • Quotations As Object
  • FullName As String
  • Index As Boolean
  • Favourite As Boolean
  • Continuous As Boolean
  • MarketID As Long
  • GroupID As Long
  • Beta As Single
  • SharesOut As Single
  • BookValuePerShare As Single
  • SharesFloat As Single
  • Address As String
  • WebID As String
  • Alias As String
  • IsDirty As Boolean
  • IndustryID As Long
  • WatchListBits As Long
  • DataSource As Long
  • DataLocalMode As Long
  • PointValue As Single
  • MarginDeposit As Single
  • RoundLotSize As Single
  • TickSize As Single
  • WatchListBits2 As Long
  • Currency As String
  • LastSplitFactor As String
  • LastSplitDate As Date
  • DividendPerShare As Single
  • DividendPayDate As Date
  • ExDividendDate As Date
  • PEGRatio As Single
  • ProfitMargin As Single
  • OperatingMargin As Single
  • OneYearTargetPrice As Single
  • ReturnOnAssets As Single
  • ReturnOnEquity As Single
  • QtrlyRevenueGrowth As Single
  • GrossProfitPerShare As Single
  • SalesPerShare As Single
  • EBITDAPerShare As Single
  • QtrlyEarningsGrowth As Single
  • InsiderHoldPercent As Single
  • InstitutionHoldPercent As Single
  • SharesShort As Single
  • SharesShortPrevMonth As Single
  • ForwardDividendPerShare As Single
  • ForwardEPS As Single
  • EPS As Single
  • EPSEstCurrentYear As Single
  • EPSEstNextYear As Single
  • EPSEstNextQuarter As Single
  • OperatingCashFlow As Single
  • LeveredFreeCashFlow As Single

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:

  • Function Add(ByVal Ticker As String) As Object
  • Function GetTickerList(ByVal nType As Long) As String
  • Function Remove(ByVal Item As Variant) As Boolean

Properties:

  • Item(ByVal Item As Variant) As Object [r/o] [default]
  • Count As Long

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();
 
 Source: https://www.amibroker.com/guide/objects.html#AWindow

Install and use xorg-server on macOS via Homebrew

  The instructions to install and use xorg-server on macOS via Homebrew: Install Homebrew (if you haven't already): /bin/bash -c ...