Top Banner
AmiBroker 6.30 User's Guide Copyright (C)1995-2017 AmiBroker.com. All rights reserved.
1478

AmiBroker 6.30 User's Guide · 2019-11-19 · Assignment organizer window ... AmiBroker 6.30 User's Guide v. Table of Contents AmiBroker Formula Language (AFL) ... DayOfWeek - day

Jun 11, 2020

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • AmiBroker 6.30User's Guide

    Copyright (C)1995-2017 AmiBroker.com.All rights reserved.

  • Table of ContentsCopyright ............................................................................................................................................................1

    Contents.................................................................................................................................................2

    Introduction ........................................................................................................................................................3About AmiBroker Editions.......................................................................................................................4Quick Tour..............................................................................................................................................6Getting started......................................................................................................................................10

    Hardware requirements..................................................................................................................10Supported operating systems........................................................................................................10Installation and running..................................................................................................................10Getting help....................................................................................................................................11AmiBroker 32-bit vs 64-bit Compatibility Chart..............................................................................13

    What's new in the latest version?.........................................................................................................15 Detailed Change Log....................................................................................................................26

    Tutorial .............................................................................................................................................................41Basic operations...................................................................................................................................43

    Adding a new symbol.....................................................................................................................43Removing a symbol........................................................................................................................43Splitting a stock..............................................................................................................................43Deleting quotation..........................................................................................................................43Adding/removing symbol from favourites.......................................................................................43Merging quotations of two symbols................................................................................................44

    Beginners' charting guide.....................................................................................................................45How to use drag-and-drop charting interface.......................................................................................51

    Special functions: SECTION_BEGIN, _SECTION_END, _SECTION_NAME, _DEFAULT_NAME, _PARAM_VALUES explained (for advanced users only)......................55

    Chart themes........................................................................................................................................60User interface customization................................................................................................................67Working with chart sheets and window layouts....................................................................................76Using layers..........................................................................................................................................82Using Web Research window...............................................................................................................84

    OPEN NEW WEB RESEARCH WINDOW.....................................................................................84Using account manager........................................................................................................................89

    CREATE A NEW ACCOUNT.........................................................................................................89Using fundamental data........................................................................................................................94

    INFORMATION WINDOW.............................................................................................................94Using New Analysis window.................................................................................................................99

    Introduction....................................................................................................................................99User interface.................................................................................................................................99

    Using Batch window...........................................................................................................................105Introduction..................................................................................................................................105User interface...............................................................................................................................105Basic operations...........................................................................................................................106Miscellaneous commands............................................................................................................107Scheduling...................................................................................................................................108

    How to get quotes from various markets............................................................................................110How to set up AmiBroker with eSignal feed (RT version only)...........................................................114

    Requirements...............................................................................................................................114

    AmiBroker 6.30 User's Guide

    i

  • Table of ContentsTutorial

    How to set up AmiBroker with myTrack feed (RT version only).........................................................116Requirements...............................................................................................................................116

    How to use AmiBroker with external data source (Quote Tracker).....................................................118One-time setup.............................................................................................................................118

    How to set up AmiBroker with IQFeed feed (RT version only)...........................................................122How to use AmiBroker with Interactive Brokers TWS.........................................................................124How to use AmiBroker with external DDE data source......................................................................131

    WHAT IS DDE..............................................................................................................................131How to work with Real-Time data plugins...........................................................................................137

    One-time setup.............................................................................................................................137How to use AmiBroker with external data source (Quotes Plus, TC2000/TCNet/TC2005, FastTrack, Metastock).......................................................................................................................143

    One-time setup.............................................................................................................................143How to update US quotes automatically using AmiQuote..................................................................146How to download quotes manually using AmiQuote..........................................................................149

    Introduction..................................................................................................................................149Metastock importer window..........................................................................................................153

    Understanding AmiBroker database concepts...................................................................................155Background..................................................................................................................................155AmiBroker database structure......................................................................................................155What about the external data?.....................................................................................................155

    Understanding categories...................................................................................................................158Working with sectors and industries.............................................................................................159

    Working with watch lists......................................................................................................................169Understanding how AFL works...........................................................................................................176Creating your own indicators..............................................................................................................181Using graph styles, colors, titles and parameters in Indicators...........................................................185How to create your own exploration...................................................................................................197How to write your own chart commentary...........................................................................................203Using studies in AFL formulas............................................................................................................207Back-testing your trading ideas..........................................................................................................209Portfolio-level backtesting...................................................................................................................221Reading backtest report......................................................................................................................233How to optimize trading system..........................................................................................................236Walk-forward testing...........................................................................................................................245Back-testing systems for futures contracts.........................................................................................249Monte Carlo Simulation of your trading system..................................................................................252Pyramiding (scaling in/out) and mutliple currencies in the portfolio backtester..................................261

    Pyramiding / Scaling....................................................................................................................261Using formula-based alerts.................................................................................................................265Using interpretation window................................................................................................................270Multiple Time Frame support in AFL...................................................................................................271Efficient use of multithreading.............................................................................................................277Ranking functionality...........................................................................................................................284Using AFL Code snippets...................................................................................................................289How to use AFL visual debugger........................................................................................................294

    ....................................................................................................................................................299Using on-chart GUI controls...............................................................................................................300

    AmiBroker 6.30 User's Guide

    ii

  • Table of ContentsTutorial

    Video Tutorials (on-line)......................................................................................................................307

    AmiBroker Reference Guide.........................................................................................................................308Windows.............................................................................................................................................309

    Chart window pane......................................................................................................................311Parameters window......................................................................................................................312Data window.................................................................................................................................314Study drawing tools......................................................................................................................315Line study properties window.......................................................................................................324Text box properties window.........................................................................................................326Formula Editor..............................................................................................................................328

    Code Snippets window.......................................................................................................................339Risk-Yield Map window................................................................................................................342Place Order dialog.......................................................................................................................343Database Settings........................................................................................................................345Intraday Settings window.............................................................................................................346Preferences window.....................................................................................................................349Customize tools window...............................................................................................................361Symbol tree window.....................................................................................................................363Information window......................................................................................................................364Notepad window...........................................................................................................................367Quote Editor window....................................................................................................................368Symbol Finder window (F3).........................................................................................................369

    Using Web Research window.............................................................................................................370OPEN NEW WEB RESEARCH WINDOW...................................................................................370Assignment organizer window.....................................................................................................375Composite recalculation window..................................................................................................376Categories window.......................................................................................................................377ASCII Import Wizard....................................................................................................................378Metastock importer window..........................................................................................................382

    Using account manager......................................................................................................................384CREATE A NEW ACCOUNT.......................................................................................................384Real-time quote window...............................................................................................................389Easy alerts window......................................................................................................................392Bar Replay window......................................................................................................................396Formula Editor..............................................................................................................................398Quick review window....................................................................................................................409Automatic analysis window..........................................................................................................410Filter settings window...................................................................................................................412System test settings window........................................................................................................413System test report window...........................................................................................................420Commission window....................................................................................................................425Commentary window....................................................................................................................426Plugins window............................................................................................................................427Indicator Maintenance Wizard......................................................................................................428Log window..................................................................................................................................430

    Menus.................................................................................................................................................432File menu.....................................................................................................................................433

    AmiBroker 6.30 User's Guide

    iii

  • Table of ContentsAmiBroker Reference Guide

    Edit menu.....................................................................................................................................436View menu...................................................................................................................................437Insert menu..................................................................................................................................440Format menu................................................................................................................................444Symbol menu...............................................................................................................................445Analysis menu..............................................................................................................................447Tools menu..................................................................................................................................448Window menu..............................................................................................................................450Help menu....................................................................................................................................452AFL Editor menu..........................................................................................................................453Automatic Analysis result list context menu.................................................................................456Chart context menu......................................................................................................................458Layouts context menu..................................................................................................................459Formula (chart) context menu......................................................................................................460Layers context menu....................................................................................................................461

    Keyboard shortcuts.............................................................................................................................463Import ASCII.......................................................................................................................................465

    How does it work?........................................................................................................................465Format definition commands........................................................................................................465Comments....................................................................................................................................481Usage examples..........................................................................................................................481Default behaviour.........................................................................................................................484User-definable file types and formats...........................................................................................484Ticker aliases...............................................................................................................................485GICS categorisation.....................................................................................................................485ICB categorisation........................................................................................................................486High resolution timestamps (milli- and micro-second)..................................................................486

    AmiBroker's OLE Automation Object Model.......................................................................................487Index of objects............................................................................................................................487ADQuotation.................................................................................................................................488ADQuotations...............................................................................................................................488Analysis........................................................................................................................................488AnalysisDoc.................................................................................................................................490AnalysisDocs................................................................................................................................492Application....................................................................................................................................492Window........................................................................................................................................493Windows.......................................................................................................................................494Commentary.................................................................................................................................494Document.....................................................................................................................................494Documents...................................................................................................................................495Market..........................................................................................................................................495Markets........................................................................................................................................495Quotation......................................................................................................................................495Quotations....................................................................................................................................496Stock............................................................................................................................................496Stocks..........................................................................................................................................497Practical Examples:......................................................................................................................498

    AmiQuote's OLE Automation Object Model........................................................................................500

    AmiBroker 6.30 User's Guide

    iv

  • Table of ContentsAmiBroker Reference Guide

    Index of objects...................................................................................................................................500Document.....................................................................................................................................500

    Technical analysis guide ..............................................................................................................................502Introduction.........................................................................................................................................502Basic tools..........................................................................................................................................503

    Price charts..................................................................................................................................504Trend lines...................................................................................................................................506Moving averages..........................................................................................................................507Regression channels....................................................................................................................508Fibonacci Retracement................................................................................................................509Fibonacci Time Zones..................................................................................................................510Bollinger bands............................................................................................................................511

    Indicators............................................................................................................................................512Accumulation/Distribution.............................................................................................................513Advance-Decline line (AD-Line)...................................................................................................514ADX / Directional Movement Index..............................................................................................515CCI - Commodity Channel Index.................................................................................................516Chaikin Oscillator.........................................................................................................................517MACD - Moving Average Convergence/Divergence....................................................................518Money Flow Index........................................................................................................................519Negative Volume Index................................................................................................................520OBV - On Balance Volume..........................................................................................................521Parabolic SAR (Stop-And-Reverse).............................................................................................522RS - Relative Strength (comparative)..........................................................................................523RSI - Relative Strength Index.......................................................................................................524ROC - Price Rate Of Change.......................................................................................................525Stochastic Slow............................................................................................................................526TRIN - Arms Index.......................................................................................................................527TRIX - TRIple eXponential...........................................................................................................528Ultimate Oscillator........................................................................................................................529VAP - Volume At Price histogram................................................................................................530Relative Performance chart..........................................................................................................531

    AmiBroker Formula Language (AFL)...........................................................................................................532AFL Reference Manual.......................................................................................................................533Introduction.........................................................................................................................................533Basics.................................................................................................................................................533

    Lexical elements..........................................................................................................................533Language structure......................................................................................................................534Keywords.....................................................................................................................................550

    AFL Function Reference - Alphabetical list of functions.....................................................................576AFL Function Reference - Categorized list of functions.....................................................................585

    #include - preprocessor include command..................................................................................596#include_once - preprocessor include (once) command.............................................................597#pragma - sets AFL pre-processor option....................................................................................598abs - absolute value.....................................................................................................................599AccDist - accumulation/distribution..............................................................................................602

    AmiBroker 6.30 User's Guide

    v

  • Table of ContentsAmiBroker Formula Language (AFL)

    acos - arccosine function.............................................................................................................603AddColumn - add numeric exploration column............................................................................604AddMultiTextColumn - adds exploration text column based on array..........................................607AddRankColumn - add ranking column(s) according to current sort set by SetSortColumns......608AddRow - add raw text row to exploration...................................................................................609AddSummaryRows - add summary row(s) to the exploration output...........................................610AddTextColumn - add text exploration column............................................................................612AddToComposite - add value to composite ticker........................................................................614ADLine - advance/decline line......................................................................................................616AdvIssues - advancing issues......................................................................................................617AdvVolume - advancing issues volume.......................................................................................618ADX - average directional movement index.................................................................................619AlertIf - trigger alerts.....................................................................................................................620AlmostEqual - rounding error insensitive comparison..................................................................622AMA - adaptive moving average..................................................................................................623AMA2 - adaptive moving average................................................................................................625ApplyStop - apply built-in stop......................................................................................................626Asc - get ASCII code of character................................................................................................631asin - arcsine function..................................................................................................................632atan - arc tan................................................................................................................................633atan2 - calculates arctangent of y/x.............................................................................................634ATR - average true range............................................................................................................635BarIndex - get zero-based bar number........................................................................................637BarsSince - bars since.................................................................................................................640BBandBot - bottom bollinger band...............................................................................................642BBandTop - top bollinger band....................................................................................................643BeginValue - Value of the array at the begin of the range...........................................................644CategoryAddSymbol - adds a symbol to a category....................................................................645CategoryCreate - add new category (such as watch list).............................................................647CategoryFind - search for category by name...............................................................................648CategoryGetName - get the name of a category.........................................................................649CategoryGetSymbols - retrieves comma-separated list of symbols belonging to given

    category................................................................................................................................651CategoryRemoveSymbol - remove a symbol from a category.....................................................653CategorySetName - set the name of category (group, market, watch list, industry)....................655CCI - commodity channel index...................................................................................................656ceil - ceil value..............................................................................................................................658Chaikin - chaikin oscillator............................................................................................................659ClipboardGet - retrieves current contents of Windows clipboard.................................................660ClipboardSet - copies the text to the Windows clipboard.............................................................661ColorBlend - blends (mixes) two colors........................................................................................662ColorHSB - specify color using Hue-Saturation-Brightness.........................................................663ColorRGB - specify color using Red-Green-Blue components....................................................665Correlation - correlation................................................................................................................667cos - cosine..................................................................................................................................669cosh - hyperbolic cosine function.................................................................................................670CreateObject - create COM object...............................................................................................671CreateStaticObject - create static COM object............................................................................672

    AmiBroker 6.30 User's Guide

    vi

  • Table of ContentsAmiBroker Formula Language (AFL)

    Cross - crossover check...............................................................................................................673Cum - cumulative sum.................................................................................................................676CumProd - cumulative product of all array elements...................................................................679Date - date...................................................................................................................................680DateNum - date number...............................................................................................................682DateTime - retrieves encoded date time......................................................................................683DateTimeAdd - adds specified number of seconds/minutes/hours/days to datetime...................685DateTimeConvert - date/time format conversion.........................................................................687DateTimeDiff - get difference in seconds between two datetime values......................................689DateTimeFormat - converts datetime to string.............................................................................690DateTimeToStr - convert datetime to string.................................................................................692Day - day of month.......................................................................................................................693DayOfWeek - day of week...........................................................................................................694DayOfYear - get ordinal number of day in a year.........................................................................695DaysSince1900 - get number of days since January 1st, 1900...................................................696DecIssues - declining issues........................................................................................................698DecVolume - declining issues volume.........................................................................................699DEMA - double exponential moving average...............................................................................700EMA - exponential moving average.............................................................................................702EnableRotationalTrading - Turns on rotational-trading mode of the backtester...........................706EnableScript - enable scripting engine.........................................................................................708EnableTextOutput - allows to enable or disable text output.........................................................709EncodeColor - encodes color for indicator title............................................................................710EndValue - value of the array at the end of the selected range...................................................712Equity - calculate single-symbol equity line..................................................................................713Error - displays user-defined error message and stops the execution.........................................717EXP - exponential function...........................................................................................................718ExRem - remove excessive signals.............................................................................................719ExRemSpan - remove excessive signals spanning given number of bars...................................721fclose - close a file........................................................................................................................722fdelete - deletes a file...................................................................................................................723fdir - list directory content.............................................................................................................724feof - test for end-of-file................................................................................................................726FFT - performs Fast Fourier Transform.......................................................................................728fgetcwd - get current working directory........................................................................................731fgets - get a string from a file........................................................................................................732fgetstatus - retrieves file status/properties...................................................................................734FIR - Finite Impulse Response filter.............................................................................................735FirstVisibleValue - get first visible value of array..........................................................................737Flip -.............................................................................................................................................738floor - floor value..........................................................................................................................739fmkdir - creates (makes) a directory.............................................................................................740fopen - open a file........................................................................................................................741Foreign - access foreign security data.........................................................................................743fputs - write a string to a file.........................................................................................................746frac - fractional part......................................................................................................................748frmdir - removes a directory.........................................................................................................749FullName - full name of the symbol..............................................................................................750

    AmiBroker 6.30 User's Guide

    vii

  • Table of ContentsAmiBroker Formula Language (AFL)

    GapDown - gap down..................................................................................................................752GapUp - gap up............................................................................................................................753GetAsyncKeyState - query the current state of keyboard keys....................................................754GetBacktesterObject - get the access to backtester object.........................................................758GetBaseIndex - retrieves symbol of relative strength base index................................................759GetCategorySymbols - retrieves comma-separated list of symbols belonging to given

    category................................................................................................................................760GetChartBkColor - get the RGB color value of chart background................................................761GetChartID - get current chart ID.................................................................................................762GetCursorMouseButtons - get current state of mouse buttons....................................................763GetCursorXPosition - get current X position of mouse pointer....................................................767GetCursorYPosition - get current Y position of mouse pointer....................................................769GetDatabaseName - retrieves folder name of current database.................................................771GetExtraData - get extra data from external data source............................................................772GetExtraDataForeign - get extra data from external data source for specified symbol................774GetFnData - get fundamental data...............................................................................................776GetFnDataForeign - get fundamental data for specified symbol..................................................778GetFormulaPath - get file path of current formula........................................................................780GetLastOSError - get text of last operating system (Windows) error...........................................781GetOption - gets the value of option in automatic analysis settings.............................................782GetPerformanceCounter - retrieves the current value of the high-resolution performance

    counter..................................................................................................................................787GetPlaybackDateTime - get bar replay position date/time...........................................................789GetPriceStyle - get current price chart style.................................................................................790GetRTData - retrieves the real-time data fields............................................................................792GetRTDataForeign - retrieves the real-time data fields (for specified symbol)............................794GetScriptObject - get access to script COM object......................................................................796GetTradingInterface - retrieves OLE automation object to automatic trading interfac.................797GfxArc - draw an arc....................................................................................................................798GfxChord - draw a chord..............................................................................................................799GfxCircle - draw a circle...............................................................................................................800GfxDrawImage - draw bitmap image............................................................................................801GfxDrawText - draw a text (clipped to rectangle).........................................................................802GfxEllipse - draw an ellipse..........................................................................................................805GfxFillSolidRect - fill rectangle with solid color.............................................................................806GfxGetTextWidth - get pixel width of text.....................................................................................807GfxGradientRect - draw a rectangle with gradient fill...................................................................808GfxLineTo - draw a line to specified point....................................................................................809GfxMoveTo - move graphic cursor to new position......................................................................810GfxPie - draw a pie.......................................................................................................................811GfxPolygon - draw a polygon.......................................................................................................812GfxPolyline - draw a polyline........................................................................................................813GfxRectangle - draw a rectangle..................................................................................................814GfxRoundRect - draw a rectangle with rounded corners.............................................................815GfxSelectFont - create / select graphic font.................................................................................816GfxSelectHatchBrush - select hatch style brush..........................................................................818GfxSelectPen - create / select graphic pen..................................................................................819GfxSelectSolidBrush - create / select graphic brush....................................................................821

    AmiBroker 6.30 User's Guide

    viii

  • Table of ContentsAmiBroker Formula Language (AFL)

    GfxSelectStockObject - select built-in graphic object...................................................................822GfxSetBkColor - set graphic background color............................................................................823GfxSetBkMode - set graphic background mode..........................................................................824GfxSetCoordsMode - set low-level graphics co-ordinate mode...................................................825GfxSetOverlayMode - set low-level graphic overlay mode...........................................................827GfxSetPixel - set pixel at specified position to specified color.....................................................828GfxSetTextAlign - set text alignment............................................................................................829GfxSetTextColor - set graphic text color......................................................................................831GfxSetZOrder - set current low-level graphic Z-order layer.........................................................833GfxTextOut - writes text at the specified location.........................................................................834GicsID - get GICS category information.......................................................................................836GroupID - get group ID/name.......................................................................................................837GuiButton - create on-chart button control...................................................................................838GuiCheckBox - creates on-chart checkbox control......................................................................839GuiDateTime - creates on-chart date-time picker control.............................................................840GuiEdit - create on-chart edit control...........................................................................................841GuiEnable - enables or disables on-chart control........................................................................842GuiGetCheck - get checked state of control................................................................................843GuiGetEvent - get GUI event.......................................................................................................844GuiGetText - get text from on-chart control..................................................................................846GuiGetValue - get numeric value of on-chart control...................................................................847GuiRadio - creates on-chart radio button control.........................................................................848GuiSetCheck - set checked state of on-chart control...................................................................849GuiSetFont - set the font for on-chart control...............................................................................850GuiSetRange - set slider control range........................................................................................851GuiSetText - set text value of on-chart control.............................................................................852GuiSetValue - set numeric value of on-chart control....................................................................853GuiSetVisible - shows or hides on-chart control..........................................................................854GuiSlider - creates on-chart slider control....................................................................................855GuiToggle - create on-chart toggle button control........................................................................856HHV - highest high value.............................................................................................................857HHVBars - bars since highest high..............................................................................................862Highest - highest value.................................................................................................................863HighestBars - bars since highest value........................................................................................864HighestSince - highest value since condition met........................................................................865HighestSinceBars - bars since highest value since condition met...............................................866HighestVisibleValue - get the highest value within visible chart area..........................................867HMA - Hull Moving Average.........................................................................................................868Hold - hold the alert signal...........................................................................................................869Hour - get current bar's hour........................................................................................................870IcbID - get ICB category information............................................................................................871IIf - immediate IF function.............................................................................................................872IIR - infinite impulse response filter..............................................................................................882IndustryID - get industry ID / name..............................................................................................884InGICS - test GICS membership..................................................................................................885InICB - test ICB membership.......................................................................................................886Inside - inside day........................................................................................................................887Int - integer part............................................................................................................................888

    AmiBroker 6.30 User's Guide

    ix

  • Table of ContentsAmiBroker Formula Language (AFL)

    InternetClose - close Internet file handle......................................................................................890InternetOpenURL - opens Internet web resource (URL)..............................................................891InternetPostRequest - sends HTTP Post request to Internet web resource (URL)......................892InternetReadString - read a string from Internet resource...........................................................894InternetSetAgent - set agent string for Internet function..............................................................895Interval - get bar interval (in seconds)..........................................................................................896InWatchList - watch list membership test (by ordinal number).....................................................898InWatchListName - watch list membership test (by name)..........................................................899IsContinuous - checks 'continuous quotations' flag state.............................................................900IsEmpty - empty value check.......................................................................................................901IsFavorite - check if current symbol belongs to favorites.............................................................902IsFinite - check if value is not infinite............................................................................................903IsIndex - check if current symbol is an index...............................................................................904IsNan - checks for NaN (not a number).......................................................................................905IsNull - check for Null (empty) value............................................................................................906IsTrue - true value (non-empty and non-zero) check...................................................................907Kurtosis - calculates kurtosis........................................................................................................908LastValue - last value of the array................................................................................................909LastVisibleValue - get last visible value of array..........................................................................913LineArray - generate trend-line array...........................................................................................914LinearReg - linear regression end-point.......................................................................................916LinRegIntercept -..........................................................................................................................917LinRegSlope - linear regression slope.........................................................................................918LLV - lowest low value.................................................................................................................920LLVBars - bars since lowest low..................................................................................................924log - natural logarithm..................................................................................................................925log10 - decimal logarithm.............................................................................................................927Lookup - search the array for bar with specified date/time..........................................................928Lowest - lowest value...................................................................................................................929LowestBars - bars since lowest....................................................................................................930LowestSince - lowest value since condition met..........................................................................931LowestSinceBars - barssince lowest value since condition met..................................................932LowestVisibleValue - get the lowest value within visible chart area.............................................933MA - simple moving average........................................................................................................934MACD - moving average convergence/divergence......................................................................941MarketID - market ID / name........................................................................................................943Matrix - create a new matrix.........................................................................................................944Max - maximum value of two numbers / arrays...........................................................................945MDI - minus directional movement indicator (-DI)........................................................................948Median - calculate median (middle element)...............................................................................949MFI - money flow index................................................................................................................950MicroSec - get bar's microsecond part of the timestamp.............................................................951MilliSec - get bar's millisecond part of the timestamp..................................................................952Min - minimum value of two numbers / arrays.............................................................................953Minute - get current bar's minute..................................................................................................956Month - month..............................................................................................................................957mtRandom - Mersene Twister random number generator...........................................................958mtRandomA - Mersene Twister random number generator (array version).................................959

    AmiBroker 6.30 User's Guide

    x

  • Table of ContentsAmiBroker Formula Language (AFL)

    MxDet - calculate determinant of the matrix.................................................................................960MxFromString - creates a new matrix out of string......................................................................961MxGetBlock - get rectangular block of items from matrix.............................................................962MxGetSize - get size of the matrix...............................................................................................963MxIdentity - create an identity matrix...........................................................................................964MxInverse - calculate inverse matrix............................................................................................965MxSetBlock - sets values in the rectangular block of matrix cells................................................966MxSolve - solves linear equation system A @ X = B...................................................................968MxSort - sorts the matrix..............................................................................................................971MxSortRows - sort the rows of the matrix....................................................................................972MxSum - calculate grand sum of the matrix.................................................................................974MxToString - convert matrix to string...........................................................................................975MxTranspose - creates transpose of an input matrix...................................................................976Name - ticker symbol...................................................................................................................977NormDist - normal distribution function........................................................................................982NoteGet - retrieves the text of the note........................................................................................983NoteSet - sets text of the note......................................................................................................984Now - gets current system date/time............................................................................................985NullCount - count consecutive Null values...................................................................................987NumToStr - convert number to string...........................................................................................988NVI - negative volume index........................................................................................................991Nz - Null (Null/Nan/Infinity) to zero...............................................................................................992OBV - on balance volume............................................................................................................994Optimize - define optimization variable........................................................................................995OptimizerSetEngine - select external optimization engine...........................................................998OptimizerSetOption - set the value of external optimizer engine parameter................................999OscP - price oscillator................................................................................................................1000OscV - volume oscillator............................................................................................................1001Outside - outside bar..................................................................................................................1002Param - add user user-definable numeric parameter................................................................1003ParamColor - add user user-definable color parameter.............................................................1011ParamDate - add user user-definable date parameter...............................................................1015ParamField - creates price field parameter................................................................................1016ParamList - creates the parameter that consist of the list of choices.........................................1018ParamStr - add user user-definable string parameter................................................................1020ParamStyle - select styles applied to the plot............................................................................1021ParamTime - add user user-definable time parameter..............................................................1024ParamToggle - create Yes/No parameter..................................................................................1025ParamTrigger - creates a trigger (button) in the parameter dialog.............................................1028PDI - plus directional movement indicator..................................................................................1029Peak - peak................................................................................................................................1030PeakBars - bars since peak.......................................................................................................1031Percentile - calculate percentile.................................................................................................1032PercentRank - calculate percent rank........................................................................................1033PlaySound - play back specified .WAV file................................................................................1034Plot - plot indicator graph...........................................................................................................1035PlotForeign - plot foreign security data......................................................................................1045PlotGrid - Plot horizontal grid line...............................................................................................1046

    AmiBroker 6.30 User's Guide

    xi

  • Table of ContentsAmiBroker Formula Language (AFL)

    PlotOHLC - plot custom OHLC chart.........................................................................................1048PlotShapes - plots arrows and other shapes.............................................................................1051PlotText - write text on the chart................................................................................................1056PlotTextSetFont - write text on the chart with user-defined font................................................1058PlotVAPOverlay - plot Volume-At-Price overlay chart................................................................1059PlotVAPOverlayA - plot multiple-segment Volume-At-Price chart..............................................1060PopupWindow - display pop-up window....................................................................................1062Prec - adjust number of decimal points of floating point number...............................................1063Prefs - retrieve preferences settings..........................................................................................1064PriceVolDistribution - general-purpose distribution function......................................................1066printf - Print formatted output to the output window...................................................................1068Prod - cumulative product of array over specified range............................................................1070ProdSince - cumulative product since condition is met..............................................................1071PVI - positive volume index........................................................................................................1072Random - random number.........................................................................................................1073Ref - reference past/future values of the array...........................................................................1075RelStrength - comparative relative strength...............................................................................1084Remap - re-maps one range to another.....................................................................................1085RequestMouseMoveRefresh - request chart to be refreshed when user moves mouse

    cursor..................................................................................................................................1087RequestTimedRefresh - forces periodical refresh of indicator pane..........................................1088RestorePriceArrays - restore price arrays to original symbol.....................................................1090Reverse - reverse the order of the elements in the array...........................................................1092RMI - Relative Momentum Index................................................................................................1093ROC - percentage rate of change..............................................................................................1094Round - round number to nearest integer..................................................................................1097RSI - relative strength index.......................................................................................................1099RWI - random walk index...........................................................................................................1101RWIHi - random walk index of highs..........................................................................................1102RWILo - random walk index of lows...........................................................................................1103SAR - parabolic stop-and-reverse..............................................................................................1104Say - speaks provided text.........................................................................................................1105Second - get current bar's second.............................................................................................1107SectorID - get sector ID / name..................................................................................................1108SelectedValue - retrieves value of the array at currently selected date/time point.....................1109SendEmail - send an e-mail message.......................................................................................1112SetBacktestMode - Sets working mode of the backtester..........................................................1113SetBarFillColor - set bar/candlestick/cloud chart fill color..........................................................1115SetBarsRequired - set number of previous and future bars needed for script/DLL to

    properly execute.................................................................................................................1117SetChartBkColor - set background color of a chart....................................................................1119SetChartBkGradientFill - enables background gradient color fill in indicators............................1121SetChartOptions - set/clear/overwrite defaults for chart pane options.......................................1123SetCustomBacktestProc - define custom backtest procedure formula file.................................1127SetForeign - replace current price arrays with those of foreign security....................................1128SetFormulaName - set the name of the formula........................................................................1130SetGradientFill - set the colors of a gradient fill plot...................................................................1131SetOption - sets options in automatic analysis settings.............................................................1133

    AmiBroker 6.30 User's Guide

    xii

  • Table of ContentsAmiBroker Formula Language (AFL)

    SetPositionSize - set trade size.................................................................................................1139SetSortColumns - sets the columns which will be used for sorting in AA window.....................1142SetStopPrecedence - set precedence of built-in stops..............................................................1143SetTradeDelays - allows to control trade delays applied by the backtester...............................1144ShellExecute - execute a file......................................................................................................1146sign - returns the sign of the number/array................................................................................1147Signal - macd signal line............................................................................................................1148sin - sine function.......................................................................................................................1150sinh - hyperbolic sine function....................................................................................................1151Skewness - calculate skewness.................................................................................................1152Sort - performs a quick sort of the array.....................................................................................1153SparseCompress - compress sparse array................................................................................1154SparseExpand - expand compressed array to sparse array......................................................1156sqrt - square root........................................................................................................................1158StaticVarAdd - an "atomic" addition for static variables.............................................................1160StaticVarCompareExchange - atomic interlocked static variable compare-exchange

    operation.............................................................................................................................1162StaticVarCount - get the total number of static variables in memory.........................................1165StaticVarGenerateRanks - generate ranking of multiple symbols and store it to static

    variables.............................................................................................................................1166StaticVarGet - gets the value of static variable..........................................................................1170StaticVarGetRankedSymbols - retrieve a list of ranked symbols from static variables..............1173StaticVarGetText - gets the value of static variable as string.....................................................1175StaticVarInfo - get the information about static variable(s)........................................................1177StaticVarRemove - remove static variable.................................................................................1178StaticVarSet - sets the value of static variable...........................................................................1180StaticVarSetText - Sets the value of static string variable.........................................................1183Status - get run-time AFL status information..............................................................................1184StdErr - standard error...............................................................................................................1190StDev - standard deviation.........................................................................................................1191StochD - stochastic slow %D.....................................................................................................1193StochK - stochastic slow %K......................................................................................................1194StrCount - count the occurrences of substring within a string....................................................1195StrExtract - extracts given item (substring) from comma-separated string................................1196StrFind - find substring in a string..............................................................................................1198StrFormat - Write formatted output to the string.........................................................................1199StrLeft - extracts the leftmost part..............................................................................................1202StrLen - string length..................................................................................................................1204StrMatch - string pattern/wildcard matching...............................................................................1205StrMid - extracts part of the string..............................................................................................1206StrReplace - string replace.........................................................................................................1207StrRight - extracts the rightmost part of the string......................................................................1208StrSort - sort comma-separated item list....................................................................................1209StrToDateTime - convert string to datetime...............................................................................1210StrToLower - convert to lowercase............................................................................................1211StrToNum - convert string to number.........................................................................................1212StrToUpper - convert to uppercase............................................................................................1213StrTrim - trim whitespaces from the string.................................................................................1214

    AmiBroker 6.30 User's Guide

    xiii

  • Table of ContentsAmiBroker Formula Language (AFL)

    Study - reference hand-drawn study..........................................................................................1215Sum - sum data over specified number of bars.........................................................................1216SumSince - sum of array elements since condition was tru.......................................................1219tan - tangent function.................................................................................................................1220tanh - hyperbolic tangent function..............................................................................................1221TEMA - triple exponential moving average................................................................................1222ThreadSleep - suspend thread for specified number of milliseconds........................................1223TimeFrameCompress - compress single array to given time frame...........................................1224TimeFrameExpand - expand time frame compressed array......................................................1226TimeFrameGetPrice - retrieve O, H, L, C, V values from other time frame................................1228TimeFrameMode - switch time frame compression mode.........................................................1230TimeFrameRestore - restores price arrays to original time frame..............................................1232TimeFrameSet - switch price arrays to a different time frame....................................................1234TimeNum - get current bar time.................................................................................................1237Trin - traders (Arms) index.........................................................................................................1238TRIX - triple exponential smoothed price...................................................................................1239Trough - trough..........................................................................................................................1240TroughBars - bars since trough..................................................................................................1241TSF - time series forecast..........................................................................................................1242Ultimate - ultimate oscillator.......................................................................................................1243UncIssues - unchanged issues..................................................................................................1244UncVolume - unchaged issues volume......................................................................................1245ValueWhen - get value of the array when condition met............................................................1246VarGet - gets the value of dynamic variable..............................................................................1249VarGetText - gets the text value of dynamic variable................................................................1251VarSet - sets the value of dynamic variable...............................................................................1253VarSetText - sets dynamic variable of string type......................................................................1255Version - get version info...........................................................................................................1256VoiceCount - get number of SAPI voices...................................................................................1257VoiceSelect - select SAPI voice.................................................................................................1258VoiceSetRate - sets voice speech rate......................................................................................1259VoiceSetVolume - set the volume of speech.............................................................................1260VoiceWaitUntilDone - waits until TTS voice has finished speaking............................................1261Wilders - Wilder's smoothing......................................................................................................1262WMA - weighted moving average..............................................................................................1263WriteIf - commentary conditional text output..............................................................................1264WriteVal - converts number to string..........................................................................................1267XYChartAddPoint - add point to exploration scatter (XY) chart.................................................1271XYChartSetAxis - set the names of X and Y axes in exploration scatter charts........................1273Year - year.................................................................................................................................1274ZIG - zig-zag indicator................................................................................................................1275_DEFAULT_NAME - retrive default name of the plot.................................................................1276_DT - convert string to datetime.................................................................................................1278_N - no text output......................................................................................................................1279_PARAM_VALUES - retrieve param values string.....................................................................1288_SECTION_BEGIN - section begin marker...............................................................................1289_SECTION_END - section end marker......................................................................................1293_SECTION_NAME - retrieve current section name...................................................................1297

    AmiBroker 6.30 User's Guide

    xiv

  • Table of ContentsAmiBroker Formula Language (AFL)

    _TRACE - print text to system debug viewer.............................................................................1298_TRACEF - print formatted text to system debug viewer...........................................................1300

    AFL Error List....................................................................................................................................1301Error 1. Operation not allowed. Operator/operand type mismatch.............................................1304

    Calculating multiple-security statistics with AddToComposite function............................................1386Equity function, Individual and Portfolio Equity Charts.....................................................................1390

    Functions accepting variable periods.........................................................................................1395User-definable functions, procedures. Local/global scope.........................................................1396

    AFL