Skip to content

AFL Function Reference

The list of taught functions is discovered from the lessons themselves — from the aflFunctions field in each page’s frontmatter — and the signatures are extracted verbatim from the official per-function pages.

Two consequences follow, and both are the point.

A function taught in a lesson cannot be missing from this page. If a lesson claims to teach ApplyStop(), it appears here.

A signature here cannot disagree with the official documentation, because it was taken from it rather than retyped.

If a name in a lesson does not exist in the official reference, this page renders a build warning naming it. In a correct build there is no warning — and separately, an automated check fails the build if any AFL example anywhere in the course calls a function that is not in the official list.

Functions are grouped by AmiBroker’s own categories and sorted alphabetically within each group. Each entry has a stable anchor — #fn-applystop, for instance — so a lesson can link straight to a function’s entry.

Site search covers this page, so searching for a function name finds both its entry here and the lessons that teach it.

Build warning: these names appear in lesson frontmatter but are not in the official AFL Function Reference: filter, barcount, title, graphxspace, exclude, positionscore, roundlotsize, positionsize, null. Check them.

243 AFL functions are taught in this course, out of 445 in the official reference for AmiBroker 7.00.1. Signatures below are as AmiBroker documents them (retrieved 2026-08-31).

Basic price pattern detection

GapDownreturns ARRAY

GapDown()

Gives a "1" or "true" on the day a security's prices gap down. Otherwise the result is "0". A gap down occurs if yesterday's low is greater than today's high.

GapUpreturns ARRAY

GapUp()

Gives a "1" or "true" on the day a security's prices gap up. Otherwise the result is "0". A gap up occurs if yesterday's high is less than today's low.

Insidereturns ARRAY

Inside()

Gives a "1" or "true" when an inside day occurs.Gives "0" otherwise. An inside day occurs when today's high is less than yesterday's high and today's low is greater than yesterday's low.

Peakreturns ARRAYAFL 1.1

Peak(ARRAY, change , n = 1)

Gives the value of ARRAY n -th peak(s) ago. This uses the Zig Zag function (see Zig Zag) to determine the peaks. n =1 would return the value of the most recent peak. n =2 would return the value of the 2nd most recent peak. Caveat: this function is based on Zig-Zag indicator and may look into the future.

PeakBarsreturns ARRAYAFL 1.1

PeakBars(ARRAY, change , n = 1)

Gives the number of bars that have passed from the n -th peak. This uses the Zig Zag function (see Zig Zag) to determine the peaks. n =1 would return the number of bars that have passed since the most recent peak. n =2 would return the number of bars that have passed since the 2nd most recent peak Caveat: this function is based on Zig-Zag indicator and may look into the future.

PlotTextSetFontreturns NOTHINGAFL 2.80

PlotTextSetFont( ''text'', ''fontname'', pointsize, x, y, color, bkcolor = colorDefault, yoffset = 0 )

This function writes text in specified co-ordinates using specified font where: 'text' is a text to display 'fontname' is a type face name pointsize is a font size in points x - is x-coordinate in bars

ShellExecutereturns NUMBERAFL 3.40

ShellExecute( ''filepath'', ''arguments'', ''parameters'', showcmd = 1 )

The function opens a file or runs executable. It is equivalent of Windows API ShellExecute, with one difference, it always uses "open" verb. This allows running executables, scripts, opening document files using their associated editors, etc. If the function succeeds, it returns a value greater than 32. If the function fails, it returns an error value that indicates the cause of the failure.

Troughreturns ARRAYAFL 1.1

Trough(ARRAY, change , n = 1)

Gives the value of ARRAY n -th trough(s) ago. This uses the Zig Zag function (see Zig Zag) to determine the troughs. Caveat: this function is based on Zig-Zag indicator and may look into the future.

TroughBarsreturns ARRAYAFL 1.1

TroughBars(ARRAY, change , n = 1)

Plots the number of bars that have passed from the n -th trough. This uses the Zig Zag function (see Zig Zag) to determine the troughs. Caveat: this function is based on Zig-Zag indicator and may look into the future.

ZIGreturns ARRAYAFL 1.1

zig(ARRAY, change )

Calculates the minimum % change Zig Zag indicator. Caveat: this function is based on Zig-Zag indicator and may look into the future - this means that you can get unrealistic results when back testing trading system using this indicator. This function is provided rather for pattern and trend recognition formulas.

Composites

AddToCompositereturns NOTHINGAFL 2.0

AddToComposite( array, ''ticker'', ''field'', flags = atcFlagDefaults )

Allows you to create composite indicators with ease. More info... Parameters: array - the array of values to be added to "field" in "ticker" composite symbol "ticker" - the ticker of composite symbol.

ADLinereturns ARRAYAFL 1.2

ADLine()

Calculates Advance/Decline line indicator

AdvIssuesreturns ARRAYAFL 1.2

AdvIssues()

Returns the number of advancing issues for a given market (the one that currently analysed stock belongs to)

AdvVolumereturns ARRAYAFL 1.2

AdvVolume()

Returns the volume of advancing issues for a given market (the one that currently analysed stock belongs to)

DecIssuesreturns ARRAYAFL 1.2

DecIssues()

Returns the number of declining issues for a given market (the one that currently analysed stock belongs to)

DecVolumereturns ARRAYAFL 1.2

DecVolume()

Returns the volume of declining issues for a given market (the one that currently analysed stock belongs to)

Trinreturns ARRAYAFL 1.2

Trin()

Calculates TRIN (Arms Index) indicator. NOTE: All built-in a/d indicators (AdLine/Trin) work only with composites calculated inside AmiBroker http://www.amibroker.com/newsletter/04-2000.html If you are using QP2 database for example you should use QP2's own symbols for advances/declines.

UncIssuesreturns ARRAYAFL 1.2

UncIssues()

Returns the number of unchanged issues for a given market (the one that currently analysed stock belongs to)

UncVolumereturns ARRAYAFL 1.2

UncVolume()

Returns the volume of unchanged issues for a given market (the one that currently analysed stock belongs to)

Date/Time

BarIndexreturns ARRAYAFL 2.3

BarIndex()

returns zero-based bar number - the same as Cum(1)-1 but it is much faster than Cum(1) when used in Indicators New in 5.30: BarIndex() now returns values always starting from zero (even if QuickAFL is turned on). This change is required because Cum() now does not require all bars and formulas mixing Cum(1) and BarIndex would work improperly otherwise.

BeginValuereturns NUMBERAFL 2.3

BeginValue( ARRAY )

This function gives the single value (number) of the ARRAY at the beginning of the selected range. If no range is marked then the value at the first bar is returned. To select the range you have to double click in the chart at the beginning of the range and then double click in the chart at the end of the range. Then >

Datereturns STRINGAFL 1.1

date()

It is used to display the selected date in commentary / interpretation window

DateTimereturns ARRAYAFL 2.3

DateTime()

Returns array of encoded date/time values suitable for using with AddColumn and formatDateTime constant to produce date time formated according to your system settings. VERSION 5.27 and above: It is important to understand that DateTime is not a simple number but rather bitset and two datetime values can only be reliably compared for equlity or inequality using == or != operators.

DateTimeConvertreturns NUMBERAFL 2.90

DateTimeConvert( format, date, time = Null )

The function allows to convert from DateTime format to DateNum and TimeNum and vice versa. format parameter controls the direction of conversion: format = 0 - converts DateTime format to DateNum format

DaysSince1900returns ARRAYAFL 3.20

DaysSince1900()

The function returns the number of days that passed since January 1st, 1900, counting from 2. January 1, 1900 is serial number 2, and January 1, 2008 is serial number 39448. Technically is equal to Windows OLEDATE and Excel's DATEVALUE function. As to why it starts counting from 2 (two) - it is to get the same values as Excel DATEVALUE.

