AFL Function Reference
How this page is built
Section titled “How this page is built”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.
Using it
Section titled “Using it”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 ARRAYGapDown()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.
Taught in:Part 5 — Breakouts, Failed Breakouts and Role ReversalPart 7 — Multi-Bar Candlestick PatternsOfficial documentation
GapUpreturns ARRAYGapUp()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.
Taught in:Part 5 — Breakouts, Failed Breakouts and Role ReversalPart 7 — Multi-Bar Candlestick PatternsOfficial documentation
Insidereturns ARRAYInside()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.
Taught in:Part 5 — Breakouts, Failed Breakouts and Role ReversalPart 5 — Consolidation and Volatility ContractionPart 7 — Multi-Bar Candlestick PatternsOfficial documentation
Outsidereturns ARRAYOutside()Gives "true" (or 1) when an outside day occurs
Taught in:Part 5 — Breakouts, Failed Breakouts and Role ReversalPart 5 — Consolidation and Volatility ContractionPart 7 — Multi-Bar Candlestick PatternsOfficial documentation
Peakreturns ARRAYAFL 1.1Peak(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.
Taught in:Part 4 — Swings, Highs and LowsPart 5 — Trendlines and ChannelsPart 7 — Classic Chart PatternsOfficial documentation
PeakBarsreturns ARRAYAFL 1.1PeakBars(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.
Taught in:Part 7 — Classic Chart PatternsOfficial documentation
PlotTextSetFontreturns NOTHINGAFL 2.80PlotTextSetFont( ''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
Taught in:Part 10 — PlotShapes() and Visual SignalsOfficial documentation
ShellExecutereturns NUMBERAFL 3.40ShellExecute( ''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.
Taught in:Part 25 — Alert Mechanisms and AlertIf()Part 35 — From Candidate to DecisionOfficial documentation
Troughreturns ARRAYAFL 1.1Trough(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.
Taught in:Part 4 — Swings, Highs and LowsPart 5 — Trendlines and ChannelsPart 7 — Classic Chart PatternsOfficial documentation
TroughBarsreturns ARRAYAFL 1.1TroughBars(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.
Taught in:Part 7 — Classic Chart PatternsOfficial documentation
ZIGreturns ARRAYAFL 1.1zig(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.
Taught in:Part 7 — Classic Chart PatternsOfficial documentation
Composites
AddToCompositereturns NOTHINGAFL 2.0AddToComposite( 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.
Taught in:Part 16 — Building Composites with AddToComposite()Part 16 — Project: Market Breadth DashboardPart 30 — Look-Ahead BiasPart 36 — Performance: QuickAFL, Multi-Threading and CostOfficial documentation
ADLinereturns ARRAYAFL 1.2ADLine()Calculates Advance/Decline line indicator
Taught in:Part 16 — Breadth Concepts: Participation and Its MeasuresOfficial documentation
AdvIssuesreturns ARRAYAFL 1.2AdvIssues()Returns the number of advancing issues for a given market (the one that currently analysed stock belongs to)
Taught in:Part 16 — Breadth Concepts: Participation and Its MeasuresOfficial documentation
AdvVolumereturns ARRAYAFL 1.2AdvVolume()Returns the volume of advancing issues for a given market (the one that currently analysed stock belongs to)
Taught in:Part 16 — Breadth Concepts: Participation and Its MeasuresOfficial documentation
DecIssuesreturns ARRAYAFL 1.2DecIssues()Returns the number of declining issues for a given market (the one that currently analysed stock belongs to)
Taught in:Part 16 — Breadth Concepts: Participation and Its MeasuresOfficial documentation
DecVolumereturns ARRAYAFL 1.2DecVolume()Returns the volume of declining issues for a given market (the one that currently analysed stock belongs to)
Taught in:Part 16 — Breadth Concepts: Participation and Its MeasuresOfficial documentation
Trinreturns ARRAYAFL 1.2Trin()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.
Taught in:Part 16 — Breadth Concepts: Participation and Its MeasuresOfficial documentation
UncIssuesreturns ARRAYAFL 1.2UncIssues()Returns the number of unchanged issues for a given market (the one that currently analysed stock belongs to)
Taught in:Part 16 — Breadth Concepts: Participation and Its MeasuresOfficial documentation
UncVolumereturns ARRAYAFL 1.2UncVolume()Returns the volume of unchanged issues for a given market (the one that currently analysed stock belongs to)
Taught in:Part 16 — Breadth Concepts: Participation and Its MeasuresOfficial documentation
Date/Time
BarIndexreturns ARRAYAFL 2.3BarIndex()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.
Taught in:Part 37 — Component 1: Market DashboardPart 37 — Component 5: Real-Time or Replay WorkspacePart 37 — Component 3: ScannerPart 37 — Component 2: Stock ExplorationPart 37 — Component 6: The Trading StrategyPart 5 — Reality Check: Do Support Levels Actually Hold?Part 7 — Reality Check: Can We Test Whether a Pattern Predicted Anything?Part 8 — Errors, Debugging and Sanity ChecksPart 8 — Null Values, Nz() and Warm-Up PeriodsPart 8 — The Array Model: The Most Important Lesson in This CoursePart 9 — Counting and Accumulating: BarsSince, Cum, SumPart 9 — Referencing Past Bars with Ref()Part 9 — ValueWhen(): Carrying a Value ForwardPart 10 — Project: Configurable Moving-Average IndicatorPart 11 — Defensive AFL: Guarding Against Bad Input and Bad DataPart 11 — Project: Your Personal AFL Utility LibraryPart 15 — Benchmarks and Relative PerformancePart 15 — Data Alignment Pitfalls Across SymbolsPart 15 — Project: Relative Strength Comparison ToolPart 16 — Project: Market Breadth DashboardPart 18 — Choosing a Data Source: A Decision FrameworkPart 23 — Knowing Where You Are: Status() and Execution ContextPart 25 — Alert Mechanisms and AlertIf()Part 25 — Duplicate Alerts and How to Stop ThemPart 25 — Project: Real-Time Breakout AlertPart 26 — Replay Exercise: Intraday Setups and AlertsPart 28 — Stops with ApplyStop()Part 30 — Insufficient Evidence and Regime DependencePart 36 — Performance: QuickAFL, Multi-Threading and CostOfficial documentation
BeginValuereturns NUMBERAFL 2.3BeginValue( 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 >
Taught in:Part 3 — Navigating and Scaling ChartsPart 8 — The Array Model: The Most Important Lesson in This CourseOfficial documentation
Datereturns STRINGAFL 1.1date()It is used to display the selected date in commentary / interpretation window
Taught in:Part 3 — Lab: Build Your First AmiBroker WorkspaceOfficial documentation
DateNumreturns ARRAYAFL 1.4datenum()Returns the array with numbers that represent quotation dates coded as follows: 10000 * (year - 1900) + 100 * month + day, so 2001-12-31 becomes 1011231 and 1995-12-31 becomes 951231
Taught in:Part 15 — Benchmarks and Relative PerformancePart 15 — Project: Relative Strength Comparison ToolPart 18 — Choosing a Data Source: A Decision FrameworkPart 18 — Free and End-of-Day Sources with AmiQuotePart 20 — Challenge: The Opening Range That MovedPart 20 — Daylight Saving and Alignment FailuresPart 20 — Exchange Time versus Your ClockPart 20 — Sessions: Regular Hours, Pre-Market and After-HoursPart 30 — Survivorship and Selection BiasPart 32 — In-Sample and Out-of-SampleOfficial documentation
DateTimereturns ARRAYAFL 2.3DateTime()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.
Taught in:Part 37 — Component 5: Real-Time or Replay WorkspacePart 37 — Component 3: ScannerPart 37 — Component 2: Stock ExplorationPart 2 — Data Defects in PracticePart 3 — Importing and Updating Market DataPart 3 — Lab: Install AmiBroker and Verify Your SetupPart 12 — Exploration: Filter, AddColumn and AddTextColumnPart 12 — Exporting Results and Building a Daily WorkflowPart 12 — Reality Check: Do High-Volume Breakouts Lead Anywhere?Part 13 — StaticVarGenerateRanks() and Top-N SelectionPart 17 — Plugins and the Database RelationshipPart 17 — The Real-Time Architecture, End to EndPart 18 — Choosing a Data Source: A Decision FrameworkPart 18 — Free and End-of-Day Sources with AmiQuotePart 18 — Appendix: IQFeedPart 20 — Exchange Time versus Your ClockPart 24 — Repeat Scanning: Mechanics and CostsPart 26 — Bar Replay: Mechanics and Honest LimitsPart 27 — From Rules to AFLPart 30 — Unrealistic Fills, Costs and LiquidityPart 36 — Performance: QuickAFL, Multi-Threading and CostOfficial documentation
DateTimeConvertreturns NUMBERAFL 2.90DateTimeConvert( 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
Taught in:Part 20 — Exchange Time versus Your ClockPart 23 — GetRTData() and the Live Quote FieldsPart 23 — Project: Real-Time Quote DashboardOfficial documentation
DateTimeDiffreturns NUMBERAFL 3.30DateTimeDiff( arg1, arg2 )DateTimeDiff( arg1, arg2 ) which will return positive values if arg1 > arg2 and negative values if arg1 The difference is given in seconds. The function can operate on scalar and array arguments, returning scalar if both inputs are scalars, and array otherwise.
Taught in:Part 2 — Survivorship, Delistings and Index MembershipPart 17 — Plugins and the Database RelationshipPart 17 — The Real-Time Architecture, End to EndPart 19 — Backfill and Database MaintenancePart 19 — Challenge: The History That Is Not All TherePart 19 — Intraday Database Settings in DetailPart 19 — Lab: Build an Intraday Market DatabasePart 20 — Daylight Saving and Alignment FailuresPart 20 — Exchange Time versus Your ClockPart 21 — Challenge: The Chart That Stopped UpdatingPart 21 — Feed Updating versus Chart RefreshPart 22 — Quote Fields and the Real-Time Quote WindowPart 23 — GetRTData() and the Live Quote FieldsPart 23 — Project: Real-Time Quote DashboardPart 24 — Project: Intraday Breakout ScannerPart 24 — Repeat Scanning: Mechanics and CostsPart 35 — The Research Lifecycle End to EndOfficial documentation
DateTimeToStrreturns STRINGAFL 2.8DateTimeToStr( NUMBER, mode = 0 )Converts number representing date/time value (for example obtained using GetCursorXPosition(), Now(), DateTime() functions) to the corresponding STRING (text). The mode parameter defines the output mode: 0 - convert both date and time portion 1 - only date 2 - only time.
Taught in:Part 37 — Component 5: Real-Time or Replay WorkspacePart 10 — Chart Titles and Dynamic TextPart 15 — Data Alignment Pitfalls Across SymbolsPart 17 — The Real-Time Architecture, End to EndPart 18 — Appendix: eSignal and Other Supported FeedsPart 19 — Intraday Database Settings in DetailPart 20 — Exchange Time versus Your ClockPart 21 — Feed Updating versus Chart RefreshPart 25 — Alert Mechanisms and AlertIf()Part 25 — Project: Real-Time Breakout AlertPart 26 — Bar Replay: Mechanics and Honest LimitsPart 36 — Performance: QuickAFL, Multi-Threading and CostOfficial documentation
Dayreturns ARRAYAFL 1.4day()Returns the array with days (1-31)
Taught in:Part 37 — Component 5: Real-Time or Replay WorkspacePart 18 — Choosing a Data Source: A Decision FrameworkPart 25 — Project: Real-Time Breakout AlertOfficial documentation
DaysSince1900returns ARRAYAFL 3.20DaysSince1900()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.
Taught in:Part 3 — Lab: Install AmiBroker and Verify Your SetupOfficial documentation
EndValuereturns NUMBERAFL 2.3EndValue( 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 >
Taught in:Part 3 — Navigating and Scaling ChartsOfficial documentation
GetPlaybackDateTimereturns NUMBERAFL 3.0GetPlaybackDateTime()The function returns bar replay playback position in datetime format, or zero if bar replay is NOT active
Taught in:Part 37 — Component 5: Real-Time or Replay WorkspacePart 17 — The Real-Time Architecture, End to EndPart 18 — Appendix: eSignal and Other Supported FeedsPart 19 — The Base Interval DecisionPart 19 — Intraday Database Settings in DetailPart 19 — Lab: Build an Intraday Market DatabasePart 20 — Exchange Time versus Your ClockPart 21 — Challenge: The Chart That Stopped UpdatingPart 21 — Feed Updating versus Chart RefreshPart 21 — Lab: Build a Real-Time Trading LayoutPart 22 — Quote Fields and the Real-Time Quote WindowPart 23 — Project: Real-Time Quote DashboardPart 24 — Defining Intraday Setup ConditionsPart 25 — Duplicate Alerts and How to Stop ThemPart 25 — Project: Real-Time Breakout AlertPart 26 — Bar Replay: Mechanics and Honest LimitsPart 26 — Replay Exercise: Reading a Session LivePart 26 — Replay Exercise: Intraday Setups and AlertsOfficial documentation
Hourreturns ARRAYAFL 2.0Hour()Retrieves current bar's hour
Taught in:Part 20 — Challenge: The Opening Range That MovedPart 20 — Daylight Saving and Alignment FailuresPart 20 — Exchange Time versus Your ClockPart 24 — Defining Intraday Setup ConditionsOfficial documentation
Intervalreturns NUMBERAFL 2.1Interval( 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
Taught in:Part 37 — Component 4: Multi-Timeframe ChartPart 37 — Component 5: Real-Time or Replay WorkspacePart 3 — Lab: Build Your First AmiBroker WorkspacePart 3 — Lab: Install AmiBroker and Verify Your SetupPart 10 — Chart Titles and Dynamic TextPart 11 — Defensive AFL: Guarding Against Bad Input and Bad DataPart 11 — Include Files and Building a LibraryPart 14 — TimeFrameSet() and TimeFrameRestore()Part 17 — Plugins and the Database RelationshipPart 17 — The Real-Time Architecture, End to EndPart 18 — Choosing a Data Source: A Decision FrameworkPart 18 — Appendix: eSignal and Other Supported FeedsPart 19 — The Base Interval DecisionPart 19 — Challenge: The History That Is Not All TherePart 19 — Intraday Database Settings in DetailPart 19 — Lab: Build an Intraday Market DatabasePart 20 — Exchange Time versus Your ClockPart 20 — Sessions: Regular Hours, Pre-Market and After-HoursPart 21 — Challenge: The Chart That Stopped UpdatingPart 21 — Intraday Chart Intervals and What They CostPart 21 — Lab: Build a Real-Time Trading LayoutPart 24 — Defining Intraday Setup ConditionsPart 25 — Project: Real-Time Breakout AlertPart 26 — Bar Replay: Mechanics and Honest LimitsOfficial documentation
Minutereturns ARRAYAFL 2.0Minute()Retrieves current bar's minute
Taught in:Part 20 — Challenge: The Opening Range That MovedPart 20 — Daylight Saving and Alignment FailuresPart 20 — Exchange Time versus Your ClockPart 24 — Defining Intraday Setup ConditionsOfficial documentation
Monthreturns ARRAYAFL 1.4Month()Returns the array with months(1-12)
Taught in:Part 5 — Lab: Map the Structure of a Real ChartOfficial documentation
Nowreturns STRINGAFL 2.3Now( format = 0 )Returns current date / time in numerous of formats: format = 0 - returns string containing current date/time formatted according to system settings format = 1 - returns string containing current date o
Taught in:Part 2 — Survivorship, Delistings and Index MembershipPart 12 — Exporting Results and Building a Daily WorkflowPart 17 — Plugins and the Database RelationshipPart 17 — The Real-Time Architecture, End to EndPart 19 — Backfill and Database MaintenancePart 20 — Exchange Time versus Your ClockPart 21 — Feed Updating versus Chart RefreshPart 24 — Project: Intraday Breakout ScannerPart 24 — Repeat Scanning: Mechanics and CostsPart 26 — Bar Replay: Mechanics and Honest LimitsPart 35 — The Research Lifecycle End to EndOfficial documentation
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.
Taught in:Part 10 — Parameters: Param, ParamToggle, ParamList and ParamColorOfficial documentation
_Nreturns nothingAFL 2.1_N( string )Protects from printing string to the commentary output window
Taught in:Part 10 — Chart Titles and Dynamic TextPart 10 — Project: Multi-Indicator Analysis PanelPart 11 — Defensive AFL: Guarding Against Bad Input and Bad DataPart 11 — Project: Your Personal AFL Utility LibraryOfficial documentation
_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).
Taught in:Part 10 — Parameters: Param, ParamToggle, ParamList and ParamColorOfficial documentation
_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.
Taught in:Part 3 — Lab: Build Your First AmiBroker WorkspacePart 8 — Syntax Basics: Statements, Comments and NamesPart 8 — What AFL Is and Where It RunsPart 8 — Your First FormulaPart 10 — Parameters: Param, ParamToggle, ParamList and ParamColorOfficial documentation
_SECTION_ENDreturns NOTHINGAFL 2.70_SECTION_END()marks end of drag-drop section
Taught in:Part 3 — Lab: Build Your First AmiBroker WorkspacePart 8 — Your First FormulaPart 10 — Parameters: Param, ParamToggle, ParamList and ParamColorOfficial documentation
AddColumnreturns NOTHINGAFL 1.8AddColumn( 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.
Taught in:Part 37 — Components 7 and 8: Backtest and Robustness EvaluationPart 37 — Component 4: Multi-Timeframe ChartPart 37 — Component 3: ScannerPart 37 — Component 2: Stock ExplorationPart 2 — Data Defects in PracticePart 2 — OHLCV and What a Bar HidesPart 3 — Importing and Updating Market DataPart 3 — Lab: Install AmiBroker and Verify Your SetupPart 5 — Reality Check: Do Support Levels Actually Hold?Part 6 — Reality Check: Does RSI Above 70 Mean Sell?Part 7 — Reality Check: Can We Test Whether a Pattern Predicted Anything?Part 11 — Project: Your Personal AFL Utility LibraryPart 12 — The Analysis Window and Its Four ModesPart 12 — Challenge: The Scan That Returns NothingPart 12 — Conditional Formatting, Sorting and Ranking ColumnsPart 12 — Exploration: Filter, AddColumn and AddTextColumnPart 12 — Exporting Results and Building a Daily WorkflowPart 12 — Project: Build a Daily Stock ScreenerPart 12 — Reality Check: Do High-Volume Breakouts Lead Anywhere?Part 14 — Project: Multi-Timeframe ScannerPart 16 — Building Composites with AddToComposite()Part 17 — Plugins and the Database RelationshipPart 18 — Choosing a Data Source: A Decision FrameworkPart 18 — Free and End-of-Day Sources with AmiQuotePart 18 — Appendix: IQFeedPart 23 — Knowing Where You Are: Status() and Execution ContextPart 26 — Replay Exercise: Reading a Session LivePart 27 — From Rules to AFLPart 28 — Stops with ApplyStop()Part 30 — Insufficient Evidence and Regime DependencePart 30 — Unrealistic Fills, Costs and LiquidityPart 33 — Sequence Risk and Risk of RuinPart 33 — What Monte Carlo Can and Cannot Tell YouPart 34 — Portfolio Exposure, Concentration and CorrelationPart 35 — Journalling and Separating Two Kinds of PerformancePart 35 — The Research Lifecycle End to EndPart 35 — Defining Your Universe and Market RegimeOfficial documentation
AddMultiTextColumnreturns NOTHINGAFL 4.20AddMultiTextColumn( 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.
Taught in:Part 12 — Building Screening Filters That Mean SomethingPart 12 — Conditional Formatting, Sorting and Ranking ColumnsPart 12 — Exploration: Filter, AddColumn and AddTextColumnPart 35 — The Research Lifecycle End to EndPart 35 — Defining Your Universe and Market RegimeOfficial documentation
AddRankColumnreturns NOTHINGAFL 5.70AddRankColumn()The function adds ranking column(s) according to current sort set by SetSortColumns to exploration result list.
Taught in:Part 12 — Conditional Formatting, Sorting and Ranking ColumnsPart 12 — Project: Build a Daily Stock ScreenerPart 13 — Ranking versus FilteringPart 35 — From Candidate to DecisionOfficial documentation
AddSummaryRowsreturns NOTHINGAFL 3.2AddSummaryRows( 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.
Taught in:Part 37 — Components 7 and 8: Backtest and Robustness EvaluationPart 37 — Component 4: Multi-Timeframe ChartPart 37 — Component 3: ScannerPart 37 — Component 2: Stock ExplorationPart 5 — Reality Check: Do Support Levels Actually Hold?Part 6 — Reality Check: Does RSI Above 70 Mean Sell?Part 7 — Reality Check: Can We Test Whether a Pattern Predicted Anything?Part 12 — Building Screening Filters That Mean SomethingPart 12 — Challenge: The Scan That Returns NothingPart 12 — Conditional Formatting, Sorting and Ranking ColumnsPart 12 — Exporting Results and Building a Daily WorkflowPart 12 — Project: Build a Daily Stock ScreenerPart 12 — Reality Check: Do High-Volume Breakouts Lead Anywhere?Part 24 — Project: Intraday Breakout ScannerPart 24 — Repeat Scanning: Mechanics and CostsPart 26 — Replay Exercise: Reading a Session LivePart 28 — Stops with ApplyStop()Part 30 — Insufficient Evidence and Regime DependencePart 30 — Survivorship and Selection BiasPart 30 — Unrealistic Fills, Costs and LiquidityPart 34 — Portfolio Exposure, Concentration and CorrelationOfficial documentation
AddTextColumnreturns NOTHINGAFL 1.8AddTextColumn( string, name, format = 1.2, textColor = colorDefault, bkgndColor = colorDefault, width = -1 )Adds a new text column to the exploration result list. The column shows text and has a caption of name. Next two parameters allow to modify text and background color. Width parameter allows to control pixel width of the column
Taught in:Part 37 — Component 3: ScannerPart 37 — Component 2: Stock ExplorationPart 3 — Importing and Updating Market DataPart 3 — Lab: Install AmiBroker and Verify Your SetupPart 12 — Exploration: Filter, AddColumn and AddTextColumnPart 12 — Exporting Results and Building a Daily WorkflowPart 12 — Project: Build a Daily Stock ScreenerPart 14 — Project: Multi-Timeframe ScannerPart 16 — Building Composites with AddToComposite()Part 17 — Plugins and the Database RelationshipPart 18 — Choosing a Data Source: A Decision FrameworkPart 23 — Knowing Where You Are: Status() and Execution ContextPart 24 — Project: Intraday Breakout ScannerPart 33 — What Monte Carlo Can and Cannot Tell YouPart 35 — Journalling and Separating Two Kinds of PerformancePart 35 — The Research Lifecycle End to EndOfficial documentation
EncodeColorreturns STRINGAFL 2.2EncodeColor ( 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.
Taught in:Part 10 — Chart Titles and Dynamic TextPart 21 — Intraday Chart Intervals and What They CostPart 21 — Lab: Build a Real-Time Trading LayoutOfficial documentation
GetChartIDreturns NUMBERAFL 2.3GetChartID()returns the chart ID of current indicator formula. Returns 0 if used in Automatic analysis.
Taught in:Part 3 — Navigating and Scaling ChartsPart 5 — Trendlines and ChannelsPart 10 — Parameters: Param, ParamToggle, ParamList and ParamColorPart 23 — RequestTimedRefresh() and Real-Time PerformanceOfficial documentation
GetPriceStylereturns NUMBERAFL 2.70GetPriceStyleReturns price chart style value to be used in Plot statement Returned value depends on selection in View->Price chart style menu
Taught in:Part 4 — Chart Types and What Each One ShowsPart 10 — Plotting with Plot(): Styles, Colours and PanesOfficial documentation
LineArrayreturns ARRAYAFL 2.5LineArray( 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.
Taught in:Part 5 — Trendlines and ChannelsOfficial documentation
Paramreturns NUMBERAFL 2.3Param( ''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.
Taught in:Part 37 — Component 5: Real-Time or Replay WorkspacePart 37 — Component 6: The Trading StrategyPart 3 — Lab: Build Your First AmiBroker WorkspacePart 3 — Navigating and Scaling ChartsPart 3 — Symbols, Watchlists and CategoriesPart 4 — Linear versus Logarithmic ScalingPart 4 — Market Structure: Trends, Ranges and TransitionsPart 4 — Swings, Highs and LowsPart 6 — Moving Averages: SMA and EMAPart 7 — Candlestick Anatomy and Single-Bar PatternsPart 7 — Reality Check: Can We Test Whether a Pattern Predicted Anything?Part 10 — Parameters: Param, ParamToggle, ParamList and ParamColorPart 10 — Project: Multi-Indicator Analysis PanelPart 11 — User-Defined Functions and ProceduresPart 14 — Project: Multi-Timeframe Trend IndicatorPart 16 — Breadth Divergence and Market RegimePart 18 — Appendix: IQFeedPart 21 — Intraday Chart Intervals and What They CostPart 28 — Stops with ApplyStop()Part 29 — Reading the Backtest ReportPart 30 — Challenge Collection: Six Broken BacktestsPart 30 — Challenge: 180% a Year with a 3% DrawdownPart 30 — Data Snooping, Curve Fitting and OverfittingPart 30 — Insufficient Evidence and Regime DependencePart 30 — Position Sizing and Portfolio ErrorsPart 30 — Unrealistic Fills, Costs and LiquidityPart 31 — What Optimize() Actually DoesPart 33 — Sequence Risk and Risk of RuinPart 35 — Defining Your Universe and Market RegimePart 36 — Advanced Debugging and TracingOfficial documentation
ParamColorreturns NUMBERAFL 2.3ParamColor( ''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.
Taught in:Part 37 — Component 1: Market DashboardPart 10 — Parameters: Param, ParamToggle, ParamList and ParamColorPart 10 — Project: ATR Volatility IndicatorPart 10 — Project: Configurable Moving-Average IndicatorPart 10 — Project: Multi-Indicator Analysis PanelPart 23 — Project: Real-Time Quote DashboardOfficial documentation
ParamDatereturns NUMBERAFL 2.60ParamDate( ''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.
Taught in:Part 10 — Parameters: Param, ParamToggle, ParamList and ParamColorPart 15 — Benchmarks and Relative PerformancePart 15 — Project: Relative Strength Comparison ToolOfficial documentation
ParamFieldreturns ARRAYAFL 2.70ParamField(''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.
Taught in:Part 4 — Chart Types and What Each One ShowsPart 10 — Parameters: Param, ParamToggle, ParamList and ParamColorPart 10 — Project: Configurable Moving-Average IndicatorOfficial documentation
ParamListreturns STRINGAFL 2.70ParamList( ''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
Taught in:Part 37 — Component 4: Multi-Timeframe ChartPart 5 — Reality Check: Do Support Levels Actually Hold?Part 10 — Parameters: Param, ParamToggle, ParamList and ParamColorPart 10 — Project: Configurable Moving-Average IndicatorPart 16 — Project: Market Breadth DashboardPart 22 — Time & Sales: What It Does and Does Not Tell YouPart 23 — Project: Real-Time Quote DashboardOfficial documentation
ParamStrreturns STRINGAFL 2.3ParamStr( ''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.
Taught in:Part 37 — Component 1: Market DashboardPart 37 — Component 3: ScannerPart 37 — Component 6: The Trading StrategyPart 10 — Parameters: Param, ParamToggle, ParamList and ParamColorPart 21 — Lab: Build a Real-Time Trading LayoutPart 30 — Insufficient Evidence and Regime DependencePart 35 — Journalling and Separating Two Kinds of PerformancePart 35 — Defining Your Universe and Market RegimeOfficial documentation
ParamStylereturns NUMBERAFL 2.70ParamStyle(''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
Taught in:Part 3 — Lab: Build Your First AmiBroker WorkspacePart 3 — Navigating and Scaling ChartsPart 4 — Chart Types and What Each One ShowsPart 10 — Parameters: Param, ParamToggle, ParamList and ParamColorPart 10 — Plotting with Plot(): Styles, Colours and PanesPart 10 — Project: Configurable Moving-Average IndicatorOfficial documentation
ParamTimereturns NUMBERAFL 2.60ParamTime( ''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.
Taught in:Part 10 — Parameters: Param, ParamToggle, ParamList and ParamColorOfficial documentation
ParamTogglereturns NUMBERAFL 2.70ParamToggle(''name'',''values'',defaultval=0 )Function that allows to use boolean (Yes/No) parameters. ''name'' - the name of the parameter ''values'' - parameter values (separated with character, e.g. "No Yes" - first string represents false value and second string represents true value) defaultval - default value of the parameter IMPORTANT: Parameter names and values must NOT contain non-printable characters (ASCII codes
Taught in:Part 37 — Component 5: Real-Time or Replay WorkspacePart 3 — Lab: Build Your First AmiBroker WorkspacePart 3 — Navigating and Scaling ChartsPart 4 — Chart Types and What Each One ShowsPart 7 — Multi-Bar Candlestick PatternsPart 10 — Parameters: Param, ParamToggle, ParamList and ParamColorPart 10 — Project: ATR Volatility IndicatorPart 10 — Project: Configurable Moving-Average IndicatorPart 10 — Project: Multi-Indicator Analysis PanelPart 13 — Ranking versus FilteringPart 14 — Project: Multi-Timeframe Trend IndicatorPart 15 — Project: Relative Strength Comparison ToolPart 16 — Building Composites with AddToComposite()Part 19 — Challenge: The History That Is Not All TherePart 20 — Daylight Saving and Alignment FailuresPart 32 — The AmiBroker Walk-Forward WorkflowPart 36 — Performance: QuickAFL, Multi-Threading and CostOfficial documentation
ParamTriggerreturns NUMBERAFL 2.70ParamTrigger( ''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
Taught in:Part 10 — Parameters: Param, ParamToggle, ParamList and ParamColorPart 23 — RequestTimedRefresh() and Real-Time PerformanceOfficial documentation
Plotreturns NUMBERAFL 1.8Plot( 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).
Taught in:Part 37 — Component 1: Market DashboardPart 37 — Component 4: Multi-Timeframe ChartPart 37 — Component 5: Real-Time or Replay WorkspacePart 3 — Lab: Build Your First AmiBroker WorkspacePart 3 — Navigating and Scaling ChartsPart 4 — Chart Types and What Each One ShowsPart 4 — Linear versus Logarithmic ScalingPart 4 — Market Structure: Trends, Ranges and TransitionsPart 6 — MACDPart 6 — Moving Averages: SMA and EMAPart 8 — Boolean Arrays: Close > MA(Close, 50)Part 8 — Errors, Debugging and Sanity ChecksPart 8 — Logic, Conditionals and IIf()Part 8 — Null Values, Nz() and Warm-Up PeriodsPart 8 — Syntax Basics: Statements, Comments and NamesPart 8 — The Array Model: The Most Important Lesson in This CoursePart 8 — What AFL Is and Where It RunsPart 8 — Your First FormulaPart 10 — Plotting with Plot(): Styles, Colours and PanesPart 10 — Project: ATR Volatility IndicatorPart 10 — Project: Configurable Moving-Average IndicatorPart 10 — Project: Multi-Indicator Analysis PanelPart 10 — Project: Trend Regime IndicatorPart 11 — Defensive AFL: Guarding Against Bad Input and Bad DataPart 11 — Include Files and Building a LibraryPart 11 — Project: Your Personal AFL Utility LibraryPart 11 — User-Defined Functions and ProceduresPart 23 — Knowing Where You Are: Status() and Execution ContextPart 28 — Stops with ApplyStop()Part 29 — Equity Curve AnalysisPart 30 — Challenge Collection: Six Broken BacktestsPart 30 — Challenge: 180% a Year with a 3% DrawdownPart 30 — Data Snooping, Curve Fitting and OverfittingPart 30 — Position Sizing and Portfolio ErrorsPart 30 — Unrealistic Fills, Costs and LiquidityPart 31 — Lab: Optimise Without Fooling YourselfPart 34 — Drawdown and Risk of Ruin in PracticeOfficial documentation
PlotGridreturns NOTHINGAFL 2.3PlotGrid( level, color = colorDefault, pattern = 1, width = 1, Label = True )Plots hotizontal grid line using built-in dotted style at given level, color, pattern, width, with or without Label. New in version 5.90: pattern - defines line pattern. Available grid patterns 1..10 a
Taught in:Part 4 — Lab: Structured Chart InterpretationPart 5 — Consolidation and Volatility ContractionPart 5 — Support and Resistance as ZonesPart 6 — ADX and Directional MovementPart 6 — Reality Check: Does RSI Above 70 Mean Sell?Part 6 — RSI and Rate of ChangePart 6 — The Stochastic OscillatorPart 6 — Volatility: True Range, ATR and Bollinger BandsPart 10 — Plotting with Plot(): Styles, Colours and PanesPart 11 — User-Defined Functions and ProceduresPart 16 — Breadth Divergence and Market RegimePart 16 — Project: Market Breadth DashboardOfficial documentation
PlotOHLCreturns NUMBERAFL 2.2PlotOHLC( 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).
Taught in:Part 37 — Component 4: Multi-Timeframe ChartPart 5 — Lab: Map the Structure of a Real ChartPart 5 — Support and Resistance as ZonesPart 14 — Project: Multi-Timeframe Trend IndicatorOfficial documentation
PlotShapesreturns NOTHINGAFL 2.3PlotShapes( shape, color, layer = 0, yposition = graph0, offset = -12, XShift = 0 );Plots arrows and other shapes on any chart pane. Parameters: shape defines type of the symbol. when shape is zero nothing is plotted values other than zero cause plotting various pre-defined shapes. Odd values plot shape BELOW indicator, even values plot shape ABOVE indicator.
Taught in:Part 37 — Component 5: Real-Time or Replay WorkspacePart 4 — Swings, Highs and LowsPart 5 — Breakouts, Failed Breakouts and Role ReversalPart 5 — Lab: Map the Structure of a Real ChartPart 6 — Moving Average Slope and CrossoversPart 7 — Candlestick Anatomy and Single-Bar PatternsPart 7 — Classic Chart PatternsPart 10 — PlotShapes() and Visual SignalsPart 10 — Project: Configurable Moving-Average IndicatorPart 10 — Project: Trend Regime IndicatorPart 11 — Variable Scope: local, global and the TrapsPart 25 — Project: Real-Time Breakout AlertPart 26 — Replay Exercise: Intraday Setups and AlertsPart 27 — From Rules to AFLPart 28 — Stops with ApplyStop()Part 30 — Challenge Collection: Six Broken BacktestsPart 30 — Challenge: 180% a Year with a 3% DrawdownPart 30 — Data Snooping, Curve Fitting and OverfittingPart 30 — Unrealistic Fills, Costs and LiquidityOfficial documentation
SelectedValuereturns NUMBERAFL 2.1SelectedValue( ARRAY )Retrieves array value at currently selected bar. Main purpose: commentary and interpreration code.
Taught in:Part 37 — Component 1: Market DashboardPart 37 — Component 4: Multi-Timeframe ChartPart 37 — Component 5: Real-Time or Replay WorkspacePart 6 — Lab: Indicator Behaviour WorkbenchPart 8 — The Array Model: The Most Important Lesson in This CoursePart 10 — Chart Titles and Dynamic TextPart 10 — Project: Multi-Indicator Analysis PanelPart 11 — Defensive AFL: Guarding Against Bad Input and Bad DataPart 11 — Project: Your Personal AFL Utility LibraryPart 13 — StaticVarGenerateRanks() and Top-N SelectionPart 16 — Project: Market Breadth DashboardOfficial documentation
SetChartOptionsreturns NOTHINGAFL 2.70SetChartOptions( 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
Taught in:Part 37 — Component 1: Market DashboardPart 37 — Component 4: Multi-Timeframe ChartPart 10 — Chart Titles and Dynamic TextPart 10 — Project: Multi-Indicator Analysis PanelPart 21 — Intraday Chart Intervals and What They CostPart 29 — Equity Curve AnalysisOfficial documentation
SetSortColumnsreturns NOTHINGAFL 2.90SetSortColumns( 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
Taught in:Part 37 — Component 4: Multi-Timeframe ChartPart 37 — Component 3: ScannerPart 37 — Component 2: Stock ExplorationPart 3 — Importing and Updating Market DataPart 3 — Lab: Install AmiBroker and Verify Your SetupPart 12 — Challenge: The Scan That Returns NothingPart 12 — Conditional Formatting, Sorting and Ranking ColumnsPart 12 — Exporting Results and Building a Daily WorkflowPart 12 — Project: Build a Daily Stock ScreenerPart 12 — Reality Check: Do High-Volume Breakouts Lead Anywhere?Part 13 — Project: Market Relative Strength Ranking ToolPart 13 — Ranking versus FilteringPart 14 — Project: Multi-Timeframe ScannerPart 15 — Data Alignment Pitfalls Across SymbolsPart 16 — Building Composites with AddToComposite()Part 17 — Plugins and the Database RelationshipPart 19 — Backfill and Database MaintenancePart 24 — Project: Intraday Breakout ScannerPart 24 — Repeat Scanning: Mechanics and CostsPart 35 — From Candidate to DecisionPart 35 — Journalling and Separating Two Kinds of PerformancePart 35 — The Research Lifecycle End to EndOfficial documentation
WriteIfreturns STRINGWriteIf( EXPRESSION, "TRUE TEXT", "FALSE TEXT" )If EXPRESSION evaluates to "true", then the TRUE TEXT string is displayed within the commentary. If EXPRESSION evaluates to "false", then the FALSE TEXT string is displayed.
Taught in:Part 37 — Component 1: Market DashboardPart 37 — Component 4: Multi-Timeframe ChartPart 37 — Component 5: Real-Time or Replay WorkspacePart 2 — Survivorship, Delistings and Index MembershipPart 3 — Symbols, Watchlists and CategoriesPart 4 — Market Structure: Trends, Ranges and TransitionsPart 6 — Lab: Indicator Behaviour WorkbenchPart 7 — Multi-Bar Candlestick PatternsPart 8 — Errors, Debugging and Sanity ChecksPart 8 — Logic, Conditionals and IIf()Part 10 — Chart Titles and Dynamic TextPart 10 — Project: Multi-Indicator Analysis PanelPart 10 — Project: Trend Regime IndicatorPart 11 — Defensive AFL: Guarding Against Bad Input and Bad DataPart 11 — Include Files and Building a LibraryPart 11 — Project: Your Personal AFL Utility LibraryPart 11 — User-Defined Functions and ProceduresPart 13 — Project: Market Relative Strength Ranking ToolPart 16 — Breadth Divergence and Market RegimePart 19 — Challenge: The History That Is Not All TherePart 26 — Replay Exercise: Reading a Session LivePart 36 — Advanced Debugging and TracingOfficial documentation
WriteValreturns STRINGWriteVal( 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).
Taught in:Part 10 — Chart Titles and Dynamic TextPart 34 — Drawdown and Risk of Ruin in PracticeOfficial documentation
File Input/Output functions
fclosereturns NOTHINGAFL 2.5fclose( filehandle )Closes a file. The filehandle (NUMBER) should be the handle returned by fopen function.
Taught in:Part 12 — Exporting Results and Building a Daily WorkflowOfficial documentation
fopenreturns FILEAFL 2.5fopen( ''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
Taught in:Part 12 — Exporting Results and Building a Daily WorkflowOfficial documentation
fputsreturns NOTHINGAFL 2.5fputs( 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.
Taught in:Part 12 — Exporting Results and Building a Daily WorkflowOfficial documentation
Indicators
AccDistreturns ARRAYAccDist()Calculates the Accumulation/ Distribution indicator.
Taught in:Part 6 — Volume and Volume-Based IndicatorsOfficial documentation
ADXreturns ARRAYAFL 1.3adx( period = 14 )Calculates Average Directional Index indicator
Taught in:Part 6 — ADX and Directional MovementPart 6 — Lab: Indicator Behaviour WorkbenchOfficial documentation
ATRreturns ARRAYAFL 1.3atr( period )Calculates Average True Range indicator
Taught in:Part 37 — Components 7 and 8: Backtest and Robustness EvaluationPart 37 — Component 1: Market DashboardPart 37 — Component 4: Multi-Timeframe ChartPart 37 — Component 5: Real-Time or Replay WorkspacePart 37 — Component 3: ScannerPart 37 — Component 2: Stock ExplorationPart 37 — Component 6: The Trading StrategyPart 2 — Data Defects in PracticePart 2 — Lab: Prove That Bad Data Breaks AnalysisPart 4 — Lab: Structured Chart InterpretationPart 5 — Breakouts, Failed Breakouts and Role ReversalPart 5 — Consolidation and Volatility ContractionPart 5 — Lab: Map the Structure of a Real ChartPart 5 — Reality Check: Do Support Levels Actually Hold?Part 5 — Support and Resistance as ZonesPart 6 — Lab: Indicator Behaviour WorkbenchPart 6 — Volatility: True Range, ATR and Bollinger BandsPart 7 — Candlestick Anatomy and Single-Bar PatternsPart 7 — Classic Chart PatternsPart 8 — Errors, Debugging and Sanity ChecksPart 8 — Logic, Conditionals and IIf()Part 8 — Variables, Numbers and ExpressionsPart 10 — Project: ATR Volatility IndicatorPart 10 — Project: Multi-Indicator Analysis PanelPart 10 — Project: Trend Regime IndicatorPart 11 — Defensive AFL: Guarding Against Bad Input and Bad DataPart 11 — Project: Your Personal AFL Utility LibraryPart 12 — Building Screening Filters That Mean SomethingPart 12 — Project: Build a Daily Stock ScreenerPart 18 — Appendix: IQFeedPart 25 — Project: Real-Time Breakout AlertPart 26 — Replay Exercise: Reading a Session LivePart 28 — Portfolio Backtesting: Many Symbols, One AccountPart 28 — Position Sizing with SetPositionSize()Part 28 — Stops with ApplyStop()Part 30 — Position Sizing and Portfolio ErrorsPart 34 — Lab: Same Strategy, Three Position-Sizing ModelsPart 34 — Volatility-Based Position SizingPart 35 — From Candidate to DecisionPart 35 — Journalling and Separating Two Kinds of PerformanceOfficial documentation
BBandBotreturns ARRAYBBandBot( ARRAY, periods = 15, width = 2 )Calculates the bottom Bollinger Band of ARRAY shifted down w idth standard deviations (using periods averaging range ).
Taught in:Part 6 — Lab: Indicator Behaviour WorkbenchPart 6 — Volatility: True Range, ATR and Bollinger BandsOfficial documentation
BBandTopreturns ARRAYBBandTop( ARRAY, periods = 15, width = 2 )Calculates the top Bollinger Band of ARRAY shifted up width standard deviations (using periods averaging range ).
Taught in:Part 6 — Lab: Indicator Behaviour WorkbenchPart 6 — Volatility: True Range, ATR and Bollinger BandsOfficial documentation
ColorBlendreturns NUMBERAFL 3.30ColorBlend( 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.
Taught in:Part 5 — Support and Resistance as ZonesPart 10 — Plotting with Plot(): Styles, Colours and PanesPart 10 — Project: Trend Regime IndicatorOfficial documentation
GetChartBkColorreturns NUMBERAFL 3.20GetChartBkColor()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.
Taught in:Part 10 — Plotting with Plot(): Styles, Colours and PanesPart 10 — Project: Trend Regime IndicatorOfficial documentation
MACDreturns ARRAYmacd( fast = 12, slow = 26)Calculates the MACD indicator using fast and slow averaging periods.
Taught in:Part 6 — MACDOfficial documentation
MDIreturns ARRAYAFL 1.3mdi( period = 14 )Calculates Minus Directional Movement Indicator (-DI line)
Taught in:Part 6 — ADX and Directional MovementPart 6 — Lab: Indicator Behaviour WorkbenchOfficial documentation
MFIreturns ARRAYmfi( periods = 14 )Calculates the Money Flow Index with period range
Taught in:Part 6 — Volume and Volume-Based IndicatorsOfficial documentation
OBVreturns ARRAYobv()Calculates the On Balance Volume indicator.
Taught in:Part 6 — Volume and Volume-Based IndicatorsOfficial documentation
PDIreturns ARRAYAFL 1.3pdi( period = 14 )Calculates Plus Directional Movement Indicator (+DI line)
Taught in:Part 6 — ADX and Directional MovementPart 6 — Lab: Indicator Behaviour WorkbenchOfficial documentation
PercentRankreturns ARRAYAFL 3.40PercentRank( 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.
Taught in:Part 37 — Component 1: Market DashboardPart 37 — Component 2: Stock ExplorationPart 5 — Consolidation and Volatility ContractionPart 5 — Lab: Map the Structure of a Real ChartPart 6 — Volatility: True Range, ATR and Bollinger BandsPart 10 — Project: ATR Volatility IndicatorPart 10 — Project: Multi-Indicator Analysis PanelPart 12 — Conditional Formatting, Sorting and Ranking ColumnsPart 12 — Project: Build a Daily Stock ScreenerOfficial documentation
PlotTextreturns NOTHINGAFL 2.80PlotText( ''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.
Taught in:Part 10 — PlotShapes() and Visual SignalsOfficial documentation
RequestMouseMoveRefreshreturns NOTHINGAFL 4.30RequestMouseMoveRefresh()The function causes that the chart is refreshed (and formula re-executed) when user moves mouse cursor over the chart area
Taught in:Part 23 — RequestTimedRefresh() and Real-Time PerformanceOfficial documentation
RequestTimedRefreshreturns NOTHINGAFL 2.90RequestTimedRefresh( interval, onlyvisible = True )The function causes given indicator window to refresh automatically every seconds regardless of data source used or connection state. interval parameter defines timeout in seconds between refreshes. Am
Taught in:Part 37 — Component 5: Real-Time or Replay WorkspacePart 17 — The Real-Time Architecture, End to EndPart 18 — Appendix: eSignal and Other Supported FeedsPart 20 — Exchange Time versus Your ClockPart 21 — Challenge: The Chart That Stopped UpdatingPart 21 — Feed Updating versus Chart RefreshPart 21 — Lab: Build a Real-Time Trading LayoutPart 22 — Quote Fields and the Real-Time Quote WindowPart 23 — Project: Real-Time Quote DashboardPart 23 — RequestTimedRefresh() and Real-Time PerformancePart 24 — Defining Intraday Setup ConditionsPart 25 — Project: Real-Time Breakout AlertPart 26 — Bar Replay: Mechanics and Honest LimitsOfficial documentation
ROCreturns ARRAYroc( ARRAY, periods = 12, absmode = False )Calculates the periods rate-of-change of ARRAY expressed as percentage. if absmode = False the value returned is 100*( array - ref( array, -periods ) )/ref( array, -periods ) if absmode = True the value returned is 100*( array - ref( array, -periods ) )/abs( ref( array, -periods ) )
Taught in:Part 37 — Component 1: Market DashboardPart 37 — Component 2: Stock ExplorationPart 6 — RSI and Rate of ChangePart 6 — What an Indicator Actually IsPart 7 — Classic Chart PatternsPart 12 — Building Screening Filters That Mean SomethingPart 12 — Project: Build a Daily Stock ScreenerPart 13 — Project: Market Relative Strength Ranking ToolPart 13 — Ranking versus FilteringPart 13 — Relative Strength: What It Does and Does Not MeanPart 15 — Sectors and Intermarket AnalysisPart 29 — Reading the Backtest ReportPart 30 — Challenge: 180% a Year with a 3% DrawdownPart 32 — Lab: Run a Walk-Forward AnalysisPart 33 — The AmiBroker Monte Carlo WorkflowPart 34 — Portfolio Exposure, Concentration and CorrelationPart 36 — Dynamic Variables: VarSet, VarGet and FriendsOfficial documentation
RSIreturns ARRAYRSI( periods = 14 ) RSIa( array, periods = 14 )Calculates the RSI indicator using periods range Second version RSIa accepts input array so it RSI can be applied to other arrays than close.
Taught in:Part 6 — Lab: Indicator Behaviour WorkbenchPart 6 — Reality Check: Does RSI Above 70 Mean Sell?Part 6 — RSI and Rate of ChangePart 6 — What an Indicator Actually IsPart 8 — Errors, Debugging and Sanity ChecksPart 10 — Project: Multi-Indicator Analysis PanelPart 12 — Challenge: The Scan That Returns NothingPart 34 — Lab: Same Strategy, Three Position-Sizing ModelsOfficial documentation
SetBarFillColorreturns NOTHINGAFL 3.1SetBarFillColor( 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
Taught in:Part 7 — Candlestick Anatomy and Single-Bar PatternsPart 10 — Plotting with Plot(): Styles, Colours and PanesOfficial documentation
SetChartBkColorreturns NOTHINGAFL 2.80SetChartBkColor( color )Sets chart background to user-specified color
Taught in:Part 21 — Challenge: The Chart That Stopped UpdatingPart 21 — Lab: Build a Real-Time Trading LayoutOfficial documentation
Signalreturns ARRAYSignal( fast = 12, slow = 26, signal = 9 )Calculates the Signal line of MACD indicator.
Taught in:Part 6 — MACDOfficial documentation
StochDreturns ARRAYStochD( periods = 14, Ksmooth =3, Dsmooth =3 )Calculates the %D line of Stochastic Oscillator (with internal slowing KSmooth, DSmooth).
Taught in:Part 6 — The Stochastic OscillatorOfficial documentation
StochKreturns ARRAYStochK( periods = 14, ksmooth =3 )Calculates the %K line of Stochastic Oscillator (with internal slowing KSmooth).
Taught in:Part 6 — The Stochastic OscillatorOfficial documentation
Information / Categories
CategoryAddSymbolreturns NOTHINGAFL 2.5CategoryAddSymbol( 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.
Taught in:Part 12 — Exporting Results and Building a Daily WorkflowOfficial documentation
CategoryGetNamereturns STRINGAFL 2.5CategoryGetName( 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.
Taught in:Part 3 — Symbols, Watchlists and CategoriesPart 15 — Sectors and Intermarket AnalysisOfficial documentation
CategoryGetSymbolsreturns STRINGAFL 2.5CategoryGetSymbols( category, index, mode = 0 )Retrieves comma-separated list of symbols belonging to given category Supported categories: categoryMarket categoryGroup categorySector categoryIndustry categoryWatchlist categoryFavorite categoryIndex
Taught in:Part 3 — Symbols, Watchlists and CategoriesPart 13 — Project: Market Relative Strength Ranking ToolPart 13 — Static Variables for Cross-Sectional WorkPart 15 — Sectors and Intermarket AnalysisPart 35 — Defining Your Universe and Market RegimeOfficial documentation
FullNamereturns STRINGAFL 1.1FullName ()The function returns stock full name which is definable by the user in Symbol Information window.
Taught in:Part 37 — Component 3: ScannerPart 37 — Component 2: Stock ExplorationPart 3 — Lab: Build Your First AmiBroker WorkspacePart 3 — Lab: Install AmiBroker and Verify Your SetupPart 12 — Exploration: Filter, AddColumn and AddTextColumnPart 12 — Exporting Results and Building a Daily WorkflowPart 16 — Building Composites with AddToComposite()Official documentation
GetDatabaseNamereturns STRINGAFL 2.3GetDatabaseName()retrieves the name of the database - the last part (folder) of the database path
Taught in:Part 18 — Appendix: eSignal and Other Supported FeedsOfficial documentation
GroupIDreturns NUMBER/STRINGAFL 1.8GroupID( 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.
Taught in:Part 3 — Symbols, Watchlists and CategoriesPart 15 — Sectors and Intermarket AnalysisOfficial documentation
IndustryIDreturns NUMBER/STRINGAFL 1.8IndustryID( 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.
Taught in:Part 3 — Symbols, Watchlists and CategoriesPart 15 — Project: Relative Strength Comparison ToolPart 15 — Sectors and Intermarket AnalysisOfficial documentation
InGICSreturns NUMBERAFL 3.40InGICS( "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.
Taught in:Part 15 — Sectors and Intermarket AnalysisOfficial documentation
InICBreturns NUMBERAFL 3.60InICB(''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.
Taught in:Part 15 — Sectors and Intermarket AnalysisOfficial documentation
InWatchListreturns NUMBERInWatchList( listno )Checks if the stock belongs to a watch list number listno . If yes - the function returns 1 otherwise 0.
Taught in:Part 2 — Survivorship, Delistings and Index MembershipPart 3 — Symbols, Watchlists and CategoriesOfficial documentation
InWatchListNamereturns NUMBERAFL 3.0InWatchListName( ''name'' )Checks if the stock belongs to a watch list number "listname" . If yes - the function returns 1 otherwise 0.
Taught in:Part 2 — Survivorship, Delistings and Index MembershipPart 3 — Symbols, Watchlists and CategoriesPart 35 — Defining Your Universe and Market RegimeOfficial documentation
MarketIDreturns NUMBER/STRINGAFL 1.8MarketID( 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.
Taught in:Part 3 — Symbols, Watchlists and CategoriesPart 15 — Sectors and Intermarket AnalysisOfficial documentation
Namereturns STRINGAFL 1.1Name()It is used to display the stock short name (ticker)
Taught in:Part 37 — Component 5: Real-Time or Replay WorkspacePart 37 — Component 2: Stock ExplorationPart 3 — Lab: Build Your First AmiBroker WorkspacePart 3 — Lab: Install AmiBroker and Verify Your SetupPart 10 — Project: Multi-Indicator Analysis PanelPart 11 — Defensive AFL: Guarding Against Bad Input and Bad DataPart 11 — Include Files and Building a LibraryPart 11 — Project: Your Personal AFL Utility LibraryPart 12 — Exporting Results and Building a Daily WorkflowPart 18 — Appendix: eSignal and Other Supported FeedsPart 31 — Lab: Optimise Without Fooling YourselfOfficial documentation
SectorIDreturns NUMBER/STRINGAFL 1.8SectorID( 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.
Taught in:Part 3 — Symbols, Watchlists and CategoriesPart 15 — Project: Relative Strength Comparison ToolPart 15 — Sectors and Intermarket AnalysisPart 34 — Portfolio Exposure, Concentration and CorrelationOfficial documentation
Low-level graphics
GfxSelectFontreturns NOTHINGAFL 3.0GfxSelectFont( ''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).
Taught in:Part 23 — Project: Real-Time Quote DashboardOfficial documentation
GfxSetOverlayModereturns NOTHINGAFL 3.0GfxSetOverlayMode( 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
Taught in:Part 23 — Project: Real-Time Quote DashboardOfficial documentation
GfxTextOutreturns NOTHINGAFL 3.0GfxTextOut( ''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.
Taught in:Part 23 — Project: Real-Time Quote DashboardOfficial documentation
Lowest/Highest
HHVreturns ARRAYhhv( 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).
Taught in:Part 37 — Components 7 and 8: Backtest and Robustness EvaluationPart 37 — Component 4: Multi-Timeframe ChartPart 37 — Component 5: Real-Time or Replay WorkspacePart 37 — Component 3: ScannerPart 37 — Component 6: The Trading StrategyPart 4 — Lab: Structured Chart InterpretationPart 4 — Market Structure: Trends, Ranges and TransitionsPart 4 — Swings, Highs and LowsPart 5 — Breakouts, Failed Breakouts and Role ReversalPart 5 — Consolidation and Volatility ContractionPart 5 — Lab: Map the Structure of a Real ChartPart 5 — Support and Resistance as ZonesPart 6 — The Stochastic OscillatorPart 7 — Classic Chart PatternsPart 9 — Challenge: State or Event?Part 9 — Running Extremes: HHV, LLV and FriendsPart 12 — Building Screening Filters That Mean SomethingPart 12 — Challenge: The Scan That Returns NothingPart 12 — Exporting Results and Building a Daily WorkflowPart 12 — Project: Build a Daily Stock ScreenerPart 12 — Reality Check: Do High-Volume Breakouts Lead Anywhere?Part 14 — Expansion Modes and the Look-Ahead TrapPart 14 — Project: Multi-Timeframe Trend IndicatorPart 14 — Project: Multi-Timeframe ScannerPart 16 — Project: Market Breadth DashboardPart 25 — Project: Real-Time Breakout AlertPart 26 — Replay Exercise: Reading a Session LivePart 26 — Replay Exercise: Intraday Setups and AlertsPart 27 — From Hypothesis to RulesPart 28 — Single-Symbol Thinking versus Portfolio RealityPart 29 — Reading the Backtest ReportPart 30 — Challenge Collection: Six Broken BacktestsPart 30 — Position Sizing and Portfolio ErrorsPart 30 — Unrealistic Fills, Costs and LiquidityPart 32 — Lab: Run a Walk-Forward AnalysisPart 35 — From Candidate to DecisionOfficial documentation
HHVBarsreturns ARRAYHHVBars( 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).
Taught in:Part 4 — Lab: Structured Chart InterpretationPart 9 — Running Extremes: HHV, LLV and FriendsOfficial documentation
Highestreturns ARRAYHighest( ARRAY )Calculates the highest value in the ARRAY since the first day/bar present in the database.
Taught in:Part 37 — Component 4: Multi-Timeframe ChartPart 2 — Lab: Prove That Bad Data Breaks AnalysisPart 3 — Importing and Updating Market DataPart 9 — Challenge: State or Event?Part 9 — Running Extremes: HHV, LLV and FriendsPart 18 — Choosing a Data Source: A Decision FrameworkPart 18 — Free and End-of-Day Sources with AmiQuotePart 19 — Backfill and Database MaintenancePart 19 — Challenge: The History That Is Not All TherePart 28 — Stops with ApplyStop()Part 29 — Equity Curve AnalysisPart 34 — Drawdown and Risk of Ruin in PracticePart 36 — Advanced Debugging and TracingOfficial documentation
HighestSincereturns ARRAYAFL 1.4HighestSince( EXPRESSION, ARRAY, Nth = 1 )Returns the highest ARRAY value since EXPRESSION was true on the Nth most recent occurrence.
Taught in:Part 5 — Lab: Map the Structure of a Real ChartPart 9 — Challenge: State or Event?Part 9 — ValueWhen(): Carrying a Value ForwardPart 19 — Backfill and Database MaintenancePart 19 — Challenge: The History That Is Not All TherePart 20 — Challenge: The Opening Range That MovedPart 20 — Sessions: Regular Hours, Pre-Market and After-HoursPart 24 — Defining Intraday Setup ConditionsPart 24 — Project: Intraday Breakout ScannerPart 30 — Look-Ahead BiasOfficial documentation
LLVreturns ARRAYllv( ARRAY, periods )Calculates the lowest value in the ARRAY over the preceding periods ( periods includes the current day). The function accepts periods parameter that can be constant as well as time-variant (array).
Taught in:Part 37 — Components 7 and 8: Backtest and Robustness EvaluationPart 37 — Component 6: The Trading StrategyPart 4 — Lab: Structured Chart InterpretationPart 4 — Market Structure: Trends, Ranges and TransitionsPart 4 — Swings, Highs and LowsPart 5 — Breakouts, Failed Breakouts and Role ReversalPart 5 — Consolidation and Volatility ContractionPart 5 — Lab: Map the Structure of a Real ChartPart 5 — Reality Check: Do Support Levels Actually Hold?Part 5 — Support and Resistance as ZonesPart 6 — The Stochastic OscillatorPart 7 — Classic Chart PatternsPart 9 — Running Extremes: HHV, LLV and FriendsPart 16 — Project: Market Breadth DashboardPart 26 — Replay Exercise: Reading a Session LivePart 28 — Single-Symbol Thinking versus Portfolio RealityPart 29 — Reading the Backtest ReportPart 30 — Challenge Collection: Six Broken BacktestsPart 30 — Position Sizing and Portfolio ErrorsPart 30 — Unrealistic Fills, Costs and LiquidityPart 32 — Lab: Run a Walk-Forward AnalysisPart 34 — Risk Per Trade and Stop DistanceOfficial documentation
LLVBarsreturns ARRAYLLVBars( 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).
Taught in:Part 4 — Lab: Structured Chart InterpretationPart 9 — Running Extremes: HHV, LLV and FriendsOfficial documentation
Lowestreturns ARRAYLowest( ARRAY )Calculates the lowest value in the ARRAY since the first day/bar present in the database.
Taught in:Part 2 — Lab: Prove That Bad Data Breaks AnalysisPart 9 — Running Extremes: HHV, LLV and FriendsPart 18 — Choosing a Data Source: A Decision FrameworkPart 19 — Backfill and Database MaintenancePart 19 — Challenge: The History That Is Not All TherePart 29 — Equity Curve AnalysisPart 34 — Drawdown and Risk of Ruin in PracticeOfficial documentation
LowestSincereturns ARRAYAFL 1.4LowestSince( EXPRESSION, ARRAY, Nth = 1 )Returns the lowest ARRAY value since EXPRESSION was true on the Nth most recent occurrence.
Taught in:Part 5 — Lab: Map the Structure of a Real ChartPart 9 — ValueWhen(): Carrying a Value ForwardPart 20 — Challenge: The Opening Range That MovedPart 20 — Sessions: Regular Hours, Pre-Market and After-HoursPart 24 — Defining Intraday Setup ConditionsPart 24 — Project: Intraday Breakout ScannerOfficial documentation
Math functions
absreturns NUMBERabs( NUMBER ) abs( ARRAY )Calculates the absolute value of the NUMBER or ARRAY.
Taught in:Part 2 — OHLCV and What a Bar HidesPart 3 — Importing and Updating Market DataPart 11 — Include Files and Building a LibraryPart 18 — Free and End-of-Day Sources with AmiQuotePart 18 — Appendix: IQFeedPart 28 — Portfolio Backtesting: Many Symbols, One AccountPart 33 — The Limits of SimulationPart 33 — What Monte Carlo Can and Cannot Tell YouPart 36 — Advanced Debugging and TracingOfficial documentation
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.
Taught in:Part 33 — Sequence Risk and Risk of RuinOfficial documentation
floorreturns NUMBER,floor ( NUMBER ) floor ( ARRAY )Calculates the highest integer that is less than NUMBER or ARRAY.
Taught in:Part 35 — From Candidate to DecisionOfficial documentation
Intreturns NUMBERInt( NUMBER ) int( ARRAY )Removes the fractional portion of NUMBER or ARRAY and returns the integer part.
Taught in:Part 20 — Daylight Saving and Alignment FailuresOfficial documentation
logreturns NUMBERlog( NUMBER ) log( ARRAY )Calculates the natural logarithm of NUMBER or ARRAY.
Taught in:Part 4 — Linear versus Logarithmic ScalingPart 33 — Sequence Risk and Risk of RuinOfficial documentation
Maxreturns ARRAYMax( ARRAY1, ARRAY2 )Returns the largest of the two parameters.
Taught in:Part 37 — Components 7 and 8: Backtest and Robustness EvaluationPart 37 — Component 1: Market DashboardPart 37 — Component 4: Multi-Timeframe ChartPart 37 — Component 3: ScannerPart 37 — Component 2: Stock ExplorationPart 37 — Component 6: The Trading StrategyPart 7 — Candlestick Anatomy and Single-Bar PatternsPart 10 — Project: ATR Volatility IndicatorPart 10 — Project: Multi-Indicator Analysis PanelPart 30 — Insufficient Evidence and Regime DependencePart 31 — Best Value versus Robust RegionPart 31 — Lab: Optimise Without Fooling YourselfPart 31 — What Optimize() Actually DoesPart 34 — Drawdown and Risk of Ruin in PracticePart 34 — Lab: Same Strategy, Three Position-Sizing ModelsPart 34 — Risk Per Trade and Stop DistancePart 34 — Volatility-Based Position SizingPart 35 — From Candidate to DecisionOfficial documentation
Minreturns ARRAYMin( ARRAY1, ARRAY2 )Returns the smallest of the two parameters.
Taught in:Part 37 — Component 1: Market DashboardPart 7 — Candlestick Anatomy and Single-Bar PatternsPart 10 — Project: ATR Volatility IndicatorPart 10 — Project: Multi-Indicator Analysis PanelPart 28 — Position Sizing with SetPositionSize()Part 30 — Insufficient Evidence and Regime DependencePart 30 — Position Sizing and Portfolio ErrorsPart 34 — Lab: Same Strategy, Three Position-Sizing ModelsPart 34 — Risk Per Trade and Stop DistancePart 34 — Volatility-Based Position SizingPart 35 — From Candidate to DecisionOfficial documentation
SafeDividereturns NUMBERAFL 4.40SafeDivide( 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.
Taught in:Part 37 — Components 7 and 8: Backtest and Robustness EvaluationPart 37 — Component 1: Market DashboardPart 37 — Component 4: Multi-Timeframe ChartPart 37 — Component 5: Real-Time or Replay WorkspacePart 37 — Component 3: ScannerPart 37 — Component 2: Stock ExplorationPart 37 — Component 6: The Trading StrategyPart 5 — Consolidation and Volatility ContractionPart 5 — Reality Check: Do Support Levels Actually Hold?Part 7 — Candlestick Anatomy and Single-Bar PatternsPart 7 — Context, Evidence and Base RatesPart 7 — Multi-Bar Candlestick PatternsPart 7 — Reality Check: Can We Test Whether a Pattern Predicted Anything?Part 8 — Variables, Numbers and ExpressionsPart 16 — Breadth Divergence and Market RegimePart 16 — Project: Market Breadth DashboardPart 28 — Portfolio Backtesting: Many Symbols, One AccountPart 28 — Position Sizing with SetPositionSize()Part 28 — Stops with ApplyStop()Part 30 — Insufficient Evidence and Regime DependencePart 30 — Position Sizing and Portfolio ErrorsPart 30 — Unrealistic Fills, Costs and LiquidityOfficial documentation
signreturns ARRAYAFL 2.50sign( 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.
Taught in:Part 22 — Time & Sales: What It Does and Does Not Tell YouOfficial documentation
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.
Taught in:Part 33 — What Monte Carlo Can and Cannot Tell YouPart 36 — Matrices and Advanced Data HandlingOfficial documentation
Matrix functions
Matrixreturns MatrixAFL 4.0Matrix( 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...
Taught in:Part 36 — Matrices and Advanced Data HandlingOfficial documentation
MxCopyreturns NOTHINGAFL 4.40MxCopy( & 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
Taught in:Part 36 — Matrices and Advanced Data HandlingOfficial documentation
MxDetreturns NUMBERAFL 4.10MxDet( 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
Taught in:Part 36 — Matrices and Advanced Data HandlingOfficial documentation
MxFromStringreturns MatrixAFL 4.10MxFromString(''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 ]
Taught in:Part 36 — Matrices and Advanced Data HandlingOfficial documentation
MxGetBlockreturns MatrixAFL 4.10MxGetBlock( 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.
Taught in:Part 36 — Matrices and Advanced Data HandlingOfficial documentation
MxGetSizereturns NumberAFL 4.0MxGetSize( 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
Taught in:Part 36 — Matrices and Advanced Data HandlingOfficial documentation
MxIdentityreturns MatrixAFL 4.0MxIdentity( 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).
Taught in:Part 36 — Matrices and Advanced Data HandlingOfficial documentation
MxInversereturns MatrixAFL 4.10MxInverse( 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.
Taught in:Part 36 — Matrices and Advanced Data HandlingOfficial documentation
MxSetBlockreturns MatrixAFL 4.10MxSetBlock( 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.
Taught in:Part 36 — Matrices and Advanced Data HandlingOfficial documentation
MxSolvereturns MatrixAFL 4.10MxSolve( 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.
Taught in:Part 36 — Matrices and Advanced Data HandlingOfficial documentation
MxSortreturns MatrixAFL 4.10MxSort( 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
Taught in:Part 36 — Matrices and Advanced Data HandlingOfficial documentation
MxSortRowsreturns MatrixAFL 4.10MxSortRows( 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.
Taught in:Part 36 — Matrices and Advanced Data HandlingOfficial documentation
MxSumreturns NUMBERAFL 4.20MxSum( matrix )The function calculates sum of all elements of matrix (grand sum)
Taught in:Part 36 — Matrices and Advanced Data HandlingOfficial documentation
MxToStringreturns StringAFL 4.10MxToString( 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 } }"
Taught in:Part 36 — Matrices and Advanced Data HandlingOfficial documentation
MxTransposereturns MatrixAFL 4.0MxTranspose( 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.
Taught in:Part 36 — Matrices and Advanced Data HandlingOfficial documentation
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
Taught in:Part 8 — Errors, Debugging and Sanity ChecksPart 11 — Defensive AFL: Guarding Against Bad Input and Bad DataPart 11 — Project: Your Personal AFL Utility LibraryPart 36 — Advanced Debugging and TracingOfficial documentation
_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
Taught in:Part 8 — Errors, Debugging and Sanity ChecksPart 11 — Defensive AFL: Guarding Against Bad Input and Bad DataPart 36 — Advanced Debugging and TracingOfficial documentation
ColorHSBreturns NUMBERAFL 2.80ColorHSB( 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.
Taught in:Part 10 — Plotting with Plot(): Styles, Colours and PanesPart 12 — Conditional Formatting, Sorting and Ranking ColumnsOfficial documentation
ColorRGBreturns NUMBERAFL 2.80ColorRGB( 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.
Taught in:Part 10 — Plotting with Plot(): Styles, Colours and PanesOfficial documentation
GetFormulaPathreturns STRINGAFL 3.90GetFormulaPath()The function returns full file path of current formula
Taught in:Part 12 — Exporting Results and Building a Daily WorkflowOfficial documentation
GetPerformanceCounterreturns NUMBERAFL 2.90GetPerformanceCounter( 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.
Taught in:Part 23 — RequestTimedRefresh() and Real-Time PerformancePart 24 — Repeat Scanning: Mechanics and CostsPart 36 — Advanced Debugging and TracingPart 36 — Performance: QuickAFL, Multi-Threading and CostOfficial documentation
GetRTDatareturns NUMBERAFL 2.60GetRTData(''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
Taught in:Part 37 — Capstone Overview and RequirementsPart 37 — Component 5: Real-Time or Replay WorkspacePart 17 — Edition Requirements and the Three Access LevelsPart 18 — Appendix: eSignal and Other Supported FeedsPart 22 — Quote Fields and the Real-Time Quote WindowPart 23 — GetRTData() and the Live Quote FieldsPart 23 — Project: Real-Time Quote DashboardOfficial documentation
GetRTDataForeignreturns NUMBERAFL 2.80GetRTDataForeign( ''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)
Taught in:Part 17 — Edition Requirements and the Three Access LevelsPart 18 — Appendix: eSignal and Other Supported FeedsPart 22 — Quote Fields and the Real-Time Quote WindowPart 23 — GetRTData() and the Live Quote FieldsOfficial documentation
IsEmptyreturns ARRAYAFL 1.5IsEmpty( 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.
Taught in:Part 8 — Null Values, Nz() and Warm-Up PeriodsOfficial documentation
IsFinitereturns NUMBER,AFL 2.3IsFinite( x )returns a nonzero value (1 or TRUE) if its argument x is not infinite, that is, if –INF x can be number or array
Taught in:Part 8 — Variables, Numbers and ExpressionsPart 11 — Defensive AFL: Guarding Against Bad Input and Bad DataPart 11 — Include Files and Building a LibraryPart 11 — Project: Your Personal AFL Utility LibraryPart 11 — User-Defined Functions and ProceduresOfficial documentation
IsNullreturns NUMBER,AFL 2.3IsNull( x )this function is synonym of IsEmpty(). Gives True if value is equal to Null (empty) value.
Taught in:Part 37 — Components 7 and 8: Backtest and Robustness EvaluationPart 37 — Component 1: Market DashboardPart 37 — Component 4: Multi-Timeframe ChartPart 37 — Component 5: Real-Time or Replay WorkspacePart 37 — Component 3: ScannerPart 37 — Component 2: Stock ExplorationPart 37 — Component 6: The Trading StrategyPart 5 — Reality Check: Do Support Levels Actually Hold?Part 6 — Reality Check: Does RSI Above 70 Mean Sell?Part 7 — Reality Check: Can We Test Whether a Pattern Predicted Anything?Part 8 — Null Values, Nz() and Warm-Up PeriodsPart 9 — Referencing Past Bars with Ref()Part 9 — ValueWhen(): Carrying a Value ForwardPart 11 — Defensive AFL: Guarding Against Bad Input and Bad DataPart 11 — Include Files and Building a LibraryPart 11 — Project: Your Personal AFL Utility LibraryPart 12 — Challenge: The Scan That Returns NothingPart 12 — Project: Build a Daily Stock ScreenerPart 12 — Reality Check: Do High-Volume Breakouts Lead Anywhere?Part 15 — Data Alignment Pitfalls Across SymbolsPart 18 — Appendix: eSignal and Other Supported FeedsPart 18 — Appendix: IQFeedPart 23 — GetRTData() and the Live Quote FieldsPart 23 — Project: Real-Time Quote DashboardPart 30 — Insufficient Evidence and Regime DependencePart 31 — Lab: Optimise Without Fooling YourselfPart 31 — What Optimize() Actually DoesPart 35 — Defining Your Universe and Market RegimePart 36 — Dynamic Variables: VarSet, VarGet and FriendsOfficial documentation
IsTruereturns ARRAYAFL 1.5istrue( ARRAY )returns 1 (or 'true') when given point is not {empty} AND not zero
Taught in:Part 8 — Boolean Arrays: Close > MA(Close, 50)Part 9 — Challenge: State or Event?Part 9 — Cleaning Signals: ExRem, ExRemSpan and FlipPart 9 — Counting and Accumulating: BarsSince, Cum, SumPart 9 — State versus Event: The Distinction That Breaks FormulasPart 12 — Challenge: The Scan That Returns NothingPart 12 — Exporting Results and Building a Daily WorkflowPart 12 — Project: Build a Daily Stock ScreenerPart 12 — Reality Check: Do High-Volume Breakouts Lead Anywhere?Part 16 — Breadth Divergence and Market RegimePart 16 — Building Composites with AddToComposite()Part 16 — Project: Market Breadth DashboardOfficial documentation
NullCountreturns NUMBERAFL 3.90NullCount( 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)
Taught in:Part 6 — ADX and Directional MovementPart 8 — Errors, Debugging and Sanity ChecksPart 8 — Null Values, Nz() and Warm-Up PeriodsPart 9 — Challenge: State or Event?Part 9 — Referencing Past Bars with Ref()Part 9 — Running Extremes: HHV, LLV and FriendsPart 11 — Defensive AFL: Guarding Against Bad Input and Bad DataPart 14 — TimeFrameSet() and TimeFrameRestore()Official documentation
Nzreturns NUMBER,AFL 2.3Nz( 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.
Taught in:Part 37 — Components 7 and 8: Backtest and Robustness EvaluationPart 37 — Component 1: Market DashboardPart 37 — Component 6: The Trading StrategyPart 2 — Data Defects in PracticePart 2 — Lab: Prove That Bad Data Breaks AnalysisPart 3 — Importing and Updating Market DataPart 4 — Linear versus Logarithmic ScalingPart 6 — Reality Check: Does RSI Above 70 Mean Sell?Part 7 — Context, Evidence and Base RatesPart 7 — Reality Check: Can We Test Whether a Pattern Predicted Anything?Part 8 — Boolean Arrays: Close > MA(Close, 50)Part 8 — Errors, Debugging and Sanity ChecksPart 8 — Null Values, Nz() and Warm-Up PeriodsPart 8 — Variables, Numbers and ExpressionsPart 10 — Project: Trend Regime IndicatorPart 11 — Defensive AFL: Guarding Against Bad Input and Bad DataPart 11 — Project: Your Personal AFL Utility LibraryPart 11 — Variable Scope: local, global and the TrapsPart 12 — Building Screening Filters That Mean SomethingPart 12 — Challenge: The Scan That Returns NothingPart 13 — Static Variables for Cross-Sectional WorkPart 16 — Building Composites with AddToComposite()Part 16 — Project: Market Breadth DashboardPart 18 — Choosing a Data Source: A Decision FrameworkPart 18 — Free and End-of-Day Sources with AmiQuotePart 18 — Appendix: IQFeedPart 20 — Challenge: The Opening Range That MovedPart 20 — Daylight Saving and Alignment FailuresPart 20 — Sessions: Regular Hours, Pre-Market and After-HoursPart 21 — Challenge: The Chart That Stopped UpdatingPart 21 — Feed Updating versus Chart RefreshPart 24 — Defining Intraday Setup ConditionsPart 28 — Reality Check: Is the Golden Cross Worth Anything?Part 28 — Stops with ApplyStop()Part 29 — Equity Curve AnalysisPart 30 — Insufficient Evidence and Regime DependencePart 34 — Lab: Same Strategy, Three Position-Sizing ModelsPart 34 — Risk Per Trade and Stop DistancePart 34 — Volatility-Based Position SizingPart 35 — The Research Lifecycle End to EndPart 35 — Defining Your Universe and Market RegimePart 36 — Static Variables in DepthOfficial documentation
PlaySoundreturns NUMBERAFL 3.40PlaySound( "filename" )The function plays back specified .WAV file. Returns 1 on success, 0 on failure
Taught in:Part 25 — Alert Mechanisms and AlertIf()Part 35 — From Candidate to DecisionOfficial documentation
SendEmailreturns NOTHINGAFL 3.90SendEmail(''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.
Taught in:Part 25 — Alert Mechanisms and AlertIf()Part 35 — From Candidate to DecisionOfficial documentation
SetBarsRequiredreturns nothingAFL 2.1SetBarsRequired( 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.
Taught in:Part 37 — Components 7 and 8: Backtest and Robustness EvaluationPart 37 — Component 1: Market DashboardPart 37 — Component 4: Multi-Timeframe ChartPart 37 — Capstone Overview and RequirementsPart 37 — Component 3: ScannerPart 37 — Component 2: Stock ExplorationPart 7 — Reality Check: Can We Test Whether a Pattern Predicted Anything?Part 9 — Challenge: State or Event?Part 9 — Cleaning Signals: ExRem, ExRemSpan and FlipPart 9 — Counting and Accumulating: BarsSince, Cum, SumPart 9 — Running Extremes: HHV, LLV and FriendsPart 14 — Project: Multi-Timeframe Trend IndicatorPart 14 — Project: Multi-Timeframe ScannerPart 14 — TimeFrameSet() and TimeFrameRestore()Part 16 — Building Composites with AddToComposite()Part 16 — Project: Market Breadth DashboardPart 24 — Defining Intraday Setup ConditionsPart 24 — Project: Intraday Breakout ScannerPart 24 — Repeat Scanning: Mechanics and CostsPart 28 — Stops with ApplyStop()Part 29 — Equity Curve AnalysisPart 30 — Insufficient Evidence and Regime DependencePart 30 — Look-Ahead BiasPart 30 — Survivorship and Selection BiasPart 30 — Unrealistic Fills, Costs and LiquidityPart 32 — Interpreting Out-of-Sample DegradationPart 35 — The Research Lifecycle End to EndPart 36 — Advanced Debugging and TracingPart 36 — Performance: QuickAFL, Multi-Threading and CostOfficial documentation
StaticVarAddreturns NOTHINGAFL 4.10StaticVarAdd( "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.
Taught in:Part 36 — Performance: QuickAFL, Multi-Threading and CostPart 36 — Static Variables in DepthOfficial documentation
StaticVarCompareExchangereturns NUMBERAFL 3.50StaticVarCompareExchange( ''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.
Taught in:Part 36 — Static Variables in DepthOfficial documentation
StaticVarCountreturns NUMBERAFL 3.30StaticVarCount()the function returns total number of static variables in memory
Taught in:Part 13 — Static Variables for Cross-Sectional WorkPart 36 — Static Variables in DepthOfficial documentation
StaticVarGenerateRanksreturns NOTHINGAFL 3.70StaticVarGenerateRanks( "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.
Taught in:Part 13 — Project: Market Relative Strength Ranking ToolPart 13 — StaticVarGenerateRanks() and Top-N SelectionPart 30 — Look-Ahead BiasOfficial documentation
StaticVarGetreturns NUMBERAFL 2.60StaticVarGet( ''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).
Taught in:Part 12 — Exporting Results and Building a Daily WorkflowPart 13 — Project: Market Relative Strength Ranking ToolPart 13 — Static Variables for Cross-Sectional WorkPart 13 — StaticVarGenerateRanks() and Top-N SelectionPart 21 — Challenge: The Chart That Stopped UpdatingPart 21 — Feed Updating versus Chart RefreshPart 21 — Lab: Build a Real-Time Trading LayoutPart 23 — RequestTimedRefresh() and Real-Time PerformancePart 36 — Static Variables in DepthOfficial documentation
StaticVarGetRankedSymbolsreturns STRINGAFL 3.70StaticVarGetRankedSymbols( "outputprefix", "inputprefix", datetime )Retrieves the comma-separated list of symbols from static variables generated using StaticVarGenerateRanks. For more information see StaticVarGenerateRanks documentation.
Taught in:Part 13 — StaticVarGenerateRanks() and Top-N SelectionOfficial documentation
StaticVarGetTextreturns STRINGAFL 2.60StaticVarGetText( ''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.
Taught in:Part 36 — Static Variables in DepthOfficial documentation
StaticVarInforeturns STRINGAFL 3.60StaticVarInfo( ''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.
Taught in:Part 13 — Static Variables for Cross-Sectional WorkPart 36 — Static Variables in DepthOfficial documentation
StaticVarRemovereturns NOTHINGAFL 2.80StaticVarRemove( ''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.
Taught in:Part 13 — Project: Market Relative Strength Ranking ToolPart 13 — Static Variables for Cross-Sectional WorkPart 13 — StaticVarGenerateRanks() and Top-N SelectionPart 36 — Static Variables in DepthOfficial documentation
StaticVarSetreturns NUMBERAFL 2.60StaticVarSet( ''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.
Taught in:Part 12 — Exporting Results and Building a Daily WorkflowPart 13 — Project: Market Relative Strength Ranking ToolPart 13 — Static Variables for Cross-Sectional WorkPart 13 — StaticVarGenerateRanks() and Top-N SelectionPart 21 — Challenge: The Chart That Stopped UpdatingPart 21 — Feed Updating versus Chart RefreshPart 21 — Lab: Build a Real-Time Trading LayoutPart 23 — RequestTimedRefresh() and Real-Time PerformancePart 36 — Performance: QuickAFL, Multi-Threading and CostPart 36 — Static Variables in DepthOfficial documentation
StaticVarSetTextAFL 2.60StaticVarSetText( ''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'.
Taught in:Part 36 — Static Variables in DepthOfficial documentation
Statusreturns NUMBERAFL 1.65status( ''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).
Taught in:Part 37 — Components 7 and 8: Backtest and Robustness EvaluationPart 37 — Component 4: Multi-Timeframe ChartPart 37 — Capstone Overview and RequirementsPart 37 — Component 9: The Research ReportPart 37 — Component 3: ScannerPart 37 — Component 2: Stock ExplorationPart 2 — Data Defects in PracticePart 2 — Lab: Prove That Bad Data Breaks AnalysisPart 2 — Survivorship, Delistings and Index MembershipPart 3 — Importing and Updating Market DataPart 3 — Lab: Install AmiBroker and Verify Your SetupPart 6 — Reality Check: Does RSI Above 70 Mean Sell?Part 7 — Reality Check: Can We Test Whether a Pattern Predicted Anything?Part 8 — What AFL Is and Where It RunsPart 9 — Challenge: State or Event?Part 9 — Cleaning Signals: ExRem, ExRemSpan and FlipPart 9 — Counting and Accumulating: BarsSince, Cum, SumPart 11 — Project: Your Personal AFL Utility LibraryPart 12 — The Analysis Window and Its Four ModesPart 12 — Building Screening Filters That Mean SomethingPart 12 — Challenge: The Scan That Returns NothingPart 12 — Exploration: Filter, AddColumn and AddTextColumnPart 12 — Exporting Results and Building a Daily WorkflowPart 12 — Lab: Your First ScanPart 12 — Project: Build a Daily Stock ScreenerPart 12 — Reality Check: Do High-Volume Breakouts Lead Anywhere?Part 13 — Project: Market Relative Strength Ranking ToolPart 13 — Static Variables for Cross-Sectional WorkPart 15 — Benchmarks and Relative PerformancePart 15 — Data Alignment Pitfalls Across SymbolsPart 15 — Project: Relative Strength Comparison ToolPart 16 — Breadth Divergence and Market RegimePart 16 — Building Composites with AddToComposite()Part 16 — Project: Market Breadth DashboardPart 17 — Plugins and the Database RelationshipPart 17 — The Real-Time Architecture, End to EndPart 18 — Choosing a Data Source: A Decision FrameworkPart 18 — Free and End-of-Day Sources with AmiQuotePart 18 — Appendix: eSignal and Other Supported FeedsPart 19 — Backfill and Database MaintenancePart 19 — The Base Interval DecisionPart 19 — Challenge: The History That Is Not All TherePart 19 — Intraday Database Settings in DetailPart 19 — Lab: Build an Intraday Market DatabasePart 20 — Challenge: The Opening Range That MovedPart 20 — Daylight Saving and Alignment FailuresPart 20 — Exchange Time versus Your ClockPart 21 — Challenge: The Chart That Stopped UpdatingPart 21 — Feed Updating versus Chart RefreshPart 21 — Lab: Build a Real-Time Trading LayoutPart 22 — Quote Fields and the Real-Time Quote WindowPart 23 — Knowing Where You Are: Status() and Execution ContextPart 23 — GetRTData() and the Live Quote FieldsPart 23 — Project: Real-Time Quote DashboardPart 23 — RequestTimedRefresh() and Real-Time PerformancePart 24 — Repeat Scanning: Mechanics and CostsPart 26 — Replay Exercise: Reading a Session LivePart 28 — Project: A Realistic Portfolio BacktestPart 28 — Reality Check: Is the Golden Cross Worth Anything?Part 28 — Single-Symbol Thinking versus Portfolio RealityPart 28 — Stops with ApplyStop()Part 30 — Data Snooping, Curve Fitting and OverfittingPart 30 — Insufficient Evidence and Regime DependencePart 30 — Survivorship and Selection BiasPart 30 — Unrealistic Fills, Costs and LiquidityPart 32 — In-Sample and Out-of-SamplePart 33 — What Monte Carlo Can and Cannot Tell YouPart 34 — Portfolio Exposure, Concentration and CorrelationPart 35 — Journalling and Separating Two Kinds of PerformancePart 35 — The Research Lifecycle End to EndPart 35 — Defining Your Universe and Market RegimePart 36 — Introduction to the Custom Backtester InterfacePart 36 — Advanced Debugging and TracingPart 36 — Performance: QuickAFL, Multi-Threading and CostPart 36 — Static Variables in DepthOfficial documentation
Studyreturns ARRAYAFL 1.5Study( 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).
Taught in:Part 3 — Navigating and Scaling ChartsPart 5 — Trendlines and ChannelsOfficial documentation
ThreadSleepreturns NOTHINGAFL 3.50ThreadSleep( 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.
Taught in:Part 36 — Static Variables in DepthOfficial documentation
VarGetreturns ARRAYAFL 2.60VarGet( ''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.
Taught in:Part 36 — Dynamic Variables: VarSet, VarGet and FriendsOfficial documentation
VarGetTextreturns STRINGAFL 2.80VarGetText( ''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
Taught in:Part 36 — Dynamic Variables: VarSet, VarGet and FriendsOfficial documentation
VarSetreturns NUMBERAFL 2.60VarSet( ''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.
Taught in:Part 36 — Dynamic Variables: VarSet, VarGet and FriendsOfficial documentation
VarSetTextreturns STRINGAFL 2.80VarSetText( ''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.
Taught in:Part 36 — Dynamic Variables: VarSet, VarGet and FriendsOfficial documentation
Versionreturns NUMBERAFL 1.9Version( 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 :)
Taught in:Part 3 — Lab: Install AmiBroker and Verify Your SetupPart 11 — Defensive AFL: Guarding Against Bad Input and Bad DataPart 11 — Include Files and Building a LibraryPart 11 — Project: Your Personal AFL Utility LibraryOfficial documentation
Moving averages, summation
AMAreturns ARRAYAFL 1.5ama ( ARRAY, SMOOTHINGFACTOR )calculates adaptive moving average - simliar to EMA() but smoothing factor could be time-variant (array).
Taught in:Part 6 — Moving Averages: SMA and EMAPart 8 — Logic, Conditionals and IIf()Part 36 — Advanced Debugging and TracingPart 36 — Performance: QuickAFL, Multi-Threading and CostOfficial documentation
Cumreturns ARRAYCum( 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.
Taught in:Part 37 — Component 4: Multi-Timeframe ChartPart 37 — Component 5: Real-Time or Replay WorkspacePart 2 — Data Defects in PracticePart 2 — Lab: Prove That Bad Data Breaks AnalysisPart 2 — Survivorship, Delistings and Index MembershipPart 3 — Importing and Updating Market DataPart 3 — Lab: Install AmiBroker and Verify Your SetupPart 4 — Lab: Structured Chart InterpretationPart 4 — Swings, Highs and LowsPart 6 — Moving Average Slope and CrossoversPart 6 — Reality Check: Does RSI Above 70 Mean Sell?Part 7 — Candlestick Anatomy and Single-Bar PatternsPart 7 — Context, Evidence and Base RatesPart 7 — Multi-Bar Candlestick PatternsPart 7 — Reality Check: Can We Test Whether a Pattern Predicted Anything?Part 8 — Boolean Arrays: Close > MA(Close, 50)Part 8 — Errors, Debugging and Sanity ChecksPart 9 — Challenge: State or Event?Part 9 — Cleaning Signals: ExRem, ExRemSpan and FlipPart 9 — Counting and Accumulating: BarsSince, Cum, SumPart 9 — State versus Event: The Distinction That Breaks FormulasPart 11 — Project: Your Personal AFL Utility LibraryPart 11 — Variable Scope: local, global and the TrapsPart 14 — Expansion Modes and the Look-Ahead TrapPart 14 — Project: Multi-Timeframe Trend IndicatorPart 14 — Project: Multi-Timeframe ScannerPart 15 — Benchmarks and Relative PerformancePart 15 — Data Alignment Pitfalls Across SymbolsPart 15 — Project: Relative Strength Comparison ToolPart 16 — Breadth Divergence and Market RegimePart 16 — Building Composites with AddToComposite()Part 16 — Project: Market Breadth DashboardPart 17 — Plugins and the Database RelationshipPart 18 — Choosing a Data Source: A Decision FrameworkPart 18 — Free and End-of-Day Sources with AmiQuotePart 20 — Challenge: The Opening Range That MovedPart 20 — Daylight Saving and Alignment FailuresPart 20 — Sessions: Regular Hours, Pre-Market and After-HoursPart 22 — Time & Sales: What It Does and Does Not Tell YouPart 25 — Duplicate Alerts and How to Stop ThemPart 28 — Reality Check: Is the Golden Cross Worth Anything?Part 28 — Stops with ApplyStop()Part 30 — Insufficient Evidence and Regime DependencePart 33 — Sequence Risk and Risk of RuinPart 33 — What Monte Carlo Can and Cannot Tell YouPart 34 — Portfolio Exposure, Concentration and CorrelationPart 36 — Performance: QuickAFL, Multi-Threading and CostOfficial documentation
DEMAreturns ARRAYAFL 2.0dema( ARRAY, periods )Calculates double exponentially smoothed average - DEMA. The function accepts time-variable periods.
Taught in:Part 10 — Project: Configurable Moving-Average IndicatorOfficial documentation
EMAreturns ARRAYema ( ARRAY, periods )Calculates a periods exponential moving average of ARRAY
Taught in:Part 6 — Lab: Indicator Behaviour WorkbenchPart 6 — Moving Averages: SMA and EMAPart 6 — What an Indicator Actually IsPart 10 — Project: Configurable Moving-Average IndicatorPart 28 — Backtester Basics: Signals and Trade PricesOfficial documentation
MAreturns ARRAYma( 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).
Taught in:Part 37 — Components 7 and 8: Backtest and Robustness EvaluationPart 37 — Component 1: Market DashboardPart 37 — Component 4: Multi-Timeframe ChartPart 37 — Component 5: Real-Time or Replay WorkspacePart 37 — Component 3: ScannerPart 37 — Component 2: Stock ExplorationPart 37 — Component 6: The Trading StrategyPart 2 — Lab: Prove That Bad Data Breaks AnalysisPart 3 — Lab: Build Your First AmiBroker WorkspacePart 5 — Breakouts, Failed Breakouts and Role ReversalPart 6 — Lab: Indicator Behaviour WorkbenchPart 6 — Moving Averages: SMA and EMAPart 6 — Volatility: True Range, ATR and Bollinger BandsPart 6 — Volume and Volume-Based IndicatorsPart 6 — What an Indicator Actually IsPart 7 — Context, Evidence and Base RatesPart 7 — Reality Check: Can We Test Whether a Pattern Predicted Anything?Part 8 — Boolean Arrays: Close > MA(Close, 50)Part 8 — Errors, Debugging and Sanity ChecksPart 8 — Logic, Conditionals and IIf()Part 8 — Null Values, Nz() and Warm-Up PeriodsPart 8 — Syntax Basics: Statements, Comments and NamesPart 8 — The Array Model: The Most Important Lesson in This CoursePart 8 — Variables, Numbers and ExpressionsPart 8 — Your First FormulaPart 10 — Project: Configurable Moving-Average IndicatorPart 10 — Project: Multi-Indicator Analysis PanelPart 10 — Project: Trend Regime IndicatorPart 11 — Defensive AFL: Guarding Against Bad Input and Bad DataPart 11 — Project: Your Personal AFL Utility LibraryPart 11 — User-Defined Functions and ProceduresPart 11 — Variable Scope: local, global and the TrapsPart 12 — Building Screening Filters That Mean SomethingPart 12 — Challenge: The Scan That Returns NothingPart 12 — Exporting Results and Building a Daily WorkflowPart 12 — Lab: Your First ScanPart 12 — Reality Check: Do High-Volume Breakouts Lead Anywhere?Part 16 — Project: Market Breadth DashboardPart 26 — Replay Exercise: Reading a Session LivePart 27 — Execution Assumptions You Must StatePart 27 — From Hypothesis to RulesPart 27 — Project: Your First Complete Trading SystemPart 27 — From Rules to AFLPart 28 — Costs: Commissions, Slippage and the SpreadPart 28 — Portfolio Backtesting: Many Symbols, One AccountPart 28 — Position Sizing with SetPositionSize()Part 28 — Project: A Realistic Portfolio BacktestPart 28 — Reality Check: Is the Golden Cross Worth Anything?Part 28 — Single-Symbol Thinking versus Portfolio RealityPart 28 — Stops with ApplyStop()Part 29 — Reading the Backtest ReportPart 30 — Challenge Collection: Six Broken BacktestsPart 30 — Challenge: 180% a Year with a 3% DrawdownPart 30 — Data Snooping, Curve Fitting and OverfittingPart 30 — Insufficient Evidence and Regime DependencePart 30 — Position Sizing and Portfolio ErrorsPart 30 — Unrealistic Fills, Costs and LiquidityPart 31 — Best Value versus Robust RegionPart 31 — Lab: Optimise Without Fooling YourselfPart 31 — Reading Parameter SurfacesPart 31 — What Optimize() Actually DoesPart 32 — Lab: Run a Walk-Forward AnalysisPart 33 — The AmiBroker Monte Carlo WorkflowPart 34 — Lab: Same Strategy, Three Position-Sizing ModelsPart 35 — Defining Your Universe and Market RegimePart 36 — Introduction to the Custom Backtester InterfacePart 36 — Matrices and Advanced Data HandlingOfficial documentation
Sumreturns ARRAYSum( 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).
Taught in:Part 5 — Reality Check: Do Support Levels Actually Hold?Part 8 — Boolean Arrays: Close > MA(Close, 50)Part 9 — Counting and Accumulating: BarsSince, Cum, SumPart 10 — Project: Trend Regime IndicatorPart 20 — Challenge: The Opening Range That MovedPart 36 — Matrices and Advanced Data HandlingOfficial documentation
SumSincereturns ArrayAFL 4.10SumSince( 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.
Taught in:Part 9 — Counting and Accumulating: BarsSince, Cum, SumPart 24 — Defining Intraday Setup ConditionsPart 24 — Project: Intraday Breakout ScannerOfficial documentation
TEMAreturns ARRAYAFL 2.0tema( ARRAY, periods )Calculates triple exponentially smoothed average - TEMA. The function accepts time-variable periods.
Taught in:Part 10 — Project: Configurable Moving-Average IndicatorOfficial documentation
Wildersreturns ARRAYAFL 1.4Wilders( ARRAY, periods )Calculates Wilder's average of the ARRAY using periods averaging range
Taught in:Part 6 — ADX and Directional MovementPart 10 — Project: Configurable Moving-Average IndicatorOfficial documentation
WMAreturns ARRAYAFL 2.0wma( 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.
Taught in:Part 6 — Moving Averages: SMA and EMAPart 10 — Project: Configurable Moving-Average IndicatorOfficial documentation
Referencing other symbol data
Foreignreturns ARRAYAFL 1.5foreign ( 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
Taught in:Part 37 — Components 7 and 8: Backtest and Robustness EvaluationPart 37 — Component 1: Market DashboardPart 37 — Capstone Overview and RequirementsPart 37 — Component 3: ScannerPart 37 — Component 2: Stock ExplorationPart 37 — Component 6: The Trading StrategyPart 2 — Splits, Dividends and Adjusted DataPart 13 — Relative Strength: What It Does and Does Not MeanPart 15 — Benchmarks and Relative PerformancePart 15 — Data Alignment Pitfalls Across SymbolsPart 15 — Foreign(), SetForeign() and RestorePriceArrays()Part 15 — Project: Relative Strength Comparison ToolPart 15 — Sectors and Intermarket AnalysisPart 16 — Breadth Concepts: Participation and Its MeasuresPart 16 — Breadth Divergence and Market RegimePart 16 — Building Composites with AddToComposite()Part 16 — Project: Market Breadth DashboardPart 29 — Equity Curve AnalysisPart 30 — Insufficient Evidence and Regime DependencePart 33 — What Monte Carlo Can and Cannot Tell YouPart 34 — Drawdown and Risk of Ruin in PracticePart 34 — Portfolio Exposure, Concentration and CorrelationPart 35 — From Candidate to DecisionPart 35 — Journalling and Separating Two Kinds of PerformancePart 35 — Defining Your Universe and Market RegimeOfficial documentation
GetBaseIndexreturns STRINGAFL 2.1GetBaseIndex( )Retrieves base relative-strength index for given security as defined in Symbol->Categories.
Taught in:Part 15 — Benchmarks and Relative PerformancePart 15 — Foreign(), SetForeign() and RestorePriceArrays()Part 15 — Project: Relative Strength Comparison ToolOfficial documentation
PlotForeignreturns NUMBERAFL 2.2PlotForeign( 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).
Taught in:Part 15 — Foreign(), SetForeign() and RestorePriceArrays()Part 32 — The AmiBroker Walk-Forward WorkflowPart 32 — Lab: Run a Walk-Forward AnalysisOfficial documentation
RelStrengthreturns ARRAYAFL 1.3RelStrength( "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.
Taught in:Part 13 — Relative Strength: What It Does and Does Not MeanPart 15 — Benchmarks and Relative PerformancePart 15 — Foreign(), SetForeign() and RestorePriceArrays()Official documentation
RestorePriceArraysreturns NOTHINGAFL 2.5RestorePriceArrays( 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.
Taught in:Part 13 — Project: Market Relative Strength Ranking ToolPart 13 — Relative Strength: What It Does and Does Not MeanPart 13 — Static Variables for Cross-Sectional WorkPart 15 — Foreign(), SetForeign() and RestorePriceArrays()Part 36 — Dynamic Variables: VarSet, VarGet and FriendsOfficial documentation
SetForeignreturns NUMBERAFL 2.5SetForeign( 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.
Taught in:Part 13 — Project: Market Relative Strength Ranking ToolPart 13 — Relative Strength: What It Does and Does Not MeanPart 13 — Static Variables for Cross-Sectional WorkPart 15 — Foreign(), SetForeign() and RestorePriceArrays()Part 36 — Dynamic Variables: VarSet, VarGet and FriendsOfficial documentation
Statistical functions
Correlationreturns ARRAYAFL 1.4correlation( 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
Taught in:Part 15 — Sectors and Intermarket AnalysisPart 34 — Portfolio Exposure, Concentration and CorrelationOfficial documentation
LinearRegreturns ARRAYAFL 2.2LinearReg( 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).
Taught in:Part 5 — Trendlines and ChannelsPart 6 — Moving Average Slope and CrossoversOfficial documentation
LinRegSlopereturns ARRAYAFL 1.4LinRegSlope( 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).
Taught in:Part 5 — Trendlines and ChannelsPart 6 — Moving Average Slope and CrossoversOfficial documentation
Medianreturns ARRAYAFL 2.5Median( 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.
Taught in:Part 37 — Components 7 and 8: Backtest and Robustness EvaluationPart 37 — Component 3: ScannerPart 37 — Component 2: Stock ExplorationPart 37 — Component 6: The Trading StrategyPart 6 — Volume and Volume-Based IndicatorsPart 11 — Project: Your Personal AFL Utility LibraryPart 13 — Project: Market Relative Strength Ranking ToolPart 13 — Ranking versus FilteringPart 30 — Survivorship and Selection BiasOfficial documentation
mtRandomreturns NUMBERAFL 3.0mtRandom( 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.
Taught in:Part 30 — Data Snooping, Curve Fitting and OverfittingPart 33 — The AmiBroker Monte Carlo WorkflowPart 33 — Sequence Risk and Risk of RuinOfficial documentation
mtRandomAreturns ARRAYAFL 3.0mtRandomA( seed = Null )This is array version of mtRandom function For more details please check mtRandom function.
Taught in:Part 30 — Data Snooping, Curve Fitting and OverfittingPart 33 — The AmiBroker Monte Carlo WorkflowPart 33 — The Limits of SimulationOfficial documentation
Percentilereturns ARRAYAFL 2.5Percentile( 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.
Taught in:Part 6 — Volume and Volume-Based IndicatorsPart 10 — Project: ATR Volatility IndicatorOfficial documentation
StDevreturns ARRAYAFL 1.4StDev( 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
Taught in:Part 5 — Consolidation and Volatility ContractionPart 5 — Trendlines and ChannelsPart 6 — Volatility: True Range, ATR and Bollinger BandsPart 11 — Project: Your Personal AFL Utility LibraryPart 34 — Portfolio Exposure, Concentration and CorrelationPart 36 — Matrices and Advanced Data HandlingOfficial documentation
String manipulation
NumToStrreturns STRINGAFL 2.5NumToStr( NUMBER, format = 1.3, separator =True, roundAndPad = False ) NumToStr( ARRAY, format = 1.3, separator =True, roundAndPad = False )It is used to convert numeric value of NUMBER or ARRAY to string. The second parameter - format - allows you to control output formatting (decimal places and leading spaces). The integer part of the number controls minimum number of characters used to display the number (if you specify high number the output will be space-padded).
Taught in:Part 3 — Lab: Build Your First AmiBroker WorkspacePart 4 — Lab: Structured Chart InterpretationPart 6 — Lab: Indicator Behaviour WorkbenchPart 7 — Candlestick Anatomy and Single-Bar PatternsPart 10 — Chart Titles and Dynamic TextPart 10 — Project: Multi-Indicator Analysis PanelPart 11 — Defensive AFL: Guarding Against Bad Input and Bad DataPart 11 — Include Files and Building a LibraryPart 11 — Project: Your Personal AFL Utility LibraryPart 11 — User-Defined Functions and ProceduresPart 12 — Exporting Results and Building a Daily WorkflowPart 18 — Appendix: eSignal and Other Supported FeedsPart 19 — Intraday Database Settings in DetailPart 21 — Intraday Chart Intervals and What They CostPart 36 — Introduction to the Custom Backtester InterfacePart 36 — Advanced Debugging and TracingPart 36 — Dynamic Variables: VarSet, VarGet and FriendsOfficial documentation
printfreturns NOTHINGAFL 2.5printf( 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.
Taught in:Part 8 — Errors, Debugging and Sanity ChecksPart 36 — Advanced Debugging and TracingOfficial documentation
StrCountreturns NUMBERAFL 3.20StrCount( ''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
Taught in:Part 37 — Component 1: Market DashboardOfficial documentation
StrExtractreturns STRINGAFL 2.4StrExtract( 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.
Taught in:Part 37 — Component 1: Market DashboardPart 13 — Static Variables for Cross-Sectional WorkPart 36 — Dynamic Variables: VarSet, VarGet and FriendsOfficial documentation
StrFormatreturns STRINGAFL 2.5StrFormat( 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.
Taught in:Part 37 — Component 1: Market DashboardPart 37 — Component 4: Multi-Timeframe ChartPart 37 — Component 5: Real-Time or Replay WorkspacePart 4 — Chart Types and What Each One ShowsPart 4 — Lab: Structured Chart InterpretationPart 4 — Linear versus Logarithmic ScalingPart 4 — Market Structure: Trends, Ranges and TransitionsPart 8 — Boolean Arrays: Close > MA(Close, 50)Part 8 — Errors, Debugging and Sanity ChecksPart 8 — Logic, Conditionals and IIf()Part 8 — Null Values, Nz() and Warm-Up PeriodsPart 8 — The Array Model: The Most Important Lesson in This CoursePart 8 — Your First FormulaPart 10 — Chart Titles and Dynamic TextPart 10 — Project: ATR Volatility IndicatorPart 10 — Project: Configurable Moving-Average IndicatorPart 10 — Project: Multi-Indicator Analysis PanelPart 10 — Project: Trend Regime IndicatorPart 11 — Defensive AFL: Guarding Against Bad Input and Bad DataPart 11 — Project: Your Personal AFL Utility LibraryPart 11 — Variable Scope: local, global and the TrapsPart 16 — Project: Market Breadth DashboardPart 29 — Equity Curve AnalysisPart 36 — Advanced Debugging and TracingOfficial documentation
StrLeftreturns STRINGAFL 2.0strleft ( 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.
Taught in:Part 12 — Project: Build a Daily Stock ScreenerOfficial documentation
StrLenreturns NUMBERAFL 1.5strlen ( STRING)calculates the length of the string
Taught in:Part 37 — Component 1: Market DashboardPart 37 — Component 3: ScannerPart 37 — Component 6: The Trading StrategyPart 11 — Project: Your Personal AFL Utility LibraryOfficial documentation
Time Frame functions
TimeFrameCompressreturns ARRAYAFL 2.5TimeFrameCompress( 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
Taught in:Part 37 — Component 4: Multi-Timeframe ChartPart 2 — Timeframes, Ticks and How Bars Are BuiltPart 14 — Expansion Modes and the Look-Ahead TrapPart 14 — Project: Multi-Timeframe Trend IndicatorPart 14 — Project: Multi-Timeframe ScannerPart 30 — Look-Ahead BiasOfficial documentation
TimeFrameExpandreturns ARRAYAFL 2.5TimeFrameExpand( 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.
Taught in:Part 37 — Component 4: Multi-Timeframe ChartPart 2 — Timeframes, Ticks and How Bars Are BuiltPart 14 — Expansion Modes and the Look-Ahead TrapPart 14 — Project: Multi-Timeframe Trend IndicatorPart 14 — Project: Multi-Timeframe ScannerPart 14 — TimeFrameSet() and TimeFrameRestore()Part 24 — Defining Intraday Setup ConditionsPart 24 — Project: Intraday Breakout ScannerPart 26 — Replay Exercise: Intraday Setups and AlertsPart 30 — Look-Ahead BiasOfficial documentation
TimeFrameGetPricereturns ARRAYAFL 2.5TimeFrameGetPrice( 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.
Taught in:Part 37 — Component 4: Multi-Timeframe ChartPart 14 — Expansion Modes and the Look-Ahead TrapPart 14 — Project: Multi-Timeframe Trend IndicatorPart 14 — Project: Multi-Timeframe ScannerPart 14 — TimeFrameSet() and TimeFrameRestore()Part 24 — Defining Intraday Setup ConditionsPart 24 — Project: Intraday Breakout ScannerPart 30 — Challenge Collection: Six Broken BacktestsPart 30 — Challenge: 180% a Year with a 3% DrawdownPart 30 — Look-Ahead BiasOfficial documentation
TimeFrameRestorereturns NOTHINGAFL 2.5TimeFrameRestore( 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.
Taught in:Part 37 — Component 4: Multi-Timeframe ChartPart 14 — Expansion Modes and the Look-Ahead TrapPart 14 — Project: Multi-Timeframe Trend IndicatorPart 14 — Project: Multi-Timeframe ScannerPart 14 — TimeFrameSet() and TimeFrameRestore()Part 24 — Defining Intraday Setup ConditionsPart 24 — Project: Intraday Breakout ScannerPart 26 — Replay Exercise: Intraday Setups and AlertsPart 30 — Look-Ahead BiasOfficial documentation
TimeFrameSetreturns NOTHINGAFL 2.5TimeFrameSet( 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.
Taught in:Part 37 — Component 4: Multi-Timeframe ChartPart 2 — Timeframes, Ticks and How Bars Are BuiltPart 14 — Expansion Modes and the Look-Ahead TrapPart 14 — Project: Multi-Timeframe Trend IndicatorPart 14 — Project: Multi-Timeframe ScannerPart 14 — TimeFrameSet() and TimeFrameRestore()Part 24 — Defining Intraday Setup ConditionsPart 24 — Project: Intraday Breakout ScannerPart 26 — Replay Exercise: Intraday Setups and AlertsPart 30 — Look-Ahead BiasOfficial documentation
Trading system toolbox
AlertIfreturns nothingAFL 2.1AlertIf( 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.
Taught in:Part 37 — Component 5: Real-Time or Replay WorkspacePart 20 — Challenge: The Opening Range That MovedPart 21 — Challenge: The Chart That Stopped UpdatingPart 25 — Alert Mechanisms and AlertIf()Part 25 — Duplicate Alerts and How to Stop ThemPart 25 — Project: Real-Time Breakout AlertPart 26 — Replay Exercise: Intraday Setups and AlertsPart 35 — From Candidate to DecisionOfficial documentation
ApplyStopreturns NothingAFL 1.7ApplyStop( type, mode, amount, exitatstop, volatile = False, ReEntryDelay = 0, ValidFrom = 0, ValidTo = -1 )controls built-in stops from the formula level (allows optimization of stops) Parameters: type = 0 = stopTypeLoss - maximum loss stop, 1 = stopTypeProfit - profit target stop, 2 = stopTypeTrailing - tr
Taught in:Part 37 — Components 7 and 8: Backtest and Robustness EvaluationPart 37 — Component 6: The Trading StrategyPart 9 — Cleaning Signals: ExRem, ExRemSpan and FlipPart 27 — Execution Assumptions You Must StatePart 27 — Project: Your First Complete Trading SystemPart 28 — Position Sizing with SetPositionSize()Part 28 — Project: A Realistic Portfolio BacktestPart 28 — Stops with ApplyStop()Part 29 — Reading the Backtest ReportPart 30 — Challenge Collection: Six Broken BacktestsPart 30 — Challenge: 180% a Year with a 3% DrawdownPart 30 — Data Snooping, Curve Fitting and OverfittingPart 30 — Unrealistic Fills, Costs and LiquidityPart 32 — Lab: Run a Walk-Forward AnalysisPart 33 — The AmiBroker Monte Carlo WorkflowPart 34 — Lab: Same Strategy, Three Position-Sizing ModelsPart 34 — Risk Per Trade and Stop DistancePart 34 — Volatility-Based Position SizingOfficial documentation
BarsSincereturns ARRAYBarsSince( ARRAY )Calculates the number of bars (time periods) that have passed since ARRAY was true (or 1)
Taught in:Part 4 — Swings, Highs and LowsPart 5 — Consolidation and Volatility ContractionPart 9 — Challenge: State or Event?Part 9 — Counting and Accumulating: BarsSince, Cum, SumPart 9 — State versus Event: The Distinction That Breaks FormulasPart 9 — ValueWhen(): Carrying a Value ForwardPart 10 — Project: Trend Regime IndicatorPart 16 — Breadth Divergence and Market RegimePart 18 — Free and End-of-Day Sources with AmiQuotePart 27 — From Hypothesis to RulesPart 29 — Equity Curve AnalysisPart 30 — Survivorship and Selection BiasPart 34 — Drawdown and Risk of Ruin in PracticeOfficial documentation
Crossreturns ARRAYCross( 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)
Taught in:Part 37 — Components 7 and 8: Backtest and Robustness EvaluationPart 37 — Component 5: Real-Time or Replay WorkspacePart 37 — Component 3: ScannerPart 37 — Component 6: The Trading StrategyPart 2 — Lab: Prove That Bad Data Breaks AnalysisPart 5 — Breakouts, Failed Breakouts and Role ReversalPart 5 — Trendlines and ChannelsPart 6 — Moving Average Slope and CrossoversPart 6 — MACDPart 9 — Challenge: State or Event?Part 9 — Referencing Past Bars with Ref()Part 9 — Running Extremes: HHV, LLV and FriendsPart 9 — State versus Event: The Distinction That Breaks FormulasPart 9 — ValueWhen(): Carrying a Value ForwardPart 10 — PlotShapes() and Visual SignalsPart 10 — Project: Configurable Moving-Average IndicatorPart 12 — Exporting Results and Building a Daily WorkflowPart 12 — Lab: Your First ScanPart 14 — Project: Multi-Timeframe ScannerPart 20 — Challenge: The Opening Range That MovedPart 24 — Project: Intraday Breakout ScannerPart 25 — Alert Mechanisms and AlertIf()Part 25 — Duplicate Alerts and How to Stop ThemPart 25 — Project: Real-Time Breakout AlertPart 26 — Replay Exercise: Intraday Setups and AlertsPart 27 — From Hypothesis to RulesPart 27 — Project: Your First Complete Trading SystemPart 27 — From Rules to AFLPart 28 — Backtester Basics: Signals and Trade PricesPart 28 — Costs: Commissions, Slippage and the SpreadPart 28 — Portfolio Backtesting: Many Symbols, One AccountPart 28 — Project: A Realistic Portfolio BacktestPart 28 — Reality Check: Is the Golden Cross Worth Anything?Part 28 — Single-Symbol Thinking versus Portfolio RealityPart 28 — Stops with ApplyStop()Part 30 — Insufficient Evidence and Regime DependencePart 31 — Best Value versus Robust RegionPart 31 — Lab: Optimise Without Fooling YourselfPart 31 — What Optimize() Actually DoesPart 33 — The AmiBroker Monte Carlo WorkflowPart 34 — Lab: Same Strategy, Three Position-Sizing ModelsPart 35 — From Candidate to DecisionPart 36 — Introduction to the Custom Backtester InterfaceOfficial documentation
EnableRotationalTradingreturns NOTHINGAFL 2.5EnableRotationalTrading()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.
Taught in:Part 28 — Portfolio Backtesting: Many Symbols, One AccountOfficial documentation
Equityreturns ARRAYAFL 2.0equity ( 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.
Taught in:Part 9 — Cleaning Signals: ExRem, ExRemSpan and FlipPart 28 — Stops with ApplyStop()Official documentation
ExRemreturns ARRAYAFL 1.5exrem ( ARRAY1, ARRAY2 )removes excessive signals: returns 1 on the first occurence of "true" signal in Array1 then returns 0 until Array2 is true even if there are "true" signals in Array1
Taught in:Part 37 — Component 5: Real-Time or Replay WorkspacePart 9 — Challenge: State or Event?Part 9 — Cleaning Signals: ExRem, ExRemSpan and FlipPart 10 — PlotShapes() and Visual SignalsPart 10 — Project: Configurable Moving-Average IndicatorPart 12 — Lab: Your First ScanPart 20 — Challenge: The Opening Range That MovedPart 24 — Project: Intraday Breakout ScannerPart 25 — Duplicate Alerts and How to Stop ThemPart 25 — Project: Real-Time Breakout AlertPart 27 — Execution Assumptions You Must StatePart 27 — From Hypothesis to RulesPart 27 — Project: Your First Complete Trading SystemPart 27 — From Rules to AFLPart 28 — Backtester Basics: Signals and Trade PricesPart 32 — In-Sample and Out-of-SamplePart 32 — Lab: Run a Walk-Forward AnalysisOfficial documentation
ExRemSpanreturns ARRAYAFL 2.0exremspan ( 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.
Taught in:Part 9 — Cleaning Signals: ExRem, ExRemSpan and FlipPart 25 — Duplicate Alerts and How to Stop ThemOfficial documentation
Flipreturns ARRAYAFL 1.5flip ( 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...
Taught in:Part 9 — Challenge: State or Event?Part 9 — Cleaning Signals: ExRem, ExRemSpan and FlipPart 9 — State versus Event: The Distinction That Breaks FormulasPart 10 — PlotShapes() and Visual SignalsPart 16 — Breadth Divergence and Market RegimePart 25 — Duplicate Alerts and How to Stop ThemPart 28 — Stops with ApplyStop()Official documentation
GetBacktesterObjectreturns OBJECTAFL 2.60GetBacktesterObject()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
Taught in:Part 29 — Trade Statistics: Wins, Losses, Payoff and ExpectancyPart 31 — Optimization Targets and Search EnginesPart 36 — Introduction to the Custom Backtester InterfaceOfficial documentation
GetOptionreturns NUMBERAFL 2.60GetOption(''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
Taught in:Part 12 — The Analysis Window and Its Four ModesPart 12 — Exporting Results and Building a Daily WorkflowPart 13 — Project: Market Relative Strength Ranking ToolPart 13 — Static Variables for Cross-Sectional WorkPart 28 — Costs: Commissions, Slippage and the SpreadPart 28 — Project: A Realistic Portfolio BacktestPart 33 — The AmiBroker Monte Carlo WorkflowOfficial documentation
GetTradingInterfacereturns OBJECTAFL 2.70GetTradingInterface(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
Taught in:Part 18 — Appendix: Interactive BrokersPart 35 — From Candidate to DecisionOfficial documentation
IIfreturns ARRAYIIf( 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).
Taught in:Part 37 — Components 7 and 8: Backtest and Robustness EvaluationPart 37 — Component 1: Market DashboardPart 37 — Component 4: Multi-Timeframe ChartPart 37 — Component 5: Real-Time or Replay WorkspacePart 37 — Component 3: ScannerPart 37 — Component 2: Stock ExplorationPart 37 — Component 6: The Trading StrategyPart 2 — OHLCV and What a Bar HidesPart 3 — Importing and Updating Market DataPart 4 — Linear versus Logarithmic ScalingPart 4 — Market Structure: Trends, Ranges and TransitionsPart 4 — Swings, Highs and LowsPart 6 — Reality Check: Does RSI Above 70 Mean Sell?Part 6 — Volume and Volume-Based IndicatorsPart 7 — Context, Evidence and Base RatesPart 7 — Reality Check: Can We Test Whether a Pattern Predicted Anything?Part 8 — Errors, Debugging and Sanity ChecksPart 8 — Logic, Conditionals and IIf()Part 9 — Counting and Accumulating: BarsSince, Cum, SumPart 10 — PlotShapes() and Visual SignalsPart 10 — Project: ATR Volatility IndicatorPart 10 — Project: Multi-Indicator Analysis PanelPart 10 — Project: Trend Regime IndicatorPart 11 — Defensive AFL: Guarding Against Bad Input and Bad DataPart 11 — User-Defined Functions and ProceduresPart 12 — Building Screening Filters That Mean SomethingPart 12 — Conditional Formatting, Sorting and Ranking ColumnsPart 12 — Exporting Results and Building a Daily WorkflowPart 18 — Appendix: IQFeedPart 20 — Challenge: The Opening Range That MovedPart 20 — Sessions: Regular Hours, Pre-Market and After-HoursPart 22 — Time & Sales: What It Does and Does Not Tell YouPart 28 — Portfolio Backtesting: Many Symbols, One AccountPart 28 — Stops with ApplyStop()Part 29 — Equity Curve AnalysisOfficial documentation
LastValuereturns NUMBERLastValue(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.
Taught in:Part 37 — Component 5: Real-Time or Replay WorkspacePart 6 — Reality Check: Does RSI Above 70 Mean Sell?Part 7 — Reality Check: Can We Test Whether a Pattern Predicted Anything?Part 8 — Boolean Arrays: Close > MA(Close, 50)Part 8 — Errors, Debugging and Sanity ChecksPart 8 — Null Values, Nz() and Warm-Up PeriodsPart 8 — The Array Model: The Most Important Lesson in This CoursePart 9 — State versus Event: The Distinction That Breaks FormulasPart 11 — Project: Your Personal AFL Utility LibraryPart 18 — Choosing a Data Source: A Decision FrameworkPart 18 — Free and End-of-Day Sources with AmiQuotePart 23 — Knowing Where You Are: Status() and Execution ContextPart 25 — Alert Mechanisms and AlertIf()Part 25 — Duplicate Alerts and How to Stop ThemPart 25 — Project: Real-Time Breakout AlertPart 26 — Bar Replay: Mechanics and Honest LimitsPart 26 — Replay Exercise: Intraday Setups and AlertsPart 28 — Stops with ApplyStop()Part 29 — Equity Curve AnalysisPart 30 — Insufficient Evidence and Regime DependencePart 35 — The Research Lifecycle End to EndPart 36 — Dynamic Variables: VarSet, VarGet and FriendsOfficial documentation
Optimizereturns NUMBERAFL 1.7Optimize( " description ", default, min , max, step )Defines optimization process parameters. With normal backtesting, scanning, exploration and comentary modes the optimize function returns default value, so the above function call returns default ; In optimization mode optimize function returns successive values from min to max (inclusively) with step stepping.
Taught in:Part 37 — Components 7 and 8: Backtest and Robustness EvaluationPart 37 — Component 9: The Research ReportPart 10 — Parameters: Param, ParamToggle, ParamList and ParamColorPart 28 — Costs: Commissions, Slippage and the SpreadPart 28 — Position Sizing with SetPositionSize()Part 28 — Reality Check: Is the Golden Cross Worth Anything?Part 30 — Challenge: 180% a Year with a 3% DrawdownPart 30 — Data Snooping, Curve Fitting and OverfittingPart 31 — Best Value versus Robust RegionPart 31 — Lab: Optimise Without Fooling YourselfPart 31 — Optimization Targets and Search EnginesPart 31 — Reading Parameter SurfacesPart 31 — What Optimize() Actually DoesPart 32 — The AmiBroker Walk-Forward WorkflowPart 32 — Interpreting Out-of-Sample DegradationPart 32 — Lab: Run a Walk-Forward AnalysisPart 32 — Walk-Forward MethodologyPart 33 — The AmiBroker Monte Carlo WorkflowOfficial documentation
OptimizerSetEnginereturns NOTHINGAFL 3.20OptimizerSetEngine( "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.
Taught in:Part 31 — Optimization Targets and Search EnginesOfficial documentation
OptimizerSetOptionreturns NOTHINGAFL 3.20OptimizerSetOption("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.
Taught in:Part 31 — Optimization Targets and Search EnginesOfficial documentation
Refreturns ARRAYRef( 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).
Taught in:Part 37 — Components 7 and 8: Backtest and Robustness EvaluationPart 37 — Component 4: Multi-Timeframe ChartPart 37 — Component 5: Real-Time or Replay WorkspacePart 37 — Component 3: ScannerPart 37 — Component 6: The Trading StrategyPart 2 — Data Defects in PracticePart 3 — Importing and Updating Market DataPart 4 — Market Structure: Trends, Ranges and TransitionsPart 4 — Swings, Highs and LowsPart 5 — Breakouts, Failed Breakouts and Role ReversalPart 5 — Lab: Map the Structure of a Real ChartPart 5 — Reality Check: Do Support Levels Actually Hold?Part 5 — Support and Resistance as ZonesPart 6 — Moving Average Slope and CrossoversPart 6 — Reality Check: Does RSI Above 70 Mean Sell?Part 6 — RSI and Rate of ChangePart 6 — Volume and Volume-Based IndicatorsPart 7 — Classic Chart PatternsPart 7 — Context, Evidence and Base RatesPart 7 — Multi-Bar Candlestick PatternsPart 7 — Reality Check: Can We Test Whether a Pattern Predicted Anything?Part 8 — The Array Model: The Most Important Lesson in This CoursePart 9 — Challenge: State or Event?Part 9 — Referencing Past Bars with Ref()Part 9 — Running Extremes: HHV, LLV and FriendsPart 9 — State versus Event: The Distinction That Breaks FormulasPart 9 — ValueWhen(): Carrying a Value ForwardPart 10 — Project: ATR Volatility IndicatorPart 10 — Project: Trend Regime IndicatorPart 12 — Challenge: The Scan That Returns NothingPart 12 — Reality Check: Do High-Volume Breakouts Lead Anywhere?Part 16 — Breadth Divergence and Market RegimePart 18 — Choosing a Data Source: A Decision FrameworkPart 18 — Free and End-of-Day Sources with AmiQuotePart 18 — Appendix: IQFeedPart 20 — Challenge: The Opening Range That MovedPart 20 — Daylight Saving and Alignment FailuresPart 20 — Sessions: Regular Hours, Pre-Market and After-HoursPart 25 — Project: Real-Time Breakout AlertPart 26 — Replay Exercise: Reading a Session LivePart 27 — From Rules to AFLPart 28 — Backtester Basics: Signals and Trade PricesPart 28 — Reality Check: Is the Golden Cross Worth Anything?Part 28 — Single-Symbol Thinking versus Portfolio RealityPart 28 — Stops with ApplyStop()Part 29 — Reading the Backtest ReportPart 30 — Challenge Collection: Six Broken BacktestsPart 30 — Insufficient Evidence and Regime DependencePart 30 — Look-Ahead BiasPart 30 — Position Sizing and Portfolio ErrorsPart 30 — Unrealistic Fills, Costs and LiquidityPart 32 — In-Sample and Out-of-SamplePart 32 — Lab: Run a Walk-Forward AnalysisPart 34 — Lab: Same Strategy, Three Position-Sizing ModelsPart 34 — Risk Per Trade and Stop DistancePart 34 — Volatility-Based Position SizingPart 35 — Defining Your Universe and Market RegimeOfficial documentation
SetBacktestModereturns NOTHINGAFL 3.0SetBacktestMode( mode )Sets working mode of the backtester. A 'mode' parameter is one of the following backtest modes: Supported backtest modes: backtestRegular - regular, signal-based backtest, redundant signals are removed
Taught in:Part 37 — Components 7 and 8: Backtest and Robustness EvaluationPart 37 — Component 6: The Trading StrategyPart 28 — Backtester Basics: Signals and Trade PricesPart 28 — Portfolio Backtesting: Many Symbols, One AccountPart 28 — Project: A Realistic Portfolio BacktestPart 28 — Reality Check: Is the Golden Cross Worth Anything?Part 30 — Challenge Collection: Six Broken BacktestsPart 33 — The AmiBroker Monte Carlo WorkflowOfficial documentation
SetCustomBacktestProcreturns NOTHINGAFL 2.70SetCustomBacktestProc( 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
Taught in:Part 29 — Trade Statistics: Wins, Losses, Payoff and ExpectancyPart 31 — Optimization Targets and Search EnginesPart 36 — Introduction to the Custom Backtester InterfaceOfficial documentation
SetOptionreturns NOTHINGAFL 2.3SetOption( 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
Taught in:Part 37 — Components 7 and 8: Backtest and Robustness EvaluationPart 37 — Component 9: The Research ReportPart 37 — Component 2: Stock ExplorationPart 37 — Component 6: The Trading StrategyPart 3 — Importing and Updating Market DataPart 3 — Lab: Install AmiBroker and Verify Your SetupPart 12 — Exploration: Filter, AddColumn and AddTextColumnPart 12 — Exporting Results and Building a Daily WorkflowPart 15 — Data Alignment Pitfalls Across SymbolsPart 23 — Knowing Where You Are: Status() and Execution ContextPart 24 — Repeat Scanning: Mechanics and CostsPart 27 — Execution Assumptions You Must StatePart 27 — Project: Your First Complete Trading SystemPart 28 — Backtester Basics: Signals and Trade PricesPart 28 — Costs: Commissions, Slippage and the SpreadPart 28 — Portfolio Backtesting: Many Symbols, One AccountPart 28 — Position Sizing with SetPositionSize()Part 28 — Project: A Realistic Portfolio BacktestPart 28 — Reality Check: Is the Golden Cross Worth Anything?Part 28 — Single-Symbol Thinking versus Portfolio RealityPart 28 — Stops with ApplyStop()Part 29 — Reading the Backtest ReportPart 29 — Return Metrics: Net Profit, CAR, RAR and ExposurePart 30 — Challenge Collection: Six Broken BacktestsPart 30 — Challenge: 180% a Year with a 3% DrawdownPart 30 — Data Snooping, Curve Fitting and OverfittingPart 30 — Look-Ahead BiasPart 30 — Position Sizing and Portfolio ErrorsPart 30 — Unrealistic Fills, Costs and LiquidityPart 31 — Best Value versus Robust RegionPart 31 — Lab: Optimise Without Fooling YourselfPart 31 — Optimization Targets and Search EnginesPart 31 — Reading Parameter SurfacesPart 31 — What Optimize() Actually DoesPart 32 — The AmiBroker Walk-Forward WorkflowPart 32 — In-Sample and Out-of-SamplePart 32 — Interpreting Out-of-Sample DegradationPart 32 — Lab: Run a Walk-Forward AnalysisPart 33 — The AmiBroker Monte Carlo WorkflowPart 33 — The Limits of SimulationPart 33 — Sequence Risk and Risk of RuinPart 33 — What Monte Carlo Can and Cannot Tell YouPart 34 — Lab: Same Strategy, Three Position-Sizing ModelsPart 34 — Portfolio Exposure, Concentration and CorrelationPart 34 — Risk Per Trade and Stop DistancePart 35 — Journalling and Separating Two Kinds of PerformancePart 36 — Introduction to the Custom Backtester InterfacePart 36 — Static Variables in DepthOfficial documentation
SetPositionSizereturns ARRAYAFL 2.70SetPositionSize( 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
Taught in:Part 37 — Components 7 and 8: Backtest and Robustness EvaluationPart 37 — Component 6: The Trading StrategyPart 27 — Execution Assumptions You Must StatePart 27 — Project: Your First Complete Trading SystemPart 28 — Costs: Commissions, Slippage and the SpreadPart 28 — Portfolio Backtesting: Many Symbols, One AccountPart 28 — Position Sizing with SetPositionSize()Part 28 — Project: A Realistic Portfolio BacktestPart 28 — Reality Check: Is the Golden Cross Worth Anything?Part 28 — Single-Symbol Thinking versus Portfolio RealityPart 29 — Reading the Backtest ReportPart 30 — Position Sizing and Portfolio ErrorsPart 31 — Best Value versus Robust RegionPart 31 — Lab: Optimise Without Fooling YourselfPart 31 — What Optimize() Actually DoesPart 32 — In-Sample and Out-of-SamplePart 32 — Lab: Run a Walk-Forward AnalysisPart 33 — The AmiBroker Monte Carlo WorkflowPart 34 — Lab: Same Strategy, Three Position-Sizing ModelsPart 34 — Portfolio Exposure, Concentration and CorrelationPart 34 — Risk Per Trade and Stop DistancePart 34 — Volatility-Based Position SizingPart 36 — Introduction to the Custom Backtester InterfaceOfficial documentation
SetTradeDelaysreturns nothingAFL 2.1SetTradeDelays( 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
Taught in:Part 37 — Components 7 and 8: Backtest and Robustness EvaluationPart 37 — Component 6: The Trading StrategyPart 27 — Execution Assumptions You Must StatePart 27 — Project: Your First Complete Trading SystemPart 27 — From Rules to AFLPart 28 — Backtester Basics: Signals and Trade PricesPart 28 — Costs: Commissions, Slippage and the SpreadPart 28 — Portfolio Backtesting: Many Symbols, One AccountPart 28 — Project: A Realistic Portfolio BacktestPart 28 — Reality Check: Is the Golden Cross Worth Anything?Part 28 — Single-Symbol Thinking versus Portfolio RealityPart 29 — Reading the Backtest ReportPart 30 — Challenge Collection: Six Broken BacktestsPart 30 — Challenge: 180% a Year with a 3% DrawdownPart 30 — Data Snooping, Curve Fitting and OverfittingPart 30 — Look-Ahead BiasPart 30 — Unrealistic Fills, Costs and LiquidityPart 31 — Best Value versus Robust RegionPart 31 — Lab: Optimise Without Fooling YourselfPart 31 — What Optimize() Actually DoesPart 32 — In-Sample and Out-of-SamplePart 32 — Lab: Run a Walk-Forward AnalysisPart 33 — The AmiBroker Monte Carlo WorkflowPart 34 — Lab: Same Strategy, Three Position-Sizing ModelsPart 34 — Risk Per Trade and Stop DistancePart 34 — Volatility-Based Position SizingPart 36 — Introduction to the Custom Backtester InterfaceOfficial documentation
ValueWhenreturns ARRAYAFL 1.1ValueWhen(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
Taught in:Part 2 — Data Defects in PracticePart 3 — Importing and Updating Market DataPart 3 — Lab: Install AmiBroker and Verify Your SetupPart 4 — Lab: Structured Chart InterpretationPart 4 — Market Structure: Trends, Ranges and TransitionsPart 4 — Swings, Highs and LowsPart 5 — Lab: Map the Structure of a Real ChartPart 9 — Challenge: State or Event?Part 9 — State versus Event: The Distinction That Breaks FormulasPart 9 — ValueWhen(): Carrying a Value ForwardPart 10 — Project: Trend Regime IndicatorPart 15 — Benchmarks and Relative PerformancePart 15 — Data Alignment Pitfalls Across SymbolsPart 15 — Project: Relative Strength Comparison ToolPart 17 — Plugins and the Database RelationshipPart 18 — Choosing a Data Source: A Decision FrameworkPart 19 — Backfill and Database MaintenancePart 19 — Challenge: The History That Is Not All TherePart 20 — Challenge: The Opening Range That MovedPart 20 — Daylight Saving and Alignment FailuresPart 20 — Exchange Time versus Your ClockPart 20 — Sessions: Regular Hours, Pre-Market and After-HoursPart 22 — Time & Sales: What It Does and Does Not Tell YouPart 24 — Defining Intraday Setup ConditionsPart 24 — Project: Intraday Breakout ScannerPart 28 — Stops with ApplyStop()Part 30 — Survivorship and Selection BiasOfficial documentation
Sources for this lesson
2 verified · checked 2026-08-31
- 01AmiBroker AFL Function Referenceamibroker.com/guide/a_funref.html2026-08-31
- 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.