EndValuereturns NUMBERAFL 2.3

EndValue( ARRAY )

This function gives the single value (number) of the ARRAY at the end of the selected range. If no range is marked then the value at the last bar is returned. To select the range you have to double click in the chart at the beginning of the range and then double click in the chart at the end of the range. Then >

Intervalreturns NUMBERAFL 2.1

Interval( format = 0 )

Interval() function returns bar interval. Possible formats: format = 0 - returns bar interval in seconds format = 1 - as above plus TICK bar intervals are returned with negative sign so Interval() func

Monthreturns ARRAYAFL 1.4

Month()

Returns the array with months(1-12)

Exploration / Indicators

_DEFAULT_NAMEreturns STRINGAFL 2.70

_DEFAULT_NAME()

This function returns the default name of plot in the drag-drop section. The default name consists of section name and comma separated list of values of numeric parameters defined in given section.

_PARAM_VALUESreturns STRINGAFL 2.70

_PARAM_VALUES()

_PARAM_VALUES retrieves the values of the parameters defined in current drag-drop section. It works the same as _DEFAULT_NAME except that no section name is included (so only the list of parameter values is returned).

_SECTION_BEGINreturns NOTHINGAFL 2.70

_SECTION_BEGIN( ''section name'' )

Marks beginning of the drag-drop section. IMPORTANT: "section name" must be a constant, literal string, enclosed in double quotation marks. You must NOT use variable here.

AddColumnreturns NOTHINGAFL 1.8

AddColumn( array, name, format = 1.2, textColor = colorDefault, bkgndColor = colorDefault, width = -1, barchart = Null )

Adds a new column to the exploration result list. The column shows array values and has a caption of name. The values are formatted using format specification. By default all variables are displayed with 2 decimal digits, but you can change this by assigning a different value to this variable: 1.5 gives 5 decimal digits, 1.0 gives no decimal digits.

AddMultiTextColumnreturns NOTHINGAFL 4.20

AddMultiTextColumn( ARRAY, ''TextList'', ''Caption'', format = 1.2, fgcolor = colorDefault, bkcolor = colorDefault, width = -1 )

Adds a text column to the exploration where text displayed is choosen based on array value. Parameters: ARRAY - parameter decides on bar-by-bar basis which item from TextList is choosen TextList - newline-separated list of texts to be displayed depending on ARRAY value.

AddRankColumnreturns NOTHINGAFL 5.70

AddRankColumn()

The function adds ranking column(s) according to current sort set by SetSortColumns to exploration result list.

AddSummaryRowsreturns NOTHINGAFL 3.2

AddSummaryRows( flags, format = 0, onlycols = 0, ...)

AddSummaryRows automatically adds "summary" row(s) to the exploration output. Parameters: The flags parameter can be combination of the following: 1 - add TOTAL row 2 - add AVERAGE row 4 - add MIN row 8 - add MAX row 16 - add COUNT row 32 - add STANDARD DEVIATION row (new in 5.70) format - defines the numeric formating in WriteVal style so 1.2 for example means 2 decimal digits.

EncodeColorreturns STRINGAFL 2.2

EncodeColor ( colorIndex )

Converts color index to string escape sequence that changes color of text output in chart title. Color escape sequence uses cXX sequence where XX is 2 digit number specifying color index c38 - defines violet, there is a special sequence c-1 that resets to default axis color.

GetChartIDreturns NUMBERAFL 2.3

GetChartID()

returns the chart ID of current indicator formula. Returns 0 if used in Automatic analysis.

GetPriceStylereturns NUMBERAFL 2.70

GetPriceStyle

Returns price chart style value to be used in Plot statement Returned value depends on selection in View->Price chart style menu

LineArrayreturns ARRAYAFL 2.5

LineArray( x0, y0, x1, y1, extend = 0, usebarindex = False )

The LineArray function generates array equivalent to trend line drawn from point (x0, y0) to point (x1, y1). x coordinates are in bars (zero based), y coordinates are in dollars. Note: x0 must be SMALLER than x1. Note 2: the function accepts only numbers therefore generates single line. To produce multiple lines you have to call it many times with different co-ordinates.

Paramreturns NUMBERAFL 2.3

Param( ''name'', defaultval, min, max, step, sincr = 0 )

Adds a new user-definable parameter, which will be accessible via Parameters dialog : right click over chart pane and select "Parameters" or press Ctrl+R allows to change chart parameters - changes are reflected immediatelly.

ParamColorreturns NUMBERAFL 2.3

ParamColor( ''name'', defaultcolor )

Adds a new user-definable parameter, which will be accessible via Parameters dialog : right click over chart pane and select "Parameters" or press Ctrl+R allows to change chart parameters - changes are reflected immediatelly.

ParamDatereturns NUMBERAFL 2.60

ParamDate( ''Name'', ''Default date'', format = 0 );

Adds a new user-definable date parameter, which will be accessible via Parameters dialog : right click over chart pane and select "Parameters" or press Ctrl+R allows to change chart parameters - changes are reflected immediatelly. "name" - defines parameter name that will be displayed in the parameters dialog "default date" - is a string holding date in any any format: YYYY-MM-DD, MM/DD/YY, DD-MM-YY, etc, etc.

ParamFieldreturns ARRAYAFL 2.70

ParamField(''name'', field = 3 )

Allows to pick the Price field for the indicator (field which is used to calculate values of the indicator). Function returns the array defined by field parameter. Default value = 3 returns Close array.

ParamListreturns STRINGAFL 2.70

ParamList( ''Name'', ''Values'', defaultval = 0 )

Creates the parameter that consist of the list of choices (specified in "values" parameter - or comma separated). defaultval parameter defines ordinal position of the default string value specified in "values" parameter. Returned value is a STRING representing choosen item. IMPORTANT: Parameter names and values must NOT contain non-printable characters (ASCII codes

ParamStrreturns STRINGAFL 2.3

ParamStr( ''name'', ''default'' )

Adds a new user-definable parameter, which will be accessible via Parameters dialog : right click over chart pane and select "Parameters" or press Ctrl+R allows to change chart parameters - changes are reflected immediatelly.

ParamStylereturns NUMBERAFL 2.70

ParamStyle(''name'', defaultstyle = styleLine, mask = maskDefault )

Allows to select the styles applied to plot. Parameters name - parameter name defaultstyle - default value of style , takes combination of style* constants mask - binary mask that defines which styles

ParamTimereturns NUMBERAFL 2.60

ParamTime( ''Name'', ''Default time'', format = 0 );

Adds a new user-definable time parameter, which will be accessible via Parameters dialog : right click over chart pane and select "Parameters" or press Ctrl+R allows to change chart parameters - changes are reflected immediatelly. "name" - defines parameter name that will be displayed in the parameters dialog "default time" - is a string holding time in any any format: HH:MM:SS, HH:MM, etc.

ParamTriggerreturns NUMBERAFL 2.70

ParamTrigger( ''Name'', ''Button text'')

Creates trigger (button) in the Parameter dialog. If you place ParamTrigger in the indicator code it will create a "button" in Parameter dialog that can be pressed. Normally ParamTrigger will return ze

Plotreturns NUMBERAFL 1.8

Plot( array , name , color/barcolor , style = styleLine, minvalue = {empty}, maxvalue = {empty}, XShift = 0, Zorder = 0, width = 1 )

Plots the graph using array data. Parameters: array - data array to be plotted name - defines graph name used for displaying values in a title bar. color - defines plot color that could be static (if third argument is a number) or dynamic (when third argument is an array).

PlotOHLCreturns NUMBERAFL 2.2

PlotOHLC( open, high, low, close , name , color/barcolor , style = styleCandle styleOwnScale , minvalue = {empty}, maxvalue = {empty}, XShift = 0, ZOrder = 0, width = 1 )

Plots the price chart using custom open, high, low, close arrays supplied as parameters. Fifth argument name defines graph name used for displaying values in a title bar. Graph color could be static (if sixth argument is a number) or dynamic (when sixth argument is an array).

SetChartOptionsreturns NOTHINGAFL 2.70

SetChartOptions( Mode = 0, Flags = 0, gridFlags = chartGridMiddle, ymin = 0, ymax = 0, blankbars = 0 )

Allows to set/clear/overwrite/set defaults for chart pane options Mode - specifies how options are set: 0 - set only the DEFAULT values for new chart. Defaults are applied only once when chart is inser

SetSortColumnsreturns NOTHINGAFL 2.90

SetSortColumns( col1, col2, .... )

sets the columns which will be used for sorting. col1, col2, ... col10 -Column numbers are ONE-based. Positive number means sort ASCENDING, negative number means sort DESCENDING. Upto 10 columns can be specified for multiple-column sort. Each subsequent call to SetSortColumns overwrites previous one, but multiple SetSortColumns make sense if you want to add multiple rankings by different columns via AddRankColumn

WriteValreturns STRING

WriteVal( NUMBER, format = 1.3, separator =True, roundAndPad = False ) WriteVal( ARRAY, format = 1.3, separator =True, roundAndPad = False )

THIS FUNCTION IS OBSOLETE. Use functionally identical NumToStr() instead. It is used to convert numeric value of NUMBER or ARRAY to string. It does NOT write anything, it simply returns a string that can be used in other operations or as a text column in exploration or displayed using printf(). The second parameter - format - allows you to control output formatting (decimal places and leading spaces).

File Input/Output functions

fclosereturns NOTHINGAFL 2.5

fclose( filehandle )

Closes a file. The filehandle (NUMBER) should be the handle returned by fopen function.

fopenreturns FILEAFL 2.5

fopen( ''filename'', ''mode'', shared = False )

Opens file, returns filehandle (NUMBER). File handle is non-zero if file opened successfully, zero on failure. Parameters: filename - STRING - contains the path to the file name. Please note that singl

fputsreturns NOTHINGAFL 2.5

fputs( string , filehandle )

Writes (puts) the string to the file. The filehandle must be a number returned by fopen function used to open the file. The file has to be open for writing or appending ("w" or "a") for this fputs to work.

Indicators

AccDistreturns ARRAY

AccDist()

Calculates the Accumulation/ Distribution indicator.

ADXreturns ARRAYAFL 1.3

adx( period = 14 )

Calculates Average Directional Index indicator

ATRreturns ARRAYAFL 1.3

atr( period )

Calculates Average True Range indicator

BBandBotreturns ARRAY

BBandBot( ARRAY, periods = 15, width = 2 )

Calculates the bottom Bollinger Band of ARRAY shifted down w idth standard deviations (using periods averaging range ).

BBandTopreturns ARRAY

BBandTop( ARRAY, periods = 15, width = 2 )

Calculates the top Bollinger Band of ARRAY shifted up width standard deviations (using periods averaging range ).

ColorBlendreturns NUMBERAFL 3.30

ColorBlend( colorFrom, colorTo, factor = 0.5 )

The function blends (mixes) colorFrom with colorTo with 'factor' proportion using the following algorithm RGB = ( 1 - factor ) * RGB(colorFrom) + factor * RGB(colorTo ); So factor = 0 means use colorFrom only, factor = 1 means use colorTo only. All in-between values mean create mix of colors. The lower the factor value means more colorFrom.

GetChartBkColorreturns NUMBERAFL 3.20

GetChartBkColor()

Returns color value of chart background. Color value in AmiBroker is either one of predefined color constants (colorWhite, colorBlack), or RGB value with offset of 56 (number of predefined colors). So to get actual RGB value you need to subtract 56 from the result of that function.

MACDreturns ARRAY

macd( fast = 12, slow = 26)

Calculates the MACD indicator using fast and slow averaging periods.

MDIreturns ARRAYAFL 1.3

mdi( period = 14 )

Calculates Minus Directional Movement Indicator (-DI line)

MFIreturns ARRAY

mfi( periods = 14 )

Calculates the Money Flow Index with period range

OBVreturns ARRAY

obv()

Calculates the On Balance Volume indicator.

PDIreturns ARRAYAFL 1.3

pdi( period = 14 )

Calculates Plus Directional Movement Indicator (+DI line)

PercentRankreturns ARRAYAFL 3.40

PercentRank( array, range )

INPUTS: array - input data range - lookback range Returns percent rank (0...100) of the current element of the array within all elements over the specified range. A value of 100 indicates that the current element of the array is the highest for the given lookback range, while a value of 0 indicates that the current value is the lowest for the given lookback range.

PlotTextreturns NOTHINGAFL 2.80

PlotText( ''text'', x, y, color, bkcolor = colorDefault, yoffset = 0 )

This function writes text in specified co-ordinates. where: x - is x-coordinate in bars (like in LineArray) y - is y-coordinate in dollars color is text color bkcolor is background color yoffset (new in 5.80) is a Y-axis offset in pixels If bkcolor is NOT specified (or equal to colorDefault) text is written with TRANSPARENT background, any other value causes solid background with specified background color.

RequestMouseMoveRefreshreturns NOTHINGAFL 4.30

RequestMouseMoveRefresh()

The function causes that the chart is refreshed (and formula re-executed) when user moves mouse cursor over the chart area

SetBarFillColorreturns NOTHINGAFL 3.1

SetBarFillColor( colorarray )

SetBarFillColor( colorarray ) allows to independently control candlestick, bar, cloud, and area chart fill color SetBarFillColor must PRECEDE the Plot() function call it applies to. when applied to: st

SetChartBkColorreturns NOTHINGAFL 2.80

SetChartBkColor( color )

Sets chart background to user-specified color

Signalreturns ARRAY

Signal( fast = 12, slow = 26, signal = 9 )

Calculates the Signal line of MACD indicator.

StochDreturns ARRAY

StochD( periods = 14, Ksmooth =3, Dsmooth =3 )

Calculates the %D line of Stochastic Oscillator (with internal slowing KSmooth, DSmooth).

StochKreturns ARRAY

StochK( periods = 14, ksmooth =3 )

Calculates the %K line of Stochastic Oscillator (with internal slowing KSmooth).

Information / Categories

CategoryAddSymbolreturns NOTHINGAFL 2.5

CategoryAddSymbol( symbol , category , number )

The CategoryAddSymbol function adds the symbol to given category, note that for markets, groups, industries 'adding' means moving from one category to another, since the symbol is assigned always to one and only one market, group, industry and sector. This limitation does not apply to watchlists, favorites, and index categories. When symbol string is empty ("") then current symbol is used.

CategoryGetNamereturns STRINGAFL 2.5

CategoryGetName( category , number )

The CategoryGetName function retrieves the name of category. category is one of the following: categoryMarket categoryGroup categorySector categoryIndustry categoryWatchlist categoryFavorite categoryIndex categoryGICS categoryICB number is a market/group/industry/sector/watchlist number: 0..255 for categoryMarket, categoryGroup, categoryIndustry 0..63 for categorySector no limit for categoryWatchlist.

CategoryGetSymbolsreturns STRINGAFL 2.5

CategoryGetSymbols( category, index, mode = 0 )

Retrieves comma-separated list of symbols belonging to given category Supported categories: categoryMarket categoryGroup categorySector categoryIndustry categoryWatchlist categoryFavorite categoryIndex

GetDatabaseNamereturns STRINGAFL 2.3

GetDatabaseName()

retrieves the name of the database - the last part (folder) of the database path

GroupIDreturns NUMBER/STRINGAFL 1.8

GroupID( mode = 0 )

Retrieves current stock group ID/name When mode = 0 (the default value ) this function returns numerical group ID (consecutive group number) When mode = 1 this function returns name of the group.

IndustryIDreturns NUMBER/STRINGAFL 1.8

IndustryID( mode = 0 )

Retrieves current stock industry ID/name When mode = 0 (the default value ) this function returns numerical industry ID (consecutive industry number) When mode = 1 this function returns name of the industry.

InGICSreturns NUMBERAFL 3.40

InGICS( "gics_code" )

The function performs yes/no test if current symbol belongs to given GICS category for example if GICS set for the symbol is 15103020 InGics("15"), InGICS("1510"), InGics("151030") and InGics("15103020") will ALL return true but all others (like InGics("20")) will return false.

InICBreturns NUMBERAFL 3.60

InICB(''icb_code'')

The function performs yes/no test if current symbol belongs to given ICB category for example if ICB set for the symbol is 9537, InICB("9000"), InICB("9500"), InICB("9530") and InICB("9537") will ALL return true but all others (like InICB("5000")) will return false.

InWatchListreturns NUMBER

InWatchList( listno )

Checks if the stock belongs to a watch list number listno . If yes - the function returns 1 otherwise 0.

InWatchListNamereturns NUMBERAFL 3.0

InWatchListName( ''name'' )

Checks if the stock belongs to a watch list number "listname" . If yes - the function returns 1 otherwise 0.

MarketIDreturns NUMBER/STRINGAFL 1.8

MarketID( mode = 0 )

Retrieves current stock market ID/name When mode = 0 (the default value ) this function returns numerical marketID (consecutive market number) When mode = 1 this function returns name of the market.

SectorIDreturns NUMBER/STRINGAFL 1.8

SectorID( mode = 0 )

Retrieves current stock sector ID/name When mode = 0 (the default value ) this function returns numerical sector ID (consecutive sector number) When mode = 1 this function returns name of the sector.

Low-level graphics

GfxSelectFontreturns NOTHINGAFL 3.0

GfxSelectFont( ''facename'', pointsize, weight = fontNormal, italic = False, underline = False, orientation = 0 )

Initializes a font with the specified characteristics. Then selects the the as current for subsequent drawing operations. Parameters: "facename" - specifies the typeface name of the font pointsize - specifies point size of the font (fractional numbers are allowed), for example 11.5 gives 11.5 point font. weight - specifies the font weight (in inked pixels per 1000).

GfxSetOverlayModereturns NOTHINGAFL 3.0

GfxSetOverlayMode( mode = 0 )

Sets overlay mode for low-level graphics. Parameters: mode - desired overlay mode. Possible values are: 0 - (default) low-level graphic is overlaid on top of charts 1 - charts are overlaid on top of low-level graphics 2 - only low-level graphics is displayed (no charts, no grids, etc) To learn more about low level graphics please read Tutorial: Using low-level graphics

GfxTextOutreturns NOTHINGAFL 3.0

GfxTextOut( ''text'', x, y )

Writes a character string at the specified location using the currently selected font. Parameters: "text" - Specifies the character string to be drawn x - Specifies the x-coordinate of the starting point of the text y - Specifies the y-coordinate of the starting point of the text Character origins are at the upper-left corner of the character cell.

Lowest/Highest

HHVreturns ARRAY

hhv( ARRAY, periods )

Calculates the highest value in the ARRAY over the preceding periods ( periods includes the current day). HHV accepts periods parameter that can be constant as well as time-variant (array).

HHVBarsreturns ARRAY

HHVBars( ARRAY, periods )

Calculates the number of periods that have passed since the ARRAY reached its periods period peak. HHVBars accepts periods parameter that can be constant as well as time-variant (array).

LLVBarsreturns ARRAY

LLVBars( ARRAY, periods )

Calculates the number of periods that have passed since the ARRAY reached its periods period trough. The function accepts periods parameter that can be constant as well as time-variant (array).

Math functions

EXPreturns NUMBER,

exp ( NUMBER ) exp ( ARRAY )

Math functions SYNTAX exp ( NUMBER ) exp ( ARRAY ) RETURNS NUMBER, ARRAY FUNCTION Calculates e raised to the NUMBER or ARRAY power.

floorreturns NUMBER,

floor ( NUMBER ) floor ( ARRAY )

Calculates the highest integer that is less than NUMBER or ARRAY.

Intreturns NUMBER

Int( NUMBER ) int( ARRAY )

Removes the fractional portion of NUMBER or ARRAY and returns the integer part.

logreturns NUMBER

log( NUMBER ) log( ARRAY )

Calculates the natural logarithm of NUMBER or ARRAY.

SafeDividereturns NUMBERAFL 4.40

SafeDivide( x, y, valueifzerodiv )

Safe division that handles division by zero using special handling (replace result with user-defined value) Parameters: x - dividend y - divisor valyeifzerodiv - the value that is returned by the function if divisor (y) is equal zero The function returns the value of x / y ( x divided by y ) as long as y != 0. If y == 0 the value specified in valyeifzerodiv argument is returned.

signreturns ARRAYAFL 2.50

sign( x )

Sign function returns 1 if x value is greater than zero, -1 if the x is less than zero and 0 if x equals zero. x can be a number or array.

sqrtreturns NUMBER,

sqrt( NUMBER ) sqrt( ARRAY )

Calculates the square root of NUMBER or ARRAY. The square root of a negative number always returns a zero result.

Matrix functions

Matrixreturns MatrixAFL 4.0

Matrix( rows, cols, initvalue, increment = 0 )

The function creates a new matrix of user specified dimensions with all elements filled with initvalue. An optional parameter 'increment' that allows to create a matrix with monotonically increasing elements. To create a matrix use my_var_name = Matrix( rows, cols, initvalue) To access matrix elements, use: my_var_name[ row ][ col ] where row is a row index (0... number of rows-1) and col is a column index (0...

MxCopyreturns NOTHINGAFL 4.40

MxCopy( & dstmatrix, src_matrix, dst_start_row, dst_endrow, dst_start_col, dst_end_col, src_start_row = -1, src_end_row = -1, src_start_col = -1, src_end_col = -1 )

Copy rectangular block from one matrix to the other (copy portions of one matrix to the other matrix) The function works in-place (ie. no allocation occurs - first argument is a reference to existing a

MxDetreturns NUMBERAFL 4.10

MxDet( mx, method = 0 )

The function calculates determinant of the matrix method = 0 - auto (use slow method for matrices of upto and including 5x5, fast for larger matrices) method = 1 - slow (Laplace expansion method, more

MxFromStringreturns MatrixAFL 4.10

MxFromString(''string'')

creates a new matrix out of string in Mathematica/Wolfram list-style: "{ { 1, 2, 3 }, { 4, 5, 6 } }", or Matlab/Maple style "[ [ 1, 2, 3 ], [ 4, 5, 6 ] ]", or GNU Octave comma-semicolon style [ 1, 2, 3; 4, 5, 6 ]

MxGetBlockreturns MatrixAFL 4.10

MxGetBlock( matrix, startrow, endrow, startcol, endcol, asArray = False )

Retrieves items from rectangular submatrix (block) and returns either smaller matrix (when asArray is set to False) or "normal" AFL array (when asArray is set to True). If array has different number of bars, unused elements are filled with Null.

MxGetSizereturns NumberAFL 4.0

MxGetSize( matrix, dim )

The function retrieves the matrix size in given dimension. matrix is the matrix variable to query for size dim is the dimension to query - 0 means rows, 1 means columns

MxIdentityreturns MatrixAFL 4.0

MxIdentity( size )

The function creates an identity matrix of defined size (square matrix with rows and columns equal to size argument filled with ones on the main diagonal and zeros elsewhere).

MxInversereturns MatrixAFL 4.10

MxInverse( mx )

The function calculates inverse of the matrix. Matrix can only be inverted if it is not singular, i.e. when its determinant is not equal zero. Inverse matrix can be used for example to solve linear equation system, but it is faster and slightly more accurate to use MxSolve for this purpose. For more info on usage of inverse matrices see MxSolve documentation.

MxSetBlockreturns MatrixAFL 4.10

MxSetBlock( matrix, startrow, endrow, startcol, endcol, values = 0 )

Sets values in the rectangular block of cells (rows in the range startrow..endrow and columns in the range startcol..endcol inclusive). This allows to fill entire or partial rows, columns and all other kind of rectangular areas in the matrix with user specified data. Row and column numbers are zero based. If values parameter is scalar, all cells in specified block are filled with that value.

MxSolvereturns MatrixAFL 4.10

MxSolve( A, B )

The function solves linear equation system A@X = B. A needs to be square matrix NxN B has to have N rows and at least one column (vertical vector). Then calling X = MxSolve( A, B ); would give vertical vector holding solution of the system of equations A @ X = B B can also be a matrix,with each of its column representing different vector B.

MxSortreturns MatrixAFL 4.10

MxSort( mx, dim = -1, ascening = True )

Sorts all items in a matrix When dim == -1 (the default) it would sort: a row if there is only one row (vector is horizontal) a column if there is only one column (vector is vertical) each column separately if there are more rows and columns than one (so we have actual 2D matrix). When dim == 0 the function sorts the items in each row separately When dim == 1 the function sorts the items in each column separately

MxSortRowsreturns MatrixAFL 4.10

MxSortRows( mx, ascending = True, col1 = 0, col2 = -1, col3 = -1 )

Sorts the rows of the matrix in ascending/descending order of the col1 column. When the col1 column has equal values, SortRows sorts according to the col2 and col3 columns in succession (if col2 and col3 are specified and >= 0 ).Column numbers are zero based. Hint: if you want to sort columns instead you can Transpose/Sort rows/Transpose back.

MxSumreturns NUMBERAFL 4.20

MxSum( matrix )

The function calculates sum of all elements of matrix (grand sum)

MxToStringreturns StringAFL 4.10

MxToString( mx )

Creates string out of matrix variable in the Wolfram list style like this (for 3x3 matrix): "{ { x00, x01, x02 }, { x10, x11, x12 }, { x20, x21, x22 } }"

MxTransposereturns MatrixAFL 4.0

MxTranspose( matrix )

The function creates a transpose of an input matrix matrix. Transpose of a matrix is a new matrix whose rows are the columns of the original.

Miscellaneous functions

_TRACEreturns NOTHINGAFL 2.4

_TRACE(''string'')

Write debug messages from AFL code to system debug viewer (it calls internally OutputDebugString Win API function) or to internal Log window (Window->Log) To view debug messages sent to system debugger

_TRACEFreturns NOTHINGAFL 4.0

_TRACEF(''format string'', arg1, .... )

This function is the same as _TRACE but the very first argument is printf-style formatting string and it allows to output formatted numbers like combination of _TRACE and StrFormat. The function writes

ColorHSBreturns NUMBERAFL 2.80

ColorHSB( hue, saturation, brightness )

The function allows to specify color out of 16 million color (24 bit) palette using Hue, Saturation and Brightness parameters. The return value is a number that can be used in Plot, PlotOHLC, PlotForeign, AddColumn, AddTextColumn functions to specify chart or column color.

ColorRGBreturns NUMBERAFL 2.80

ColorRGB( red, green, blue )

The function allows to specify color out of 16 million color (24 bit) palette using Red, Green, Blue components. The return value is a number that can be used in Plot, PlotOHLC, PlotForeign, AddColumn, AddTextColumn functions to specify chart or column color.

GetFormulaPathreturns STRINGAFL 3.90

GetFormulaPath()

The function returns full file path of current formula

GetPerformanceCounterreturns NUMBERAFL 2.90

GetPerformanceCounter( bReset = False )

GetPerformanceCounter retrieves the current value of the high-resolution performance counter. Returned value is in milliseconds. Resolution is upto 0.001 ms (1 microsecond). The value of high-resolution counter represents number of milliseconds from either system start (boot) or from last counter reset. To reset the counter you need to call GetPerformanceCounter function with bReset parameter set to True.

GetRTDatareturns NUMBERAFL 2.60

GetRTData(''fieldname'')

Retrieves the LAST (the most recent) value of the following fields reported by streaming real time data source: "Ask" - current best ask price "AskSize " - current ask size "Bid" - current best bid pri

GetRTDataForeignreturns NUMBERAFL 2.80

GetRTDataForeign( ''fieldname'' , ''symbol'' )

This function is similar to GetRTData but allows to specify symbol OTHER than currently selected and it is much faster than SetForeign/GetRTData combo. The function retrieves the LAST (the most recent)

IsEmptyreturns ARRAYAFL 1.5

IsEmpty( ARRAY )

returns 1 (or 'true') when given point in array is {empty} Note: {empty} value is used internaly by AFL to mark bars when the value is not available - for example for the first 20 bars the value of 20-day simple moving average is not available ({empty}) IsNull is a synonym for IsEmpty. It is suggested to use IsNull in new formulas, because of naming consistency with Null constant.

IsNullreturns NUMBER,AFL 2.3

IsNull( x )

this function is synonym of IsEmpty(). Gives True if value is equal to Null (empty) value.

NullCountreturns NUMBERAFL 3.90

NullCount( array, mode = 1 )

Counts the number of consecutive nulls at the beginning of the array (mode = 1), at the end of the array (mode=2), from both ends (mode=3) and all nulls in the array (including non-consecutive) (mode=0)

Nzreturns NUMBER,AFL 2.3

Nz( x, valueifnull = 0 )

Converts Null/Nan/Infinity values to zero (or user defined value) x can be number or array. You can use the Nz function to return zero, or another specified value when argument x is Null or Nan or Infinite. For example, you can use this function to convert a Null (empty) value to another value and prevent it from propagating through an expression.

PlaySoundreturns NUMBERAFL 3.40

PlaySound( "filename" )

The function plays back specified .WAV file. Returns 1 on success, 0 on failure

SendEmailreturns NOTHINGAFL 3.90

SendEmail(''subject'', ''message'', ShowUI = False )

Send an e-mail to an address defined in the Preferences/Alert page. A direct version of functionality already provided by AlertIF. This function sends e-mail unconditionally and it is easier to use if you don't need state logic provided by AlertIf. Note that "From" and "To" addresses as well as SMTP email configuration should be done in Tools->Preferences, "Alerts" page.

SetBarsRequiredreturns nothingAFL 2.1

SetBarsRequired( backwardref = -1, forwardref = -1 )

set number of previous and future bars needed for script/DLL to properly execute. If your formula is pure AFL you don't need to use this function at all, as AmiBroker automatically calculates number of bars required for all its built-in functions. But if you are using script or a DLL you may need to use this function to make sure that your indicators are properly calculated in QuickAFL mode.

StaticVarAddreturns NOTHINGAFL 4.10

StaticVarAdd( "name", value, keepAll = True, persistent = False )

StaticVarAdd implements an atomic addition (interlocked read-add-write) operation for static variables. It is multithreading safe addition for static variables that are shared by multiple threads. This function is atomic with respect to calls to other static variable functions. KeepAll flag when it is set to true emulates the behavior of AddToComposite.

StaticVarCompareExchangereturns NUMBERAFL 3.50

StaticVarCompareExchange( ''varname'', exchange, comperand )

Parameters: "varname" - Specifies the name of the destination static variable. Static variable if exists must be scalar numeric type. If static variable is not initialized, the function assumes that it has value of zero. exchange - specifies the exchange value. Scalar numeric. comperand - specifies the value to compare to the destination static variable. Scalar numeric.

StaticVarCountreturns NUMBERAFL 3.30

StaticVarCount()

the function returns total number of static variables in memory

StaticVarGenerateRanksreturns NOTHINGAFL 3.70

StaticVarGenerateRanks( "outputprefix", "inputprefix", topranks, tiemode )

The function implements general-purpose multiple symbol bar-by-bar ranking. StaticVarGenarateRanks( "outputprefix", "inputprefix", topranks, tiemode ) "inputprefix" is a prefix that defines names of static variables that will be used as input for ranking. AmiBroker will search for all static variables that begin with that prefix and assume that remaining part of the variable name is a stock symbol.

StaticVarGetreturns NUMBERAFL 2.60

StaticVarGet( ''varname', align = True' )

Gets the value of static variable. Static variable - the variable has static duration (it is allocated when the program begins and deallocated when the program ends) and initializes it to Null unless another value is specified. Static variables allow to share values between various formulas. ARRAY static variables are now supported (version 5.30 and above).

StaticVarGetRankedSymbolsreturns STRINGAFL 3.70

StaticVarGetRankedSymbols( "outputprefix", "inputprefix", datetime )

Retrieves the comma-separated list of symbols from static variables generated using StaticVarGenerateRanks. For more information see StaticVarGenerateRanks documentation.

StaticVarGetTextreturns STRINGAFL 2.60

StaticVarGetText( ''varname'' )

Gets the value of static variable as string. The only difference between StaticVarGet is that this function always returns string, so if given static variable does not exist it returns empty string "" instead of Null. Numbers are also converted to string.

StaticVarInforeturns STRINGAFL 3.60

StaticVarInfo( ''varname'', ''field'' )

The function provides information about static variables. Arguments: "varname" - is a variable name. It can be also a wildcard template such as "myvariable*" and then it means that AmiBroker will search for all variables beginning with " myvariable". * character matches any string, ? matches any single character "field" - defines the information to retrieve.

StaticVarRemovereturns NOTHINGAFL 2.80

StaticVarRemove( ''variablename'' )

This function removes static variable and releases associated memory. With AmiBroker version 5.30, StaticVarRemove() supports wildcards in the variable name. "varname" parameter can be either exact variable name or wildcard match string. The '*' matches any number of characters, including zero characters. The '?' matches exactly one character.

StaticVarSetreturns NUMBERAFL 2.60

StaticVarSet( ''varname'', value, persistent = False, compressionMode = cmDefault )

Sets the value of static variable. Returns 1 on success 0 on failure. Static variable - the variable has static duration (it is allocated when the program begins and deallocated when the program ends) and initializes it to Null unless another value is specified. Static variables allow to share values between various formulas.

StaticVarSetTextAFL 2.60

StaticVarSetText( ''varname'', ''value'', persist = False )

Sets the value of static string variable. Returns 1 on success 0 on failure. Static variable - the variable has static duration (it is allocated when the program begins and deallocated when the program ends) and initializes it to Null unless another value is specified. Static variables allow to share values between various formulas. Starting from version 5.80 there is a new parameter 'persist'.

Statusreturns NUMBERAFL 1.65

status( ''statuscode'' )

Returns run-time status of the analysis engine. Supported status codes: "stocknum" - gives you the ordinal number of currently analysed symbol "action" - gives information in what context given formula is run: 1 - actionIndicator (INDICATOR), 2 - actionCommentary (COMMENTARY), 3 - actionScan (SCAN), 4 - actionExplore (EXPLORATION), 5 - actionBacktest (BACKTEST / OPTIMIZE), 6 - actionPortfolio (portfolio backtest).

Studyreturns ARRAYAFL 1.5

Study( STUDYID, CHARTID = 1, scale = -1 )

generates an array equivalent to a trendline study drawn by the user - allows detecting trendline breakouts from AFL. STUDYID is a two-character identifier of the study. identifiers are: "UP" - uptrend, "DN" - downtrend, "SU" - support, "RE" - resistance, "ST" - stop loss, however you can use ANY identifiers (there are no limitations except that AmiBroker accepts only 2 letter codes).

ThreadSleepreturns NOTHINGAFL 3.50

ThreadSleep( milliseconds )

ThreadSleep( milliseconds ) suspends current thread for specified number of milliseconds (maximum is 100 ms). Works only from NON-UI threads. When called from UI thread the function does NOTHING and returns immediatelly. Please do NOT abuse this function. Using it may negatively impact performance. The function is provided for advanced users to implement inter-thread synchronization.

VarGetreturns ARRAYAFL 2.60

VarGet( ''varname'' )

Gets the value of dynamic variable. Returns the NUMBER or ARRAY depending on type of underlying variable. Dynamic variables are variables that are named dynamically, typically by creating a variable name from a static part and a variable part. For example, the following example dynamically constructs the variable name from a variable prefix and a static suffix. Dynamic variables are always global.

VarGetTextreturns STRINGAFL 2.80

VarGetText( ''varname'' )

Gets the text (string) value of dynamic variable. Similar to VarGet but always returns always string values (if underlying variable has different type it is converted to string) Allows for example appe

VarSetreturns NUMBERAFL 2.60

VarSet( ''varname'', value )

Sets the value of dynamic variable. Returns 1 on success, 0 on failure. Dynamic variables are variables that are named dynamically, typically by creating a variable name from a static part and a variable part. The following example dynamically constructs the variable name from a variable prefix and a static suffix. Dynamic variables are always global.

VarSetTextreturns STRINGAFL 2.80

VarSetText( ''varname'', ''valuetext'' )

Sets the text (string) value of dynamic variable. Similar to VarSet but allows to assign string (text) instead of number/array. Dynamic variables are variables that are named dynamically, typically by creating a variable name from a static part and a variable part. For example, the following example dynamically constructs the variable name from a variable prefix and a static suffix.

Versionreturns NUMBERAFL 1.9

Version( minrequired = 0)

Returns the AmiBroker version number as float ( 3.90 for example ). Additionally when you specify Version( 4.0 ) AmiBroker will issue an error message when running the formula on AB earlier than 4.0 :)

Moving averages, summation

AMAreturns ARRAYAFL 1.5

ama ( ARRAY, SMOOTHINGFACTOR )

calculates adaptive moving average - simliar to EMA() but smoothing factor could be time-variant (array).

Cumreturns ARRAY

Cum( ARRAY ) Cum( Value )

Calculates a cumulative sum of the ARRAY from the first period in the chart. Note: Starting from AmiBroker 5.30, the Cum() function does NOT force using all bars. In the past versions Cum() functions effectively turned OFF QuickAFL feature by requesting all bars to be processed. Since Cum() function was popular it caused that many legacy formulas that used it were not benefiting from QuickAFL.

DEMAreturns ARRAYAFL 2.0

dema( ARRAY, periods )

Calculates double exponentially smoothed average - DEMA. The function accepts time-variable periods.

MAreturns ARRAY

ma( ARRAY, periods )

Calculates a periods simple moving average of ARRAY The function accepts periods parameter that can be constant as well as time-variant (array).

Sumreturns ARRAY

Sum( ARRAY, periods )

Calculates a cumulative sum of the ARRAY for the specified number of lookback periods (including today). The function accepts periods parameter that can be constant as well as time-variant (array).

SumSincereturns ArrayAFL 4.10

SumSince( condition, array, incFirst = False )

The function calculates running sum of array elements since condition was true. It works like: x = Cum ( array ) - ValueWhen ( condition, Cum ( array ) ); or like: x = Sum ( array, BarsSince ( condition ) ); but much faster. When incFirst is set to True, the sum includes the very first value at the bar when condition was true.

TEMAreturns ARRAYAFL 2.0

tema( ARRAY, periods )

Calculates triple exponentially smoothed average - TEMA. The function accepts time-variable periods.

Wildersreturns ARRAYAFL 1.4

Wilders( ARRAY, periods )

Calculates Wilder's average of the ARRAY using periods averaging range

WMAreturns ARRAYAFL 2.0

wma( ARRAY, periods )

Calculates weighted average. 5 day weighted average gives weight of 5 to the most recent quote, 4 to the previous quote, downto 1 for the 5-bar back quote. The function accepts time-variable periods.

Referencing other symbol data

Foreignreturns ARRAYAFL 1.5

foreign ( TICKER, DATAFIELD, fixup = 1)

Allows referencing other (than current) tickers in the AFL formulas. TICKER is a string that holds the symbol of the stock. DATAFIELD defines which array is referenced. Allowable data fields: "O" (open

GetBaseIndexreturns STRINGAFL 2.1

GetBaseIndex( )

Retrieves base relative-strength index for given security as defined in Symbol->Categories.

PlotForeignreturns NUMBERAFL 2.2

PlotForeign( tickersymbol , name , color/barcolor , style = styleCandle styleOwnScale , minvalue = {empty}, maxvalue = {empty}, XShift = 0, ZOrder = 0, width = 1 )

Plots the foreign-symbol price chart (symbol is defined by tickersymbol parameter). Second argument name defines graph name used for displaying values in a title bar. Graph color could be static (if third argument is a number) or dynamic (when third argument is an array).

RelStrengthreturns ARRAYAFL 1.3

RelStrength( "tickername", fixup = 1)

Calculates relative strength of currently selected security compared to "tickername" security. When you give an empty string as argument, a standard relative strength base security taken from Stock->Categories will be used.

RestorePriceArraysreturns NOTHINGAFL 2.5

RestorePriceArrays( tradeprices = False )

The RestorePriceArrays restores original price and volume arrays after the call to SetForeign . tradeprices parameter has to match the one used in SetForeign() function. When tradeprices argument is set to TRUE, then not only OHLC, V, OI, Avg arrays are restored, but BuyPrice, SellPrice, ShortPrice, CoverPrice, PointValue, TickSize, RoundLotSize, MarginDeposit variables too.

SetForeignreturns NUMBERAFL 2.5

SetForeign( ticker, fixup = True, tradeprices = False )

The SetForeign function replaces current price/volume arrays with those of foreign security, returns True (1) if ticker exists, False (0) otherwise. If ticker does not exist (and function returns false) price arrays are not changed at all. fixup parameter controls if data holes are filled with previous bar data or not.

Statistical functions

Correlationreturns ARRAYAFL 1.4

correlation( ARRAY1, ARRAY2, periods )

Calculates correlation between ARRAY1 and ARRAY2 using periods range For more information about correlation please check this: http://en.wikipedia.org/wiki/Correlation

LinearRegreturns ARRAYAFL 2.2

LinearReg( ARRAY, periods )

Calculates linear regression line end-point value according to a + b * x (where a and b are intercept and slope of linear regression line) from the ARRAY using periods range. The function accepts periods parameter that can be constant as well as time-variant (array).

LinRegSlopereturns ARRAYAFL 1.4

LinRegSlope( ARRAY, periods )

Calculates linear regression line slope from the ARRAY using periods range. The function accepts periods parameter that can be constant as well as time-variant (array).

Medianreturns ARRAYAFL 2.5

Median( array, period )

The Median function - finds median (middle element) value of the array over period elements. Note that LOWER median is returned when 'period' is an even number. If you want to get average of upper and lower median for even 'periods' you need to use Percentile( array, period, 50 ) instead. It will do the averaging for you but runs slower.

mtRandomreturns NUMBERAFL 3.0

mtRandom( seed = Null ) mtRandomA( seed = Null )

mtRandom( seed = Null ) - returns single random number (scalar) in the range [0,1) mtRandomA( seed = Null ) - returns array of random numbers in the range of [0,1) seed is random generator seed value. If you don't specify one, the random number generator is automatically initialized with current time as a seed that guarantees unique sequence Both functions use Mersene Twister mt19973ar-cok algorithm.

mtRandomAreturns ARRAYAFL 3.0

mtRandomA( seed = Null )

This is array version of mtRandom function For more details please check mtRandom function.

Percentilereturns ARRAYAFL 2.5

Percentile( array, period, rank )

The Percentile function gives rank percentile value of the array over last period bars. rank is 0..100 - defines percentile rank in the array Performance note: the implementation of percentile function involves sorting that is relatively slow process even though that quicksort algorithm is used. Since version 5.92 Percentile supports variable period.

StDevreturns ARRAYAFL 1.4

StDev( ARRAY, periods , Population = True )

Calculates moving standard deviation of the ARRAY over periods bars AmiBroker 6.20 adds 3rd argument "Population = True". When Population is True it calculates population based stdev, otherwise sample based StDev( Array, range, False ) - works the same as Excel's STDEV StDev( Array, range, True ) - works the same as Excel's STDEV.P

String manipulation

printfreturns NOTHINGAFL 2.5

printf( formatstr , ... )

The printf function formats and prints a series of characters and values to the output window, which can be either commentary or interpretation window. If arguments follow the format string, the format string must contain specifications that determine the output format for the arguments.

StrCountreturns NUMBERAFL 3.20

StrCount( ''string'', ''substring'' )

Function returns integer which is number of times substring was found in string. It is case sensitive. The function can be used for example to count the number of commas in comma-separated list

StrExtractreturns STRINGAFL 2.4

StrExtract( list, item, separator = ',' )

Extracts given item (substring) from comma-separated list of items. item is a zero-based index of the item in the list (see also note below). If no substring at given index is found then empty string is returned (""). Useful to retrive symbols from the list obtained via GetCategorySymbols function.

StrFormatreturns STRINGAFL 2.5

StrFormat( formatstr, ... )

The StrFormat function formats and returns a series of characters and values in the result string. If arguments follow the format string, the format string must contain specifications that determine the output format for the arguments. StrFormat and printf behave identically except that printf writes output to the window, while StrFormat does not write anything to output window but returns resulting string instead.

StrLeftreturns STRINGAFL 2.0

strleft ( STRING, count )

Extracts the first (that is, leftmost) count characters from STRING and returns a copy of the extracted substring. If count exceeds the string length, then the entire string is extracted.

Time Frame functions

TimeFrameCompressreturns ARRAYAFL 2.5

TimeFrameCompress( array, interval, mode = compressLast )

The TimeFrameCompress function compresses single array to given interval using given compression mode available modes: compressLast - last (close) value of the array within interval compressOpen - open

TimeFrameExpandreturns ARRAYAFL 2.5

TimeFrameExpand( array, interval, mode = expandLast )

The TimeFrameExpand function expands time-compressed array from interval time frame to base time frame ( interval parameter must match the value used in TimeFrameCompress or TimeFrameSet ) The TimeFrameExpand is used to decompress array variables that were created in different time frame. Decompressing is required to properly display the array created in different time frame.

TimeFrameGetPricereturns ARRAYAFL 2.5

TimeFrameGetPrice( pricefield, interval, shift = 0, mode = expandFirst )

The TimeFrameGetPrice - retrieves OHLCV fields from other time frames. This works immediatelly without need to call TimeFrameSet at all. First parameter - pricefield - is one of the following: "O", "H", "L", "C", "V", "I" (open interest). Interval is bar interval in seconds. You can use pre-defined interval constants: in1Minute, in5Minute, in15Minute, inHourly, inDaily, inWeekly, inMonthly.

TimeFrameRestorereturns NOTHINGAFL 2.5

TimeFrameRestore( tradeprices = False )

The TimeFrameRestore function restores price arrays replaced by TimeFrameSet . Note that only OHLC, V, OI and Avg built-in variables are restored to original time frame when you call TimeFrameRestore() . All other variables created when being in different time frame remain compressed. To de-compress them to original interval you have to use TimeFrameExpand . Tradeprice argument should be set to false.

TimeFrameSetreturns NOTHINGAFL 2.5

TimeFrameSet( interval )

The TimeFrameSet replaces current price/volume arrays: open, high, low, close, volume, openint, avg with time-compressed bars of specified interval once you switched to a different time frame all calculations and built-in indicators operate on selected time frame. To get back to original interval call TimeFrameRestore() function.

Trading system toolbox

AlertIfreturns nothingAFL 2.1

AlertIf( BOOLEAN_EXPRESSION , command , text , type = 0, flags = 1+2+4+8, lookback = 1 );

Triggers alert action if BOOLEAN_EXPRESSION is true. 1. BOOLEAN_EXPRESSION is the expression that if evaluates to True (non zero value) triggers the alert. If it evaluates to False (zero value) no alert is triggered. Please note that only lookback most recent bars are considered. 2. The command string defines the action taken when alert is triggered.

Crossreturns ARRAY

Cross( ARRAY1, ARRAY2 )

Gives a "1" or true on the day that ARRAY1 crosses above ARRAY2. Otherwise the result is "0". To find out when ARRAY1 crosses below ARRAY2, use the formula cross(ARRAY2, ARRAY1)

EnableRotationalTradingreturns NOTHINGAFL 2.5

EnableRotationalTrading()

When placed on the top of system formula it turns on rotational-trading (aka. fund-switching) mode of the backtester. Note: this function is now marked as obsolete. Use SetBacktestMode( backtestRotational ) in new formulas. IMPORTANT NOTE: Unless you specifically want to implement fund-switching/rotational trading system you should NOT use this mode. Rotational trading is popular method for trading mutual funds.

Equityreturns ARRAYAFL 2.0

equity ( Flags = 0, RangeType = -1, From = 0, To = 0 )

NOTE: This function is left here for backward compatibility and is using old, single-security backtester. New coding should rather use portfolio-level equity (special ~~~EQUITY ticker). Function: Returns single-security Equity line based on buy/sell/short/cover rules, buy/sell/short/coverprice arrays, all apply stops, and all other backtester settings.

ExRemSpanreturns ARRAYAFL 2.0

exremspan ( ARRAY1, numbars )

Removes excessive signals that span numbars bars since initial signal. (In other words first non-zero bar passes through, then all subsequent non-zero bars are ignored (zero is returned) until numbars bars have passed since initial signal. From then on a new signal may pass through) This function is marked as obsolete. To implement N-bar stop you should use ApplyStop function instead.

Flipreturns ARRAYAFL 1.5

flip ( ARRAY1, ARRAY2 )

works as a flip/flop device or "latch" (electronic/electric engineers will know what I mean) returns 1 from the first occurence of "true" signal in Array1 until a "true" occurs in Array2 which resets the state back to zero unil next "true" is detected in Array1...

GetBacktesterObjectreturns OBJECTAFL 2.60

GetBacktesterObject()

This funciton is used in custom backtester procedures to get the access to backtester object. Note that GetBacktester method should only be called when Status("action") returns actionPortfolio. For more details please read Custom Backtester documentation

GetOptionreturns NUMBERAFL 2.60

GetOption(''fieldname'')

Gets the value of various options in automatic analysis settings. field - is a string that defines the option to read. There are following options available: "NoDefaultColumns" - if set to True - explo

GetTradingInterfacereturns OBJECTAFL 2.70

GetTradingInterface(

Retrieves OLE automation object to automatic trading interface. "Name" is the interface name. You have to have trading interface installed separately to make it work otherwise you will get the error message attempting to use this function. Trading interface for Interactive Brokers is available from download section: http://www.amibroker.com/download.html

IIfreturns ARRAY

IIf( EXPRESSION, TRUE_PART, FALSE_PART )

Trading system toolbox SYNTAX IIf( EXPRESSION, TRUE_PART, FALSE_PART ) RETURNS ARRAY or NUMBER FUNCTION "Immediate-IF" - a conditional function that returns the value of the second parameter (TRUE_PART) if the conditional expression defined by the first parameter (EXPRESSION) is true; otherwise, the value of third parameter is returned (FALSE_PART).

LastValuereturns NUMBER

LastValue(ARRAY, lastmode = True )

Returns last calculated value of the specified ARRAY. The result of this function can be used in place of a constant (NUMBER) in any function argument. If last bar of the ARRAY is undefined or Null (e.g., only 100-days loaded and you request the last value of a 200-day moving average) then the lastvalue function returns zero.

OptimizerSetEnginereturns NOTHINGAFL 3.20

OptimizerSetEngine( "name" )

The function selects external optimization engine defined by name. The following optimization engines are shipped with AmiBroker as of version 5.20 Standard Particle Swarm Optimizer ("spso") Tribes (improved PSO) ("trib") Covariance Matrix Adaptation Evolutionary Strategy ("cmae") New engines may be added in the future.

OptimizerSetOptionreturns NOTHINGAFL 3.20

OptimizerSetOption("name", value )

The function set additional parameters for external optimization engine. The parameters are engine-dependent. For example SPSO, TRIBES and CMAE optimizers support "Runs" (number of runs) and "MaxEval" (maximum evaluations (tests)per single run) parameters.

Refreturns ARRAY

Ref( ARRAY, period )

References a previous or subsequent element in a ARRAY. A positive period references "n" periods in the future; a negative period references "n" periods ago. The function accepts periods parameter that can be constant as well as time-variant (array).

SetCustomBacktestProcreturns NOTHINGAFL 2.70

SetCustomBacktestProc( filename, enable = True )

This function allows changing custom backtest procedure file from AFL formula level. To learn more about custom backtester procedures please read this document . Parameters filename parameter instructs

SetOptionreturns NOTHINGAFL 2.3

SetOption( field, value )

Sets various options in automatic analysis settings. Affects also Equity() function results. field - is a string that defines the option to change. There are following options available: "NoDefaultColu

SetPositionSizereturns ARRAYAFL 2.70

SetPositionSize( size, method )

This function allows to control trade (position) size in four different ways, depending on 'method' parameter. Parameters: size (ARRAY) defines desired trade size method (ARRAY) defines how 'size' is i

SetTradeDelaysreturns nothingAFL 2.1

SetTradeDelays( buydelay, selldelay, shortdelay, coverdelay )

Sets trade delays applied by the backtester. This function allows you to override trade delays from the "Settings" page. It is important do understand what trade delays really do. They in fact internal

ValueWhenreturns ARRAYAFL 1.1

ValueWhen(EXPRESSION, ARRAY, n = 1)

Returns the value of the ARRAY when the EXPRESSION was true on the n -th most recent occurrence. Note: this function allows also 0 and negative values for n - this enables referencing future

Sources for this lesson

2 verified · checked 2026-08-31

  1. 01AmiBroker AFL Function Referenceamibroker.com/guide/a_funref.html2026-08-31
  2. 02AmiBroker AFL Function Reference by categoryamibroker.com/guide/a_catfunref.html2026-08-31

Every technical claim on this page was checked against the official AmiBroker documentation on the date shown. Where the course disagrees with folklore, the source is how you can tell which one to trust.