AmiBroker 5.80 User`s Guide - Srini & Francis Share Trading Report

AmiBroker 5.80 User`s Guide - Srini & Francis Share Trading Report
AmiBroker 5.80
User’s Guide
Copyright (C)1995-2014 AmiBroker.com.
All rights reserved.
AmiBroker 5.80 User’s Guide
Table of Contents
Copyright .......................................................................1
Contents ..................................................................2
Introduction ....................................................................3
About AmiBroker Editions ..................................................4
Quick Tour ................................................................6
Getting started ..........................................................11
Hardware requirements .................................................11
Supported operating
systems ...........................................11
Installation
and running ..............................................11
Getting help ..........................................................12
AmiBroker 32-bit
vs 64-bit
Compatibility
Chart ........................14
What’s new in the latest
version? ........................................16
Detailed
Change Log..................................................25
Tutorial .......................................................................38
Basic operations .........................................................40
Adding a new symbol ...................................................40
Removing a symbol .....................................................40
Splitting
a stock .....................................................40
Deleting quotation ....................................................40
Adding/removing
symbol from favourites ................................41
Merging quotations
of two symbols .....................................41
Beginners’
charting
guide ................................................42
How to use drag-and-drop
charting
interface ..............................48
Chart themes .............................................................57
User interface
customization
.............................................64
Working with chart sheets and window layouts .............................73
Using layers .............................................................79
Using Web Research window................................................81
Using account manager....................................................86
Using fundamental
data ...................................................91
Using New Analysis
window................................................96
Introduction ..........................................................96
User interface ........................................................96
Metastock importer
window............................................102
How to get quotes from various
markets ..................................106
How to set up AmiBroker with eSignal feed (RT version
only) .............108
How to set up AmiBroker with myTrack feed (RT version
only) .............110
How to use AmiBroker with external
data source (Quote Tracker) ..........114
How to set up AmiBroker with IQFeed feed (RT version
only) ..............116
How to use AmiBroker with Interactive
Brokers TWS
.......................122
How to use AmiBroker with external
DDE data source ......................129
How to work with Real-Time data plugins .................................136
How to use AmiBroker with external
data source (Quotes Plus,
TC2000/TCNet/TC2005,
FastTrack,
Metastock) .............................140
How to update US quotes automatically
using AmiQuote ....................143
How to download quotes manually using AmiQuote ..........................147
Understanding
AmiBroker database concepts ...............................149
i
AmiBroker 5.80 User’s Guide
Table of Contents
Tutorial
Background ...........................................................149
AmiBroker database structure .........................................149
What about the external
data? ........................................150
Understanding
categories ................................................152
Working with sectors
and industries
..................................154
Working with watch lists ................................................164
Understanding
how AFL works .............................................172
Creating your own indicators
............................................177
Using graph styles,
colors,
titles
and parameters
in Indicators .........181
How to create your own exploration
......................................194
How to write your own chart commentary ..................................200
Using studies
in AFL formulas ...........................................204
Back-testing
your trading
ideas .........................................206
Portfolio-level
backtesting .............................................219
Reading backtest
report .................................................232
How to optimize
trading
system ..........................................235
Walk-forward
testing ....................................................246
Back-testing
systems for futures
contracts ..............................251
Pyramiding (scaling
in/out)
and mutliple
currencies
in the portfolio
backtester .............................................................255
Using formula-based
alerts ..............................................260
Using interpretation
window.............................................264
Multiple
Time Frame support in AFL......................................265
Efficient
use of multithreading
.........................................271
Ranking functionality
...................................................279
Using AFL Code snippets .................................................284
Video Tutorials
(on-line)
...............................................286
AmiBroker Reference Guide.....................................................287
Windows.................................................................288
Chart window pane....................................................290
Parameters window....................................................292
Data window..........................................................295
Study drawing tools ..................................................296
Line study properties
window.........................................305
Text box properties
window...........................................307
Formula Editor .......................................................309
Risk-Yield
Map window................................................317
Place Order dialog ...................................................318
Database Settings ....................................................320
Intraday Settings
window.............................................321
Preferences window...................................................325
Customize tools window...............................................338
Symbol tree window...................................................340
Information
window...................................................342
Notepad window.......................................................345
Quote Editor
window..................................................346
Symbol Finder window (F3) ............................................347
ii
AmiBroker 5.80 User’s Guide
Table of Contents
AmiBroker Reference Guide
Assignment organizer
window..........................................348
Composite recalculation
window.......................................353
Categories window....................................................354
ASCII Import Wizard ..................................................356
Metastock importer
window............................................357
Real-time quote window...............................................361
Easy alerts
window...................................................363
Bar Replay window....................................................368
Formula Editor .......................................................370
Quick review window..................................................374
Automatic analysis
window............................................376
Filter
settings
window...............................................384
System test settings
window..........................................385
System test report
window............................................388
Commission window....................................................389
Commentary window....................................................397
Plugins window.......................................................402
Indicator
Maintenance Wizard .........................................403
Log window...........................................................404
Using Web Research window...............................................405
Using account manager...................................................407
Menus
...................................................................409
File menu............................................................410
Edit menu............................................................413
View menu............................................................415
Insert menu..........................................................418
Format menu..........................................................422
Symbol menu..........................................................423
Analysis menu........................................................426
Tools menu...........................................................427
Window menu..........................................................429
Help menu............................................................432
AFL Editor
menu......................................................433
Automatic Analysis
result
list
context
menu..........................437
Chart context
menu...................................................439
Layouts context
menu.................................................441
Formula (chart)
context
menu.........................................442
Layers context
menu..................................................444
Keyboard shortcuts ......................................................446
Import ASCII ............................................................448
How does it work? ....................................................448
Format definition
commands...........................................448
Comments
.............................................................466
Usage examples .......................................................466
Default behaviour ....................................................469
User-definable
file
types and formats ................................469
Ticker aliases .......................................................469
GICS categorisation
..................................................470
iii
AmiBroker 5.80 User’s Guide
Table of Contents
AmiBroker Reference Guide
ICB categorisation
...................................................470
AmiBroker’s OLE Automation
Object Model.................................472
Index of objects .....................................................472
ADQuotation ..........................................................473
ADQuotations .........................................................473
Analysis .............................................................473
AnalysisDoc ..........................................................475
AnalysisDocs .........................................................477
Application ..........................................................478
Window...............................................................479
Windows..............................................................479
Commentary...........................................................479
Document.............................................................480
Documents............................................................480
Market...............................................................480
Markets ..............................................................481
Quotation ............................................................481
Quotations ...........................................................481
Stock................................................................481
Stocks...............................................................483
Practical
Examples: ..................................................483
AmiQuote’s OLE Automation
Object Model..................................485
Index of objects ........................................................485
Document.............................................................485
Technical analysis guide ......................................................487
Introduction ............................................................487
Basic tools .............................................................488
Price charts .........................................................489
Trend lines ..........................................................491
Moving averages ......................................................493
Regression channels ..................................................495
Fibonacci Retracement ................................................496
Fibonacci Time Zones.................................................497
Bollinger
bands......................................................498
Indicators ..............................................................499
Accumulation/Distribution
............................................500
Advance-Decline
line (AD-Line) .......................................501
ADX/ Directional
Movement Index .....................................502
CCI - Commodity Channel Index ........................................503
Chaikin Oscillator
...................................................504
MACD- Moving Average Convergence/Divergence
.........................505
Money Flow Index .....................................................506
Negative Volume Index ................................................507
OBV- On Balance Volume..............................................508
Parabolic
SAR (Stop-And-Reverse)
.....................................509
RS - Relative
Strength
(comparative)
.................................510
RSI - Relative
Strength
Index ........................................511
iv
AmiBroker 5.80 User’s Guide
Table of Contents
Technical
analysis guide
ROC- Price Rate Of Change...........................................513
Stochastic
Slow......................................................514
TRIN - Arms Index ....................................................515
TRIX - TRIple eXponential ............................................516
Ultimate Oscillator
..................................................517
VAP - Volume At Price histogram ......................................518
Relative Performance chart ...........................................519
AmiBroker Formula Language (AFL) ..............................................520
AFL Reference Manual ....................................................521
Introduction ............................................................521
Basics ..................................................................521
Lexical elements .....................................................521
Language structure ...................................................522
Keywords.............................................................538
AFL Function
Reference - Alphabetical
list
of functions .................562
AFL Function
Reference - Categorized
list
of functions ..................572
#include - preprocessor
include
command..............................582
#include_once
- preprocessor
include
(once) command..................584
#pragma - sets AFL pre-processor
option ..............................585
abs - absolute
value .................................................586
AccDist - accumulation/distribution
..................................589
acos - arccosine
function ............................................590
AddColumn - add numeric exploration
column ...........................591
AddRankColumn - add ranking
column(s)
according
to current
sort
set by SetSortColumns ............................................594
AddSummaryRows - add summary row(s) to the exploration
output ........595
AddTextColumn - add text exploration
column ..........................597
AddToComposite - add value to composite ticker .......................599
ADLine - advance/decline
line ........................................601
AdvIssues - advancing issues .........................................602
AdvVolume - advancing issues volume ..................................603
ADX- average directional
movement index .............................604
AlertIf
- trigger
alerts .............................................605
AlmostEqual - rounding
error insensitive
comparison ..................607
AMA- adaptive
moving average ........................................608
AMA2- adaptive
moving average .......................................610
ApplyStop - apply built-in
stop ......................................611
Asc - get ASCII code of character ....................................615
asin - arcsine
function ..............................................616
atan - arc tan .......................................................617
atan2 - calculates
arctangent
of y/x .................................618
ATR - average true range .............................................619
BarIndex - get zero-based
bar number.................................621
BarsSince - bars since ...............................................624
BBandBot - bottom bollinger
band.....................................626
BBandTop - top bollinger
band........................................627
BeginValue - Value of the array at the begin of the range ............628
v
AmiBroker 5.80 User’s Guide
Table of Contents
AmiBroker Formula Language (AFL)
CategoryAddSymbol - adds a symbol to a category ......................629
CategoryCreate
- add new category
(such as watch list) ...............631
CategoryFind - search for category
by name...........................632
CategoryGetName - get the name of a category .........................633
CategoryGetSymbols
- retrieves
comma-separated
list
of symbols
belonging
to given category ......................................635
CategoryRemoveSymbol - remove a symbol from a category ...............637
CategorySetName - set the name of category
(group,
market, watch
list,
industry) ..................................................639
CCI - commodity channel index ........................................641
ceil - ceil
value ....................................................643
Chaikin - chaikin
oscillator
.........................................644
ClipboardGet
- retrieves
current
contents
of Windows clipboard .......645
ClipboardSet
- copies the text to the Windows clipboard ..............646
ColorBlend - blends (mixes)
two colors ...............................647
ColorHSB - specify
color using Hue-Saturation-Brightness
.............648
ColorRGB - specify
color using Red-Green-Blue
components .............650
Correlation
- correlation
............................................652
cos - cosine .........................................................654
cosh - hyperbolic
cosine function ....................................655
CreateObject
- create COM object .....................................656
CreateStaticObject
- create static
COM object ........................657
Cross - crossover
check ..............................................658
Cum- cumulative
sum.................................................661
Date - date ..........................................................664
DateNum - date number................................................666
DateTime - retrieves
encoded date time ...............................667
DateTimeAdd - adds specified
number of seconds/minutes/hours/days
to datetime ......................................................669
DateTimeConvert - date/time
format conversion ........................671
DateTimeDiff
- get difference
in seconds between two datetime
values ...........................................................673
DateTimeToStr - convert
datetime
to string ...........................674
Day - day of month...................................................675
DayOfWeek - day of week..............................................676
DayOfYear - get ordinal
number of day in a year ......................677
DaysSince1900 - get number of days since January 1st, 1900...........678
DecIssues - declining
issues .........................................680
DecVolume - declining
issues volume ..................................681
DEMA- double exponential
moving average .............................682
EMA- exponential
moving average .....................................684
EnableRotationalTrading
- Turns on rotational-trading
mode of the
backtester .......................................................688
EnableScript
- enable scripting
engine ...............................691
EnableTextOutput
- enables/disables
text output in the Chart
Commentary window................................................692
EncodeColor - encodes color for indicator
title ......................693
EndValue - value of the array at the end of the selected
range .......695
vi
AmiBroker 5.80 User’s Guide
Table of Contents
AmiBroker Formula Language (AFL)
Equity - calculate
single-symbol
equity
line .........................696
Error - displays
user-defined
error message and stops the
execution ........................................................700
EXP - exponential
function ...........................................701
ExRem- remove excessive
signals .....................................702
ExRemSpan - remove excessive
signals
spanning given number of bars ...704
fclose - close a file ................................................705
fdelete - deletes
a file .............................................706
fdir - list
directory
content ........................................707
feof - test for end-of-file
..........................................709
FFT - performs Fast Fourier
Transform ................................711
fgets - get a string
from a file .....................................714
fgetstatus
- retrieves
file
status/properties
........................716
FIR - Finite
Impulse Response filter
.................................718
FirstVisibleValue
- get first
visible
value of array .................720
Flip -...............................................................721
floor - floor
value ..................................................722
fmkdir - creates
(makes) a directory .................................723
fopen - open a file ..................................................724
Foreign - access foreign
security
data ...............................726
fputs - write a string
to a file .....................................729
frac - fractional
part ...............................................731
frmdir - removes a directory .........................................732
FullName - full
name of the symbol ...................................733
GapDown - gap down...................................................735
GapUp - gap up.......................................................736
GetAsyncKeyState - query the current
state of keyboard keys ..........737
GetBacktesterObject
- get the access to backtester
object ............741
GetBaseIndex - retrieves
symbol of relative
strength
base index ......742
GetCategorySymbols
- retrieves
comma-separated
list
of symbols
belonging
to given category ......................................743
GetChartBkColor
- get the RGB color value of chart background ........744
GetChartID - get current
chart ID....................................745
GetCursorMouseButtons
- get current
state of mouse buttons ...........746
GetCursorXPosition
- get current
X position
of mouse pointer .........750
GetCursorYPosition
- get current
Y position
of mouse pointer .........752
GetDatabaseName - retrieves
folder
name of current
database ..........754
GetExtraData - get extra data from external
data source ..............755
GetFnData - get fundamental
data .....................................757
GetOption - gets the value of option in automatic
analysis
settings .........................................................759
GetPerformanceCounter
- retrieves
the current
value of the
high-resolution
performance
counter ..............................761
GetPlaybackDateTime
- get bar replay position
date/time ..............763
GetPriceStyle
- get current
price chart style ........................764
GetRTData - retrieves
the real-time
data fields ......................766
GetRTDataForeign - retrieves
the real-time
data fields
(for
specified
symbol) ................................................768
vii
AmiBroker 5.80 User’s Guide
Table of Contents
AmiBroker Formula Language (AFL)
GetScriptObject
- get access to script
COM object ....................770
GetTradingInterface
- retrieves
OLE automation
object
to automatic
trading
interfac .................................................771
GfxArc - draw an arc .................................................772
GfxChord - draw a chord ..............................................773
GfxCircle
- draw a circle ............................................774
GfxDrawText - draw a text (clipped
to rectangle) .....................775
GfxEllipse
- draw an ellipse .........................................778
GfxGetTextWidth
- get pixel
width of text ............................779
GfxGradientRect
- draw a rectangle
with gradient
fill ................780
GfxLineTo - draw a line to specified
point ...........................781
GfxMoveTo - move graphic
cursor to new position ......................782
GfxPie - draw a pie ..................................................783
GfxPolygon - draw a polygon ..........................................785
GfxPolyline
- draw a polyline ........................................786
GfxRectangle - draw a rectangle ......................................787
GfxRoundRect - draw a rectangle
with rounded corners .................788
GfxSelectFont
- create / select
graphic
font .........................789
GfxSelectPen - create / select
graphic
pen...........................791
GfxSelectSolidBrush
- create / select
graphic
brush ..................793
GfxSetBkColor - set graphic
background color .........................794
GfxSetBkMode - set graphic
background mode...........................795
GfxSetCoordsMode - set low-level
graphics
co-ordinate
mode...........796
GfxSetOverlayMode - set low-level
graphic
overlay
mode...............798
GfxSetPixel
- set pixel
at specified
position
to specified
color .....799
GfxSetTextAlign
- set text alignment .................................800
GfxSetTextColor
- set graphic
text color .............................802
GfxSetZOrder - set current
low-level
graphic
Z-order
layer ...........803
GfxTextOut - writes
text at the specified
location ...................804
GicsID - get GICS category
information ...............................806
GroupID - get group ID/name ..........................................807
HHV- highest
high value .............................................808
HHVBars - bars since highest
high ....................................812
Highest - highest
value ..............................................813
HighestBars - bars since highest
value ...............................814
HighestSince
- highest
value since condition
met.....................815
HighestSinceBars
- bars since highest
value since condition
met......816
HighestVisibleValue
- get the highest
value within
visible
chart
area .............................................................817
HMA- Hull Moving Average ............................................818
Hold - hold the alert
signal .........................................819
Hour - get current
bar’s hour ........................................820
IcbID - get ICB category
information .................................821
IIf - immediate IF function ..........................................822
IndustryID
- get industry
ID / name..................................831
InGICS - test GICS membership ........................................832
InICB - test ICB membership ..........................................833
Inside - inside
day..................................................834
viii
AmiBroker 5.80 User’s Guide
Table of Contents
AmiBroker Formula Language (AFL)
Int - integer
part ...................................................835
Interval
- get bar interval
(in seconds) .............................837
InWatchList
- watch list
membership test (by ordinal
number) .........839
InWatchListName - watch list
membership test (by name)...............840
IsContinuous
- checks ’continuous
quotations’
flag state .............841
IsEmpty - empty value check ..........................................842
IsFavorite
- check if current
symbol belongs to favorites ............843
IsFinite
- check if value is not infinite
............................844
IsIndex - check if current
symbol is an index ........................845
IsNan - checks for NaN (not a number) ................................846
IsNull - check for Null (empty) value ................................847
IsTrue - true value (non-empty
and non-zero)
check ...................848
LastValue - last value of the array ..................................849
LastVisibleValue
- get last visible
value of array ...................853
LineArray - generate trend-line
array ................................854
LinearReg - linear
regression
end-point ..............................856
LinRegIntercept
-....................................................857
LinRegSlope - linear
regression
slope ................................858
LLV - lowest low value ...............................................860
LLVBars - bars since lowest low ......................................864
log - natural
logarithm ..............................................865
log10 - decimal logarithm ............................................867
Lookup - search the array for bar with specified
date/time ...........868
Lowest - lowest value ................................................870
LowestBars - bars since lowest .......................................871
LowestSince - lowest value since condition
met.......................872
LowestSinceBars
- barssince
lowest value since condition
met.........873
LowestVisibleValue
- get the lowest value within
visible
chart
area .............................................................874
MA- simple moving average ...........................................875
MACD- moving average convergence/divergence
.........................882
MarketID - market ID / name..........................................884
Max - maximum value of two numbers / arrays ..........................885
MDI - minus directional
movement indicator
(-DI) .....................888
Median - calculate
median (middle
element) ...........................889
MFI - money flow index ...............................................890
MicroSec - get bar’s microsecond
part of the timestamp ...............891
MilliSec
- get bar’s millisecond
part of the timestamp ...............892
Min - minimum value of two numbers / arrays ..........................893
Minute - get current
bar’s minute ....................................896
Month - month........................................................897
mtRandom - Mersene Twister
random number generator ...................898
mtRandomA - Mersene Twister
random number generator
(array
version) .........................................................899
Name- ticker
symbol .................................................900
NoteGet - retrieves
the text of the note .............................904
NoteSet - sets text of the note ......................................905
Now - gets current
system date/time ..................................906
ix
AmiBroker 5.80 User’s Guide
Table of Contents
AmiBroker Formula Language (AFL)
NumToStr - convert
number to string ..................................908
NVI - negative
volume index ..........................................911
Nz - Null (Null/Nan/Infinity)
to zero ................................912
OBV- on balance volume ..............................................914
Optimize - define optimization
variable ..............................915
OptimizerSetEngine
- select
external
optimization
engine .............918
OptimizerSetOption
- set the value of external
optimizer
engine
parameter ........................................................919
OscP - price oscillator
..............................................920
OscV - volume oscillator
.............................................921
Outside - outside
bar ................................................922
Param - add user user-definable
numeric parameter ....................923
ParamColor - add user user-definable
color parameter .................930
ParamDate - add user user-definable
date parameter ...................934
ParamField - creates
price field
parameter ...........................935
ParamList - creates
the parameter that consist
of the list
of
choices ..........................................................937
ParamStr - add user user-definable
string
parameter ..................939
ParamStyle - select
styles
applied
to the plot .......................940
ParamTime - add user user-definable
time parameter ...................943
ParamToggle - create Yes/No parameter ................................944
ParamTrigger - creates
a trigger
(button)
in the parameter dialog ....947
PDI - plus directional
movement indicator ............................948
Peak - peak..........................................................949
PeakBars - bars since peak...........................................950
Percentile
- calculate
percentile ....................................951
PercentRank - calculate
percent rank .................................952
PlaySound - play back specified
.WAV file ............................953
Plot - plot indicator
graph ..........................................954
PlotForeign
- plot foreign
security
data .............................964
PlotGrid - Plot horizontal
grid line .................................966
PlotOHLC - plot custom OHLC chart ....................................967
PlotShapes - plots arrows and other shapes ...........................970
PlotText - write text on the chart ...................................975
PlotTextSetFont
- write text on the chart with user-defined
font .....977
PlotVAPOverlay
- plot Volume-At-Price
overlay
chart ..................978
PlotVAPOverlayA - plot multiple-segment
Volume-At-Price
chart ........979
PopupWindow - display
pop-up window..................................981
Prec - adjust
number of decimal points
of floating
point number......982
Prefs - retrieve
preferences
settings ................................983
printf
- Print
formatted
output to the output window. ................985
PVI - positive
volume index ..........................................987
Random - random number...............................................988
Ref - reference
past/future
values of the array ......................990
RelStrength
- comparative
relative
strength ..........................999
RequestTimedRefresh
- forces periodical
refresh
of indicator
pane...1001
RestorePriceArrays
- restore
price arrays to original
symbol ........1003
RMI - Relative
Momentum Index .......................................1005
x
AmiBroker 5.80 User’s Guide
Table of Contents
AmiBroker Formula Language (AFL)
ROC- percentage
rate of change .....................................1006
Round - round number to nearest integer .............................1009
RSI - relative
strength
index .......................................1011
RWI - random walk index .............................................1013
RWIHi - random walk index of highs ..................................1014
RWILo - random walk index of lows ...................................1015
SAR- parabolic
stop-and-reverse
....................................1016
Say - speaks provided
text ..........................................1017
Second - get current
bar’s second ...................................1019
SectorID - get sector ID / name.....................................1020
SelectedValue
- retrieves
value of the array at currently
selected
date/time
point ........................................1021
SetBacktestMode - Sets working mode of the backtester ...............1024
SetBarFillColor
- set bar/candlestick/cloud
chart fill
color ........1026
SetBarsRequired
- set number of previous
and future
bars needed
for script/DLL
to properly
execute ..............................1028
SetChartBkColor
- set background color of a chart ...................1030
SetChartBkGradientFill
- enables background gradient
color fill
in indicators
...................................................1032
SetChartOptions
- set/clear/overwrite
defaults
for chart pane
options .........................................................1034
SetCustomBacktestProc
- define custom backtest
procedure formula
file ............................................................1037
SetForeign - replace
current
price arrays with those of foreign
security ........................................................1038
SetFormulaName - set the name of the formula ........................1040
SetGradientFill
- set the colors
of a gradient
fill
plot ............1041
SetOption - sets options
in automatic
analysis
settings .............1043
SetPositionSize
- set trade size ....................................1049
SetSortColumns - sets the columns which will
be used for sorting
in AA window....................................................1052
SetTradeDelays
- allows to control
trade delays applied
by the
backtester ......................................................1053
ShellExecute
- execute a file .......................................1055
sign - returns
the sign of the number/array .........................1056
Signal - macd signal
line ...........................................1057
sin - sine function .................................................1059
sinh - hyperbolic
sine function .....................................1060
sqrt - square root ..................................................1061
StaticVarCompareExchange
- atomic interlocked
static
variable
compare-exchange
operation ......................................1063
StaticVarCount
- get the total
number of static
variables
in
memory..........................................................1066
StaticVarGenerateRanks
- generate ranking
of multiple
symbols and
store it to static
variables ....................................1067
StaticVarGet
- gets the value of static
variable ....................1071
StaticVarGetRankedSymbols
- retrieve
a list
of ranked symbols
from static
variables ...........................................1074
xi
AmiBroker 5.80 User’s Guide
Table of Contents
AmiBroker Formula Language (AFL)
StaticVarGetText
- gets the value of static
variable
as string ......1076
StaticVarInfo
- get the information
about static
variable(s)
........1078
StaticVarRemove - remove static
variable ............................1079
StaticVarSet
- sets the value of static
variable ....................1081
StaticVarSetText
- Sets the value of static
string
variable. ........1084
Status - get run-time
AFL status
information ........................1086
StdErr - standard
error .............................................1092
StDev - standard
deviation ..........................................1093
StochD - stochastic
slow %D
.........................................1095
StochK - stochastic
slow %K
.........................................1096
StrCount - count the occurrences
of substring
within
a string .......1097
StrExtract
- extracts
given item (substring)
from comma-separated
string ..........................................................1098
StrFind - find substring
in a string ................................1100
StrFormat - Write formatted
output to the string ....................1101
StrLeft
- extracts
the leftmost
part ................................1104
StrLen - string
length ..............................................1106
StrMid - extracts
part of the string ................................1107
StrReplace - string
replace .........................................1108
StrRight - extracts
the rightmost
part of the string ................1109
StrToDateTime - convert
string
to datetime ..........................1110
StrToLower - convert
to lowercase ...................................1111
StrToNum - convert
string
to number.................................1112
StrToUpper - convert
to uppercase ...................................1113
Study - reference
hand-drawn study ..................................1114
Sum- sum data over specified
number of bars ........................1115
tan - tangent function ..............................................1118
tanh - hyperbolic
tangent function ..................................1119
TEMA- triple
exponential
moving average ............................1120
ThreadSleep - suspend thread for specified
number of milliseconds
...1121
TimeFrameCompress - compress single
array to given time frame .......1122
TimeFrameExpand - expand time frame compressed array ................1124
TimeFrameGetPrice - retrieve
O, H, L, C, V values from other time
frame ...........................................................1126
TimeFrameMode - switch time frame compression
mode..................1128
TimeFrameRestore - restores
price arrays to original
time frame .....1130
TimeFrameSet - switch price arrays to a different
time frame ........1132
TimeNum - get current
bar time ......................................1135
Trin - traders
(Arms) index .........................................1136
TRIX - triple
exponential
smoothed price ............................1137
Trough - trough .....................................................1138
TroughBars - bars since trough ......................................1139
TSF - time series
forecast ..........................................1140
Ultimate - ultimate
oscillator
......................................1141
UncIssues - unchanged issues ........................................1142
UncVolume - unchaged issues volume ..................................1143
ValueWhen - get value of the array when condition
met...............1144
VarGet - gets the value of dynamic variable .........................1147
xii
AmiBroker 5.80 User’s Guide
Table of Contents
AmiBroker Formula Language (AFL)
VarGetText - gets the text value of dynamic variable ................1149
VarSet - sets the value of dynamic variable .........................1150
VarSetText - sets dynamic variable
of string
type ...................1152
Version - get version
info ..........................................1153
Wilders - Wilder’s
smoothing ........................................1154
WMA- weighted moving average .......................................1155
WriteIf
- commentary conditional
text output ........................1156
WriteVal - converts
number to string ................................1159
XYChartAddPoint - add point to exploration
scatter
(XY) chart .......1163
XYChartSetAxis
- set the names of X and Y axes in exploration
scatter
charts ..................................................1166
Year - year .........................................................1167
ZIG - zig-zag
indicator .............................................1168
_DEFAULT_NAME- retrive
default
name of the plot ....................1169
_DT - convert
string
to datetime ....................................1171
_N - no text output .................................................1172
_PARAM_VALUES
- retrieve
param values string ........................1180
_SECTION_BEGIN- section
begin marker ...............................1181
_SECTION_END- section
end marker ...................................1185
_SECTION_NAME- retrieve
current
section
name.......................1189
_TRACE- print
text to system debug viewer ..........................1190
AFL Error List .........................................................1192
Calculating
multiple-security
statistics
with AddToComposite
function ..............................................................1263
Equity function,
Individual
and Portfolio
Equity Charts ................1267
Functions accepting
variable
periods ................................1272
User-definable
functions,
procedures.
Local/global
scope ............1273
AFL Tools ..............................................................1277
Automatic technical
analysis ........................................1277
Automatic analysis
window...........................................1278
Formula Editor ......................................................1278
Guru Advisor Commentary window......................................1278
AFL Scripting
Host .....................................................1280
Basics ..............................................................1280
Requirements ........................................................1280
Enabling AFL Scripting
Host .........................................1280
Further information .................................................1285
Component Object Model support in AFL..................................1286
Introduction ........................................................1286
Calling functions
defined
in script .................................1286
Using external
COM/ActiveX objects
in AFL...........................1288
Plug-in in AFL.........................................................1291
CommonCoding mistakes in AFL..........................................1292
Porfolio
Backtester
Interface
Reference Guide ..........................1297
How to add user-defined
metrics
to backtest/optimization
report ........1312
Using low-level
graphics
functions .....................................1321
Usage examples: .....................................................1323
xiii
AmiBroker 5.80 User’s Guide
Table of Contents
Technical information ........................................................1328
Troubleshooting
guide ..................................................1329
Files and directories
used by AmiBroker ................................1333
Crash recovery
system and automatic
bug reporting ......................1335
Performance tuning tips ................................................1338
Performance monitoring ..............................................1341
Multithreading
performance ..........................................1342
Howto purchase AmiBroker ?..................................................1343
Credits ......................................................................1345
xiv
Copyright
AmiBroker 5.80 User’s Guide.
Copyright ' 1995-2014 Tomasz Janeczko/AmiBroker.com. All rights reserved.
AmiBroker, AmiQuote, AmiFeed, AmiBroker.com and AmiBroker logo are trademarks of
Tomasz Janeczko/AmiBroker.com.
Microsoft, ActiveX, JScript, VBScript, Internet Explorer, MSDN, Windows, Windows
NT, Win32, and Win32s are either registered trademarks or trademarks of Microsoft
Corporation in the U.S.A. and/or other countries.
Amiga is a registered trademarks or trademarks of Amiga Technologies, GmbH.
Windows, Windows NT are either registered trademarks or trademarks of Microsoft
Corporation. Metastock is a trademark of Equis International, Inc. Other brand
and product names are registered trademarks or trademarks of their respective
owners.
Copyright
1
AmiBroker 5.80 User’s Guide
Copyright
AmiBroker 5.80 User’s Guide
Contents
•
•
•
•
•
•
•
•
•
•
•
Introduction
Quick tour
Getting started
What’s new in AmiBroker?
Tutorial
Reference guide
Technical analysis guide
AmiBroker Formula Language (AFL)
Technical information
How to purchase AmiBroker?
Credits
Copyright ' 1995-2014 Tomasz Janeczko/AmiBroker.com. All rights reserved.
AmiBroker, AmiQuote, AmiFeed, AmiBroker Formula Language, AFL, AmiBroker.com and
AmiBroker logo are trademarks of Tomasz Janeczko/AmiBroker.com.
AmiBroker uses Microsoft Active Scripting technologies. Microsoft, ActiveX,
JScript, VBScript, Internet Explorer, MSDN, Windows, Windows NT, Win32, and
Win32s are either registered trademarks or trademarks of Microsoft Corporation in
the U.S.A. and/or other countries. Windows, Windows NT are either registered
trademarks or trademarks of Microsoft Corporation. Metastock is a trademark of
Equis International, Inc. Other brand and product names are registered trademarks
or trademarks of their respective owners.
Contents
2
Introduction
Thank you for choosing AmiBroker. This guide will help you get up and running.
AmiBroker is a comprehensive technical analysis program, with an advanced
charting, back-testing and scanning capabilities. It gives everything you need to
trade successfully. Just check out our quick features tour to find out what is
included in this powerful software package.
If you are a first time user and just installed the software please check out
Tutorial section that will guide you through most important aspects of using
AmiBroker.
The next chapter - Reference guide - provides detailed description of every
window and more technical documentation covering ASCII importer and automation
interface.
In the Technical analysis guide you will find material that will introduce you to
the world of charting and technical indicators.
The next part of the guide describes AmiBroker Formula Language - a powerful tool
that allows you to create your own trading systems, scans, custom indicators and
commentaries. You will find the description of the language and its syntax, a
complete reference of all functions and more.
The last part is provided for the user’s of previous versions - this chapter will
help them finding out what new features were added without the need to re-read
all documention.
Introduction
3
AmiBroker 5.80 User’s Guide
Introduction
About AmiBroker Editions
AmiBroker software is currently available in 2 editions: Standard and
Professional.
The following table summarizes differences between these two editions:
Feature
Professional
Edition
Standard Edition
End-of-day charting/backtesting/scanning
Yes
Yes
1-, 5-, 15- minute, hourly Intraday
charting/backtesting/scanning
Yes
Yes
Custom minute bars
Yes
Yes
Tick charts/backtesting/scanning
No
Yes*
1-second, 5-second, 15-second bar
charts/backtesting/scanning
No
Yes
Streaming real time quote display
10 symbols
UNLIMITED symbols
Time and Sales window
1 symbol
UNLIMITED symbols
GetRTData / GetRTDataForeign AFL function
No
Yes
Wait for backfill in Automatic Analysis
No
Yes
Automatically updating real time charts
Yes
Yes
Maximum Adverse/Favourable Excursion
Distribution charts
in Portfolio backtest reports
No
64-bit version
No
Yes
Multi-threading Charts
Yes
Yes
Multi-threading Analysis window
Yes, upto 2
threads
Yes, upto 32
threads **
No
Not required, but
nice to have
Yes
Requires RT data subscription
(Professional
Edition works with
EOD data perfectly
fine, but
real-time features
(like real-time
quote) of course
are require
real-time data
source)
* - this feature is available only using eSignal RT, Interactive Brokers, DDE
feed
In the future the Professional Edition may have additional extra features not
available in Standard Edition. For pricing and ordering information check out How
About AmiBroker Editions
4
AmiBroker 5.80 User’s Guide
Introduction
to order section.
** - the number of threads depends on number of logical processors on your
computer and number of symbols under test. For details see: Efficient use of
Multithreading.
About AmiBroker Editions
5
AmiBroker 5.80 User’s Guide
Introduction
Quick Tour
Basic features
Powerful charting
• object-oriented drawing tools (trend lines, rays, parallel lines,
regression channels, fibonacci retracement, expansion, Fibonacci time
extensions, Fibonacci timezone, arc, gann square, gann square, cycles,
circles, rectangles, text on the chart, and more)
• drag-and-drop indicator creation - allows you to create complex indicators
without writing single line of code
• modern, fully customizable user interface
• instant viewing of intraday/daily/weekly/montly charts in line, bar or
candlestick styles overlaid with configurable moving averages, Bollinger
bands, Volume chart, SAR, etc.
• ability to display most common 1-, 5-, 15-, 60- minute intraday charts as
well as fully customizable N-minute charts (where N is 1..1380 )
• 5-second and 15-second bar charts (RT version)
• tick charts, custom N-tick charts (RT version)
• multiple time frame charts
• on-the-fly time compression - no need to wait when switching between
various chart periodicities
• relative performance charts
• tens of most popular indicators built-in including ROC, RSI, MACD, OBV,
CCI, MFI, NVI, Stochastics, Ultimate oscillator, DMI, ADX, Parabolic SAR,
TRIN, Advance/Decline line, Accumulation/Distribution, TRIX, Chaikin
oscillator, unique risk-to-yield map and more
• study drawing tools including trend lines, horizontal/vertical lines,
Fibonacci retracements and timezones, text boxes
• multiple chart panes, windows, different views and time scales are possible
all at the same time
• extermely fast zooming and live scrolling
Multiple data feeds
AmiBroker is capable of handling virtually ANY exchange in the world.
• Real-time streaming quotes via eSignal’s TurboFeed featuring access to all
US exchanges and major European exchanges.
• Real-time streaming quotes via myTRACK feed, IQFeed, QCharts/Quote.com,
QuoteTracker, Interactive Brokers, any DDE-enabled data feed
• Direct feed from Quotes Plus, TC2000, FastTrack and Metastock (including
intraday) databases. Read more...
• User-configurable ASCII import wizard - allows you to read quotes in the
format you can define (including intraday)!
• Built-in Metastock(R) database importer - reads directly all symbols from
your Metastock database (works with both EOD and intraday modes) in a
matter of seconds!
• AmiQuote downloader program provides quick way of obtaining free end-of-day
from major world exchanges (all US markets, LSE, ASX, Paris, Milan,
Frankfurt)
Quick Tour
6
AmiBroker 5.80 User’s Guide
Introduction
• Free FOREX data downloadable via AmiQuote
• Free historical intraday delayed quotes from US exchanges downloadable via
AmiQuote
• Script-driven, one-click automatic downloaders available for NYSE, Amex,
Nasdaq, Australian Stock Exchange, Johannesburg Stock Exchange, Warsaw
Stock Exchange
AmiBroker is successfully used in the following countries: USA, Canada, United
Kingdom, Australia, Germany, Italy, Southern Africa, Poland, Holand, Norway,
France, ...
For more information on data sources for AmiBroker click here.
Symbol & quotes database
AmiBroker features advanced database system that offers the following:
• build-up and store historical tick or 5- or 15-second bar data for
backtesting purposes (certain RT data sources only)
• build-up and store intraday minute-bar or end-of-day data for backtesting
purposes
• unlimited number of symbols and unlimited number of quotes
• multiple database support
• stores quotes, company information, financial results, categories,
industry/sector information
• powerful filtering by sector, industry, group and market
• innovative symbol tree browser showing symbols grouped by sectors,
industries, indexes
• automatic handling for composities (number and volumes of advancing,
declining and unchanged symbols)
• automation support allowing you to control your database from external
programs written in any language including Java Script, VBScript
AmiBroker Formula Language
The language
The AFL is an advanced formula language that allows you to create your own
indicators, trading systems and commentaries. It is specialy designed for traders
so writing analysis formulas is easier and quicker than in general-purpose
languages.
AFL features more than 200 built-in AFL functions to use as a building blocks for
your formulas. AFL includes trigonometric, averaging, statistical, data
manipulation, conditional, pattern-detection and predefined indicator functions.
AFL supports unlimited variables, unlimited parentheses nesting, unlimited nested
function calls and multiple logical operators. Version 4.40 brings completely
rewritten engine with native flow-control and looping (if-else, while),
user-defined functions and procedures with local and global variable scope.
New version 4.50 provides native multiple time-frame support, so you can mix
Quick Tour
7
AmiBroker 5.80 User’s Guide
Introduction
different bar intervals in single formula.
Formula Editor / Drag-drop charting
Formula Editor allows you to quickly re-create any indicator/study found in the
literature. Drag and drop charting allows to create complex overlays,
indicators-on-indicators and more. Among other things it is possible to:
•
•
•
•
•
any number of graphs that can be overlaid in the same chart pane
modify built-in indicators
custom or automatic scaling
flexible grids
access to composite data (number/volume of advancing, declining, unchanged
issues)
Formula - based alerts
• Ability to write complex formula-based alerts that can be displayed on the
screen, sent to you via e-mail, plus play a user-defined WAV file.
• Ability to run external applications via alerts - this allows automated
trade execution
PORTFOLIO-LEVEL system back-testing, optimization, explorations and screening
Screening: Automatic analysis window enables you to scan your database for
symbols matching your defined buy/sell rules. AmiBroker automaticaly produces the
report telling you if buy/sell signals occurred on given symbol in the specified
period of time.
Exploration: search your database for symbols matching your criteria and create
the report showing the data you want to see: indicator values, past performance,
etc. Then sort the results by any value listed.
Back-testing: AmiBroker can also perform full-featured back-testing of your
trading strategy, giving you an idea about performance of your system.
The back-testing engine highlights:
•
•
•
•
•
•
•
•
•
PORTFOLIO LEVEL BACKTESTING/OPTIMIZATION
Three-dimensional (3D), fully animated charts of optimization results
Advanced custom backtester interface
User-definable backtest metrics
Different position sizing / money management techniques based on Portfolio
Equity
Hyper-fast execution - AmiBroker can backtest 10000 symbols (3000 data bars
each) = 30 million data points in FIVE minutes!
Integrated support for MULTIPLE time-frames in single formula
NEW Report Explorer provides great way to organize/compare/view all
backtest results
Scanning/Exploration/Backtest/Optimization on Real Time data (tick and up)
(RT version only)
Quick Tour
8
AmiBroker 5.80 User’s Guide
Introduction
• Scanning/Exploration/Backtest/Optimization on intraday data (1-min bars and
up)
• Back testing whole exchange or only limited, user-definable set matching
your market, group, industry, sector selection
• Equity curve plotting, Equity rainbows, composite equities curves
• Test long, short or both long and short trades
• Maximum-loss stop, profit-target stop, trailing-stop, N-bar (time) stop
• Realistic back-testing
• Ability to control position size from your formula (Read more...)
• Create your own composites and scan/backtest them
• Detailed reporting giving you imporant statistics of your system.
Optimization: AmiBroker allows you to optimize your trading system with up to 10
optimization variables on single or MULTIPLE securities at once!
Automatic Chart Commentaries and Interpretation
• Full, textual descriptions of actual situation on the market
• automatic buy-sell arrows visible on the charts
• automatic textual interpretation of indicators and price chart
(Window->Interpretation)
Scripting/COM/DLL support
• AFL engine allows embedding VBScript/JScript code within AFL formulas
providing UNLIMITED possibilities
• ability to call external COM (ActiveX) objects from the AFL formula
• free SDK (software development kit) for registered users allowing writing
indicator DLLs (plug-ins)
• many already available 3rd party plug-ins
Additional features
Portfolio manager
Built-in portfolio manager helps you track your investments. It
allows you to registed buy/sell transactions, calculates brokerage
commission, dividend (with setable dividend tax), cash
deposits/withdrawals. You get the instant calculation of your equity
value, percentage and point yield.
Scripting support
AmiBroker features automation interface that exposes objects and
methods that could be accessed from any programming language
including scripting dialects such as JScript (JavaScript) and
VBScript. The scripting capabilities of AmiBroker allows you to
automate time consuming database management tasks. Using scripting
you will be able to create automatic downloaders, maintenace tools,
exporters customized to your specific needs.
Internet integration
Quick Tour
9
AmiBroker 5.80 User’s Guide
Introduction
AmiBroker features built-in web browser that allows you to quickly
view company profiles. The profile viewer is completely configurable
so you can set it up for your particular exchange. The settings are
market based so you can access different web sites for each market
automatically. No longer will you be forced to waste your time
browsing manually to get the latest news and symbol related
information.
Configurability
AmiBroker is designed to be configurable and customizable in almost
every area. It is not tied to particular exchange or data provider.
Thanks to flexible import methods and scripting you will be able to
adopt it easily to your favourite market(s). Also technical analysis
tools built in into AmiBroker allow you to change every parameter
with easy, and if you want even more, you can create your own
indicators using flexible formula language.
Quick Tour
10
AmiBroker 5.80 User’s Guide
Introduction
Getting started
Hardware requirements
Supported operating systems
Installation and running
Getting help
Hardware requirements
To run AmiBroker you need PC-Compatible computer meeting following minimum
requirements
•
•
•
•
Pentium 450 MHz or higher
128 MB RAM
20 MB hard disk space
256 color graphics card (high color recommended) 800x600 minimum screen
resolution
Recommended machine configuration
• CPU: 1GHz or more, multiple cores
• 512 MB RAM or more
Supported operating systems
AmiBroker works on the following operating systems:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Windows 8 (any edition) 32-bit
Windows 8 (any edition) 64-bit
Windows 7 (any edition) 32-bit
Windows 7 (any edition) 64-bit
Windows Vista (any edition) 32-bit
Windows Vista (any edition) 64-bit
Windows Server 2008 (any edition) 32-bit
Windows Server 2008 (any edition) 64-bit
Windows Server 2008 R2 (any edition) 64-bit
Windows XP (any edition)
Windows XP x64 (64-bit)
Windows 2000 (any edition)
Windows NT 4.0 SP 3 (or higher) + Internet Explorer 4.0 or higher installed
Windows Millenium
Windows 98/98SE/95osr2/95
For more information about OS compatibility see: 32-bit/64-bit version
compatibility chart
Installation and running
Install AmiBroker using it’s setup program - it is available for download from
http://www.amibroker.com/download.html. After downloading double click on the
Getting started
11
AmiBroker 5.80 User’s Guide
Introduction
program’s icon. This will launch the setup program - you can safely accept all
default values by clicking "Next" on each page and "Install" on the last page. By
default AmiBroker is installed to "C:\Program Files\AmiBroker" directory and this
location is referred to as "main AmiBroker directory".
If setup program asks you to restart machine please do so to allow to replace
system components.
After installation, you can start AmiBroker from Windows’ standard
Start->Programs->AmiBroker->AmiBroker menu.
Just after starting AmiBroker splash window shows up, then for few seconds
AmiBroker loads its quotation database. Next the main AmiBroker screen appears.
AmiBroker main screen with price chart,
MACD and RSI indicators and profile view open. (Windows version)
In default setup you can see the toolbar, workspace window with symbol list on
the left side and chart windows on the right side.
The toolbar provides fast access to the most often used program functions. With
the symbol list view you can select active symbol. Changing the selection will
cause chart redraw and update in some information windows if they are open. The
chart windows let you to analyse current price trends and the behaviour of
technical indicators.
You can quit AmiBroker using the File/Exit menu item.
Getting help
AmiBroker features new context-senstive help system, available by pressing F1 key
anywhere in the program.
When you press F1 key while any window and any menu is shown, AmiBroker opens up
a relevant help file page describing the window or menu in question. No more
searching through the help file.
In addition to using F1 context-sensitive help it is highly recommended to read
ALL Tutorial articles first. The answers to most common problems are given there.
In case of major problem check Troubleshooting guide. Also there is a "Search"
tab on the left of this on-line help window that allows to quickly locate
information by keyword(s). Just type word(s) you are looking for and click
"Display".
In case of further questions/problems you may check the following resources:
• AmiBroker web page - which is searchable using "Search" box in the top left
corner of the page.
The page gives you an access to:
♦ AmiBroker Tips newsletter containing valuable step-by-step
instructions on using various aspects of AmiBroker
Getting help
12
AmiBroker 5.80 User’s Guide
Introduction
♦ Support area - featuring additional documentation
♦ Frequently Asked Questions - the list of most commonly asked
questions with the answers
♦ AFL Library - featuring ready-to-use AFL formulas for custom
indicators, commentaries and trading systems
♦ Members area - featuring material accessible by registered users only
• AmiBroker mailing list - the place where you can meet other AmiBroker
users, ask questions and share with ideas (with searchable archive). To
subscribe please send an empty e-mail to: [email protected]
To unsubscribe please send an empty e-mail to
[email protected]
Checking these places first will help me focusing on developing new features in
AmiBroker. In case of problems not covered in above resources please don’t
hesitate to contact me at: [email protected]
Getting help
13
AmiBroker 5.80 User’s Guide
Introduction
AmiBroker 32-bit vs 64-bit Compatibility Chart
SUMMARY
The following table clearly shows that AmiBroker Professional 32 bit runs on
EVERY Windows version (BOTH 32 and 64-bit) and with every data plugin. 64-bit
version of AmiBroker runs solely on 64-bit versions of Windows and only with
limited number of data sources due to lack of data vendors’ API support for
64-bit technology.
AmiBroker
Professional
32-bit
AmiBroker
Professional
64-bit
Operating systems
Windows 8 32-bit
Yes
No
Windows 8 64-bit
Yes
Yes
Windows 7 32-bit
Yes
No
Windows 7 64-bit
Yes
Yes
Windows Vista
Yes
No
Windows Vista x64
Yes
Yes
Windows Server 2008 (32-bit)
Yes
No
Windows Server 2008 x64 (64-bit)
Yes
Yes
Windows XP
Yes
No
Windows XP x64 (64-bit)
Yes
Yes
Windows 2000
Yes
No
Windows NT 4
Yes
No
Windows Millenium Edition (ME)
Yes
No
Windows 98
Yes
No
Windows 95
Yes
No
Addressable memory space
32-bit Operating System
64-bit Operating System
2 GB or 3 GB
3)
N/A
4 GB
1000 GB
Yes
Yes
Data sources
AmiQuote (Yahoo, MSN, Google
Finance)
AmiBroker 32-bit vs 64-bit Compatibility Chart
14
AmiBroker 5.80 User’s Guide
Introduction
Metastock import
Yes
Yes
Metastock plugin
Yes
Yes
eSignal RT
Yes
Yes
IQFeed RT
Yes
Yes
Interactive Brokers
Yes
Yes
Premium Data (via Metastock
plugin)
Yes
Yes
TC2000/TCNet
Yes
No2)
FastTrack
Yes
No2)
DDE
Yes
Yes
ODBC database
Yes
Yes
any ASCII file (via import)
Yes
Yes
Remarks:
1)
64-bit native version of this plugin possible and is under development
64-bit native version of this plugin is not technically possible because of
lack of 64-bit API from data vendor at the moment
3)
3GB addressable memory is only possible with /3G switch in 32-bit Windows
BOOT.INI file
2)
AmiBroker 32-bit vs 64-bit Compatibility Chart
15
AmiBroker 5.80 User’s Guide
Introduction
What’s new in the latest version?
Highlights of version 5.80
In addition to completely new functionality this version focuses on incremental
improvements and enhancements of existing functionality. There are hundreds of
new features and changes to existing functionality as compared to version 5.70,
listed in detail in "Release Notes" document in AmiBroker directory. Below is
just a short list of few of them:
• Brand-new completely rewritten AFL Formula Editor that supports the
following features:
♦ Improved Syntax highlighting
♦ Automatic brace matching/highlighting (NEW)
♦ Auto indentation (NEW)
♦ Indentation markers (NEW)
♦ Enhanced auto-complete in two modes (immediate (NEW) and on-demand)
♦ Parameter information
♦ Line numbering margin and selection margin (NEW)
♦ Code folding (NEW)
♦ In-line Error Reporting (NEW)
♦ New tabbed user interface with ability to work in both MDI and
separate floating frame mode, can be moved behind main AmiBroker
screen and brought back (Window->Toggle Frame) (NEW) or kept on top
(Window->Keep on top)
♦ Rectangular block copy/paste/delete (Use mouse and hold down left Alt
key to mark rectangular block)
♦ Enhanced printing (with syntax highlighting and header/footer)
• Code snippets - these are small pieces of re-usable AFL code. They can be
inserted by right-clicking in the AFL editor window and choosing "Insert
Snippet" menu. Code snippets are user-definable.
• New features in Low-level graphics
♦ multiple Z-order layers GfxSetZOrder
♦ co-ordinates can now be given in both pixels and bar-price mode
GfxSetCoordsMode
♦ speed improvements (upto 3x)
• Persistent Static variables - StaticVarSet/StaticVarSetText (added
’persistent’ parameter)
• Analysis (Backtest/Optimize) enhancements
♦ new "Trade using FX cash conversion" setting
♦ 64-bit SPSO/Tribes engine fixes
• New/enhanced AFL functions
♦ PlotTextSetFont (NEW)
♦ GfxSetCoordsMode (NEW)
♦ GfxSetZOrder (NEW)
♦ GfxGetTextWidth (NEW)
♦ fopen (added ’shared’ parameter)
♦ StaticVarSet/StaticVarSetText (added ’persistent’ parameter)
♦ SetOption (new option "StaticVarAutoSave")
♦ SetChartOptions (new flags chartDisableYAxisCursor,
chartDisableTooltips )
What’s new in the latest version?
16
AmiBroker 5.80 User’s Guide
Introduction
♦ PlotText (new parameter yoffset)
Highlights of version 5.70
In addition to completely new functionality this version focuses on incremental
improvements and enhancements of existing functionality. There are 116 new
features and changes to existing functionality as compared to version 5.60,
listed in detail in "Release Notes" document in AmiBroker directory. Below is
just a short list of few of them:
• Analysis improvements:
♦ New Multi-threaded Individual Optimization
♦ New general-purpose ranking functions
StaticVarGenerateRanks/StaticVarGetRankedSymbols
♦ User-definable ranking columns (via AddRankColumn function)
♦ Lots of internal speedups in backtesting/optimization engine
♦ SPSO, Tribes optimization engines now available also in 64-bit
• Time&Sales improvements: user-definable filtering, user-definable colors, 2
user-selectable display modes
• Database improvements:
♦ 64-bit version supports files larger than 2GB per symbol
♦ in-memory cache can hold upto 100 000 symbols (up from 20K)
♦ new 64-bit DDE and ODBC plugins
• Charting improvements:
♦ Greatly improved performance QuickData technology implemented
lowering CPU usage for charts
♦ Edit->’Paste Special’ allows to copy-paste entire chart pane with
various options
♦ Distance measuring when drawing trendlines (X,Y distance in the
status bar)
♦ X/Y constrains for drawing tools (press X and/or Y key to constrain
movement in either X or Y direction when drawing)
♦ ASCII importer adds support for millisecond timestamps
• AFL improvements:
♦ new functions:
◊ StaticVarGenerateRanks, StaticVarGetRankedSymbols general-purpose user-definable ranking
◊ Error - display user-definable error messages (also useful for
plugin developers)
◊ fdir - directory listing
◊ CategoryCreate - programmatic creation of watch-lists
◊ AddRankColumn - ranking columns in exploration
♦ performance improved for Percentile() (order(s) of magnitude)
♦ new fields supported in GetFnData
♦ XShift support added to PlotShapes
♦ speeded up transcendental mathfunctions (sqrt, sin,asin, cos, acos,
tan, atan, ln, log10, etc)
♦ improved SetSortColumns
What’s new in the latest version?
17
AmiBroker 5.80 User’s Guide
Introduction
Highlights of version 5.60
• Multithreaded GDI (graphics) rendering - now all drawing (graphic
rendering) is done in separate worker threads so the user interface is way
more responsive and charts are updated faster and completely independently
from each other.
• Automatic Walk-Forward out-of-sample summary report - each out-of-sample
step produces individual report now, plus there is a new summary report
that covers all out-of-sample steps. It is visible in the Report Explorer
as last one and has "PS" type.
• Enhanced color-coded backtest report
• XY (scatter) charts in explorations
• Chart themes and improved chart look (esp. the grid)
• One-click automatic setup and update of stocks listing, sector and industry
assignments for all major US exchanges
• Unlimited ad-hoc chart intervals by means of new Interval combo box that
accepts any interval typed manually
• support for ICB (Industry Classification Benchmark) categories in AFL, UI,
ASCII importer and OLE interface
• native Gradient area charts
• super-thick lines in Plot, PlotOHLC, PlotForeign
• new AFL functions: GetAsyncKeyState, InIcb, IcbID, StaticVarInfo,
SetGradientFill, XYChartAddPoint, XYChartSetAxis
• updated AFL functions with new functionality: Status, CategoryGetSymbols,
CategoryGetName, CategorySetName, CategoryAddSymbol, CategoryRemoveSymbol,
CategoryFind, Plot, PlotOHLC, PlotForeign
• new 64-bit eSignal plugin
• updated UI in many places
• many other improvements (see Release Notes for details)
Highlights of version 5.50
• New Analysis window introduced in version 5.50 brings the following
improvements over old Automatic Analysis
♦ multi-threaded operation = speed - new Analysis window uses all
available CPUs/cores to execute formulas in many threads in parallel
providing significant speed ups. For example on 4 core Intel i7 that
can run upto 8 threads, it can run upto 8 times faster than old
Analysis window. Exact speed up depends on complexity of the formula
(the more complex it is, the more speedup is possible), amount of
data processed (RAM access may be not as fast as CPU thus limiting
possible speed gains).
♦ non-blocking operation - you can now view, scroll and sort results of
analysis while they are still generated, also as user interface
thread is not used for processing for most part, charts and other
GUI-driven program parts are way more responsive than with old
automatic analysis
♦ multiple instances - you can run more than one instance of New
Analysis at a time, so you can run many
scans/backtest/explorations/optimizations in parallel without waiting
for one to complete
What’s new in the latest version?
18
AmiBroker 5.80 User’s Guide
•
•
•
•
•
•
•
•
•
•
•
•
Introduction
♦ slicker user interface - New Analysis window can act as tabbed
document, can be floated, buttons can be re-arranged for better
workflow. There is way more space for the result list, extra
information about execution is provided on the new "Info" tab. Also
walk-forward results are now displayed within New Analysis window for
less clutter.
Mini High-Low rank chart in Real Time quote window
User-definable mini bar charts in Explorations (see AddColumn function)
Add Rank Column feature - right-click Analysis result list and choose "Add
Rank column" - it adds a column with ordinal rankings based on current sort
or just row number column when list is not sorted
IRA account backtesting via SettlementDelay feature (see SetOption
function)
Range bars algorithm improved significantly
new AFL functions: ThreadSleep, StaticVarCompareExchange
updated AFL functions with new functionality: AddColumn, SetOption,
GetOption, CategoryGetSymbols, PopupWindow, GetFnData, ClipboardSet
updated OLE interface to support new Analysis window
updated custom backtester interface to support access to local,
per-analysis EquityArray property
updated UI in many places
Owner-draw list views for 10x speed improvement when displaying millions of
rows
many other improvements (see Release Notes for details)
Highlights of version 5.40
• Fully Multi-threaded charting. Massively parallel AFL execution (each chart
pane runs in separate thread) allows to maximize speed and utilisation of
modern multi-core / multi-CPU computers. For example on 8-core Intel i7 CPU
your charts will run upto 8 times faster than in version 5.30. The AFL
engine has been completely rewritten from ground up to allow multiple
instances of the engine running simultaneously. This enables not only
multithreading but also enhances responsiveness of entire application, as
even badly-written user formula used in a chart is not able to lock or slow
the rest of the program. Multi-threading is ON by default. It can be turned
off by unchecking "Multi-threaded charts" box in Tools->Preferences, "AFL"
tab but it is strongly discouraged. Multi-threading should be ON if you
want AmiBroker to operate at full speed.
• 12 new AFL functions
♦ DateTimeAdd - adds specified number of seconds/minutes/hours/days to
datetime
♦ HMA - Hull Moving average
♦ FIR - Finite Impulse Response filter
♦ PercentRank - calculate percent rank
♦ Lookup - search the array for bar with specified date/time
♦ FirstVisibleValue - get first visible value of the array
♦ LastVisibleValue - get last visible value of the array
♦ InGICS - check if given symbol belongs to specified GICS category
♦ GicsID - get information about GICS category
♦ PlaySound - play .WAV sound file
♦ ShellExecute - execute external program / file
What’s new in the latest version?
19
AmiBroker 5.80 User’s Guide
Introduction
♦ _DT - synonym of StrToDateTime
• Quote Editor improvements and fixes: allows user to turn on/off time shift
and editing timestamps down to milliseconds, fixed handling of 12 hour
(AM/PM) regional setting
• Charting improvements: better looking value labels, low-level gfx functions
speeded up 4 times.
• Charting-related changes
♦ Data Window and data tooltip readout is immediate and does not
require extra AFL execution (values required to display them are
stored in RAM during normal chart refresh and available without need
to re-run the formula). Tooltip variable is now obsolete. To display
custom values in tooltips without plotting a line you can use Plot()
with styleHidden flag.
♦ Interpreation display does not require AFL execution
♦ Inserting indicator and resetting parameters are orders of magnitude
faster
♦ chart zoom setting is now saved in a layout file and restored when
layout is loaded
• OLE interface improvements (new IsBusy method of Analysis object and Import
method refreshes UI automatically)
• AFL engine improvements:
♦ added warnings that detect potential user mistakes - such as
assignment within conditional expression or redundant calls to Plot()
function
♦ added extra checks for invalid parameter values for many functions
and array subscript == Null - appropriate error message is displayed
♦ PlotText optimized to conserve memory and reduce execution time by
skipping invisible parts
• Account manager fixes
• improved compatibility with Windows 7 (high-DPI aware manifest,
compatibility with Internet Explorer 9)
• 64bit-specific fixes (including fixing problems with 3rd party DLLs)
• new appearance themes and many other improvements and fixes
Highlights of version 5.30
• changed database format to support time stamp granularity down to one
microsecond (0.000001s) and more data fields
• static array variables
• user-definable backtest report charts (see examples in Charts window,
"Report Charts" folder)
• new Data Window (Window->Data Window)
• new Performance Monitor tool
• tick statistics added to Time&Sales window
• chart blank area extension using END key (on the keyboard), to restore
original setting press HOME key
• added option to require variable declarations
(SetOption("RequireDeclarations", True ));
• persistent column state (widths/order/visibility) in the Automatic Analysis
and all other list-views.
• gradient area charts capability (see Charts - Basic Chart - Gradient Price
chart)
What’s new in the latest version?
20
AmiBroker 5.80 User’s Guide
Introduction
• new typeof() AFL operator
• new AFL functions
♦ ColorBlend
♦ DateTimeDiff
♦ HighestVisibleValue
♦ LowestVisibleValue
♦ StaticVarCount
• User-definable Z-order of drawings and indicator plots
• optional data padding for non-trading days
• Rectangle and ellipse drawing tools are now solid by default
• X-Y co-ordinate labels added (use View->X-Y Labels menu to display/hide).
• Support for SSL (secure connection) and TCP/IP port selection for e-mail
alerts added
• new Symbols window with ultra quick full-text search and sorting
• support for GICS 4-level category system
• placing orders directly from chart (Interactive Brokers)
• many other improvements and fixes (see Release Notes document for details)
Highlights of version 5.20
• Smart (non-exhaustive) trading system optimization
•
•
•
•
•
•
•
AmiBroker now ships with 3 non-exhaustive, evolutionary optimization
algorithms:
SPSO (Standard Particle Swarm Optimizer)
TRIBES (Advances Particle Swarm)
CMA-ES (Covariance Matrix Adaptation Evolutionary Strategy
Support for market-neutral, long-short balanced strategies via
MaxOpenLong/MaxOpenShort control and separate long/short rankings in the
backtester
Performance optimizations in chart drawing engine - charts are orders of
magnitude faster when number of bars displayed is much greater than number
of pixels.
Log window implemented - allow tracing and run-time error reporting
QuickAFL implemented in the Automatic Analysis - speeds up backtests,
optimization and explorations by factor of 2 or more (if range is less than
all quotations). (Note: in order to enable it you need to check "Use
QuickAFL" box in the Automatic Analysis setttings).
Multiple-segment Volume-At-Price charts (via PlotVAPOverlayA function)
32-bit AmiBroker is now LARGEADDRESSAWARE, i.e. can now use upto 4GB of RAM
Built-in Quarterly and Yearly intervals
• Automatic summary rows in the explorations (via AddSummaryRows AFL
function)
• Charting enhancements and improvements
♦ better handling of drawing tools
♦ better magnet mode
♦ Fibonacci timezones now include lines 144 and 233
♦ zooming via scroll bar improved
• Range bars now use per-symbol TickSize as a unit
• new AFL functions:
GetChartBkColor
What’s new in the latest version?
21
AmiBroker 5.80 User’s Guide
Introduction
CategorySetName
PlotVAPOverlayA
AddSummaryRows
DaysSince1900
OptimizerSetEngine
OptimizerSetOption
StrCount
• AFL performance improvements in LinearReg, LinRegSlope, LinRegIntercept,
TSF and StdErr, Day(), Month(), Year(), DaysSince1900(), DayOfWeek(),
DayOfYear() functions (order of magnitude faster)
• Improved AFL functions: queued Say() command (text-to-speech), improved
StrExtract() - can now refer to items counting from the end
• real-time data plugins updated (IB version 1.2.4, eSignal version 1.9.0),
IBController updated to support latest changes in data sources
Highlights of version 5.10
• Automatic Walk-Forward testing (trading system optimization and validation
technique)
• Floating windows (TRUE multi-monitor charting capability)
ability to "undock" (or "float") the chart window and move it to separate
monitor.
All layout code is also updated to correctly save and restore multi-monitor
chart setups
http://www.amibroker.com/video/FloatAndLink.html
• Symbol and Interval linking
multiple charts can now be linked by symbol and/or by interval using
easy-to-use color-coded links
• AFL Code Profiler - shows code analysis with detailed per-function timing
report (AFL Editor: Tools->Code Check & Profile menu)
• Real-time quote window improvements
♦ re-ordering of symbols in the RT quote using drag-and-drop
♦ direct type-in symbols into RT quote window
♦ ability to separate groups of symbols by inserting empty line
♦ faster refresh and multi-stage background color fading on quote
change
• new/improved AFL functions
♦ (new) SetBarFillColor
♦ (improved) GetCursorXPosition
♦ (improved) GetCursorYPosition
♦ (improved) GetCursorMouseButtons
♦ (improved) SetChartOptions
♦ (improved) SetOption
What’s new in the latest version?
22
AmiBroker 5.80 User’s Guide
Introduction
♦ (improved) Status
• Improved speed of backtesting/optimization (up to 2x in some cases as
compared to v5.00)
• improved chart crosshairs - no flicker, work faster and can be switched
on/off globally
• track more foreign markets: now you can define rates for up to 20
currencies (different than base currency) for multiple currency backtesting
in the preferences window.
• new backtester modes: backtestRegularRaw2 and backtestRegularRaw2Multi
• new FindSignal method of backtester object
• 3D optimization chart animation is now smoother (100fps)
• unlimited nesting of #include and #include_once statements
• Improved scaling of semi-log charts, MDI tab order saved in the layout,
improved bug reporting, high resoltion Vista icon added, other fixes and
improvements
Highlights of version 5.00
• New Watchlist system featuring:
♦ unlimited number of watch lists
♦ lists keep original order in which symbols were added (still can be
sorted alphabetically on-demand)
♦ new AFL function to refer to watch lists by name
• Support for AFL Code Wizard - brand new automatic formula creation program
for people without any programming experience. For more information about
AFL Code wizard see this introductory video:
http://www.amibroker.com/video/amiwiz/AFLWiz1.html
• AFL engine enhancements
♦ new flow control statements: switch /case / break / continue
♦ new compound assignment operators: +=, -=, *=, /=, %=, &=, |=
♦ new functions: GetPlaybackDateTime(), PopupWindow(), Mersene Twister
Random Number Generator mtRandom(), and others
• New dedicated memory heap allocators for quotes and trading system signals
resulting in ability to run much longer optimizations than ever without
getting out-of-memory messages
• Two new backtester modes (available using SetBacktestMode function)
allowing handling of unfiltered (raw) entry signals
• User-definable 5-tier commission schedule in the backtest (Automatic
Analysis / Settings)
• Chart template sharing
now you can save the chart as "Chart Template, Complete (*.chart)" that
stores all layout AND referenced formulas in SINGLE file that can be sent
to your friend and entire chart will be restored on any computer with ease,
without need to copy individual formulas.
What’s new in the latest version?
23
AmiBroker 5.80 User’s Guide
Introduction
• New-Look charts - divider lines between panes are now single pixel and no
borders around charts giving cleaner, larger and more readable chart
display and printout
• Custom Range Bars (supported in the charts and via TimeFrameSet())
• New Low-level graphics interface (23 new AFL functions)
• HTML Import in Automatic Analysis
• Full screen Anti-Aliasing in 3D optimization chart viewer (beautifully
smooth 3D charts and improved readability)
• Enhanced Real-Time Quote window display (faster updates, dual-color change
marks)
• Control of Time Shift in the ASCII importer
Highlights of version 4.90:
• new Fundamental data support including
♦ automatic download from free Yahoo Finance site
♦ access to fundamental data from AFL level
♦ new fundamental data fields in the Information window
• new Web Research window
♦ user-definable sites
♦ multiple on-line research windows open simultaneously
♦ flexible auto-synchronization options
• new Account Manager
♦ tracking history of all transactions
♦ tracking open position unrealized profit
♦ tracking account equity history
♦ short and long trades, automatic handling of scaling in/out
♦ unlimited number of accounts
♦ per-account settings/commissions
• new Bar Replay tool - great learning tool, featuring
♦ re-playing all symbols’ data at once
♦ fast scrolling
♦ user-definable playback speed and interval
• added Text-To-Speech capability via Say() AFL function. Now AmiBroker can
speak out loud any text, for example it can say "Buy 100 shares of AAPL at
91". This is controllable from formula level so you can make it to speak
depending on market conditions, signals generated from your formula, etc.
• added ability to fill indicator background with gradient color - via
SetChartBkGradientFill AFL function.
• new Fast Fourier Transform function
• automatic exploration result sorting from AFL level - via SetSortColumns
AFL function.
• high-resolution performance timing added via GetPerformanceCounter,
per-chart timed refreshes via RequestTimedRefresh
• HoldMinDays / EarlyExitDays feature in the backtester
• ’Every tick’ chart refresh capability added (Professional Edition only)
• MDI Tabs added as UI enhancement.
• OLE interface enhancements/additions
What’s new in the latest version?
24
AmiBroker 5.80 User’s Guide
Introduction
Detailed Change Log
CHANGES FOR VERSION 5.50.2 (as compared to 5.50.1)
• New Analysis: If current formula is open in the formula editor it is
auto-saved prior to running any Analysis (as old AA did)
• New Analysis: on Backtest/Optimization current formula is saved in
@LastBacktestFormula registry key so it can be referenced by Individual
Equity formula
• New Analysis and Old AA: HoldMinBars > 0 can now be used together with
AllowSameBarExit=True Settings: ’Stops’ tab: N Bar stop has priority check
box state was not saved. Fixed
• New Analysis: on attempt to load analysis project file that contains
formula path that does not exist or is not writable AmiBroker will create
the formula in the "Formulas\Imported" folder instead of not creating it at
all
• New Analysis: WinXP-only - RMB click column descend/ascend menus were not
working due to Windows XP bug. Fixed.
• New Analysis: when formula is picked from the folder that is inside current
working directory, then relative path is used and stored in project instead
of absolute path previously used
• New Analysis: SeparateLongShortRank required proper MaxLongPos and
MaxShortPos definitions in order to work. Now if they are missing defaults
are applied as in old AA.
• Plugins: IQFeed: added "You can’t close plugin window" on attempt to close
working IQFeed window.
• UI: Chart tree, Layout tree in "Explorer" theme
• UI: Category list now features new icons and decreased indentation
• UI: Owner-draw listviews now fully implement ellipsis item truncation
mechanism, but using ExtTextOut only which is 6 times faster than DrawText
that Windows uses
• UI: Floating non-chart windows (account/web browser/analysis) are not
closed when switching layouts.
• Plugins: IQFeed plugin uses new faster IQFeed API, downloads less and uses
way more efficient method to backfill 1/5/15-second base time intervals
CHANGES FOR VERSION 5.50.1 (as compared to 5.50.0)
• New Analysis: Individual Backtest implemented. Note that it runs with
approx same speed as old AA as Individual Backtest is single threaded for
reasons explained in the User’s manual
http://www.amibroker.com/guide/h_multithreading.html
• New Analysis: toolbar icons for parameters and settings changed to avoid
confusion with the icon for preferences
• UI: Symbol List uses Windows 7/Vista style
• New Analysis: Toolbar customization is now saved
• MRU (most recently used) file menu moved to submenu and MRU list increased
to 10 items
• Charts: fixed small alignment problem on Y axis when using fixed
(nonproportional) font
• New Analysis: backtester object now has EquityArray property that returns
Detailed Change Log
25
AmiBroker 5.80 User’s Guide
Introduction
entire equity array (not just current value).
Please note that values are filled during backtest and only after backtest
is complete, all values are valid. If you call it in the middle, it will
contain only "upto given point" data. Avoid abusing this function and it is
costly in terms of RAM/CPU.e).
You may use
bo.EquityArray instead of Foreign("~~~Equity", "C" )
in custom backtester code.
It accesses local copy of equity in New Analysis (unlike Foreign that
accesses global symbol)
• New Analysis: AddToComposite with atcDeleteValues | atcEnableInPortfolio
did not delete previous values. Fixed
• New Analysis: "Interval" menu item in the auto-repeat group renamed to "AR
interval" because some users interpreted it wrong (as periodicity)
• New Analysis: OLE interface implemented
Description in the http://www.amibroker.com/guide/objects.html
Example
The following JScript example
a) opens analysis project from C:\Analysis1.apx file
b) starts backtest (asynchronously)
c) waits for completion
d) exports results
e) closes analysis document
AB = new ActiveXObject( "Broker.Application" );
try
{
NewA = AB.AnalysisDocs.Open( "c:\\analysis1.apx" ); // opens given
analysis project file
if ( NewA )
{
NewA.Run( 2 ); // starts analysis (asynchronous - returns immediatelly
// (0-scan, 1- exploration, 2- portfolio backtest, 4- optimization,
6-walk forward)
while ( NewA.IsBusy )
WScript.Sleep( 500 ); // wait for completion
NewA.Export( "test.html" ); // exporing results
WScript.echo( "ended" );
NewA.Close(); // closing analysis window
}
}
catch ( exc )
{
WScript.echo( "Exception: " + exc.message );
Detailed Change Log
26
AmiBroker 5.80 User’s Guide
Introduction
}
• Charts: more tweaks for Y axis algorithm for readability. Now in
Tools->Preferences, "Charting" the user may select different grid stepping:
Instead of default 1, 2, 5, 10 grid stepping, user may select to use 2.5
step instead of 2 (Use 2.5 step in Y axis)
• GetFnData() supports new field "Alias" - return Alias field without need to
use OLE
• GetOption supports new fields: ApplyTo and Filter*, eliminates the need to
use OLE for that purpose
New fields:
-"ApplyTo" - returns Analysis "Apply To" setting 0 - all symbols, 1 current symbol, 2 - filter
- "FilterIncludeIndex", "FilterIncludeFavorite", "FilterIncludeMarket",
"FilterIncludeGroup", "FilterIncludeSector", "FilterIncludeIndustry",
"FilterIncludeWatchlist" - return "Include" filter settings -1 - means NOT
selected (not included), >= 0 index of included category
- "FilterExcludeIndex", "FilterExcludeFavorite", "FilterExcludeMarket",
"FilterExcludeGroup", "FilterExcludeSector", "FilterExcludeIndustry",
"FilterExcludeWatchlist" - return "Exclude" filter settings -1 - means NOT
selected (not excluded), >= 0 index of excluded category
• Fix for FPU inaccurracies in range bars implemented
CHANGES FOR VERSION 5.50.0 (as compared to 5.49.2)
• New Analysis: "Save" creates now a Analysis project (.apx) file that
includes all settings and formula needed in single file. The file itself is
in human readable XML format. When such file is loaded on somebodys’ else
computer it will recreate original formula if one is not present. It will
warn if there is a name conflict and let you decide to keep existing
formula or overwrite.
• UI: File open dialog now has "All supported files" option in the "Files of
type"
• UI: PopupWindow is now resizable (see size gripper in the lower-right
corner)
• AFL: PopupWindow function has additional parameters to control width/height
and flag that controls whenever popup window captures input focus
PopupWindow( "bodytext","captiontext", timeout = 5, left = -1, top = -1,
width = -1, height = -1, captureFocus = True );
width = width in pixels, -1 - use default width
height = height in pixels, -1 - use default height
captureFocus - decides whenever popup window captures input focus or not
Example: popup window that does not change input focus:
PopupWindow("test", "caption", 30, -1, -1, -1, -1, False);
• New Analysis: ApplyStops applied in non-regular modes are passed to 2nd
phase properly now.
• New Analysis: "Show current trade arrows" fixed.
• New Analysis: View->Filtering menu options were not available when New
Analysis was active. Fixed.
Detailed Change Log
27
AmiBroker 5.80 User’s Guide
Introduction
• New Analysis: Standard Edition has a limit of max 2 threads per Analysis
window instance.
• UI: Log window clicking on error displayed AFL Editor and marked Line+1,
Col+1 char position instead of proper place. Fixed
• New Analysis: Errors are now displayed in a modern message bar instead of
dialog box
• UI: holding down Ctrl and Q keys simultaneously while AmiBroker is starting
resets all menus/command bars to defaults
• New Analysis: scroll bar properly works when "Walk forward" tab is active
• New Analysis: Walk forward tab content can be now copied using Edit->Copy /
Ctrl+C
• New Analysis: when "wait for backfill" was turned on and external data
source was very slow to repond (like IQFeed during backfill) subsequent
calls to Status(’stocknum’) could give non-unique numbers. Fixed.
• New Analysis: Copy to clipboard includes headers now
• New Analysis: Column customization/state persistence implemented
• Charts: New Y axis grid algorithm for clearer display on condensed charts
• AFL: CategoryGetSymbols supports new categoryAll (all symbols in the
database) and new Mode parameter
CategoryGetSymbols( category, number, mode = 0 );
Mode parameter decides what field is retrived:
0 (default value) - ticker symbol
1 - full name
Example: to get all symbols existing in the database simply call
CategoryGetSymbols( categoryAll, 0 );
to get full names of all symbols use:
CategoryGetSymbols( categoryAll, 0, 1 );
• AFL: Added Warning 503. Using OLE / CreateObject / CreateStaticObject is
not multi-threading friendly. See Users’ Guide ""Efficient use of
multithreading"" for more details.
• AFL: Added ThreadSleep( milliseconds ) function. It 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.
• AFL: Added StaticVarCompareExchange function. Provides atomic interlocked
compare/exchange functionality
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.
Return Values
The return value is the initial value of the destination static variable.
Detailed Change Log
28
AmiBroker 5.80 User’s Guide
Introduction
If variable did not exist, it returns zero.
The StaticVarCompareExchange function performs an atomic comparison of the
"varname" static variable value with the Comperand value. If the static
variable value is equal to the Comperand value, the Exchange value is
stored in the static variable. Otherwise, no operation is performed.
The function StaticVarCompareExchange provides a simple mechanism for
synchronizing access to static variables that are shared by multiple
threads. The following examples show how to implement semaphore and
critical section in AFL using StaticVarCompareExchange function:
// EXAMPLE 1 : Simple semaphore (no waiting)
if( StaticVarCompareExchange( "semaphore", 1, 0 ) == 0 ) // obtain
semaphore
{
// protected section here
// Here you have exclusive access (no other threads that check for
semaphore will enter simultaneously)
/////////////////////////
StaticVarSet("semaphore", 0 ); // reset semaphore
}
else
{
_TRACE("Can not obtain semaphore");
}
///////////////
// EXAMPLE 2 HOW TO IMPLEMENT CRITICAL SECTION IN AFL
///////////////
function _TryEnterCS( secname )
{
global _cursec;
_cursec= "";
// try obtaining semaphore for 1000 ms
for( i = 0; i < 1000; i++ )
if( StaticVarCompareExchange( secname, 1, 0 ) == 0 )
{
_cursec = secname;
break;
}
else ThreadSleep( 1 ); //sleep one millisecond
return _cursec != "";
}
// call it ONLY when _TryEnterCS returned TRUE !
function _LeaveCS()
{
global _cursec;
Detailed Change Log
29
AmiBroker 5.80 User’s Guide
Introduction
if( _cursec != "" )
{
StaticVarSet( _cursec, 0 );
_cursec = "";
}
}
function TimeConsumingWork()
{
// WARNING: the Percentile is CPU hungry as it involves lots of sorting,
the loop below may take > 1 second to complete
for( i = 0; i< 10; i++ ) Percentile( C, 100, 10 );
}
//_TRACE("Without CS Begin " + GetChartID() );
//TimeConsumingWork(); // some time consuming calculation
//_TRACE("Without CS End" + GetChartID() );
// Example usage (critical section)
if( _TryEnterCS( "mysemaphore" ) )
{
// you are inside critical section now
_TRACE("Begin CS " + GetChartID() );
TimeConsumingWork(); // some time consuming calculation
_TRACE("End CS " + GetChartID() );
_LeaveCS();
}
else
{
_TRACE("Unable to enter CS");
}
CHANGES FOR VERSION 5.49.2 (as compared to 5.49.1)
• New Analysis: added Optimize->3D Optimization chart menu
• New Analysis: buttons for Portfolio Equity/Individual Equity charts added
• New Analysis: Info Bar added (that duplicates some of the info that
normally appears on the Info Tab). It can be turned on using Settings->Info
Bar
• New Analysis: Report generation is now OFF by default when running
optimization/walk forward as in old AA. This gives about 0.9 sec gain per
step.
• New Analysis: Single-symbol optimization made faster by caching already
compressed quote array on subsequent steps
• New Analysis: the check for Status("StockNum") was sensitive to blanks
between parenthesis, function name and string parameter. Now it is made
insensitive to blanks.
• New Analysis: when "Range" was "n last bars" or "n last days",
Status("rangefromdate") gave date of preceding bar. Fixed.
• UI: "Performance" tooltip title was not always updated on time. Fixed.
Detailed Change Log
30
AmiBroker 5.80 User’s Guide
Introduction
• UI: "Wait for plugin" window displays progress bar with "marquee" style
instead of circle of dots
CHANGES FOR VERSION 5.49.1 (as compared to 5.49.0)
• New Analysis: Testing on unaligned data sometimes took longer than expected
because of the work necessary to bring signals in order. Now a smart method
avoids most of the memory transfers and can give 10x speedup on backtesting
very long unaligned intraday data.
• New Analysis: "Backtest started", "Exploration started" text in the info
tab appeared twice per run (instead of once). Fixed
• New Analysis: Backtest report did not include formula code. Fixed.
• New Analysis: Fixed crash that could occur when running analysis with Range
set to "N recent bars" and N was exceeding number of quotes.
• New Analysis: Float/Normal/Close popup menu RMB menu was active everywhere
in floating window instead of only caption area. Fixed.
• New Analysis: Implement single-thread start when Status("StockNum") is
detected in the code. Other threads are started when first symbol
processing is completed.
• New Analysis: Send to Analysis did not update formula combo box properly in
certain scenarios: when formula X was selected, then formula Y, then
formula X again. Fixed.
• Old AA: status bar displays true timing for fair comparisons between old AA
and new Analysis. Watching progress bar numbers was misleading as it closed
before all processing was truly complete, so it looked like old AA
completed sooner than it really did
• UI: menu item for Old Automatic Analysis restored as apparently some users
got lost. Also attempt to run old Automatic analysis displays an
information about new Analysis window
CHANGES FOR VERSION 5.49.0 (as compared to 5.48.0)
• New Analysis: when floating pane is made normal from/to dates were reset to
today. Fixed.
• New Analysis: when Apply To: Filter is defined so NO symbol matches the
criteria, appropriate message is displayed when trying to run Analysis and
action is terminated instead of displaying progress bar forever
• New Analysis: when analysis window is "floating" double click/show
arrows/sync affects active MDI chart just like old AA did, as opposed to
last one (when analysis is not floating)
• New Analysis: Optimization parameter setup stage uses now not more than 100
bars. This reduces setup time.
• New Analysis: implemented import / export, File menu now has Import HTML
and Export HTML/CSV commands
• New Analysis: Implemented "Wait for backfill" option. This slows down
analysis sequence so AmiBroker waits for external RT data source to deliver
backfill data
When "wait for backfill" option is turned on, AmiBroker checks if data for
given symbol are complete, if not, it sends request to external source to
backfill the data and waits 1 second.
After one second, it checks again, it data are complete, if not, it waits
another 1 second, and so on. Once data are complete given symbol is used
Detailed Change Log
31
AmiBroker 5.80 User’s Guide
Introduction
for formula execution.
• New Analysis: Custom backtester uses "last backtest settings" when calling
GetStatus() instead of old AA settings
• New Analysis: auto-repeat interval edit field did not allow to enter values
if moved to main toolbar via customization. Fixed.
• Formula Editor Analysis toolbar button now operates on New Analysis window
• Default for timestamping of intraday compression changed to "Show START
time of interval"
• Charts: AFL error message color is now definable in Tools->Preferences,
"Color" tab
• Charts: Tooltips automatically display also OHL prices (in addition to
close) when Plot style is set to candlestick, bar or when PlotOHLC was used
• UI: Adjusted item Y offset for owner drawn listviews for consitent look
with old layout of system listviews in Windows XP and earlier OSes
• UI: Account, Analysis and Web research windows don’t use client edge/border
anymore - gives slicker / less crowded look
• UI: when focus is switched to floating document window, the application
menu is switched to proper context
• UI: When File->Close was used on floating pane, document was closed but
docking pane was not. Fixed.
• UI: The toolbar button and menu option to launch old Automatic Analysis
window are now hidden (can be brought back by using Tools->Customize), old
AA can also be launched from new Analysis via Analysis->Old Analysis menu
• UI: New menu options and toolbar button to launch new analysis window
• UI: Moved all menu items controlling visibility of docking windows to
"Window" menu
• UI: floating state of windows can now be turned on/off using right-click
menu over tab / floating window caption
• UI: File->Save (when currently selected window is a chart) command now
saves Chart template. To save database use "Save database" instead.
• UI: Defaults for data window are changed, so extra OHL display is turned
off by default as currently PlotOHLC displays all 4 prices in the tooltip
and data window already
• UI: Data window scroll bars are hidden and do not flicker when updating
• UI: "Save All" toolbar button removed, "Save database" button added to
replace it
• Web Research: turned on "silent" mode - should prevent error message boxes
displayed by IE engine.
• QuoteEngine: Range bars algorithm improved significantly
• Quote array uses 20480 bytes (512 quotes) allocation chunk size (exactly
5x4KB page) for better alignment with Windows virtual memory pages
CHANGES FOR VERSION 5.48.0 (as compared to 5.47.0)
• New Analysis: custom metrics columns were invisible in
backtest/optimizations. Fixed. (#91031)
• New Analysis: backtest did not display proper column names when Report mode
was different than trade list. Fixed. Also added support for changing
report mode via SetOption().
• New Analysis: Auto-repeat Scan/Explore implemented (aka. "Run every" in old
AA) (use drop down menu next to "Settings" button)
• New Analysis: Showing arrows by double click implemented
Detailed Change Log
32
AmiBroker 5.80 User’s Guide
Introduction
• New Analysis: Sync chart on select option implemented (use drop down menu
next to "Settings" button)
• Fixed window activation issue after RMB click in chart window when
non-chart floating windows are active
• New Analysis: Cancelling walk-forward did not restore date range and
settings and didn’t reset internal step counter. Fixed.
• New Analysis: Formula path disappeared when window was made floating.
Fixed.
• New Analysis: in 5.47 non-exhaustive optimizers sometimes stopped after
first step in walk-forward. Fixed.
• Charting: scroll bar zoom function remains active even at extreme zoom in
levels
• New Analysis: Fixed problem with opt steps warning dialog appearing
sometimes in the out-of-sample tests in walk forward sequence
• New Analysis: Signal heaps are separated now, allowing to run concurrent
backtest/optimizations in many analysis windows
• New Analysis: removed unnecessary refreshes of symbol list during
optimizations that caused slowdowns when user had large database
• New Analysis: The size of control fields is properly adjusted with regards
to DPI
• New Analysis: Status("StockNum") was always zero in 5.47 and earlier. Now
it is set properly.
Caveat: be careful when you run codes that use Status("StockNum")==0 for
special processing in multithreading mode.
Other threads with "StockNum" = 1, 2, 3,... will run simultaneously! If you
store static variables in step 0 these variables may be empty if you access
them from other parallel running threads.
• Fixed Error 53 message that was giving an error when proper \" (quotation
mark espace sequence) was used
CHANGES FOR VERSION 5.47.0 (as compared to 5.46.0)
• New Analysis: last used ApplyTo/Range/From/to dates/filters and other
settings are saved when Analysis window is closed
• Fix to "slow response" problems some users reported when switching symbols
• Fibonacci retracement- modifying Z-order affected only control trendline,
not all lines as it should. Fixed.
• New Analysis: implemented Walk-Forward testing (use drop arrow next to
Optimization button)
• AFL engine: new error 53: incorrect \ espace sequence. Error is issued when
user forgets that single slash must be written as \\
• Default title for new analysis window is "AnalysisX" (instead of "Unnamed")
where X is consecutive number 1, 2..
• attempt to use Say() on computer without sound card or without driver
installed does not result in throwing exception/crash report, but it is
rather silently ignored
CHANGES FOR VERSION 5.46.0 (as compared to 5.45.0)
• New Analysis: Exhaustive multi-threaded optimization implemented
• New Analysis: Smart (non-exhaustive) multi-threaded optimization
implemented in a way compatible with existing optimizer plugins
Detailed Change Log
33
AmiBroker 5.80 User’s Guide
Introduction
Note however that due to the fact that most non-exhaustive optimization
plugins are not re-entrant, AmiBroker prevents from running more than one
non-exhaustive multi-threaded optimization at a time. You can however, run
many exhaustive optimizations in parallel, as they don’t require external
plugins.
• Slight modification to the way how compressed bar charts are drawn (so bars
with H==L are better visible)
CHANGES FOR VERSION 5.45.0 (as compared to 5.44.1)
• 64-bit version compiled with new version of C runtime (Microsoft security
update)
• Fixed date/time column sorting in virtual list views when regional date
format was different than yyyy-MM-dd
• AFL: ClipboardSet() returns True (1) when clipboard has been successfully
set. Sometimes clipboard is locked by another applications and then write
can fail (ClipboardSet() will return zero/False then)
• New Analysis: Changed alignment of Date/Time column to left in backtest
result list.
• Most AFL engine setup moved to worker threads. Result - smaller UI thread
load in MT charts (better scalability) and much faster (upto 2x)
explorations/scans in New Analysis window
• New Analysis: added "Info" tab that provides some summary information about
analysis (number of rows, timings, backtest summary) - contents can be
copied using Ctrl+C / Edit->Copy
NOTE:
End users should only look at "Completed in... sec" line that shows actual
run time of the analysis (scan/exploration/backtest).
The times shown in "timings" row are for Amibroker.com internal use. In
development/testing they help us tweak the performance of various parts of
analysis engine. The detailed timings do not sum up to actual run time. No
further infomation is available at the moment. The "timings" row is subject
to change/removal in the future versions.
If you have problems/questions with the performance of new Analysis window
please copy (Ctrl+C) the contents of Info tab and send to support.
• New Analysis: first-phase backtest signal processing and ranking moved to
non-UI threads, enabling better parallelism, results in better backtest
performance (upto 2x in with trivial codes)
CHANGES FOR VERSION 5.44.0 (as compared to 5.43.1)
• New Analysis: fixed AddToComposite()
• New Analysis: Interval() function was working incorrectly in new analysis
window. Fixed.
• New Analysis: Backtest ~~~EQUITY symbol did not have "use only local
database" set in 5.43.1. Fixed.
• New Analysis: Backtest performance improved by removing some unnecessary
list view refreshes (now it should never be slower than old AA even with
Detailed Change Log
34
AmiBroker 5.80 User’s Guide
Introduction
simplest formulas)
CHANGES FOR VERSION 5.43.1 (as compared to 5.43.0)
• When range different than "All quotes" was selected, backtest in new
Analysis window could produce incorrect results in 5.43.0. Fixed.
CHANGES FOR VERSION 5.43.0 (as compared to 5.42.0)
• New Analysis Window: multi-threaded Backtest feature implemented
(experimental)
•
•
•
•
•
•
Note that only first phase of backtest is multithreaded (each symbol in
separate thread). 2nd phase (custom backtest) is executed in main thread as
there is only one symbol to work on (i.e. equity) and it needs to talk with
OLE which is single threaded and GUI.
Load/Unload buttons removed from Plugins dialog. This was developer-only
feature and it was abused by ordinary people who were unloading plugins
that were actually in -use (such as data plugins when being connected to
given data source)
ListViews: the last line (partially shown) in RT quote window was not
easily selectable. Fixed
New Analysis window: Implemented Parameters dialog
AFL: GetCursorMouseButtons() sometimes missed clicks when multithreading
was on and formula took ages to execute. Now it is now 100% reliable.
Auto-selection of proper layer based on selected viewing interval
NOTE: This feature can be turned off by click with RIGHT mouse button over
layers window and UNCHECKING "Auto-select layer"
IRA accounts support - implemented Settlement delay in backtester, via
SetOption("SettlementDelay", x )
"SettlementDelay" option describes the number of days (not bars) it takes
for sale proceeds to settle and be available for opening new positions.
SetOption("SettlementDelay", 3 ); // this will cause that proceeds from
sale are only available for trading on 3rd day after sale
For detailed tracking
" Detailed log" report option now shows available and unsettled funds for
T+1, T+2 and so on
Note: when using this option it is recommended to use backtestRegularRaw
instead of backtestRegular, otherwise some trades may not be entered
because funds are not settled immediately and you need to be able to enter
not on first but subsequent buy signals and that is exactly what
backtestRegularRaw offers.
Note2: old backtester (Equity() function) ignores settlement delay
• Zoom in/out toolbar buttons zoom in finer steps (+/-10%)
• Analysis ListView, RMB menu new option: "Add Rank column" - adds a column
with ordinal rankings based on current sort or just row number column when
list is not sorted
• New feature: Adding new chart/research/account/analysis via (+) tab
• New Analysis window: Implemented SetSortColumns
Detailed Change Log
35
AmiBroker 5.80 User’s Guide
Introduction
• New Analysis window: Implemented AddSummaryRows
CHANGES FOR VERSION 5.42.0 (as compared to 5.41.0)
• Implemented right click menu in new Analysis windows (Add symbols to
watchlist/Show arrows functionality)
• Zoom in/out toolbar buttons now have auto-repeat feature
• In 5.41.0 Ctrl+C from list view copied text without tabs (column
separators). Fixed
• In 5.41.0 did not refresh progress dialog optimization status list. Fixed.
(owner draw list view initial size is retrieved in PreSubclass now)
• In 5.41.0 did not display Time&Sales in reverse order (newest on top).
Fixed.
CHANGES FOR VERSION 5.41.0 (as compared to 5.40.3)
• New Analysis window (File->New->Analysis) - featuring multithreaded Scan
and Exploration
Performance note:
to fully benefit from multithreading it is best to use AmiBroker local
NATIVE database (not external)
as it is the only database that can deliver data quickly enough.
Tests show that on AmiBroker native databases scans and explorations are
100% scalable to multiple cores
- i.e. for example would run upto 8 times faster on 8 CPU/core machine.
IMPORTANT: This window is work-in-progress. Multithreaded Backtest and
Optimization features will be added later.
• AFL: AddColumn - added mini bar charts to explorations
Exploration now features ability to create mini bar charts in individual
cells.
AddColumn has new parameter ’barchart’
AddColumn( ARRAY, "Caption", format = 1.2, fgcolor = colorDefault, bkcolor
= colorDefault, width = -1, barchart = null )
’barchart’ parameter accepts values from 0...100 represening percentage
width of bar chart displayed in a cell
the in-cell bar chart is drawn with bkcolor (background color).
Example usage:
Filter=1;
AddColumn( Close, "Close" );
rank = PercentRank( Close, 100 );
Color = ColorHSB( rank * 64/100, 255, 255 );
AddColumn( rank, "100-day percent rank", 1.2, colorDefault, Color, -1, rank
);
Detailed Change Log
36
AmiBroker 5.80 User’s Guide
•
•
•
•
•
•
•
•
•
•
Introduction
Note that although this example uses same value for numeric display and
chart bar width, it does NOT need
to be the same, i.e. numerical value of the cell is independent from bar
chart.
Totally rewritten listview with very efficient owner draw code speeds up
list view scrolling/resizing/repainting more than 10 times. Native system
ListView control is terribly slow on Windows XP/Vista/7 (surprisingly it
was many times faster in Win9x!)
AFL: Percentile() does a param check for range > 0 now
Mini-chart in RT Quote window - Mini chart shows where LAST price is within
LOW-HIGH range.
Errors and warnings are now displayed in red color in the indicator pane
During actual GDI chart rendering AmiBroker measures time and if it exceeds
500ms timeout it stops rendering with Warning 901.
This check is required because GDI rendering occurs in GUI thread and if
GUI thread does not process messages for half second Windows will think
that application is "not responding".
This prevents making application stuck with some overly complex, possibly
incorrect formulas that call hundreds of Plot()s
Warning 502: Calling Plot()/PlotOHLC over 500 times is displayed in
indicator in runtime to prevent abuse
All list views, pressing Ctrl and NumPad’+’ automatically adjusts column
widths to content
if data are missing in the in-memory cache, Foreign() calls from non-GUI
threads use synchronous retrieval method for reliability.
This provides reliable results in AA but may slow down the multi-threaded
operations if cache size is too small and user uses more Foreign() calls
than in-memory cache size.
IMPORTANT:
For optimum performance in-memory cache setting (Tools->Preferences->Data)
should be GREATER than number of Foreign() calls in any single formula
used.
Values lower than that cause lots of disk activity and serialization of all
Foreign calls that means that additional threads must wait for data
retrieval to complete.
Old and new Analysis window: outputting millions of rows to listview is
much faster now
All list views - Ctrl+A (Select All) made much faster
CHANGES FOR EARLIER VERSIONS ARE DOCUMENTED IN RELEASE NOTES DOCUMENT THAT YOU
CAN FIND IN AMIBROKER INSTALLATION FOLDER.
Detailed Change Log
37
Tutorial
This chapter will guide you through the most important parts of AmiBroker.
Basic tasks:
• Basic operations
User interface topics:
•
•
•
•
•
•
•
•
•
•
Beginners’ charting guide
How to use drag-and-drop charting interface
Chart themes
User interface customization
Working with chart sheets and window layouts
Working with layers
Using Web Research
Using Account Manager
Using Fundamental data
Using New Analysis window
Updating quotes:
•
•
•
•
•
•
•
How to get quotes from various exchanges
Setting up eSignal RT feed (RT version only)
Setting up myTrack RT feed (RT version only)
Setting up Quote Tracker as a RT data source
Setting up IQFeed RT feed (RT version only)
How to use AmiBroker in Real Time mode (RT version only)
Using AmiBroker with other external data source (Quotes Plus, TC2000 /
TCNet, Metastock, FastTrack)
• Automatic update of EOD quotes for US & Canada markets from Yahoo
• Using manual mode of AmiQuote downloader (Yahoo, MSN Money Central,
Quote.com Livecharts)
• Using Metastock importer
Database management:
• Understanding database concepts
• Understanding categories
• Working with watch lists
AmiBroker Formula Language topics:
•
•
•
•
•
•
•
Understanding how AFL language works
Creating your own indicators
Using graph styles and colors in the indicators
How to create your own exploration
How to write your own chart commentary
Using studies in your AFL formulas
Backtesting your trading ideas
Tutorial
38
AmiBroker 5.80 User’s Guide
•
•
•
•
•
•
•
•
•
•
•
•
Tutorial
Portfolio backtesting
Reading backtest report
How to optimize a trading system (advanced)
Walk-Forward testing (advanced)
Backtesting futures (advanced)
Pyramiding/scaling and multiple currencies in the portfolio backtester
(advanced)
Using formula-based alerts (advanced)
Using interpretation window (advanced)
Multiple time frame support (advanced)
Efficient use of multithreading (advanced)
Ranking functionality (advanced)
How to use code snippets
More information:
• Video Tutorials On-Line
Tutorial
39
AmiBroker 5.80 User’s Guide
Tutorial
Basic operations
Adding a new symbol
In order to add a new symbol into database you can use Symbol->New menu item or
Add symbol toolbar button.
After selecting this function you will be prompted for new ticker symbol. The
maximum ticker symbol length is 48 characters. For proper import functioning you
should enter the symbol with CAPITALS.
Removing a symbol
In order to remove existing symbol from the database you can use Symbol->Remove
menu item or Remove symbol toolbar button. After choosing this function you will
be asked for confirmation of symbol removing. Note well that this operation can
not be undone !!!
Removing multiple symbols at once is possible using Assignment organizer.
Splitting a stock
To perform stock split use Symbol->Split menu item or Split toolbar button.
AmiBroker provides easy way of handling stock splits. Program will try to guess
split date and ratio by analyzing quotations. If there is just a single quotation
after split this should work, if not you will be asked for split date and ratio.
Note well that this operation can not be undone!!!
From version 2.0 and up the split function offers more functionality: you can use
old-style ratio or you can specify a split using following expression:
x->y
which means that x shares before split become y after it. For example 2->3 means
that 2 shares become 3 after the split. So ordinary split into five pieces will
be 1->5.
As you have probably guessed it is possible now to perform reverse-split, for
example 2->1, which means that 2 shares are joined together into 1 share.
Deleting quotation
To delete a quotation simply select the quote you want to delete by clicking on
the chart (a vertical line will appear showing selected date and quote). Then
choose Edit->Delete quotation menu option.
To delete quotations of all stocks from given day you should use Edit->Delete
session.
Basic operations
40
AmiBroker 5.80 User’s Guide
Tutorial
You can also use Quote Editor to delete quotes.
Adding/removing symbol from favourites
To add the symbol to the favourites you should check favourite box in the
Information window. To remove it from favourites simply uncheck that box.
Alternatively you can click on the tree with the right mouse button and select
"Add to favourites" and "Remove from favourites" options from the context menu.
Merging quotations of two symbols
It happens sometimes that the ticker for the symbol is changed then you may get
two tickers in your database - one holding historical quotes and the second one
holding newest quotes (after name change). In order to put all quotes to the
single ticker you should use Symbol->Merge feature. You should just select the
new ticker (after name change) and choose Symbol->Merge. Then from the combo you
should choose original ticker ("merge with") and optionally check the following
fields:
• overwrite duplicate quotes - checking this option will overwrite the quotes
already existing in "new" ticker with those present in "old" ticker (this
should really not be the case, but may happen).
• delete "merge with" afterwards - checking this option will delete the "old"
ticker after merging
• assign alias name - checking this option will copy the "old" ticker to the
alias field of the "new" ticker
Adding/removing symbol from favourites
41
AmiBroker 5.80 User’s Guide
Tutorial
Beginners’ charting guide
Introduction
AmiBroker charting engine allows object-oriented manipulation of all drawings.
Now you can simply move, resize, cut, copy, paste and delete all drawing objects
with ease. This chapter will guide you though most important aspects of using
charting tools.
Let’s now take a look at the user interface:
As you can see the in the center we have chart area in which price chart with
moving average and Bollinger bands is plotted (you can control the apperance of
built-in charts from Tools->Preferences window).
In the bottom of the chart you can see date axis (marked with red color), and
below scroll bar and chart sheets tab control. Scroll bar can be used to display
past quotes, while sheet tab allows to view different chart pages/sheets (click
here to learn more about chart sheets).
Beginners’ charting guide
42
AmiBroker 5.80 User’s Guide
Tutorial
To the right you can see Y-axis area (marked with blue color) that shows Y-scale
and value labels. Value labels are color fields that display precisely the "last
value" of plots. "Last value" is the value of the indicator (or price) for the
last currently displayed (rightmost) bar. Y-axis area is used also to move/size
chart vertically.
Next to the right is a drawing objects toolbar that allows you to choose from
available drawing types (note that only most popular tools are shown here,
complete set is available from Insert menu). A special tool called "Select" (red
arrow) is used to select/move/resize already drawn objects and to select quotes
from the chart.
In the upper part you can see formatting toolbar that allows you to quickly
modify color, style (thick/dotted) and mode (snap to price) of currently selected
drawing object.
In the picture you can also see the trend line drawn with sizing handles marked.
These handles are used to drag/size the object as will be explained below.
Basic operations
Scrolling
To scroll the chart forward/backward just drag scroll bar thumb or use < and >
arrows on the left and right sides of the scroll bar. Note that using < > scroll
bar arrows allows you to move chart by one bar. To scroll the chart you can also
use the mouse equipped with a wheel. Just roll the wheel up and down to scroll
back and forward.
Zooming
To zoom the chart (increase or decrease number of data points (bars) displayed)
you can use either View->Zoom menu, zoom toolbar or mouse wheel.
You can also zoom by dragging the left or right edge of scroll bar. There are
following options available: zoom-in - decreases the number of data points
displayed, zoom-out - increases the number of data points displayed, zoom-all displays all available bars, zoom-normal resets number of bars displayed to the
value defined in Tools->Preferences->Charting. Zoom-in and zoom-out options are
accessible directly from the View toolbar. (see picture below). To zoom using
mouse wheel just press and hold down CTRL key and roll the wheel. You can also
zoom to any from-to range selected on the chart (see ’Marking range’ later in
this tutorial)
Shrinking, expanding and moving Y-axis scale
To move Y-axis scale hover the mouse to Y-axis area (marked with blue color in
the picture above) and you will see that cursor changes to up/down arrow. Now you
click and drag up/down Y axis and release button when the axis is in the correct
position.
To shrink/expand Y-axis scale: press down SHIFT key and click in the Y-axis area,
now shrink/expand Y axis scale by moving your mouse up and down. Release the
Beginners’ charting guide
43
AmiBroker 5.80 User’s Guide
Tutorial
button to finish.
To reset Y-axis scale and position simply double click in the Y-axis area.
Changing bar interval (periodicity)
You can easily switch between daily/weekly/monthly and intraday intervals by
choosing it from View menu and pressing the toolbar button (see below).
The toolbar uses following notation for intervals - i -intraday, h hourly, d - daily, w - weekly, m - monthly. The i represents "base"
intraday interval as defined in File->Database Settings. Remaining
intraday intervals are available from View->Intraday menu.
The interval setting affects active window only, so each window can
have different interval.
Please note that intraday intervals are disabled if your database is
in end-of-day mode. Intraday modes are available only for databases
that have "Base time interval" in File->Database Settings set to
anything less than end-of-day. If you for example set "Base time
interval" in File->Database Settings to 5-minute, all chart
periodicities from 5-minutes up will be enabled.
The following intervals are built-in:
•
•
•
•
•
•
•
•
•
•
daily
weekly
monthly
hourly (intraday)
15-minute (intraday)
5-minute (intraday)
1-minute (intraday)
15-second (intraday RT only)
5-second (intraday RT only)
tick (intraday RT only)
In addition to that you can define 5 custom n-minute bar intervals and 5 custom
n-tick intervals in Tools->Preferences->Intraday. Custom intervals are available
from View->Intraday menu only.
Selecting a quote
You can very easily see the past quote and values of indicators by using "select"
mode. To select past quote first switch to "Select" mode (red arrow in the
toolbar) then click in the chart area (but not on the drawing object). A vertical
line will show up marking the quote under the cursor. The chart title will
display this bar quote. Indicator panes will show indicator value for given bar.
Once quote is selected you can move to previous/next quote using keyboard left
and right arrow (cursor) <- and -> keys.
Beginners’ charting guide
44
AmiBroker 5.80 User’s Guide
Tutorial
To switch off quote selection either click again on the line or click in the date
axis area (marked with red color in the picture above) or click in the right
margin (blank quotes) area. When selection is off chart title displays the values
for last visible bar.
Marking range
To show range marker just double click the chart at the beginning of the range
and double click again at the end of the range. You can also use F12 key in
conjunction with "select" mode (described above). Just select quote and press F12
for begin and SHIFT+F12 for the range end. You can switch off the range marker by
pressing CTRL+F12 key or double clicking in the same place twice.
Range markers can be used to select zoom-in range (View->Zoom->Range) and to
perform calculations on selected values via BeginValue and EndValue AFL
functions.
Adding / closing chart panes
Each window can consist of several panes displaying various charts / indicators.
To display a new indicator in a separate chart pane just find the indicator in the Charts list
(use Window -> Charts menu) and double-click on the indicator name.
For more information see
Drag&drop charting tutorial.
To close any chart pane: click on the pane, then use either View->Pane->Close
from main menu or click on the pane with right mouse button and choose Close from
context menu.
Linking and locking chart
Multiple chart windows (that were open usign File->New->Default Chart or
File->New->Blank chart) can be interval-linked, symbol-linked using appropriate
small "S" and "I" buttons that appear on the left side of the scroll bar. When
you click on button the menu showing colors will pop up, select one color from 2
or more charts and symbols linked using same color will be linked using symbol
and/or interval. Linking means that change of the symbol and/or interval in one
of the linked windows automatically changes symbol and/or interval in all linked
windows using same link color.
You can also prevent symbol from being changed for given chart. It can be done by
turning on little pad lock button ("Symbol Lock") on the right side of the scroll
bar. When chart is symbol-locked, it will not allow to change the symbol selected
unless the lock is released (by pressing pad lock button again).
Using drawing tools
AmiBroker features extensive set of drawing tools:
Beginners’ charting guide
45
AmiBroker 5.80 User’s Guide
Tutorial
The following tools are available:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
trend line
ray (new in 4.20)
extended line (new in 4.20)
vertical line
horizontal line
parallel lines (new in 4.20)
Regression channels: Raff, standard deviation, standard error
(all new in 4.20)
Fibonacci Retracement study (enhanced in 4.20)
Fibonacci Time zones study
Fibonacci Fan
Fibonacci arc
Gann Square (new in 4.20)
Gann Fan (new in 4.20)
Ellipse tool
Arc tool
Rectangle
text box tool
They are available from Insert menu and Draw toolbar. Each drawing
object can be moved, resized, copied, deleted and modified after it
is drawn.
To draw an object on the chart switch on appropriate tool button (see picture
below) and start drawing on the chart by pointing the mouse and pressing left
mouse button where you want to start the drawing. Then move the mouse. Study
tracking line will appear. Release left mouse button when you want to finish
drawing. You can also cancel study drawing by pressing ESC (escape) key.
If you hover your mouse over the object you will see that cursor shape changes in
the proximity of the object. This means that
If cursor is near either end of the object it will change its shape to sizing
pointer:
If the cursor is near remaining parts of the object it will change its shape to
moving pointer:
Once object is drawn it can be selected, moved, resized, deleted, copied.
Beginners’ charting guide
46
AmiBroker 5.80 User’s Guide
Tutorial
To select the object simply move the mouse
over the object so "moving pointer" appears
and click once - the object will be marked so
the sizing handles (see first picture) will
appear.
To de-select click in the blank chart space.
To size the object click on the sizing handle
and drag to the desired location as shown in
the picture.
To move the object click on any other part of
the object and move to the desired location.
To delete object - select it first and press DEL (DELETE) key on the keyboard or
use Edit->Delete menu or use Delete toolbar button.
To copy the object to the clipboard - select it first and press Ctrl+C or use
Edit->Copy menu or use Copy toolbar button.
To cut the object - select it first and press Ctrl+X or use Edit->Cut menu or use
Cut toolbar button.
To paste the object from the clipboard press Ctrl+V or use Edit->Paste or use
Paste toolbar button. Pasted object will drawn in the exactly same location as
copied one and will be selected automatically so you can move it to a new
location.
To apply color or style to the object select it and use Format menu or Format
tool bar buttons to change color, thick, dotted and snap to price styles. Note
that you can also select color and style of the object before drawing new object:
simply deselect previous object (if any), change color / style selections and
draw new object.
To modify properties of the object - either double click it or use
Edit->Properties menu or Alt+ENTER key
To delete all objects use Edit->Delete All menu
Further information
To learn more about drawing tools please read Drawing tools reference chapter.
Beginners’ charting guide
47
AmiBroker 5.80 User’s Guide
Tutorial
How to use drag-and-drop charting interface
Introduction
AmiBroker allows you to easily create and modify your indicators with few moves of a mouse. From
now on you can build sophisticated indicators without any programming knowledge at all. The
available (ready-to-use) indicators are listed in Charts tab of the Workspace window.
There is a video tutorial at: http://www.amibroker.net/video/dragdrop1.html that
shows basic usage of new drag and drop functionality.
How to insert a new indicator.
To display a new indicator in a separate chart pane just find the indicator in the Charts list
(use Window -> Charts menu) and double-click on the indicator name.
Alternatively you can choose Insert from the context menu. As a result new indicator pane will be
created and Parameters dialog will be displayed. Here you can change the properties of the
indicator (like color or periods). To accept the settings press OK button. (you will find the
detailed description of parameters window below).
Example:
To insert RSI pane - find RSI indicator in the list, double-click on the name, select the number
of periods and color, then press OK.
How to overlay one indicator on another indicator.
To overlay one indicator on another one, press LEFT mouse button on the indicator name, drag
(with mouse button held) the chosen indicator into the destination pane and release the button.
Example:
To insert another RSI (based different periods number) into the same pane - drag RSI into the
previously created RSI pane, change the number of periods in the Parameters window and press OK
Alternatively you can choose Overlay option from context menu.
How to use drag-and-drop charting interface
48
AmiBroker 5.80 User’s Guide
Tutorial
How to delete the indicator.
To remove the indicator, press Close button from the menu on the top right-hand side of the
indicator pane (the menu will be displayed if you place the mouse cursor in the nearby). This
menu allows you also to move the indicator pane up/down or maximize the pane.
You can also use Close command from context menu that shows up when you click on
the chart pane with right mouse button.
How to remove the indicator plot from the pane.
To remove one of the indicators displayed in the indicator pane - click with RIGHT mouse button
on the chart title (near the top of chart pane) and select the indicator that you want to remove.
How to use drag-and-drop charting interface
49
AmiBroker 5.80 User’s Guide
Tutorial
You can also remove the indicator plot using Delete Indicator option from chart
context menu.
How to change parameters/colors/styles of indicators.
The Parameters window allows you to change parameters, colors and styles of your indicators.
Parameters window is displayed when you insert a new indicator. You can also click RIGHT mouse on
the chart pane and choose Parameters from the context menu. Parameters window displays all the
parameters defined in AFL code of certain indicators (also user-defined parameters) so it’s
contents depends on the indicator chosen. However - for most of the indicators you will see:
• Price Field - the data used to calculate the indicator. If the ’Price Field’ contains
’Close’, it means that indicator is calculated out of Close prices. Price Field is not
available for all indicators, because not all indicators allow you to choose the input
(e.g. ADLine).
• Periods - defines the number of periods used to calculate the indicator
• Color - allows you to change the color of the indicator
• Style - allows you to determine the style of the plot (the styles are described in more
detail in Using graph styles and colors tutorial section.
How to overlay indicators with different scales.
To have in one pane two (or more) indicators that use different scaling, drag the second
indicator onto the first one, in Parameters window click on Style field and check StyleOwnScale
setting.
Example:
Drag OBV (On Balance Volume) into RSI pane. Then define style as styleOwnScale. As a result both indicators are visible and properly displayed.
How to create an indicator based on another indicator.
AmiBroker allows you also to easily create indicators based on values of another indicator. All
you need to do is to press LEFT mouse button on the indicator name, drag (with mouse button held)
the chosen indicator into the destination pane and release the button. As a result - the
indicator will be placed in the existing chart pane. In the parameters dialog Price field
parameters indicates what base values are used to calculate the indicator.
Example:
To calculate Simple Moving Average of previously created RSI indicator, drag the MA indicator
into RSI pane. The contents of "Price Field" parameter indicates, that Moving Average is
calculated out of RSI(15) values. (See the below picture).
How to use drag-and-drop charting interface
50
AmiBroker 5.80 User’s Guide
Tutorial
NOTE: The part below contains technical information for advanced users only. Beginners may skip
this part.
Using Param(), ParamColor(), ParamToggle(), ParamStyle() functions
These functions, when used in formula, allow you to change indicators’ settings directly from
Parameters window.
Param( (’’name’’, defvalue, min = 0, max = 100, step = 1, sincr = 0 )
Adds a new user-definable parameter, which will be accessible via Parameters dialog.
•
•
•
•
•
"name" - defines parameter name that will be displayed in the parameters dialog
defvalue - defines default value of the parameter
min, max - define minimum and maximum values of the parameter
step - defines minimum increase of the parameter via slider in the Parameters dialog
sincr - defines the increase of default value when more than one section of the same kind
is inserted (dropped) onto the chart. For example if you insert the default Moving Average
indicator into the same pane twice, the first moving average will be based on 15 periods,
the other one on 25 (defvalue=15 + sincr=10)
ParamColor( ’’name’’, defaultcolor )
Adds a new user-definable color parameter, accessible via Parameters dialog.
• ’’name’’ - defines parameter name that will be displayed in the parameters dialog
• defaultcolor - defines default color value of the parameter
ParamColor function allows you to use colorCycle as a default value. When you use colorCycle
parameter, default color cycles through red, blue, green, turquoise, gold, violet, bright green,
dark yellow, when you insert your indicators into the same pane.
ParamStyle(’’name’’, defaultval = styleLine, mask = maskDefault ) - allows to select the styles
applied to the plot from the Parameters window. Apart from styles available in previous versions
of AmiBroker, there are two new style constants:
• styleHidden - a combination of styleNoDraw | styleNoRescale
• styleDashed - dashed line
The list of available styles displayed in the Parameters window depends on the mask parameter.
How to use drag-and-drop charting interface
51
AmiBroker 5.80 User’s Guide
Tutorial
• maskDefault - show thick, dashed, hidden, own scale styles (this is default mask for
ParamStyle)
• maskAll - show all style flags
• maskPrice - show thick, hidden, own scale, candle, bar
• maskHistogram - show histogram, thick, hidden, own scale, area
ParamField(’’name’’, field = 3 ) - allows to pick the Price field for the indicator (field which
is used to calculate values of the indicator). Function returns the array defined by field
parameter. Default value = 3 returns Close array. The possible values of field parameter are:
• -1 - ParamField returns the values of the indicator that was inserted as a first one into
the pane, or Close if no indicator was present
• 0 - returns Open array
• 1 - returns High array
• 2 - returns Low array
• 3 - returns Close array (default)
• 4 - returns Average array = (H+L+C)/3
• 5 - returns Volume array
• 6 - returns Open Interest array
• 7,8,9,.... - return values of indicators inserted into the pane.
ParamToggle(’’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
_
Example:
The below indicator allows you to check how the parameters work in the custom code. You can
change settings from Parameters dialog.
Buy = Cross(MACD(), Signal() );
Sell = Cross(Signal(), MACD() );
pricefield = ParamField("Price Field", 2);
Color = ParamColor("color",colorRed);
style = ParamStyle("style",styleLine,maskAll);
arrows = ParamToggle("Display arrows", "No|Yes",0);
Plot(pricefield,"My Indicator",Color,style);
if(arrows)
{
PlotShapes(Buy*shapeUpArrow+Sell*shapeDownArrow,IIf(Buy,colorGreen,colorRed) );
}
Special functions: SECTION_BEGIN, _SECTION_END, _SECTION_NAME, _DEFAULT_NAME, _PARAM_VALUES
explained
(for advanced users only)
These are new functions that are used by drag & drop mechanism. The most
important pair is _SECTION_BEGIN("name") and _SECTION_END().
How to use drag-and-drop charting interface
52
AmiBroker 5.80 User’s Guide
Tutorial
When you drop the formula onto chart pane AmiBroker appends the formula you have
dragged at the end of existing chart formula and wraps inserted code with
_SECTION_BEGIN("name") and _SECTION_END() markers:
So, if original formula looks as follows:
P = ParamField("Price field",-1);
Periods = Param("Periods", 15, 2, 200, 1, 10 );
Plot( MA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ),
ParamStyle("Style") );
it will be transformed by AmiBroker to:
_SECTION_BEGIN("MA");
P = ParamField("Price field",-1);
Periods = Param("Periods", 15, 2, 200, 1, 10 );
Plot( MA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ),
ParamStyle("Style") );
_SECTION_END();
_SECTION_BEGIN/_SECTION_END markers allow AmiBroker to identify code parts and
modify them later (for example remove individual sections). In addition to that
sections provide the way to make sure that parameters having the same name in
many code parts do not interfere each other. For example if you drop two moving
averages the resulting code will look as follows:
_SECTION_BEGIN("MA");
P = ParamField("Price field",-1);
Periods = Param("Periods", 15, 2, 200, 1, 10 );
Plot( MA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ),
ParamStyle("Style") );
_SECTION_END();
_SECTION_BEGIN("MA1");
P = ParamField("Price field",-1);
Periods = Param("Periods", 15, 2, 200, 1, 10 );
Plot( MA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ),
ParamStyle("Style") );
_SECTION_END();
Note that code and is parameter names are identical in both parts. Without
sections the parameters with the same name will interfere. But thanks to uniquely
named sections there is no conflict. This is so because AmiBroker identifies the
parameter using section name AND parameter name, so if section names are unique
then parameters can be uniquely identified. When dropping indicator AmiBroker
automatically checks for already existing section names and auto-numbers
similarly named sections to avoid conflicts. Section name also appears in the
Parameter dialog:
How to use drag-and-drop charting interface
53
AmiBroker 5.80 User’s Guide
Tutorial
Last but not least: you should NOT remove _SECTION_BEGIN / _SECTION_END markers
from the formula. If you do, AmiBroker will not be able to recognize sections
inside given formula any more and parameters with the same name will interfere
with each other.
_SECTION_NAME is a function that just gives the name of the function (given in
previous _SECTION_BEGIN call).
_DEFAULT_NAME is a function that returns the default name of plot. The default
name consists of section name and comma separated list of values of numeric
parameters defined in given section. For example in this code:
_SECTION_BEGIN("MA1");
P = ParamField("Price field");
Periods = Param("Periods", 15, 2, 200, 1, 10 );
Plot( MA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ),
ParamStyle("Style") );
_SECTION_END();
_DEFAULT_NAME will evaluate to "MA1(Close,15)" string.
_PARAM_VALUES works the same as _DEFAULT_NAME except that no section name is
included (so only the list of parameter values is returned). So in above example
_PARAM_VALUES will evaluate to "(Close, 15)" string.
Frequently Asked Questions about drag & drop functionality
Q. What is the difference between Insert and Insert Linked option in chart menu?
A. Insert command internally creates a copy of the original formula file and
places such copy into hidden drag-drop folder so original formula will not be
affected by subsequent editing or overlaying other indicators onto it. Double
clicking on formula name in the chart tree is equivalent with choosing Insert
command from the menu. On the other hand Insert Linked command does not create
How to use drag-and-drop charting interface
54
AmiBroker 5.80 User’s Guide
Tutorial
any copy of the formula. Instead it creates new chart pane that directly links to
original formula. This way subsequent editing and/or overlaying other indicators
will modify the original
Q. I can not see buy/sell arrows from my trading system
A. Trade arrows can be displayed on any chart pane (not only one built-in price
chart). However, by default, the arrow display is turned OFF. To turn it ON you
have to open Parameter dialog, switch to "Axes and grid" and switch "Show trading
arrows" option to "Yes".
Q. The read me says: "Automatic Analysis formula window is now drag&drop target
too (you can drag formulas and AFL files onto it)". What does it mean?
A. It means that you can drag the formula from either Chart tree or .AFL file
from Windows Explorer and drop it onto Automatic Analysis (AA) formula window and
it will load the formula into AA window. This is an alternative to loading
formula via "Load" button in AA window.
Q. Can I drop a shortcut onto the formula window ?
A: No you can’t. You can only drag & drop files with .AFL extension (shortcuts in
Windows have .lnk extension).
Q. Can I add my own formulas to the Chart tree ?
A. Yes you can. Simply save your .AFL formula into Formulas subfolder of
AmiBroker directory and it will appear under "Charts" tree (View->Refresh All may
be needed to re-read the directory if you are using external editor)
Q. I have added new file to the Formulas folder, but it does not show up in the
Charts tree unless I restart AmiBroker? Is there a way to refresh Chart tree ?
A. You can refresh Chart tree by choosing View->Refresh All menu.
How to use drag-and-drop charting interface
55
AmiBroker 5.80 User’s Guide
Tutorial
Q. If I modify the formula that ships with AmiBroker will it be overwritten by
next upgrade?
A. Yes it will be overwritten. If you wish to make any modifications to the
formulas provided with AmiBroker please save your modified versions under new
name or (better) in your own custom subfolder.
Q. I can see Reset All button in Parameters dialog but it sets all parameters to
default values. Is there a way to reset SINGLE parameter ?
A. No, there is no such option yet, but it will be added in upcoming betas.
Q. I dragged RSI to the price chart pane and got a straight red line at the
bottom of the pane. What is wrong?
A. When you drop two indicators / plots that have drastically different values
you have to use style OwnScale for one of it. You can turn on OwnScale style
using Parameter dialog. This ensures that scales used for each are independent
and you can see them properly. Otherwise they use one common scale that fits both
value ranges that results in flattened plots.
Q. The light grey color of the new AFL special functions_SECTION_BEGIN etc makes
them invisible in my bluegrey background IB color. How could I change the special
functions color ?
A. Right now, you can’t. But there will be a setting for coloring special
functions in the next version.
Q. When I drop the indicator the Parameter dialog does not show all parameters.
Is this correct ?
A. Yes it works that way. The idea behind it is simple. When you drop new
indicator AmiBroker displays a dialog with parameters ONLY for currently dropped
indicator. This is to make sure that newly inserted indicator parameters are
clearly visible (on top) and new user is not overwhelmed by tens of other
parameters referring to previously dropped indicators. On the other hand when you
choose "Parameters" item from context menu then ALL parameters will show up allowing you to modify them all any time later.
How to use drag-and-drop charting interface
56
AmiBroker 5.80 User’s Guide
Tutorial
Chart themes
AmiBroker 5.52 introduces 6 pre-defined chart themes switchable in
Tools->Preferences, "Axes & Grid" tab:
1. Basic Theme
Chart themes
57
AmiBroker 5.80 User’s Guide
Tutorial
2. Nature Simple Theme
Chart themes
58
AmiBroker 5.80 User’s Guide
Tutorial
3. Nature Gradient Theme
Chart themes
59
AmiBroker 5.80 User’s Guide
Tutorial
4. Gray Theme
Chart themes
60
AmiBroker 5.80 User’s Guide
Tutorial
5. Dark Gray Theme
Chart themes
61
AmiBroker 5.80 User’s Guide
Tutorial
6. Black Theme
Chart themes
62
AmiBroker 5.80 User’s Guide
Chart themes
Tutorial
63
AmiBroker 5.80 User’s Guide
Tutorial
User interface customization
A newly introduced customizable user-interface has several nice features that
allow complete control over look and feel of AmiBroker user interface.
Advanced nested docking / tear-off tabs
To dock a pane into any side of the application or as a tab simply click on
docking window caption bar and drag it. If you do this, docking stickers will
show up to make it easy to choose destination place as shown below
User interface customization
64
AmiBroker 5.80 User’s Guide
Tutorial
You can also click on docking pane tab and drag it (tear off) and dock as a
separate window. This way you can arrange all docking windows either as separate
windows or as tabs or as a mixture of these two approaches. You can also make
window / tab floating if you drag it while holding down CTRL key.
Sliding Auto-hide panes
Another very useful feature that allows to conserve precious real estate on your
monitor is auto-hiding of panes. To control (switch on/off) this feature there is
a pinup button in the upper right corner of each docking window. If you unpin it
- the pane will automatically hide when it loses focus.
User interface customization
65
AmiBroker 5.80 User’s Guide
User interface customization
Tutorial
66
AmiBroker 5.80 User’s Guide
Tutorial
Advanced customizable toolbars, menus and keyboard shortcuts
New user interface allows full user control over appearance, layout and position
of all toolbars, buttons and menus. It allows you to add your own buttons,
remove/re-arrange existing ones. Also you define or re-define new/existing
keyboard shortcuts. All these customization features are available from
Tools->Customize menu or from Customize chevron menu.
Chevron menu is available from little arrow button placed at the end of toolbar
strip. It allows to access auto-hidden elements of the toolbar as well as
customization features.
User interface customization
67
AmiBroker 5.80 User’s Guide
Tutorial
Add or Remove buttons submenu allows to quickly show / hide toolbar buttons
according to your preference. In customization mode (when you enter it using
Tools->Customize you can also move buttons around to change the order in which
they appear, and you can also resize edit fields and combo fields (such as ticker
selection field) by selecting them first and resizing the border that will show
after making selection.
User interface customization
68
AmiBroker 5.80 User’s Guide
Tutorial
You can even add and design your own buttons using built-in image editor:
Themed appearance
AmiBroker allows also to pick your preferred user-interface "appearance" or
"theme" to suit your personal taste.
User interface customization
69
AmiBroker 5.80 User’s Guide
Tutorial
MDI (multiple document interface) tabs
AmiBroker is multiple document interface (MDI) application. In short it means
that it allows you to open and work with multiple windows at the same time. To
learn more about what MDI is you may check this article:
http://en.wikipedia.org/wiki/Multiple_document_interface
Now MDI tabs (shown in the picture above ) are just an additional way to switch
multiple open windows (in addition to Window menu where the list of open document
windows is also available).
User interface customization
70
AmiBroker 5.80 User’s Guide
Tutorial
It is important to understand that MDI tabs are not "user definable" in the sense
that you can not define their names freely, unlike chart sheets (which are
definable). Their names are automatically derived from document/window name. For
chart windows the name is always in the format of: Symbol - FullName, web browser
windows use HTML page title (as defined by HTML document), account manager
windows use actual account file name (that you can choose when you save them).
MDI tabs are basically document window switcher (like Windows TASK BAR in the
bottom) and they are automatically managed by AmiBroker whenever you open new or
close window.
And it works exactly using the same idea as Windows task bar. Let us look at this
analogy closer:
When you use Windows Task Bar:
- you open the application - a new button in the task bar appears
- and you can switch between open applications using task bar buttons.
- you can not rename the button because it represents application name.
- and you need to be careful with opening too many applications because all open
applications consume system resources
Now using AmiBroker MDI tabs:
- you open the document (window) -> a new button (tab) appears
- you can switch between open windows using buttons (tabs)
- you can not rename the button because it represents document/window name
- and you need to be careful with opening too many documents/windows because all
open documents consume system resources
You can turn off MDI tabs by unchecking "Show MDI tabs" box in the
Tools->Customize, Appearance page, as shown below:
Historical note: In pre-4.90 versions, to switch the documents you would need to
User interface customization
71
AmiBroker 5.80 User’s Guide
Tutorial
use Window menu. Now in addition to that you can use tabs. But this is just
convenience feature, more info at:
http://en.wikipedia.org/wiki/Tabbed_Document_Interface (Note that wikipedia links
describing TDI / MDI are somewhat outdated and AmiBroker actually combines
advantages of BOTH TDI and MDI approaches (for example you can tile windows in
AB’s TDI)
For more information see Houston conference presentation:
http://www.amibroker.com/docs/Houston1.pdf (PDF format),
http://www.amibroker.com/docs/Houston1.html (Flash format).
User interface customization
72
AmiBroker 5.80 User’s Guide
Tutorial
Working with chart sheets and window layouts
AmiBroker manages multiple chart sheets and multi-window layouts with ability to
quickly load/save thems. This feature enables you to quickly switch between
different indicator sets saving your time dramatically.
Chart sheets and templates
A chart sheet is a set of chart panes (with indicators) displayed within single
frame.
You can switch between different sheets by clicking on the tabs located in the
bottom of AmiBroker window as show in the following picture:
You can change the name of the tab by clicking on it with RIGHT mouse button, so
the following window appears:
You can change all four tab names (one by one) so they are more descriptive (and
they relate to the contents of the sheet).
You can scroll tabs using arrow buttons and you can re-arrange them by dragging
(click on tab, hold down left mouse button and drag to desired position - an
arrow will show target position).
You can also access any sheet quickly by clicking with RIGHT mouse button over
arrows to pop-up the menu that lists all tabs and allows immediate selection
(without scrolling)
Working with chart sheets and window layouts
73
AmiBroker 5.80 User’s Guide
Tutorial
The next step is to set up your sheets according to your personal preference.
Just add/remove chart panes to/from each sheet. This way you can have upto 60
different indicator sets that you can recall very quickly by switching to
appropriate tab. The actual number of sheets is definable in
Tools->Preferences->Charting "Number of chart sheets"
The complete set of chart sheets is called a "template" and you can make this
setup permantent just right-click on the chart and select the following menu item
(Template->Save, Template->Save as default):
The default template is used if you create a new window (Window->New)
You can also load once saved template by choosing Template->Load from chart’s
right mouse button menu.
In addition to old local template format a new one is added with .chart extension
that keeps not only window sizes and formula references (paths) but also formulas
themselves, so all you need to do is to save your chart into one file (Chart
Template, Complete *.chart) and copy that file onto different computer and chart
will be recreated with all formulas linked to it.
To Save chart into new format do the following:
Working with chart sheets and window layouts
74
AmiBroker 5.80 User’s Guide
Tutorial
1. Click with RIGHT MOUSE button over the chart and select Template->Save...
2. In the file dialog, "Files of type" combo select "Chart Template, Complete
(*.chart)"
3. Type the file name and click Save.
To load previously saved complete chart do the following:
1. Click with RIGHT MOUSE button over the chart and select Template->Load...
2. In the file dialog, select previously saved *.chart file and press "Open"
Note: The procedure AmiBroker does internally is as follows: When you save the
chart into new format it saves XML file with:
a) names of all sheets, panes, their sizes, locations and other settings
b) paths to all formulas used by all panes
c) the text of formulas themselves
When you load the chart in new format AmiBroker:
a) sets up the sheets/panes according to information stored in the file
b) for each formula stored in the file it checks if the same formula exists
already on target computer:
- if it does not exist - it will create one
- if it exists and the contents is identical to the formula stored in .chart file
it will do nothing
- if it exists and the contents is different then it will create NEW formula file
with _imported.afl suffix (so old file is not touched) and will reference the
pane to the _imported.afl formula instead.
IMPORTANT NOTE: if you use any #include files AmiBroker will store the contents
of include files as well inside chart file and will attempt to recreate them on
target machine. Please note that in case of includes it will check if it exists
and if it is different. If both conditions are met (different file exists
already) it will ask to replace or not. If you choose to replace - it will
replace and make backup of existing one with .bak extension. If you are using any
files in "standard include files" and include them using <> braces, AmiBroker
will restore files in target machine standard include folder as well (even if the
standard include folder path is different on the source machine).
A new .chart format is intended to be used to port charts between different
computers. For storing layouts/templates on local computer you should rather use
old formats as they consume much less space (they store only references,not the
formulas themselves). One may however use new format for archiving purposes as it
keeps formulas and all references in one file that is very convenient for
backups.
Symbol and Interval Linking
Working with chart sheets and window layouts
75
AmiBroker 5.80 User’s Guide
Tutorial
Now it is possible to link chart windows either by symbol and/or by time
interval. To link chart windows use linking buttons located in the bottom of the
chart window as shown in the picture below:
Grey "S" and "I" buttons mean no link. Any other color (red, green, magenta,
yellow, pink, white, brown, dark green, blue) means that given chart belong to
given color-coded linked group. All windows with same color link will switch
symbol and/or interval simultaneously.
Floating windows
If you are using multiple monitors, you can find it useful to display AmiBroker
charts on multiple windows. To make it easy, AmiBroker 5.10 introduces "floating"
chart windows. Normally all chart windows live inside main AmiBroker application
window. If you make chart window floating, you are essentially detaching the
chart window from parent AmiBroker frame, so you can move it outside, for example
to the other monitor.
You can switch between normal and floating state using Window menu as shown
below:
Working with chart sheets and window layouts
76
AmiBroker 5.80 User’s Guide
Tutorial
The following video tutorial shows how to use floating windows and symbol linking
in practice:
http://www.amibroker.com/video/FloatAndLink.html
Window layouts
A window layout is a complete set of multiple windows open each with different
symbol, different display interval, different size, different set of chart
sheets.
The picture below shows 4-window layout each with different set of indicator
panes. To the left you can see "Layouts" pane in the Workspace window showing the
list of stored local and global layouts.
Working with chart sheets and window layouts
77
AmiBroker 5.80 User’s Guide
Tutorial
Using AmiBroker 4.20 you can now have unlimited number of custom, multiple-window
templates that can be switched between with just double click on layout name in
the "Layouts" tab of the Workspace window.
You can open, save, delete layout by clicking on the Layout tree with right mouse
button and choosing appropriate function. "Save As" option saves current layout
under new name.
Local layouts are per-database while Global layouts are visible from all
databases.
Information saved in layouts include: window sizes and postions,
maximized/minimized state chart panes available on each sheet (independent for
each window), selected bar interval, selected symbol, selected chart sheet
Most recently used layout can be saved on exit and database switch automatically
(see: Tools->Preferences->Miscellaneous "Save on exit: Layouts")
Note: since version 4.90 multiple windows can be switched not only using
old-style Window menu but also using new MDI tabs. More on MDI tabs can be found
in the "User-interface customization" chapter.
Working with chart sheets and window layouts
78
AmiBroker 5.80 User’s Guide
Tutorial
Using layers
What layers are
Layers are like pieces of transparent plastic. You can put drawings on them.
visible or invisible. This allows to show/hide
the drawings placed on other layers.
Layers can be made
drawings placed on given layer without affecting
How to work with layers.
First of all make sure that Workspace window is visible (Window->Layers)
Then switch to "Layers" tab.
Here you can see the list of pre-defined layers.
The checkboxes on the left side of each layer control layer visibility. If checkbox is marked
than given layer is visible, if it is unmarked - the layer is invisible. Initially first five
layers will be "locked" to intervals.
These built-in layers are:
Default layer - always visible
Intraday layer - visible only when viewing intraday charts
Daily layer - visible only when viewing daily charts
Weekly layer - visible only when viewing weekly charts
Monthly layer - visible only when viewing monthly charts
A locked layer changes its visibility automatically when interval changes and you can not change
its visibility by clicking on the left-side checkbox.
The remaining layers are not locked and they can be shown/hidden freely by marking the checkbox.
To draw a study in a given layer simply
a) SELECT the layer first (click on name to highlight it)
b) DRAW the study as usual
As long you select the other layer all drawings will be placed on selected layer. After drawing a
study you can assign it to any
other layer via object properties box.
Context menu
If you click on layer name with right mouse button you will see the context menu containing the
following options:
Add layer
Remove layer
Show all layers
Hide all layers
Toggle
Unlock built-in layers
Lock built-in layers
Properties.
Add/Remove layer are self-explanatory. Please note that you can not remove first 5 (built-in)
layers
Show all/Hide all - shows and hides all NOT LOCKED layers
Toggle - toggles visibility of all NOT LOCKED layers
Using layers
79
AmiBroker 5.80 User’s Guide
Tutorial
Unlock/Lock built-in layers - allows you to unlock/lock 5 first (built-in) layers. Once layer is
unlocked its visibility does not change automatically when interval changes and you can show/hide
it manually.
Properties - this launches properties box that allows you to rename layer and
decide if given
layer should or should not be locked to interval displayed.
If you mark "Lock visibility to interval" box the layer will
show/hide automatically depending on
what interval is
currently displayed. You can define visibility for each layer using "Interval" combo and
"Show/hide automatically" buttons. Note that there is a *separate* visibility setting for EACH
interval. The layer properties box ALWAYS shows "monthly" interval at start but this is just a
startup condition you just switch to particular interval
and modify visibility.
To setup locked layer completely you have to set visibility for every
layer listed in the "Interval" combo-box. Simply select the interval and choose if layer should
be shown or hidden for this interval, select next interval and again choose show or hide, select
next and so on...until you define visibility for all intervals.
Using layers
80
AmiBroker 5.80 User’s Guide
Tutorial
Using Web Research window
Web Research window allows you to view on-line news, research, profiles,
statistics and all kind of information related to currently selected symbol
available over the Internet (World Wide Web). Using Web Research instead of plain
web browser has speed advantage as you don’t need to type complicated/long
addresses (URLs) each time you need to get desired information.
Web Research window introduced in version 4.90, replaces and enhances previously
available Profile window. Now it allows unlimited number of user-definable web
research (profile) pages, browsing to any web page (just type URL), tab-browsing,
opening multiple pages at once, selective auto-synchronization.
Web-Reasarch uses Internet Explorer engine so you can be sure that pages are
rendered with the same quality you would get from stand-alone browser.
OPEN NEW WEB RESEARCH WINDOW
Use File->New->Web Research menu to create new web research window
PICKING PRE-DEFINED WEB RESEARCH PAGE:
To display any pre-defined web research page, simply click on the drop down arrow
in the Address combo-box and pick one item from the list. Once you do so, the web
page relevant to currently selected symbol will be automatically displayed.
Using Web Research window
81
AmiBroker 5.80 User’s Guide
Tutorial
Now you can specify if and when displayed page should change automatically if you
select different symbol.
The Sync button allows to decide when page should be automatically synchronized
with currently selected symbol.
• Don’t sync - means that page should not be synchronized with currently
selected symbol at all
• Sync active - means that page should be synchronized ONLY when it is
currently active or becomes active (by user clicking on given tab) - this
is recommended setting for web-research profiles since it conserves
bandwidth and resources (not active pages are not synchronized and do not
consume any bandwidth)
• Sync always - means that page is synchronized with currently selected
symbol always, no matter if it is active or not.
NAVIGATION
Web Research window operates in a way very similar to stand-alone browser. To
display any web page just type the URL address to "Address" field and press ENTER
(RETURN) key. To navigate back and forward in the history use <- and -> buttons.
Using Web Research window
82
AmiBroker 5.80 User’s Guide
Tutorial
To close currently displayed page use regular window close X button as shown in
the picture above
DEFINING YOUR OWN WEB RESEARCH PLACES
In addition to web-research pre-defined pages you can define any number of your
own places. To do so use Tools->Customize menu, Web Pages tab.
To add new place press New button, then type the URL template in the URL field
and web page description in the Description field.
The URL template is the web address in that has parts that depend on selected
symbol. The URL template is parsed by AmiBroker to make actual URL to the web
page. For example to see Yahoo’s profiles page you can use following URL
template:
http://biz.yahoo.com/p/{t0}/{t}.html.
Using Web Research window
83
AmiBroker 5.80 User’s Guide
Tutorial
Symbols enclosed in brackets {} define fields which are evaluated in execution
time. {t0} symbol is evaluated to the first character of the ticker name and {t}
is evaluated to the whole ticker name. So if AAPL is selected AmiBroker will
generate following URL from above template:
http://biz.yahoo.com/p/a/aapl.html
Then AmiBroker uses built-in web browser (Web Research window) to display the
contents of the page.
Special fields encoding scheme
As shown in above example template URL can contain special fields which are
substituted at run time by values corresponding to the currently selected symbol.
The format of the special field is {x} where x is describes field type. Currently
there are three allowable field types: ticker symbol in original case {t}, ticker
symbol in lowercase {s}, ticker symbol in UPPERCASE {S}, alias {a}, web id {i}.
You can specify those fields anywhere within the URL and AmiBroker will replace
them with appropriate values entered in the Information window. You can also
reference to single characters of ticker, alias or web id. This is useful when
given web site uses first characters of, for example, ticker to group the html
files (Yahoo Finance site does that), so you have files for tickers beginning
with ’a’ stored in subdirectory ’a’. To reference to single character of the
field use second format style {xn} where x is field type described above and n is
zero-based index of the character. So {a0} will evaluate to the first character
of the alias string. To get first two characters of a ticker write simply
{t0}{t1}. Note about web id field: this new field in Information window was added
to handle situations when web sites do not use ticker names for storing profile
files. I found some sites that use their own numbering system so they assign
unique number to each symbol. AmiBroker allows you to use this nonstandard coding
for viewing profiles. All you have to do is to enter correct IDs in Web ID field
and use appropriate template URL with {i} keyword.
Pages stored locally
You may want to have all pages stored on your local hard disk. This has an
advantage that profiles are accessible instantly but they can take significant
amount of storage space and you will need to update them from time to time. To
access locally stored files use the following template URL (example, C: denotes
drive): file://C:\the_folder_with_profile_files\{t}.html. You are not limited to
HTML files, you can use simple TXT files instead. Then create (or download) the
.html (or txt) files for each symbol in the portfolio. These files should obey
the following naming convention: <ticker>.html. So for example for APPLE (ticker
AAPL) the profile should have the name AAPL.html (or AAPL.txt)
Web-based profiles
If you want to display the profiles from remote web pages you will need to find
out how they are accessible (the URL to the web page) and how the data for
different symbols are accessible. I will describe the problem on the example of
Sharenet (www.sharenet.co.za) site providing the data for companies listed on
Johannesburg Stock Exchanges. Sharenet provides company information that is
Using Web Research window
84
AmiBroker 5.80 User’s Guide
Tutorial
accessible at the following address (URL):
http://www.sharenet.co.za/free/free_company_na.phtml?code=JSECODEp>
The problem is that database provided by Sharenet uses long ticker names and
JSECODE is a short symbol code. For example for "Accord Technologies" company the
ticker in Sharenet database is ACCORD but the code is ACR. To solve the problem
we will need to use Web ID field in the symbol Information window. If you have
Sharenet database just choose the ACCORD from the ticker list, open
Symbol->Information window and enter ACR to the Web ID edit box and click OK.
Then enter the following URL template to the URL edit box:
http://www.sharenet.co.za/free/free_company_na.phtml?code={i}p>
To be 100% sure please select the text above with a mouse. Then copy it to the
clipboard (Edit->Copy, CTRL-C). Then switch to AmiBroker and click on the Profile
URL edit box. Delete everything from it and press CTRL-V (this will paste the
text). Type "Sharenet" into Description field.
Please note that we have used {i} special field in the template that will be
replaced by AmiBroker with the text entered in the Web ID field of the symbol
information window. Now please select File->New->Web Research and pick Sharenet
from Address combo box. You should see the profile for ACCORD company.
You can also delete any entry by selecting it from the list and pressing Delete
button. You can change the order in which pages appear in the Web Research
address combo using Move Up and Move Down buttons (select the item first and then
use buttons).
Configuration data are stored in webpages.cfg plain text file that holds any
number of URL templates in the form of:
URLTemplate|Description
(each entry in separate line)
Using Web Research window
85
AmiBroker 5.80 User’s Guide
Tutorial
Using account manager
Account manager is a tool for keeping track of your trades and your performance.
You are able to enter trades you make, deposit/withdraw funds, check the
statistics and historical performance. All transactions are recorded so you will
never forget what happened in the past. Account manager allows you to keep track
of unlimited number of accounts.
New account manager replaces and enhances functionality provided by portfolio
manager in pre-4.90 versions.
CREATE A NEW ACCOUNT
Use File->New->Account menu to create new account
FUNDING AN ACCOUNT
Before you do any trading, you have to fund your account. To do so press
"FUNDING" button on the account manager toolbar, then select "Deposit" as
operation type, enter the DATE when you have funded your account and enter the
amount.
Note that funding date must PRECEDE any trading, as account manager won’t allow
you to trade prior to funding date. Initial deposit will show as "initial equity"
in summary tab.
Using account manager
86
AmiBroker 5.80 User’s Guide
Tutorial
THE SETTINGS
It is good idea to go to "Summary tab" and setup commissions and trading mode. If
this account is used for End-of-day trading you should set "EOD Mode" to YES,
otherwise (if you trade intraday) you should set "EOD Mode" to NO. Depending on
this setting Buy/Sell dialogs will allowyou to enter date and time of the trade
or only date.
Commission table allows to enter both per-share (per-contract) commissions and
commissions that are expressed as percent of trade value. Or a combination of
both. You can also set minimums and maximums expressed in dollar amount and/or
percent of trade value. For example if your broker may use 0.01$ (one cent) per
share commission, then you would use PerShare = 0.01 and %OfTradeValue = 0. If
your broker uses say 0.2% of trade value then you would use PerShare = 0 and
%OfTradeValue = 0.2;
Practical example: Interactive Brokers default commission for U.S. stocks is:
0.005 per share but not less than 1 dollar and not more than 0.2% of trade value.
Appropriate settings for such schedule are shown in the screenshot above.
Commission table works as follows: first sum of per-share commission and % of
trade value is calculated. Then the result is checked against minimum and maximum
Using account manager
87
AmiBroker 5.80 User’s Guide
Tutorial
limits and if calculated value exceeds the limit then commission is set to value
of such the limit, otherwise calculated value is used without change.
Summary page contains a little bit of basic statistics as well.
ENTERING TRADES
Once you funded an account you can enter trades.To buy (enter long position or
cover short position ) click on "BUY" button.
Then in the Buy dialog you need to select the symbol, the trade date/time. Once
they are entered AmiBroker will display price of given symbol at the selected
date/time (or preceding one if no exact match is found). It will also calculate
maximum possible quantity taking price and available funds into account.
You can change the price and quantity manually.
All other values (net market valye, commission, market deposit, currency, fx
rate) are calculated or retrieved automatically from Symbol->Information page.
Once values are good, click OK to confirm transaction. If you made mistake, you
can press UNDO (Edit->Undo) to revert last transaction.
Similar procedure is for selling (entering short positions or closing longs) with
the exception that you should press "SELL" button instead.
All transactions that you made are listed in the "Transactions" sheet. All open
positions are listed in "Open Positions" sheet. If you enter the trade for symbol
that has position already open, AMiBroker will adjust "open positions"
accordingly (perform scaling in/out). Once open position is closed it is removed
from "open positions" list and moved to "Closed trades" sheet.
Using account manager
88
AmiBroker 5.80 User’s Guide
Tutorial
After each transaction, "Equity history" sheet is updated with current account
equity value and also "Summary" page is updated with basic open/long/short trade
stats.(More stats are to come).
IMPORTANT
You have to remember that you must enter all transactions in chronological
manner(oldest first, newest last), as account manager won’t allow you to add
trades out-of-order. If you make mistake, there is one-level undo that you can
use to revert to state before last transaction. If you made more mistakes, the
only option is to close account without saving and re-open original file.
SAVING YOUR ACCOUNT DATA
To save edits made to account use File->Save (or File->Save As to save under new
name). Note that account files are NOT encrypted now, and it is quite easy to
read the file for everyone who has the access to it. So make sure not to leave
your files on some public computer. Password protection/encryption is planned but
NOT implemented yet.
Using account manager
89
AmiBroker 5.80 User’s Guide
Tutorial
OPENING PREVIOUSLY CREATED ACCOUNT
To open account file, go to File->Open, in the File dialog, select "Account
(*.acx)" from "Files of type" combo-box, and select the account file you want to
load.
MULTIPLE ACCOUNTS
You can create/open multiple accounts at once (just use File->New->Account,
File->Open many times).
Using account manager
90
AmiBroker 5.80 User’s Guide
Tutorial
Using fundamental data
AmiBroker 4.90 adds ability to use 32 fundamental data items. Fundamental data
can be automatically downloaded for all U.S. stocks for free using AmiQuote. New
Information window allows you to view these items, while new AFL function:
GetFnData allows to access fundamentals programmatically.
INFORMATION WINDOW
To display fundamental data in Information window, please use Symbol->Information
menu. This will open Information window with several fundamenta data fields as
shown in the picture below (if you created new database, it probably will not
have these data present initially and you would need to download them)
DOWNLOADING FREE FUNDAMENTAL DATA FROM YAHOO
New version of AmiQuote now features ability to download free fundamental data
from Yahoo Finance web site. This is implemented using 2 different Yahoo pages:
Using fundamental data
91
AmiBroker 5.80 User’s Guide
Tutorial
1. Yahoo Fundamental - Basic data source (free basic fundamental data, 200
symbols in one request).
Data are retrieved from the following URL:
http://finance.yahoo.com/q?s={Ticker} (Download data link).
That page provides the following data:
EPS (ttm)
EPS Est Current Year
EPS Est Next Year
EPS Est Next Quarter
PEG Ratio
Book Value
EBITDA
Sales Revenue
Dividend Pay date
Ex Dividend date
Dividend Per Share
1yr Target Price
Shares Float
Shares Outstanding
Explanation of values:
http://help.yahoo.com/help/us/fin/quote/quote-03.html
2. Yahoo Fundamental - Extra data source (extended fundamental data, 1 symbol
in one request, more data - available in registered version only).
Data are retrieved from the following URL:
http://finance.yahoo.com/q/ks?s={Ticker} (Key Statistics page)
That page provides following data:
Forward P/E
PEG Ratio
Profit Margin
Operating Margin
Return on Assets
Return on Equity
Revenue (ttm)
Qtrly Revenue Growth
Gross Profit
EBITDA
(Diluted) EPS
Qtrly Earnings Growth
Book Value Per Share
Operating Cash Flow
Levered Free Cash Flow
Beta
Shares Outstanding
Float
% Held by Insiders
% Held by Institutions
Shares Short (prior month)
Using fundamental data
92
AmiBroker 5.80 User’s Guide
Tutorial
Shares Short
Forward Annual Dividend Rate
Trailing Annual Dividend Rate
Dividend Date
Ex-Dividend Date
Last Split Factor
Last Split Date
Explanation of values:
http://help.yahoo.com/help/us/fin/research/research-12.html
IMPORTANT NOTE: Unregistered version of AmiQuote allows you to
download fundamental-ex data for first 20 tickers in the list. To
download data for more symbols you need to register AmiQuote.
Downloading data is easy and staightforward:
1. Run AmiQuote
2. In AmiQuote, select Tools->Get tickers from AmiBroker
3. Select Yahoo Fundamental - Basic or Yahoo Fundamental - Extra from Source
drop down list
4. Make sure that Automatic import box is checked
5. Press Green Arrow to Start Download
Once download is complete, you should see fundamental data updated in Information
window in AmiBroker.
ACCESSING FUNDAMENTAL DATA FROM FORMULA (AFL) LEVEL
To access fundamental data from AFL level you can use new GetFnData function. It
has quite simple syntax:
GetFnData("field")
Using fundamental data
93
AmiBroker 5.80 User’s Guide
Tutorial
where "field" is any of the following fundamental data field supported. For
detailed list please see GetFnData function reference.
The function returns the number (scalar) representing current value of
fundamental data item. There is no history of values (no arrays are returned), so
it is useful for scanning, explorations (for current situation), market
commentary / interpretation, but not for backtesting. Example exploration formula
looks as follows:
AddColumn( Close / GetFnData( "EPS" ) , "Current P/E ratio" );
AddColumn( Close / GetFnData( "EPSEstNextYear" ) , "Est. Next Year P/E ratio" );
Filter = Status("lastbarinrange");
IMPORTING FUNDAMENTAL DATA FROM OTHER SOURCES
AmiBroker allows also to import fundamentals using its flexible ASCII importer
and/or OLE interface as all new fields are exposed as properties of Stock object.
ASCII importer $FORMAT command now supports the following extra fields for
fundamental data:
DIV_PAY_DATE
EX_DIV_DATE
LAST_SPLIT_DATE
LAST_SPLIT_RATIO
EPS
EPS_EST_CUR_YEAR
EPS_EST_NEXT_YEAR
EPS_EST_NEXT_QTR
FORWARD_EPS
PEG_RATIO
BOOK_VALUE (requires SHARES_OUT to be specified as well)
BOOK_VALUE_PER_SHARE
EBITDA
PRICE_TO_SALES (requires CLOSE to be specified as well)
PRICE_TO_EARNINGS (requires CLOSE to be specified as well)
PRICE_TO_BV (requires CLOSE to be specified as well)
FORWARD_PE (requires CLOSE to be specified as well)
REVENUE
SHARES_SHORT
DIVIDEND
ONE_YEAR_TARGET
MARKET_CAP (requires CLOSE to be specified as well - it is used to calculate
shares outstanding)
SHARES_FLOAT
SHARES_OUT
PROFIT_MARGIN
OPERATING_MARGIN
RETURN_ON_ASSETS
RETURN_ON_EQUITY
QTRLY_REVENUE_GROWTH
GROSS_PROFIT
Using fundamental data
94
AmiBroker 5.80 User’s Guide
Tutorial
QTRLY_EARNINGS_GROWTH
INSIDER_HOLD_PERCENT
INSTIT_HOLD_PERCENT
SHARES_SHORT_PREV
FORWARD_DIV
OPERATING_CASH_FLOW
FREE_CASH_FLOW
BETA
Note that if you want to import only fundamental data with ASCII importer
(without quotes) you need to use $NOQUOTES 1 command. See Formats\aqfe.format and
Formats\aqfn.format files for example usage - these are files actually used by
AmiQuote to implement automatic import of fundamental data downloaded from Yahoo.
The names of extra properties of Stock object are the same as used by GetFnData
function and they are listed in detail in OLE objects reference.
Using fundamental data
95
AmiBroker 5.80 User’s Guide
Tutorial
Using New Analysis window
Introduction
New Analysis window introduced in version 5.50 (first time actually in 5.41.0
BETA) brings the following improvements over old Automatic Analysis:
• multi-threaded operation = speed - new Analysis window uses all available
CPUs/cores to execute formulas in many threads in parallel providing
significant speed ups. For example on 4 core Intel i7 that can run upto 8
threads, it can run upto 8 times faster than old Analysis window. Exact
speed up depends on complexity of the formula (the more complex it is, the
more speedup is possible), amount of data processed (RAM access may be not
as fast as CPU thus limiting possible speed gains).
• non-blocking operation - you can now view, scroll and sort results of
analysis while they are still generated, also as user interface thread is
not used for processing for most part, charts and other GUI-driven program
parts are way more responsive than with old automatic analysis
• multiple instances - you can run more than one instance of New Analysis at
a time, so you can run many scans/backtest/explorations/optimizations in
parallel without waiting for one to complete
• slicker user interface - New Analysis window can act as tabbed document,
can be floated, buttons can be re-arranged for better workflow. There is
way more space for the result list, extra information about execution is
provided on the new "Info" tab. Also walk-forward results are now displayed
within New Analysis window for less clutter.
User interface
You can open New Analysis window in a number of ways:
1. click on the New Tab (+) button and selecting New Analysis
or
2. File -> New -> New Analysis menu
or
3. Analysis-> New Analysis menu
or
4. right click on the formula in the Charts window and selecting Analysis
Using New Analysis window
96
AmiBroker 5.80 User’s Guide
Tutorial
or
5. from the Formula Editor, pressing Send to Analysis button
Basically the user interface for New Analysis window is functionally similar to
old automatic analysis and looks as follows:
Using New Analysis window
97
AmiBroker 5.80 User’s Guide
Tutorial
Basic operations
Selecting the symbol to apply analysis to.
Click on the drop down arrow in the Apply to combo to select operation mode: All
symbols / Current symbol / Filter
Defining Filter
If Apply To is set to Filter, Analysis window will be run on the symbols that
match filtering criteria that are definable in the Filter Settings window. To
open Filter Settings window press
Filter button
Using New Analysis window
98
AmiBroker 5.80 User’s Guide
Tutorial
Defining date/time Range
Click on the drop down arrow in the Range combo to select range selection mode:
All symbols / N recent bar(s) / N recent day(s) / From-To dates
The ’N’ can represent any number. For example to define range of 15 recent days,
select 1 recent day(s) first and then type in 15 and press ENTER. You will see
the text automatically update to 15 recent day(s). Remember you don’t need to
type whole thing, just a number is perfectly enough.
Viewing reports / Running Report Explorer
To view the report from last backtest, click on the Report button. To run the
Report Explorer use a Report button drop down menu as shown below
Changing settings / options
To change backtester settings click on the Settings button. To turn on/off
additional options like:
•
•
•
•
Sync chart on select
Wait for backfill
Auto repeat Scan/Explore
Auto repeat interval
click on the drop down arrow on the Settings button to display the menu as shown
below
Using New Analysis window
99
AmiBroker 5.80 User’s Guide
Tutorial
Auto-repeat interval can be entered in the Interval field. Note that plain
numbers (like 5) represent minutes. To get seconds you need to enter 5sec or 5s
and press ENTER
Running Walk forward Test
Click on the arrow on the Optimize button to display the menu as shown below and
select Walk-Forward
The results of Walk forward test will be displayed in Walk Forward tab (see
bottom of Analysis window).
Displaying 3D optimization chart
To display 3D optimization chart, first run the Optimize that has exactly two
optimization parameters and then click on the arrow on the Optimize button to
display the menu as shown above and select 3D Optimization Chart.
Displaying Equity charts
Equity charts (portfolio and individual) can be added to chart windows using
Portfolio Equity / Individual Equity options as shown above.
Exporting and importing result list
Using New Analysis window
100
AmiBroker 5.80 User’s Guide
Tutorial
To export data to CSV file or HTML file use File -> Export HTML/CSV menu (from
the main window). To import previously exported HTML file use File->Import
HTML... as shown in the picture below. Note that these menu items appear only if
you have New Analysis window active.
Using New Analysis window
101
AmiBroker 5.80 User’s Guide
Tutorial
How to get quotes from various markets
REAL-TIME DATA (Professional Edition only)
Country/Exchange
Data source
Type
Price
Download
Update
Comments
Automatic
Dedicated
RT plug-in
- details
here
Automatic
Automatic
Dedicated
RT plug-in
- details
here
Automatic
Automatic
Real time
streaming
quotes.
All US Stock and
Futures markets.
FOREX
eSignal
Tick, 5-,
15- second
1-, 5-,
15-,
60-minute
intraday
More pricing
information
Automatic
10-day
tick,
60-day
minute bar
backfill.
Major European
markets.
Historical
EOD (10
years)
US stocks,
futures,
options, FOREX
DTN IQFeed
500
symbols,
tick,
5-sec,
15-sec,
1-minute
and up,
120 days
backfill
$63/month
basic fee
More pricing
information
(note:
unfiltered
feed)
US, Canada and
European
exchanges
Interactive
Brokers
100 symbols
streaming
RT, 1-sec,
1-minute
bars and
up.
$10 per month
in
commissions,
or free if
your monthly
commissions
are >$30
Dedicated
RT plug-in
- details
here
30 day
backfill
How to get quotes from various markets
102
AmiBroker 5.80 User’s Guide
Tutorial
available
for IB
customers
Real time
streaming
quotes.
All US Stock and
Futures markets.
myTrack
Major European
markets.
1-, 5-,
15-,
60-minute
intraday
See service
plans
Automatic
Automatic
Dedicated
RT plug-in
- details
here
Automatic
Dedicated
RT plug-in
- details
here
Automatic
Dedicated
RT plugin
- details
here
15-day
minute bar
backfill.
Historical
EOD (15
years)
Real time
streaming
quotes.
Various
exchanges /
various sources
Quote
Tracker
(detailed list)
Warsaw Stock
Exchange
Limited
(max. 5
days,
usually one
day)
backfills
Statica
Various
(any data source
that has DDE
interface)
1-, 5-,
15-,
60-minute
intraday
DDE link
Various
(including
free)
More pricing
information
30/90 days
intraday +
mixed mode
EOD
just
streaming
quotes, no
backfill
Automatic
Automatic
Dedicated
RT plug-in
Free
Automatic
Automatic
- details
here
END-OF-DAY, INTRADAY DELAYED DATA
AmiBroker can handle virtually EVERY exchange in the world if only plain ASCII
data for that exchange are available. The table below list some of the data
sources.
How to get quotes from various markets
103
AmiBroker 5.80 User’s Guide
Tutorial
AmiBroker comes preloaded with sample DJIA components database. You can update
this sample database (and any other US & Canada market databases) with a new
quotes using supplied AmiQuote program.
Later in this tutorial you will find detailed instructions on how to use
AmiQuote.
Quote sources for AmiBroker (this list is not complete - keep in mind the fact
that almost any source can be used). Use links to find out more (note that some
links require internet connection)
Country/Exchange
Data source
Type
Price
Download
Yahoo Finance
Historical +
Current EOD
Free
Automatic
(AmiQuote)
Google Finance
Historical EOD
Free
Automatic
(AmiQuote)
MSN Money Central
Historical EOD
Free
Automatic
(AmiQuote)
Norgate Investor
Services (Premium Data)
Historical EOD +
Daily updates +
Sectors /
Industries / etc +
Delisted symbols
Paid
Automatic
Historical +
Current EOD +
Sectors/Industries
Paid
Automatic
FastTrack (mutual
funds)
Historical +
Current EOD +
Families
Paid
Automatic
FOREX
Historical EOD +
Intraday
Free
Automatic
(AmiQuote)
USA + Canada
(NYSE/Nasdaq/AMEX/TSE)
TC 2000/TCNet (stocks)
TC2000 Mutual Funds
Australia
(Australian Stock
Exchange)
Paid:
Details
here
Automatic
CSI
http://www.csidata.com
Historical EOD
Norgate Investor
Services
Historical EOD
(also US stock and
future markets)
Paid
Automatic
BodhiFreeway
Historical
Paid
Automatic
How to get quotes from various markets
104
AmiBroker 5.80 User’s Guide
Tutorial
(Bodhi
downloader)
Yahoo Finance Australia
Current EOD
Free
Automatic
(AmiQuote)
50+ International
Exchanges
Yahoo Finance
Historical +
Current EOD
Free
Automatic
(AmiQuote)
Poland
(Warsaw Stock Exchange)
Bossa.pl
Historical +
Current EOD
Free
Automatic
(script-based)
Sharenet
Historical +
Current EOD
Paid
Automatic
(Sharenet
downloader)
Investor Data
Historical
Paid
Manual
PF-online
Historical +
Current EOD
Free
Manual
South Africa
(Johannesburg Stock
Exchange)
Holand (Amsterdam Euronext)
How to get quotes from various markets
105
AmiBroker 5.80 User’s Guide
Tutorial
How to set up AmiBroker with eSignal feed (RT version
only)
Requirements
IMPORTANT: You have to have eSignal application installed on your machine and a
valid eSignal subscription.
One-time setup
To use AmiBroker with eSignal feed you will need to perform a one-time setup
described below:
• Run AmiBroker
• Choose File->New database
• Type a new folder name (for example: C:\Program Files\AmiBroker\eSignal )
and click Create as shown in the picture below:
• Choose eSignal RT data Plug-in from Data source combo and "Enable" from
Local data storage
• Enter appropriate number of bars to load:
90000 for 1-minute database combined with long history daily database
• Click on Configure button to show plugin configuration dialog as shown
below
How to set up AmiBroker with eSignal feed (RT version only)
106
AmiBroker 5.80 User’s Guide
Tutorial
Enter here your eSignal user and password (if you have eSignal properly
installed AmiBroker will pre-set these fields to user/password entered in
eSignal software). You may also adjust Number of symbols. This should not
exceed your account limit and you may consider lowering this value if you
want to use AmiBroker in parallel with another Data manager client
application. (If you exceed the limit of your subscription AmiBroker will
re-adjust this number down)
Click OK
• Now choose Base periodicity. Note that recommended periodicity is 1 minute,
but you can select all base periods starting from tick upto hourly.
Note that selecting tick, 1-second, 5-seconds or 15-seconds periodicities
will cause transmission of huge amounts of data from eSignal servers (for
actively traded security it can be several megabytes for just one symbol
and very few days of history). If you have a modem connection this setting
is highly discouraged. Also if you should consider using 1-second bars
instead of pure ticks since this mode is faster.
Also note that to get long end-of-day histories together with intraday data
you should go to File->Database Settings->Intraday Settings and turn ON
"Allow mixed EOD/intraday data" option.
• Click OK.
From now on your AmiBroker reads quotes directly from the eSignal.
To learn how to use AmiBroker in Real Time mode read this tutorial article.
How to set up AmiBroker with eSignal feed (RT version only)
107
AmiBroker 5.80 User’s Guide
Tutorial
How to set up AmiBroker with myTrack feed (RT version
only)
Note: the most recent version of this document can be found at:
http://www.amibroker.com/mytrack.html. Please check this page for updates.
Requirements
IMPORTANT: You have to have myTrack subscription with SDK feature enabled.
To have the SDK working, run the myTrack program, click on CHAT, then on
Entitlements and then on Features, check the box SDK.
One-time setup
To use AmiBroker with myTrack feed you will need to perform a one-time setup
described below:
• Run AmiBroker
• Choose File->New database
• Type a new folder name (for example: C:\Program Files\AmiBroker\myTrack )
and click Create as shown in the picture below:
• Choose myTrack RT data Plug-in from Data source combo and "Enable" from
Local data storage
• Click on Configure button to show plugin configuration dialog as shown
below
How to set up AmiBroker with myTrack feed (RT version only)
108
AmiBroker 5.80 User’s Guide
Tutorial
Enter here your myTrack user and password . You may also adjust Number of
symbols. This should not exceed your account limit.
Click OK
• Now choose Base time interval. Note that supported bar intervals are 1
minute and daily (end-of-day).
If you want to have long daily histories AND intraday charts you should
consider running TWO instances of AmiBroker. One for EOD charts and second
for intraday charting. Both instances may use myTrack as a data source.
• Click OK.
From now on your AmiBroker reads quotes directly from the myTrack.
To learn how to use AmiBroker in Real Time mode read this tutorial article.
How to set up AmiBroker with myTrack feed (RT versiononly)
109
AmiBroker 5.80 User’s Guide
Tutorial
How to use AmiBroker with external data source (Quote
Tracker)
IMPORTANT: You need QuoteTracker 2.4.9C OR ABOVE (3.1.0 recommended). Can operate
on standard edition but AmiBroker RT is recommended.
VERY IMPORTANT: QuoteTracker has to be CONFIGURED so its internal server is
running. Click here for the explanation.
CAVEAT: QuoteTracker should be considered as poor-man’s real-time substitute. Its
performance can not be compared to true real-time feed as eSignal or myTrack that
offer very reliable, long back-fills and true tick-by-tick updates.
QuoteTracker plugin currently works in TWO modes:
daily mode - plugin adds and updates the last (todays) bar with the most recent quotes in nearly
real time- it means that you have to use it in conjunction with already existing end-of-day
database.
intraday mode - plugin provides one day intraday historical data - more days can
be accumulated if AmiBroker with QT is launched everyday so AmiBroker can save
histories to its local database.
One-time setup
Make sure that your QuoteTracker has enabled QT HTTP server: Options->Edit Preferences : Misc
tab: HTTP Server Settings
If you are using unregistered version of QuoteTracker make sure you click on ads often enough.
To use an external data source with AmiBroker you will need to perform a one-time
setup described below:
Run AmiBroker Choose File->New database Type a new folder name (for example:
C:\Program Files\AmiBroker\NewData ) and click Create as shown in the picture
below:
How to use AmiBroker with external data source (Quote Tracker)
110
AmiBroker 5.80 User’s Guide
Tutorial
Choose appropriate entry from Data source combo:
• Quote Tracker users select "Quote Tracker plug-in" as a Data Source and
"Enable" from Local data storage
Click on Configure button to show plugin configuration dialog as shown below
How to use AmiBroker with external data source (Quote Tracker)
111
AmiBroker 5.80 User’s Guide
Tutorial
You may also click on Retrieve button to pre-fill AmiBroker database with symbols
already present in QuoteTracker. From now on your AmiBroker reads quotes from
Quote Tracker in nearly real time.
To learn how to use AmiBroker in Real Time mode read this tutorial article.
Description of QuoteTracker plugin configuration options
QT plugin configuration dialog looks as follows:
Here is a description of the settings:
QuoteTracker server port: defines the port on which QT HTTP internal server is
visible. 16239 is the default value used by QuoteTracer and you should not change
QuoteTracker HTTP server settings:
this in most cases. If in doubt please check
Options->Edit Preferences : Misc tab: HTTP Server Settings menu of QT.
Refresh inteval - defines how often AmiBroker will ask QT for quotes. 5 second is
default. You may consider changing it to 10 or 15 seconds in case you have lots
of symbols and slow machine
Auto-add symbols from AmiBroker - if this option is turned ON (by default it is)
if you switch in AmiBroker to the symbol that is not present in any of QT
portfolios - it will be automatically added to default QT portfolio. It also
applies to any other kind of access (for example if you try to import symbols to
AmiBroker and they do not exist in QT - they will be added if this option is
turned on). Switching it OFF disables auto-add feature.
Max. number of added symbols - defines the maximum number of symbols that get
added using auto-add feature descibed above. This protects QuoteTracker from
becoming overloaded (AmiBroker can handle tens of thousands symbols with ease but
QuoteTracker can NOT)
Use optimized routine for intraday data retrieval - turning this on (default,
recommended) significantly speeds-up data retrieval in intraday modes. If this
How to use AmiBroker with external data source (Quote Tracker)
112
AmiBroker 5.80 User’s Guide
Tutorial
option is enabled and AmiBroker already has partial intraday data for today
AmiBroker asks QT just for a few last time and sales records that occurred since
last update upto current time, if this option is disabled AmiBroker always asks
QT for time&sales records from entire day.
Time difference relative to US Eastern time - the time difference (in hours)
between your local time and US Eastern time (EST). This field is needed because
QuoteTracker’s server reports all times in EST time zone. This means that if you
live in Australia QuoteTracker will report ASX quotes with EST time zone and they
will be 15 hours off from your local time. While AmiBroker has the setting for
shifting intraday charts and this is not a problem when running Intraday mode, it
becomes a problem when using daily (EOD) mode because quotes reported by
QuoteTracker are one day off then. This setting solves this as AmiBroker adds the
number of hours entered here to the time reported by QuoteTracker to get the
valid date of quote in daily mode. This field is filled in with the difference
calculated using your Windows Time settings.
Retrieve symbols from QuoteTracker - pressing "Retrieve" button adds all symbols
present in QuoteTracker to AmiBroker symbol list.
How to use AmiBroker with external data source (Quote Tracker)
113
AmiBroker 5.80 User’s Guide
Tutorial
How to set up AmiBroker with IQFeed feed (RT version
only)
Note: the most recent version of this document can be found at:
http://www.amibroker.com/iqfeed.html . Please check this page for updates.
Requirements
If you don’t have IQFeed CONNECTION MANAGER already installed you have to install
it first. You can download IQFeed client setup from here (version 4.2.0.7).
http://www.amibroker.com/video/IQFeed.html
To use AmiBroker with IQFeed you will need to perform a one-time setup described below:
• Run AmiBroker
• Choose File->New database
• Type a new folder name (for example: C:\Program Files\AmiBroker\IQFeed ) and click Create
as shown in the picture below:
• Choose DTN IQFeed data Plug-in from Data source combo and "Enable" from Local data storage
• Now choose Base time interval. Select 1-minute
• Enter appropriate number of bars to load:
100000 for 1-minute database to get max history (8 months) available from IQFeed
How to set up AmiBroker with IQFeed feed (RT version only)
114
AmiBroker 5.80 User’s Guide
Tutorial
• Click on "Intraday Settings". Check "Allow mixed EOD/Intraday data" box. Click OK
• Click OK.
From now on your AmiBroker reads quotes directly from the IQFeed.
To learn how to use AmiBroker in Real Time mode read this tutorial article.
How to set up AmiBroker with IQFeed feed (RT version only)
115
AmiBroker 5.80 User’s Guide
Tutorial
How to use AmiBroker with Interactive Brokers TWS
Note: the most recent version of this document can be found at:
http://www.amibroker.com/ib.html . Please check this page for updates.
IB PLUGIN FEATURES SUMMARY:
• supports upto 100 streaming symbols in real time (equal to IB TWS limit)
• supports all base time intervals: daily, hourly, 15-,5-,1-minute,
15-,5-second, tick
• automatic connection (no need to manually "accept incoming connection" in
TWS)
• supports upto 30 DAYS intraday data BACKFILL in 1-minute bar interval
• upto 2000 bars backfill using 1-sec/5-sec/15-second bar intervals
INSTRUCTIONS:
NOTE: Interactive Brokers TWS is CPU-hungry application, therefore for best
results we recommend using machine with 1GHz processor or faster.
NOTE 2: There is a VIDEO tutorial showing how to set it up at
http://www.amibroker.com/video/ib.html
To use Interactive Brokers data plugin with AmiBroker you need to:
1. run web-based TWS or download standalone TWS
2. In TWS, select Configure -> API -> Enable Active X and Socket clients
Also enter 127.0.0.1 in TWS, Configure->API->Trusted IP addresses menu to
prevent "Allow incoming connection?" dialog.
3. Run AmiBroker and create new database with Interactive Brokers plugin as a
data source, following these steps:
• Run AmiBroker
• Choose File->New database
• Type a new folder name (for example: C:\Program Files\AmiBroker\IB ) and
click Create as shown in the picture below:
How to use AmiBroker with Interactive Brokers TWS
116
AmiBroker 5.80 User’s Guide
Tutorial
• Choose InteractiveBrokers(r) data Plug-in from Data source combo and
"Enable" from Local data storage
• Enter 30000 or more into "Number of bars to load" field
• Now choose Base time interval. Supported intervals are: EOD, hourly,
15-minute, 5-minute, 1-minute. Professional Edition of AmiBroker allows
also to select Tick, 5-second, 15-second intervals.
Note that backfill is in bar interval of 1-minute or less (TWS limitation).
If you want to have long daily histories AND intraday charts you should
consider running TWO instances of AmiBroker. One for EOD charts and second
for intraday charting. Both instances may use IB as a data source.
• Click OK.
From now on your AmiBroker reads quotes directly from the Interactive Brokers.
HOW TO USE BACKFILL FEATURE
Backfill feature in plugin 1.3.7 allows to download 24 intraday historical data
to fill-in the gaps that may have occurred when AmiBroker / TWS is not running.
IB Backfill feature is configurable from File->Database Settings, Configure :
How to use AmiBroker with Interactive Brokers TWS
117
AmiBroker 5.80 User’s Guide
Tutorial
Two main backfill-related settings are:
1. request length
2. automatic backfill
When request length is considered, as explained in TWS API Release Notes at:
http://www.interactivebrokers.com/en/software/apiReleaseNotes/apiBetanotes.php
currently IB backfill feature is limited to some fixed duration / bar interval
ranges. For example you can get maximum 2000 1-second ticks, maximum 10000
seconds in 5-second interval (2000 bars), maximum 30000 seconds in 15-second
interval (also 2000 bars) and maximum of 5 DAYS of 1-minute bars.
By default AmiBroker uses maximum allowable amounts.
As for "automatic backfill on first data access" - when it is checked AmiBroker
attempts to backfill symbol when you display a chart for given symbol (or perform
backtest or scan). Please note that TWS API currently allows only one backfill at
a time so when there is a backfill already running in the background, automatic
backfill request for next symbol will be ignored, until previous backfill is
complete.
It is convenient to have this option turned on, however it can cause additional
load on your internet connection because of data needed to be downloaded during
backfill process.
If you switch "automatic backfill on first data access" option off, you will
still be able to backfill data for current symbol or all symbols in real-time
quote window list usign appropriate menu options from plugin status menu.
How to use AmiBroker with Interactive Brokers TWS
118
AmiBroker 5.80 User’s Guide
Tutorial
Backfill Current option allows to force backfill of currently selected symbol,
while Backfill All RT quote window symbols allow to force backfill of all symbols
listed in Real-Time Quote window. Backfill of multiple symbols is performed
sequentially (one at a time) due to limitations of TWS.
Backfill length submenu allows to select desired backfill length.
During backfilling a tooltip pops up informing the user about symbol being
currently backfilled and plugin status color changes to light blue (turquoise) as
shown below:
SYMBOLOGY
Symbol format now uses the symbol mode of TWS, not the underlying mode. The
symbol mode in TWS can be seen in the ’View->Symbol Mode’ menu option in TWS.
The format is: SYMBOL-EXCHANGE-TYPE
where
SYMBOL is the same as the symbol column as displayed in TWS while under symbol
mode
EXCHANGE (optional) is the exchange d in TWS while under symbol mode
TYPE (optional) is one the following:
How to use AmiBroker with Interactive Brokers TWS
119
AmiBroker 5.80 User’s Guide
Tutorial
STK - stocks, FUT - futures, FOP - options on futures, OPT - options, IND indexes, CASH -cash (ideal FX)
Note that for stocks only the EXCHANGE and TYPE fields are optional. The exchange
will be set to BEST (SMART) and the TYPE will be set to STK.
Please take special care when typing symbols as some of them (futures) have
MULTIPLE SPACES in the symbol name. You have to type EXACTLY THE SAME number of
spaces as provided in the examples below
(see the dashes below symbol name that make it easier to see the number of
characters)
Examples:
IB SYMBOL
Type
Description
CSCO
Stock
Cisco Corporation, Nasdaq
GE
Stock
General Electric, NYSE
VOD-LSE
Stock
VODAFONE GROUP, London Stock Exchange
ESM4-GLOBEX-FUT
Future
Emini ES Jun04 futures, Globex
QQQFJ-CBOE-OPT
Option
Jun 04, 36.0 CALL option QQQFJ
INDU-NYSE-IND
Index
Dow Jones Industrials Index
YM
Future
YM Jun 04 future, ECBOT
(note 3 spaces between symbol and month
and 1 space between month and year)
QMN5-NYMEX-FUT
Future
QM (Crude) June 2005 future contract,
NYMEX
XAUUSD-SMART-CMDTY
Commodity
London Gold Spot
CFD
(contract
for
difference)
IB US500 contract for difference
Cash Forex
EURUSD currency pair, IDEAL
EURUSD currency pair, IDEALPRO
JUN 04-ECBOT-FUT
---
IBUS500-SMART-CFD-USD
EUR.USD-IDEAL-CASH
EUR.USD-IDEALPRO-CASH
Again:
ECBOT futures symbols have length of 21 characters with 3 spaces between contract
symbol and month name and one space between month and 2 digit year
Contract
3 spaces
spa
ce
Month
Year
-
E
C
B
O
T
-
F
U
T
Z
B
J
U
N
0
4
-
E
C
B
O
T
-
F
U
T
Z
F
J
U
N
0
4
-
E
C
B
O
T
-
F
U
T
Z
N
J
U
N
0
4
-
E
C
B
O
T
-
F
U
T
Y
M
J
U
NOTES ON IB API LIMITATIONS:
N
0
4
-
E
C
B
O
T
-
F
U
T
1. Backfill is available for REAL IB accounts only (not on demo)
How to use AmiBroker with Interactive Brokers TWS
120
AmiBroker 5.80 User’s Guide
Tutorial
2. Open price is NOT provided by IB. For that reason Open field is empty in real
time quote window
3. The data from IB does not include a timestamp on the trades. The current
system time is used to timestamp each tick.
4. IB TWS streaming data are NOT tick-by-tick, but rather 0.2-0.3 second
snapshots, read this for details:
http://www.interactivebrokers.com/cgi-bin/discus/board-auth.pl?file=/2/37364.html
How to use AmiBroker with Interactive Brokers TWS
121
AmiBroker 5.80 User’s Guide
Tutorial
How to use AmiBroker with external DDE data source
Note: the most recent version of this document can be found at:
http://www.amibroker.com/dde.html . Please check this page for updates.
WHAT IS DDE
DDE (Dynamic Data Exchange) is a Windows protocol used to allow applications to
exchange data. For example, when you change a form in your database program or a
data item in a spreadsheet program, they can be set up to also change these forms
or items anywhere they occur in other programs you may use. DDE uses a
client/server model in which the application requesting data is considered the
client and the application providing data is considered the server.
Thousands of applications use DDE, including Microsoft’s Excel, Word, Lotus
1-2-3, and Visual Basic.
For more information about DDE as communication mechanism in Windows please
follow this link:
http://msdn.microsoft.com/library/en-us/winui/WinUI/WindowsUserInterface/DataExchange/DynamicDataExchange/Abo
DDE FOR TRADERS
What DDE offers for traders? Basically real time streaming quotes. There is NO
BACKFILL via DDE. Many real-time data providers and brokerages provide ability to
get real-time data by means of DDE. You should ask your brokerage/real-time data
vendor if they offer DDE link. The DDE plugin now available for AmiBroker allows
to link to (almost) any DDE source (server) supplying real-time quotes. This
makes it attractive option for all data sources that do not have dedicated
plugin.
WHEN NOT TO USE DDE PLUGIN
If you are using eSignal, IQFeed, Quote.com, and any other source that has
dedicated plugin - you should use this dedicated plugin instead of DDE. This is
so because dedicated plugins are ALWAYS better option (provide more features plus
they are faster) than generic DDE.
DDE PLUGIN FEATURES SUMMARY
• user-definable DDE server/topic/item for each field (open, high, low,
close, volume, trade size, total volume, bid, bid size, ask, ask size,
time)
• supports upto 500 streaming symbols in real time (version 1.1.0)
• supports all base time intervals: daily, hourly, 15-,5-,1-minute,
15-,5-second, tick
• NO BACKFILL (due to the fact that most DDE sources do not provide backfill)
HISTORY
• 1.2.2 - includes "Time shift" field in the context dialog, stores
configuration per-database in dde.config file instead of in the registry
How to use AmiBroker with external DDE data source
122
AmiBroker 5.80 User’s Guide
Tutorial
plus other small improvements
• 1.2.1 - fixed problem with ’type mismatch’
• 1.2.0 - by default plugin uses regional settings numeric format now
and CPU load is decreased
• 1.1.0 - symbol limit increased from 40 to 500
• 1.0.0 - initial release (BETA)
INSTRUCTIONS
To use DDE data plugin with AmiBroker you need to:
1. (optional *) Download the latest version DDE plugin from
http://www.amibroker.com/bin/DDE.dll and copy it to PLUGINS subfolder of
AmiBroker directory.
*Version 1.2.2 of DDE.DLL (Jun 7, 2007) is already included in AmiBroker
5.00 full setup
2. Enable DDE in the 3rd party software you are using as DDE server (consult
data vendor/brokerage software documentation for details on how to enable
DDE)
3. Run AmiBroker and create new database with "DDE universal data plugin" as a
data source, following these steps:
• Run AmiBroker
• Choose File->New database
• Type a new folder name (for example: C:\Program Files\AmiBroker\DDE ) and
click Create as shown in the picture below:
• Choose DDE universal data plugin from Data source combo and "Enable" from
How to use AmiBroker with external DDE data source
123
AmiBroker 5.80 User’s Guide
Tutorial
Local data storage
• Enter 10000 or more into "Number of bars to load" field
• Now choose Base time interval. Supported intervals are: EOD, hourly,
15-minute, 5-minute, 1-minute. Professional Edition of AmiBroker allows
also to select Tick, 5-second, 15-second intervals.
• Click CONFIGURE button - IMPORTANT: in the "CONFIGURE" dialog you have to
setup all fields following the description of your data vendor.
Please check also paragraph below ("CONFIGURING DDE PLUGIN TO WORK WITH
YOUR VENDOR") for detailed description. ATTENTION: you can not skip this
part - without setting up fields specifically for your data vendor, the DDE
WILL NOT WORK.
• Click OK.
The Plugin status indicator should change from Yellow "WAIT" to Green "OK" within
a few seconds. If it does not turn to "OK" state it means that either:
a) server name and/or fields are not set up correctly
or
b) DDE server (3rd party application) is not running or is not enabled
If indicator shows "OK" - then real time qutoes flow into AB. You can check it by
displaying Window->Real time quote. Note: since there is no backfill you would
need to wait for at least 3 bars of data to be collected before chart shows up.
How to use AmiBroker with external DDE data source
124
AmiBroker 5.80 User’s Guide
Tutorial
CONFIGURING DDE PLUGIN TO WORK WITH YOUR VENDOR
Various data vendors come use different DDE connection strings, here a few
typical exampels will be shown.
Most documentation of DDE uses Excel DDE syntax which looks as
follows:=SERVER|TOPIC!ITEM
Server is a name of the DDE server such as WINROS, IQLINK, REUTER, CQGPC, MT,
MTLink, etc.
Topic is the topic of DDE conversation. Depending on Data source topic may be
just the ticker symbol (like in IQFeed), or the field name (like in winros).
Item is the item of DDE conversation. Depending on data source it can be field
name (like in IQFeed) or ticker symbol (like in Winros).
So DDE connection string in two most common standards look as follows:
=WINROS|LAST!MSFT
=IQLINK|MSFT!LAST
Now DDE plugin configuration screen looks like this:
In the UPPER part of the dialog you can see "DDE Server" field. In this field you
should enter SERVER part of DDE connection string (=SERVER|TOPIC!ITEM) without
equation mark and without | character.
How to use AmiBroker with external DDE data source
125
AmiBroker 5.80 User’s Guide
Tutorial
Below you can see 12 text entry boxes where you can define DDE topic and item for
each data field your data source provides. Here you should enter TOPIC!ITEM pair
of the DDE connection string (=SERVER|TOPIC!ITEM) with exlamation mark between
DDE topic and DDE item.
As you can see in the picture above, DDE plugin allow you to use a few special
strings, namely: {Ticker}, {Field}, {FieldSp}, {Server}, {Id} which are evaluated
in run-time for each symbol separately allowing to construct dynamic DDE strings
(depending on selected ticker for example) required by most data sources:
• {Ticker} - evaluates to ticker symbol of given security
• {Field} - evaluates to the corresponding field name (without spaces), i.e.
Open, High, Low, Last, LastSize, Volume, Ask, AskSize, Bid, BidSize, Time,
Req
• {FieldSp} - similar to {field} but 2-word field names have spaces, namely:
"Last Size", "Ask Size", "Bid Size"
• {Server} - evaluates to server name
• {Id} - evaluates to unique ID (running counter incremented by 1 with each
symbol)
All other texts are carbon-copied, so if you write for example:
PREFIX_{Ticker }_SUFFIX!MYTEXT
it will evaluate to =SERVER|PREFIX_MSFT_SUFFIX!MYTEXT (provided that current
symbol is MSFT)
Next to field definitions we can see what given definition will evaluate to (in
Excel notation). This makes it easy to verify if definition is correct.
Sample evaluation uses always "MSFT" as a {Ticker}, and 34 as {id}.
If your data source does not provide all fields you can make given field empty.
Note that for proper operation the "Last" price (the price of last trade) is
required. If your data source does not provide "last" price (most of forex
sources don’t have "last") you can force DDE plugin to use "Bid" instead. For
that you should make "Last" field blank and provide appropriate DDE topic!item
pair in "Bid" field. Please also note that Topic!Item pairs should evaluate to
unique values.
In the top part of the dialog you can see "Preset" combo-box.
As of now it allows to pre-set the fields using two generic schemes:
a) {Field}!{Ticker} - "last price" evaluates to =SERVER|Last!MSFT
b) {Ticker}!{Field} - "last price" evaluates to =SERVER|MSFT!Last
In the future "Preset" box will contain more presets for various DDE source that
you submit.
A FEW EXAMPLES
Connection examples are shown on the web page: http://www.amibroker.com/dde.html
How to use AmiBroker with external DDE data source
126
AmiBroker 5.80 User’s Guide
Tutorial
TEST PLATFORMS
DDE plugin has been tested and it is known to work properly on Windows XP (32 bit
DDE) and Windows 9x (16 bit DDE).The following DDE servers are verified by us to
work properly:
• IQLINK (DTN)
• WINROS (eSignal)
• MT (Metaquote)
DDE plugin does NOT work with the following DDE servers:
• VTSPOT (Visual Trader) - due to improper coding in VisualTrader that causes
Microsoft DDEML library DdeConnect function to hang on the very first
connection attempt
All other DDE servers not listed above should work properly. Contact support at
amibroker.com in case of problems.
HELP US TO HELP THE OTHERS:
In order to help the others to configure DDE plugin for their data vendor, once
you succeded to link with your particular vendor please drop as a note with a
screenshot of the CONFIGURE dialog and name of the source. This will be later
included in this document as a reference how to use various data sources. Also
working setups will be added to "presets" combo for easy one-click configuration.
NOTES ON DDE PLUGIN:
1. There is NO BACKFILL in DDE plugin. You can use however ASCII importer (this
includes AmiQuote) to import historical data right into the database that you
will update later in real time using DDE plugin.
2. Change, % change fields are NOT available (yet)
3. Time and Req fields are now ignored (this may change in the future)
4. The current system time is used to timestamp each tick.
5. When your source does not offer "LAST" price (like several Forex sources) you
should make "Last" field EMPTY in the configuration dialog. This will tell the
plugin to use "BID" field instead.
6. Plugin status (connected/disconnected) always initially comes up with "Wait"
state (Yellow indicator). It means that no DDE conversation has been established.
If at least ONE DDE conversation starts successfully it will turn to "OK" state
(green indicator). If DDE server was not running at first attempt to connect, the
plugin wil NOT attempt to reconnect automatically. Instead you should force
reconnection manually (see point 7). The indicator may turn to "Disconnected"
(red indicator) only in two cases:
a) you were connected properly but DDE server (3rd party app) has been closed
How to use AmiBroker with external DDE data source
127
AmiBroker 5.80 User’s Guide
Tutorial
b) you selected "shutdown" from plugin status menu
7. You can reconnect at any time by selecting "reconnect" from plugin status
menu.
How to use AmiBroker with external DDE data source
128
AmiBroker 5.80 User’s Guide
Tutorial
How to work with Real-Time data plugins
One-time setup
In order to use AmiBroker with any real-time data source you have to set up the
database with appropriate data plug-in first. This is required only once at the
database creation time. Instructions for setting up are available here: eSignal,
myTrack, IQFeed, QuoteTracker.
Check also on-line data sources page at http://www.amibroker.com/quotes.html for
new plugins.
Adding symbols
Now you can add symbols to your database. To do so please go to Symbol->New menu.
In the add symbol dialog enter one or more tickers (comma separated) you wish to
add to your database. If you want to see the chart for newly added symbol just
select it from the Symbol tree in the workspace window. Please allow few seconds
(depending on the speed of your internet connection) to backfill historical data.
You may add more tickers that your RT account allows. AmiBroker will
automatically switch/update/refresh symbols so the most recently used symbols are
active and older ones are automatically removed from Data manager. Doing so
however may lead to some problems if you exceed your subscription limits too
much. So it is advised to use this feature responsibly and not expecting getting
500 symbols while your subscription is limited to only 50.
Note that the above mechanism does not apply to real time quote window and it can
not hold more symbols than your subscription limit.
Showing real time quote window
AmiBroker RT features real-time watch window that allows
you to watch streaming quotes. To show this window choose
Window->Realtime Quote menu. (see image to the right ---->)
To add symbols to Realtime quote window you either double
click on the symbol tree or use right mouse button menu Add
to Realtime quote option as shown in the picture above.
How to work with Real-Time data plugins
129
AmiBroker 5.80 User’s Guide
Tutorial
Working with real time quote window
The RT quote window provides real-time streaming quotes and some basic
fundamental data. It is fairly easy to operate as shown in the picture below:
How to work with Real-Time data plugins
130
AmiBroker 5.80 User’s Guide
Tutorial
You can also display context menu by pressing RIGHT mouse button over RT quote
window.
How to work with Real-Time data plugins
131
AmiBroker 5.80 User’s Guide
Tutorial
The context menu allows you to access the following options:
• Time & Sales
Opens Time & Sales window that provides information about every bid, ask
and trade streaming from the market.
• Easy Alerts
Opens Easy Alerts window that provides way to define realtime alerts
executed when bid/ask/last and other fields hit user-defined levels
• Add Symbol
Adds current symbol to Real-Time Quote list
• Add watch list...
Adds entire watch list to real-time quote window
• Remove Symbol
Removes highlighted line (symbol) from the Real-Time Quote list.
• Remove All
Removes all symbols from real-time quote list
• Hide
Hides Real-Time Quote list
Working with intraday and daily charts
If your data source supports mixed EOD/Intraday mode (such as eSignal or IQFeed)
you can use single database for both types of charts.
However if your data source does not support mixed EOD/Intraday mode and if you
want to have long daily histories AND intraday charts you should consider running
TWO instances of AmiBroker. One for EOD charts and second for intraday charting.
Both may use the same real-time data source.
Connection status display
The data plug-in connection status is displayed in the plugin status display area
located in the lower right part of the AmiBroker main window as shown in the
picture below. When connection status changes AmiBroker plays a beep sound and
How to work with Real-Time data plugins
132
AmiBroker 5.80 User’s Guide
Tutorial
pops up bubble tool tip to inform about status change.
The bubble tip provides more detailed information text and disappears
automatically after 2 seconds.
If you want to re-display it just hover your mouse over plugin status display
area.
To enable quick examination of connection status AmiBroker displays color coded
information:
• OK (green light) means that connection is OK and indicates correct
operation of the plugin
• WAIT (yellow light) means that connection is being set-up right now or the
plugin is connected only partially (to few of many servers). Usually this
state is transient and within few seconds the status comes back to "OK".
• ERR (red light) means that connection is broken. It may mean invalid user
name/password for your subscription, or the fact that some 3rd party
component / program required is not running (for example if QuoteTracker is
not running and you are using QuoteTracker plugin). This state usually
requires some user intervention such as checking/fixing user/password in
File->Database Settings->Configure or running required component. When you
fix the reason the plugin will automatically attempt to reconnect (and if
reconnect is successfull then "OK" will be displayed)
• SHUT (purple light) means that some serious problem occurred and the plugin
will not attempt to reconnect automatically. In most cases you have to
first fix the problem that caused this state and then reconnect manually
using plugin context menu described below. Alternativelly you can just
restart AmiBroker.
Using plugin context menu
Real time plugins provide some additional controls via plugin context menu. This
context menu is available when you click with RIGHT mouse button over plugin
status display area. If you do, the menu like this will be displayed:
How to work with Real-Time data plugins
133
AmiBroker 5.80 User’s Guide
Tutorial
Please note that various plugins offer various options in this menu, however most
plugins provide at least 3 basic and useful options:
• Reconnect - this option allows you to reconnect manually. Most RT plugins
attempt to reconnect automatically, but sometimes manual reconnect is
necessary.
• Shutdown (Disconnect) - this allows to shutdown RT plugin. This is useful
when you want to stop streaming of quotes.
• Force backfill - this option causes that plugin re-downloads entire
(intraday) history from the server. Usually the plugin automatically
handles all backfills so you don’t need to trigger backfills by hand. If
the plugin detects that you have some missing quotes from last available
bar till current date/time it triggers backfills and it is all automatic.
But... in at least two cases this option is useful:
♦ backfilling more bars after settings change (when you enlarge ’number
of bars to load’ in File->Database Settings dialog you have to force
backfill for symbols that were backfilled previously with smaller
number of bars)
♦ cleaning up bad ticks (when you see a bad tick you may try forcing
backfill in hope that data vendor has cleaned up its database and you
will get fixed data - works well for eSignal that really appears to
fix bad ticks after they happen)
Things you should NOT do, or you should do very carefully
You should note the fact that when you are using data plugin then the plugin
controls the quotation database (see Understanding database concepts article),
therefore you should NOT import quotes from ASCII files (this includes AmiQuote)
for symbols that are already present in the real-time database.
If you do, the plugin will eventually overwrite your imports with the real-time
data or your database will become corrupted (if you import end-of-day data over
intraday database).
So please do not import ASCII (especially EOD data) into real-time intraday
database fed by the plugin.
You may ask: why this is not disabled at all. The answer is that sometimes it is
useful and sometimes it will work (but these are rare cases). For example it will
work if you import INTRADAY data into the intraday database fed by QuoteTracker
plugin and both the database and imported data have exactly the same bar
interval.
It also works if you import the data for symbols that are NOT present in the
database. In this case newly imported symbols are marked by ASCII importer as
How to work with Real-Time data plugins
134
AmiBroker 5.80 User’s Guide
Tutorial
"use only local database for this symbol" (See Information window for details),
so they are EXCLUDED from the real-time update. This is useful if you want to
import some other data (even not quote data) and access it via Foreign function
while using your real-time database.
So ASCII import is not disabled in real-time database but you have to use it with
extreme care and know what you are doing.
Second thing is using Quote Editor. Although data are controlled by the plugin it
is in most cases possible to use Quote Editor. However please note that you will
be able to edit only 1-minute data or higher interval, and you will be able only
to edit symbols that are backfilled completely (there is no running backfill for
the particular symbol) and you will NOT be able to edit last three bars. This is
so because last three bars are cached in the plugin. So you will be able to edit
them only when new bars arrive making them ’older’ than last three.
’WAIT FOR BACKFILL’ feature
The users of eSignal, myTrack and IQFeed real-time plugins may now check "wait
for backfill" box in the Automatic analysis window and all scans, explorations
and backfills will wait for completion of backfill process for given symbol. This
flag has no effect on databases that do not use plugins (external data sources)
or use end-of-day plugins (like FastTrack, QP2, TC2000/TCNet, etc). This flag has
also no effect when using QT plugin due to the fact that QuoteTracker manages
backfills by itself and does not provide any control of backfill process to 3rd
party applications.
How to work with Real-Time data plugins
135
AmiBroker 5.80 User’s Guide
Tutorial
How to use AmiBroker with external data source (Quotes
Plus, TC2000/TCNet/TC2005, FastTrack, Metastock)
One of the new features introduced in AmiBroker version 3.90 is the ability to
read directly external databases. This is achieved by means of data plug-in DLLs
that allow to link AmiBroker database with an external source. Please note that
althrough you will be using external database, you will still need an AmiBroker
database for storing additional information that is not supported by the external
source like hand-drawn studies, assignments to groups, watch lists, composites
and so on. You can find more information on AmiBroker database handling here.
One-time setup
To use an external data source with AmiBroker you will need to perform a one-time
setup described below:
• Run AmiBroker
• Choose File->New database
• Type a new folder name (for example: C:\Program Files\AmiBroker\NewData )
and click Create as shown in the picture below:
• Choose appropriate entry from Data source combo:
♦ Quotes Plus users select "Quotes Plus plug-in" as a Data Source and
"Disable" from Local data storage
♦ TC2000/TCNet users select "TC2000/TCNet plug-in" as a Data Source and
"Enable" from Local data storage
♦ TC2000 for Mutual Funds users select "TC2000 Mutual Funds plug-in" as
a Data Source and "Enable" from Local data storage
How to use AmiBroker with external data source (Quotes Plus, TC2000/TCNet/TC2005, FastTrack,
136Metasto
AmiBroker 5.80 User’s Guide
Tutorial
♦ TC2005 users select "TC2000/TCNet plug-in" as a Data Source and
"Enable" from Local data storage
Note: TC2005 users may need to follow these instructions (click here)
if TC2000 plugin does not show up.
♦ FastTrack users select "FastTrack plug-in" as a Data Source and
"Disabled" from Local data storage
♦ Metastock users select "Metastock plug-in" as a Data Source and
"Disable" from Local data storage
• Click on Configure button to show plugin configuration dialog as shown
below
• Metastock plug-in only (skip this point in case of TC2000, Quotes Plus,
FastTrack ):
Click on the "Add folder" button to add Metastock database directory as
your data source (browse for Metastock MASTER file and click OK) as shown
below:
How to use AmiBroker with external data source (Quotes Plus, TC2000/TCNet/TC2005, FastTrack,
137Metasto
AmiBroker 5.80 User’s Guide
Tutorial
- you can add unlimited number of Metastock directories effectivelly
overcoming MS 4096 symbols limitation.
• Click Retrieve button - this will setup a new database with all symbols and
full names. Quotes Plus and TC2000 plugins will also setup your
sectors/industries names and assignments, as shown below (in case of Quotes
Plus plugin):
From now on your AmiBroker reads quotes directly from the external data source.
No need to import/update quotes anymore. All new quotes will appear automatically
without user intervention.
IMPORTANT: If there are new symbols added or old symbols deleted to/from the
external data source, you will need to go to File->Database Settings->Configure
and click "RETRIEVE" again to get new symbols.
Plug in performance notes
Using AmiBroker native database gives absolutely the best performance (it takes
less than 2 milliseconds to retrieve 1000 data bars).
Metastock plugin is also quite fast, as it can retireve 1000 bars in about 6-7
milliseconds (including looking up for symbol in 5 different directories). In
fact AmiBroker can access Metastock data faster than Metastock itself :-)
How to use AmiBroker with external data source (QuotesPlus, TC2000/TCNet/TC2005, FastTrack,
138Metastoc
AmiBroker 5.80 User’s Guide
Tutorial
Quotes Plus performance depends on various factors - first access can be much
slower (0.1-0.2 sec for 1000 bars) but subsequent accesses are faster (downto 5
milliseconds). FastTrack plugin is as fast as Quotes Plus plugin.
TC2000 is not as fast, especially if you are using data only on CD. So it is
advised to copy your database to hard disk for better performance. But still,
even when using CD-only data, AmiBroker ca access 1000 bars from TC2000 in about
0.25 sec (first access) and 0.015 sec (subsequent accesses). Also it is advised
to enable "Local data storage" when using TC2000 plugin because it gives
tremendous (>10 times) speed-up (once you access the TC2000 data, AmiBroker
caches them in its own native database for fast retrieval).
Times are approximate and do not include one-time plug-in initialization process.
Measurements where done on fairly low-end Celeron 600 based computer with 196KB
RAM and 24x CD-ROM
In-memory caching
By default AmiBroker holds only 10 the most recently accessed symbols’ data in
RAM. This takes up about 320 KB (yes, kilobytes) of memory for 1000 bars per
symbol loaded. You can enlarge "In memory cache" (Tools->Preferences : "Data"
tab) to 100 (approx. 3.2MB additional RAM consumption ) or 1000 (approx. 32MB
additional RAM consumption) or even more to get much better performance for
subsequent data access (once data are in RAM AmiBroker does not need to ask
plugin again and again)
How to use AmiBroker with external data source (QuotesPlus, TC2000/TCNet/TC2005, FastTrack,
139Metastoc
AmiBroker 5.80 User’s Guide
Tutorial
How to update US quotes automatically using AmiQuote
QUICK START
Run AmiBroker
Choose Tools->Auto-update quotes (US & Canada)
HOW IT WORKS
AmiQuote loads (or retrieves from AmiBroker) a ticker list file (.TLS) which is
simple ASCII file with ticker symbols, then parses it and generates URLs to the
Yahoo! finance site based on ticker name, mode (current quotes or historical),
country and From/To date. Then, when you start the download process, it requests
the data from Yahoo and stores downloaded data in the separate .AQD (daily) or
.AQH (historical) files for each ticker. After download, if AmiBroker is running,
AmiQuote will import the quotes into AmiBroker automaticaly.
USAGE
Automatic update
The easiest method to work with AmiQuote and AmiBroker is to use the procedure
given in Quick Start section of this document. Just run AmiBroker and AmiQuote
and choose Tools->Auto-update AmiBroker database. This method updates historical
quotes from the last date present in AmiBroker upto today. When performing
automatic update, AmiQuote performs internally 4 steps a) retrieves the ticker
list from AmiBroker (all symbols loaded currently in AmiBroker);
b) gets the last quotation date available in AmiBroker;
c) performs historical download from last date upto today;
d) instructs AmiBroker to import downloaded files.
Please note that this procedure works only for US & Canada markets, because Yahoo
provides historical quotes only for that markets.
Note that AmiQuote currently supports a new command line parameter: /autoupdate.
This option forces AmiQuote to perform automatic update procedure without user
intervention.
By default AmiBroker’s Tools menu is configured as follows:
C:\Program Files\AmiBroker\AmiQuote\Quote.EXE /autoupdate
So, you are able to update your US database with a single click on
Tools->Auto-update quotes (US & Canada) in AmiBroker
Manual operation
Automatic mode is nice but there are cases when you have to perform some tasks
manually. There is a good old document describing that mode of operation at: How
to download quotes manually using AmiQuote . Everything written in this document
remains valid with one exception - now importing to AmiBroker are performed
How to update US quotes automatically using AmiQuote
140
AmiBroker 5.80 User’s Guide
Tutorial
automatically if you have Automatic import checkbox marked.
There are also several cases when you prefer to do things manualy, then please
don’t forget about some useful tools available at your fingertips:
File->Open, File->Save, File->Save As
These functions enable you to load and save your edited ticker lists
for future repeated use.
Edit->Add tickers
This function allows you to add the tickers to the list. Just type
space separated tickers into the field that will show up when you
choose this function.
Edit->Delete tickers
This function allows you to delete tickers from the list. Just select
the items you want to delete from the list view (multiple selection
possible by holding SHIFT or CTRL key while clicking on items), and
choose this function.
Edit->Mark all, Edit->Unmark all, Edit->Toggle, Edit->Mark selection,
Edit->Unmark selection
These functions allow you to mark the tickers for download. Please
note that AmiQuote puts a checkmark before ticker name in the list
view. ONLY MARKED items will be downloaded. This allows you to
perform selective downloads/updates.
View->Refresh
Basically AmiQuote handles refreshes by itself when needed. For
example if you changed the date range, the list will be refreshed
before starting download. But there are some cases when you may want
to refresh the list by yourself. For example if you downloaded and
imported quotes once and want to do this again you would need to
choose this function. The Refresh function simply applies all date
and type settings to the URLs listed, and MARKS all tickers for a new
download.
Tools->Import into AmiBroker
This function is useful if you want to import just downloaded quotes
into AmiBroker but you have Automatic import checkbox cleared.
Tools->Get tickers from AmiBroker
This function retrieves all symbols from currently loaded AmiBroker
database and fills the AmiQuote ticker list with them.
How to update US quotes automatically using AmiQuote
141
AmiBroker 5.80 User’s Guide
Tutorial
Tools->Get last update date
This function retrieves the date of the most recent quotation of the
first symbol present in currently loaded AmiBroker database and sets
the From date to this date.
Tools->Settings
Displays the settings window where you can define the destination
directory where all downloads are stored. Note that blank destination
directory means that downloads will be stored in the current working
directory (in most cases this is the folder from where current .TLS
file was loaded).
In this window you can also change the mode of writing the files. By
default historical files are overwritten while daily files get
appended. This is recommended setup. Appending daily files simply
allows you to create intra-day historical files when you do the
updates daily. You may change this behaviour for your particular
purpose.
How to update US quotes automatically using AmiQuote
142
AmiBroker 5.80 User’s Guide
Tutorial
How to download quotes manually using AmiQuote
Introduction
The purpose of this document is to explain how to use AmiQuote and AmiBroker in
order to obtain quotes from Yahoo finance and Quote.com sites. AmiQuote is a
companion program to AmiBroker charting/analysis software. The main purpose of
AmiQuote is to simplify and automate downloading daily and historical quotation
data from free Yahoo! Finance (USA, major European exchanges and some other
countries), Quote.com (USA only) sites, MSN (USA and some European exchanges),
Integratir (US stocks), Forex (Finam free site)
Yahoo provides data in "Historical" and "Current" modes of AmiQuote. Quote.com
provides data in "Intraday" mode of AmiQuote.
Preparing ticker list
A ticker list is a simple text file which lists line by line the tickers you want
to import. The AmiQuote ticker list file has .TLS extension. AmiQuote comes with
pre-written ticker list for components of main NYSE and NASDAQ indices and a
number of European indices/markets. Additional ticker lists are available on the
starter page at: http://www.amibroker.com/starter/. You can use those pre-written
ticker lists or you can customize them or write your own one. In order to edit
existing .TLS file or write completely new one all you need is plain text editor
such as Notepad or any other plain ASCII editor (not MS Word!). All you have to
do is to write tickers you want to import line by line (single ticker in single
line) and save the file. Please make sure that you are saving the file with .TLS
extension. Otherwise AmiQuote will not load this file.
Please note that Yahoo uses suffixes for non-US stocks. So in order to get quotes
for non-US symbol you would need to add appropriate suffix to the ticker symbol.
The suffixes in alphabetical order are (you can click on link to get the symbol
list for each exchange) : .AS - Amsterdam, .AX - Australia (ASX), .BC Barcelona, .BE - Berlin, .BO - Bombay, .BM - Breman, .BR - Brussels, .BA - Buenos
Aires, .CL - Calcuta, .CR - Caracas, .V - CDNX, .CO - Copenhagen, .D Dusseldorf, .F - Frankfurt, .H - Hamburg, .HA - Hanover, .HK - Hong Kong, .I Ireland, .JK - Jakarta, .KA - Karachi, .KQ - Kosdaq, .KS - KSE, .KL - Kuala
Lumpur, .L - London, .LM - Lima, .LS - Lisbon, .MA - Madrid, .MX - Mexico, .MI Milan, .MU - Munich, .NS - NSE, .NZ - New Zeland, .OL - Oslo, .PA - Paris , .SN Santiago, .SS - Shanghai, .SZ Shenzhen, .ST - Stockholm, .SG - Stutgart, .TW Taiwan, .TA - Tel Aviv, .TO - Toronto, .VA - Valencia, .VI - Viena, .DE - XETRA,
.S - Zurich.
Please note that also Yahoo and Quote.com use different symbols for indices. The
main difference is that Yahoo uses ^ (dash) prefix and Quote.com uses $ (dollar)
prefix.
For list of indices provided by Yahoo please click here.
For list of indices provided by Lycos/Quote.com please click here. Please note
that recently Lycos/Quote.com stopped delivering free quotes and you need to have
How to download quotes manually using AmiQuote
143
AmiBroker 5.80 User’s Guide
Tutorial
Livecharts subcription ($9.95/month) in order to use it. For more details see
this Knowledge Base article.
For list of symbols provided by MSN please click here.
Downloading data
In order to download the data please launch AmiQuote.
Then please click on "Open" button in the toolbar (or
choose File->Open menu) as shown in picture on the
right.
From the file dialog please choose one .TLS file (for
example DIJA.TLS) and click Open button. The you will
see the main screen of AmiQuote filled with the list
of tickers loaded, as show in picture below.
Choose appropriate Data Source
- Yahoo Historical - allows you to download end-of-day histories upto current day
(current day data appear few hours after session end)
- Yahoo Current - allows you to download current day quotes (15-min delayed)
during the trading session
- Lycos/Quote.com Intraday - allows you to download intraday and daily historical
data (1-min bars and up) - for US stocks/futures only. If you have choosen this
mode you should also select the bar interval (see the limitations described
below) - need Livecharts subscription ($9.95/month)
- MSN Historical - allows you to download end-of-day histories upto current day
(current day data appear few hours after session end)
- Forex - allows you to download end-of-day and intraday (registered version)
histories for the following currency pairs: EURCHF, EURGBP, EURJPY, EURUSD,
GBPUSD, USDCHF, USDJPY
After choosing correct options please click on green arrow (or use File -> Start
Download menu). The download process will begin. AmiQuote will display progress
messages and status information including number of completed downloads and
number of files left. At anytime you can stop download process with "Stop" button
How to download quotes manually using AmiQuote
144
AmiBroker 5.80 User’s Guide
Tutorial
(red box). After finishing the download AmiQuote will automatically update the
quotes in AmiBroker (if only AmiBroker is running in parallel and "automatic
import" box in AmiQuote is checked.
Limitations
Intraday interval bar data (1-min, 5-min, 15-min, 60-min and 120-min) are
available for US securities only. Historical data for international exchanges are
usually much shorter than for US markets.
Because intraday bar data are downloaded from Quote.com servers the ticker
symbols for indices are different than those used by Yahoo. For complete
reference please check
http://finance.lycos.com/home/misc/symbol_search.asp?options=i
Intraday bar data are limited to 500 bars regardless of bar interval. In other
words you always get 500 bars data, whenever these are 1-min, 5-min, 15-min,
60-min or 120-min data - so by choosing bigger interval you get data from more
days. This is the limitation imposed by Livecharts server.
Importing quotes into AmiBroker
NOTE: This step is no longer necessary if you are using "automatic import"
feature of AmiQuote. The explanations are provided only for users wanting to
import selectively or re-import files downloaded in the past.
First, please launch AmiBroker. From the File menu please select Import From
ASCII option. You will see the following file dialog:
How to download quotes manually using AmiQuote
145
AmiBroker 5.80 User’s Guide
Tutorial
In this picture I marked the most important items for easy identification. Marked
with red is type selector combo-box ("Files of type"). In order to import
AmiQuote files (those with .AQH and .AQD extensions you should choose AmiQuote
Historical or AmiQuote Daily, or AmiQuote Intraday (.AQI) or AmiQuote MSN (.AQM)
or AmiQuote eSignalCentral (.AQE) from the combo box (red arrow shows those
options).
After choosing right type you will see only files of appropriate type in the file
list (blue arrow shows that). Now you can select one or more files from the list.
Multiple selection is possible by holding CTRL key depressed while selecting the
items with a mouse (you can also press SHIFT for choosing a range of files with a
single click). Now when you are done choosing the files you want to import just
click "Open" button. The import process will start and you will see progress bar
showing the AmiBroker is importing the data. After finishing the import AmiBroker
will automatically refresh symbol list and you will see updated tickers and
charts. If anything goes wrong with the import process AmiBroker writes a log
file called "import.log" and located in AmiBroker’s main directory. You can watch
this log file if you want to find out what went wrong (since import.log is simple
text file you can open it with any text editor)
Common questions
Question
How can I
edit my own
ticker list
(.TLS) file?
Answer
You can create or edit .TLS using Windows Notepad. When saving a
file simply give .TLS extension to the file (instead of the
default. TXT)
There are following ready-to-use ticker lists available for
download:
What about
ready-to-use
complete
ticker lists
for NYSE,
NASDAQ, AMEX?
•
•
•
•
•
•
•
DJIA.TLS (30 stocks)
DJTA.TLS (20 stocks)
DJUA.TLS (15 stocks)
NASDAQ100.TLS (100 stocks)
NYSE.TLS (2612 stocks)
NASDAQ.TLS (4464 stocks)
AMEX.TLS (794 stocks)
Further information
For further information please consult AmiBroker User’s Guide section "Data
management - Importing data from ASCII file". In case of any further questions,
comments and suggestions please contact me at: [email protected]
How to download quotes manually using AmiQuote
146
AmiBroker 5.80 User’s Guide
Tutorial
Metastock importer window
IMPORTANT NOTE: Metastock importer should be used ONLY if you want to import MS
data to native, local AmiBroker database once. If you want AmiBroker to just read
Metastock database DIRECTLY without need to import new data over and over please
set up your database WITH METASTOCK PLUGIN as described in the Tutorial.
NOTE 2: if you setup your database with the MS plugin you should NOT use
Metastock importer, because there is no point in using it when your data are
already fed by the plugin.
Metastock importer opens AmiBroker to very rich source of historical data. The
importer supports both old Metastock 6.5 and new 7.x (XMASTER) formats.
Basically Metastock data consist of:
• MASTER/EMASTER file which holds general information about the tickers,
stock names, etc.
• F1.DAT....Fxx.DAT files which hold actual quotation data
The MASTER/EMASTER file is essential because it holds the references to Fxx.DAT
files. Fxx.DAT files store only quotations in either 5 field
(date/high/low/close/volume), 6 or 7 field
(date/open/high/low/close/volume/openinterest) format. As you see MASTER/EMASTER
and Fxx.DAT files are closely connected and you need them all to import the data.
Usage
To import Metastock data you should do the following:
• Choose Metastock import from the menu
• Using the directory requester (Browse...) select the location of data in
Metastock format (the directory with MASTER/EMASTER and Fxx.DAT files)
• After choosing proper directory AmiBroker will display the list of
Metastock importer window
147
AmiBroker 5.80 User’s Guide
Tutorial
available symbols and date ranges. By default all available symbol will be
marked for importing (checkmark at the beginning of the list). Now you can
exclude some symbol from the import list by clicking appropriate item in
the list (checkmark will toggle when you click).
• You can decide to which group and watch list the new symbols are added
using Group and Watch List combos.
• After making your selections push ’Import’ button to start the process of
importation.
• During the process you can cancel the operation by clicking ’Abort’ button
in the progress window
Metastock importer window
148
AmiBroker 5.80 User’s Guide
Tutorial
Understanding AmiBroker database concepts
Background
A typical Windows application, for example, Paint, works with a SINGLE file. You
just open and save that single file (.BMP in Paint, or .DOC in MS WORD), and that
file holds all the necessary information.
AmiBroker is a more complex piece of software. It uses huge amounts of data (all
quotes from different tickers, hand drawn studies, assignments to groups,
markets, watch lists, favorites, industries, sectors, etc.), so it must manage
multiple files.
It would actually be possible to save all this information in a single file, but
it would be (a) huge, and (b) slow to update selectively. So AmiBroker uses
multiple files for storing all the data. There are a lot of files associated with
any database. The files for a particular database are stored in a directory (and
its subdirectories) specific to that database. In AmiBroker documentation, such a
directory is referred to either as a "database directory" (versions 3.9 or later)
or as a "workspace directory" (earlier AmiBroker versions).
When you install AmiBroker for the first time, a default database directory is
created, called ’data’, in the AmiBroker directory. This database directory
contains a sample Dow Jones Industrial Average database.
In AmiBroker database menu and dialog selections, you are choosing or creating a
database directory, not an individual file.
AmiBroker database structure
A database (or a workspace) is a directory that holds a set of binary files,
which are stored in 0-9, a-z, ’_’ subdirectories. Those binary files hold quotes,
symbol information, your studies (trend lines, Fibonacci stuff). Each symbol’s
information is stored separately in the file with the name of the ticker symbol
located in the subdirectory corresponding to the first character of the symbol,
so IBM quotation data/studies are stored in the ’IBM’ file located in the ’I’
subdirectory.
The default database for AB is the ’data’ directory. It contains DJIA sample
data. You may create additional databases in other directories via the File->’New
database’ menu.
In addition to these subdirectories and files, two additional files are also
created by AmiBroker: broker.workspace and broker.master. The first is used to
store category names and information about advancing/declining/unchanged issues.
The latter stores the table of all symbols that is used for quick loading of the
database. These two files are located in the root directory of each database, the
’data’ directory, by default.
In almost all cases, you should NOT touch files in an AmiBroker database, as the
program manages them automatically, and no user intervention is required.
Understanding AmiBroker database concepts
149
AmiBroker 5.80 User’s Guide
Tutorial
What about the external data?
AmiBroker 3.9 has the ability to read quotes DIRECTLY from an external data
source. Currently, AmiBroker can read directly from Quotes Plus (QP2), TC2000
(TC2K) and Metastock (MS) databases. This is achieved by means of data plug-ins
that AmiBroker uses to read the data from an external data source. When a user
decides that she/he wants to use an external database - AmiBroker - instead of
reading the quotes from its own database - just asks the plug-in for quotes for
any given symbol. The plug-in reads the external database and feeds the data to
AmiBroker. The whole process is shown in the picture below:
As you can see, data plug-ins provide read-only access to the quotes in the
external database. This means that your external data sources are never modified
by AmiBroker. Changes or additions that you make to data and charts (like hand
drawn studies, assignments to categories, etc.) are always saved in AmiBroker’s
own database. So AmiBroker still uses its own database (to save changes, as a
cache to speed up access, and for other tasks), even when using an external data
source.
The Data source switch represented in the graphic above can be set by the user to
access various external databases. External data sources are selected by going to
the File->’Database settings’ dialog, shown below:
What about the external data?
150
AmiBroker 5.80 User’s Guide
Tutorial
You may also choose to store the quotes retrieved from the external source to
AmiBroker’s own database for faster retrieval in subsequent accesses. If you want
to do this, you should switch the ’Local data storage’ setting to ’Enabled’.
Note: Similar settings can be found in the Tools->Preferences ’Data’ tab, but
these are only defaults used when creating new databases. File->Database Settings
configurations always take precedence over those done in Preferences -- EXCEPT in
the following cases: If you choose the ’Default’ entry in the Data Source drop
down list (shown above), or the ’Default’ radio button for Local Data Storage
(also shown above), AmiBroker will use your Preferences settings for those items.
What about the external data?
151
AmiBroker 5.80 User’s Guide
Tutorial
Understanding categories
AmiBroker has an ability to assign symbols to different categories allowing you
(when properly set up) to narrow your analysis searches to the symbols meeting
certain selection criteria (thanks to Filter feature available in Quick Review
and Automatic Analysis windows). The initial set up of categories may be a little
bit complicated especially when you want to track several thousands symbols.
Categories show up in Symbols
window. First and foremost
thing to remember is categories
do NOT work like folders and
Workspace window does NOT work
like Windows Explorer.
The difference is fundamental.
In the Windows Explorer file
appears (usually) only once in
the given tree leaf.
In the symbol tree given symbol
shows up multiple times because
it appears in every category
leaf to which it belongs to
even if this is the same symbol
and only it exists only as
single entity.
Symbols window is divided into
three parts:
a) search box
b) category tree
c) symbol list
The search box allows to
perform full text searches
(including wildcard matching)
against symbol and full name
within selected category. So
for example if you select
"Technology" sector and type A*
(letter ’A’ and wildcard
character *) the symbol list
will show all symbols belonging
to Technology sector with
symbol or full name beginning
with letter ’A’. Another
example would be tping *-A0-FX
- this will return all forex
symbols on eSignal database
(those ending with -A0-FX
substring).
Understanding categories
152
AmiBroker 5.80 User’s Guide
Tutorial
The category tree (see the
picture) shows different kind
of categories.
The symbol list (bottom part)
shows the list of symbols
belonging to selected category.
The symbol list can be sorted
by symbol or by full name. To
sort just click on the header
row of the list. Once you
choose desired sorting order it
will be kept for all subsequent
category choices and searches.
Also the order of columns can
be changed so Full name column
appears as first one. To
re-arrange column, click on the
column header, hold down the
moust button and drag the
column to desired location.
Then release mouse button.
Single symbol belongs to MANY
categories at the same time.
For example AAPL (Apple Inc.)
will belong to:
• Stocks group category
• Nasdaq market category
• Information sector
category
• Comp-Computer Mfg
industry category
and may also belong to several
watch lists and favorites
category. All at the same time.
That’s why one symbol will
appear in many leaves of the
workspace symbol tree. Now if
you delete the SYMBOL it will
of course disappear from ALL
categories because you have
deleted the symbol itself, not
its assignment to category.
There are two types of categories:
Understanding categories
153
AmiBroker 5.80 User’s Guide
Tutorial
1. with mutualy exclusive membership: groups, markets, sectors/industries,
GICS - it means that symbol must belong to single group, single market and
single sector/industry at a time. You can move the symbol from one
group/market/sector/industry to another but you can not remove this
assignment - you should create "Unassigned" group/market/sector/industry
instead and move ’unassigned’ symbols there.
2. with free membership: watch lists/favorites/indexes- it means that a symbol
may belong to ANY number (including zero) of watch lists (and to
favorite/index category too). In this case you can remove this assignment
by Watch List->Remove
Watch lists are covered in detail in the User’s Guide: Tutorial: Working
with Watch Lists.
There is also one special category called "ALL" that shows up in the workspace
symbol tree. It simply lists ALL symbols present in the database.
Working with sectors and industries
Basics - predefined sectors and industries
Now we will focus on setting up sectors and industries and assigning the symbols
to them. First let me discuss some basic ideas.
AmiBroker comes with an example Dow Jones Industrials database holding all 30
components of this world’s most famous market average. They are assigned to
predefined sectors and industries. These sectors and industries are exactly the
same as used on Yahoo finance site and here is a table which shows them all:
Sector
Industry
Chemical Manufacturing
Chemicals - Plastics & Rubber
Containers & Packaging
Fabricated Plastic & Rubber
Basic Materials (0)
Forestry & Wood Products
Gold & Silver
Iron & Steel
Metal Mining
Misc. Fabricated Products
Non-Metallic Mining
Paper & Paper Products
Aerospace & Defense
Constr. - Supplies & Fixtures
Capital Goods (1)
Constr. & Agric. Machinery
Construction - Raw Materials
Working with sectors and industries
154
AmiBroker 5.80 User’s Guide
Tutorial
Construction Services
Misc. Capital Goods
Mobile Homes & RVs
Conglomerates (2)
Conglomerates
Apparel/Accessories
Appliance & Tool
Audio & Video Equipment
Auto & Truck Manufacturers
Consumer Cyclical (3)
Auto & Truck Parts
Footwear
Furniture & Fixtures
Jewelry & Silverware
Photography
Recreational Products
Textiles - Non Apparel
Tires
Beverages (Alcoholic)
Beverages (Non-Alcoholic)
Consumer/Non-Cyclical (4)
Crops
Fish/Livestock
Food Processing
Office Supplies
Personal & Household Prods.
Tobacco
Coal
Energy (5)
Oil & Gas - Integrated
Oil & Gas Operations
Oil Well Services & Equipment
Consumer Financial Services
Insurance (Accident & Health)
Insurance (Life)
Financial (6)
Insurance (Miscellaneous)
Insurance (Prop. & Casualty)
Investment Services
Misc. Financial Services
Money Center Banks
Regional Banks
Working with sectors and industries
155
AmiBroker 5.80 User’s Guide
Tutorial
S&Ls/Savings Banks
Biotechnology & Drugs
Healthcare (7)
Healthcare Facilities
Major Drugs
Medical Equipment & Supplies
Advertising
Broadcasting & Cable TV
Business Services
Casinos & Gaming
Communications Services
Hotels & Motels
Motion Pictures
Personal Services
Printing & Publishing
Services (8)
Printing Services
Real Estate Operations
Recreational Activities
Rental & Leasing
Restaurants
Retail (Apparel)
Retail (Catalog & Mail Order)
Retail (Department & Discount)
Retail (Drugs)
Retail (Grocery)
Retail (Home Improvement)
Retail (Specialty)
Retail (Technology)
Schools
Security Systems & Services
Waste Management Services
Communications Equipment
Computer Hardware
Computer Networks
Computer Peripherals
Technology (9)
Computer Services
Computer Storage Devices
Electronic Instruments & Controls
Working with sectors and industries
156
AmiBroker 5.80 User’s Guide
Tutorial
Office Equipment
Scientific & Technical Instr.
Semiconductors
Software & Programming
Air Courier
Airline
Transportation (10)
Misc. Transportation
Railroads
Trucking
Water Transportation
Electric Utilities
Utilities (11)
Natural Gas Utilities
Water Utilities
It is important to understand the difference between a sector and an industry:
industries "belong" to sectors, for example: "Air Courier", "Airline",
"Railroads", "Trucking" industries belong to "Transportation" sector. So if a
symbol is assigned to given industry, it is "automatically" assigned also to the
corresponding sector.
In the example DJIA database each stock is assigned to specific industry, for
example GM (General Motors) is assigned to "Auto & Truck Manufacturers" industry,
and this implicates that GM belongs to "Consumer/Cyclical" sector.
AmiBroker can handle up to 32 sectors and up to 256 industries.
How to assign symbol to the industry?
You can change the industry to which given symbol is assigned by using
Window->Information dialog (Industry combo box)
Working with sectors and industries
157
AmiBroker 5.80 User’s Guide
Tutorial
or using Symbol->Organize Assignments.
The first method is fine if you want to change single symbol settings. The latter
is better if you want to move multiple symbols from one category to another.
Working with sectors and industries
158
AmiBroker 5.80 User’s Guide
Tutorial
How to define your own sectors and industries
Please go to Symbol->Categories dialog, the last two tabs are "Sectors" and
"Industries". First, switch to the "Sectors" tab and you will see the list of 32
sector names. You can now select the sector by clicking once on its name and edit
the sector name by pressing ENTER or clicking "Edit name" button. Hit ENTER again
to accept the name change.
After you renamed the sectors you can switch to the "Industries" tab. Similarly
to the previous tab you can select the industry in the list and edit its name in
the same manner. Here you can also assign the industry to the sector using
"Sector" combo. Just select the sector to which you want to assign currently
selected industry.
Working with sectors and industries
159
AmiBroker 5.80 User’s Guide
Tutorial
Where sector and industry information is stored?
Generally speaking this information is stored in AmiBroker database. The sector
and industry names and settings are stored in the broker.workspace file (in the
workspace folder), symbol data files hold only the information about the
assignment of the symbol to given industry (IndustryID).
When you create a new workspace (a database) AmiBroker sets up your industries
and sectors according to the templates stored in the "broker.sectors" and
"broker.industries" files. These are simple text files that could be edited with
plain text editor (such as Notepad). These files could be also used for quick,
automatic setup of the sectors and industries. AmiBroker comes with predefined
broker.sectors and broker.industries that follow described above convention (see
the table). You can rewrite broker.sectors and broker.industries files to define
your own default scheme. So, "broker.sectors" and "broker.industries" files are
used as a template when creating new workspace. Once workspace is created these
files are not taken into consideration. In this way you may have different
categories in each workspace. If you want AmiBroker to load them into already
existing workspace please delete broker.workspace file before opening the
workspace. If you then open the workspace AmiBroker will read broker.sectors and
broker.industries.
The layout of broker.sectors file is very simple: it is plain text file holding
sector names written line by line as shown below:
Basic Materials
Capital Goods
Conglomerates
Consumer Cyclical
Consumer/Non-Cyclical
Energy
Financial
Working with sectors and industries
160
AmiBroker 5.80 User’s Guide
Tutorial
Healthcare
Services
Technology
Transportation
Utilities
The layout of broker.industries is similar, but in addition to industry names
there is a number at the beginning of each line:
8 Advertising
1 Aerospace & Defense
10 Air Courier
10 Airline
3 Apparel/Accessories
3 Appliance & Tool
3 Audio & Video Equipment
3 Auto & Truck Manufacturers
3 Auto & Truck Parts
4 Beverages (Alcoholic)
4 Beverages (Non-Alcoholic)
7 Biotechnology & Drugs
8 Broadcasting & Cable TV
8 Business Services
8 Casinos & Gaming
0 Chemical Manufacturing
0 Chemicals - Plastics & Rubber
5 Coal
9 Communications Equipment
The numbers at front of industry names are "Sector IDs". Those numbers decide to
which sector given industry belongs to. Because several industries may belong to
one sector - you may need to put the same number for sector Id. Sector IDs are
zero based, which means that 0 refers to the first line (sector name) of
"broker.sectors" file, while 7 refers to the eighth line of this file. In the
example above: "Advertising" industry belongs to "Services" sector, while
"Aerospace & Defence" industry belongs to "Capital Goods" sector.
If you don’t want to setup detailed industry information and want assign symbols
only to sectors you can define one-to-one relationship between first 32
industries so they will be equivalent to sectors. Using the broker.sectors as
show earlier in this article 1-1 broker.industries file would look like:
0
1
2
3
4
5
6
7
8
9
Basic Materials
Capital Goods
Conglomerates
Consumer Cyclical
Consumer/Non-Cyclical
Energy
Financial
Healthcare
Services
Technology
Working with sectors and industries
161
AmiBroker 5.80 User’s Guide
Tutorial
10 Transportation
11 Utilities
Note that this file is essentially the same as broker.sectors with the only
difference that we have consecutive numbers prepended to each line. Using this
kind of setup setting the industry will be equivalent to setting the sector.
Making it automatic
As described above symbol and industries names and relationship can be easily set
up quickly using "broker.sectors" and "broker.industries" files. It will save
some work needed otherwise to enter this information in Symbol->Categories
window.
Unfortunately a lot more work is needed to assign all symbols to the industries
even using Symbol->Organize Assignments dialog.
Fortunatelly there is a way to setup and update the database automatically.
In pre-5.60 version it still required scripting and lots of work (see 4th issue
of AmiBroker Tips newsletter) but version 5.60 brings completely new ways to
setup the database automatically.
The improved ASCII importer in v5.60 allows to import symbols, sectors and
industry names and build complete database in just one step.
Let us say that we have CSV file that looks as follows:
"DDD","3D Systems Corporation","Technology","Computer Software: Prepackaged
Software"
"MMM","3M Company","Health Care","Medical/Dental Instruments"
"SVN","7 Days Group Holdings Limited","Consumer Services","Hotels/Resorts"
"AHC","A.H. Belo Corporation","Consumer Services","Newspapers/Magazines"
"AIR","AAR Corp.","Capital Goods","Aerospace"
"AAN","Aaron’s, Inc.","Technology","Diversified Commercial Services"
Now we can import it into AmiBroker and automatically setup all sectors and
industries using this format definition
$FORMAT Ticker, FullName,SectorName,IndustryName
$SEPARATOR ,
$AUTOADD 1
$NOQUOTES 1
$OVERWRITE 1
$CLEANSECTORS 1
$SORTSECTORS 1
The last two commands ($CLEANSECTORS and $SORTSECTORS) instruct AmiBroker to
clean (wipe) existing sector/industry names before importing and sort newly
imported sectors after importing so they appear alphabetically
AmiBroker will read such ASCII file one-by one, then it will check whenever given
sector name/industry name already exists, if not - it will create new
Working with sectors and industries
162
AmiBroker 5.80 User’s Guide
Tutorial
sector/industry. Then it will assign given symbol to specified sector/industry.
The result will be a database with new sector/industry structure being set up and
symbols assigned to proper sectors and industries.
Described functionality is used to implement Tools->Update US symbol list and
categories tool.
One-click "Update US symbol list and categories"
Automatic setup and update of US stock database is available from Tools->Update
US symbol list and categories menu. This is implemented using new #import command
and new ASCII importer commands described above.
The command downloads symbol, sector and industry list from amibroker.com web
site and create or update current database with stocks listed on NYSE, Nasdaq and
AMEX. It also creates sector and industry structure and assigns stocks to proper
industries.
CAVEAT: Be aware that using this tool will WIPE (delete) any existing
sectors/industries and replace them with the ones imported automatically.
Note about GICS
GICS stands for Global Industry Classification Standard
(http://en.wikipedia.org/wiki/Global_Industry_Classification_Standard).
AmiBroker allows also GICS 4-level classification system, but demo database does
not have symbols classified according to that standard. You can find GICS
classification codes in GICS.txt file inside AmiBroker folder.
Note about ICB
ICB stands for Industry Classification Benchmark
(http://en.wikipedia.org/wiki/Industry_Classification_Benchmark).
AmiBroker allows also ICB 4-level classification system, but demo database does
not have symbols classified according to that standard. You can find ICB
classification codes in ICB.txt file inside AmiBroker folder.
Working with sectors and industries
163
AmiBroker 5.80 User’s Guide
Tutorial
Working with watch lists
AmiBroker 5.00 uses now new watch list system. Watch lists differ from other
kinds of categories (as groups, markets, industries, sectors) in that, that you
can assign single symbol to more than one watch list.
You can use UNLIMITED number of watch lists with their names definable in
Symbol->Categories window. The members of each watch list is shown in the symbol
tree under "Watch lists" leaf.
Watch lists are now stored as text files inside "Watchlists" folder inside
database. The folder contains of any number of .TLS files with watch lists
themselves and index.txt that defines the order of watch lists. You can add your
own .tls file (one symbol per line) and AmiBroker will update index.txt
automatically (adding any new watch lists at the end)The .TLS files can also be
open in AmiQuote.
Watch lists remember the order in which symbols were added, so for example if you
sort AA result list in some order and then you"add symbols to watch list" the
order will be kept in the watch list.
Adding / removing watch lists
You can now Add/Delete watch lists using Symbol->Watch List->New Watchlist and
Symbol->Watch List->Delete Watch list menu or from watch list context menu. Note
that if you have done any customization to the menu, you may need to go to
Tools->Customize, select "Menu Bar" and press "Reset" button for this new menu
items to appear.
Working with watch lists
164
AmiBroker 5.80 User’s Guide
Tutorial
Adding tickers to watch lists
You can easily add a ticker to the watch list by simply clicking with a right
mouse button over the item in the symbol tree and choosing Watch List->Add
selected symbol option:
After choosing this option a watch list selector window will appear:
Here you should select the list you want to add the symbol to. Note that you can
add one symbol to multiple lists at once, by holding CTRL key while clicking on
the list items. After clicking OK selected symbol (MSFT) appears in the watch
list of your choice:
Working with watch lists
165
AmiBroker 5.80 User’s Guide
Tutorial
You can also type-in symbols directly into the watch list using Symbol->Watch
list->Type-in option. Symbols should be comma-separated. You can also right click
over the watch list name in the workspace tree to type in symbols directly into
the watch list.
Sorting tickers in a watch list
You can now alphabetically sort the symbols in the watch list - click on the
watch list with RIGHT mouse button and select "Sort Alphabetically"
Removing tickers from watch lists
Removing symbols from the watch list is as easy as adding them. Just click on the
list member with a right mouse button and select Remove from watch list(s). Then
similar list selector window will appear showing only those lists that currently
selected symbol belongs to. You can now select one or more lists and the symbol
will be removed from the list(s).
Erasing watch lists
Sometimes you may want to clear (or erase) the whole watch list. Then just select
Symbol->Watch list->Erase (empty) option. In the watch list selector window mark
the list(s) you want to clear and click OK. This way selected watch list(s)
become empty.
Hiding/Unhiding empty watch lists
By default empty watch lists are shown in the symbol tree but you can hide them
by right-click on watch list in the symbol tree and select "Hide Empty
Watchlists" menu. To un-hide, select this option again.
Using watch lists in Automatic analysis window
AmiBroker gives you a very easy way to store the results of scanning, backtesting
and exploration into a watch list with a single mouse click - just run your
favourite AFL formula over the whole database and click on the results list with
a right mouse button to see the following menu:
Working with watch lists
166
AmiBroker 5.80 User’s Guide
Tutorial
When you choose Add all/selected results to watch list a watch list selector will
appear where you select to which list symbols should be added, then after
clicking OK all symbols filtered by your trading rules will automatically appear
in the watch list of your choice.
You can also use option Replace watch list with the results/selected results
This new option empties the watch list before adding results. The order of
symbols in the result list is preserved in the watch list.
How to import/export watch list from/to file
IMPORT WATCH LIST FROM FILE
1. Choose Symbol->Watch List->Import menu, or right click over watch list in the
tree and choose Import.
Working with watch lists
167
AmiBroker 5.80 User’s Guide
Tutorial
2. Choose destination watch list
3. In the file dialog that will appear pick .TLS, .LST, .TXT or .CSV file
.TLS, .CSV, .TXT files should have one ticker symbol per line and no other
fields.
.LST files are Quotes-Plus standard, comma separated list files that have the
ticker symbol in the first column
and some additional data in remaining columns. AmiBroker reads just first column
and ignores rest.
4. Click OK.
EXPORT WATCHLIST TO FILE
1. Choose Symbol->Watch List->Export menu.
or right click over watch list in the tree and choose Export.
2. Choose source watch list and switch to "External data source"
3. In the file dialog choose the file to export to. Generated file will be simple
ASCII file witch one ticker symbol per line.
How to import/export watch list from/to external database
ATTENTION: It works ONLY if you have "Data source" set to "Fast Track" plugin in
Working with watch lists
168
AmiBroker 5.80 User’s Guide
Tutorial
File->Database Settings (and if you have FastTrack database installed of course).
IMPORT FAMILY FROM FASTTRACK
1. Choose Symbol->Watch List->Import menu, or right click over watch list in the
tree and choose Import.
2. Choose destination watch list and switch to "External data source"
3. In the dialog that will appear unfold one category and select the family you
want to import symbols from:
Working with watch lists
169
AmiBroker 5.80 User’s Guide
Tutorial
4. Click OK.
EXPORT WATCHLIST TO FASTTRACK FAMILY
1. Choose Symbol->Watch List->Export menu.
or right click over watch list in the tree and choose Export.
2. Choose source watch list and switch to "External data source"
3. Now either TYPE IN the new personal family name in "New user family" (and the
description in the file next on the right side) OR choose existing personal
family from the list.
Working with watch lists
170
AmiBroker 5.80 User’s Guide
Working with watch lists
Tutorial
171
AmiBroker 5.80 User’s Guide
Tutorial
Understanding how AFL works
Introduction
One of most important aspects of AFL is that it is an array processing language.
It operates on arrays (or rows/vectors) of data. This way of operation is quite
similar to the way how popular spreadsheets work (like Microsoft Excel). Anyone
familiar with MS Excel should have no trouble quickly picking up AFL. - In fact
all the examples in this article were all created using MS Excel.
What is an Array?
An array is simply a list (or row) of values. In some books it may be referred to
as a vector. Each numbered row of values in the example represents an individual
array. Amibroker has stored in its database 6 arrays for each symbol. One for
opening price, one for the low price, one for the high price, one for the closing
price and one for volume (see the rows labelled 1-5 below) and one for open
interest. These can be referenced in AFL as open, low, high, close, volume,
openint or o, l, h, c, v, oi.
Bar
1
Open
1
2
3
4
5
6
7
8
9
10
1,23
1,24
1,21
1,26
1,24
1,29
1,33
1,32
1,35
1,37
Fig 1. Open price array
Any other array is calculated from these 6 arrays using formulae built into AFL.
These arrays are not stored in the database but calculated where necessary.
Each individual value in an array has a date associated with it. If you have the
tool tip option turned on (Preferences -> Miscellaneous Tab - > Price data tool
tips), when you move your cursor over candle on a daily candle chart, a small
yellow rectangle appears. AFL then looks up the open, low, high, close, volume
values in the appropriate array and displays them inside the tool tip.
Processing arrays - why is AFL so fast?
Lets see how the following statement is processed:
MyVariable = ( High + Low )/2;
When AFL is evaluating statement like this ( High + Low )/2 it does not need to
re-interpret this code for each bar. Instead it takes the High ARRAY and Low
ARRAY and adds corresponding array elements in single stage. In other words +
operator (and other operators too) work on arrays at once and it is executed at
full compiled-code speed, then the resulting array (each element of it) is
divided by 2 also in single stage.
Let’s look into the details - see fig 2.. When AFL engine looks at the ( High +
Low )/2 it first takes High (1) and Low (2) arrays and produces (in single
compiled step) the temporary array (3). Then it creates the final array (4) by
Understanding how AFL works
172
AmiBroker 5.80 User’s Guide
Tutorial
dividing each element of temporary array by two. This result is assigned to
myVariable
Bar
1
2
3
4
5
6
7
8
9
10
1 High (built-in array)
1,24 1,27 1,25
1,29 1,25
1,29
1,35
1,35 1,37 1,29
2 Low (built-in array)
1,20 1,21 1,19
1,20 1,21
1,24
1,30
1,28 1,31 1,27
2,49 2,46
2,53
2,65
2,63 2,68 2,46
3
High+Low (temporary array
created during evaluation)
2,44 2,48 2,44
4
( High+Low ) /2 (gets
assigned to MyVariable)
1,22 1,24 1,22 1,245 1,23 1,265 1,325 1,315 1,34 1,23
Fig 2. AFL steps when processing ( High + Low ) /2
Moving averages, conditional statements
Let us now consider the following code:
Cond1 = Close > MA( Close, 3 );
Cond2 = Volume > Ref( Volume, -1 );
Buy = Cond1 AND Cond2;
Sell = High > 1.30;
This code generates a buy signal when todays close is higher than 3 day moving
average of close AND todays volume is higher than yesterday’s volume. It also
generates a sell signal when today’s high is higher than 1.30.
If in your AFL code you need to see if the closing price is greater than say a 3
day simple moving average AFL will first run through the close array creating a
new array called MA(close,3) for the symbol being analysed. Each cell in the new
array can then be compared one for one in the close array. In the example an
array called Cond1 is created this way. For each cell where the closing price is
greater than the corresponding cell value in MA(close,3) the cell value for new
array ’Cond1’ is set to ’1’. If the closing price is not greater than the
corresponding price in the close array the value in ’Cond1’ is set to ’0’.
AFL can also look forwards or backwards a number of cells in an array using the
Ref function (see row 6 where temporary array is created holding previous day
volume)
In row 9 a new array called Cond2 has been created by comparing the value of each
cell in the volume array with its previous cell setting the Cond2 cell value to
’1’ if true and ’0’ if false.
Row 10 shows an array called ’Buy’ created by comparing the cell values in Cond1
with the cell values in Cond2. If the cell in Cond1 has a ’1’ AND so does the
corresponding cell in Cond2 then a ’1’ is placed in the ’Buy’ array cell.
Row 11 shows an array called ’Sell’ created whenever the cell value in the close
array is greater than $1.30.
Understanding how AFL works
173
AmiBroker 5.80 User’s Guide
Day
Tutorial
1
2
3
4
5
6
7
8
9
10
1
Open
1,23 1,24
1,21
1,26
1,24
1,29
1,33
1,32
1,35
1,37
2
High
1,24 1,27
1,25
1,29
1,25
1,29
1,35
1,35
1,37
1,29
3
Low
1,20 1,21
1,19
1,20
1,21
1,24
1,30
1,28
1,31
1,27
4
Close
1,23 1,26
1,24
1,28
1,25
1,25
1,31
1,30
1,32
1,28
5
Volume
8310 3021
5325
2834
1432
5666
7847
555
6749
3456
6
Ref( Volume, -1 )
(temporary array
created during eval)
Null
8310
3021
5325
2834
1432
5666
7847
555
6749
7
MA( Close, 3 )
(temporary array
created during eval)
Null
Null
8
Cond1 = Close <
MA(close,3) (gives 1
(or true) if condition
met, zero otherwise)
Null
Null
9
Cond2 = Volume >
Ref(volume,-1)
Null
10 Buy = Cond1 AND Cond2
11 Sell = High > 1.30
1,243 1,260 1,257 1,260 1,270 1,287 1,310 1,300
0
Null
Null
0
0
1
0
1
1
0
0
0
1
1
0
0
1
1
0
1
0
1
0
0
1
0
0
0
0
0
0
0
0
1
1
1
0
Obviously Buy and Sell are special arrays whose results can be displayed in the
Analyser window or on screen using a red or green value as needed.
Getting little bit more complex
The examples above were very simple. Now I will just explain 3 things that seem
to generate some confusion among the users:
• referencing selected values (SelectedValue, BeginValue, EndValue,
LastValue)
• IIF function
• AMA function
As written in the Tutorial: Basic charting guide you can select any quote from
the chart and you can mark From-To range. The bar selected by verticall line is
called "selected" bar while start and end bars of the range are called "begin"
and "end" bars. AFL has special functions that allow to reference value of the
array at selected, begin and end bar respectively. These functions are called
SelectedValue, BeginValue and EndValue. There is one more function called
LastValue that allows to get the value of the array at the very last bar. These
four functions take the array element at given bar and return SINGLE NUMBER
representing the value of the array at given point. This allows to calculate some
statistics regarding selected points. For example:
EndValue( Close ) - BeginValue( Close )
Will give you dollar change between close prices in selected from-to range.
Understanding how AFL works
174
AmiBroker 5.80 User’s Guide
Tutorial
When number retrieved by any of these functions is compared to an array or any
other arithmetic operation involving number and the array is performed it works
like the number spanned all array elements. This is illustrated in the table
below (rows 2, 6, 7). Green color marks "begin" bar and red color marks "end"
bar. Selected bar is marked with blue.
Day
1
2
3
4
5
6
7
8
9
10
1
Open
1,23
1,24
1,21
1,26
1,24
1,29
1,33
1,32
1,35
1,37
2
BeginValue(
Open )
1,24
1,24
1,24
1,24
1,24
1,24
1,24
1,24
1,24
1,24
3
EndValue( Open
)
1,32
1,32
1,32
1,32
1,32
1,32
1,32
1,32
1,32
1,32
4
SelectedValue(
Open )
1,21
1,21
1,21
1,21
1,21
1,21
1,21
1,21
1,21
1,21
5
LastValue(
Open )
1,37
1,37
1,37
1,37
1,37
1,37
1,37
1,37
1,37
1,37
6
Close
1,22
1,26
1,23
1,28
1,25
1,25
1,31
1,30
1,32
1,28
7
Close <=
BeginValue(
Open )
8
result = IIF(
Close <=
BeginValue(
Open ), Close,
Open );
9
Period
10
Factor =
2/(Period+1)
11 1 - Factor
12
AMA( Close,
Factor )
1
1,22
2
0
1,24
3
1
1,23
4
0
1,26
2
0
1,24
3
0
1,29
0
1,33
5
2
0
1,32
3
0
1,35
0
1,37
4
2
0,667
0,500
0,400
0,667
0,500
0,333
0,667
0,500
0,400
0,667
0,333
0,500
0,600
0,333
0,500
0,667
0,333
0,500
0,600
0,333
0,8125 1,0363 1,1138 1,2234 1,2367 1,2399 1,2853 1,2927 1,3036 1,2866
Now the IIF(condition, truepart, falsepart) function. It works that it returns
the value of second (truepart) or third (falsepart) argument depending on
condition. As you can see in the table above in row 8 the values come from Close
array (truepart) for bars when condition is true (1) and come from Open array
(falsepart) for the remaining bars. In that case the array returned by IIF
function consists of some values from Close and some values from Open array. Note
that both truepart and falsepart are arrays and they are evaluated regardless of
the condition (so this is not a regular IF-THEN-ELSE statement but function that
returns array)
The AMA( array, factor) function seems to cause the most problems with
understanding it. But in fact it is very simple. It works in recursive way. It
means that it uses its previous value for the calculation of current value. It
processes array bar by bar, with each step it multiplies given cell of first
argument (array) by given cell of second argument (factor) and adds it to the
previous value of AMA multiplied by (1-factor). Lets consider column 3. The value
Understanding how AFL works
175
AmiBroker 5.80 User’s Guide
Tutorial
of AMA in the column 3 is given by multipling close price from column 3 (1,23) by
factor (0,4). Than we add the previous value of AMA (1,0363) multiplied by
(1-factor = 0,6). The result (rounded to 4 places) is 1,23 * 0,4 + 1,0363 * 0,6 =
1,1138.
If you look at the figures in the row 12 you may notice that these values look
like a moving average of close. And that’s true. We actually presented how to
calculate variable-period exponential moving average using AMA function.
New looping
With version 4.40 AmiBroker brings ability to iterate through quotes using for
and while loops and adds if-else flow control statement. These enhancements make
it possible to work BOTH ways: either use ARRAY processing (described above) for
speed and simplicity or use LOOPS for doing complex things. As an example how to
implement variable period exponential averaging (described above) using looping
see the following code:
Period = ... some calculation
vaexp[ 0 ] = Close[ 0 ]; // initialize first value
for( i = 1; i < BarCount; i++ )
{
// calculate the value of smoothing factor
Factor = 2/(Period[ i ] + 1 );
// calculate the value of i-th element of array
// using this bar close ( close[ i ] ) and previous average value ( vaexp[ i 1 ] )
vaexp[ i ] = Factor * Close[ i ] + ( 1 - Factor ) * vaexp[ i - 1 ];
}
As you can see the code is longer but on the other hand it is very similar to any
other programming language as C/Pascal/Basic. So people with some experience with
programming may find it easier to grasp.
If you are beginner I suggest to learn array processing first before digging into
more complex looping stuff.
If you’re having trouble coding AFL I suggest you generate the arrays in the
example in Excel for yourself. If that’s a problem get some help from a friend especially if that friend is an accountant.
Once you’ve got the hang of it you can code any system from a book on trading or build one yourself.
--- Special thanks to Geoff Mulhall for original article in the newsletter that
was the basis of this tutorial ---
Understanding how AFL works
176
AmiBroker 5.80 User’s Guide
Tutorial
Creating your own indicators
There are two ways to create your own indicators:
1) using drag-and-drop interface
2) by writing your own formula
First method, using drag-and-drop interface is very simple and does not require
writing single line of code. To learn more about drag-and-drop indicator creation
please check Tutorial: How to use drag-and-drop charting interface
Second method involves writing an indicator formula in flexible AFL (AmiBroker
Formula Language). You can find the description of this language in AFL Reference
Guide section of user’s guide. Here we will present basic steps needed to define
and display your own custom indicator. In this example we will define an
"indicator" that will show line volume graph (opposite to built-in bar volume
graph).
Just follow these steps
1. Select Analysis->Formula Editor option from the menu as shown below:
2. You will see the following dialog displayed on the screen:
Creating your own indicators
177
AmiBroker 5.80 User’s Guide
Tutorial
It presents an empty Formula Editor window.
3. Now single-click in the edit field located in the editor toolbar to change
the name of the indicator:
Now you can edit the name of the custom indicator. Give it the name "My own
indicator". After you press ENTER key the caption will be updated with the
new file name as shown below:
4. Now type the formula:
Plot( Volume, "My volume chart", colorGreen );
This formula instructs AmiBroker to plot built-in Volume array. Second
parameter specifies the title of the plot and third parameter defines the
color. The picture below shows formula editor after entering the code:
5. Now click Apply indicator toolbar button (or choose Tools->Apply indicator
Creating your own indicators
178
AmiBroker 5.80 User’s Guide
Tutorial
menu) as shown in the picture and close editor by pressing X button in the
upper right corner of the editor window.
Now the indicator you have just written is displayed as a chart. You can also
find it stored as a formula in Chart tree:
Now you can improve your indicator by adding Param functions so both color and
style of the plot can be modified using Parameters dialog. To do so, click with
RIGHT mouse button over chart pane and select Edit Formula (or press Ctrl+E)
And modify the formula to:
Plot( Volume, "My volume chart", ParamColor("Color", colorGreen ),
ParamStyle("Style", 0, maskAll ) );
Creating your own indicators
179
AmiBroker 5.80 User’s Guide
Tutorial
Then press Apply indicator to apply the changes. Now click with RIGHT mouse
button over chart pane again and select Parameters (or press Ctrl+R) and you will
see parameters dialog allowing to modify colors and styles used to plot a chart:
Also in the "Axes & Grid" tab you will be able to change settings for axes, grids
and other charting options referring to this particular chart:
For further information on creating your indicators please check Using graph
styles and colors tutorial section
For further reference on using Formula Editor please consult Environment Formula Editor and AmiBroker Formula Language - AFL Tools sections of AmiBroker
User’s guide and using AFL editor.
Creating your own indicators
180
AmiBroker 5.80 User’s Guide
Tutorial
Using graph styles, colors, titles and parameters in
Indicators
AmiBroker provides customizable styles and colors of graphs in custom indicators.
These features allow more flexibility in designing your indicators. This article
will explain how to use styles and colors. It will also explain how to define
chart title that appears at the top of the chart.
Plot() function
Plot is the function used to plot a chart. It takes 9 parameters, out of which
first 3 are required.
Plot( array, name, color, style = styleLine, minvalue = Null, maxvalue = Null,
XShift = 0, ZOrder = 0, width = 1 )
• array parameter represents data to be plotted,
• name parameter defines the name of the graph (used in title string to show
the values of the indicator),
• color parameter defines the color of plot,
• style defines "the look" of the chart (i.e. line/histogram/candlestick/bar,
etc). Default style is line.
• minvalue and maxvalue are rarely used paremeters that define hard-coded
minimum and maximum values used when graph uses "independent" scaling, i.e.
styleOwnScale is specified in style parameter. Usually you don’t need to
specify them at all.
• XShift allows shifting chart past the last bar (for example displaced
moving averages or projections into the future)
• ZOrder - defines the Z-axis position of given plot. The default is zero.
Zorder = 0 means also where the "grid" is located. So if you want to plot
BEHIND the grid you need to specify negative zorder parameter.Plots are
drawn in the following order:
zorder parameter takes precedence over the order of calling Plot()
functions, so if z-order is set, it determines plotting order. See this
picture. If multiple plots use the same z-order parameter they are plotted
in reverse call order (ones that appear last in the code are plotted
first). This rule can be changed by already existing switch graphzorder = 1
which, when specified, reverses this behaviour (so plots are drawn in call
order). Please note the above applies to each zorder "layer" separately (so
within same zorder "layer" reverse call rule applies)
• width - (new in 5.60) defines pixel or percent width of given plot. The
default is 1 pixel. Positive values specify PIXEL width, negative values
specify width in percent of current bar width. So for example -20 will give
you dynamic width that is 20% of bar width.
An example, the following single function call plots a RSI indicator with red
color line:
Plot( RSI(14), "My RSI", colorRed );
Using graph styles, colors, titles and parameters in Indicators
181
AmiBroker 5.80 User’s Guide
Tutorial
As you can see we have provided only first three (required) parameters. First
parameter is the array we need to plot. In our example it is RSI(14) indicator.
Second parameter is just the name. It can be any name you want. It will be
displayed in the title line along with indicator value as shown in the picture
below:
Third parameter is the color. To specify plot color you can use one of the
following pre-defined constants:
Color constants
Custom colors refer to color user-defined palette editable using
Tools->Preferences->Colors, the numerical values that appear after = (equation)
mark are for reference only and you don’t need to use them. Use just the name
such as colorDarkGreen.
colorCustom1 = 0
colorCustom2 = 1
colorCustom3 = 2
colorCustom4 = 3
colorCustom5 = 4
colorCustom6 = 5
colorCustom7 = 6
colorCustom8 = 7
colorCustom9 = 8
colorCustom10 = 9
colorCustom11 = 10
colorCustom12 = 11
colorCustom13 = 12
colorCustom14 = 13
colorCustom15 = 14
colorCustom16 = 15
colorBlack = 16
colorBrown = 17
colorDarkOliveGreen = 18
colorDarkGreen = 19
colorDarkTeal = 20
colorDarkBlue = 21
colorIndigo = 22
colorDarkGrey = 23
colorDarkRed = 24
colorOrange = 25
colorDarkYellow = 26
colorGreen = 27
Using graph styles, colors, titles and parameters in Indicators
182
AmiBroker 5.80 User’s Guide
Tutorial
colorTeal = 28
colorBlue = 29
colorBlueGrey = 30
colorGrey40 = 31
colorRed = 32
colorLightOrange = 33
colorLime = 34
colorSeaGreen = 35
colorAqua = 35
colorLightBlue = 37
colorViolet = 38
colorGrey50 = 39
colorPink = 40
colorGold = 41
colorYellow = 42
colorBrightGreen = 43
colorTurquoise = 44
colorSkyblue = 45
colorPlum = 46
colorLightGrey = 47
colorRose = 48
colorTan = 49
colorLightYellow = 50
colorPaleGreen = 51
colorPaleTurquoise = 52
colorPaleBlue = 53
colorLavender = 54
colorWhite = 55
You can also use new 24-bit (full color palette) functions ColorRGB and ColorHSB
You can easily plot multi colored charts using both Plot functions. All you need
to do is to define array of color indexes.
In the following example MACD is plotted with green color when it is above zero
and with red color when it is below zero.
dynamic_color = IIf( MACD() > 0, colorGreen, colorRed );
Plot( MACD(), "My MACD", dynamic_color );
In addition to defining the color we can supply 4th parameter that defines style
of plot. For example we can change previous MACD plot to thick histogram instead
of line:
dynamic_color = IIf( MACD() > 0, colorGreen, colorRed );
Plot( MACD(), "My MACD", dynamic_color, styleHistogram |
styleThick );
As you can see, multiple styles can be combined together using | (binary-or)
Using graph styles, colors, titles and parameters in Indicators
183
AmiBroker 5.80 User’s Guide
Tutorial
operator. (Note: the | character can be typed by pressing backslash key ’\’ while
holding down SHIFT key). Resulting chart looks like this:
To plot candlestick chart we are using styleCandle constant, as in this example:
Plot( Close, "Price", colorBlack, styleCandle );
To plot traditional bars with color (green up bars and red down bars) we just
specify color depending on relationship between open and close price and styleBar
in style argument:
Plot( Close, "Price", IIf( Close > Open, colorGreen, colorRed ),
styleBar | styleThick );
All available style constants are summarized in the table below.
Style constants
Style is defined as a combination (using either addition (+) or binary-or (|)
operator) of one or more following flags ( you can use predefined style__
constants instead of numbers)
styleLine = 1 - normal (line) chart (default)
styleHistogram = 2 - histogram chart
styleThick =4 - fat (thick)
styleDots = 8 - include dots
styleNoLine = 16 - no line
styleDashed = 32 - dashed line style
styleCandle = 64 - candlestick chart
styleBar = 128 - traditional bar chart
styleNoDraw = 256 - no draw (perform axis scaling only)
styleStaircase = 512 - staircase (square) chart
styleSwingDots = 1024 - middle dots for staircase chart
styleNoRescale = 2048 - no rescale
styleNoLabel = 4096 - no value label
stylePointAndFigure = 8192 - point and figure
styleArea = 16384 - area chart (extra wide histogram)
styleOwnScale = 32768 - plot is using independent scaling
styleLeftAxisScale = 65536 - plot is using left axis scale (independent from
right axis)
styleNoTitle = 131072 - do not include this plot value in title string
styleCloud = 262144 - paint a "cloud" (filled area) chart (see examples below)
styleClipMinMax = 524288 - clip area between Min and Max levels defined in Plot
statement. (Note: this style is not compatible with most printers)
styleGradient - (new in 5.60) - gradient area chart. Upper gradient color is
specified by color parameter in Plot() function, bottom gradient color is either
Using graph styles, colors, titles and parameters in Indicators
184
AmiBroker 5.80 User’s Guide
Tutorial
background color or can be defined using SetGradientFill function. styleGradient
can be combined with styleLine
Not all flag combinations make sense, for example (64+1) (candlestick + line)
will result in candlestick chart (style=64)
Note on candlestick/bar charts: if these styles are applied to Plot() function
then they use indirectly O, H, L arrays.
If you want to specify your own OHL values you need to use PlotOHLC() function.
New styleCloud and styleClipMinMax styles bring new interesting possibilities
shown in the sample image below:
The formula for chart in the middle pane (rainbow 24-bit multiple moving
averages) looks as follows:
side = 1;
increment = Param("Increment",2, 1, 10, 1 );
for( i = 10; i < 80; i = i + increment )
{
up = MA( C, i );
down = MA( C, i + increment );
Using graph styles, colors, titles and parameters in Indicators
185
AmiBroker 5.80 User’s Guide
Tutorial
if( ParamToggle("3D effect?", "No|Yes", 1 ) )
side = IIf(up<=down AND Ref( up<=down, 1 ), 1, 0.6 );
PlotOHLC( up,up,down,down, "MA"+i, ColorHSB( 3*(i - 10),
Param("Saturation", 128, 0, 255 ),
side * Param("Brightness", 255, 0, 255 ) ), styleCloud | styleNoLabel
);
}
The formula for the chart in the lower pane (slow stochastic %K with colored tops
and bottoms) looks as follows. It uses styleClipMinMax to achieve clipping of the
cloud region between min and max levels specified in the plot statement. Without
this style area between min/max would be filled. Please note that due to Windows
GDI limitation clipping region (styleClipMinMax) is supported only on raster
(bitmap) devices so it is not compatible with printers or WMF (windows metafile)
output.
SetChartOptions(0,0,ChartGrid30 | ChartGrid70 );
r = StochK(14);
Plot( r, "StochK", colorBlack );
PlotOHLC( r,r,50,r, "", IIf( r > 50, colorRed, colorGreen ), styleCloud |
styleClipMinMax, 30, 70 );
X-shift feature
The XShift parameter allows to displace (shift) the plot in horizontal direction
by specified number of bars. This allows to plot displaced moving averages and
projections into the future. See the following sample code of displaced moving
average:
Periods = Param("Periods", 30, 2, 100 );
Displacement = Param("Displacement", 15, -50, 50 );
Plot( MA( C, Periods ), _DEFAULT_NAME(), ColorCycle, styleLine, 0, 0,
Displacement );
PlotForeign() function
It is now easy to overlay price plots of multiple symbols using PlotForeign
function:
PlotForeign( tickersymbol, name, color/barcolor, style = styleCandle |
styleOwnScale, minvalue = {empty}, maxvalue = {empty}, xshift = 0)
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). Color indexes are related to the
current palette (see Preferences/Color)
style defines chart plot style (see Plot() function for possible values)
Using graph styles, colors, titles and parameters in Indicators
186
AmiBroker 5.80 User’s Guide
Tutorial
PlotForeign( "^DJI", "Dow Jones", colorRed );
PlotForeign( "^NDX", "Nasdaq 100", colorBlue );
PlotForeign( "^IXIC", "Nasdaq Composite", colorGreen );
Multiple plots using different scaling
Two new styles can be used to plot multiple graphs using different Y-scale:
styleOwnScale and styleLeftAxisScale.
It also makes it easy to plot 2 or more "own scale" plots with the same scaling:
minimum = LastValue( Lowest( Volume ) );
maximum = LastValue( Highest( Volume ) );
Plot( Close, "Price", colorBlue, styleCandle );
/* two plots below use OwnScale but the scale is common because we
set min and max values of Y axis */
Plot( Volume, "Volume", colorGreen, styleHistogram | styleThick |
styleOwnScale, minimum, maximum );
Plot( MA( Volume, 15 ), "MA volume", colorRed, styleLine |
styleOwnScale, minimum, maximum );
New style: styleLeftAxisScale = 65536 - allows to plot more than one graph using
common scaling but different from regular (right axis) scale.
Example: price plot plus volume and moving average plot:
// Plot price plot and its moving average
Plot( Close, "Price", colorWhite, styleCandle );
Plot( MA( Close, 20 ), "MAC", colorRed );
// Now plot volume and its moving average using left-hand axis
scaling
Plot( Volume , "Volume", colorBlue, styleLeftAxisScale |
styleHistogram | styleThick );
Plot( MA( Volume,15), "MAV", colorLightBlue, styleLeftAxisScale );
New parameters make it also easy to plot ribbons, for example:
Plot( Close, "Price", colorBlue, styleCandle );
Plot( 2, /* defines the height of the ribbon in percent of pane width
*/
"Ribbon",
IIf( up, colorGreen, IIf( down, colorRed, 0 )), /* choose color */
styleOwnScale|styleArea|styleNoLabel, -0.5, 100 );
Using custom defined parameters
AmiBroker allows to create user-defined parameters. Such parameters are then
available via Parameters dialog for quick and fast adjustment of indicator.
Using graph styles, colors, titles and parameters in Indicators
187
AmiBroker 5.80 User’s Guide
Tutorial
Most often used parameter functions are (click on the links to get more detailed
description):
•
•
•
•
Param( "name", default, min, max, steps, incr = 0 )
ParamStr( "name", "default" );
ParamColor( "name", defaultcolor );
ParamStyle(’’name’’, defaultval = styleLine, mask = maskDefault )
They make it possible to define your own parameters in your indicators. Once
Param functions are included in the formula you can right click over chart pane
and select "Parameters" or press Ctrl+R, and change them via Parameters dialog
and get immediate response.
The simplest case looks like this:
period = Param("RSI period", 12, 2, 50, 1 );
Plot( RSI( period ), "RSI( " + period + ") ", colorRed );
Right click over the chart and choose "Parameters" and move the slider and you
will see RSI plotted with different periods immediatelly as you move the slider.
Sample code below shows how to use ParamStr to get the ticker symbol and
ParamColor to get colors.
ticker = ParamStr( "Ticker", "MSFT" );
sp = Param( "MA Period", 12, 2, 100 );
PlotForeign( ticker, "Chart of "+ticker,
ParamColor( "Price Color", colorBlack ), styleCandle );
Plot( MA( Foreign( ticker, "C" ), sp ), "MA", ParamColor( "MA Color",
colorRed ) );
The following sample formula (from AmiBroker mailing list) that allows to
visually align price peak/troughs with sine curve on the chart:
Cycle = Param("Cycle Months", 12, 1, 12, 1 )*22;//264==12mth,22==1mth
xfactor = Param("Stretch",1,0.1,2,0.1);//1==1yr,2==2yr
xshift = Param("slide",0,-22,22,2)/3.1416^2;//slide curve 1==5days
x = 2*3.1416/Cycle/xfactor;
y = sin(Cum(x)-xshift);
Plot(C,"Daily Chart", colorBlack, styleCandle | styleNoLabel);
Plot(y,
"cycle =" + WriteVal(Cycle*xfactor/22,1.0)+"months",
colorBlue,styleLine|styleNoLabel|styleOwnScale);
Right click over the chart and choose "Parameters" and move the sliders and you
will see chart immediatelly reflecting your changes.
For more information on user-definable parameters please check also Tutorial:
Using drag-and-drop interface
Using graph styles, colors, titles and parameters in Indicators
188
AmiBroker 5.80 User’s Guide
Tutorial
Plotting texts at arbitrary positions on the chart
AmiBroker now allows annotation of the chart with text placed on any x, y
position specified on the formula level using new PlotText function.
PlotText( "text", x, y, color, bkcolor = colorDefault )
where
x - is x-coordinate in bars (like in LineArray)
y - is y-coordinate in dollars
color is text color, bkcolor is background color. 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
Example:
Plot(C,"Price", colorBlack, styleLine );
Plot(MA(C,20),"MA20", colorRed );
Buy=Cross( C, MA(C,20 ) );
Sell= Cross( MA( C, 20 ), C );
dist = 1.5*ATR(10);
for( i = 0; i < BarCount; i++ )
{
if( Buy[i] ) PlotText( "Buy\[email protected]" + C[ i ], i, L[ i ]-dist[i], colorGreen );
if( Sell[i] ) PlotText( "Sell\[email protected]" + C[ i ], i, H[ i ]+dist[i], colorRed,
colorYellow );
}
PlotShapes( Buy * shapeUpArrow + Sell * shapeDownArrow, IIf( Buy, colorGreen,
colorRed ) );
Gradient fill of the background
AmiBroker 4.90 allows to fill indicator background with gradually changing color.
To achieve this you need to use new function SetChartBkGradientFill( topcolor,
bottomcolor, titlebkcolor = default )
The function enables background gradient color fill in indicators.
Please note that this is independent from chart background color (background
color fills entire pane, gradient fill is only for actual chart interior, so axes
area is not affected by gradient fill). Parameters are as follows:
topcolor - specifies top color of the gradient fill
bottomcolor - specifies bottom color of the gradient fill
titlebkcolor - (optional) the background color of title text. If not specified
then top color is automatically used for title background.
Example:
Using graph styles, colors, titles and parameters in Indicators
189
AmiBroker 5.80 User’s Guide
Tutorial
SetChartBkGradientFill( ParamColor("BgTop", colorWhite),ParamColor("BgBottom",
colorLightYellow));
Gradient fill area charts
Version 5.60 brings native gradient area charts. To display a simple gradient
chart it is enough to use styleGradient in the Plot() function call. By default
upper gradient color is specified by color parameter in Plot() function, bottom
gradient color is either background color. styleGradient can be combined with
styleLine.
A simple gradient area chart can be displayed using:
Plot( C, "C", colorDefault, styleGradient | styleLine );
For detailed control over gradient colors and baseline there is an extra function
SetGradientFill( topcolor, bottomcolor, baseline, baselinecolor ) that should be
called before Plot().
When you use SetGradientFill function, the upper gradient color is specified by
topcolor argument, bottom gradient color is specified by botttomcolor. Optional
parameters (baseline/baselinecolor) allow reverse gradient chart (such as
underwater equity) and 3 color gradients top->baseline->bottom. See code for
Underwater Equity for example usage of reverse gradient chart (with baseline at
the top). Baseline parameter specifies the Y-axis position of chart baseline. The
baselinecolor parameter specifies the color of gradient that is to be used at
that level. If baselinecolor is not specified, then only 2-color gradient is
plotted (topcolor->bottomcolor).
For example to display three-color gradient Rate Of Change that will use green as
"top" color for positive values, background color as "baseline" color and red as
"bottom" color for negative values it is enough to write:
SetGradientFill( colorGreen /*top*/, colorRed /*bottom*/, 0 /*baseline level*/,
GetChartBkColor() /*baseline color */);
Plot( ROC( C, 14), "ROC", colorLightOrange, styleLine | styleGradient, Null,
Null, 0, -1 );
The resulting chart will look as follows (using Basic chart theme):
.. or this way (using Black chart theme):
Using graph styles, colors, titles and parameters in Indicators
190
AmiBroker 5.80 User’s Guide
Tutorial
Super thick charts
Version 5.60 allows to define the line width beyond styleThick that was the only
option before.
Now 9th parameter of Plot() defines pixel or percent width of given plot. The
default is 1 pixel. Positive values specify pixel width, negative values specify
width in percent of current bar width. So for example -20 will give you dynamic
width that is 20% of bar width. Example:
Plot( C, "Close", colorDefault, styleBar, Null, Null, 0, 1, -20 /* line width as
percent of bar */ );
As you zoom-in the bars will become thicker and thicker.
Now you can get super thick lines as shown in the example below (10-pixel thick
line chart):
Plot( C, "Close", colorRed, styleLine, Null, Null, 0, 1, 10 /* 10 pixel wide */
);
Miscellaneous
As you already know each plot has its own name that is used to create a title
string which displays names and values of indicators. AmiBroker however allows
you to override this automatic mechanism and define your own title string from
the scratch. The Title reserved variable is used for that. You just assign a
string to it and it will be displayed in the chart instead of automatically
generated one.
Also there two more reserved variables (GraphXSpace and GraphZOrder) that allow
to fine-tune indicator look.
They are all described in the table below.
Variable
Usage
Applies to
Title
Defines title text
Indicators
If you use Title variable you have to specify colors in
Using graph styles, colors, titles and parameters in Indicators
191
AmiBroker 5.80 User’s Guide
Tutorial
the string.
Colors can be specified using \\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.
For example
Title = "This is written in \\c38violet color \\c27and
this in green";
You can also use new AFL function that makes it easier.
Function is called
EncodeColor( colornumber ).
And you can write the above example like this:
Title = "This is written in " + EncodeColor( colorViolet
) + "violet color " + EncodeColor( colorGreen ) + "and
this in green";
Multi-line caption is possible by simply embedding line
break \n, for example:
Title = "This is 1st line\nThis is second line";
Tooltip
Obsolete in 5.40. Use Data window instead or use Plot()
with styleHidden if you want to add your custom values to
data tooltip.
Indicators
For example:
Plot( my_value, "MyValueForTooltip", colorBlack,
styleHidden );
GraphXSpace defines how much extra space should be added above and
below graph line (in percent).
For example:
Indicators
GraphXSpace = 5;
adds 5% extra space above and below the graph line. When
GraphXSpace is not defined in the formula then default 2%
is used.
GraphZOrder GraphZOrder variable allows to change the order of
plotting indicator lines. When GraphZOrder is not defined
or is zero (false) - old ordering (last to first) is
used, when GraphZOrder is 1 (true) - reverse ordering is
applied.
Indicators
Obsolete graph variables
This table shows obsolete reserved variables. They are still functional for
backward-compatibility but new code should use Plot() functions only. What’s
more, when using new Plot() functions you should NOT use obsolete variables
below.
Using graph styles, colors, titles and parameters in Indicators
192
AmiBroker 5.80 User’s Guide
Tutorial
Variable
Usage
Applies to
maxgraph
specifies maximum number of graphs to be drawn in custom
indicator window (default=3)
Indicators
graphN
defines the formula for the graph number N (where N is a
number 0,1,2,..., maxgraph-1)
Indicators
graphNopen, define additional O, H, L price arrays for candlestick and
graphNhigh, traditional bar charts
graphNlow,
Indicators
graphNcolor defines the color index of Nth graph line. Color indexes
are related to the current palette - see
Preferences/Color.
Indicators
graphNbarcolor
defines the array that holds palette indexes for each bar
drawn
Indicators
graphNstyle
Indicators
defines the style of Nth graph. Style is defined as a
combination (sum) of one or more following flags ( you can
use predefined style__ constants instead of numbers)
Using graph styles, colors, titles and parameters in Indicators
193
AmiBroker 5.80 User’s Guide
Tutorial
How to create your own exploration
One of the most useful features of the Analysis window is called "Exploration".
Basically, an exploration works in a similar way to scan but instead of looking
for and reporting just buy/sell signals it allows you to generate customizable
screening (or exploration) report that can give you much more information than
simple scan.
The idea behind an exploration is simple - one variable called filter controls
which symbols/quotes are accepted. If "true" (or 1) is assigned to that variable
for given symbol/quote it will be displayed in the report.
So, for example, the following formula will accept all symbols with closing
prices greater than 50 :
filter = close > 50;
(NOTE: To create new formula please open Formula Editor using Analysis->Formula
Editor menu, type the formula and choose Tools->Send to Analysis menu in Formula
editor)
Note that exploration uses all range and filter settings that are also used by
back-tester and scanning modes so you can get multiple signals (report lines) if
you select "All quotations" range. To check just the most recent quote you
should choose "1 recent bar(s)"
Now, what about customizable reports?
Yes, exploration mode allows you to create and then export a report with
completely customizable columns and it is quite simple to do.
All you have to do is to tell AmiBroker what columns do you want. This can be
done by calling AddColumn function in your exploration formula:
AddColumn( Close, "Close" );
The first argument of AddColumn function is the data ARRAY you want to display,
the second argument defines the column caption
If you now press "Explore" button in the Analysis window you will get the result
similar to this:
How to create your own exploration
194
AmiBroker 5.80 User’s Guide
Tutorial
Note that there are actually 3 columns: predefined Ticker and Date/Time column
and one custom columnholding close price. Note that only tickers with close price
greater than 50 are reported.
Now you can click "Export" and your exploration will be saved to CSV (comma
separated values) file that could be easily loaded to any other program including
Excel for further analysis.
Actually AddColumn function accepts more arguments to allow you to customize the
output even more. The full syntax is:
AddColumn( array, name, format = 1.2, textColor = colorDefault, bkgndColor =
colorDefault )
format parameter allows you to define the formatting applied to numbers. 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. So, in our example, typing:
AddColumn( Close, "Close", 1.4 );
will give closing prices displayed with 4 decimal digits.
(Note for advanced users: the integer part of this number can be used to pad formatted number with spaces - 6.0
will give no decimal digits but a number space-padded upto 6 characters.
)
There are also special format pre-defined constants that allow to display
date/time and single character codes:
How to create your own exploration
195
AmiBroker 5.80 User’s Guide
Tutorial
• formatDateTime - produces date time formated according to your system
settings
AddColumn( DateTime(), "Date / Time", formatDateTime );
• formatChar - allows outputting single ASCII character codes:
Example (produces signal file accepted by various other programs):
Buy=Cross(MACD(),Signal());
Sell=Cross(Signal(), MACD());
Filter=Buy OR Sell;
SetOption("NoDefaultColumns", True );
AddColumn( DateTime(), "Date", formatDateTime );
AddColumn( IIf( Buy, 66, 83 ), "Signal", formatChar );
textColor and bkgndColor arguments allow you to produce colorful reports. By
default result list is displayed using system color but you can override this
behaviour providing your own colors.
For example, the code that displays close price in green color when 1 day rate of
change is positive and otherwise uses red color:
AddColumn( Close, "Close", 1.4, IIF( ROC(C, 1 ) > 0, colorGreen, colorRed ) );
Examples
The exploration mode is extermely flexible: you can, for example, export the
whole database to CSV file using the following formula:
filter = 1; /* all symbols and quotes accepted */
AddColumn(Open,"Open",1.4);
AddColumn(High,"High",1.4);
AddColumn(Low,"Low",1.4);
AddColumn(Close,"Close",1.4);
AddColumn(Volume,"Volume",1.0);
This one will show you only heavily traded securities:
filter = volume > 5000000; /* adjust this threshold for your own
needs */
AddColumn(Close,"Close",1.4);
AddColumn(Volume,"Volume",1.0);
or...just show securities with volume being 30% above its 40-day exponential
average
filter = volume > 1.3 * ema( volume, 40 );
AddColumn(Close,"Close",1.4);
AddColumn(Volume,"Volume",1.0);
With this one, you can export multiple indicator values for further analysis:
How to create your own exploration
196
AmiBroker 5.80 User’s Guide
Tutorial
filter = close > ma( close, 20 ); /* only stocks trading above its 20
day MA*/
AddColumn( macd(), "MACD", 1.4 );
AddColumn( signal(), "Signal", 1.4 );
AddColumn( adx(), "ADX", 1.4 );
AddColumn( rsi(), "RSI", 1.4 );
AddColumn( roc( close, 15 ), "ROC(15)", 1.4 );
AddColumn( mfi(), "MFI", 1.4 );
AddColumn( obv(), "OBV", 1.4 );
AddColumn( cci(), "CCI", 1.4 );
AddColumn( ultimate(), "Ultimate", 1.4 );
One more example of color output:
Filter =1;
AddColumn( Close, "Close", 1.2 );
AddColumn( MACD(), "MACD", 1.4 , IIf( MACD() > 0, colorGreen,
colorRed ) );
AddTextColumn( FullName(), "Full name", 77 , colorDefault, IIf( Close
< 10, colorLightBlue, colorDefault ) );
Scatter (X-Y) charts in Exploration
Version 5.60 brings a new feature to the exploration - scatter X/Y charts.
Scatter charts are useful to display relationships between many symbols such as
correlation, risk, etc. They can be seen as replacement and upgrade to
"Risk/yield" map that was hard coded to just one function. Now you can code your
own X-Y charts that are not limited to just risk/yield maps.
All you need to do to display your own scatter plot is to add XYChartAddPoint to
your formula for each X-Y point you want to have on your chart.
For example you can get scatter plot of MFE/Profit and MAE/Profit relationships
as shown in the description of XYChartAddPoint AFL function.
To display risk/yield scatter chart using new functions follow the steps below.
1. Click File->New->Analysis
2. Pick "Formulas\Exploration\RiskYield.afl" file (listed below)
3. Click on Explore button in the new Analysis window
4. In the bottom row of tabs you will see new "Risk/Yield" tab, click on it and
you will see XY chart generated during exploration:
How to create your own exploration
197
AmiBroker 5.80 User’s Guide
Tutorial
You can hover the mouse over that X-Y chart to read the values and you can click,
drag to mark rectangle to zoom in. Click without marking rectangle restores full
view.
//
//
//
//
//
//
XY scatter chart example
This is AFL equivalent of Risk-Yield map
Note that this exploration should be run on
WEEKLY data
it calculates average weekly gain (yield)
and standard deviation of gains (risk)
Filter=Status("lastbarinrange");
Length = SelectedValue( BarIndex() );
Chg = ROC( C, 1 ); //one bar yield
yield = MA( Chg, Length - 1);
risk = StDev( Chg, Length - 1);
AddColumn(yield,"yield");
AddColumn(risk,"risk");
Clr = ColorHSB( 2 * Status("stocknum") % 255, 255, 255 );
XYChartAddPoint( "Risk/Yield", Name(), risk[ Length ], yield[ Length ] , Clr );
XYChartSetAxis("Risk/Yield", "Risk[%]", "Yield[%]");
Final tip
How to create your own exploration
198
AmiBroker 5.80 User’s Guide
Tutorial
Please don’t forget that you can sort the results of the exploration by any
column by simply clicking on its header.
How to create your own exploration
199
AmiBroker 5.80 User’s Guide
Tutorial
How to write your own chart commentary
One of the interesting aspects of using AmiBroker Formula Language is writing
automatic chart commentaries. The idea behind this technique is as follows:
1. You write the commentary formula that consists of two basic elements:
static texts and AFL expressions
2. AmiBroker evaluates expressions using currently selected symbol data and
generates dynamic content
3. The mixture of static text and evaluated formulas are displayed in
commentary output window
4. Additionally buy/sell arrows are plotted on the chart
Commentaries are available from Analysis->Commentary menu. When you open
commentary window you will see two tabs: Commentary and Formula. In the Formula
tab you can type the AFL statements which will be evaluated by AmiBroker
resulting in dynamic commentary that appears in Commentary tab. The following
sections will guide you through the steps needed to write your very own
commentary formulas.
Writing static texts
Static text elements written in the formula should be enclosed in the quotation
marks and terminated by semicolon sign as shown below:
"This is sample static text statement";
You can write several statements and each statement will be placed in a new line
in the commentary output window:
"This is first line of text";
"This is second line of text";
Please type these examples into edit field in the Formula tab and switch to
Commentary tab. You will see the texts displayed in the output area but without
any quotation marks or semicolons. This is because AmiBroker has evaluated this
simple text statements into strings and it displayed the strings in the output
window.
To write several lines of text you can use a couple of statements as shown above
or you can do this using single statement and line break sequence (’\n’):
"This is first line of text\nThis is second line of text\nThis is
third line of text";
You can also concatenate the string constants which will result in single line
text:
"This" +
" is" +
" single"+
How to write your own chart commentary
200
AmiBroker 5.80 User’s Guide
Tutorial
" line" + " of text";
I guess that you are quite bored with these simple examples, let’s start with
some dynamic content.
Dynamic content
To enable dynamic commentaries AFL has a couple of special functions available,
but two of them are the most important: WriteVal() and WriteIF(). WriteIF()
function is used for conditional text display and will be described later in this
article, now let us see what we can do using WriteVal() function.
The AFL reference manual says:
SYNTAX
writeval( NUMBER );
writeval( ARRAY );
RETURNS
STRING
FUNCTION
This function can only be used within an Guru commentary.
It is used to display the numeric value of NUMBER or
ARRAY.
So, if you want to display a value of a number or currently selected bar of the
array you should use writeval() function. But... wait a minute - what does it
mean "currently selected bar of the array"? Let me explain this using simple
formula (please type it in the Formula tab):
writeval( close );
When you switch to Commentary tab you will see the value of closing price (the
same one which is displayed at the top of main price chart). But when you click
on the chart in another place, selecting different date and then you click
"Refresh" button you will see different value - the closing price at day you have
selected. So writeval( close ) function displays the value of currently selected
bar of close array. And it works exactly the same way with other arrays. If you
write
writeval( macd() );
you will see the exact value of MACD indicator at the day you have selected in
the main chart. Having our current know-how we are able to write some statistics:
"Closing price = " + WriteVal( close );
"Change since yesterday = " + WriteVal( close - ref( close, -1 ) );
"Percent chg. since yesterday = " + WriteVal( roc( close, 1 ) ) + "
%";
"MACD =" + WriteVal( macd() ) + " , Signal line =" + WriteVal(
signal() );
When you switch to Commentary tab you will see output similiar to this one:
How to write your own chart commentary
201
AmiBroker 5.80 User’s Guide
Tutorial
Closing price = 17.940
Change since yesterday = -0.180
Percent chg. since yesterday = -0.993 %
MACD = -0.001 , Signal line = 0.063
Quite nice, isn’t it? You can also write current symbol ticker and selected date
using name() and date() functions as shown below:
"Statistics of " + name() + " as of " + date();
But what we miss here is an ability to write something if some condition is met
and write something different otherwise...
Conditional text output
AFL is equipped with very nice function called WriteIF() that can output
different texts depending on the condition. Let us look what documentation says:
SYNTAX
writeif( EXPRESSION, "TRUE TEXT", "FALSE TEXT" )
RETURNS
STRING
FUNCTION
This function can only be used within an Guru commentary.
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.
So we can easily output different text depending on expession, for example:
writeif( macd() > signal(), "The MACD is bullish because is is above
it’s signal line", "The MACD is bearish because it is below its
signal line" );
You can also combine several WriteIf() function calls in order to handle more
possibilities:
"The current market condition for "+ name() + " is: ";
avgcond1 = ( c > ema( close, 200) ) + 0.1 * ( close > ema( close, 90)
) + 0.1 * ( close > ema( close , 30 ) );
avgcond2 = -( c < ema( close, 200) ) - 0.1 * ( close < ema( close,
90) ) - 0.1 * ( close < ema( close , 30 ) );
WriteIf( avgcond1
"Very Bullish",
WriteIf( avgcond1
"Bullish",
WriteIf( avgcond1
"Mildly Bullish",
== 1.2,
== 1.1,
== 1.0,
"") ) ) +
WriteIf( avgcond2 == -1.2,
"Very Bearish",
How to write your own chart commentary
202
AmiBroker 5.80 User’s Guide
Tutorial
WriteIf( avgcond2 == -1.1,
"Bearish",
WriteIf( avgcond2 == -1.0,
"Mildly Bearish", "") ) );
The formula above will return the text "The current market condition for {your
ticker here} is: Very Bullish" if close price is above 30 day average and close
is above 90 day average and close is above 200 day average. In other cases the
formula will give you Bullish, Mildly Bullish, Mildly Bearish, Bearish or Very
Bearish ratings.
For more examples on AFL commentaries please check AFL formula library especially
MACD commentary formula which demonstrates all techniques presented here.
Now you are ready to start with your own commentaries... Good luck!
How to write your own chart commentary
203
AmiBroker 5.80 User’s Guide
Tutorial
Using studies in AFL formulas
AmiBroker 3.52 introduces ability to reference hand-drawn studies from AFL
formulas. This feature is quite unique among trading software and as you will
find out using this feature is quite easy.
I will show you an example how to check if the trend line is broken from AFL
code. All we need to do is three simple steps:
1. Draw a trend line
2. Define study ID
3. Write the formula that checks trend line break
Drawing trend line
A trend line is a sloping line drawn between two
prominent points on a chart.
In this example we will draw the rising trend line
that defines the uptrend. This kind of trend line is
usually drawn between two (or more) troughs (low
points) to illustrate price support.
For sure you know how to draw a trend line in
AmiBroker - just select a "Trend line" tool from
"Draw" toolbar, find at least two recent troughs and
just draw the line.
Define study ID
As you probably know, you can modify the properties of
each line drawn in AmiBroker by clicking with the
right mouse button over the study and selecting
"Properties" from the menu. The properties dialog that
shows up allows you to define exact start/end points
and choose line colour, style and left and/or right
extension mode.
For further analysis we will use the right-extended
trend line (click on appropriate checkbox) to make
sure that the trend line is automaticaly extended when
new data are added.
Since version 3.52 the properties dialog allows also to define "Study ID" (the
combo below colour box). "Study ID" is a two-letter code of the study that can be
assigned to any study within a chart that allows AmiBroker to reference it from
AFL. Predefined 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).
This way if you draw the support lines in many symbols and give them all "SU"
Using studies in AFL formulas
204
AmiBroker 5.80 User’s Guide
Tutorial
identifier then you will be able to reference the support line from AFL code.
So we will assign the "SU" study ID to the rising support trend line we have just
drawn.
Write the formula that checks trend line break
In this example we will detect if the closing price drops BELOW support trend
line. This is actually very simple:
sell = cross( study( "SU" ), close, GetChartID() );
Note that study() function accepts two arguments: the first is StudyID two letter
code that corresponds to one given in properites dialog; the second argument is
chart ID - it should be taken either via GetChartID() function (then it refers to
current indicator) or read from Parameter dialog, Axes & Grid: Miscellaneous:
Chart ID.
Using studies in AFL formulas
205
AmiBroker 5.80 User’s Guide
Tutorial
Back-testing your trading ideas
Introduction
One of the most useful things that you can do in the analysis window is to
back-test your trading strategy on historical data. This can give you valuable
insight into strengths and weak points of your system before investing real
money. This single AmiBroker feature is can save lots of money for you.
Writing your trading rules
First you need to have objective (or mechanical) rules to enter and exit the
market. This step is the base of your strategy and you need to think about it
yourself since the system must match your risk tolerance, portfolio size, money
management techniques, and many other individual factors.
Once you have your own rules for trading you should write them as buy and sell
rules in AmiBroker Formula Lanugage (plus short and cover if you want to test
also short trading).
In this chapter we will consider very basic moving average cross over system. The
system would buy stocks/contracts when close price rises above 45-day exponential
moving average and will sell stocks/contracts when close price falls below 45-day
exponential moving average.
The exponential moving average can be calculated in AFL using its built-in
function EMA. All you need to do is to specify the input array and averaging
period, so the 45-day exponential moving average of closing prices can be
obtained by the following statement:
ema( close, 45 );
The close identifier refers to built-in array holding closing prices of currently
analysed symbol.
To test if the close price crosses above exponential moving average we will use
built-in cross function:
buy = cross( close, ema( close, 45 ) );
The above statement defines a buy trading rule. It gives "1" or "true" when close
price crosses above ema( close, 45 ). Then we can write the sell rule which would
give "1" when opposite situation happens - close price crosses below ema( close,
45 ):
sell = cross( ema( close, 45 ), close );
Please note that we are using the same cross function but the opposite order of
arguments.
So complete formula for long trades will look like this:
Back-testing your trading ideas
206
AmiBroker 5.80 User’s Guide
Tutorial
buy = cross( close, ema( close, 45 ) );
sell = cross( ema( close, 45 ), close );
NOTE: To create new formula please open Formula Editor using Analysis->Formula
Editor menu, type the formula and choose Tools->Send to Analysis menu in Formula
editor
Back testing
To back-test your system just click on the Back test button in the Automatic
analysis window. Make sure you have typed in the formula that contains at least
buy and sell trading rules (as shown above). When the formula is correct
AmiBroker starts analysing your symbols according to your trading rules and
generates a list of simulated trades. The whole process is very fast - you can
back test thousands of symbols in a matter of minutes. The progress window will
show you estimated completion time. If you want to stop the process you can just
click Cancel button in the progress window.
Analysing results
When the process is finished the list of simulated trades is shown in the bottom
part of Automatic analysis window. (the Results pane). You can examine when the
buy and sell signals occurred just by double clicking on the trade in Results
pane. This will give you raw or unfiltered signals for every bar when buy and
sell conditions are met. If you want to see only single trade arrows (opening and
closing currently selected trade) you should double click the line while holding
SHIFT key pressed down. Alternatively you can choose the type of display by
selecting appropriate item from the context menu that appears when you click on
the results pane with a right mouse button.
In addition to the results list you can get very detailed statistics on the
performance of your system by clicking on the Report button. To find out more
about report statistics please check out report window description.
Changing your back testing settings
Back testing engine in AmiBroker uses some predefined values for performing its
task including the portfolio size, periodicity (daily/weekly/monthly), amount of
commission, interest rate, maximum loss and profit target stops, type of trades,
price fields and so on. All these settings could be changed by the user using
settings window. After changing settings please remember to run your back testing
again if you want the results to be in-sync with the settings.
For example, to back test on weekly bars instead of daily just click on the
Settings button select Weekly from Periodicity combo box and click OK, then run
your analysis by clicking Back test.
Reserved variable names
The following table shows the names of reserved variables used by Automatic
Analyser. The meaning and examples on using them are given later in this chapter.
Back-testing your trading ideas
207
AmiBroker 5.80 User’s Guide
Tutorial
Variable
Usage
Applies to
buy
defines "buy" (enter long position) trading rule
Automatic
Analysis,
Commentary
sell
defines "sell" (close long position) trading rule
Automatic
Analysis,
Commentary
short
defines "short" (enter short position - short sell)
trading rule
Automatic
Analysis
cover
defines "cover" (close short position - buy to cover)
trading rule
Automatic
Analysis
buyprice
defines buying price array (this array is filled in
with the default values according to the Automatic
Analyser settings)
Automatic
Analysis
sellprice
defines selling price array (this array is filled in
with the default values according to the Automatic
Analyser settings)
Automatic
Analysis
shortprice
defines short selling price array (this array is
filled in with the default values according to the
Automatic Analyser settings)
Automatic
Analysis
coverprice
defines buy to cover price array (this array is
filled in with the default values according to the
Automatic Analyser settings)
Automatic
Analysis
exclude
If defined, a true (or 1) value of this variable
excludes current symbol from scan/exploration/back
test. They are also not considered in buy and hold
calculations. Useful when you want to narrow your
analysis to certain set of symbols.
Automatic
Analysis
roundlotsize
defines round lot sizes used by backtester (see
explanations below)
Automatic
Analysis
(new in
4.10)
ticksize
defines tick size used to align prices generated by
built-in stops (see explanations below) (note: it
does not affect entry/exit prices specified by
buyprice/sellprice/shortprice/coverprice)
Automatic
Analysis
(new in
4.10)
pointvalue
allows to read and modify future contract point value
(see backtesting futures)
CAVEAT: this AFL variable is by default set to 1
(one) regardless of contents of Information window
UNLESS you turn ON futures mode
(SetOption("FuturesMode", True ))
Automatic
Analysis
(new in
4.10)
margindeposit
allows to read and modify future contract margin (see
backtesting futures)
Automatic
Analysis
(new in
4.10)
Back-testing your trading ideas
208
AmiBroker 5.80 User’s Guide
positionsize
Allows control dollar amount or percentage of
portfolio that is invested into the trade (see
explanations below)
Tutorial
Automatic
Analysis
(new in 3.9)
Advanced concepts
Until now we discussed fairly simple use of the back tester. AmiBroker, however
supports much more sophisticated methods and concepts that will be discussed
later on in this chapter. Please note that the beginner user should first play a
little bit with the easier topics described above before proceeding.
So, when you are ready, please take a look at the following recently introduced
features of the back-tester:
a) AFL scripting host for advanced formula writers
b) enhanced support for short trades
c) the way to control order execution price from the script
d) various kinds of stops in back tester
e) position sizing
f) round lot size and tick size
g) margin account
h) backtesting futures
AFL scripting host is an advanced topic that is covered in a separate document
available here and I won’t discuss it in this document. Remaining features are
much more easy to understand.
Short trade support
In the previous versions of AmiBroker, if you wanted to back-test system using
both long and short trades, you could only simulate stop-and-reverse strategy.
When long position was closed a new short position was opened immediatelly. It
was because buy and sell reserved variables were used for both types of trades.
Now (with version 3.59 or higher) there are separate reserved variables for
opening and closing long and short trades:
buy - "true" or 1 value opens long trade
sell - "true" or 1 value closes long trade
short - "true" or 1 value opens short trade
cover - "true" or 1 value closes short trade
Som in order to back-test short trades you need to assign short and cover
variables.
If you use stop-and-reverse system (always on the market) simply assign sell to
short and buy to cover
short = sell;
cover = buy;
This simulates the way pre-3.59 versions worked.
Back-testing your trading ideas
209
AmiBroker 5.80 User’s Guide
Tutorial
But now AmiBroker enables you to have separate trading rules for going long and
for going short as shown in this simple example:
// long trades entry and exit rules:
buy = cross( cci(), 100 );
sell = cross( 100, cci() );
// short trades entry and exit rules:
short = cross( -100, cci() );
cover = cross( cci(), -100 );
Note that in this example if CCI is between -100 and 100 you are out of the
market.
Controlling trade price
AmiBroker now provides 4 new reserved variables for specifying the price at which
buy, sell, short and cover orders are executed. These arrays have the following
names: buyprice, sellprice, shortprice and coverprice.
The main application of these variables is controlling trade price:
BuyPrice = IIF( dayofweek() == 1, HIGH, CLOSE );
// on monday buy at high, otherwise buy on close
So you can write the following to simulate real stop-orders:
BuyStop = ... the formula for buy stop level;
SellStop = ... the formula for sell stop level;
// if anytime during the day prices rise above buystop level
(high>buystop)
// the buy order takes place (at buystop or low whichever is higher)
Buy = Cross( High, BuyStop );
// if anytime during the day prices fall below sellprice level ( low
< sellstop )
// the sell order takes place (at sellstop or high whichever is
lower)
Sell = Cross( SellPrice, SellStop);
BuyPrice = max( BuyStop, Low ); // make sure buy price not less than
Low
SellPrice = min( SellStop, High ); // make sure sell price not
greater than High
Please note that AmiBroker presets buyprice, sellprice, shortprice and coverprice
array variables with the values defined in system test settings window (shown
below), so you can but don’t need to define them in your formula. If you don’t
define them AmiBroker works as in the old versions.
Back-testing your trading ideas
210
AmiBroker 5.80 User’s Guide
Tutorial
During back-testing AmiBroker will check if the values you assigned to buyprice,
sellprice, shortprice, coverprice fit into high-low range of given bar. If not,
AmiBroker will adjust it to high price (if price array value is higher than high)
or to the low price (if price array value is lower than low)
Back-testing your trading ideas
211
AmiBroker 5.80 User’s Guide
Tutorial
Profit target stops
As you can see in the picture above, new settings for profit target stops are
Back-testing your trading ideas
212
AmiBroker 5.80 User’s Guide
Tutorial
available in the system test settings window. Profit target stops are executed
when the high price for a given day exceedes the stop level that can be given as
a percentage or point increase from the buying price. By default stops are
executed at price that you define as sell price array (for long trades) or cover
price array (for short trades). This behaviour can be changed by using "Exit at
stop" feature.
"Exit at stop" feature
If you mark "Exit at stop" box in the settings the stops will be executed at
exact stop level, i.e. if you define profit target stop at +10% your stop and the
buy price was 50 stop order will be executed at 55 even if your sell price array
contains different value (for example closing price of 56).
Maximum loss stops work in a similar manner - they are executed when the low
price for a given day drops below the stop level that can be given as a
percentage or point increase from the buying price
Trailing stops
This kind of stop is used to protect profits as it tracks your trade so each time
a position value reaches a new high, the trailing stop is placed at a higher
level. When the profit drops below the trailing stop level the position is
closed. This mechanism is illustrated in the picture below (10% trailing stop is
shown):
<
The trailing stop, as well as two other kind of stops could be enabled from user
interface (Automatic analysis’ Settings window) or from the formula level - using
ApplyStop function:
Back-testing your trading ideas
213
AmiBroker 5.80 User’s Guide
Tutorial
To reproduce the example above you would need to add the following code to your
automatic analysis formula:
ApplyStop( 2, 1, 10, 1 ); // 10% trailing stop, percent mode, exit at stop ON
or you can write it using predefined constants that are more descriptive
ApplyStop( stopTypeTrail, stopModePercent, 10, True );
Trailing stops could be also defined in points (dollars) and percent of profit
(risk). In the latter case the amount parameter defines the percentage of profits
that could be lost without activating the stop. So 20% percent of profit (risk)
stop will exit your trade that has maximum profit of $100 when the profit
decreases below $80.
Dynamic stops
The ApplyStop() function allows now to change the stop level from trade to trade.
This enables you to implement for example volatility-based stops very easily.
For example to apply maximum loss stop that will adapt the maximum acceptable
loss based on 10 day average true range you would need to write:
ApplyStop( 0, 2, 2 * ATR( 10 ), 1 );
or you can write it using predefined constants that are more descriptive
ApplyStop( stopTypeLoss, stopModePoint, 2 * ATR( 10 ), True );
The function above will place the stop 2 times 10 day ATR below entry price.
As ATR changes from trade to trade - this will result in dynamic, volatility
based stop level. Please note that 3rd parameter of ApplyStop function (the
amount) is sampled at the trade entry and held troughout the trade. So in the
example above it uses ATR(10) value from the date of the entry. Further changes
of ATR do not affect the stop level.
See complete APPLYSTOP function documentation for more details.
Coding your own custom stop types
ApplyStop function is intended to cover most "popular" kinds of stops. You can
however code your own kind of stops and exits using looping code. For example the
following re-implements profit target stop and shows how to refer to the trade
entry price in your formulas:
/* a sample low-level implementation of Profit-target stop in AFL: */
Buy = Cross( MACD(), Signal() );
priceatbuy=0;
Back-testing your trading ideas
214
AmiBroker 5.80 User’s Guide
Tutorial
for( i = 0; i < BarCount; i++ )
{
if( priceatbuy == 0 &Buy[ i ] )
priceatbuy = BuyPrice[ i ];
if( priceatbuy > 0 &SellPrice[ i ] > 1.1 * priceatbuy )
{
Sell[ i ] = 1;
SellPrice[ i ] = 1.1 * priceatbuy;
priceatbuy = 0;
}
else
Sell[ i ] = 0;
}
Position sizing
This is a new feature in version 3.9. Position sizing in backtester is
implemented by means of new reserved variable
PositionSize = <size array>
Now you can control dollar amount or percentage of portfolio that is invested
into the trade
• positive number define (dollar) amount that is invested into the trade for
example:
PositionSize = 1000; // invest $1000 in every trade
• negative numbers -100..-1 define percentage:
-100 gives 100% of current portfolio size,
-33 gives 33% of available equity for example:
PositionSize = -50; /* always invest only half of the current equity */
• dynamic sizing example:
PositionSize = - 100 + RSI();
as RSI varies from 0..100 this will result in position depending on RSI
values -> low values of RSI will result in higher percentage invested
If less than 100% of available cash is invested then the remaining amount earns
interest rate as defined in the settings.
There is also a new checkbox in the AA settings window: "Allow position size
shrinking" - this controls how backtester handles the situation when requested
position size (via PositionSize variable) exceeds available cash: when this flag
is checked the position is entered with size shinked to available cash if it is
unchecked the position is not entered.
Back-testing your trading ideas
215
AmiBroker 5.80 User’s Guide
Tutorial
To see actual position sizes please use a new report mode in AA settings window:
"Trade list with prices and pos. size"
For the end, here is an example of Tharp’s ATR-based position sizing technique
coded in AFL:
Buy = <your buy formula here>
Sell = 0; // selling only by stop
TrailStopAmount = 2 * ATR( 20 );
Capital = 100000; /* IMPORTANT: Set it also in the Settings: Initial Equity */
Risk = 0.01*Capital;
PositionSize = (Risk/TrailStopAmount)*BuyPrice;
ApplyStop( 2, 2, TrailStopAmount, 1 );
The technique could be summarized as follows:
The total equity per symbol is $100,000, we set the risk level at 1% of total
equity. Risk level is defined as follows: if a trailing stop on a $50 stock is
at, say, $45 (the value of two ATR’s against the position), the $5 loss is
divided into the $1000 risk to give 200 shares to buy. So, the loss risk is $1000
but the allocation risk is 200 shares x $50/share or $10,000. So, we are
allocating 10% of the equity to the purchase but only risking $1000. (Edited
excerpt from the AmiBroker mailing list)
Round lot size and tick size
Round lot size
Various instruments are traded with various "trading units" or "blocks". For
example you can purchase fractional number of units of mutual fund, but you can
not purchase fractional number of shares. Sometimes you have to buy in 10s or
100s lots. AmiBroker now allows you to specify the block size on global and
per-symbol level.
You can define per-symbol round lot size in the Symbol->Information page (pic.
3). The value of zero means that the symbol has no special round lot size and
will use "Default round lot size" (global setting) from the Automatic Analysis
settings page (pic. 1). If default size is set also to zero it means that
fractional number of shares/contracts are allowed.
You can also control round lot size directly from your AFL formula using
RoundLotSize reserved variable, for example:
RoundLotSize = 10;
Tick size
This setting controls the minimum price move of given symbol. You can define it
on global and per-symbol level. As with round lot size, you can define per-symbol
tick size in the Symbol->Information page (pic. 3). The value of zero instructs
Back-testing your trading ideas
216
AmiBroker 5.80 User’s Guide
Tutorial
AmiBroker to use "default tick size" defined in the Settings page (pic. 1) of
Automatic Analysis window. If default tick size is also set to zero it means that
there is no minimum price move.
You can set and retrieve the tick size also from AFL formula using TickSize
reserved variable, for example:
TickSize = 0.01;
Note that the tick size setting affects ONLY trades exited by built-in stops
and/or ApplyStop(). The backtester assumes that price data follow tick size
requirements and it does not change price arrays supplied by the user.
So specifying tick size makes sense only if you are using built-in stops so exit
points are generated at "allowed" price levels instead of calculated ones. For
example in Japan - you can not have fractional parts of yen so you should define
global ticksize to 1, so built-in stops exit trades at integer levels.
Margin account
Account margin setting defines percentage margin requirement for entire account.
The default value of Account margin is 100. This means that you have to provide
100% funds to enter the trade, and this is the way how backtester worked in
previous versions. But now you can simulate a margin account. When you buy on
margin you are simply borrowing money from your broker to buy stock. With current
regulations you can put up 50% of the purchase price of the stock you wish to buy
and borrow the other half from your broker. To simulate this just enter 50 in the
Account margin field (see pic. 1) . If your intial equity is set to 10000 your
buying power will be then 20000 and you will be able to enter bigger positions.
Please note that this settings sets the margin for entire account and it is NOT
related to futures trading at all. In other words you can trade stocks on margin
account.
Additional settings
• "Reverse entry signal forces exit" check box to the Backtester settings.
When it is ON (the default setting) - backtester works as in previous
versions and closes already open positon if new entry signal in reverse
direction is encountered. If this switch is OFF - even if reverse signal
occurs backtester maintains currently open trade and does not close positon
until regular exit (sell or cover) signal is generated.
In other words when this switch is OFF backtester ignores Short signals
during long trades and ignores Buy signals during short trades.
• "Allow same bar exit (single bar trade)" option to the Settings
When it is ON (the default settings) - entry and exit at the very same bar
is allowed (as in previous versions)
if it is OFF - exit can happen starting from next bar only (this applies to
regular signals,there is a separate setting for ApplyStop-generated exits).
Switching it to OFF allows to reproduce the behaviour of MS backtester that
is not able to handle same day exits.
Back-testing your trading ideas
217
AmiBroker 5.80 User’s Guide
Tutorial
• "Activate stops immediately"
This setting solves the problem of testing systems that enter trades on
market open. In versions prior to 4.09 backtester assumed that you were
entering trades on market close so built-in stops were activated from the
next day. The problem was when you in fact defined open price as the trade
entry price - then same day price fluctuations did not trigger the stops.
There were some published workarounds based on AFL code but now you don’t
need to use them. Simply if you trade on open you should mark "Activate
stops immediately" (pic. 1).
You may ask why do not simply check the buyprice or shortprice array if it
is equal to open price. Unfortunatelly this won’t work. Why? Simply because
there are doji days when open price equals close and then backtester will
never know if trade was entered at market open or close. So we really need
a separate setting.
• "Use QuickAFL"
QuickAFL(tm) is a feature that allows faster AFL calculation under certain
conditions. Initially (since 2003) it was available for indicators only, as
of version 5.14+ it is available in Automatic Analysis too.
Initially the idea was to allow faster chart redraws through calculating
AFL formula only for that part which is visible on the chart. In a similar
manner, automatic analysis window can use subset of available quotations to
calculate AFL, if selected range parameter is less than All quotations".
Detailed explanation on how QuickAFL works and how to control it, is
provided in this Knowledge Base article:
http://www.amibroker.com/kb/2008/07/03/quickafl/
Note that this option works not only in the backtester, but also in
optimizations, explorations and scans.
See Also:
Portfolio-level backtesting article.
Backtesting systems for futures contracts article.
APPLYSTOP function description
Using AFL editor section of the guide.
Insider guide to backtester (newsletter 1/2002)
Back-testing your trading ideas
218
AmiBroker 5.80 User’s Guide
Tutorial
Portfolio-level backtesting
IMPORTANT: Please read first Tutorial: Backtesting your trading ideas article
New backtester works on PORTFOLIO LEVEL, it means that there is single portfolio
equity and position sizing refers to portfolio equity. Portfolio equity is equal
to available cash plus sum of all simultaneously open positions at given time.
AmiBroker’s portfolio backtester lets you combine trading signals and trade
sizing strategies into simulations which exactly mimic the way you would trade in
real time. A core feature is its ability to perform dynamic money management and
risk control at the portfolio level. Position sizes are determined with full
knowledge of what’s going on at the portfolio level at the moment the sizing
decision is made. Just like you do in reality.
HOW TO SET IT UP ?
There are only two things that need to be done to perform portfolio backtest
1. You need to have first the formula that generates buy / sell / short /cover
signals as described in "Backtesting your trading ideas" article
2. You should define how many simultaneous trades you want to test and what
position sizing algorithm you want to use.
SETTING UP MAXIMUM NUMBER OF SIMULTANEOUSLY OPEN TRADES
There are two ways to set the maximum number of simultaneously open trades:
1. Go to the Settings dialog, switch to Portfolio tab and enter the number to
Max. Open Positions field
2. Define the maximum in the formula itself (this overrides any setting in the
Settings window) using SetOption function:
SetOption("MaxOpenPositions", 5 ); // This sets maximum number of open positions
to 5
SETTING UP POSITION SIZE
IMPORTANT: to enable more than one symbol to be traded you have to add
PositionSize variable to your formula, so less than 100% of funds are invested in
single security:
PositionSize = -25; // invest 25% of portfolio equity in single trade
or
PositionSize = 5000; // invest $5000 into single trade
There is a quite common way of setting both position size and maximum number of
Portfolio-level backtesting
219
AmiBroker 5.80 User’s Guide
Tutorial
open positions so equity is spread equally among trades:
PosQty = 5; // You can define here how many open positions you want
SetOption("MaxOpenPositions", PosQty );
PositionSize = -100/PosQty; // invest 100% of portfolio equity divided by max.
position count
You can also use more sophisticated position sizing methods. For example
volatility-based position sizing (Van Tharp-style):
PositionSize = -2 * BuyPrice/(2*ATR(10));
That way you are investing investing 2% of PORTFOLIO equity in the trade adjusted
by BuyPrice/2*ATR factor.
USING POSITION SCORE
You can use new PositionScore variable to decide which trades should be entered
if there are more entry signals on different securities than maximum allowable
number of open positions or available funds. In such case AmiBroker will use the
absolute value of PositionScore variable to decide which trades are preferred.
See the code below. It implements simple MA crossover system, but with additional
flavour of preferring entering trades on symbols that have low RSI value. If more
buy signals occur than available cash/max. positions then the stock with lower
RSI will be preferred. You can watch selection process if you backtest with
"Detailed log" report mode turned on.
The code below includes also the example how to find optimum number of
simultaneously open positions using new Optimization in Porfolio mode.
/*****
** REGULAR PORTFOLIO mode
** This sample optimization
** finds what is optimum number of positions open simultaneously
**
****/
SetOption("InitialEquity", 20000 );
SetTradeDelays(1,1,1,1);
RoundLotSize = 1;
posqty = Optimize("PosQty", 4, 1, 20, 1 );
SetOption("MaxOpenPositions", posqty);
// desired position size is 100% portfolio equity
// divided by PosQty positions
PositionSize = -100/posqty;
// The system is very simple...
// MA parameters could be optimized too...
p1 = 10;
Portfolio-level backtesting
220
AmiBroker 5.80 User’s Guide
Tutorial
p2 = 22;
// simple MA crossover
Short=Cross( MA(C,p1) , MA(C,p2) );
Buy=Cross( MA(C,p2) , MA(C,p1) );
// always in the market
Sell=Short;
Cover=Buy;
// now additional score
// that is used to rank equities
// when there are more ENTRY signals that available
// positions/cash
PositionScore = 100-RSI(); // prefer stocks that have low RSI;
BACKTEST MODES
AmiBroker 5.0 offers 6 different backtest modes:
•
•
•
•
•
•
regular mode (backtestRegular)
regular raw mode (backtestRegularRaw)
regular raw + multiple positions mode (backtestRegularRawMulti)
regular raw2 mode (backtestRegularRaw2)
regular raw2 + multiple positions mode (backtestRegularRaw2Multi)
rotational trading mode (backtestRotational)
All "regular" modes use buy/sell/short/cover signals to enter/exit trades, while
"rotational" mode (aka "ranking / switching" system) uses only position score and
is descibed later.
Backtest modes are switchable using SetBacktestMode() AFL function.
The difference between "regular" modes is how repeated (also known as "redundant"
or "extra") entry signals are handled. An "extra" entry signal is the signal that
comes AFTER initial entry but before first matching exit signal.
In the regular mode - the default one, redundant entry signals are removed as
shown in the picture below.
Portfolio-level backtesting
221
AmiBroker 5.80 User’s Guide
Tutorial
As you can see Buy-Sell signal pairs are matched and treated as a TRADE. If trade
is NOT entered on first entry signal due to weak rank, not enough cash or
reaching the maximum open position count, subsequent entry signals are ignored
until matching exit signal. After exit signal, the next entry signal will be
possible candidate for entering trade. The process of removing excess signals
occurring after first buy and matching sell (and short-cover pair respectively)
is the same as ExRem() AFL function provides. To use regular mode you don’t need
to call SetBacktestMode function at all, as this is the default mode.
You may or may not consider removing extra signals desirable. If you want to act
on ANY entry signal you need to use second mode - backtestRegularRaw. To turn it
on you need to include this line in the code:
// signal-based backtest, redundant (raw) signals are NOT removed, only one
position per symbol allowed
SetBacktestMode( backtestRegularRaw );
It does NOT remove redundant entry signals and will act on ANY entry provided
that it is scored highly enough and there is a cash available and maximum number
of open positions is not reached. It will however allow only ONE OPEN POSITION
per symbol at any given time. It means that if log trade is already open and
later in the sequence appears an extra buy signal, it will be ignored until a
Portfolio-level backtesting
222
AmiBroker 5.80 User’s Guide
Tutorial
"sell" signal comes (short-cover signals work the same). Note that you can still
use sigScaleIn/sigScaleOut to increase or decrease the size of this existing
position, but it will appear as single line in backtest result list.
If you want ALL repeated entry signals to be acted and allow to open multiple,
separate positions on the same symbol without scaling in/out effect (so multiple
positions on the same symbol open simultaneously appear as separate lines in the
backtest report) you need to use backtestRegularRawMulti mode by adding the
following line to the code:
SetBacktestMode( backtestRegularRawMulti );
In this mode MULTIPLE positions per symbol will be open if BUY/SHORT signal is
"true" for more than one bar and there are free funds. Sell/Cover exit all open
positions on given symbol, Scale-In/Out work on all open positions of given
symbol at once.
Remark: The remaining modes are for advanced users only
Raw2 modes are "special" for advanced users of custom backtester. They are only
useful if you do custom processing of exit signals in custom backtester
procedure. They should NOT be used otherwise, because of performance hit and
memory consumption Raw2 modes cause.
The common thing between Raw and Raw2 modes is that they both do NOT remove
excess ENTRY signals. The difference is that Raw modes remove excess EXIT
signals, while Raw2 do NOT.
In Raw2 modes all exit signals (even redundant ones) are passed to second phase
of backtest just in case that you want implement strategy that skips first exit.
Lets suppose that you want to exit on some condition from first phase but only in
certain hours or after certain numbers of bars in trade or only when portfolio
equity condition is met. Now you can do that in Raw2 modes.
Note that Raw2 modes can get significantly slower when you are using custom
backtester code that iterates thru signals as there can be zillions of exit
signals in the lists even for symbols that never generated any entry signals,
therefore it is advised to use it only when absolutely necessary. Raw2 modes are
also the most memory consuming. Note also that if you run the system WITHOUT
custom backtest procedure there should be no difference between Raw and Raw2
modes (other than speed & memory usage) as first matching exit signal is what is
used by default.
ROTATIONAL TRADING
Rotational trading (also known as fund-switching or scoring and ranking) is
possible too. For more information see the description of EnableRotationalTrading
function.
HOLDMINBARS and EARLY EXIT FEES
(Note that these features are available in portfolio-backtester only and not
compatible with old backtester or Equity() function)
Portfolio-level backtesting
223
AmiBroker 5.80 User’s Guide
Tutorial
HoldMinBars is a feature that disables exit during user-specified number of bars
even if signals/stops are generated during that period
Please note that IF during HoldMinBars period ANY stop is generated it is
ignored. Also this period is ignored when it comes to calculation of trailing
stops (new highest highs and drops below trailing stops generated during
HoldMinBars are ignored).This setting, similar to EarlyExitFee/EarlyExitBars is
available on per-symbol basis (i.e. it can be set to different value for each
symbol)
Example:
SetOption("HoldMinBars", 127 );
Buy=BarIndex()==0;
Sell=1;
// even if sell signals are generated each day,
//they are ignored until bar 128
Early exit (redemption) fee is charged when trade is exited during first N bars
since entry.
The fee is added to exit commission and you will see it in the commissions
reported for example in detailed log. However, it is NOT reflected in the
portfolio equity unless trade really exits during first N bars - this is to
prevent affecting drawdowns if trade was NOT exited early.
// these two new options can be set on per-symbol basis
// how many bars (trading days)
// an early exit (redemption) fee is applied
SetOption("EarlyExitBars", 128 );
// early redemption fee (in percent)
SetOption("EarlyExitFee", 2 );
(note 180 calendar days is 128 or 129 trading days)
// how to set it up on per-symbol basis?
// it is simple - use ’if’ statement
if( Name() == "SYMBOL1" )
{
SetOption("EarlyExitBars", 128 );
SetOption("EarlyExitFee", 2 );
}
if( Name() == "SYMBOL2" )
{
SetOption("EarlyExitBars", 25 );
SetOption("EarlyExitFee", 1 );
}
In addition to HoldMinBars, EarlyExitBars there are sibling features (added in
4.90) called HoldMinDays and EarlyExitDays that work with calendar days instead
of data bars. So we can rewrite previous examples to use calendar days
accurately:
Portfolio-level backtesting
224
AmiBroker 5.80 User’s Guide
Tutorial
// even if sell signals are generated each day,
//they are ignored until 180 calendar days since entry
SetOption("HoldMinBars", 180 );
Buy=BarIndex()==0;
Sell=1;
// these two new options can be set on per-symbol basis
// how many CALENDAR DAYS
// an early exit (redemption) fee is applied
SetOption("EarlyExitDays", 180 );
// early redemption fee (in percent)
SetOption("EarlyExitFee", 2 );
(note 180 calendar days is 128 or 129 trading days)
// how to set it up on per-symbol basis?
// it is simple - use ’if’ statement
if( Name() == "SYMBOL1" )
{
SetOption("EarlyExitDays", 180 );
SetOption("EarlyExitFee", 2 );
}
if( Name() == "SYMBOL2" )
{
SetOption("EarlyExitDays", 30 );
SetOption("EarlyExitFee", 1 );
}
RESOLVING SAME BAR, SAME SYMBOL SIGNAL CONFLICTS
It is possible for the system to generate on the very same symbol both entry and
exit signal at the very same bar. Consider for example, this very simple system
that generates buy and sell signals on every bar:
Buy = 1;
Sell = 1;
If you add an exploration code to it to show the signals:
AddColumn(Buy,"Buy", 1.0 );
AddColumn(Sell, "Sell", 1.0 );
Filter = Buy OR Sell;
you will get the following output (when you press Explore);
Portfolio-level backtesting
225
AmiBroker 5.80 User’s Guide
Tutorial
Now because of the fact that entry and exit signals do NOT carry any timing
information, so you don’t know which signal comes first, there are three ways how
such conflicting same bar, entry and exit signals may be interpreted:
1. only one signal is taken at any bar, so trade that begins on bar 1 ends on
bar 2 and next trade may only be open on bar 3 and closed on bar 4
2. both signals are used and entry signal precedes exit signal, so trade that
begins on bar 1 ends on bar 1, then text trade opens on bar 2 and ends on
bar 2, and so on (we have single-bar trades and we are out of market
between bars)
3. both signals are used and entry signal comes after exit signal. In this
situation the very first signal (exit) is ignored because we are flat, and
trade is open on same bar entry signal. Then we don’t have any more signals
for given bar and trade is closed on the next bar exit signal, then we get
another entry (same bar). So trade that begins on bar 1 ends on bar 2, then
text trade opens on bar 2 and ends on bar 3, and so on (we have trades that
span between bars, but both exit and entry signal occuring on the very same
bar are acted upon)
Since, as we mentioned already, buy/sell/short/cover arrays do not carry timing
information we have to somehow tell AmiBroker how to interpret such conflict. One
would think that it is enough to set buyprice to open and sellprice to close to
deliver timing information, but it is NOT the case. Price arrays themselves DO
NOT provide timing information neither. You may ask why. This is quite simple,
first of all trading prices do not need to be set to exact open/close. In several
scenarios you may want to define buyprice as open + slippage and sellprice as
close - slippage. Even if you do use exact open and close, it happens quite often
that open is equal close (such ase defines a doji candlestick) and then there is
no way to find out from price alone, whenever it means close or open. So again
buyprice/sellprice/shortprice/coverprice variables DO NOT provide any timing
information.
The only way to control the way how same bar, same symbol entry/exit conflicts
are resolved is via AllowSameBarExit option and HoldMinBars option.
Scenario 1. Only one signal per symbol is taken at any bar
Portfolio-level backtesting
226
AmiBroker 5.80 User’s Guide
Tutorial
This scenario is used when AllowSameBarExit option is set to False (turned off).
In this case it does not really matter whether exit or entry was the first within
single bar. It is quite easy to understand: on any bar only one signal is acted
upon. So if we are flat on given symbol, then entry signal is taken (with buy
signal taking precedence over short), other signals are ignored and we move to
next bar. If we are long on given symbol, then sell signal is taken, trade is
exited and we move to next bar ignoring other signals. If we are short on given
symbol then cover signal is taken, trade is exited and we move to next bar again
ignoring other signals. If there we are in the market but there is no matching
exit signal - the position is kept and we move to next bar.
SetOption("AllowSameBarExit", False );
Buy = 1;
Sell = 1;
The following pictures show which signals are taken and resulting trade list. All
trades begin one day and end next day. New trade is open on the following day.
Scenario 2. Both entry and exit signals are used and entry signal precedes exit
signal
This scenario is used when AllowSameBarExit option is set to True (turned on) and
HoldMinBars is set to zero (which is the default setting).
In this case we simply act on both signals immediately (same bar). So if we are
flat on given symbol, then entry signal is taken (with buy signal taking
precedence over short), but we do not move to the next bar immediately. Instead
we check if exit signals exist too. If we are long on given symbol, then sell
signal is taken. If we are short on given symbol then cover signal is taken. Only
after processing all signals we move to the next bar.
SetOption("AllowSameBarExit", True );
Buy = 1;
Sell = 1;
Portfolio-level backtesting
227
AmiBroker 5.80 User’s Guide
Tutorial
The following pictures show which signals are taken and resulting trade list. As
we can see, this time all signals are acted upon and we have sequence of
single-bar trades.
Scenario 3. Both signals are used and entry signal comes after exit signal.
This scenario is used when AllowSameBarExit option is set to True (turned on) and
HoldMinBars is set to 1 (or more).
In this case we simply act on both signals in single bar, but we respect the
HoldMinBars = 1 limitation, so trade that was just open can not be closed the
same bar. So if we are long on given symbol, then sell signal is taken. If we are
short on given symbol then cover signal is taken. We don’t move to next bar yet.
Now if we are flat on given symbol (possibly just exited position on this bar
exit signal), then entry signal is taken if any (with buy signal taking
precedence over short) and then we move to the next bar.
SetOption("AllowSameBarExit", True );
SetOption("HoldMinBars", 1 );
Buy=1;
Sell=1;
The following pictures show which signals are taken and resulting trade list. As
we can see, again all signals are acted upon BUT... trade duration is longer they are not same bar trades - they all span overnight.
Portfolio-level backtesting
228
AmiBroker 5.80 User’s Guide
Tutorial
How does it work in portfolio case?
The mechanism is the same regardless if you test on single symbol or multiple
symbols. First same-bar conflicts are resolved on every symbol separately the way
described above. Then, when you test on multiple symbols, resulting trade
candidates are subject to scoring by PositionScore described in earlier part of
this document.
Support for market-neutral, long-short balanced strategies
An investment strategy is considered market neutral if it seeks to entirely avoid
some form of market risk, typically by hedging. The strategy holds Long / short
equity positions, with long positions hedged with short positions in the same and
related sectors, so that the equity market neutral investor should be little
affected by sector- or market-wide events. This places, in essence, a bet that
the long positions will outperform their sectors (or the short positions will
underperform) regardless of the strength of the sectors.
In version 5.20 the following backtester options have been added to simplify
implementing market-neutral systems: SeparateLongShortRank, MaxOpenLong,
MaxOpenShort.
SeparateLongShortRank backtester option
To enable separate long/short ranking use:
SetOption("SeparateLongShortRank", True );
When separate long/short ranking is enabled, the backtester maintains TWO
separate "top-ranked" signal lists, one for long signals and one for short
signals. This ensures that long and short candidates are independently even if
position score is not symetrical (for example when long candidates have very high
positive scores while short candidates have only fractional negative scores).
That contrasts with the default mode where only absolute value of position score
matters, therefore one side (long/short) may completely dominate ranking if score
Portfolio-level backtesting
229
AmiBroker 5.80 User’s Guide
Tutorial
values are asymetrical.
When SeparateLongShortRank is enabled, in the second phase of backtest, two
separate ranking lists are interleaved to form final signal list by first taking
top ranked long, then top ranked short, then 2nd top ranked long, then 2nd top
ranked short, then 3rd top ranked long and 3rd top ranked short, and so on... (as
long as signals exist in BOTH long/short lists, if there is no more signals of
given kind, then remaining signals from either long or short lists are appended)
For example:
Entry signals(score):ESRX=Buy(60.93), GILD=Short(-47.56), CELG=Buy(57.68),
MRVL=Short(-10.75), ADBE=Buy(34.75), VRTX=Buy(15.55), SIRI=Buy(2.79),
As you can see Short signals get interleaved between Long signals even though
their absolute values of scores are smaller than corresponding scores of long
signals. Also there were only 2 short signals for that particular bar so, the
rest of the list shows long signals in order of position score. Although this
feature can be used independently, it is intended to be used in combination with
MaxOpenLong and MaxOpenShort options.
MaxOpenLong / MaxOpenShort backtester options
MaxOpenLong - limits the number of LONG positions that can be open simultaneously
MaxOpenShort - limits the number of SHORT positions that can be open
simultaneously
Example:
SetOption("MaxOpenPositions", 15 );
SetOption("MaxOpenLong", 11 );
SetOption("MaxOpenShort", 7 );
The value of ZERO (default) means NO LIMIT. If both MaxOpenLong and MaxOpenShort
are set to zero ( or not defined at all) the backtester works old way - there is
only global limit active (MaxOpenPositions) regardless of type of trade.
Note that these limits are independent from global limit (MaxOpenPositions). This
means that MaxOpenLong + MaxOpenShort may or may not be equal to
MaxOpenPositions.
If MaxOpenLong + MaxOpenShort is greater than MaxOpenPositions then total number
of positions allowed will not exceed MaxOpenPositions, and individual long/short
limits will apply too. For example if your system MaxOpenLong is set to 7 and
maxOpenShort is set to 7 and MaxOpenPositions is set to 10 and your system
generated 20 signals: 9 long (highest ranked) and 11 short, it will open 7 long
and 3 shorts.
If MaxOpenLong + MaxOpenShort is smaller than MaxOpenPositions (but greater than
zero), the system won’t be able to open more than (MaxOpenLong+MaxOpenShort).
Please also note that MaxOpenLong and MaxOpenShort only cap the number of open
positions of given type (long/short). They do NOT affect the way ranking is made.
I.e. by default ranking is performed using ABSOLUTE value of positionscore.
Portfolio-level backtesting
230
AmiBroker 5.80 User’s Guide
Tutorial
If your position score is NOT symetrical, this may mean that you are not getting
desired top-ranked signals from one side. Therefore, to fully utilise MaxOpenLong
and MaxOpenShort in rotational balanced ("market neutral") long/short systems it
is desired to perform SEPARATE ranking for long signals and short signals. To
enable separate long/short ranking use:
SetOption("SeparateLongShortRank", True );
See Also:
Backtesting your trading ideas article.
Backtesting systems for futures contracts article.
Using AFL editor section of the guide.
Insider guide to backtester (newsletter 1/2002)
Portfolio-level backtesting
231
AmiBroker 5.80 User’s Guide
Tutorial
Reading backtest report
To view the report of last backest simply click Report button in the automatic
analysis window. To view results of ALL past backtest, click drop down arrow on
the Report button and choose Report Explorer option. This will display the Report
Explorer window that will show the list of all backtests performed. If you double
click on the line - detailed report will be shown.
New report is hugely enhanced compared to old one. It includes separate
statistics for all, long and short sides as well as large number of new metrics.
You can get short help on given figure by hovering your mouse over given field
name. You will see the description in the tooltip. Short explanations are
provided also below:
Exposure % - ’Market exposure of the trading system calculated on bar by bar
basis. Sum of bar exposures divided by number of bars. Single bar exposure is the
value of open positions divided by portfolio equity.
Net Risk Adjusted Return % - Net profit % divided by Exposure %
Annual Return % - Compounded Annual Return % (CAR)
Risk Adjusted Return % - Annual return % divided by Exposure %
Avg. Profit/Loss, also known as Expectancy ($) - (Profit of winners + Loss of
losers)/(number of trades), represents expected dollar gain/loss per trade
Avg. Profit/Loss %, also known as Expectancy (%) - ’(% Profit of winners + % Loss
of losers)/(number of trades), represents expected percent gain/loss per trade
Avg. Bars Held - sum of bars in trades / number of trades
Max. trade drawdown - The largest peak to valley decline experienced in any
single trade. The lower the better
Max. trade % drawdown - The largest peak to valley percentage decline experienced
in any single trade. The lower the better
Max. system drawdown - The largest peak to valley decline experienced in
portfolio equity. The lower the better
Max. system % drawdown - The largest peak to valley percentage decline
experienced in portfolio equity. The lower the better
Recovery Factor - Net profit divided by Max. system drawdown
CAR/MaxDD - Compound Annual % Return divided by Max. system % drawdown. Good if
bigger than 2
RAR/MaxDD - Risk Adjusted Return divided by Max. system % drawdown. Good if
bigger than 2.
Reading backtest report
232
AmiBroker 5.80 User’s Guide
Tutorial
Profit Factor - Profit of winners divided by loss of losers
Payoff Ratio - Ratio average win / average loss
Standard Error - Standard error measures chopiness of equity line. The lower the
better.
Risk-Reward Ratio - Measure of the relation between the risk inherent in a
trading the system compared to its potential gain. Higher is better. Calculated
as slope of equity line (expected annual return) divided by its standard error.
Ulcer Index - Square root of sum of squared drawdowns divided by number of bars
Ulcer Performance Index - (Annual profit - Tresury notes profit)/Ulcer
Index’>Ulcer Performance Index. Currently tresury notes profit is hardcoded at
5.4. In future version there will be user-setting for this.
Sharpe Ratio of trades - Measure of risk adjusted return of investment. Above 1.0
is good, more than 2.0 is very good. More information
http://www.stanford.edu/~wfsharpe/art/sr/sr.htm . Calculation: first average
percentage return and standard deviation of returns is calculated. Then these two
figures are annualized by multipling them by ratio
(NumberOfBarsPerYear)/(AvgNumberOfBarsPerTrade). Then the risk free rate of
return is subtracted (currently hard-coded 5) from annualized average return and
then divided by annualized standard deviation of returns.
K-Ratio - Detects inconsistency in returns. Should be 1.0 or more. The higher K
ratio is the more consistent return you may expect from the system. Linear
regression slope of equity line multiplied by square root of sum of squared
deviations of bar number divided by standard error of equity line multiplied by
square root of number of bars. More information: Stocks & Commodities V14:3
(115-118): Measuring System Performance by Lars N. Kestner
Color-coding in the backtest report (new in 5.60)
Version 5.60 brings enhanced backtest report: color-coding ’good’ and ’bad’
values in backtest report. Some of the metrics in the backtest report are
color-coded. Blue means "neutral", Green means "good", Red means "bad". Metrics
that are not colorized are always black.
This color coding is of course arbitrary and should be used as guideance only.
Treat ’red’ as a warning flag and advice to check the value in detail.
As of now the following metrics are colorized:
Net Profit, Net Profit % - bad < 0, good > 0
Annual Profit %, bad < 0, neutral betwen 0 and 10, good > 10
RAR % bad < 0, good > (10 / Exposure)
Avg. Profit/Loss all trades (Expectancy $) - bad < 0, good > 0
Avg Profit/Loss % all trades (Expectancy %) - bad < 0, good > 0
Max. system % drawdown - bad: dd worse than -30%, neutral: dd between -30 and
-10%, good - -10% to 0%
CAR/MaxDD, RAR/MaxDD - bad < 1, neutral between 1 and 2, good > 2
Recovery factor - bad < 1, neutral between 1 and 2, good > 2
Reading backtest report
233
AmiBroker 5.80 User’s Guide
Tutorial
Payoff ratio - bad < 1, neutral between 1 and 2, good > 2
See Also:
Old backtest report
Backtesting your trading ideas article.
Portfolio Backtesting article.
Backtesting systems for futures contracts article.
Using AFL editor section of the guide.
Insider guide to backtester (newsletter 1/2002)
Reading backtest report
234
AmiBroker 5.80 User’s Guide
Tutorial
How to optimize trading system
NOTE: This is fairly advanced topic. Please read previous AFL tutorials first.
Introduction
The idea behind an optimization is simple. First you have to have a trading
system, this may be a simple moving average crossover for example. In almost
every system there are some parameters (as averaging period) that decide how
given system behaves (i.e. is is well suited for long term or short term, how
does is react on highly volatile stocks, etc). The optimization is the process of
finding optimal values of those parameters (giving highest profit from the
system) for a given symbol (or a portfolio of symbols). AmiBroker is one of the
very few programs that allow you to optimize your system on multiple symbols at
once.
To optimize your system you have to define from one upto ten parameters to be
optimized. You decide what is a minimum and maximum allowable value of the
parameter and in what increments this value should be updated. AmiBroker then
performs multiple back tests the system using ALL possible combinations of
parameters values. When this process is finished AmiBroker displays the list of
results sorted by net profit. You are able to see the values of optimization
parameters that give the best result.
Writing AFL formula
Optimization in back tester is supported via new function called optimize. The
syntax of this function is as follows:
variable = optimize( "Description", default, min, max, step );
where:
variable - is normal AFL variable that gets assigned the value returned by
optimize function.
With normal backtesting, scanning, exploration and comentary modes the optimize
function returns default value, so the above function call is equivalent to:
variable = default;
In optimization mode optimize function returns successive values from min to max
(inclusively) with step stepping.
"Description" is a string that is used to identify the optimization variable and
is displayed as a column name in the optimization result list.
default is a default value that optimize function returns in exploration,
indicator, commentary, scan and normal back test modes
min is a minimum value of the variable being optimized
max is a maximum value of the variable being optimized
How to optimize trading system
235
AmiBroker 5.80 User’s Guide
Tutorial
step is an interval used for increasing the value from min to max
Notes:
• AmiBroker supports upto 100 calls to optimize function (therefore upto 100
optimization variables), note that if you are using exhaustive optimization
then it is really good idea to limit number of optimization variables to
just few.
• Each call to optimize generate (max - min)/step optimization loops and
multiple calls to optimize multiply the number of runs needed. For example
optimizing two parameters using 10 steps will require 10*10 = 100
optimization loops.
• Call optimize function only ONCE per variable at the beginning of your
formula as each call generates a new optimization loops
• Multiple-symbol optimization is fully supported by AmiBroker
Examples
1. Single variable optimization:
sigavg = Optimize( "Signal average", 9, 2, 20, 1 );
Buy = Cross( MACD( 12, 26 ), Signal( 12, 26, sigavg ) );
Sell = Cross( Signal( 12, 26, sigavg ), MACD( 12, 26 ) );
2. Two-variable optimization (suitable for 3D charting)
per = Optimize("per", 2, 5, 50, 1 );
Level = Optimize("level", 2, 2, 150, 4 );
Buy=Cross( CCI(per), -Level );
Sell = Cross( Level, CCI(per) );
3. Multiple (3) variable optimization:
mfast = Optimize( "MACD Fast", 12, 8, 16, 1 );
mslow = Optimize("MACD Slow", 26, 17, 30, 1 );
sigavg = Optimize( "Signal average", 9, 2, 20, 1 );
Buy = Cross( MACD( mfast, mslow ) , Signal( mfast, mslow, sigavg ) );
Sell = Cross( Signal( mfast, mslow, sigavg ), MACD( mfast, mslow ) );
After entering the formula just click on Optimize button in "Automatic Analysis"
window. AmiBroker will start testing all possible combinations of optimization
variables and report the results in the list. After optimization is done the list
of result is presented sorted by the Net % profit. As you can sort the results by
any column in the result list it is easy to get the optimal values of parameters
for the lowest drawdown, lowest number of trades, largest profit factor, lowest
market exposure and highest risk adjusted annual % return. The last columns of
result list present the values of optimization variables for given test.
How to optimize trading system
236
AmiBroker 5.80 User’s Guide
Tutorial
When you decide which combination of parameters suits your needs the best all you
need to do is to replace the default values in optimize function calls with the
optimal values. At current stage you need to type them by hand in the formula
edit window (the second parameter of optimize function call).
Displaying 3D animated optimization charts
To display 3D optimization chart, you need to run two-variable optimization
first. Two variable optimization needs a formula that has 2 Optimize() function
calls. An example two-variable optimization formula looks like this:
per = Optimize("per", 2, 5, 50, 1 );
Level = Optimize("level", 2, 2, 150, 4 );
Buy=Cross( CCI(per), -Level );
Sell = Cross( Level, CCI(per) );
After entering the formula you need to click
"Optimize" button.
Once optimization is complete you should click on
the drop down arrow on Optimize button and choose
View 3D optimization graph. In a few seconds a
colorful three-dimensional surface plot will
appear in a 3D chart viewer window. An example 3D
chart generated using above formula is shown
below.
How to optimize trading system
237
AmiBroker 5.80 User’s Guide
Tutorial
By default the 3D charts display values of Net profit against optimization
variables. You can however plot 3D surface chart for any column in the
optimization result table. Just click on the column header to sort it (blue arrow
will appear indicating that optimization results are sorted by selected column)
and then choose View 3D optimization graph again.
By visualizing how your system’s parameters affect trading performance, you can
more readily decide which parameter values produce "fragile" and which produce
"robust" system performance. Robust settings are regions in the 3D graph that
show gradual rather than abrupt changes in the surface plot. 3D optimization
charts are great tool to prevent curve-fitting. Curve-fitting (or
over-optimization) occurs when the system is more complex than it needs to be,
and all that complexity was focused on market conditions that may never happen
again. Radical changes (or spikes) in the 3D optimization charts show clearly
over-optimization areas. You should choose parameter region that produces a broad
and wide plateau on 3D chart for your real life trading. Parameter sets producing
profit spikes will not work reliably in real trading.
3D chart viewer controls
AmiBroker’s 3D chart viewer offers total viewing capabilities with full graph
rotation and animation. Now you can view your system results from every
conceivable perspective. You can control the position and other parameters of the
chart using the mouse, toolbar and keyboard shortcuts, whatever you find easier
for you. Below you will find the list.
How to optimize trading system
238
AmiBroker 5.80 User’s Guide
Tutorial
Mouse controls:
- to Rotate - hold down LEFT mouse button and move in X/Y directions
- to Zoom-in, zoom-out - hold down RIGHT mouse button and move in X/Y directions
- to Move (translate) - hold down LEFT mouse button and CTRL key and move in X/Y
directions
- to Animate - hold down LEFT mouse button, drag quickly and release button while
dragging
Keyboard controls:
SPACE - animate (auto-rotate)
LEFT ARROW KEY - rotate vert. left
RIGHT ARROW KEY - rotate vert. right
UP ARROW KEY - rotate horiz. up
DOWN ARROW KEY - rotate horiz. down
NUMPAD + (PLUS) - Near (zoom in)
NUMPAD - (MINUS) - Far (zoom out)
NUMPAD 4 - move left
NUMPAD 6 - move right
NUMPAD 8 - move up
NUMPAD 2 - move down
PAGE UP - water level up
PAGE DOWN - water level down
Smart (non-exhaustive) optimization
Introduction
AmiBroker now offers smart (non-exhaustive) optimization in addition to regular,
exhaustive search. Non-exhaustive search is useful if number of all parameter
combinations of given trading system is simply too large to be feasible for
exhaustive search.
Exhaustive search is perfectly fine as long as it is reasonable to use it. Let’s
say you have 2 parameters each ranging from 1 to 100 (step 1).
That’s 10000 combinations - perfectly OK for exhaustive search. Now with 3
parameters you got 1 million combinations - it is still OK for exhaustive search
(but can be lenghty). With 4 parameters you have 100 million combinations and
with 5 parameters (1..100) you have 10 billion combinations. In that case it
would be too time consuming to check all of them, and this is the area where
non-exhaustive smart-search methods can solve the problem that is not solvable in
reasonable time using exhaustive search.
Quick Start
Here is absolutely the SIMPLEST instruction how to use new non-exhaustive
optimizer (in this case CMA-ES).
1. Open your formula in the Formula Editor
2. Add this single line at the top of your formula:
How to optimize trading system
239
AmiBroker 5.80 User’s Guide
Tutorial
OptimizerSetEngine("cmae"); // you can also use "spso" or "trib" here
3. (Optional) Select your optimization target in Automatic Analysis, Settings,
"Walk-Forward" tab, Optimization target field. If you skip this step it will
optimize for CAR/MDD (compound annual return divided by maximum % drawdown).
and... that’s it.
Now if you run optimization using this formula, it will use new evolutionary
(non-exhaustive) CMA-ES optimizer.
How does it work ?
The optimization is the process of finding minimum (or maximum) of given
function. Any trading system can be considered as a function of certain number of
arguments. The inputs are parameters and quotation data , the output is your
optimization target
(say CAR/MDD). And you are looking for maximum of given function.
Some of smart optimization algorithms are based on nature (animal behavior) - PSO
algorithm, or biological process - Genetic algorithms,
and some are based on mathematical concepts derived by humans - CMA-ES.
These algorithms are used in many different areas, including finance. Enter "PSO
finance" or "CMA-ES finance" in Google and you will find lots of info.
Non-exhaustive (or "smart") methods will find global or local optimum. The goal
is of course to find global one, but if there is a single sharp peak
out of zillions parameter combinations, non-exhaustive methods may fail to find
this single peak, but taking it form trader’s perspecive, finding single sharp
peak is useless for trading because that result would be instable (too fragile)
and not replicable in real trading. In optimization process we are rather looking
for plateau regions with stable parameters and this is the area where intelligent
methods shine.
As to algorithm used by non-exhaustive search it looks as follows:
a) the optimizer generates some (usually random) starting population of parameter
sets
b) backtest is performed by AmiBroker for each parameter set from the population
c) the results of backtests are evaluated according to the logic of algorithm
and new population is generated based on the evolution of results,
d) if new best is found - save it and go to step b) until stop criteria are met
Example stop criteria can include:
a) reaching specified maximum iterations
b) stop if the range of best objective values of last X generations is zero
c) stop if adding 0.1 standard deviation vector in any principal axis direction
does not change the value of objective value
How to optimize trading system
240
AmiBroker 5.80 User’s Guide
Tutorial
d) others
To use any smart (non-exhaustive) optimizer in AmiBroker you need to specify the
optimizer engine you want to use in the AFL formula using OptimizerSetEngine
function.
OptimizerSetEngine("name")
The function selects external optimization engine defined by name. AmiBroker
currently ships with 3 engines: Standard Particle Swarm Optimizer ("spso"),
Tribes ("trib"), and CMA-ES ("cmae") - the names in braces are to be used in
OptimizerSetEngine calls.
In addition to selecting optimizer engine you may want to set some of its
internal parameters. To do so use OptimizerSetOption function.
OptimizerSetOption("name", value ) function
The function set additional parameters for external optimization engine. The
parameters are engine-dependent.
All three optimizers shipped with AmiBroker (SPSO, Trib, CMAE) support two
parameters: "Runs" (number of runs) and "MaxEval" (maximum evaluations (tests)per
single run). The behaviour of each parameter is engine-dependent, so same values
may and usually will yield different results with different engines used.
The difference between Runs and MaxEval is as follows. Evaluation (or test) is
single backtest (or evaluation of objective function value).
RUN is one full run of the algorithm (finding optimum value) - usually involving
many tests (evaluations).
Each run simply RESTARTS the entire optimization process from the new beginning
(new initial random population).
Therefore each run may lead to finding different local max/min (if it does not
find global one). So Runs parameter defines number of subsequent algorithm runs.
MaxEval is the maximum number of evaluations (bactests) in any single run.
If the problem is relatively simple and 1000 tests are enough to find global max,
5x1000 is more likely to find global maximum
because there are less chances to be stuck in local max, as subsequent runs will
start from different initial random population
Choosing parameter values can be tricky. It depends on problem under test, its
complexity, etc, etc.
Any stochastic non-exhaustive method does not give you guarantee of finding
global max/min, regardless of number of tests if it is smaller
than exhaustive. The easiest answer is to : specify as large number of tests as
it is reasonable for you in terms of time required to complete.
Another simple advice is to multiply by 10 the number of tests with adding new
dimension. That may lead to overestimating number
of tests required, but it is quite safe. Shipped engines are designed to be
simple to use, therefore "reasonable" default/automatic values are used so
optimization can be usually run without specifying anything (accepting defaults).
How to optimize trading system
241
AmiBroker 5.80 User’s Guide
Tutorial
Caveat
It is important to understand that all smart optimization methods work best in
continuous parameter spaces and relatively smooth objective functions. If
parameter space is discrete evolutionary algorithms may have trouble finding
optimum value. It is especially true for binary (on/off) parameters - they are
not suited for any search method that uses gradient of objective function change
(as most smart methods do). If your trading system contains many binary
parameters, you should not use smart optimizer directly on them. Instead try to
optimize only continuous parameters using smart optimizer, and switch binary
parameters manually or via external script.
SPSO - Standard Particle Swarm Optimizer
Standard Particle Swarm Optimizer is based on SPSO2007 code that is supposed to
produce good results provided that correct parameters (i.e. Runs, MaxEval) are
provided for particular problem.
Picking correct options for the PSO optimizer can be tricky therefore results may
significantly vary from case to case.
SPSO.dll comes with full source codes inside "ADK" subfolder.
Example code for Standard Particle Swarm Optimizer:
(finding optimum value in 1000 tests within search space of 10000 combinations)
OptimizerSetEngine("spso");
OptimizerSetOption("Runs", 1 );
OptimizerSetOption("MaxEval", 1000 );
sl = Optimize("s", 26, 1, 100, 1 );
fa = Optimize("f", 12, 1, 100, 1 );
Buy = Cross( MACD( fa, sl ), 0 );
Sell = Cross( 0, MACD( fa, sl ) );
TRIBES - Adaptive Parameter-less Particle Swarm Optimizer
Tribes is adaptive, parameter-less version of PSO (particle swarm optimization)
non-exhaustive optimizer. For scientific background see:
http://www.particleswarm.info/Tribes_2006_Cooren.pdf
In theory it should perform better than regular PSO, because it can automatically
adjust the swarm sizes and algorithm strategy to the problem being solved.
Practice shows that its performance is quite similar to PSO.
The Tribes.DLL plugin implements "Tribes-D" (i.e. dimensionless) variant. Based
on http://clerc.maurice.free.fr/pso/Tribes/TRIBES-D.zip by Maurice Clerc.
How to optimize trading system
242
AmiBroker 5.80 User’s Guide
Tutorial
Original source codes used with permission from the author
Tribes.DLL comes with full source code (inside "ADK" folder)
Supported parameters:
"MaxEval" - maximum number of evaluations (backtests) per run (default = 1000).
OptimizerSetOption("MaxEval", 1000 );
You should increase the number of evaluations with increasing number of
dimensions (number of optimization params).
The default 1000 is good for 2 or maximum 3 dimensions.
"Runs" - number of runs (restarts). (default = 5 )
You can leave the number of runs at default value of 5.
By default number of runs (or restarts) is set to 5.
To use Tribes optimizer, you just need to add one line to your code:
OptimizerSetEngine("trib");
OptimizerSetOption("MaxEval", 5000 ); // 5000 evaluations max
CMA-ES - Covariance Matrix Adaptation Evolutionary Strategy optimizer
CMA-ES (Covariance Matrix Adaptation Evolutionary Strategy) is advanced
non-exhaustive optimizer.
For scientific background see:
http://www.bionik.tu-berlin.de/user/niko/cmaesintro.html
According to scientific benchmarks outperforms nine other, most popular
evolutionary strategies (like PSO, Genetic and Differential evolution).
http://www.bionik.tu-berlin.de/user/niko/cec2005.html
The CMAE.DLL plugin implements "Global" variant of search with several restarts
with increasing population size
CMAE.DLL comes with full source code (inside "ADK" folder)
By default number of runs (or restarts) is set to 5.
It is advised to leave the default number of restarts.
You may vary it using OptimizerSetOption("Runs", N ) call, where N should be in
range 1..10.
Specifying more than 10 runs is not recommended, although possible.
Note that each run uses TWICE the size of population of previous run so it grows
exponentially.
Therefore with 10 runs you end up with population 2^10 greater (1024 times) than
the first run.
How to optimize trading system
243
AmiBroker 5.80 User’s Guide
Tutorial
There is another parameter "MaxEval". The default value is ZERO which means that
plugin will automatically calculate MaxEval required. It is advised to NOT to
define MaxEval by yourself as default works fine.
The algorithm is smart enough to minimize the number of evaluations required and
it converges very fast to solution point, so often it finds solutions faster than
other strategies.
It is normal that the plugin will skip some evaluations steps, if it detects that
solution was found, therefore you should not be surprised that optimization
progress bar may move very fast at some points. The plugin also has ability to
increase number of steps over initially estimated value if it is needed to find
the solution. Due to its adaptive nature, the "estimated time left" and/or
"number of steps" displayed by the progress dialog is only "best guess at the
time" and may vary during optimization course.
To use CMA-ES optimizer, you just need to add one line to your code:
OptimizerSetEngine("cmae");
This will run the optimization with default settings which are fine for most
cases.
It should be noted, as it is the case with many continouos-space search
algorithms, that decreasing "step" parameter in Optimize() funciton calls does
not significantly affect optimization times. The only thing that matters is the
problem "dimension", i.e. the number of different parameters (number of optimize
function calls). The number of "steps" per parameter can be set without affecting
the optimization time, so use the finest resolution you want. In theory the
algorithm should be able to find solution in at most 900*(N+3)*(N+3) backtests
where "N" is the dimension. In practice it converges a LOT faster. For example
the solution in 3 (N=3) dimensional parameter space (say 100*100*100 = 1 million
exhaustive steps) can be found in as few as 500-900 CMA-ES steps.
Multi-threaded individual optimization
Starting from AmiBroker 5.70 in addition to multiple-symbol multithreading, you
can perform multi-threaded single-symbol optimization. To access this
functionality, click on drop down arrow next to "Optimize" button in the New
Analysis window and select "Individual Optimize".
How to optimize trading system
244
AmiBroker 5.80 User’s Guide
Tutorial
"Individual Optimize" will use all available processor cores to perform
single-symbol optimization, making it much faster than regular optimization.
In "Current symbol" mode it will perform optimization on one symbol. In "All
symbols" and "Filter" modes it will process all symbols sequentially, i.e. first
complete optimization for first symbol, then optimization on second symbol, etc.
Limitations:
1. Custom backtester is NOT supported (yet)
2. Smart optimization engines are NOT supported - only EXHAUSTIVE optimization
works.
For explanation of these limitations see Tutorial: Efficient use of
multi-threading.
Eventually we may get rid of limitation (1) - when AmiBroker is changed so custom
backtester does not use OLE anymore. But (2) is probably here to stay for long.
How to optimize trading system
245
AmiBroker 5.80 User’s Guide
Tutorial
Walk-forward testing
AmiBroker 5.10 features the automatic Walk-Forward test mode.
The automatic Walk forward test is a system design and validation technique in
which you optimize the parameter values on a past segment of market data
(in-sample), then verify the performance of the system by testing it forward in
time on data following the optimization segment (out-of-sample). You evaluate
the system based on how well it performs on the test data (out-of-sample), not
the data it was optimized on. The process can be repeated over subsequent time
segments. The following illustration shows how the process works.
The purpose of walk-forward test is to determine whenever the performance of
optimized trading system is the realistic or the result of curve-fitting. The
performance of the system can be considered realistic if it has predicitive value
and performs good on unseen (out-of-sample) market data. When the system is
properly designed, the real-time trading performance should be in relation to
that uncovered during optimization. If the system is going to work in real
trading, it must first pass a walk-forward test. In other words, we don’t really
care about in-sample results as they are (or should be) always good. What matters
is out-of-sample system performance. It is the realistic estimate of how the
system would work in real trading and will quickly reveal any curve-fitting
issues. If out-of-sample performance is poor then you should not trade such a
system.
The premise of performing several optimization/tests steps over time is that the
recent past is a better foundation for selecting system parameter values than the
distant past. We hope is that the parameter values chosen on the optimization
Walk-forward testing
246
AmiBroker 5.80 User’s Guide
Tutorial
segment will be well suited to the market conditions that immediately follow.
This may or may not be the case as markets goes through bear/bull cycle, so care
should be taken when choosing the length of in-sample period. For more
information about system design and verification using walk-forward procedure and
all issues involved, we can recommend Howard Bandy’s book: "Quantitative Trading
Systems" (see links on AmiBroker page).
To use Walk-Forward optimization please follow these steps:
1. Goto Tools->Automatic Analysis
2. Click Settings button, then switch to Walk-Forward tab
3. Here you can see Walk forward settings for In-sample optimization,
out-of-sample backtest
Start and End dates mark initial period begin / end
This period will be moved forward by Step until the End reaches the Last
date.
The Start date can move forward by step too, or can be anchored (constant)
if Anchored check is on.
If you mark Use today then Last date entered will be ignored and TODAY
(current date) will be used instead.
By default an EASY MODE is selected which simplifies the process of
setting up WF parameters.
It assumes that:
Walk-forward testing
247
AmiBroker 5.80 User’s Guide
Tutorial
a) Out-of-sample segment immediatelly follows in-sample segment
b) the length of out-of-sample segment equals to the walk-forward step
Based on these two assumptions the EASY mode takes in-sample END date and
sets out-of-sample START date to the following day. Then adds in-sample
STEP and this becomes out-of-sample END date.
In-sample and Out-of-sample step values are set to the same values. The
EASY mode guarantees correctness of WF procedure settings.
You should use Easy mode (EOD) when testing on end-of-day data or Easy mode
(Intraday) when testing on intraday data. The difference is that in EOD
mode the END date of previous period and START date of next period are the
same - thus avoiding gap
between periods. Intraday mode set START date of the next period as NEXT
DAY after END of previous period. That guarantees
that boundary day is not counted twice when testing on intraday data.
In the Advanced mode, the user has complete control over all values, to the
extent that they may not constitute valid WF procedure.
The interface allows to selectivelly disable in-sample and out-of-sample
phases using checkboxes at top (for special things like running sequential
backtests without optimization).
All settings are immediatelly reflected in the PREVIEW list that shows all
generated IS/OOS segments and their dates.
4. The Optimization target field defines the optimization raport COLUMN NAME
that
will be used for sorting results and finding the BEST one. Any built-in
column can be used
(as appears in the optimization output), or you can use any custom metric
that you define
in custom backtester. The default is CAR/MDD, you can however select any
other built-in metric from the combo.
You can also TYPE-IN any custom metric that you have added via custom
backtester interface.
5. Once you defined Walk-Forward settings, please go to Automatic Analysis and
6. press the dropdown ARROW on the Optimize button and select Walk Forward
Optimization
This will run sequence of optimizaitons and backtest and the results will
be displayed in the Walk Forward document that is open in the main
application frame. When optimization is running you can click MINIMIZE
button on the Progress dialog to minimize it - this allows to see the Walk
Forward output during the optimization steps.
IN-SAMPLE and OUT-OF-SAMPLE combined equity
Combined in-sample and out-sample equities are available by ~~~ISEQUITY and
~~~OSEQUITY composite tickers (consecutive periods of IS and OOS are concatenated
and scaled to maintain continuity of equity line - this approach assumes that you
generally speaking are compounding profits).
Walk-forward testing
248
AmiBroker 5.80 User’s Guide
Tutorial
To display IS and OOS equity you may use for example this:
PlotForeign("~~~ISEQUITY","In-Sample Equity", colorRed, styleLine);
PlotForeign("~~~OSEQUITY","Out-Of-Sample Equity", colorGreen, styleLine);
Title = "{{NAME}} - {{INTERVAL}} {{DATE}} {{VALUES}}";
OUT-OF-SAMPLE summary report (new in 5.60)
Version 5.60 brings a new walk-forward summary report that covers all
out-of-sample steps. It is visible in the Report Explorer as last one and has
"PS" type.
There were significant changes to walk forward testing made to allow summary
out-of-sample report. The most important change is that each subsequent
out-of-sample test uses initial equity equal to previous step ending equity.
(Previously it used constant initial equity). This change is required for proper
calculation of all statistics/metrics throughout all sections of out-of-sample
test.
Summary report shows the note that built-in metrics correctly represent all
out-of-sample steps but summary custom metrics are composed using user-definable
method:
1 first step value, 2 last step value, 3 sum, 4 average, 5 minimum, 6 maximum.
By default summary report shows last step value of custom metrics UNLESS user
specifies different combining method in
bo.AddCustomMetrics() call.
bo.AddCustomMetrics has now new optional parameter - CombineMethod
bool AddCustomMetric( string Title, variant Value, [optional] variant
LongOnlyValue, [optional] variant ShortOnlyValue , [optional] variant DecPlaces =
2, [optional] variant CombineMethod = 2 )
This method adds custom metric to the backtest report, backtest "summary" and
optimization result list. Title is a name of the metric to be displayed in the
report, Value is the value of the metric, optional arguments LongOnlyValue,
ShortOnlyValue allow to provide values for additional long/short-only columns in
the backtest report. Last argument DecPlaces controls how many decimal places
should be used to display the value.
Supported CombineMethod values are:
1 first step value, - summary report will show the value of custom metric from
very first out-of-sample step
2 last step value (default), - summary report will show the value of custom
metric from the last out-of-sample step
3 sum, - summary report will show the sum of the values of custom metric from all
out of sample steps
4 average, - summary report will show the average of the values of custom metric
from all out of sample steps
5 minimum, - summary report will show the smallest value of custom metric from
all out of sample steps
6 maximum.- summary report will show the largest value of custom metric from all
Walk-forward testing
249
AmiBroker 5.80 User’s Guide
Tutorial
out of sample steps
Note that certain metrics calculation methods are complex and for example
averaging them would not lead to mathematically correct representation of all out
of sample test. Summaries of all built-in metrics are mathematically correct
out-of-the-box (i.e. they are *not* averages, but properly calculated metrics
using method that is appropriate for given value). This contrasts with custom
metrics, because they are user-definable and it is up to the user to select
’combining’ method, and still it may happen that none of the available methods is
appropriate.
For that reason the report includes the note that explains what user-definable
method was used to combine custom metrics.
Walk-forward testing
250
AmiBroker 5.80 User’s Guide
Tutorial
Back-testing systems for futures contracts
Introduction
Before you read this article you should read first "Backtesting your trading
ideas" section as it gives necessary background of backtesting in general.
When you open long position on stocks you just buy given number of shares at
given price, then after some time you sell them and your profit is given by
difference between sell and buy price mutliplied by number of shares. If you want
to open long position on future contract you pay a deposit - margin - for each
contract. The margin is just a little part of full contract value (for example
10%). So you can buy 10 contracts paying no more than full value of one contract.
This gives you a leverage that makes trading futures more risky than trading
stocks. When price of the contract changes your profit/loss changes accordingly.
If contract’s point value is 1 each 1$ change in contract price represents 1$
profit/loss per contract - like in stocks. But futures can have point value
different that 1. If, for example, point value is 5 each 1 point change in price
of the contract represents 5$ profit/loss in your equity. When you close position
you get the margin deposit back, so your profit/loss is given by number of
contracts multiplied by point value mutlipled by difference between sell and buy
prices.
Futures mode of the backtester
There are 3 futures-only settings in the backtester:
• Futures mode check box (Settings-General page)
• Margin deposit (Symbol-Information page)
• Point value (Symbol-Information page)
Back-testing systems for futures contracts
251
AmiBroker 5.80 User’s Guide
Tutorial
Futures mode check box in the settings page (underscored with green line in the
picture above) is the key to backtesting futures. It instructs backtester to use
margin deposit and point value in calculations.
The remaining settings are per-symbol and they are accessible from
Symbol->Information window.
Margin deposit
Back-testing systems for futures contracts
252
AmiBroker 5.80 User’s Guide
Tutorial
The margin is the amount of money required to open single contract position. You
can specify per-symbol margin in the Symbol-Information page (picture above).
Positive values describe margin value in dollars, while negative express margin
value as percentage of contract price. Margin value of zero is used for stocks
(no margin). Margin can be also specified in the formula by using MarginDeposit
reserved variable:
MarginDeposit = 675;
In the Futures mode margin setting is used to determine how many contacts can be
purchased. Let’s suppose that your initial equity is set to $50000 and you want
to invest upto 20% of equity in single trade and the margin deposit is $675. In
that case your "desired" position size is 50’000 * 0.2 = 10’000. Provided that
you have set round lot size to 1, the backtester will "buy" 10000/675 =
(integer)14.8148 = 14 contracts, and true positon value will be $9450 (18.9% of
the initial equity).
To simulate this in AmiBroker you would need to enter 50000 in the Initial Equity
field in the backtester, switch on futures mode, and setup remaining parameters
in your formula:
PositionSize = -20; // use 20% of equity
MarginDeposit = 675; // this you can set also in the
Symbol-Information page
RoundLotSize = 1; // this you can set also in the Settings page
All further trades will use the same logic but position will be sized according
to current cumulated equity instead of initial equity level, unless you specify
fixed position size in your formula ( PositionSize = 10000 for example).
Point value
Point-value is per-symbol setting (definable in Symbol-Information window (picture above)) that determines the amount of profit generated by one contract
for a one point increase in price. Example: copper is quoted in cents per pound,
a price quote of 84.65 (or 8465) equals 84 cents and 65/100 of a cent per pound.
A change of +.37 or 37 represents 37/100ths of a cent you will normally hear it
quoted as 37 points. But because of the fact that point value for copper is 2.5
every point change gives $2.5 profit/loss, so in this example profit/loss for the
day would be 2.5 * 37 = $92.50.
You can also set it from the formula level using PointValue reserved variable,
for example:
PointValue = 2.5;
Note: When you load old database AmiBroker presets point value field to 1 and
assumes that by default 1 point represents one dollar so one dollar change gives
one dollar profit/loss. This is done to ensure that you get correct results even
if you (by mistake) run futures mode test on stocks.
Back-testing systems for futures contracts
253
AmiBroker 5.80 User’s Guide
Tutorial
Note 2: Although point value setting affects (multiplies) profits/losses it does
NOT affect built-in stops. The stops ALWAYS operate on price movement alone. So
you should be aware that setting 10% profit target stop will result in 25% profit
on trade exited by this stop when point value is set to 2.5.
Simple cases
Points-only test
Points only test is equivalent to trading just one contract. This can be easily
accomplished using Futures mode of the backtester and adding the following one
line to your formula:
PositionSize = MarginDeposit = 1;
Trading ’n’ contracts
In a similar way you can setup your formula so it always trades say 7 contracts.
All you need to do is to add the following to your formula:
NumContracts = 7;
PositionSize = NumContracts * MarginDeposit;
Back-testing systems for futures contracts
254
AmiBroker 5.80 User’s Guide
Tutorial
Pyramiding (scaling in/out) and mutliple currencies in
the portfolio backtester
IMPORTANT: Please read first Tutorial: Backtesting your trading ideas article and
Portfolio Backtesting
Starting from version 4.70 portfolio backtester allows position scaling and
supports multiple currencies. Note that these advanced features are supported by
PORTFOLIO backtester only. Old single-security backtester and single-security
equity() function do NOT support these features.
Pyramiding / Scaling
Two special constants: sigScaleIn / sigScaleOut added to provide means to tell
the backtester when you want to scale-in/out
All you have to do to implement pyraminding is to:
- Assign sigScaleIn to BUY/SHORT variable if you want to scale-in (increase size
of) LONG/SHORT position
- Assign sigScaleOut to BUY/SHORT variable if you want to scale-out (decrease
size of) LONG/SHORT position
Scaling size is defined by PositionSize variable which in case of scaling defines
not absolute positionsize but dollar increase or decrease.
IMPORTANT: Please note that backtester treats trade that you scale-in/out as
SINGLE trade (i.e. will show single row in trade list). The only difference
versus plain trade is that it will calculate average entry price (and avg. entry
fx rate) based on all partial entries and average exit price (and avg. exit fx
rate) based on all parial exits and will show average prices in entry/exit price
field. The commission is of course applied correctly to each (partial) entry/exit
depending on partial buy/sell size.
If you want to see details about scaling you have to run backtest in "DETAIL LOG"
mode as only then you will see how scaling-in /out works and how average prices
are calculated.
Note also that scaling-in/-out and multiple-currency support is available only in
portfolio backtester. Old backtester as well as Equity() function do NOT handle
scaling-in/out nor multiple currencies (they simply ignore scaling commands).
Easy examples:
Example 1: dollar-cost averaging (each month you buy stocks for fixed dollar
amount)
FixedDollarAmount = 500;
MonthBegin = Month() != Ref( Month(), -1 );
FirstPurchase = Cum( MonthBegin ) == 1;
Pyramiding (scaling in/out) and mutliple currencies in the portfolio backtester
255
AmiBroker 5.80 User’s Guide
Tutorial
Buy = IIf( FirstPurchase, 1, // True (or 1) represents regular buy signal
IIf( MonthBegin, sigScaleIn, // each month increase position
0 ) ); // otherwise no signal
Sell = 0; // we do not sell
PositionSize = FixedDollarAmount;
Example 2: dollar-cost averaging
(simplified formula because AB treats first sigScaleIn as buy anyway)
FixedDollarAmount = 500;
MonthBegin = Month() != Ref( Month(), -1 );
FirstPurchase = Cum( MonthBegin ) == 1;
Buy = IIf( MonthBegin, sigScaleIn, 0 ); // each month increase position
Sell = 0; // we do not sell
PositionSize = FixedDollarAmount;
Example 3: increasing position when profit generated by trade without pyramiding
becomes greater than 5% and decreasing position when loss is greater than -5%
// percent equity change threshold when pyramiding is performed
PyramidThreshold = 5;
// regular trading rules (no pyramiding)
Buy = Cross( MACD(), Signal() );
Sell = Cross( Signal(), MACD() );
e = Equity(1); // generate equity without pyramiding effect
PcntProfit = 100 * ( e - ValueWhen( Buy, e ) )/ValueWhen( Buy, e );
InTrade = Flip( Buy, Sell );
// ExRem is used here to ensure that scaling-in/out occurs
// only once since trade entry
DoScaleIn = ExRem( InTrade AND PcntProfit > PyramidThreshold, Sell );
DoScaleOut = ExRem( InTrade AND PcntProfit < -PyramidThreshold, Sell );
// modify rules to handle pyramiding
Buy = Buy + sigScaleIn * DoScaleIn + sigScaleOut * DoScaleOut;
PositionSize = IIf( DoScaleOut, 500, 1000 ); // enter and scale-in size $1000,
scale-out size: $500
Pyramiding (scaling in/out) and mutliple currencies in the portfolio backtester
256
AmiBroker 5.80 User’s Guide
Tutorial
Example 4: partial exit (scaling out) on profit target stops
Example of code that exits 50% on first profit target, 50% on next profit target
and everything at trailing stop:
Buy = Cross( MA( C, 10 ), MA( C, 50 ) );
Sell = 0;
//
//
//
//
the system will exit
50% of position if FIRST PROFIT TARGET stop is hit
50% of position is SECOND PROFIT TARGET stop is hit
100% of position if TRAILING STOP is hit
FirstProfitTarget = 10; // profit
SecondProfitTarget = 20; // in percent
TrailingStop = 10; // also in percent
priceatbuy=0;
highsincebuy = 0;
exit = 0;
for( i = 0; i < BarCount; i++ )
{
if( priceatbuy == 0 AND Buy[ i ] )
{
priceatbuy = BuyPrice[ i ];
}
if( priceatbuy > 0 )
{
highsincebuy = Max( High[ i ], highsincebuy );
if( exit == 0 AND
High[ i ] >= ( 1 + FirstProfitTarget * 0.01 ) * priceatbuy )
{
// first profit target hit - scale-out
exit = 1;
Buy[ i ] = sigScaleOut;
}
if( exit == 1 AND
High[ i ] >= ( 1 + SecondProfitTarget * 0.01 ) * priceatbuy )
{
// second profit target hit - exit
exit = 2;
SellPrice[ i ] = Max( Open[ i ], ( 1 + SecondProfitTarget * 0.01 ) *
priceatbuy );
}
Pyramiding (scaling in/out) and mutliple currencies in the portfolio backtester
257
AmiBroker 5.80 User’s Guide
Tutorial
if( Low[ i ] <= ( 1 - TrailingStop * 0.01 ) * highsincebuy )
{
// trailing stop hit - exit
exit = 3;
SellPrice[ i ] = Min( Open[ i ], ( 1 - TrailingStop * 0.01 ) *
highsincebuy );
}
if( exit >= 2 )
{
Buy[ i ] = 0;
Sell[ i ] = exit + 1; // mark appropriate exit code
exit = 0;
priceatbuy = 0; // reset price
highsincebuy = 0;
}
}
}
SetPositionSize( 50, spsPercentOfEquity );
SetPositionSize( 50, spsPercentOfPosition * ( Buy == sigScaleOut ) ); // scale
out 50% of position
Mulitple Currency Support
The portfolio backtester allows to backtest systems on securites denominated in
different currencies. It includes ability to use historical (variable) currency
rates. Currency rates are definable in "Currencies" page in the preferences. The
currency in which given symbol is denominated in can be entered in
Symbol->Information page.
"Currencies" page in Preferences - allows to define base currency and exchange
rates (fixed or dynamic)
for different currencies. This allows to get correct backtest results when
testing securities denominated in different currency than your base portfolio
currency.
How does AB know whether I want the fixed or dynamic quote?
There are following requirements to use currency adjustements:
a) Symbol->Information, "Currency" field shows currency different than BASE
currency
b) Appropriate currency (defined in Symbol) has matching entry in
Preferences->Currencies page
c) the dynamic rate "FX SYMBOL" defined in the preferences EXISTS in your
database and HAS QUOTES for each day under analysis range.
What is "INVERSE" check box for in the preferences?
Let’s for example take EURUSD.
Pyramiding (scaling in/out) and mutliple currencies inthe portfolio backtester
258
AmiBroker 5.80 User’s Guide
Tutorial
When "USD" is your BASE currency then EUR exchange rate would be "straight"
EURUSD fx (i.e. 1.3).
But when "EUR" is your BASE currency then USD exchange rate would be INVERSE of
EURUSD (i.e. 1/1.3).
Opposite would be true with FX rates like USDJPY (which are already "inverse").
Pyramiding (scaling in/out) and mutliple currencies inthe portfolio backtester
259
AmiBroker 5.80 User’s Guide
Tutorial
Using formula-based alerts
Introduction
AmiBroker allows you to define formula-based alerts. When alert is triggered a
text can be displayed, user-defined sound played back, e-mail notification can be
sent and any external application can be launched. This is all handled by single
AlertIF function.
By default all alerts generate text that is displayed in the Alert Output window.
To show this window you have to select Window->Alert Output menu.
There is also Easy Alerts window that allows you to define simple alerts that do
not require any coding (but do not offer full flexibility of AlertIf function).
Settings
Alert - related settings are present in the "Alerts" tab of Tools->Preferences
window.
It allows to define e-mail account settings, test sound output and define which
parts of AmiBroker can generate alerts via AlertIF function.
E-mail setting page now allows to choose among most popular authorization schemes
like: AUTH LOGIN (most popular), POP3-before-SMPT (popular), CRAM-MD5, LOGIN
PLAIN.
"Enable alerts from" checkboxes allow you to selectively enable/disable alerts
generated by Automatic analysis, Commentary/Interpretation and custom indicators.
Alert output window now has an additional column that shows the source of alert if this is Automatic Analysis, Commentary or one of your custom indicators. This
makes it easier to find out which part of AmiBroker generates alerts.
New in AmiBroker 5.30 - support for SSL (secure connection) used by GMail for
example.
In order to enable SSL support you need to follow these steps:
1. Download and run SSL add-on from http://www.amibroker.com/bin/SSLAddOn.exe
2. Configure (Tools->Preferences->Alerts) with SSL enabled as shown below
Using formula-based alerts
260
AmiBroker 5.80 User’s Guide
Tutorial
AlertIF function
AlertIF function is similar to WriteIF. But instead of just writing the text to
the output window (commentary/interpretation) it allows to:
•
•
•
•
direct the customized text to "alert output" window,
make a sound (just by computer beeper or from .WAV file)
send an e-mail
launch any external application
The syntax is as follows:
AlertIf( BOOLEAN_EXPRESSION, command, text, type = 0, flags = 1+2+4+8, lookback =
1 );
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. If it is
empty the alert text is simply displayed in the Alert output window
(Window->Alert Output). Other supported values of command string are:
SOUND the-path-to-the-WAV-file
EMAIL
Using formula-based alerts
261
AmiBroker 5.80 User’s Guide
Tutorial
EXEC the-path-to-the-file-or-URL <optional args>
SOUND command plays the WAV file once.
EMAIL command sends the e-mail to the account defined in the settings
(Tools->Preferences->E-mail). The format of the e-mail is as follows:
Subject: Alert type_name (type) Ticker on Date/Time
Body: text
EXEC command launches external application or file or URL specified after EXEC
command. <optional args> are attached after file name and text is attached at the
end
3. Text defines the text that will be printed in the output window or sent via
e-mail or added as argument to the application specified by EXEC command
4. Type defines type of the alert. Pre-defined types are 0 - default, 1 - buy, 2
- sell, 3 - short, 4- cover. YOu may specify higher values and they will get name
"other"
5. Flags control behaviour of AlertIF function. This field is a combination (sum)
of the following values:
( 1 - display text in the output window, 2 - make a beep (via computer speaker),
4 - don’t display repeated alerts having the same type, 8 - don’t display
repeated alerts having the same date/time) By default all these options are
turned ON.
6. lookback parameter controls how many recent bars are checked
Examples:
Buy = Cross( MACD(), Signal() );
Sell = Cross( Signal(), MACD() );
Short = Sell;
Cover = Buy;
AlertIF( Buy, "EMAIL", "A sample alert on "+FullName(), 1 );
AlertIF( Sell, "SOUND C:\\Windows\\Media\\Ding.wav", "Audio alert", 2 );
AlertIF( Short, "EXEC Calc.exe", "Launching external application", 3 );
AlertIF( Cover, "", "Simple text alert", 4 );
Note EXEC command uses ShellExecute function and allows not only EXE files but
URLs too.
Notes
1. Please note that by default AlertIf function does not generate repetitive
signals when the same scan is run multiple times. During experimentation you may
Using formula-based alerts
262
AmiBroker 5.80 User’s Guide
Tutorial
prefer to get repeated signals in subsequent scans. To do so you should change
default flags to 1 + 2:
AlertIF( condition, "", "Text", 1, 1+2 );
2. If you want to generate the alert only on COMPLETED bar you may need to add
this code:
barcomplete = BarIndex() < LastValue(BarIndex());
AlertIF( barcomplete AND condition, "", "Text", 1 );
Using formula-based alerts
263
AmiBroker 5.80 User’s Guide
Tutorial
Using interpretation window
Note: Please read How to write your own chart commentary article before
proceeding.
Interpretation window (Window->Interpretation) shows chart-sensitive
commentaries. To add a interpretation just use Formula Editor and add commentary
code after the code for the indicator. Please note that to get the best
performance you should use conditional statement that ensures that interpretation
code is executed only in "commentary" mode.
if( Status("action") == actionCommentary )
{
// printf statements here....
}
Example:
Plot( Close, "Price", -1, 64 );
Plot( SAR( Prefs( 50 ), Prefs( 51 ) ), "SAR",-17, 8+16 );
if( Status("action") == actionCommentary )
{
printf("The Parabolic SAR provides excellent exit points. \n");
printf("You should Close long positions when the price falls below\n");
printf("the SAR AND Close Short positions when the price rises above the
SAR.\n");
printf( WriteIf( Graph1 > Close, "SAR is above close", "SAR is below close" ) );
}
Using interpretation window
264
AmiBroker 5.80 User’s Guide
Tutorial
Multiple Time Frame support in AFL
Release 4.41 brings ability to use multiple time frames (bar intervals) in single
formula. The time frame functions can be divided into 3 functional groups:
1. switching time frame of build-in O, H, L, C, V, OI, Avg arrays:
TimeFrameSet, TimeFrameRestore
2. compressing/expanding single arrays to/from specified interval:
TimeFrameCompress, TimeFrameExpand
3. immediate access to price/volume arrays in different time frame:
TimeFrameGetPrice
First group is used when your formula needs to perform some calculations on
indicators in different time frame than currently selected one. For example if
you need to calculate 13-bar moving average on 5 minute data and 9 bar
exponential avarage from hourly data while current interval is 1 minute you would
write:
TimeFrameSet( in5Minute ); // switch to 5 minute frame
/* MA now operates on 5 minute data, ma5_13 holds time-compressed 13 bar MA of
5min bars */
ma5_13 = MA( C, 13 );
TimeFrameRestore(); // restore time frame to original
TimeFrameSet( inHourly ); // switch now to hourly
mah_9 = EMA( C, 9 ); // 9 bar moving average from hourly data
TimeFrameRestore(); // restore time frame to original
Plot( Close, "Price", colorWhite, styleCandle );
// plot expanded average
Plot( TimeFrameExpand( ma5_13, in5Minute), "13 bar moving average from 5 min
bars", colorRed );
Plot( TimeFrameExpand( mah_9, inHourly), "9 bar moving average from hourly bars",
colorRed );
TimeFrameSet( interval ) - replaces current built-in 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() funciton. If you want to call TimeFrameSet again
with different interval you have to restore original time frame first using
TimeFrameRestore(). Interval is time frame interval in seconds. For example: 60
is one minute bar. You should use convenient constants for common intervals:
in1Minute, in5Minute, in15Minute, inHourly, inDaily, inWeekly, inMonthly.
Multiple Time Frame support in AFL
265
AmiBroker 5.80 User’s Guide
Tutorial
With version 4.70 you can also specify N-tick intervals. This is done by passing
NEGATIVE value as interval. For example -5 will give 5-tick bar compression, and
-133 will give 133-tick compression. Please note that using N-tick intervals
works only if your database uses Tick base time interval set in File -> Database
Settings dialog.
TimeFrameSet( -133 ); // switch to 133-tick interval
TimeFrameRestore() - restores price arrays replaced by SetTimeFrame.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.
Once you switch the time frame using TimeFrameSet, all AFL functions operate on
this time frame until you switch back the time frame to original interval using
TimeFrameRestore or set to different interval again using TimeFrameSet. It is
good idea to ALWAYS call TimeFrameRestore when you are done with processing in
other time frames.
When time frame is switched to other than original interval the results of all
functions called since TimeFrameSet are time-compressed too. If you want to
display them in original time frame you would need to ’expand’ them as described
later. Variables created and assigned before call to TimeFrameSet() remain in the
time frame they were created. This behaviour allows mixing unlimited different
time frames in single formula.
Please note that you can only compress data from shorter interval to longer
interval. So when working with 1-minute data you can compress to 2, 3, 4, 5, 6,
....N-minute data. But when working with 15 minute data you can not get 1-minute
data bars. In a similar way if you have only EOD data you can not access intraday
time frames.
Second group: TimeFrameCompress/TimeFrameExpand allow to compress and expand
single arrays to / from different time frames. Especially worth mentioning is
TimeFrameExpand that 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. For example if you want to display weekly moving
average it must be ’expanded’ so the data of one weekly bar covers five daily
bars (Monday-Friday) of corresponding week.
TimeFrameExpand( array, interval, mode = expandLast ) - expands time-compressed
array from ’interval’ time frame to base time frame (’interval’ must match the
value used in TimeFrameCompress or TimeFrameSet)
Available modes:
expandLast - the compressed value is expanded starting from last bar within given
period (so for example weekly close/high/low is available on Friday’s bar)
expandFirst - the compressed value is expanded starting from first bar within
given period (so for example weekly open is available from Monday’s bar)
expandPoint - the resulting array gets not empty values only for the last bar
within given period (all remaining bars are Null (empty)).
Multiple Time Frame support in AFL
266
AmiBroker 5.80 User’s Guide
Tutorial
Caveat: expandFirst used on price different than open may look into the future.
For example if you create weekly HIGH series, expanding it to daily interval
using expandFirst will enable you to know on MONDAY what was the high for entire
week.
TimeFrameCompress is provided for completeness and it can be used when you want
to compress single array without affecting built-in OHLC,V arrays. If you call
TimeFrameCompress it does not affect results of other functions.
wc = TimeFrameCompress( Close, inWeekly );
/* now the time frame is still unchanged (say daily) and our MA will operate on
daily data */
dailyma = MA( C, 14 );
/* but if we call MA on compressed array, it will give MA from other time frame
*/
weeklyma = MA( wc, 14 ); // note that argument is time-compressed array
Plot( dailyma, "DailyMA", colorRed );
weeklyma = TimeFrameExpand( weeklyma, inWeekly ); // expand for display
Plot( weeklyma, "WeeklyMA", colorBlue );
During this formula the time frame remained at original setting we only
compressed single array.
TimeFrameCompress( array, interval, mode = compressLast )
- compresses single array to given interval using given compression mode
available modes:
compressLast - last (close) value of the array within interval
compressOpen - open value of the array within interval
compressHigh - highest value of the array within interval
compressLow - lowest value of the array within interval
compressVolume - sum of values of the array within interval
Graph0 = TimeFrameExpand( TimeFrameCompress( Close, inWeekly, compressLast ),
inWeekly, expandLast );
Graph1 = TimeFrameExpand( TimeFrameCompress( Open, inWeekly, compressOpen ),
inWeekly, expandFirst );
Third group consist of just one useful function: TimeFrameGetPrice which allows
to reference price and volume from other time frames without switching
/compressing/expanding time frames. Just one function call to retrieve price from
higher time frame. It allows also to reference not only current but past bars
from different time frames.
TimeFrameGetPrice( pricefield, interval, shift = 0, mode = expandFirst );
- references OHLCV fields from other time frames. This works immediatelly without
need to call TimeFrameSet at all.
Multiple Time Frame support in AFL
267
AmiBroker 5.80 User’s Guide
Tutorial
Price field is one of the following: "O", "H", "L", "C", "V", "I" (open
interest). Interval is bar interval in seconds. shift allows to reference past
(negative values) and future (positive values) data in higher time frame. For
example -1 gives previous bar’s data (like in Ref function but this works in
higher time frame).
Examples:
TimeFrameGetPrice( "O", inWeekly, -1 ) // gives you previous week Open price
TimeFrameGetPrice( "C", inWeekly, -3 ) // gives you weekly Close price 3 weeks
ago
TimeFrameGetPrice( "H", inWeekly, -2 ) // gives you weekly High price 2 weeks ago
TimeFrameGetPrice( "O", inWeekly, 0 ) // gives you this week Open price.
TimeFrameGetPrice( "H", inDaily, -1 ) // gives previous Day High when working on
intraday data
Shift works as in Ref() function but it is applied to compressed time frame.
Note these functions work like these 3 nested functions
TimeFrameExpand( Ref( TimeFrameCompress( array, interval, compress(depending on
field used) ), shift ), interval, expandFirst )
therefore if shift = 0 compressed data may look into the future ( weekly high can
be known on monday ). If you want to write a trading system using this function
please make sure to reference PAST data by using negative shift value.
The only difference is that TimeFrameGetPrice is 2x faster than nested
Expand/Compress.
Note on performance of TimeFrame functions:
a) Measurements done on Athlon 1.46GHz, 18500 daily bars compressed
to weekly time frame
TimeFrameGetPrice( "C", inWeekly, 0 ) - 0.0098 sec (9.8 milliseconds)
TimeFrameSet( inWeekly ) - 0.012 sec (12 milliseconds)
TimeFrameRestore( ) - 0.006 sec (6 milliseconds)
TimeFrameCompress( Close, inWeekly, compressLast ); - 0.0097 sec (9.7
milliseconds)
TimeFrameExpand( array, inWeekly, expandLast ); - 0.0098 sec (9.8
milliseconds)
b) Measurements done on Athlon 1.46GHz, 1000 daily bars compressed to
weekly time frameall functions below 0.0007 sec (0.7 millisecond)
How does it work internally ?
Time-frame functions do not change the BarCount - they just squeeze the arrays so
you have first N-bars filled with NULL values and then - last part of the array
contains the actual time-compressed values. This is why it is essential to expand
the data back to the original frame with TimeFrameExpand. The following simple
exploration shows what happens after you switch to a higher timeframe. Run
Exploration on current symbol, all quotations, periodicity set to daily and you
will see how "weekly close compressed" column contains empty values at the
beginning and weekly compressed data at the end of array.
Multiple Time Frame support in AFL
268
AmiBroker 5.80 User’s Guide
Tutorial
Filter = 1;
AddColumn(Close, "Daily close");
TimeFrameSet(inWeekly);
AddColumn(wc = Close, "weekly close compressed");
TimeFrameRestore();
AddColumn( TimeFrameExpand(wc, inWeekly), "weekly close expanded");
EXAMPLES
EXAMPLE 1: Plotting weekly MACD and cross arrows from daily data
TimeFrameSet( inWeekly );
m = MACD(12, 26 ); // MACD from WEEKLY data
TimeFrameRestore();
m1 = TimeFrameExpand( m, inWeekly );
Plot( m1, "Weekly MACD", colorRed );
PlotShapes( Cross( m1, 0 ) * shapeUpArrow, colorGreen );
PlotShapes( Cross( 0, m1 ) * shapeDownArrow, colorGreen );
EXAMPLE 2: weekly candlestick chart overlaid on line daily price chart
wo
wh
wl
wc
=
=
=
=
TimeFrameGetPrice(
TimeFrameGetPrice(
TimeFrameGetPrice(
TimeFrameGetPrice(
"O",
"H",
"L",
"C",
inWeekly,
inWeekly,
inWeekly,
inWeekly,
0,
0,
0,
0,
expandPoint
expandPoint
expandPoint
expandPoint
);
);
);
);
PlotOHLC( wo, wh, wl, wc, "Weekly Close", colorWhite, styleCandle );
Plot( Close, "Daily Close", colorBlue );
EXAMPLE 3: Simplified Triple screen system
/* switch to weekly time frame */
TimeFrameSet( inWeekly );
whist = MACD( 12, 26 ) - Signal( 12, 26, 9 );
wtrend = ROC( whist, 1 ); // weekly trend - one week change of weekly macd
histogram
TimeFrameRestore();
/* expand calculated MACD to daily so we can use it with daily signals */
wtrend = TimeFrameExpand( wtrend, inWeekly );
/* elder ray */
bullpower= High - EMA(Close,13);
bearpower= Low - EMA(Close,13);
Buy = wtrend > 0 /* 1st screen: positive weekly trend */
AND
bearpower < 0 AND bearpower > Ref( bearpower, -1 ) /* 2nd screen bear power
Multiple Time Frame support in AFL
269
AmiBroker 5.80 User’s Guide
Tutorial
negative but rising */
AND
H > Ref( H, -1 ); /* 3rd screen, if prices make a new high */
BuyPrice = Ref( H, -1 ); // buy stop level;
Sell = 0 ; // exit only by stops
ApplyStop( stopTypeProfit, stopModePercent, 30, True );
ApplyStop( stopTypeTrailing, stopModePercent, 20, True );
Multiple Time Frame support in AFL
270
AmiBroker 5.80 User’s Guide
Tutorial
Efficient use of multithreading
AmiBroker 5.50 fully supports multithreading (parallel execution on all CPU
cores) in both charting and New Analysis window. This greatly enhances speed of
operation and improves responsivity of application as worker AFL execution
threads do not block the user interface. For example on 4 core Intel i7 that can
run upto 8 threads, it can run upto 8 times faster than old Analysis window.
Exact speed up depends on complexity of the formula (the more complex it is, the
more speedup is possible), amount of data processed (RAM access may be not as
fast as CPU thus limiting possible speed gains).
This chapter describes how to avoid pitfalls that can affect multithreaded
performance.
Understanding how multithreading is implemented
It is important to understand one simple rule first - in AmiBroker one thread can
run one operation on one symbols’ data:
1 operation * 1 symbol = 1 thread
The operation is displaying single chart pane, scan, exploration, backtest,
optimization. The consequences are as follows: single chart pane always uses one
thread. Also a single backtest or optimization running on one symbol uses one
thread only.
But a chart that consists of 3 panes uses 3 threads, even though they all operate
on the same symbol. So we can also write:
N operations * 1 symbol = N threads
We can also run single operation (like scan/exploration/backtest/optimization) on
multiple symbols, then
1 operation * N symbols = N threads
Of course you can also run multiple Analysis windows each of it running multiple
symbols or run multiple charts on multiple symbols, then
P operations * N symbols = ( P * N ) threads
It is also important to understand that some operations consist of not only AFL
execution part but some extra processing and/or user-interface work. In such
cases only AFL execution can be done with multiple threads. This has consequences
for Individual Backtest mode which will be described in detail further.
Note: In version 5.70 there is one exception from this rule: new multi-threaded
individual optimization, that allows to run single-symbol optimization using
multiple threads.
Limits
Efficient use of multithreading
271
AmiBroker 5.80 User’s Guide
Tutorial
The number of threads that actually are launched depends on your CPU and the
version of AmiBroker you are using. Standard Edition has a limit of 2 (two)
threads per Analysis window. Professional Edition has a limit of 32 threads per
Analysis window. In addition to this limit, AmiBroker will detect how many
logical processors are reported by Windows (for example a single Intel i7 920 CPU
is recognized as 8 logical processors (4 cores x 2 hyperthreading)) and will not
run more threads per single Analysis window than the number of logical
processors.
Common pitfals
There are following areas of AFL programming that require some attention if you
want to write multithreading-friendly AFL formulas:
1.
2.
3.
4.
5.
Avoiding the use of OLE / CreateObject
Reducing use of AddToComposite / Foreign to minimum
Efficient and correct use of static variables
Implementing pre-processing / initialisation in the Analysis window
Accessing ~~~Equity symbol
Generally speaking the AFL formula can run in full speed only if it does not
access any shared resources. Any attempt to access shared resource may result in
formula execution waiting for the semaphore/critical section that protects shared
resource from simultaneous modification.
1. Avoiding the use of OLE / CreateObject
AmiBroker fully supports calling OLE objects from AFL formula level, and it is
still safe to use, but there are technical reasons to advocate against using OLE.
The foremost reason is that OLE is slow especially when called not from "owner"
thread.
OLE was developed by Microsoft back in 1990’s in the 16-bit days it is old
technology and it effectivelly prevents threads from running at full speed as all
OLE calls must be served by one and only user-interface thread. For more details
see this article:
http://blogs.msdn.com/b/oldnewthing/archive/2008/04/24/8420242.aspx
For this reason, if only possible you should strictly avoid using OLE /
CreateObject in your formulas.
If you fail to do so, the performance will suffer. Any call to OLE from a worker
thread causes posting a message to OLE hidden window and waiting for the main
application UI thread to handle the request. If multiple threads do the same, the
performance would easily degrade to single-thread level, because all OLE calls
are handled by main UI thread anyway.
Not only that. Threads waiting for OLE can easily deadlock when OLE server is
busy with some other work. AmiBroker contains some hi-tech patented code that
checks for such OLE deadlock condition and is able to unlock from it, but it may
take even upto 10 seconds to unlock. Even worse. OLE calls made from non-UI
thread suffer from overhead of messaging and marshaling and can be as much as 30
Efficient use of multithreading
272
AmiBroker 5.80 User’s Guide
Tutorial
slower compared to when they are called from same process main UI thread. To
avoid all those troubles, avoid using OLE if only possible.
For example instead of using OLE to do RefreshAll like this:
AB = CreateObject("Broker.Application"); // AVOID THIS
AB.RefreshAll(); // AVOID THIS
Use AmiBroker native RequestTimedRefresh function which is orders of magnitude
faster and does not cause any problems. If you want to refresh UI after
Scan/Analysis/Backtest use SetOption("RefreshWhenCompleted", True )
Keep in mind that in most cases the refresh is completely automatic (for example
after AddtoComposite) and does not require any extra coding at all.
If you use OLE to read Analysis filter settings (such as watch list number), like
this:
AB = CreateObject("Broker.Application"); // AVOID THIS
AA = AB.Analysis; // AVOID THIS
wlnum = AA.Filter( 0, "watchlist" ); // AVOID THIS
you should replace OLE calls by simple, native call to GetOption that allows to
read analysis formula filter settings in multithreading friendly manner. For
example to read Filter Include watch list number use:
wlnum = GetOption("FilterIncludeWatchlist"); // PROPER WAY
For more information about supported filter settings fields see GetOption
function reference page.
Also note that AB.Analysis OLE object always refers to OLD automatic analysis
window. This has side effect of launching/displaying old automatic analysis
whenever you use AB.Analysis in your code. As explained above, all calls to OLE
should be removed from your formulas if you want to run in New multithreaded
Analysis window. It is only allowed to access new Analysis via OLE from external
programs / scripts. To access new Analysis from external program you need to use
AnalysisDocs/AnalysisDoc objects as described in OLE Automation interface
document.
2. Reducing use of AddToComposite / Foreign to minimum
Any access to other than "current" symbol from the formula level involves global
lock (critical section) and therefore may impact the performance. For this reason
it is recommended to reduce use of AddToComposite/Foreign functions and use
static variables wherever possible
3. Efficient and correct use of static variables
The access to static variables is fast, thread safe and atomic on single
StaticVarSet/StaticVarGet call level. It means that it reads/writes entire array
in atomic way, so no other thread will read/write that array in the middle of
Efficient use of multithreading
273
AmiBroker 5.80 User’s Guide
Tutorial
other thread updating it.
However, care must be taken if you write multiple static variables at once.
Generally speaking when you write static variables as a part of multi-symbol
Analysis scan/exploration/backtest, optimization, you should do the writing
(StaticVarSet) on very first step using Status("stocknum")==0 as described below.
This is recommended way of doing things:
if( Status("stocknum") == 0 )
{
// do all static variable writing/initialization here
}
Doing all initialization/writes to static variables that way provides best
performance and subsequent reads (StaticVarGet) are perfectly safe and fast. You
should avoid making things complex when it is possible to follow simple and
effective rule of one writer - multiple readers. As long as only one thread
writes and many threads just read static variables, you are safe and you don’t
need to worry about synchronization.
For advanced formula writers only:
If you, for some reason, need to write multiple static variables that are shared
and accessed from multiple threads at the same time, and when you must ensure
that all updates are atomic, then you need to protect regions of your formula
that update multiple static variables with a semaphore or critical section. For
best performance you should group all reads/writes in one section like this:
if( _TryEnterCS( "mysemaphore" ) ) // see StaticVarCompareExchange function for
implementation
{
// you are inside critical section now
// do all static var writing/reading here - no other thread will interfere here
_LeaveCS();
}
else
{
_TRACE("Unable to enter CS");
}
The implementation of both semaphore and critical section in AFL is shown in the
examples to StaticVarCompareExchange function.
4. Implementing pre-processing / initialisation in the Analysis window
Sometimes there is a need to do some initialization or some time consuming
calculation before all the other work is done. To allow for that processing
without other threads interferring with the outcome you can use the following if
clause:
if( Status("stocknum") == 0 )
{
/// initialization / pre processing code
Efficient use of multithreading
274
AmiBroker 5.80 User’s Guide
Tutorial
}
AmiBroker detects such statement and runs very first symbol in one thread only,
waits for completion and only after completion it launches all other threads.
This allows things like setting up static variables for use in further
processing, etc.
5. Accessing ~~~Equity symbol
Using Foreign("~~~Equity", "C" ) makes sense only to display chart of the equity
of the backtest that has completed. It is important to understand that new
Analysis window supports multiple instance, and therefore it can not use any
shared equity symbol, because if it did, multiple running backtest would
interfere with each other. So New Analysis has local, private instance of all
equity data that is used during backtesting and only AFTER backtesting is
complete, it copies ready-to-use equity data to ~~~Equity symbol. This means that
if you call Foreign("~~~Equity", "C" ) from within the formula that is currently
being backtested, you will receive previous backtest equity, not current one.
To access current equity, you need to use custom backtester interface. It has
"Equity" property in the backtester object that holds current account equity. If
you need equity as an array there are two choices, either collect values this
way:
SetOption("UseCustomBacktestProc", True );
if( Status("action") == actionPortfolio )
{
bo = GetBacktesterObject();
bo.PreProcess(); // Initialize backtester
PortEquity = Null; // will keep portfolio equity values
for(bar=0; bar < BarCount; bar++)
{
bo.ProcessTradeSignals( bar );
// store current equity value into array element
PortEquity[ i ] = bo.Equity;
}
bo.PostProcess(); // Finalize backtester
// AT THIS POINT YOU PortEquity contains ARRAY of equity values
}
Or you can use EquityArray property added to Backtester object in v5.50.1
if( Status("action") == actionPortfolio )
{
Efficient use of multithreading
275
AmiBroker 5.80 User’s Guide
Tutorial
bo = GetBacktesterObject();
bo.Backtest();
AddToComposite( bo.EquityArray, // get portfolio Equity array in one call
"~~~MY_EQUITY_COPY", "X",
atcFlagDeleteValues | atcFlagEnableInPortfolio );
}
Please note that values are filled during backtest and all values are valid only
after backtest is complete (as in above example). If you call it in the middle of
backtest, it will contain equity only upto given bar. Avoid abusing this function
and it is costly in terms of RAM/CPU (however it is less costly than Foreign).
Both ways presented will access local, current copy of equity in New Analysis
(unlike Foreign that accesses global symbol values from previous backtest)
Single-symbol operations run in one thread
As explained at the beginning of the article, any operation such as scan,
exploration, backtest, optimization or walk forward test that is done on single
symbol can only use one thread. For that reason there is almost no speed
advantage compared to running same code in the old versions of AmiBroker.
Update as of 5.70: This version has a new "Individual Optimize" functionality
that allows to run single-symbol optimization using multiple threads, albeit some
limitations: only exhaustive optimization is supported and no custom backtester
is supported. This is for two reasons: a) smart optimization engines need the
result of previous step to decide what parameter combination choose for the next
step; b) second phase of backtest talks to UI and OLE (custom backtester) and as
such can not be run from non-UI thread (see below for the details).
Individual Backtest can only be run in one thread
The most important thing to understand is that the Individual backtest is a
portfolio-level backtest ran on just ONE symbol. Even if you run it on watch
list, it still executes things sequentially, single backtest on single symbol at
once, then moving to next symbol in the watch list. Why this is so is described
below.
Both portfolio level and individual backtests consist of the very same two phases
I. running your formula and collecting signals
II. actual backtest that may involve second run of your formula (custom
backtester)
Phase I runs the formula on each symbol in the list and it can be multi-threaded
(if there is more than one symbol in the list).
Phase II that processes the signals collected in phase I, generates raport and
displays results is done only once per backtest.
It can not be multi-threaded because:
a) it talks to User Interface (UI)
b) it uses OLE/COM to allow you to run custom backtester.
Efficient use of multithreading
276
AmiBroker 5.80 User’s Guide
Tutorial
Both OLE and UI + access can not be done from worker (non user-interface) thread.
Even worse OLE/UI + multithreading equals death, see:
http://blogs.msdn.com/b/oldnewthing/archive/2008/04/24/8420242.aspx
Usually, in case of multi symbol portfolios, Phase I takes 95% of time needed to
run portfolio backtest so once you run phase I in multiple threads, you get very
good scalability as only 5% is not multi-threaded.
Since individual backtest runs on ONE symbol then the only phase that can be run
in multiple threads, i.e. phase 1 - consists of just one run, and as such is run
in one thread.
To be able to run Phase II from multiple threads you would NOT be able to talk to
UI and would NOT be able to use COM/OLE (no custom backtester).
That causes that Individual Backtest can NOT be any faster than in old Automatic
Analysis.
Doing the math & resonable expectations
Some users live in fantasy land and think that they can throw say 100GB data and
the data will be processed fast because "they have latest hardware". This is dead
wrong. What you will get is a crash. While 64-bit Windows removes 2GB
per-application virtual address space barrier, it is not true that there are no
limits anymore.
Unfortunatelly even people with technical background forget to do the basic math
and have some unresonable expectations. First and foremost thing that people are
missing is the huge difference between access speeds made by data size. The term
"Random Access Memory" in the past (like back in 1990) meant that accessing data
takes the same amount of time, regardless of location. That is NO LONGER the
case. There are huge differences in access speeds depending on where data is
located. For example Intel i7 920, triple channel configuration accesses L1
cached data with 52GB/second speed, L2 cached data 30GB/second (2x slower!), L3
cached data 24GB/second and regular RAM with 11GB/second. It means that cached
data access is 5 times faster than RAM access. Things get even more dramatic if
you run out of RAM and system has to go to the disk. With most modern SSD disks
we speak about just 200MB/sec (0.2GB/sec). That is two orders (100x) of magnitude
slower than RAM and three orders of magnitude slower than cache. That assumes
zero latency (seek). In real world, disk access can be 10000 times slower than
RAM.
Now do yourself a favour and do the math. Divide 100GB by 0.2GB/second SSD disk
speed. What you will get ? 500 seconds - almost ten minutes just to read the
data. Now are you aware that if application does not process messages for just 1
second is considered as "not responding" by Windows? What does that mean? It
means that even in 64-bit world, any Windows application will have trouble
processing data sets that exceed 5GB just because of raw disk read speed that in
best case does not exceed 200MB/sec (usually much worse). Attempting to backtest
such absurd amounts of data on high-end PC will just lead to crash, because
timeouts will be reached, the Windows will struggle processing messages and you
will overrun system buffers. And it has nothing to do with software. It is just
brutal math lesson that some forgot. First and most important rule for getting
Efficient use of multithreading
277
AmiBroker 5.80 User’s Guide
Tutorial
more speed is limit your data size, so it at least fits in RAM.
Efficient use of multithreading
278
AmiBroker 5.80 User’s Guide
Tutorial
Ranking functionality
A ranking is a relationship between a set of items such that, for any two items,
the first is either ’ranked higher than’, ’ranked lower than’ or ’ranked equal
to’ the second. The simplest way to obtain the rank is to sort items by ’value’
or ’score’. For example you can take 100-bar rate of change for symbols - it will
be your item ’score’ or ’value. Then sort the results by it so you will get
symbol list where first one is best performing (highest rate of change) and the
last one is worst performing one.
AmiBroker allows user to perform/use three different kind of rankings
1. use ranking of trade entry signals (buy/short) to decide which entries are
preferred over the others during portfolio backtesting/optimization
2. display multiple rankings in tables created using Exploration
3. generate numeric ranks for later use (general-purpose functionality)
The first kind of ranking is performed automatically if your trading system
formula defines PositionScore variable. You can use PositionScore variable to
decide which trades should be entered if there are more entry signals on
different securities than maximum allowable number of open positions or available
funds. In such case AmiBroker will use the absolute value of PositionScore
variable to decide which trades are preferred. For the details about ranking
functionality during backtesting see Portfolio Backtester tutorial.
Second kind of ranking is simply assigning a number (rank) to the line of
exploration output. The rank column is added to the exploration output just by
calling AddRankColumn function after performing a sort using SetSortColumns
function. You can call SetSortColumns multiple times and you can call
AddRankColumn multiple times to achieve many different ranks based on
multiple-columns. See example below:
Filter = 1;
AddColumn( Close, "Close" );
AddColumn( Volume, "BI" );
AddSummaryRows( 31 + 32, 1.5 );
AddRankColumn(); // without prior sorting AddRankColumn just adds line number
SetSortColumns( -4 );
AddRankColumn(); // rank according to 4th column (descending)
SetSortColumns( -3 );
AddRankColumn(); // rank according to 3rd column (ascending)
A third kind of ranking is general-purpose, bar-by-bar ranking that is performed
using static variables. It is most resource hungry (computationally intensive)
but also gives most possibilities.
Generally the process involves creating static variables with values to be used
for sorting/ranking, i.e. "scores" and then calling a special function
Ranking functionality
279
AmiBroker 5.80 User’s Guide
Tutorial
(StaticVarGenerateRanks) that generates new set of static variables that hold
calculated ranks.
NOTE: This function is NOT intended to replace bakctester’s built-in ranking via
PositionScore. Just the opposite: whenever you can, you should use PositionScore
as it is way way faster and less memory-consuming way to perform backtests with
ranking.
StaticVarGenerateRanks is generally intended to be used for tasks OTHER than
backtesting such as explorations or indicators that may require ranking
functionality, but of course it can also be used for backtesting when/where
PositionScore alone does not allow to implement what you need in your trading
system.
WARNING: this function is computationally and memory intensive. It takes about
20ms per 15K bars and 7 symbols. Try to call it just once per
scan/exploration/backtest using if( Status("stocknum")==0) or better yet, use
separate scan just once to pre-calculate ranks and use it later (like composite
creation scan). If you fail to do so and call StaticVarGenerateRanks for every
symbol performance would drop significantly as this function not only needs lots
of time to compute but it also has to lock the access to shared memory used by
static variables so other threads trying to access static variables would wait
until this function completes.
StaticVarGenerateRanks function
StaticVarGenarateRanks( "outputprefix", "inputprefix", topranks, tiemode ) is a
core element of general purpose ranking system. It takes 4 parameters:
"outputprefix" - the prefix appended to output static variables that hold the
ranks, "inputprefix" the prefix of static variables holding scores (input),
topranks - which defines how many top/bottom ranking symbols should be included
in the generated rank set and tiemode that defines how ties (equal ranks) should
be resolved.
The "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. Say you want to rank stocks by ROC (rate of change). All you need
to do is to store values into static variables. Let us say that we will use
static variable names like "ItemScoreAPPL", "ItemScoreMSFT", and so on.
To fill input static variables you can use this loop:
for ( i = 0; ( sym = StrExtract( symlist, i ) ) != ""; i++ )
{
SetForeign( sym );
Value = ROC( C, 10 );
RestorePriceArrays();
StaticVarSet( "ItemScore" + sym, Value );
}
Ranking functionality
280
AmiBroker 5.80 User’s Guide
Tutorial
Now you are ready to perform sorting/ranking. There are two modes, normal ranking
mode and Top/Bottom Rank mode. Normal ranking mode is performed when toprank
argument is set to zero.
StaticVarGenerateRanks( "rank", "ItemScore", 0, 1224 );
In this case StaticVarGenerateRanks call would generate set of static variables
starting with prefix defined by 2nd argument each variable holding the rank of
particular symbol, so in this case RankItemScoreMSFT will hold ranking of MSFT,
RankItemScoreAAPL will hold ranking of AAPL. Note that in AmiBroker rank count
start from ONE.
Third argument (topranks) is zero in normal ranking mode. Fourth argument
(tiemode) defines how ties are ranked. Supported modes are 1234 and 1224. In 1224
mode ties are numbered with equal rank.
Example code for normal ranking mode (everything done is done in one pass, can be
used in indicator):
symlist = "C,CAT,DD,GE,IBM,INTC,MSFT";
// delete static variables
StaticVarRemove( "ItemScore*" );
// fill input static arrays
for ( i = 0; ( sym = StrExtract( symlist, i ) ) != ""; i++ )
{
SetForeign( sym );
Value = ROC( C, 10 );
RestorePriceArrays();
StaticVarSet( "ItemScore" + sym, Value );
}
// perform ranking
StaticVarGenerateRanks( "rank", "ItemScore", 0, 1224 ); // normal rank mode
// read ranking
for ( i = 0; ( sym = StrExtract( symlist, i ) ) != ""; i++ )
{
Plot( StaticVarGet( "RankItemScore" + sym ), sym, colorCustom10 + i );
}
Top/bottom ranking mode (that generates top/bottom ranking tables that hold
indexes to top ranking values. When topranks > 0 top ranked values are used, when
topranks < 0 then bottom ranked values are used. The values are stored in
variables that have format of:
OutputprefixInputprefixN where N is a number 1, 2, 3 representing top/bottom
ranks. Let us assume that OutputPrefix parameter is "Top" and Inputprefix
parameter is ROC. In such case variable TopROC1 would hold the index of top rated
value. TopROC2 would hold second top rated value, and so on.
StaticVarGenerateRanks function uses rank numbering that starts from ONE. In top
Ranking functionality
281
AmiBroker 5.80 User’s Guide
Tutorial
ranking mode StaticVarGenerateRanks will also prepare static variable that
contains comma separated list of variable names that can be used to find out
which index refers to which symbol. So if TopROC1 holds 1 you would lookup first
substring in TopROCSymbols variable to find out what variable (symbol) ranked at
the top.
Additionally StaticVarGetRankedSymbols gives easy-to-use method to retrieve comma
separated list of ranked symbols for particular datetime.
Example code for top ranking mode:
symlist = "C,CAT,DD,GE,IBM,INTC,MSFT";
// delete static variables
StaticVarRemove( "ItemScore*" );
// fill input static arrays
for ( i = 0; ( sym = StrExtract( symlist, i ) ) != ""; i++ )
{
SetForeign( sym );
Value = ROC( C, 10 );
RestorePriceArrays();
StaticVarSet( "ItemScore" + sym, Value );
}
// perform ranking
StaticVarGenerateRanks( "rank", "ItemScore", 0, 1224 ); // normal rank mode
StaticVarGenerateRanks( "top", "ItemScore", 3, 1224 ); // top-N mode
StaticVarGenerateRanks( "bot", "ItemScore", -3, 1224 ); // bottom-N mode
// read ranking
for ( i = 0; ( sym = StrExtract( symlist, i ) ) != ""; i++ )
{
Plot( StaticVarGet( "RankItemScore" + sym ), sym, colorCustom10 + i );
}
sdt = SelectedValue( DateTime() );
Title = "{{NAME}} -{{DATE}} - {{VALUES}} TOP: " + StaticVarGetRankedSymbols(
"top", "ItemScore", sdt ) +
" BOT: " + StaticVarGetRankedSymbols( "bot", "ItemScore", sdt ) ;
How to use StaticVarGenerateRanks in Analysis window
Since ranking is resource hungry process, it should be performed just once per
Analysis run, not for every symbol. You can achieve it either by running separate
ranking-generation formula once by hand prior to running Analysis or using
Status("stocknum") == 0 statement that would ensure that ranking process is done
Ranking functionality
282
AmiBroker 5.80 User’s Guide
Tutorial
only for the very first symbol from the watch list under analysis.
Here is an example code for exploration that takes currently active watch list or
all symbol list and performs ranking
if ( GetOption( "ApplyTo" ) == 2 )
{
wlnum = GetOption( "FilterIncludeWatchlist" );
List = CategoryGetSymbols( categoryWatchlist, wlnum ) ;
}
else
if ( GetOption( "ApplyTo" ) == 0 )
{
List = CategoryGetSymbols( categoryAll, 0 );
}
else
{
Error( "The formula works fine if your ApplyTo setting is ’Filter’ or ’All’
" );
}
if ( Status("stocknum") == 0 ) // GENERATE RANKING WHEN WE ARE ON VERY FIRST
SYMBOL
{
StaticVarRemove( "values*" );
for ( n = 0; ( Symbol = StrExtract( List, n ) ) != "";
{
SetForeign ( symbol );
values = RSI();
RestorePriceArrays();
StaticVarSet ( "values" + symbol, values );
_TRACE( symbol );
}
n++
)
StaticVarGenerateRanks( "rank", "values", 0, 1224 );
}
symbol = Name();
values = StaticVarGet ( "values" + symbol );
rank = StaticVarGet ( "rankvalues" + symbol );
AddColumn ( values, "values" );
AddColumn ( rank, "rank" );
Filter = 1;
SetSortColumns( 2, 4 );
Ranking functionality
283
AmiBroker 5.80 User’s Guide
Tutorial
Using AFL Code snippets
Code snippet is a small piece of AFL code. It can be inserted by right-clicking
in the AFL editor window and choosing "Insert Snippet" menu
There are two files located in AmiBroker directory that hold snippets:
CodeSnippets.xml - these are snippets shipped with AmiBroker installation (and
can be replaced in subsequent installations, so don’t modify it!)
UserSnippets.xml - these are user-definable snippets. This file is NOT present in
the installation and user can create it by him/herself.
The XML schema for snippets file is simple (as below). Key trigger functionality
is NOT yet implemented, however Keytrigger fields should be included in the
definition for future use. It will be work like ’autocomplete’ so that you type
the shortcut it, it will unfold to the formula.
<?xml version="1.0" encoding="ISO-8859-1"?>
<AmiBroker-CodeSnippets CompactMode="0">
<Snippet>
<Name>First Snippet</Name>
<Description>Description of the snippet</Description>
<Category>User category</Category>
<KeyTrigger>?trigger1</KeyTrigger>
<Formula>
<![CDATA[
// the formula itself
Using AFL Code snippets
284
AmiBroker 5.80 User’s Guide
Tutorial
]]>
</Formula>
</Snippet>
<Snippet>
<Name>Second Snippet</Name>
<Description>Description of the snippet</Description>
<Category>User category</Category>
<KeyTrigger>?trigger2</KeyTrigger>
<Formula>
<![CDATA[
// the formula itself
]]>
</Formula>
</Snippet>
</AmiBroker-CodeSnippets>
Using AFL Code snippets
285
AmiBroker 5.80 User’s Guide
Tutorial
Video Tutorials (on-line)
For your convenience we have prepared the following Video Tutorials (in
Macromedia Flash format) on our web page:
•
•
•
•
•
•
•
•
How to install AmiBroker
How to use drag-and-drop charting interface
How to setup new database with eSignal RT feed (RT version)
How to setup new database with IQFeed RT feed (RT version)
How to setup new database with Interactive Brokers (RT version)
How to use AmiQuote in ’manual’ mode
How to use chart sheets and layouts
How to use layers
How to use AFL Code Wizard
For more video tutorials please check:
http://www.amibroker.com/support.html
Video Tutorials (on-line)
286
AmiBroker Reference Guide
•
•
•
•
AmiBroker User Interface Reference
ASCII Importer reference
AmiBroker’s OLE automation object model
AmiQuote’s OLE automation object model
AmiBroker Reference Guide
287
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Windows
This part describes functionality of AmiBroker windows.
All these windows are asynchronous i.e. you can open as many windows as you like,
and work with all of them at the same time.
Charting
•
•
•
•
•
•
•
•
•
Chart window pane
Data window
Parameters window
Study drawing tools
Line study properites window
Text box properties window
Formula editor
Risk-yield map window
Place order window
Settings
• Database settings / Intraday settings
• Preferences
• Customize tools window
Symbol / Data
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Symbol tree
Information window
Notepad window
Quote Editor window
Symbol finder window
Finance window
Profile view
Assignment organizer window
Composite calculator window
Categories window
Import Wizard window
Metastock importer window
Real-time Quote window
Easy Alerts window
Time/Sales window
Bar Replay window
Analysis/Tools
•
•
•
•
•
Formula editor
Quick review window
Analysis window
Filter settings window
System test settings window
Windows
288
AmiBroker 5.80 User’s Guide
•
•
•
•
•
•
•
AmiBroker Reference Guide
Commission schedule window
System test report window
Commentary window
Plugins window
Indicator Maintenance wizard
Log window
Performance Monitor
Windows
289
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Chart window pane
This window shows the chart of different technical indicators.
In the bottom of the chart you can see X axis, depending on Parameter window
setting it may or may not display dates, and below you can see scroll bar and
chart sheets tab control. Scroll bar can be used to display past quotes, while
sheet tab allows to view different chart pages/sheets (click here to learn more
about chart sheets).
To the right you can see Y-axis area (marked with blue color) that shows Y-scale
and value labels. Value labels are color fields that display precisely the "last
value" of plots. "Last value" is the value of the indicator (or price) for the
last currently displayed (rightmost) bar. Y-axis area is used also to move/size
chart vertically.
Chart parameters and settings can be adjusted by clicking with RIGHT MOUSE button
over chart and choosing Parameters option from the chart context menu.
Chart window pane
290
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Chart can also be scrolled, resized, moved, shrinked, resized - to learn more
about it please read Tutorial: Basic Charting Guide.
Chart window pane
291
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Parameters window
This window allows the user to modify parameters specified in the AFL formula via
Param, ParamStr, ParamColor, ParamStyle, ParamField, ParamToggle, ParamDate,
ParamTime, ParamList functions and also to adjust axes and grid settings.
It is accessible via chart context menu (right click the mouse over the chart
pane to see the context menu) : choose Parameters and a small window with
parameter list will appear. To edit parameter value simply click on the item
value field as shown in the picture. Then depending on type of the parameter
appropriate control(s) will appear.
For example, if given parameter is a string then text field will appear, and if
given parameter is color then color-picker control will allow you to change the
color.
When editing numeric parameters you can adjust the value by either entering the
value to the edit field or by moving a slider control. To show the edit field click on the number itself (marked with blue color in the picture below). To show
a slider control click next to the number (right-hand side).
If given parameter is a number then slider or the edit field will be shown as in
the picture below:
You can move the slider using mouse, <- -> cursor keys and mouse wheel. As
changes are made underlying chart is immediately refreshed giving great feedback
for the user.
Parameters are grouped into "sections". Sections represent part of the codes
surrounded by _SECTION_BEGIN/_SECTION_END markers. To learn more about this check
Tutorial: Using drag-and-drop interface.
Parameters window
292
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
At any time you can press Reset all button that will reset all parameters to
default values.
For more information on using parameters please read Tutorial: Using colors,
styles, titles and parameters in the indicators and Tutorial: Using drag-and-drop
interface.
Parameter window allows also to control axes and grid appearance as well as some
other per-chart settings. These controls are available in the second Axes & Grid
tab as shown below:
The following options are available:
• Axes
• Grid
♦ Scaling:
◊ Automatic - minimum and maximum value of Y axis is determined
automatically by AmiBroker
◊ Custom - minimum and maximum value of Y axis are user-defined
♦ Minimum - minimum Y axis value (this property is locked if automatic
scaling is selected, to unlock choose Custom scaling)
♦ Maximum - maximum Y axis value (this property is locked if automatic
scaling is selected, to unlock choose Custom scaling)
♦ Type
◊ Linear - use linear Y axis scale
◊ Logarithmic - use logarithmic Y axis scale
♦ Show date axis - turn on/off date display on X axis
♦ Show middle lines - display automatic Y axis grid lines spaced evenly
between minimum and maximum
♦ Show upper/lower limits - display minimum and maximum Y axis value
labels
♦ Show % values - display values as percents
♦ Levels - allows to turn on grid lines at some fixed, popular levels
such as 30/70, 20/80, 10/90, -100/+100, 0
• Miscellaneous
Parameters window
293
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
♦ Show trading arrows - when turned ON this pane will show
buy/sell/short/cover arrows generated by corresponding options
available from Automatic Analysis menu.
♦ File path (locked) - shows the path to the formula file that given
chart uses
♦ Chart ID (locked) - shows the numeric value of Chart ID given pane
uses. Chart ID does not matter unless you use Study() function in
your formula(s).
Parameters window
294
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Data window
Data window can be displayed using
Window->Data Window menu
The Data Window shows the date/time
and values of open, high, low, close,
volume, open interest, aux1 and aux2
of the bar under the mouse cursor. It
also shows mouse cursor Y-coordinate
("Value") expressed in terms of price
corresponding to current mouse cursor
location.
The Data Window also shows the values
of all indicators defined in the
formula. These values are
automatically updated when cursor
stops moving for a fraction of a
second.
Data window
295
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Study drawing tools
AmiBroker’s study drawing tools are accessible from Draw / Fibonacci & Gann
toolbars:
The following tools are available:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
trend line
ray (new in 4.20)
extended line (new in 4.20)
vertical line
horizontal line
parallel lines (new in 4.20)
Regression channels: Raff, standard deviation,
standard error (all new in 4.20)
Fibonacci Retracement study (enhanced in 4.20)
Fibonacci Time zones study
Fibonacci Extensions (new in 4.60)
Fibonacci Time Extensions (new in 4.60)
Fibonacci Fan
Fibonacci arc
Gann Square (new in 4.20)
Gann Fan (new in 4.20)
Ellipse tool
Triangle tool (new in 4.30)
Andrews’ pitchfork (new in 4.30)
Cycles tool (new in 4.60)
Arrow tool (new in 4.70)
Zig-zag tool (new in 4.70)
Arc tool
Rectangle
text box tool
The default Select tool (red arrow) is used to select
drawing objects and quotations on the chart. If you want to
draw given study just switch on appropriate button and start
drawing on the chart by pointing the mouse where you want to
start the drawing and click-and-hold left mouse button. Then
move the mouse. Study tracking line will appear. Release
left mouse button when you want to finish drawing. You can
also cancel study drawing by pressing ESC (escape) key. For
beginners’ guide to charting check Tutorial: Charting guide
Trend line, Ray, Extended, Vertical, Horizontal
These tools give different flavours of basic trend line. Trend line gives a line
segment, Ray gives right-extended trend line, Extended gives trend line that is
extended automatically from both left- and right- sides. Vertical and Horizontal
are self-explaining.
Study drawing tools
296
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Arrow
Similar to Trend line but ends with an arrow
Zig-zag
Draws a series of connected trend lines. To end drawing press ESC key.
Parallel
This tool allows to draw a series of parallel trend line segments. First you draw
a trend line as usual, then a second line parallel to the first is automatically
created and you can move them around with the mouse. Once you click on the chart
it is placed in given position. Then another parallel line appears that can be
placed somewhere else. And again, and again. To stop this please either press ESC
key or choose "Select" tool.
Regression channels
AmiBroker allows to draw easily 3 kinds of regression channels:
• Raff regression channel
• Standard error channel
• Standard deviation channel
All these channels are based on linear regression trend line.
The Regression Channel is constructed by plotting two parallel, equidistant lines
above and below a Linear Regression trendline. The distance between the channel
lines to the regression line is the greatest distance that any one high or low
price is from the regression line.
Standard Error Channels are constructed by plotting two parallel lines above and
below a linear regression trendline. The lines are plotted a specified number of
standard errors away from the linear regression trendline.
Standard Deviation Channels are constructed by plotting two parallel lines above
and below a linear regression trendline. The lines are plotted a specified number
of standard errors away from the linear regression trendline.
You can choose the type of channel by double clicking on the channel study (or
choosing Properties from right mouse button menu)
Study drawing tools
297
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
If Use common color and style box is marked channel lines use the same style and
color as regression (middle) line. If it is not marked you can set separate
colors and style for upper and lower channel line. You can also switch off
completely upper and lower channel lines by unticking Show Upper line and Show
Lower line boxes.
"Study ID" column defines study identifier that can be used in your custom
formulas to detect crossovers. You can change these IDs if required by simple
editing these fields. For more information on Study IDs check Tutorial: Using
studies in AFL formulas
More information on regression channels is available from Technical analysis
guide.
Ellipse and Arc drawing tools
These new drawing tools are connected to the date/price coordinates (as trend
lines) rather than to the screen pixels so they can change the visual shape when
displayed at various zoom factors or screen sizes.
To see the properties of these elements you should double-click on the clock-like
3, 6, 9 or 12 hour positions.
Fibonacci arc
This new drawing tool generates standard Fibonacci-arcs that are controlled by
the trend line drawn with a dotted style. To see the properites of the arcs click
on the controlling trend line.
Study drawing tools
298
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Note that arc radius and central point are relative to the controlling trendline
and because Fibonacci arcs must be circular regardless of screen size/resolution
and zoom factor the position of the arcs may move in date/price domain.
Fibonacci retracement
First please note that Fibonacci tool works differently depending on the
direction of drawing and "show extensions" flag. See the pictures below.
Upward drawing direction
Show Extensions ON
Upward drawing direction
Show Extensions OFF
as you can see it shows both retrace levels (38.2, 50, 61.8) and extension levels
(127.2, 161.8). If "show extensions" box is OFF the tool shows ONLY retrace
levels. It works in a similar way when controlling trend line is drawn downwards.
Study drawing tools
299
AmiBroker 5.80 User’s Guide
Downward drawing direction
Show Extensions ON
AmiBroker Reference Guide
Downward drawing direction
Show Extensions OFF
Now more about Fibonacci settings window:
First column "Show" switches particular line ON/OFF
Second column "Level (%)" defines percentage level. 100 and 0 represent
Study drawing tools
300
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Y-coordinate
of begin and end points of controlling trend line.
Third column "Color" defines color of the line, Fourth column "Style" allows
to choose between regular, thick and dotted styles.
Fifth and Sixth columns "Left side" and "Right side" control display of text
that appear on the left and right side of the Fibonacci level line. Empty - means
no text,
% - means percentage level, $ - means dollar (point) level.
Seventh column "Study ID" defines study identifier that can be used in your
custom formulas
to detect crossovers. Each Fibonacci level has a separate ID be default F0... F9.
You can change these IDs if required by simple editing these fields.
As described in User’s Guide: Tutorial: Using studies in AFL formulas
you can easity write the formula that checks for penetration of particular
Fibonacci level.
In this example we will detect if the closing price drops F2 (38.2%
retracement) level line. The formula is very simple:
sell = cross( study( "F2" ), close );
Note that study() function accepts two arguments: the first is StudyID two letter
code that corresponds to one given in properites dialog; the second argument is
chart ID - by default it is 1 (when it is not given at all) and then it
references the studies drawn in the main price pane. For checking studies drawn
in other panes you should use the codes given above (in the table describing
study() function).
Please note that this formula is universal - it will use appropriate level from
any symbol that has Fibonacci lines drawn.
This is so because AmiBroker keeps data of all studies drawn in its database.
When you scan using above code - AmiBroker checks if Fibonacci levels are drawn
for symbol being currently scanned,
if it finds one - it looks what F2 study is - it finds that this is a fibonacci
line 38.2% located (for example for particular symbol) at $29.06
so AmiBroker internally substitutes study( "F2" ) by $29.06 (caveat: this is
simplification - in fact it internally generates array that represents a trend
line) and checks for cross.
"Extension factor" decides how far lines are right-extended (in X-axis
direction). If you enter 2 you will get lines extended twice as much as default
’1’. If you enter 0 Fibonacci level lines will end where controlling trend line
ends.
"Use as default" - if you check this box and accept the settings by clicking OK all Fibonacci drawings that you will draw later will use these settings.
When using text box tool just type the text in the box, when you want to finish
click outside the text box. You can also cancel editing by pressing ESC key.
Fibonacci Extensions
Study drawing tools
301
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
The Fibonacci Extensions tool is similar to the Fibonacci Retracements tool. The
Fibonacci Extensions tool requires a third point. The extensions and retracement
levels are drawn from this third point, but based upon the distance between the
first two points. A common use of this tool is to first connect two points that
represent the endpoints of a major trend (or wave). Then choose the third point
to be the endpoint of a retracement of that trend. Extensions are then drawn in
the direction of the initial trend, from the third point, using the distance
between points one and two as a basis for the extension levels.
The Fibonacci Extensions toolbar button and drawing tool work much like the
Andrew’s Pitchfork drawing tool. First, click on the Fibonacci Extension button
on the toolbar. Then, click three times, once on each of the points that are
involved in the Fibonacci Extension. The first click should be on the starting
point of the initial trendline. The second click should be on the ending point of
the initial trendline. The third click should be on the ending bar of the
retracement period.
As with Fibonacci Retracements, there is a great deal of flexibility via
Fibonnacci settings tab available after clicking on the study with a right mouse
and selecting "Properties" from the context menu.
Fibonacci Time Extensions
Fibonacci Time Extensions tool is used to specify vertical lines at date/time
levels which are determined to be probable values of changes in trend based on
the markets previous date/time range and a third extension point.
The time extension tool should be used as follows. First, click on the Fibonacci
Time extension button on the toolbar. Then select the first range point
(typically a major top or bottom of a market) by clicking on the chart where you
want the range to begin, then move the mouse pointer to select the second range
point by again clicking on the chart where you want the range to end. Extension
lines now will be drawn onto the future bars.
As in Fibonacci Price retracement and extensions tools you have complete control
over which percentages are used in the Time Extensions tool, and the colours of
each of the extension values via Properites dialog.
Gann square and Gann Fan
Gann Squares indicate possible time and price movements from important highs and
lows. To draw a Gann Square on a chart move the cursor on the chart to the
starting point. The starting point is generally an important High or Low on the
chart. Then drag the mouse to the right until a desired ending point is reached.
The start and end points will be the corners of the square. The ending point is
often to the right of the chart bars. Watch for trends to change directions at
the Gann Square levels. As the Gann Square is drawn to the screen the angle of
the controlling trend line is shown in the status bar.
Properties Window
Study drawing tools
302
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
The properties window is used to change the square levels, color, style,
thickness, and defaults. Click on any of the Gann Square Show entries to add or
remove lines. Click in the square color box to change the line color. Click on
style combo boxes to change the line style. Check the Use as Default box to save
the settings as the default for all subsequent Gann Squares that are drawn. "Left
side" and "Right side" columns control display of text that appear on the left
and right side of the Gann lines. Empty - means no text, % - means percentage
level, $ - means dollar (point) level. "Study ID" column defines study identifier
that can be used in your custom formulas to detect crossovers. You can change
these IDs if required by simple editing these fields. For more information on
Study IDs check Tutorial: Using studies in AFL formulas
Triangle tool
Triangle tool is self-explaining. Drawing a triangle is easy: left-click at the
first point, hold down and drag to the second point, then release mouse button
and drag to the third point and click once. The controlling triangle will become
the pitchfork.
Andrews’ Pitchfork
Andrews pitchfork is a study using parallel trendlines. In constructing the
study, starting points are chosen. The first is a major peak or trough on the
left side of the chart display. The second and third starting points are chosen
to be a major peak and a major trough to the right of the first point. After all
starting points have been decided, AmiBroker draws a trendline from the first
point (the most left) so that it passes directly between the right most points.
Study drawing tools
303
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
This line is called the handle of the pitchfork. The second and third trend lines
are drawn by AmiBroker beginning at the starting points and parallel to the
handle. Dr. Andrews suggested that prices make it to the median line (or handle)
about 80% of the time while the price trend is in place. This means that while
the basic long term price trend remains intact, Dr. Andrews believed that the
smaller trends in price would gravitate toward the median line while the larger
price trend remained in tact. When that does not occur, it may be evidence that a
reversal in the larger price trend may be in progress or provides evidence of a
stronger bias at work in market. When price fails to make it to the medial line
from either side, it is often an expression of the relative enthusiasm of buyers
and sellers and may predict the next major direction of prices. If prices fail to
reach the median line while above the median line, it is a bullish and failing to
reach the median line from below is bearish.
Operating Andrews’ Pitchfork tool is similar to drawing triangle. Left-click at
the first point, hold down and drag to the second point, then release mouse
button and drag to the third point and click once. The controlling triangle will
become the pitchfork.
Cycles tool
To use time cycles tool, click on the cycles drawing tool button in the toolbar
then click at the starting point of the cycle and drag to the end of the cycle.
These two control points control the interval between the cycle lines. When you
release the mouse button you will get a series of
parallel lines with equal interval in between them.
Study drawing tools
304
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Line study properties window
In the study properites window you can select start and end coordinates as well
as line colours and styles. You can also enable automatic left- or right- line
extension so that line will be extended when new quotes will be available.
There are following fields available:
• Start X, Start Y, End X, End Y - study start and end coordinates
• Third X, Third Y - visible only for TRI-POINT studies like triangle,
pitchfork - the coordinates of 3rd control point of the study
• Lock position - if this field is marked it’s impossible to chenge the
position of the study with use of mouse
• Color - allows you to change the study color
• StudyID - defines Study ID which allows you to refer to the study from AFL
formula.
The detailed information is available in Using studies in your AFL formulas
chapter.
• Layer - indicates the layer that the study is placed on.
To learn more about layers read Working with layers.
• Thick / Dotted line - these options alow you to change the format of the
study
• Left / Right Extend - you can choose whether line is extended
Line study properites window is accessible from chart window’s right mouse button
menu. When you click on a study line with a right mouse button the following menu
appears:
Line study properties window
305
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Simply choose Properties to show the line study window.
Line study properties window
306
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Text box properties window
In the text box properites window you can change the text displayed in the box,
select start co-ordinates as well as text and background colours and transparent
style.
There are following fields available:
•
•
•
•
Start X, Start Y - text coordinates
Color - allows you to change the color of the text
Background Color - allows you to change the color of the background
Layer - indicates the layer that the text is placed on. To learn more about
layers read Working with layers.
Text box properites window is accessible from right mouse button menu. When you
click on a text box with a right mouse button the following menu appears:
Simply choose Properties to show the text box properties window.
Text box properties window
307
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
In the text box properites window you can change the text displayed in the box,
select start co-ordinates as well as text and background colours and transparent
style.
Text box properties window
308
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Formula Editor
A new AFL Formula Editor features:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Syntax highlighting (improved in 5.80)
Automatic brace matching/highlighting (NEW in 5.80)
Auto indentation (NEW in 5.80)
Indentation markers (NEW in 5.80)
Enhanced auto-complete in two modes (immediate (NEW in 5.80) and on-demand)
Parameter information tooltips
Line numbering margin and selection margin (NEW in 5.80)
Code folding (NEW in 5.80)
In-line Error Reporting (NEW in 5.80)
New tabbed user interface with ability to work in both MDI and separate
floating frame mode, can be moved behind main AmiBroker screen and brought
back (Window->Toggle Frame) (NEW in 5.80) or kept on top (Window->Keep on
top)
Rectangular block copy/paste/delete (Use mouse and hold down left Alt key
to mark rectangular block) (new in 5.80)
Auto capitalisation (change case)
Virtual space (new in 5.80)
Enhanced printing (with syntax highlighting and header/footer)
Code snippets (new in 5.80)
These features greatly simplifies writing formula and provides instant help so time needed to
write formula decreases significantly.
Formula Editor
309
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Menu
Formula Editor menu options are described in detail in Menus: Formula Editor
chapter of the guide.
Toolbar
The Formula Editor toolbar provides the following buttons:
•
•
•
•
•
•
•
•
•
•
New - clears the formula editor window
Open - opens the formula file
Save - saves the formula under current name
Print - prints the formula
Cut - cuts the selection and copies to the clipboard
Copy - copies the selection to the clipboard
Paste - pastes current clipboard content in the current cursor position
Undo - un-does recent action (multiple-level)
Redo - re-does recent action (multiple-level)
Formula Name - an EDIT field that allows to modify the formula file name,
once you change the name here and press Save button the formula will be
saved under new name and the change will be refleced in editor CAPTION BAR
and in the STATUS BAR (Status bar shows full path).
• Check syntax - checks current formula for errors
• Apply indicator - saves the formula and applies current formula as a
chart/indicator ONCE
• Analysis - saves the formula and selects it as current formula in Automatic
Analysis window and repeat most recently used Analysis operation (i.e. Scan
or Exploration or Backtest or Optimization)
Usage
Typical use of Formula Editor is as follows:
• open Formula Editor
• type the formula
• type meaningful name that describes the purpose of you code into Formula
Name field
• click Apply indicator button (if you have written indicator code)
.. or..
click Analysis button to display Automatic Analysis window (when you have
written exploration/scan or trading system)
Formula Editor
310
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Syntax highlighting
AmiBroker’s AFL editor features user-definable syntax highlighting that automatically applies
user-defined colors and styles to different language elements like functions and reserved
variable names, strings, numbers, comments, etc. This feature greatly simplifies code writing.
You can modify coloring scheme in Preferences window.
Enhanced error reporting
When you make an error in your formula, AmiBroker’s enhanced error reporting will
help you to locate and fix an error by highlighting the place where error occured
and displaying extended error description with the examples of common mistakes
and advice how to fix them. In version 5.80 description of errors are displayed
in-line with the code.
A message bar displays total number of errors and/or warnings. If you press "Go
to error" button the editor will move the caret to the relevant line with the
error, if you press it again, it will move to the next error and so on. If you
close the message bar with the "X" button all error messages will be cleared
(hidden) from the view. You can use Edit->Clear Error Message menu (Ctrl+E) to
clear individual error message (in the current line).
Context help
Formula Editor
311
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
You can quickly display relevant AFL function reference page if you press F1 key
or choose "Function reference" from the context menu while the caret is inside or
right after function name as shown in the picture below:
Automatic statement completion
The automatic completion feature (available when you press CTRL+SPACE key
combination) finishes typing your functions and reserved variables for you, or
displays a list of candidates if what you’ve typed has more than one possible
match. You can select the item from the list using up/down arrow keys or your
mouse. To accept selection press RETURN (ENTER). You can also type immediately
space (for variables) or opening brace (for function) and AmiBroker will
auto-complete currently selected word and close the list. To dismiss the list
press ESC key.
Formula Editor
312
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Parameter Information
When you are typing a function, you can display a Tool Tip containing the
complete function prototype, including parameters. The Parameter Info Tool Tip
is also displayed for nested functions.
With your insertion point next to a function, type an open parenthesis as you
normally would to enclose the parameter list.
AmiBroker displays the complete declaration for the function in a pop-up window
just under the insertion point.
Typing the closing parenthesis dismisses the parameter list.
You can also dismiss the list if you press arrow up/down key, click with
the mouse or press RETURN.
Formula Editor
313
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Editor configuration
The settings of the AFL editor can be changed using Tools->Preferences, Editor
page:
• Auto change case - controls whenever editor automatically changes case of
reserved keywords (for example if user typed valuewhen it would change it
to ValueWhen)
Formula Editor
314
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
• Parameter info - controls whenever parameter info tips are displayed
• Virtual space - controls whenever it is possible to place the caret freely
in any place after the end of a line
• Move edited files from drag-drop to custom folder - normally formulas
created by drag-drop mechanism are located in hidden drag-drop folder, if
you then want to edit them, you can do so in place so they remain in drag
drop (hidden) folder, or you may choose to move them automatically to
’custom’ folder. This switch enables automatic move to custom folder
• Copy as HTML - enables copies in HTML format so AFL code is copied with
colors, without it it will be copied as plain text without formatting
• Use separate frame - if turned on it displays AFL Editor in completely
separate frame that behaves like separate application, if it is turned off,
then AFL editor is displayed as a MDI tab within main AmiBroker frame
(along with charts, analysis windows, web, account windows and so on). By
default it is turned on
• Auto-complete: in "On-demand" mode auto-complete list shows up only when
you press Ctrl+SPACE, in "Immediate" mode auto-complete list pops up
automatically as soon as you type first character (letter) of the
identifier.
Window control
AFL Editor Window as a separate frame can be brought on top or to the back as any
other application window using Windows Task Bar. In addition to that there is a
Window->Toggle Frame menu (and Ctrl+‘ shortcut, ‘ is the tilde key just above TAB
key on most keyboards) that allows to quickly toggle between AmiBroker main frame
and AFL editor frame.
The user may also turn on Window->Keep On Top feature that keeps editor window on
top of AmiBroker main frame.
Margins
Formula Editor
315
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Line numbers margin, Selection margin and Fold margin can be switched on/off
using View menu. In this menu there are also options to fold/unfold all code.
Code snippets
Code snippet is a small piece of AFL code. It can be inserted by right-clicking
in the AFL editor window and choosing "Insert Snippet" menu
For more information about Code snippets see Tutorial: Using Code-snippets
Formula Editor
316
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Risk-Yield Map window
This map provides fast information about risk and possible yields. Yield is a the
average weekly percentage return while Risk is a standard deviation of percentage
weekly returns. On the X axis risk is presented and on Y axis - yield. Thus in
the upper part of the map we have got symbols with giving best yield, with risk
increasing from left to right side of the map.
Selected symbol is marked with a different color, and you can zoom the part of
the map by pressing left mouse button and marking rectangle to zoom in.
Risk-Yield Map window
317
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Place Order dialog
NOTE: This functionality requires automated trading interface add-on that can be
downloaded separately
To place order from the chart please first choose Insert->Buy Order or
Insert->Sell Order menu or appropriate buttons from Order toolbar, then AmiBroker
will allow you to draw a horizontal line with mouse cursor over the chart. Simply
click with LEFT mouse button over chart and hold it down - you a horizontal line
will show marking the price level, once you move the line to correct level,
release left mouse button to place the order (the following dialog will show up),
or press ESC key to cancel entire operation.
In the "Brokerage" currently selected trading interface is displaed. After
installing Interactive Brokers automated trading interface (from
http://www.amibroker.com/at/) the text "Interactive Brokers" should appear. If
there is no trading interface installed the combo box will be empty. If you
installed other trading interfaces they should appear in the list.
In the "Action" field you can choose either Buy or Sell - note that preselected
is the option choosen earlier from the menu or the toolbar.
In the "Type" field you can choose order type (Market, Limit, Stop, StopLimit,
etc), by default "Limit" order is selected.
In the "Expiry" field you can choose how long given order will be valid.
Currently available are Day and GoodTilCanceled.
In the "Quantity" field you can enter the number of shares / contracts to
buy/sell
In the "Limit Price" field you can enter the limit price for the order AmiBroker will fill the value selected on chart by default.
Place Order dialog
318
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
In the "Stop Price" field you can enter stop price for Stop and Stop Limit
orders.
In the "Bracket" group you can choose additional automatic bracket orders.
Bracket orders are "child" stop loss and/or take profit orders that are connected
to main "Parent" order and work as OCA (one cancel another) group (so when for
example take profit is triggered, the corresponding stop loss is canceled).
Bracket prices are calculated automatically from Limit price. The distance
between limit price and stop loss / take profit levels is defined by appropriate
"offset" fields. The distance can be expressed in amount (dollars) or percent of
limit price.
All prices are subject to rounding depending on current symbol TickSize setting
(see Information window). If TickSize is not defined (i.e. is equal to zero),
then AmiBroker assumes 0.01 (one cent).
Status field (highlighted in yellow) - shows the connection status between
AmiBroker and trading interface. Any connection error will be displayed here and
in case of an error AmiBroker will disable "Accept" button will attempt to
reconnect every 5 seconds. You can also manually trigger reconnection attempt by
pressing button with two green arrows.
When status field shows "Connected" then Accept button is enabled and you can
press it to place order. Note that currently the interface places orders with
Transmit flag set to FALSE. This means that orders are NOT actually transmitted
to exchange but await manual transmit in the TWS. This is safety measure.
Once dialog is closed by pressing Accept, the horizontal line showing the limit
price entered will stay on chart. You can not move it by default, but you can
delete it by selecting it and pressing "DEL" (Delete) key.
Place Order dialog
319
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Database Settings
This window allows you to define per-database settings. It is accessible via
File->Database Settings menu.
IMPORTANT: These per-database settings in this window take precedence over
default values definable in Preferences window. See explanation in Tutorial:
Understanding database concepts.
The database settings window is divided into two parts: General and Data source
General settings part are enabled only at the database creation time (File->New
database), once database is created these controls become disabled.
• Browse... - allows to browse for folder where new database should be
created.
• Create - clicking on this button creates the database inside the folder
specified in Database folder edit field.
For more details about creating new database working with particular data source
please check Tutorial section.
Data source part becomes enabled once database is created and it can be used to
modify settings for already existing databases (via File->Database Settings
menu). The following controls are available:
• Data source: defines data souce, this can be either
♦ (local) - it means that no external source is used and data are
maintained by AmiBroker itself. Such database can be updated either
Database Settings
320
AmiBroker 5.80 User’s Guide
•
•
•
•
•
•
AmiBroker Reference Guide
using AmiQuote (Tools->Auto-update quotes) or using ASCII import Import Wizard, Metastock importer, or script.
♦ external data source (one of: eSignal, myTrack, QuoteTracker, Quotes
Plus, TC2000/TCNet, FastTrack, Metastock) - it means that data are
retrieved directly from external database / data source. Such
database is updated automatically via plugin and does not require any
user action in AmiBroker. For example if you use TC2000 as a data
source all data that are present in TC2000 system become
automatically available in AmiBroker. For more details please read
Tutorial: Understanding database concepts.
Local data storage: decides if data from external data source should be
stored/cached also in AmiBroker’s own files. If "Enabled" then external
data are cached in local files. If "Disabled" then local files do not store
external data. Switching this to "Enabled" is required for most real-time
data sources as eSignal, myTrack, QuoteTracker. This setting has no effect
if data source is set to (local).
Number of bars to load - defines how many bars should be loaded from
external data source and kept in AmiBroker. Examples: 10-years EOD: 2600,
60-days intraday 1-minute: 30000 (approx). This setting has no effect if
data source is set to (local).
Base time interval - defines what ’base’ bar interval is used in this
database. For real-time data sources this should be set once at the
database creation time. This is so because real-time sources need to
collect RT ticks and pack them (time-compress) into interval bars. This
setting defines the minimum ’grain’. For EOD sources it is (End-of-day
(daily). For real-time sources this should be 1-minute or higher. For some
real-time sources (like eSignal) this can be also set to tick, 5-sec or
15-sec.
Please note also that you won’t be able to use intraday charting and/or
analysis until base time interval is set to something below end-of-day
interval (it can be 1-minute for example). For more details please read
Tutorial: Basic charting guide.
Flush cache - allows to force cache flushing and force retrieving fresh
data from the plugin
Configure - allows to display data source specific configuration dialog see
Tutorial section for details on configuring various data sources.
Intraday settings - allows to define per-database settings for intraday
databases (see below)
Intraday Settings window
Intraday Settings window
321
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
• Filtering - this provides control over the display of intraday data.
AmiBroker collects all the data but displays only those data which are
inside selected trading hours start-end time. Please note that this affects
all charts and windows except Quote Editor that always displays all
available data.
Show 24 hours trading (no filtering) - all data are displayed (no filtering
at all)
Show day session only - only the data between day session (RTH) start and
end times are displayed
Show night session only - only the data between night sesison (ETH) start
and times are displayed
Show day and night session only - only the data between either day session
start/end time or night session start/end time are displayed
Filter weekends - when checked AmiBroker collects but does not display data
from weekends. When unchecked those data are collected and displayed.
• Trading hours Start / End - defines trading hours start and end times for
day (RTH) and night (ETH) sessions separately (see above). Please note that
the times should be specified in your local time zone.
• Daily time-compression uses - this decides how AmiBroker performs intraday
to daily time compression
Exchange time - daily data are constructed from intraday bars starting from
00:00 and ending at 23:59 in the EXCHANGE (or data source) TIME ZONE
Intraday Settings window
322
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Local time - daily data are constructed from intraday bars starting from
00:00 and ending at 23:59 in the LOCAL (computer) TIME ZONE
Day/Night session times as defined above - daily data are constructed from
the intraday bars that start at the start time of night session (previous
day) and end at the end time of day session)
• Time shift - is the time difference (in hours) between your local time zone
and the exchange time zone
• Allow mixed EOD/Intraday data - it allows to work with database that has a
mixture of intraday and EOD data in one data file. If this is turned on
then in intraday modes EOD bars are removed on-the-fly and in daily mode
EOD bars are displayed instead of time compressed intraday or if there is
no EOD bar for corresponding day then intraday bars are compressed as
usual.
This mode works in conjunction with new versions of plugins that allow
mixed data. As of June 2008 Mixed mode is now supported by IQFeed plugin,
eSignal plugin (1.7.0 or higher) plugins only. Mixed mode allows intraday
plus very long daily histories in one database.
Note that Intraday Settings available from Database Settings dialog are
PER-DATABASE. There is however also an option to define PER-GROUP intraday
settings. To use PER-GROUP intraday settings you have to open Symbol->Categories
window, switch to Groups tab and
check "Group uses own intraday settings" box as shown in the picture below
Then you can click on Intraday Settings button to display per-group settings.
Please note that each group in the category list can have its own individual
settings so you can easily setup groups so they contain instruments traded in
different hours. You can move symbols between groups using Symbol->Organize
assignments dialog.
Intraday Settings window
323
AmiBroker 5.80 User’s Guide
Intraday Settings window
AmiBroker Reference Guide
324
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Preferences window
Charting tab - allows you to modify charting options
• Default number of quotations in a chart - this sets the amount of bars
initially displayed in the chart. (in other words it defines "normal" zoom
range)
• Blank bars in right margin - defines how many blank bars are added in the
right margin (past the last available quote). This blank margin allows you
to project studies (trend lines for example) into the future
• Quote selection only by CTRL+LMB - this decides how vertical selection line
is invoked. When this box is unchecked - single click on the chart causes
display of the selection line, when this box is checked you have to hold
down CTRL key while clicking to get the selection line
• Show vertical line between days (intraday)/years(EOD) - this decides if
dotted vertical line is displayed on the chart to mark day (in intraday
mode) or year (in EOD mode) boundaries
• Show value labels - this decides if value lables for indicator / price
chart lines should be displayed. See basic charting guide for explanation
what value label is.
• Candlesticks - this setting provides detailed control over the appearance
of candlesticks. The distinct color may be used to draw part of the
candlestick or entire candle may be drawn in the same color as its
interior.
• Drawing
Preferences window
325
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
♦ Return to select mode after drawing - when checked current tool is
deactivated after drawing and select mode is entered, when unchecked
currently selected drawing tool remains active after drawing (allows
to plot one study after another, note that the same effect can be
achieved even if this box is checked - it is enough to hold down
SHIFT key while drawing and the tool will remain active)
♦ Auto-select last drawn object - this useful feature automatically
selects recently drawn object. This allows to hit ALT+ENTER to
display properties box immediately without need to click on the
study, and allows to Copy the study via CTRL+C also without
additional click
♦ Snap to price % threshold - defines how far price ’magnet’ works, it
will snap to price when the mouse is nearer than % threshold from
H/L/C price
• Miscellaneous
♦ Ask for parameters of newly inserted indicators - when checked
AmiBroker will automatically display Parameters window each time you
insert new indicator or overlay one indicator over another.
♦ Ask for confirmation when deleting indicator sections - when checked
AmiBroker will ask you to confirm deletion of any overlaid indicator
section (applies to indicators created via drag-and-drop). Please
note that deletion of indicator section modifies the underlying
formula. More on this in Tutorial: Drag-and-drop
♦ Max number of chart sheets - defines how many chart sheets (tabs)
should be available. More information on chart sheets is in the
Tutorial section here. Note that this setting will take effect after
restart.
•
Preferences window
326
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Color tab - allows to define colors for particular chart element.
The controls provide user definable color selection for charts, grid &
background.
Palette editor - allows to modify custom colors that can be referenced later via
colorCustom0..colorCustom15 constants
Preferences window
327
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Editor tab - controls the appearance and features of AFL editor.
• Use syntax highlighting - when checked editor automatically colorizes your
code (different colors/styles for functions, constants, numbers, etc)
• Auto-change case - when checked the function and reserved variable names
are automatically capitalised so if you type bARSSince, editor will change
it to BarsSince
• Auto-complete - when checked you will be able to use auto-completion
feature (CTRL+SPACE will auto-complete the word)
• Parameter info - when checked the editor will display parameter information
tooltip when you type a function name and opening brace
• Highlight error line - when checked the formula editor marks the line of
code that contains an error with a yellow background (Windows 2000 and XP
only)
• Copy As HTML - when checked the AFL editor on Edit->Copy / Cut command puts
not only plain text and RTF formats to the clipboard but also HTML and
DwHTML (Dreamweaver HTML) formats allowing pasting syntax-colorized code to
Macromedia Dreamweaver and other HTML-aware applications. Note: rarely (on
very few machines) turning this on may cause problems with pasting to
Outlook.
• Move edited files from Drag-drop to Custom folder - when checked the editor
will automatically move manually edited formulas created by drag-and-drop
mechanism inside hidden ’Drag-drop’ subfolder to ’Custom’ subfolder.
• Font settings - allows you to define AFL editor font face and size
• Colors and styles - allows you to define what colors and styles will be
used to mark certain language elements when syntax highlighting is ON.
Preferences window
328
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Data tab - allows you to define default, global values for all databases.
IMPORTANT: some of these settings may get overwritten by PER-DATABASE settings in
File->Database Settings window. See explanation in Tutorial: Understanding
database concepts.
• Data source: defines default data souce (for databases that do not specify
other source in File->Database Settings)
• Local data storage: default setting for external databases (this setting
gets overwritten by File->Database Settings). If "Enabled" then external
data are cached in local files. If "Disabled" then local files do not store
external data.
• In-memory cache (max. symbols) - defines how many symbols data should be
kept in RAM (for very fast access) - this works together with the next
setting
• In-memory cache (max. MegaBytes) - defines how many MB of RAM should be
used for temporary data cache (for very fast access)
• Number of bars to load - default setting for external databases (this
setting gets overwritten by File->Database Settings). Defines how many bars
should be loaded from external data souce and kept in AmiBroker. Examples:
10-years EOD: 2600, 60-days intraday 1-minute: 30000 (approx)
• Limit number of saved quotations - if this option is ON AmiBroker will save
database with limited number of quotations. This prevents the database from
growing too much
• Max. number of saved quotations - this is the limit itself. Preferable 300
or higher for EOD databases, 3000 or higher for intraday
Preferences window
329
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
• Default database path - this defines the path to the database that is
loaded on startup. If such database does not exist it will be re-created at
startup time.
Intraday tab - provides settings for intraday charting
• Custom time intervals - allow to define your own N-minute or N-hours
intervals (available later from View->Intraday menu)
• Custom N-tick chart settings - allow to define your own N-tick charts
(available later from View->Intraday menu)
• Align custom minute bars to regular market hours - when checked AmiBroker
will trim pre-market custom interval bar so new bar will begin exactly when
trading hours start. Trading hours can be set per-database in
File->Database Settings->Intraday settings. Let’s say that we have
45-minute bars. Without this setting we would bet bars starting at 9:00,
9:45, 10:30, 11:15 etc. When this is turned on and trading starts at 9:30
we have guarantee that bars will be aligned to 9:30: 8:45, 9:30, 10:15,
11:00
• Time compressed bars shows:
♦ time of FIRST tick inside bar - when selected the bar gets the time
stamp of the very first trade inside given time slot (bar)
♦ time of the LAST tick inside bar - when selected the bar gets the
time stamp of the very last trade inside given time slot (bar)
♦ START time of the interval - when selected the bar is time-stamped
with start time of the time slot (bar). Lets say that 30 minute bar
covers 9:00:00..9:29:59. When this is selected AmiBroker will display
Preferences window
330
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
time of this bar as 9:00
♦ END time of the interval - when selected the bar is time-stamped with
start time of the time slot (bar). Lets say that 30 minute bar covers
9:00:00..9:29:59. When this is selected AmiBroker will display time
of this bar as 9:29:59
• Realtime chart refresh interval - defines interval between automatic chart
refreshes in real-time mode. By default charts are refreshed every 3
seconds but in very volatile market you may prefer to set it to 1, so
charts are refreshed every second in real-time mode.
New in 4.90: To enable ’every tick’ chart refresh in Professional Edition,
go to Tools->Preferences, Intraday tab and enter ZERO (0) into "Intraday
chart refresh interval" field. (note Standard Edition won’t allow to do
that).
Once you enter zero, AmiBroker will refresh all charts with every new trade
arriving provided that the formulasyou use execute fast enough. If not, it
will dynamically adjust refresh rate to maintain maximum possible refresh
rate without consuming more than 50% of CPU (on average). So for example if
your charts take 0.2 sec to execute AmiBrokerwill refresh them on average
2.5 times per second.
Note: built-in Windows Performance chart shows cumulated CPU consumption
for all processes, to display PER-PROCESS CPU load use SysInternals free
software http://www.sysinternals.com/Utilities/ProcessExplorer.html
Preferences window
331
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
• Price data tooltips
if checked small tooltips will appear when you hover over the chart
displaying selected bar date, prices / indicator values
• Show interpretation in tooltip
if checked data tooltips will include also interpretation text that is
normally displayed in the Interpretation window.
• Data tip auto-hide timeout
defines how many seconds data tooltip should remain on the screen if you
don’t move your mouse.
• Add full name to ticker in the ticker box
when checked the ticker box displays not only symbol but also full name of
the issue
• Add full name to ticker in the tree
when checked the workspace tree displays not only symbol but also full name
of the issue
• Full-name tooltips in symbol tree
when checked then full name of symbol is displayed in the tooltip that
appears when you move your mouse over symbol in the symbol tree.
• Data-tip auto-hide timeout
defines time in seconds how long data tooltip (that shows values of
indicators) will be displayed when mouse cursor does not move
• Thousand separator
defines thousand separator for number displayed on charts and all
list-views.
• Decimal places in RT quote window
defines how many decimal places should be displayed in Real Time quote
Preferences window
332
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
window.
• Axis font
defines font face and size to be used for chart axis and text tool
• No minimum size for resizing dialogs
when checked it allows to size dialogs below the minimum size (so some
controls become invisible)
• Display plugin activity
when checked AmiBroker displays information about accessing data plugin in
the status bar
• Case sensitive ticker symbols
when checked ticker symbols are case sensitive. In other words INTC and
Intc and iNTc are considered DIFFERENT. This is required for some Canadian
symbols for example. Please use with caution. If your exchange do not use
case-sensitive tickers please make sure it is UNCHECKED.
• Auto-arrange charts
if this option is on chart windows are scaled and arranged to fit the
screen after every opening/closing chart window.
• Auto-tile multiple chart windows
when checked multiple chart windows are always tiled vertically on every
resize of the main application window.
• Ask to save changed data
when checked AmiBroker asks if you want to save modified data on exit. When
unchecked AmiBroker saves modified data without asking.
• Save on exit: Preferences, Templates, Layouts
controls which settings should be saved automatically on exit
Preferences window
333
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Alerts tab - It allows to define e-mail account settings, test sound output and
define which parts of AmiBroker can generate alerts via AlertIF function.
E-mail settings page now allows to choose among most popular authorization
schemes like: AUTH LOGIN (most popular), POP3-before-SMPT (popular), CRAM-MD5,
LOGIN PLAIN. Version 5.30 allows also to use SSL (secure connection) used by
GMail for example. For more information about setting up with GMail see Tutorial:
Formula based alerts.
Enable alerts from checkboxes allow you to selectively enable/disable alerts
generated by Automatic analysis, Commentary/Interpretation and custom indicators.
Keyboard tab
- keyboard tab has been moved to Tools->Customize dialog
Preferences window
334
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
AFL tab
• Multi-threaded charts - enables multi-threaded execution of AFL in
charts/indicators. Multi-threading allows to maximize speed and utilisation
of modern multi-core / multi-CPU computers. For example on 8-core Intel i7
CPU your charts will run upto 8 times faster than in version 5.30. In
version 5.40 the AFL engine has been completely rewritten from ground up to
allow multiple instances of the engine running simultaneously. This enables
not only multithreading but also enhances responsiveness of entire
application, as even badly-written user formula used in a chart is not able
to lock or slow the rest of the program. Multi-threading is ON by default.
It can be turned off by unchecking this box but it is strongly discouraged.
Multi-threading should be turned ON if you want AmiBroker to operate at
full speed.
• Catch system exceptions in Indicators and commentaries - when checked all
exceptions (run-time errors) are catched by the indicator drawing code, so
no Bug Recovery window appears. Instead exception information is displayed
inside chart pane. It is recommended to have this turned ON especially when
you use real-time data
• Stop parsing on first error - when checked parser stops further code
analysis on first encountered error so only one (first) error is displayed
in the formula editor error list. If it is unchecked then parser will list
all errors found. It is recommended to turn it off.
• Enable loop termination by Shift-BREAK - when checked AmiBroker will allow
to break any for(), while() and do-while() loop by pressing and holding
down SHIFT and BREAK(PAUSE) keys on your keyboard.
Preferences window
335
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
• Check Shift+BREAK key every - defines how often keyboard state should be
checked when loop is executed. Note that specifying small values will make
loop execution slower.
• Endless loop detection threshold - defines the number of loop iterations
after which AmiBroker will terminate the loop with "Possible Endless loop
detected" error message. This is useful in situations when the code has
infinite loop (due to mistake of the formula author) because it won’t allow
AmiBroker to hang due to infinite looping
• Standard include path - the default path to use when #include statement
uses < > braces instead of ""
• Formula tree root path - the root path of Formula file/directory tree
displayed in the Charts tab of Workspace window
• Show hidden folders - determines if formula tree should show subfolders
with "hidden" attribute (drag-drop folder is created as "hidden" by the
setup program)
Currencies tab
This page allows to define base currency and exchange rates (fixed or dynamic)
for different currencies. This allows to get correct backtest results when
testing securities denominated in different currency than your base portfolio
currency. For more details please check Tutorial: Pyramiding and
multiple-currency support in the backtester.
Preferences window
336
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
How does AB know whether I want the fixed or dynamic quote?
There are following requirements to use currency adjustements:
a) Symbol->Information, "Currency" field shows currency different than BASE
currency
b) Appropriate currency (defined in Symbol) has matching entry in
Preferences->Currencies page
c) the dynamic rate "FX SYMBOL" defined in the preferences EXISTS in your
database and HAS QUOTES for each day under analysis range.
What is "INVERSE" check box for in the preferences?
Let’s for example take EURUSD.
When "USD" is your BASE currency then EUR exchange rate would be "straight"
EURUSD fx (i.e. 1.3).
But when "EUR" is your BASE currency then USD exchange rate would be INVERSE of
EURUSD (i.e. 1/1.3).
Opposite would be true with FX rates like USDJPY (which are already "inverse").
Preferences window
337
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Customize tools window
This dialog allows you to customize the User Interface. It can be invoked from
Tools->Customize menu.
In "Tools" tab you define custom tool menu items:
You can launch executable files (.exe), script files (.js, .vbs), web pages
(.html) and any other registered file types from the tools menu. In order to add
a new tool you should open this dialog and click "New" button. Then enter the
tool name, command (by hand or using file dialog) optional arguments and initial
directory. If you check "Prompt for arguments" checkbox AmiBroker will ask for
program’s arguments each time
Version 5.60 brings new #import command that allows to import ASCII files from
local disk or even from remote (web) sources.
In the Tools->Customize, "Tools" page, you can now define custom tool that uses
new #import command
Command: #import
Arguments: URL to download data from
Initial dir: path to format definition file
This functionality is used by the "Update US symbol list and categories" tool.
Other tabs provide UI customization features described in Customize UI tutorial
section.
Keyboard tab
The keyboard tab allows you to define your own keyboard shortcuts.
Customize tools window
338
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
To assign a shortcut key
On the Tools menu, click Customize, and then click the Keyboard tab.
In the Categories list, select the menu that contains the command to which you
want to assign the shortcut key.
In the Commands list, select the command to which you want to assign the shortcut
key.
Put the cursor in the Press New Shortcut Key box, press the shortcut key or key
combination that you want, and click Assign.
If you press a key or key combination that is invalid, no key is displayed. You
cannot assign key combinations with ESC, F1, or combinations such as CTRL+ALT+DEL
that are already being used by your operating system.
If you press a key or key combination that is currently assigned to another
command and press "Assign" the error message will appear giving you choice to
either cancel or re-assign the key shortcut to new command.
To delete a shortcut key
On the Tools menu, click Customize, and then click the Keyboard tab.
On the Categories, and Commands lists, select the location for the shortcut key
you want to delete.
In the Current Keys list, select the shortcut key you want to delete and click
Remove.
To reset all shortcut keys to their default values
On the Tools menu, click Customize, and then click the Keyboard tab.
Click Reset All.
Customize tools window
339
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Symbol tree window
In this windows we have got list of available symbols and categories. Selecting
one of them will refresh all opened charts and update information windows. This
selection is global for the program i.e. all symbol functions will reference
symbol selected in this window.
Symbols window is divided into three parts:
a) search box
b) category tree
c) symbol list
The search box allows to perform full text searches
(including wildcard matching) against symbol and
full name within selected category. So for example
if you select "Technology" sector and type A*
(letter ’A’ and wildcard character *) the symbol
list will show all symbols belonging to Technology
sector with symbol or full name beginning with
letter ’A’. Another example would be tping *-A0-FX this will return all forex symbols on eSignal
database (those ending with -A0-FX substring).
The category tree (see the picture) shows different
kind of categories.
The symbol list (bottom part) shows the list of
symbols belonging to selected category. The symbol
list can be sorted by symbol or by full name. To
sort just click on the header row of the list. Once
you choose desired sorting order it will be kept for
all subsequent category choices and searches. Also
the order of columns can be changed so Full name
column appears as first one. To re-arrange column,
click on the column header, hold down the moust
button and drag the column to desired location. Then
release mouse button.
Single symbol belongs to MANY categories at the same
time. For example AAPL (Apple Inc.) will belong to:
•
•
•
•
Stocks group category
Nasdaq market category
Information sector category
Comp-Computer Mfg industry category
and may also belong to several watch lists and
favorites category. All at the same time. That’s why
one symbol will appear in many leaves of the
workspace symbol tree. Now if you delete the SYMBOL
Symbol tree window
340
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
it will of course disappear from ALL categories
because you have deleted the symbol itself, not its
assignment to category.
Symbol tree window
341
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Information window
This window allows you to display and edit preferences of the symbol.
• Symbol
The short name, used in Select window and with quotation import
functions. If you use them, please check if ticker given in this field is
the same as used in your quotation datasource
• Alias
The alternative ticker name. It will be useful if you e.g. get the realtime
quotes and backfill from two separate datasources, that use different
ticker names.
• Full name
Official version of firm name
• Code
Symbol code number
• Web ID
Symbol Web ID - can be used when you define Profile view
• Address
Corporation address
Information window
342
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
• Issue
Total number of shares
• Nominal value
• Book value
• Currency
• Market
Indicates which market the symbol belongs to.
• Industry
Indicates which industry the symbol belongs to.
• Group
Indicates which Group the symbol belongs to.
• Round lot size
Various instruments are traded with various "trading units" or "blocks".
For example you can purchase fractional number of units of mutual fund, but
you can not purchase fractional number of shares. Sometimes you have to buy
in 10s or 100s lots. AmiBroker now allows you to specify the block size on
global and per-symbol level.
You can define per-symbol round lot size in the Symbol->Information page .
The value of zero means that the symbol has no special round lot size and
will use "Default round lot size" (global setting) from the Automatic
Analysis settings page. If default size is set also to zero it means that
fractional number of shares/contracts are allowed.
• Tick size
This setting controls the minimum price move of given symbol. You can
define it on global and per-symbol level. As with round lot size, you can
define per-symbol tick size in the Symbol->Information page (pic. 3). The
value of zero instructs AmiBroker to use "default tick size" defined in the
Settings page (pic. 1) of Automatic Analysis window. If default tick size
is also set to zero it means that there is no minimum price move.
Note that the tick size setting affects ONLY trades exited by built-in
stops and/or ApplyStop(). The backtester assumes that price data follow
tick size requirements and it does not change price arrays supplied by the
user.
So specifying tick size makes sense only if you are using built-in stops so
exit points are generated at "allowed" price levels instead of calculated
ones. For example in Japan - you can not have fractional parts of yen so
you should define global ticksize to 1, so built-in stops exit trades at
integer levels.
• Margin deposit - explained in Backtesting systems for futures contracts
• Point value - explained in Backtesting systems for futures contracts
• Continuous quotations
Enables continuous trading for this symbol (this enables candlestick charts
and manual entry open/high/low/volume controls and candlestick charts),
Information window
343
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
otherwise symbol is traded with price fixing
• Index
Specifies if symbol belongs to Indexes category.
• Favourites
Specifies if symbol belongs to Favourites category.
• Use only local database for this symbol
Indicates that symbol is not updated via the plugin in real-time database.
This field is checked by default if the symbol is added into realtime
database as a result of import from ASCII file (also AmiQuote download).
This setting allows you to keep additional symbols in the database and
prevent plugin from overwriting the imported data.
For explanation of Fundamental data fields please read "Tutorial: Using
fundamental data" chapter of this guide.
Information window
344
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Notepad window
Notepad window (that you can show/hide using
Window->Notepad menu) that allows to store free-text
notes about particular security. Just type any text
and it will be automatically saved / read back as you
browse through symbols. Notes are global and are saved
in "Notes" subfolder as ordinary
text files.
Notes can be also read and written to using AFL
langauge NoteGet and NoteSet functions.
NoteGet( "Symbol" );
- retrieves note linked to "symbol". If symbol is ""
(empty string) then current symbol is used
NoteSet( "Symbol", "Text..." );
- sets text of the note linked to "symbol".
If symbol is "" (empty string) then current symbol is
used.
If you overwrite note from AFL level that is opened at
the same time in Notepad editor the editor will ask
you (when you switch the focus to it) if it should
reload new text or allow to save your manually entered
text.
Example:
NoteSet("AMD", "Jun 15, 2004: AMD will deliver its
first multi-core processors next year");
Notepad window
345
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Quote Editor window
Quote Editor allows editing, deleting and adding quotes.
To add new quote:
- select (new) entry
- enter date/time
- enter price data
- click on the list on the entry other than (new)
To edit existing quote:
- select quote from the list
- edit price data
- click on the list on the entry other than current
To delete existing quote(s):
- mark one or more quotes (multiple selection possible by holding down SHIFT or
CTRL key)
- click "Delete" button
Quote Editor window
346
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Symbol Finder window (F3)
Stock finder window allows you to quickly search the database for a symbol by
typing the first letters of its full name or ticker. This feature is very useful
when you don’t know the ticker symbol. The symbol finder is accessible via
Edit->Find symbol, Symbol->Find menus or by pressing F3 key.
To find a symbol just type one or more letters in the Search for box. Choose by
Name if you want to perform full name search or choose by Ticker if you want to
look up for the ticker. When you type the letters in the edit box appropriate
symbols will appear in the list. You can click on the item to choose one or you
can just press ENTER key to select the first one. Note that searching starts when
the edit box contains at least 1 character - if it is empty no symbol is shown in
the list.
Symbol Finder window (F3)
347
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Using Web Research window
Web Research window allows you to view on-line news, research, profiles,
statistics and all kind of information related to currently selected symbol
available over the Internet (World Wide Web). Using Web Research instead of plain
web browser has speed advantage as you don’t need to type complicated/long
addresses (URLs) each time you need to get desired information.
Web Research window introduced in version 4.90, replaces and enhances previously
available Profile window. Now it allows unlimited number of user-definable web
research (profile) pages, browsing to any web page (just type URL), tab-browsing,
opening multiple pages at once, selective auto-synchronization.
Web-Reasarch uses Internet Explorer engine so you can be sure that pages are
rendered with the same quality you would get from stand-alone browser.
OPEN NEW WEB RESEARCH WINDOW
Use File->New->Web Research menu to create new web research window
PICKING PRE-DEFINED WEB RESEARCH PAGE:
To display any pre-defined web research page, simply click on the drop down arrow
in the Address combo-box and pick one item from the list. Once you do so, the web
page relevant to currently selected symbol will be automatically displayed.
Using Web Research window
348
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Now you can specify if and when displayed page should change automatically if you
select different symbol.
The Sync button allows to decide when page should be automatically synchronized
with currently selected symbol.
• Don’t sync - means that page should not be synchronized with currently
selected symbol at all
• Sync active - means that page should be synchronized ONLY when it is
currently active or becomes active (by user clicking on given tab) - this
is recommended setting for web-research profiles since it conserves
bandwidth and resources (not active pages are not synchronized and do not
consume any bandwidth)
• Sync always - means that page is synchronized with currently selected
symbol always, no matter if it is active or not.
NAVIGATION
Web Research window operates in a way very similar to stand-alone browser. To
display any web page just type the URL address to "Address" field and press ENTER
(RETURN) key. To navigate back and forward in the history use <- and -> buttons.
Using Web Research window
349
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
To close currently displayed page use regular window close X button as shown in
the picture above
DEFINING YOUR OWN WEB RESEARCH PLACES
In addition to web-research pre-defined pages you can define any number of your
own places. To do so use Tools->Customize menu, Web Pages tab.
To add new place press New button, then type the URL template in the URL field
and web page description in the Description field.
The URL template is the web address in that has parts that depend on selected
symbol. The URL template is parsed by AmiBroker to make actual URL to the web
page. For example to see Yahoo’s profiles page you can use following URL
template:
http://biz.yahoo.com/p/{t0}/{t}.html.
Using Web Research window
350
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Symbols enclosed in brackets {} define fields which are evaluated in execution
time. {t0} symbol is evaluated to the first character of the ticker name and {t}
is evaluated to the whole ticker name. So if AAPL is selected AmiBroker will
generate following URL from above template:
http://biz.yahoo.com/p/a/aapl.html
Then AmiBroker uses built-in web browser (Web Research window) to display the
contents of the page.
Special fields encoding scheme
As shown in above example template URL can contain special fields which are
substituted at run time by values corresponding to the currently selected symbol.
The format of the special field is {x} where x is describes field type. Currently
there are three allowable field types: ticker symbol in original case {t}, ticker
symbol in lowercase {s}, ticker symbol in UPPERCASE {S}, alias {a}, web id {i}.
You can specify those fields anywhere within the URL and AmiBroker will replace
them with appropriate values entered in the Information window. You can also
reference to single characters of ticker, alias or web id. This is useful when
given web site uses first characters of, for example, ticker to group the html
files (Yahoo Finance site does that), so you have files for tickers beginning
with ’a’ stored in subdirectory ’a’. To reference to single character of the
field use second format style {xn} where x is field type described above and n is
zero-based index of the character. So {a0} will evaluate to the first character
of the alias string. To get first two characters of a ticker write simply
{t0}{t1}. Note about web id field: this new field in Information window was added
to handle situations when web sites do not use ticker names for storing profile
files. I found some sites that use their own numbering system so they assign
unique number to each symbol. AmiBroker allows you to use this nonstandard coding
for viewing profiles. All you have to do is to enter correct IDs in Web ID field
and use appropriate template URL with {i} keyword.
Pages stored locally
You may want to have all pages stored on your local hard disk. This has an
advantage that profiles are accessible instantly but they can take significant
amount of storage space and you will need to update them from time to time. To
access locally stored files use the following template URL (example, C: denotes
drive): file://C:\the_folder_with_profile_files\{t}.html. You are not limited to
HTML files, you can use simple TXT files instead. Then create (or download) the
.html (or txt) files for each symbol in the portfolio. These files should obey
the following naming convention: <ticker>.html. So for example for APPLE (ticker
AAPL) the profile should have the name AAPL.html (or AAPL.txt)
Web-based profiles
If you want to display the profiles from remote web pages you will need to find
out how they are accessible (the URL to the web page) and how the data for
different symbols are accessible. I will describe the problem on the example of
Sharenet (www.sharenet.co.za) site providing the data for companies listed on
Johannesburg Stock Exchanges. Sharenet provides company information that is
Using Web Research window
351
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
accessible at the following address (URL):
http://www.sharenet.co.za/free/free_company_na.phtml?code=JSECODEp>
The problem is that database provided by Sharenet uses long ticker names and
JSECODE is a short symbol code. For example for "Accord Technologies" company the
ticker in Sharenet database is ACCORD but the code is ACR. To solve the problem
we will need to use Web ID field in the symbol Information window. If you have
Sharenet database just choose the ACCORD from the ticker list, open
Symbol->Information window and enter ACR to the Web ID edit box and click OK.
Then enter the following URL template to the URL edit box:
http://www.sharenet.co.za/free/free_company_na.phtml?code={i}p>
To be 100% sure please select the text above with a mouse. Then copy it to the
clipboard (Edit->Copy, CTRL-C). Then switch to AmiBroker and click on the Profile
URL edit box. Delete everything from it and press CTRL-V (this will paste the
text). Type "Sharenet" into Description field.
Please note that we have used {i} special field in the template that will be
replaced by AmiBroker with the text entered in the Web ID field of the symbol
information window. Now please select File->New->Web Research and pick Sharenet
from Address combo box. You should see the profile for ACCORD company.
You can also delete any entry by selecting it from the list and pressing Delete
button. You can change the order in which pages appear in the Web Research
address combo using Move Up and Move Down buttons (select the item first and then
use buttons).
Configuration data are stored in webpages.cfg plain text file that holds any
number of URL templates in the form of:
URLTemplate|Description
(each entry in separate line)
Using Web Research window
352
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Assignment organizer window
In order to make assigning the symbols to categories simpler and faster a new
assignment organizer was developed. Now you can simply mark a group of symbols
and quickly move them from one category to another.
You can also delete multiple symbols using this window. To do so, select one or
more symbols from the left pane and click on "Delete" button.
Assignment organizer window
353
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Composite recalculation window
This dialog allows automatic calculation of number and volume of
advancing/declining/unchanged issues. Also possible in this dialog is calculation
of volume numbers for indexes if imported incorrectly. Note well, that automatic
recalculation of composite data makes only sense when you follow whole exchange
(all symbols are included in your database) otherwise this calculation will give
wrong results.
In order to calculate the composites in the database it’s necessary to set the
base index for the market, as it may happen that not all stocks are quoted every
businness day. AmiBroker checks the ’base index’ quotations dates and tries to
find the corresponding quotes of all the stocks belonging to that market, to find
out how many issues advanced, declined and not changed at all.
To calculate composities you need to:
• Open Categories window using Symbol -> Categories menu item.
• Select base index for given market in Markets tab and Base indexes for Composites combo.
For example if you are following NYSE this can by ^DJI (Dow Jones Average)
^DJI must be marked as index in Symbol -> Information and must belong to
the same market.
• Choose "Symbol ->Calculate composites" menu item to open the window shown
below and mark : Number of advancing/declining issues and choose markets
that you calculate composities for and the time range.
• Click Calculate.
There are also two additional fields available:
• Volume for base index
• Copy volume to all indexes
These fields are provided in case you DON’T have real volume data for index
quotes. In that case AmiBroker can calculate volume for index as a sum of volumes
of all stocks belonging to given market. First option assigns calculated volume
Composite recalculation window
354
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
only to base index, the second copies the volume figure to all indices belonging
to given market.
Composite recalculation window
355
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Categories window
This dialog, allows you to define names of markets, groups, sectors and
industries. For each market you can also define base indexes for calculating
relative strength, composite data, beta or web profile URL. The detailed
information about categories can be found in Understanding categories chapter of
this manual.
To Edit name of certain category, please select it from the list and press ’Edit
name’ button.
Base indexs for fields allow you to set the index used in calculation of:
• Relative Strength indicator
• Composities via Composite calculation option
• Beta
Profile field allows you to define URL-template for viewing on-line (or off-line)
companies’ profiles. These URL-templates are market-based, what means you can
have different templates for each market. The template is then parsed to create
the actual URL to the web page, which will be displayed in an embedded web
browser. To learn more read How to set up the profile view chapter.
Categories window
356
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
ASCII Import Wizard
ASCII Import Wizard provides an easy way to import your quotation data files as
well as define your own import formats for future use. Note that wizard offers
only a subset of features available in ASCII importer so it is provided for
novice users only.
The wizard guides you through 3 simple steps
1. Picking the files to import
2. Defining fields
3. Additional settings
Step 1. Picking the files
In this step you select the files you want to import. Just click on the Pick
files button and you will see a file dialog. Browse to the folder where your data
files are located and select the file(s). Please note that you can select
multiple files by holding CTRL or SHIFT key while clicking on the files. After
making your selection please click Open
A complete list of files that you have selected will be displayed in the field at
the bottom of the wizard window. Please check if the list is correct, if not
click "Pick files" to correct your choice.
Step 2. Defining fields
ASCII Import Wizard
357
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
In this step you define the types of fields in the data file. For your
convenience date file sample is shown (a few first lines of the first selected
file) at the bottom of the window.
To define fields please select appropriate field types from Column N combo-boxes.
For example, if the first field (column) in your data file is a symbol ticker
please select "Ticker" from Column 1 combo box. If second field in your data file
is a date in Year-Month-Day format please select "YMD" from the second combo-box.
You can select also DMY for Day-Month-Year dates, MDY for Month-Day-Year dates.
Other field types available from the wizard are: "Open", "Close", "High", "Low"
for the prices and "Volume".
Note about the dates: AmiBroker recognizes both 4 digit and 2 digit year dates.
As for months both numbers and three letter codes ("Jan", "Feb", ...) are
allowed. Also day, month and year may be separated by any of the following
characters: / (slash), \ (backslash), - (minus sign) or may not be separated at
all. All you have to do is to specify the order: DMY, MDY, YMD. For example valid
YMD dates are (31th December 2000):
20001231,
001231,
2000-12-31
2000/12/31
2000-Dec-31
00-12-31
00/12/31
00\12\31
ASCII Import Wizard
358
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
If your file has more than 7 columns please check More columns box and you will
see additional combo-boxes.
The remaining controls here are:
Group: here you should select to which group new symbols are added
Watch list: here you should select to which watch list new symbols are added (if
empty - they are not added to any watch list)
Separator: here you should select the character used as a field separator (comma
is the most often)
Skip lines: this tells AmiBroker how many initial lines should be skipped
(ignored) - for example a few first lines of the file should contain a comment or
other information that should be ignored, and this is the place to define this
Log errors: this tells AmiBroker that it should log all errors to the file
(import.log). In case of any errors this log will be displayed to the user after
finishing import process.
Automatically add new symbols: this tells AmiBroker to add the symbols that
appear in the data file but do not exist yet in AmiBroker database.
Calculate composites: this tells AmiBroker to calculate advance/decline figures
and volume for indexes after import (this requires composites to be set up
properly before importing)
Allow negative prices: this tells AmiBroker to allow negative number in close,
open, high, low fields. By default zero and negative values are NOT allowed.
No quotation data: allows to import data that do not contain prices. For example
ticker lists and/or categories.
Step 3. Additional settings
ASCII Import Wizard
359
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
By default the format you have defined is for single-use only. It is OK for
novice users and for experimenting with the wizard.
If you, however, want to make your definition permantent and available in the
future via ASCII importer you should check Add current settings to ASCII importer
definitions box. Then you should enter the Format description, File mask and
Format file name (or you can accept automatically generated defaults). If you do
so, you will be able to use the format defined in the ASCII importer window just by selecting your own format (as typed in Format description field) from the
"Files of type" combo of a file dialog.
Whatever you decide, you should click "Finish" button in order to start importing
your data.
ASCII Import Wizard
360
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Metastock importer window
IMPORTANT NOTE: Metastock importer should be used ONLY if you want to import MS
data to native, local AmiBroker database once. If you want AmiBroker to just read
Metastock database DIRECTLY without need to import new data over and over please
set up your database WITH METASTOCK PLUGIN as described in the Tutorial.
NOTE 2: if you setup your database with the MS plugin you should NOT use
Metastock importer, because there is no point in using it when your data are
already fed by the plugin.
Metastock importer opens AmiBroker to very rich source of historical data. The
importer supports both old Metastock 6.5 and new 7.x (XMASTER) formats.
Basically Metastock data consist of:
• MASTER/EMASTER file which holds general information about the tickers,
stock names, etc.
• F1.DAT....Fxx.DAT files which hold actual quotation data
The MASTER/EMASTER file is essential because it holds the references to Fxx.DAT
files. Fxx.DAT files store only quotations in either 5 field
(date/high/low/close/volume), 6 or 7 field
(date/open/high/low/close/volume/openinterest) format. As you see MASTER/EMASTER
and Fxx.DAT files are closely connected and you need them all to import the data.
Usage
To import Metastock data you should do the following:
• Choose Metastock import from the menu
• Using the directory requester (Browse...) select the location of data in
Metastock format (the directory with MASTER/EMASTER and Fxx.DAT files)
• After choosing proper directory AmiBroker will display the list of
Metastock importer window
361
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
available symbols and date ranges. By default all available symbol will be
marked for importing (checkmark at the beginning of the list). Now you can
exclude some symbol from the import list by clicking appropriate item in
the list (checkmark will toggle when you click).
• You can decide to which group and watch list the new symbols are added
using Group and Watch List combos.
• After making your selections push ’Import’ button to start the process of
importation.
• During the process you can cancel the operation by clicking ’Abort’ button
in the progress window
Metastock importer window
362
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Using account manager
Account manager is a tool for keeping track of your trades and your performance.
You are able to enter trades you make, deposit/withdraw funds, check the
statistics and historical performance. All transactions are recorded so you will
never forget what happened in the past. Account manager allows you to keep track
of unlimited number of accounts.
New account manager replaces and enhances functionality provided by portfolio
manager in pre-4.90 versions.
CREATE A NEW ACCOUNT
Use File->New->Account menu to create new account
FUNDING AN ACCOUNT
Before you do any trading, you have to fund your account. To do so press
"FUNDING" button on the account manager toolbar, then select "Deposit" as
operation type, enter the DATE when you have funded your account and enter the
amount.
Note that funding date must PRECEDE any trading, as account manager won’t allow
you to trade prior to funding date. Initial deposit will show as "initial equity"
in summary tab.
Using account manager
363
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
THE SETTINGS
It is good idea to go to "Summary tab" and setup commissions and trading mode. If
this account is used for End-of-day trading you should set "EOD Mode" to YES,
otherwise (if you trade intraday) you should set "EOD Mode" to NO. Depending on
this setting Buy/Sell dialogs will allowyou to enter date and time of the trade
or only date.
Commission table allows to enter both per-share (per-contract) commissions and
commissions that are expressed as percent of trade value. Or a combination of
both. You can also set minimums and maximums expressed in dollar amount and/or
percent of trade value. For example if your broker may use 0.01$ (one cent) per
share commission, then you would use PerShare = 0.01 and %OfTradeValue = 0. If
your broker uses say 0.2% of trade value then you would use PerShare = 0 and
%OfTradeValue = 0.2;
Practical example: Interactive Brokers default commission for U.S. stocks is:
0.005 per share but not less than 1 dollar and not more than 0.2% of trade value.
Appropriate settings for such schedule are shown in the screenshot above.
Commission table works as follows: first sum of per-share commission and % of
trade value is calculated. Then the result is checked against minimum and maximum
Using account manager
364
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
limits and if calculated value exceeds the limit then commission is set to value
of such the limit, otherwise calculated value is used without change.
Summary page contains a little bit of basic statistics as well.
ENTERING TRADES
Once you funded an account you can enter trades.To buy (enter long position or
cover short position ) click on "BUY" button.
Then in the Buy dialog you need to select the symbol, the trade date/time. Once
they are entered AmiBroker will display price of given symbol at the selected
date/time (or preceding one if no exact match is found). It will also calculate
maximum possible quantity taking price and available funds into account.
You can change the price and quantity manually.
All other values (net market valye, commission, market deposit, currency, fx
rate) are calculated or retrieved automatically from Symbol->Information page.
Once values are good, click OK to confirm transaction. If you made mistake, you
can press UNDO (Edit->Undo) to revert last transaction.
Similar procedure is for selling (entering short positions or closing longs) with
the exception that you should press "SELL" button instead.
All transactions that you made are listed in the "Transactions" sheet. All open
positions are listed in "Open Positions" sheet. If you enter the trade for symbol
that has position already open, AMiBroker will adjust "open positions"
accordingly (perform scaling in/out). Once open position is closed it is removed
from "open positions" list and moved to "Closed trades" sheet.
Using account manager
365
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
After each transaction, "Equity history" sheet is updated with current account
equity value and also "Summary" page is updated with basic open/long/short trade
stats.(More stats are to come).
IMPORTANT
You have to remember that you must enter all transactions in chronological
manner(oldest first, newest last), as account manager won’t allow you to add
trades out-of-order. If you make mistake, there is one-level undo that you can
use to revert to state before last transaction. If you made more mistakes, the
only option is to close account without saving and re-open original file.
SAVING YOUR ACCOUNT DATA
To save edits made to account use File->Save (or File->Save As to save under new
name). Note that account files are NOT encrypted now, and it is quite easy to
read the file for everyone who has the access to it. So make sure not to leave
your files on some public computer. Password protection/encryption is planned but
NOT implemented yet.
Using account manager
366
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
OPENING PREVIOUSLY CREATED ACCOUNT
To open account file, go to File->Open, in the File dialog, select "Account
(*.acx)" from "Files of type" combo-box, and select the account file you want to
load.
MULTIPLE ACCOUNTS
You can create/open multiple accounts at once (just use File->New->Account,
File->Open many times).
Using account manager
367
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Real-time quote window
Working with real time quote window
The RT quote window provides real-time streaming quotes and some basic
fundamental data. It is fairly easy to operate as shown in the picture below:
You can also display context menu by pressing RIGHT mouse button over RT quote
window.
Real-time quote window
368
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
The context menu allows you to access the following options:
• Time & Sales
Opens Time & Sales window that provides information about every bid, ask
and trade streaming from the market.
• Easy Alerts
Opens Easy Alerts window that provides way to define realtime alerts
executed when bid/ask/last and other fields hit user-defined levels
• Add Symbol
Adds current symbol to Real-Time Quote list
• Add watch list...
Adds entire watch list to real-time quote window
• Type-in symbols
Allows to type the symbols directly as comma-separated list
• Insert empty line
Adds empty (separator) line - useful for grouping symbols
• Remove Symbol
Removes highlighted line (symbol) from the Real-Time Quote list.
• Remove All
Removes all symbols from real-time quote list
• Hide
Hides Real-Time Quote list
Re-arranging symbols using drag-and-drop
Real-time quote window now (v5.10 and up) allows you to re-arrange the list of
symbols by drag-and-drop mechanism. Simply click the left mouse button over the
symbol, hold it down and drag to desired location then release the button.
Real-time quote window
369
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Easy alerts window
Easy alert window allows to define real-time alerts without any coding. Please
note that this functionality is available ONLY if you are using real-time data
plugin and is not available in end-of-day mode.
Adding new alert
•
•
•
•
•
press Add button
enter ticker symbol into Symbol field
choose price field from Field combo box
enter high trigger value and/or low trigger value
select at least one of the Text/Pop-up/E-mail/Sound fields
Alert will be generated when selected price field (for example Ask) will become
equal or greater than High value (if defined), or when selected price field will
become equal or less than Low value (if defined). Alert once hit will not
re-trigger until you press "Reset".
Modifying an alert
Select one of listed alerts and modify values in the edit fields below. If you
want to modify an alert that was hit already, after doing modifications please
press "Reset" button
Deleting alerts
Select one or more alerts from the list (multiple selection possible by pressing
down SHIFT key) and then press Delete button.
Resetting triggered alerts
Easy alerts window
370
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
The alert that was once hit is market as "Hit high" or "Hit low" in the status
field and becomes inactive (won’t trigger anymore). If you want to re-activate
it, select it from the list and press Reset button.
Kinds of alert output
• Text
when this checkbox is marked, when alert is triggered the text defined in
comment field will be displayed in Alert Output window (use Window->Alert
output menu to display it)
• Pop-up
when this checkbox is marked, triggered alert will display pop-up dialog
box
• E-mail
when this checkbox is marked, triggered alert will send an e-mail to the
account defined in Preferences/Alerts.
• Sound
when this checkbox is marked, triggered alert will play sound defined in
Preferences/Alerts.
Easy alerts window
371
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Time & Sales window
NOTE: Standard Edition is limited to 1 time & sales window, Professional Edition
allows UNLIMITED number of time & sales window open simultaneously.
Time & Sales window that provides information about every bid, ask and trade
streaming from the market. Each row displayed represents either new trade, new
bid or new ask that is sent by the streaming data source.
Each line in time and sales window is marked with color to make it easier to
distinguish between various conditions.
Coloring rules are:
•
•
•
•
•
•
•
•
•
light green background means NEW ASK
light red background means NEW BID
normal (white) background means NEW TRADE
Red text for bid/ask price/size means that the value is LESS than previous
value of the same category
(for example bid price written in red letters mean that the new BID is
lower than previous bid price, green volume field means that the volume of
last trade or ask/bid size is greater than last trade volume or ask/bid
size)
Red last trade price means trade occuring on or below current bid
Green text for bid/ask price/size means that the value is GREATER then
previous value.
Green last trade price means trade occuring on or above current ask.
Black text for bid/ask price/size/volume means that the value is the same
Black last trade price means trade occuring inside current bid-ask range
(greater than bid and less than ask)
Time&Sales window in version 5.30 shows some "recent statistics" regarding
trading namely:
• number of trades and average # of trades per second
• number of trades and shares traded at ask or above
Easy alerts window
372
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
• number of trades and shares traded at bid or below
• ask minus bid difference expressed in number of trades and shares
• ask minus bid difference expressed as percentage ratio to total
trades/total volume traded
A little background:
Ask minus bid: the positive numbers represent more transactions occuring on ASK
side than on BID side. This in theory may mean more buying than selling, but in
practice things are largely dependent on security traded. Esp. dark liquidity
pools do not show in order books and may report trades to the tape several
seconds later thus invalidating relationship between bid/ask and actual trade
prices.
IMPORTANT:
These are temporary, short-term stats - they cover ONLY trades displayed in the
T&S window since opening of the window OR
resetting stats.
You can reset statistics using right click menu : "Reset Stats"
Easy alerts window
373
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Bar Replay window
Bar Replay tool is available from Tools->Bar Replay menu. Bar Replay feature
plays back data for all symbols at once with user-defined speed. It means that
data for all symbols will end at specified "playback position". This affects all
formulas (no matter if they are used in charts (indicators) or auto-analysis).
Controls description
Navigation bar:
•
- Rewind to the beginning
•
- one Step Back
•
- Stop - turns bar replay OFF (chart are not affected by bar reply)
•
- Pause - pauses current playback or enters pause mode that allows to
manually drag the slider bar and affect chart display - in PAUSE mode data
are internally modified so quotes past selected "playback" position are
invisible to any part of AmiBroker ( charts / automatic analysis ), except
quotation editor
•
- Play - playback bars history
•
- one Step Forward
•
- Forward to end of selected range
Slider bar - allows to see the playback progress as well as MANUALLY move back
and forward by dragging the slider thumb.
Start/End - controls provide start and end simulation dates. The playback works
so that all data upto currently selected "Playback position" are visible. Data
past this position are invisible. "Playback position" can change from
user-defined "Start" to "End"dates. The small ^ buttons on the right side of
Start / End date fields allow to set Start/End to currently selected date on the
chart.
Step interval - defines interval of the step. Recommended setting is base
interval of your database. So if you have 1-minute database, step interval should
be 1 minute. If you have EOD database, step interval should be daily, however it
is allowed to select higher step intervals. Note that chart viewing interval is
independent from that. So you can playback 1 minute database and watch 15 minute
Bar Replay window
374
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
bars (they will look like real - building last "ghost" bar as new data come in)
Speed parameter defines step frequency. It means how many steps will be played
back within one second. Default is 1. Maximum is 5 minimum is 0.1. If you select
3 for example, AmiBroker will play one step every 0.333 sec giving total of 3
steps per second.
Skip afterhours - when turned on, playback skips hours outside regular trading
hours as defined in File->Database Settings->Intraday Settings
Skip weekends - when turned on, playback skips Saturdays and Sundays
Usage
To ENTER Playback mode - press PLAY
or PAUSE
buttons - then data are
truncated at current "playback position".
To EXIT Playback mode - press STOP
button or close Bar Replay dialog - the
full data set will be restored.
Note that playback simulation is done internally and the database is kept
untouched in fact (all data are still visible in Quote Editor), so there is no
risk using Bar Reply.
Bar Replay window
375
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Formula Editor
A new AFL Formula Editor features:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Syntax highlighting (improved in 5.80)
Automatic brace matching/highlighting (NEW in 5.80)
Auto indentation (NEW in 5.80)
Indentation markers (NEW in 5.80)
Enhanced auto-complete in two modes (immediate (NEW in 5.80) and on-demand)
Parameter information tooltips
Line numbering margin and selection margin (NEW in 5.80)
Code folding (NEW in 5.80)
In-line Error Reporting (NEW in 5.80)
New tabbed user interface with ability to work in both MDI and separate
floating frame mode, can be moved behind main AmiBroker screen and brought
back (Window->Toggle Frame) (NEW in 5.80) or kept on top (Window->Keep on
top)
Rectangular block copy/paste/delete (Use mouse and hold down left Alt key
to mark rectangular block) (new in 5.80)
Auto capitalisation (change case)
Virtual space (new in 5.80)
Enhanced printing (with syntax highlighting and header/footer)
Code snippets (new in 5.80)
These features greatly simplifies writing formula and provides instant help so time needed to
write formula decreases significantly.
Formula Editor
376
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Menu
Formula Editor menu options are described in detail in Menus: Formula Editor
chapter of the guide.
Toolbar
The Formula Editor toolbar provides the following buttons:
•
•
•
•
•
•
•
•
•
•
New - clears the formula editor window
Open - opens the formula file
Save - saves the formula under current name
Print - prints the formula
Cut - cuts the selection and copies to the clipboard
Copy - copies the selection to the clipboard
Paste - pastes current clipboard content in the current cursor position
Undo - un-does recent action (multiple-level)
Redo - re-does recent action (multiple-level)
Formula Name - an EDIT field that allows to modify the formula file name,
once you change the name here and press Save button the formula will be
saved under new name and the change will be refleced in editor CAPTION BAR
and in the STATUS BAR (Status bar shows full path).
• Check syntax - checks current formula for errors
• Apply indicator - saves the formula and applies current formula as a
chart/indicator ONCE
• Analysis - saves the formula and selects it as current formula in Automatic
Analysis window and repeat most recently used Analysis operation (i.e. Scan
or Exploration or Backtest or Optimization)
Usage
Typical use of Formula Editor is as follows:
• open Formula Editor
• type the formula
• type meaningful name that describes the purpose of you code into Formula
Name field
• click Apply indicator button (if you have written indicator code)
.. or..
click Analysis button to display Automatic Analysis window (when you have
written exploration/scan or trading system)
Formula Editor
377
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Syntax highlighting
AmiBroker’s AFL editor features user-definable syntax highlighting that automatically applies
user-defined colors and styles to different language elements like functions and reserved
variable names, strings, numbers, comments, etc. This feature greatly simplifies code writing.
You can modify coloring scheme in Preferences window.
Enhanced error reporting
When you make an error in your formula, AmiBroker’s enhanced error reporting will
help you to locate and fix an error by highlighting the place where error occured
and displaying extended error description with the examples of common mistakes
and advice how to fix them. In version 5.80 description of errors are displayed
in-line with the code.
A message bar displays total number of errors and/or warnings. If you press "Go
to error" button the editor will move the caret to the relevant line with the
error, if you press it again, it will move to the next error and so on. If you
close the message bar with the "X" button all error messages will be cleared
(hidden) from the view. You can use Edit->Clear Error Message menu (Ctrl+E) to
clear individual error message (in the current line).
Context help
Formula Editor
378
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
You can quickly display relevant AFL function reference page if you press F1 key
or choose "Function reference" from the context menu while the caret is inside or
right after function name as shown in the picture below:
Automatic statement completion
The automatic completion feature (available when you press CTRL+SPACE key
combination) finishes typing your functions and reserved variables for you, or
displays a list of candidates if what you’ve typed has more than one possible
match. You can select the item from the list using up/down arrow keys or your
mouse. To accept selection press RETURN (ENTER). You can also type immediately
space (for variables) or opening brace (for function) and AmiBroker will
auto-complete currently selected word and close the list. To dismiss the list
press ESC key.
Formula Editor
379
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Parameter Information
When you are typing a function, you can display a Tool Tip containing the
complete function prototype, including parameters. The Parameter Info Tool Tip
is also displayed for nested functions.
With your insertion point next to a function, type an open parenthesis as you
normally would to enclose the parameter list.
AmiBroker displays the complete declaration for the function in a pop-up window
just under the insertion point.
Typing the closing parenthesis dismisses the parameter list.
You can also dismiss the list if you press arrow up/down key, click with
the mouse or press RETURN.
Formula Editor
380
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Editor configuration
The settings of the AFL editor can be changed using Tools->Preferences, Editor
page:
• Auto change case - controls whenever editor automatically changes case of
reserved keywords (for example if user typed valuewhen it would change it
to ValueWhen)
Formula Editor
381
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
• Parameter info - controls whenever parameter info tips are displayed
• Virtual space - controls whenever it is possible to place the caret freely
in any place after the end of a line
• Move edited files from drag-drop to custom folder - normally formulas
created by drag-drop mechanism are located in hidden drag-drop folder, if
you then want to edit them, you can do so in place so they remain in drag
drop (hidden) folder, or you may choose to move them automatically to
’custom’ folder. This switch enables automatic move to custom folder
• Copy as HTML - enables copies in HTML format so AFL code is copied with
colors, without it it will be copied as plain text without formatting
• Use separate frame - if turned on it displays AFL Editor in completely
separate frame that behaves like separate application, if it is turned off,
then AFL editor is displayed as a MDI tab within main AmiBroker frame
(along with charts, analysis windows, web, account windows and so on). By
default it is turned on
• Auto-complete: in "On-demand" mode auto-complete list shows up only when
you press Ctrl+SPACE, in "Immediate" mode auto-complete list pops up
automatically as soon as you type first character (letter) of the
identifier.
Window control
AFL Editor Window as a separate frame can be brought on top or to the back as any
other application window using Windows Task Bar. In addition to that there is a
Window->Toggle Frame menu (and Ctrl+‘ shortcut, ‘ is the tilde key just above TAB
key on most keyboards) that allows to quickly toggle between AmiBroker main frame
and AFL editor frame.
The user may also turn on Window->Keep On Top feature that keeps editor window on
top of AmiBroker main frame.
Margins
Formula Editor
382
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Line numbers margin, Selection margin and Fold margin can be switched on/off
using View menu. In this menu there are also options to fold/unfold all code.
Code snippets
Code snippet is a small piece of AFL code. It can be inserted by right-clicking
in the AFL editor window and choosing "Insert Snippet" menu
For more information about Code snippets see Tutorial: Using Code-snippets
Formula Editor
383
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Quick review window
This window provides overall market information like:
•
•
•
•
•
•
•
daily symbol quotes
weekly returns comparison table
monthly returns comparison table
quarterly returns comparison table
yearly returns comparison table
Price/Earnings comparison
Price/Book value comparison
In the Date field you select the base date for comparisons. For example weekly
returns are calculated by dividing base day close price with the closing price
one week before.
Filter button allows you to narrow down your search to symbols defined in Filter
settings window.
Quick review window
384
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Automatic analysis window
Automatic analysis window enables you to check your quotations against defined
buy/sell rules. AmiBroker can produce report telling you if buy/sell signals
occurred on given symbol in the specified period of time. It can also simulate
trading, giving you an idea about performance of your system.
In the upper part of window you can see the path to the formula used along with
Pick and Edit buttons.
Pick button opens up a file dialog that allows you to choose the formula you want
to use for the analysis.
Edit button opens up the AFL Formula Editor that allows you to edit currently
selected formula.
If you want to create new formula just open Formula Editor directly from
Tools->Formula Editor menu, type the formula and press Analysis button in the
Formula Editor toolbar.
In the formula editor you need to write the code that specifies either
scan/exploration you want to run or a trading system you want to back test. You
can find the description of this language in AFL reference guide.
In order to make things work you should write two assignment statements (one for
buy rule, second for the sell rule), for example:
buy = cross( macd(), 0 );
Automatic analysis window
385
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
sell = cross( 0, macd() );
Below these fields there are several controls for setting:
1. To which symbol(s) analysis should be applied.
You can select here all symbols, only currently selected symbol (selected
in Select Window) or custom filter setting
2. Time range of analysis
analysis can be applied to all available quotations or only to the defined
number of most recent quotations (or days) or to a date range (from/to)
In the lower part of the analysis window you can see 4 buttons:
1. Scan
this starts the signal scan mode - AmiBroker will search through defined
range of symbols and quotations for buy/sell signals defined by your
trading rules.If one of the buy/sell conditions is fulfilled, AmiBroker
will display a line describing when and on which symbol the signal has
occurred. Next AmiBroker proceeds to the end of the range so multiple
signals on single symbol may be generated.
2. Explore
this starts an exploration mode when AmiBroker scans through database to
find symbols that match user-defined filter. The user can define output
columns that show any kind of information required. For more information
please check out "Tutorial: How to create your own exploration"
3. Back Test
this starts the back-testing mode - AmiBroker will search through defined
range of symbols and quotation for BUY signal defined by your buy rule. If
the buy rule is fulfilled, AmiBroker will "buy" currently analyzed shares.
Next it will search for SELL signal. Then, if sell rule is fulfilled,
AmiBroker will "sell" previously bought symbols. At the same time it will
display the information about this trading in the listview. After
performing simulation the summary will be displayed. Read more in
"Tutorial: How to backtest your trading system"...
The back testing parameters could be changed using Settings window.
4. Settings - allows you to change back tester settings
5. Optimize - allows you to optimize your trading system. Read more in the
"Tutorial: How to optimize your trading system"...
6. Check - this option allows you to check if your formula references future
quotes. AmiBroker analyses your formula and detects if it uses quotes past
current bar. Please note that formulas referencing future can give
unrealistic backtesting results that can not be reproduced in real trading,
therefore you should avoid systems that reference future.
7. Report
this displays Report window that allows you to watch, print and save test
results
8. Equity
- available only after backtesting - displays Equity curve for currently
selected symbol in a new chart pane. Check out "AFL: Equity chart and
function".
9. Export - allows you to export the results to CSV (comma separated values)
file
Automatic analysis window
386
AmiBroker 5.80 User’s Guide
10.
AmiBroker Reference Guide
Close
this closes the analysis window
Moreover you two options "Load" and "Save" for loading and saving your trading
rules from/to files.
Enlarging results view in Automatic analysis window
There is a small arrow button next to the "Result list" horizontal divider line.
This button is provided to enlarge/shrink the result list. When you are editing
your formula it is good to have edit view larger, but to see the backtesting
results it is convenient to enlarge the result list. In that case just click on
that button and the result list will be enlarged (and the edit field will get
shrinked). To do the reverse just click the button again.
Automatic analysis window
387
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Filter settings window
This window is available from "Filter/Define..." button in quick-review and
analysis windows.
Filtering option gives you ability to narrow your search to symbols belonging to
the specified market, group, sector and industry. You can also mark to include
only favourites or indexes. You can use include and/or exclude type filter so you
can also selectively exclude some kind of symbols .
If you use more than one category (for example you select Market and Sector ) the
filter will pass only those symbols that match first AND second category (this
logical conjunction, not alternative)
Filter settings window
388
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
System test settings window
Here you can define the following parameters of back-testing:
General tab
Initial equity - defines the size of your account. In Portfolio backtest - it
represents entire portfolio size. In "Individual" backtest it is per-symbol
initial equity.
Positions considered (long, short, both long and short)
Futures mode
This check box in the settings page is the key to backtesting futures. It
instructs backtester to use margin deposit and point value in calculations.
Min. shares
The minimum number of shares that are allowed to buy/short. Backtester will not
enter trades below that limit. Should be 1 for stocks. Fractional values are good
for mutual funds.
Min. pos value
The minimum position value (in base currency) of the trade that is allowed to be
entered. Backtester will not enter trades below that limit. Zero means no limit.
System test settings window
389
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Pad and align to reference symbol
When this is turned on, all symbols’ quotes are padded and aligned to reference
symbol. Note: by default this setting is OFF. Use responsibly. It may slow down
backtest/exploration/scan and introduce some slight changes to indicator values
when your data has holes and holes are filled with previous bar data. The feature
is intended to be used when your system uses general market timing (generates
global signals based on data and/or indicators calculated using Foreign from
’reference’ symbol) or when you are creating composites out of unaligned data.
Note: if reference symbol does not exist, data won’t be padded.
Account margin
This setting defines percentage margin requirement for entire account. The
default value of Account margin is 100. This means that you have to provide 100%
funds to enter the trade, and this is the way how backtester worked in previous
versions. But now you can simulate a margin account. When you buy on margin you
are simply borrowing money from your broker to buy stock. With current
regulations you can put up 50% of the purchase price of the stock you wish to buy
and borrow the other half from your broker. To simulate this just enter 50 in the
Account margin field (see pic. 1) . If your intial equity is set to 10000 your
buying power will be then 20000 and you will be able to enter bigger positions.
Please note that this settings sets the margin for entire account and it is NOT
related to futures trading at all. In other words you can trade stocks on margin
account.
Commissions
• commission table - backtester will use commission table as defined in
Commission Schedule table window (press Define... button to show it).
• percent - commission is expressed as a percent of trade value
• $ per trade - commission is fixed amount of dollars (or your currency) per
trade
• $ per share/contract - commission is expressed in dollars (or your
currency) per share/contract purchased/sold
Annual interest rate
This setting allows you to define annual interest earned when you are out of the
market or your position is less than available equity.
Periodicity
This setting controls bar interval used for
backtesting/scan/exploration/optimization. To backtest intraday data you should
switch to proper interval there and then run the backtest.
Allow position size shrinking
If you mark this box AmiBroker will shrink down positions if available equity is
less than requested position size (via PositionSize variable). If this box is
unmarked positions will not be entered in such case.
System test settings window
390
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Activate stops immediatelly
When you trade on open and want to have built-in stops activated on the same bar
- just mark this box.
If you trade on close and want built-in stops to be activated from the next bar unmark this box.
You may ask why do not simply check the buyprice or shortprice array if it is
equal to open price. Unfortunatelly this won’t work. Why? Simply because there
are doji days when open price equals close and then backtester will never know if
trade was entered at market open or close.
Round lot size
Various instruments are traded with various "trading units" or "blocks". For
example you can purchase fractional number of units of mutual fund, but you can
not purchase fractional number of shares. Sometimes you have to buy in 10s or
100s lots. AmiBroker now allows you to specify the block size on global and
per-symbol level.
You can define per-symbol round lot size in the Symbol->Information page. The
value of zero means that the symbol has no special round lot size and will use
"Default round lot size" (global setting) from the Automatic Analysis settings
page. If default size is set also to zero it means that fractional number of
shares/contracts are allowed.
You can also control round lot size directly from your AFL formula using
RoundLotSize reserved variable, for example:
RoundLotSize = 10;
Tick size
This setting controls the minimum price move of given symbol. You can define it
on global and per-symbol level. As with round lot size, you can define per-symbol
tick size in the Symbol->Information page. The value of zero instructs AmiBroker
to use "default tick size" defined in the Settings page of Automatic Analysis
window. If default tick size is also set to zero it means that there is no
minimum price move.
You can set and retrieve the tick size also from AFL formula using TickSize
reserved variable, for example:
TickSize = 0.01;
Note that the tick size setting affects ONLY trades exited by built-in stops
and/or ApplyStop(). The backtester assumes that price data follow tick size
requirements and it does not change price arrays supplied by the user.
So specifying tick size makes sense only if you are using built-in stops so exit
points are generated at "allowed" price levels instead of calculated ones. For
System test settings window
391
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
example in Japan - you can not have fractional parts of yen so you should define
global ticksize to 1, so built-in stops exit trades at integer levels.
Reverse entry signal forces exit
When it is ON (the default setting) - backtester works as in previous versions
and closes already open positon if new entry signal in reverse direction is
encountered. If this switch is OFF - even if reverse signal occurs backtester
maintains currently open trade and does not close positon until regular exit
(sell or cover) signal is generated.
In other words when this switch is OFF backtester ignores Short signals during
long trades and ignores Buy signals during short trades.
Allow same bar exit (single bar trade)
When it is ON - entry and exit at the very same bar is allowed, when it is OFF
then exit may occur only on bars following the entry bar. You may turn "Allow
same bar exit" option ON only if you are entering trades on OPEN. If you are
entering trades on any other time than bar’s open, this option should be turned
off to avoid looking into the future.
Use QuickAFL
QuickAFL(tm) is a feature that allows faster AFL calculation under certain
conditions. Initially (since 2003) it was available for indicators only, as of
version 5.14+ it is available in Automatic Analysis too.
Initially the idea was to allow faster chart redraws through calculating AFL
formula only for that part which is visible on the chart. In a similar manner,
automatic analysis window can use subset of available quotations to calculate
AFL, if selected range parameter is less than All quotations".
Detailed explanation on how QuickAFL works and how to control it, is provided in
this Knowledge Base article: http://www.amibroker.com/kb/2008/07/03/quickafl/
Note that this option works in the backtester/optimizer, explorations and scans.
Trades tab
• prices buy/sell/short/cover price fields - allows the user to define at
which price to buy/sell/short sell/buy to cover during system test
• delays buy/sell/short/cover delay - allows to define custom delay between
signal and trade
Stop tab
•
•
•
•
max. loss stop
profit target stop
trailing stop
N-bar stop
See APPLYSTOP function for more details on different stop settings
System test settings window
392
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Report tab
Result list shows
This decides which format of result list is used by new backtester. Possible
choices:
• Trade list (the default) - each trade is listed in a separate row. Trades
are ordered by exit date by default
• Detailed log - each data bar is listed separately. The log shows scores,
positions and other very detailed information useful for debugging your
trading system/position sizing/scoring strategies
• Summary - one row per backtest is generated. The row contains backtest
summary/statistics (like the report)
Risk free rates
Defines risk free rates for Sharpe and UPI stats
Distribution charts spacing
Defines the spacing of profit, MAE and MFE distribution charts. The spacing is
the % amount of profit/MAE/MFE per single bar in a chart.
Generate detailed reports for individual backtests
This causes that in Individual backtest mode full report is generated and stored
for every security under test. Note that this will slow down the test and take up
quite a bit of hard disk space
Include trade list in the report
When turned ON (by default) the backtest report includes also trade list. Note
that trade lists may be huge and consume quite a bit of disk space
Warn before time-consuming optimizations
When turned ON (by default), AmiBroker will display confirmation dialog box when
your optimization has more than 300 steps.
Portfolio tab
System test settings window
393
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Max. Open Positions
Max. Open Positions - the maximum number of simultaneously open positions.
.Settable also using SetOption("MaxOpenPositions", number ) function.
Add artificial future bar
When checked AmiBroker adds tommorrow’s bar and this enables you to see
tommorrow’s (or next bar) trade recommendations when your system uses one bar
delay. Artificial future bar is has incremented date and volume set to zero and
all price fields (OHLC) set to CLOSE price of last data bar.
Limit trade size as % of entry bar volume
This prevents from entering the trades greater than given percentage of entry
bar’s volume. For example if backtesting daily data and today’s volume for thinly
traded stock is 177,000 shares, setting this to 10% will limit the maximum trade
size to 17,700 shares (10% of total daily volume). This prevents from ’affecting
the market’ by huge orders.
IMPORTANT NOTE:
Some instruments like MUTUAL FUNDS come without VOLUME data. To backtest such
instruments please set this field to ZERO (0) or check "Disable trade size limit
weh bar volume is zero" box. This effectively turns OFF this feature. Otherwise
you won’t be able to enter any trade at all.
Disable trade size limit when bar volume is zero
System test settings window
394
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
When it is turned ON and the entry bar volume is zero the backtesterwill not
apply the "limit trade size as % of entry bar volume"- this is to allow
backtesting mutual funds that come with zero volume data When it is OFF and entry
bar volume is zero then backtester will not allow to enter the trade on such bar.
Use previous bar equity for position sizing
Affects how percent of current equity position sizing is performed.
Unchecked (default value) means: use current (intraday) equity to perform
position sizing, checked means: use previous bar closing equity to perform
position sizing.
Enable custom backtest procedure
When checked AmiBroker applies the custom backtest formula specified in the field
below to every backtest that you run. This is useful if you want to permantently
add your custom metrics to all backtests without need to copy paste the same
code.
Custom backtest procedure path
The full path to custom backtest formula (see above).
Old tab
Drawdown figures based on...
Drawdown figures in the backtest report measure equity dip experienced during the
trade(s). To calculate the dip you can use the worst case scenario: low price for
long trades and high price for short trades or single price (open or close) for
both long and short trades. "Drawdown figures based on..." setting (pic. 2)
allows you to choose the price(s) used to calculate drowndowns. Using worst case
scenario you will get a few percent bigger drawdowns than using close or open
price. On the other hand Equity() function always uses shortprice/coverprice
array so you may choose open or close field here to match drawdowns as observed
in equity line.
Formula
- mark this box to include AFL formula in the backtest report
Settings
- mark this box to include settings in the backtest report
Incl. out-of-market pos
- mark this box to include out-of-market positions in the backtest report
Overall summary
- mark this box to include sum of individual symbol backtest results
System test settings window
395
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Symbol summary
- mark this box to include per-symbol summaries
Trade list
- choose format of trade list included in the report
System test settings window
396
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
System test report window
NEW BACKTESTER REPORT
Exposure % - ’Market exposure of the trading system calculated on bar by bar
basis. Sum of bar exposures divided by number of bars. Single bar exposure is the
value of open positions divided by portfolio equity.
Net Risk Adjusted Return % - Net profit % divided by Exposure %
Annual Return % - Compounded Annual Return % (CAR) - this is
Risk Adjusted Return % - Annual return % divided by Exposure %
Avg. Profit/Loss - (Profit of winners + Loss of losers)/(number of trades)
Avg. Profit/Loss % - ’(% Profit of winners + % Loss of losers)/(number of trades)
Avg. Bars Held - sum of bars in trades / number of trades
Max. trade drawdown - The largest peak to valley decline experienced in any
single trade
Max. trade % drawdown - The largest peak to valley percentage decline experienced
in any single trade
Max. system drawdown - The largest peak to valley decline experienced in
portfolio equity
Max. system % drawdown - The largest peak to valley percentage decline
experienced in portfolio equity
Recovery Factor - Net profit divided by Max. system drawdown
CAR/MaxDD - Compound Annual % Return divided by Max. system % drawdown
RAR/MaxDD - Risk Adjusted Return divided by Max. system % drawdown
Profit Factor - Profit of winners divided by loss of losers
Payoff Ratio - Ratio average win / average loss
Standard Error - Standard error measures chopiness of equity line. The lower the
better.
Risk-Reward Ratio - Measure of the relation between the risk inherent in a
trading the system compared to its potential gain. Higher is better. Calculated
as slope of equity line (expected annual return) divided by its standard error.
Ulcer Index - Square root of sum of squared drawdowns divided by number of bars
System test report window
397
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Ulcer Performance Index - (Annual profit - Tresury notes profit)/Ulcer
Index’>Ulcer Performance Index. Currently tresury notes profit is hardcoded at
5.4. In future version there will be user-setting for this.
Sharpe Ratio of trades - Measure of risk adjusted return of investment. Above 1.0
is good, more than 2.0 is very good. More information
http://www.stanford.edu/~wfsharpe/art/sr/sr.htm . Calculation: first average
percentage return and standard deviation of returns is calculated. Then these two
figures are annualized by multipling them by ratio
(NumberOfBarsPerYear)/(AvgNumberOfBarsPerTrade). Then the risk free rate of
return is subtracted (currently hard-coded 5) from annualized average return and
then divided by annualized standard deviation of returns.
K-Ratio - Detects inconsistency in returns. Should be 1.0 or more. The higher K
ratio is the more consistent return you may expect from the system. Linear
regression slope of equity line multiplied by square root of sum of squared
deviations of bar number divided by standard error of equity line multiplied by
square root of number of bars. More information: Stocks & Commodities V14:3
(115-118): Measuring System Performance by Lars N. Kestner
OLD BACKTESTER REPORT
This window (accessible from Report button in Automatic analysis window) provides
very useful information about the performance of a trading system under the test.
The information included here can be customized using system test settings
dialog.
System test report window
398
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Explanation of values:
Total net profit: This is total profit/loss realized by the test. Includes the
closed-out value of the open position (if there is any).
Return on account: This is total profit/loss as a percentage of initial
investment.
Total commissions paid: The amount of commissions paid during trades.
Open position gain/loss: The closed-out value of open position that existed at
the end of the test.
Buy-and-hold profit: The total profit/loss realized by buy-and-hold strategy
(including commission).
Buy-and-hold % return: The total buy-and-hold strategy return as a percentage of
initial investment.
Bars in test: The number of bars tested (Overall summary shows sum of number of
bars in all symbols).
Days in test: The number of days between first bar date and last bar date
(overall summary shows arithmetic average of number of days accross the
population of symbols under test)
System to buy-and-hold index: An index showing how much better/worse is the
system compared to buy-and-hold strategy. A value of 0% means that system gives
the same profit as buy-and-hold strategy. A value of 200% means that system gives
200% more profit than buy-and-hold strategy. A value of -50% means that system
gives a half of the gains of buy-and-hold strategy.
Annual system % return: Calculated compound annual percentage return of the
system (*see the note)
Annual B&H % return: Calculated compound annual percentage return of the buy and
hold strategy (*see the note)
System drawdown: The largest equity dip experienced by the system (relative to
the initial investment).
B&H drawdown: The largest equity dip experienced by the buy and hold strategy
(relative to the initial investment).
Max. system drawdown: The largest point distance between equity peak value and
the following trough value experienced by the system
Max. system % drawdown: The largest percentage distance between equity peak value
and the following trough value experienced by the system
Max. B&H drawdown: The largest point distance between equity peak value and the
following trough value experienced by the buy and hold strategy
Max. B&H % drawdown: The largest percentage distance between equity peak value
and the following trough value experienced by the buy and hold strategy
Trade drawdown: The largest equity dip experienced by any single trade (relative
to the trade’s entry price).
Max. trade drawdown: The largest point distance between equity peak value and the
following trough value experienced by any single trade
Max. trade % drawdown: The largest percentage distance between equity peak value
and the following trough value experienced by any single trade
Total number of trades: The number of trades (winners + losers)
Percent profitable: The number of winning trades compared to total number of
trades shown as a percentage
Profit of winners/Loss of losers: Total amount of money gained in winners/lost in
System test report window
399
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
losers.
Total # of bars in winners/losers: The number of bars spent during winning/losing
trades
Largest winning/losing trade: The amount of biggest winner/loser
# of bars in largest winner/loser: The number of bars in the biggest
winning/losing trade
Average winning/losing trade: The average of winning/losing trades (sum of
winners/losers divided by a number of winning/losing trades)
Average # of bars in winners/losers: The average of number of bars in
winning/losing trades (total number of bars in winners/losers divided by a number
of winning/losing trades)
Max consec. winners/losers: The largest number of consecutive winning/losing
trades.
Bars out of the market: The number of bars for which the system was completely
out of the market (was neither long nor short). If you open and close the
position during single day, even if you have no open position on market open and
no position on close this day is NOT considered as out of the market.
Interest earned: The total interest earned between trades. Note that AmiBroker
simulates O/N (overnight) deposits. This means that if you closed the position on
Monday and opened the next one on Tuesday you earn interest for single O/N
deposit.
Exposure: Shows how much you are exposed to the market. It is a ratio of bars in
the market divided by total number of bars under test. (The number of bars in the
market is given by total number of bars minus bars out of the market)
Risk adjusted ann. return: Shows annual return of the system (*see note) adjusted
(divided) by market exposure. If your system gained 10% over one year with the
exposure of 50% the adjusted return would be 20% (10%/0.5)
Ratio avg win/avg loss: The absolute value of the ratio of average winning trade
to average losing trade
Profit factor: The absolute value of the ratio of the profit of winners to loss
of losers
Avg. trade (win & loss): The average trade profit calculated as sum of winners
and losers divided by the number of trades.
*Note: Calculation method used for annual percentage returns:
Most of the software (including two the most popular so-called professional
packages) use very simple annualization method based on the following formula:
simple_annualized_percentage_return = percentage_return * ( 365 / days_in_test );
unfortunatelly this method is wrong and very misleading since it would tell you
that annual return is 22% when your system earned 44% during two years. This
value is too optimistic. In fact annual return in this case is only 20%: if your
initial investment was 10000 you earn 20% during the first year so you then get
12000 and 20% the second year that gives you 14400 = ( 12000 * 120 % ). So after
two years you earned 44% but annually it is only 20%.
System test report window
400
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
AmiBroker is one of the few programs that calculates annual returns correctly and
will give you correct value of 20% as shown in the example above. The formula
that AmiBroker uses for annual return calculation is as follows:
correctly_annualized_perc_return = 100% * ( (final_value/initial_value) ^ ( 365 /
days_in_test ) - 1 )
where x^y means rising x to the power of y.
Known differencies between statistics produced by ’old’ and ’new’ (portfolio)
backtester
Old backtester
New (portfolio) backtester
System and trade
drawdown
calculations
based on
Open/Close/H-L range
(worst case) selectable
in settings
Close price only (regardless of
settings) - subject to change
Max. % trade
drawdown
Calculated based on
total equity
Calculated based on ACTUAL trade value
at entry point.
Stats available
for all trades only
separately for long, short and all
trades
Based on portfolio equity.
PositionSizing
Based on individual
symbol equity
PositionSize = -25;
will enter 25% of current porfolio
equity
Include only closed
trades, open trade is
reported separately
Include all trades (closed and those
still open at the end of analysis
period). Any open trades are closed
out at ’close’ price always.
Exposure
calculated regardless
of position size (no
matter on what is
position size if trade
is taken for particular
bar it assumes 100%
exposure at that bar)
calculations include now (in 4.43.0)
the total amount of open positions
compared to total portfolio equity.
Exposure is calculated on bar by bar
basis so if only 50% funds are in open
trade, then exposure for this bar is
0.5. Then individual bar exposures are
summed up and divided by number of
bars to produce exposure figure. This
way true market exposure is
calculated.
Multiple
security testing
N independent accounts
(multiple single
equity)
Portfolio equity common to all symbols
under test
Trade statistics
System test report window
401
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Commission window
Commission table is available in the Account manager and in Automatic Analysis ->
Settings window, "General" tab, "Commission and rates: Define..."
In this window you can enter commission taken by buy/sell transactions.
There are 5 tiers of commission schedule table plus "default" tier that is used
when others are not defined or transaction does not match any tier defined. Tiers
can be defined based on transaction value or number of shares/contracts traded.
Each tier has user definable minimum and maximum. If min/max is not defined or
set to zero - the tier is not active.
Each tier allows to define commission on per-share, per-trade, % of trade volume
basis and allows to define minimum and maximum commission values based on dollar
or percent values.
Commission window
402
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Commentary window
Commentary window enables you to view textual descriptions of actual technical
situation on given market.
Commentaries are generated using formulas written in AmiBroker’s own formula
language. You can find the description of this language in AmiBroker Formula
Language Reference Guide.
Moreover Commentary feature gives you also graphical representation of buy & sell
signals by placing the marks (arrows) on the price chart.
Newbies should read "Tutorial: How to write your own commentary" for step-by-step
instructions and working with AFL editor.
"Refresh" button causes AmiBroker to reinterpret the commentary using currently
selected symbol/date.
"Load" and "Save" buttons allow to load/save commentary formulas.
"Close" button closes the commentary window.
Now the Guru chart commentary window is automatically updated and sychronized
with the date selected on the chart using "Pick" selector tool. This way you can
easily read any indicator value on any selected date right off the chart
commentary window.
Commentary window
403
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Plugins window
Plugins window lists all loaded plug in DLLs. It is useful for inspecting which
plugins are active.
In addition to just showing the list of plugins you can unload all DLLs by
pressing "Unload" button and load them back by pressing "Load" button. Please
note that a DLL must be placed in the "Plugins" subfolder of AmiBroker main
directory to be seen.
At start AmiBroker scans the "Plugins" folder and loads the DLLs that follows the
specifications of AmiBroker plugin. If a DLL is loaded it is "locked" for writing
so it can not be overwritten or modified.
During the development process it is necessary to overwrite/modify the DLL code because when you apply the changes to the source code these changes must be
recompiled and stored into DLL file. To allow the developer to overwrite the DLL
used by AmiBroker the "Unload" function is available in this window. Unloading
releases the DLL so it can be overwritten without the need to restart AmiBroker.
Then, after modifying the DLL code, you can load the DLL back using "Load"
function.
IMPORTANT NOTE: AmiBroker makes no representations on features and performance of
non-certified third-party plug-ins. Specifically certain plug-ins can cause
instabilities or even crashes. Entire use of non-certified third-party plugins is
at your own risk.
Plugins window
404
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Indicator Maintenance Wizard
Indicator maintenance checks for any indicators that were deleted from any
layouts on your hard disk and frees table from entries
allocated for indicators that were deleted. This procedure is rarely but still
needed because if you delete indicator from one
layout there is no guarantee that there is no other layout file buried somewhere
on your hard disk that still references given indicator.
So Indicator Maintenance scans all hard disks and all partitions looking for
layout files and analysing them to built the
" actually used" table of indicators.
The ones which are not referenced by any layout can be deleted from internal
table.
Depending on your choice you may leave default behaviour (cleaning up only
internal table) or deleting actual formula files
that are not referenced. This is up to you. If you don’t use particular formula
for say AA Scan/Backtest/Optimization you can
delete it. If you use it or need it for some archive purposes - leave it
unchecked.
Indicator Maintenance Wizard
405
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
If you are not sure what options to choose, just press "Next" all the time and
you will safely complete the procedure without changing any settings.
Indicator Maintenance Wizard
406
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Log window
The Log window (available from Window->Log menu) allows to view:
• edit-time errors displayed during formula check
• run-time errors that occur when formula is running (not edited)
• _trace command output within AmiBroker (without using 3rd party debug view)
To perform tasks such clearing the output, copying, changing settings use right mouse click over the log window list.
Double click on the error line brings up the editor, so you can fix the error
easily.
While "edit-time" error list is cleared automatically each time you check the
syntax in the editor, the run-time error list is NOT cleared, so all errors
remain listed, even if they are fixed already, unless you manually clear the
list.
Note that _TRACE output is by default directed to outside debugger (like
DebugView), in order to enable internal display you need to switch appropriate
option in the Tools->Preferences->AFL You can choose to display internally /
externally or in both places.
Internal _trace has much lower performance penalty (order of magnitude) than
external, but that is achieved by the fact that
internal log window is refreshed only when application is not busy. It is
appropriate for some uses, but you may prefer more immediate
refresh offered by DebugView.
Note that internal log window accepts special string "!CLEAR!" that causes
deleting contents of the log window, as presented in the example below:
_TRACE("!CLEAR!"); // this clears the internal log window.
_TRACE("First line after clear");
Log window
407
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Performance Monitor window
The performance monitor is available from Tools->Performance Monitor menu and it
shows some memory and usage statistics:
•
•
•
•
•
•
number of symbols in the database
number of symbols cached in RAM
quotation data memory usage
current symbol memory usage
total chart refresh time
real-time data stream update frequency
The contents of the window is updated automatically every 3 seconds
This tool is intended to be used now for two purposes:
a) tweaking cache settings for best RAM usage (for example optimizations will run
faster if all quotation data can be kept in RAM)
b) monitoring real-time performance
More uses will probably come in the future.
Log window
408
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Menus
This chapter describes AmiBroker menus.
There are following main pull down menus:
•
•
•
•
•
•
•
•
•
•
File
Edit
View
Insert
Format
Symbol
Analysis
Tools
Window
Help
And the following CONTEXT menus:
• AFL Editor context menu (available when you click with RIGHT mouse button
in the AFL editor)
• Automatic Analysis window context menu (available when you click with RIGHT
mouse button over Automatic Analysis RESULT LIST)
• Alert Output context menu (available when you click with RIGHT mouse button
in the Alert Output window)
• Chart pane context menu (available when you click with RIGHT mouse button
in the chart pane)
• Layouts context menu (available when you click with RIGHT mouse button in
the Workspace -> Layouts tree )
• Formula context menu (available when you click with RIGHT mouse button in
the Workspace -> Charts tree )
• Layers context menu (available when you click with RIGHT mouse button in
the Workspace -> Layers list )
• RealTime Quote context menu (available when you click with RIGHT mouse
button in the Real time quote list)
Menus
409
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
File menu
New
• Database
Creates a new AmiBroker database and launches Database settings window.
• Default Chart
Creates new chart window using default template. It’s possible to select
the symbols and time frame independently in each of the windows opened.
• Linked Chart
Creates linked chart window based on current template and active chart.
Linked windows use the same symbol selection, so if you change the selected
symbol for one of them, the other one will synchronize automatically.
Linked windows can have DIFFERENT viewing time frame selected. Simply
activate the window and select desired interval from View menu for one
window, then switch to the other one and select different interval for it.
This option allows you to select different time frame or indicators’ set in
each window and easily move through the database.
• Blank Chart
Creates new (blank) chart window. This is useful if you want to create
completely new setup of charts that do not share the same chart IDs. It is
important if you want to have indicators that have independent parameters
from the other windows that you have created.
• Blank Pane
Creates new (blank) chart pane
• Account
Creates New Account (Account Manager)
File menu
410
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
• Web Research
Creates New Web Research window
Open
Opens document (account, database or HTML file - you can pick document type from
"Files of type" combo in the File selector window)
Close
Closes current (active) document window (chart, account, web research)
Open Database
Allows you to open an existing AmiBroker database. Please select the database
folder and press OK.
Save Database
Saves the currently used database
Save Database As...
Saves database into new location
Save
Saves current document (account, html file)
Save As...
Saves current document (account, html file) under new name
Save All
Saves all documents currently open
Database Settings
Opens Database settings dialog that allows you to change your database parameters
or intraday settings.
Import Wizard
Launches ASCII Import Wizard window, that allows you to easily import ASCII
(text) files into your database
Import ASCII
Allows you to import ASCII files with use of predefined import formats. To learn
more how to use ASCII importer, please read ASCII Importer reference chapter.
Import MetaStock data
Launches Metastock importer window. IMPORTANT NOTE: Metastock importer should be
used ONLY if you want to import MS data to native, local AmiBroker database once.
If you want AmiBroker to just read Metastock database DIRECTLY without need to
import new data over and over please set up your database WITH METASTOCK PLUGIN
as described in the Tutorial.
Print
Allows you to print currently displayed charts.
File menu
411
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Print Preview
Prints currently displayed charts with the preview (you can check the appearance
of the document before it’s printed).
Print Setup
Opens printout setup dialog.
Send Chart via E-mail
AmiBroker creates .png image (with the currently displayed chart) and uses your
default mailing program (e.g. Outlook Express) to send the file as an
attachement.
Exit
Closes AmiBroker program.
File menu
412
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Edit menu
Undo
Allows to undo the last operation performed on chart studies (trendlines etc.).
This option will be unavailable if no study has been drawn or moved.
Cut, Copy, Paste, Delete
These options can be used to cut, copy, paste or delete studies from the chart.
Cut, copy and delete will be greyed out if no object on the chart is selected. To
paste the object, it’s necessary to use ’copy’ or ’cut’ option first.
To learn more about drawing tools in AmiBroker, please read Drawing tools
reference chapter.
Delete All
Deletes all the objects from the currently opened chart window.
Image
• Copy As Bitmap - copies the curently opened chart to the system clipboard
as a .BMP image. You can paste the clipboard contents e.g. into ’Paint’
application.
• Copy As Metafile - copies the curently opened chart to the system clipboard
as a metafile
• Export to file - saves the currently displayed chart as .PNG file
• Send by E-mail - AmiBroker creates .png image (with the currently displayed
chart) and uses your default mailing program (e.g. Outlook Express) to send
the file as an attachement.
Delete quotation
Deletes currently selected bar.
Delete Session
Deletes currently selected bar from ALL the symbols in the database.
Properties
Opens a study properties dialog. More information can be found in Drawing tools
Edit menu
413
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
reference chapter.
Edit menu
414
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
View menu
Crosshair
Turns on/off crosshair.
X-Y labels
Controls the display of X-Y value labels
• Off
• With crosshair only - display X-Y
value labels when crosshair is
activated
• Always on - always display X-Y value
labels
Price Chart Style
Changes the style of the default Price
chart
• Auto - uses settings defined in Tools
->Preferences
• Line - line chart
• CandleSticks - candlestick chart
• Bars - traditional bar chart
Intraday
Allows you to chose one of intraday time
intervals and decide whether to display day
or night sessions. Day and night sessions’
hours can be set in: Database settings
window (File -> Database Settings ->
Intraday settings) or separately for group
in Categories window (Symbol ->
Categories).
• Day / Night - shows two bars (day and
night) per day
• Show 24 hours trading - no filtering
is applied and all the data in the
database is included in the chart.
• Show day session only - displays day
sessions only.
• Show night session only - displays
night sessions only.
• Show day and night sessions displays day and night sessions.
Daily, Weekly, Monhly, Quarterly, Yearly
Allows to change the display time interval.
View menu
415
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Pad non-trading days
Enable padding of Saturdays, Sundays and
other non-trading days with previous close
price
Filtering
Allows to choose between no filtering (24
hours trading display), regular trading
only, extended trading only.
Zoom
Controls the zoom of the chart
• In - reduces number of bars displayed
• Out - increases number of bars
displayed
• All - displays all the available bars
for the current symbol
• Normal - displays default number of
bars (defined in Tools -> Preferences
-> Charting)
• Range - displays the bars from the
selected range
• Shorter bars - reduces the vertical
size of the bars
• Longer bars - increases the vertical
size of the bars
History
Allows to move Back/Forward in
’browser-like’ way.
• Previous move to previous symbol
(keyboard shortcut: Ctrl+Alt+LEFT)
• Next move to next symbol (keyboard
shortcut: Ctrl+Alt+RIGHT)
Pane
• Close - closes curently selected
chart pane
• Arrange All - arranges all the
displayed charts
• Move Down - moves curently selected
chart pane one position down
View menu
416
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
• Move Up - moves curently selected
chart pane one position up
• Maximize - maximizes curently
selected chart pane
• Restore - restores the charts layout
after using Maximize
Toolbars
Allows you to display/hide the toolbars.
Refresh
Refreshes the chart window.
Refresh All
Refreshes the chart window and re-reads the contents of all the categories in
symbols tree in Workspace window.
Note to users of previous versions: the items that control Symbol, Layouts,
Layers, Charts, Information and other windows have been moved to Window menu.
View menu
417
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Insert menu
Trend line
Draws a trend line.
To draw a trend line the chart - start drawing by pointing the mouse and pressing
left mouse button where you want to start the drawing. Then move the mouse and
study tracking line will appear. Release left mouse button when you want to
finish drawing. Alternatively you can click once in the place where you want the
trendline to begin, move the mouse and click once again to finish drawing. You
can also cancel study drawing by pressing ESC (escape) key.
Ray
Draws a ray. Ray is a right-extended trend line.
Extended line
Draws an extended line. Extended line is a trend line that is extended
automatically from both left- and right- sides.
Insert menu
418
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Horizontal line
Draws a horizontal line. Horizontal line is self expanding so it is only
necessary to click on the chosen price-level.
Vertical line
Draws a vertical line. Vertical line is self expanding so it is only necessary to
click on the chosen bar.
Parallel lines
Draws parallel trendlines.
This tool allows to draw a series of parallel trend line segments. First you draw
a trend line as usual, then a second line parallel to the first is automatically
created and you can move them around with the mouse. Once you click on the chart
it is placed in given position. Then another parallel line appears that can be
placed somewhere else. And again, and again. To stop this please either press ESC
key or choose "Select" tool.
Regression channel
Draws Raff, standard deviation, standard error channels. To read the detailed
information regarding this tool please read Drawing tools reference chapter.
Andrews’ pitchfork
Draws an Andrews’ pitchfork. Read Drawing tools reference chapter for more
detailed information.
Triangle
Draws a Triangle. Left-click in the first point, move to the second point then
click once, then move to the third point and click once again.
Rectangle
Draws a rectangle. Left-click in the first point, move to the position where you
want to place the oposioposite corner and click once again.
Ellipse
Draws an Ellipse. Ellipse is connected to the date/price coordinates (as trend
Insert menu
419
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
lines) rather than to the screen pixels so it can change the visual shape when
displayed at various zoom factors or screen sizes. To see the properties of
ellipse you should double-click on the clock-like 3, 6, 9 or 12 hour positions.
Arc
Draws an Arc. Arc, the same as Ellipse is connected to the date/price coordinates
(as trend lines) rather than to the screen pixels so it can change the visual
shape when displayed at various zoom factors or screen sizes. To see the
properties of ellipse you should double-click on the clock-like 3, 6, 9 or 12
hour positions.
Cycle
Draws time cycles. To use time cycles tool, click on the cycles drawing tool
button in the toolbar then click at the starting point of the cycle and drag to
the end of the cycle. These two control points control the interval between the
cycle lines. When you release the mouse button you will get a series of parallel
lines with equal interval in between them.
Text
Allows to place a custom text on the chart. Left-click on the chart to start
typing. To finish - click once again on the chart, outside the text box. You can
also cancel typing by pressing ESC (escape) key.
Zig-zag
Draws a series of connected trend lines. To finish the series double-click or
press ESC (escape) key.
Arrow
Draws a line that ends with an arrow. Drawing technique is exactly the same as
drawing a trend line.
Fibonacci
Group of Fibonacci drawing tools.
Read Drawing tools reference chapter
for more detailed information.
• Fibonacci Retracement study
Insert menu
420
AmiBroker 5.80 User’s Guide
•
•
•
•
•
AmiBroker Reference Guide
Fibonacci Time zones study
Fibonacci Fan
Fibonacci Arc
Fibonacci Extensions
Fibonacci Time Extension lines
Gann
Group of Gann drawing tools.
• Gann Fan
• Gann Square
Read Drawing tools reference chapter for more detailed information.
Insert menu
421
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Format menu
These options allow you to apply color or style to the objects. Note that you can
also select color and style of the object before drawing new object: simply
deselect previous object (if any), change style selections and draw new object.
Thick
Changes drawn object formatting to thick style.
Dotted
Changes study formatting to dotted style.
Left Extend
Extends the trendline to the left.
Right Extend
Extends the trendline to the right.
Snap to price
Turns on the magnet that snaps the drawn studies to the prices. Snap to price %
threshold can be set in Preferences window. Snap to price % threshold defines how
far price ’magnet’ works, it will snap to price when the mouse is nearer than %
threshold from H/L/C price
Format menu
422
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Symbol menu
New
Allows you to add new symbols into the database. After selecting this function
you will be prompted for new ticker symbol. Please try not to exceed 26 chars.
For proper import functioning you should enter the symbol with CAPITALS.
Delete
Removes currently selected symbol from the database. After choosing this function
you will be asked for confirmation of symbol removing. Note well that this
operation can not be undone.
Split
Allows you to perform stock split. AmiBroker provides easy way of handling stock
splits. Program will try to guess split date and ratio by analyzing quotations.
If there is just a single quotation after split this should work, if not you will
be asked for split date and ratio. You can specify a split using following
expression: x->y which means that x shares before split become y after it. For
example 2->3 means that 2 shares become 3 after the split. It is also possible to
perform reverse-split, for example 2->1, which means that 2 shares are joined
together into 1 share.
Merge
This function allows you to merge two tickers, when the ticker for the symbol is
changed and in your database - one symbol holds historical quotes and the second
one holds newest quotes (after name change). I You should just select the new
ticker (after name change) and use Symbol->Merge. Then from the combo you should
choose original ticker ("merge with") and optionally check the following fields:
Symbol menu
423
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
• overwrite duplicate quotes - checking this option will overwrite the quotes
already existing in "new" ticker with those present in "old" ticker (this
should really not be the case, but may happen).
• delete "merge with" afterwards - checking this option will delete the "old"
ticker after merging
• assign alias name - checking this option will copy the "old" ticker to the
alias field of the "new" ticker
Find
Opens Symbol finder window that allows you to quickly search the database for a
symbol by typing the first letters of its full name or ticker.
Information
Opens the Information window for the symbol, which allows you to change the
symbol properties.
Finances
Finances window allows you to enter some fundamental data for the symbol (sales
income, earnings before taxes (EBT), earnings after taxes (EAT) ). AmiBroker will
compute P/E (Price to Earnings ratio) and EPS (Earnings Per Share) indicators out
of the data given.
Quote Editor
Opens Quote Editor window that allows you to edit, delete and add quotations into
your database.
Watchlist
These options allow you to manage your watchlists. Working with watch lists
chapter explains in more detail the way you can use the below options.
• Add Selected Symbol - adds the currently selected symbol to the specified
watchlist(s).
• Remove Selected Symbol - removes the currently selected symbol from the
specified watchlist(s).
• Type-in Symbols - allows you to type-in the symbols to the watchlist(s).
• Import - allows to import the watchlist from the .TLS file
• Export - exports the symbols belonging to the watchlist to the .TLS (symbol
list) file
• Erase (make empty) - removes all the symbols from the specified watchlist.
• Sort alphabetically - sorts tickers alphabetically in the specified
watchlist
• Hide empty watchlists - hides watch lists with no symbols in the symbol
tree
• New watchlist - creates new watch list
• Delete watchlist - deletes selected watch list (it does not delete symbols
from teh database)
Categories
Categories window allows you to define names of markets, groups, sectors and
industries. For each market you can also define base indexes for calculating
relative strength, composite data, beta or web profile URL.
Symbol menu
424
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Organize assignments
Assignment organizer window allows you to easily change the category assignments
for the symbols or to delete multiple symbols from the database.
Calculate Composities
Opens Composite calculation window that allows for automatic calculation of
number and volume of advancing/declining/unchanged issues or volume numbers for
indices.
Symbol menu
425
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Analysis menu
Quick Review
Opens Quick review window that provides overall market information like: daily
symbol quotes, daily/weekly/monthly/quarterly/yearly returns comparison table or
Price/Earnings and Price/Book value comparison.
Automatic Analysis
Opens Automatic Analysis window that enables you to check your quotations against
defined buy/sell rules or explore your database. AmiBroker can produce report
telling you if buy/sell signals occurred on given symbol in the specified period
of time, simulate trading, giving you an idea about performance of your system or
optimize the trading system you use to improve it’s performance.
Commentary
Displays Commentary window which allows you to view textual descriptions of
actual technical situation on given market.
Formula Editor
Opens the Formula Editor window that enables you to write your own formulas.
AFL Code Wizard
Opens the AFL Code Wizard - the add-on program that creates trading system AFL
code from plain English sentences. See introduction video to AFL Code Wizard.
Analysis menu
426
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Tools menu
Database Purify
Database purify tool allows to detect missing/extra quotes, possible splits or
invalid OHLC relationship.
Indicator Maintenance
Opens Indicator Maintenance wizard, that helps to clean up unused indicator space
Bar Replay
Opens Bar Replay tool, which allows to replay historical data.
Preferences
Opens Preferences window which allows you to configure the program.
Save Preferences
Saves all the preferences changes (the information is store in broker.prefs
file).
Plugins
Opens Plugins window. It contains the lists of all loaded plug-in DLLs and can be
used for inspecting which plugins are active. It’s also possible to unload the
plugins.
Customize
Customize tools dialog allows you to define custom tools that can be invoked from
Tools menu.
Auto-update quotes
Auto-update quotes option updates historical quotes from the last date present in
AmiBroker upto today with use of AmiQuote Downloader. The detailed description on
how to use AmiQuote do obtain free quotations can be found in Automatic update of
EOD quotes tutorial chapter.
Sharenet Downloader
Launches the script which downloads the quotations from Sharenet (South Africa
only).
Tools menu
427
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Export to CSV file
Runs a script that exports the database to the CSV file. Note that you can use
Automatic Analysis window to export the quotes way faster than with use of this
script.
Cleanup database
Launches the script that allows you to find non-traded stocks in the database.
Script automatically scans the database and checks the latest quotation date. If
it is old enough, the script will display warning message and lets you decide
whether the stock should be deleted or not. Additionally script can generate a
list of "old" stocks and save it to the text file. The detailed information is
available in: 05-2000 issue of the newsletter.
Tools menu
428
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Window menu
IMPORTANT NOTE to old version users: Window -> New and Window -> New Linked
options have been moved to File->New->Default Chart and File->New->Linked Chart
menus.
Symbols tab - symbols tree with categories (See: Understanding categories).
Layouts tab - list of available global and local layouts (See: Working with chart
sheets and window layouts).
Layers tab - list of chart layers (See: Working with layers).
Charts tab - the window showing the list of chart formulas (See: Working with
drag-drop charting interface).
Interpretation
Displays/hides the Interpretation window.
Realtime Quote
Displays/hides the Realtime Quote window. The RT quote window provides real-time
streaming quotes and some basic fundamental data. To learn more read: How to use
AmiBroker in Real Time mode chapter.
Window menu
429
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Alert Output
Shows/hides Alert Output window. The window displays texts generated by formula
based alert. The detailed information on how to use alerts is available in: Using
formula-based alerts part of the Users’ Guide.
Notepad
Displays/hides Notepad window, that allows to store free-text notes about
particular security. Just type any text and it will be automatically saved / read
back as you browse through symbols. Notes are global and are saved in "Notes"
subfolder as ordinary text files.
Symbol Information
Shows symbol information window with fundamental data.
Time & Sales
Shows Time and Sales real time window
Log
Shows the log window that displays AFL error messages, run-time errors and _TRACE
output
Data window
Shows the data window that displays values of chart indicators
Risk/Yeld map
Displays Risk/Yeld map of all the symbols in the database. Risk/yield map
calculates average weekly return (the yield) and standard deviation of the weekly
returns (the risk) over at least 12 weeks. It requires at least 60 bars worth of
data for every stock. To zoom in - mark the area with the mouse. To zoom-out
simply click on the map.
Cascade
Cascades opened chart windows.
Tile Horizontaly
Tiles the opened chart windows horizontally.
Tile Vertically
Tiles the opened chart windows vartically.
Normal
Switches the chart window to "normal" (non-floating) state. More info here.
Floating
Switches the chart window to floating state. More info here.
Arange Icons
Allows you to arrange the minimized windows. Arrange icons works only if:
Window menu
430
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
• You created more than two windows (via Window->New or Window->New Linked)
• You have minimized them
• You moved the minimized boxes
Arrange icons option will align the windows nicely at the bottom of the AmiBroker
window.
Window menu
431
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Help menu
Help Contents
Displays the contents of the AmiBroker Users’ Guide.
Search
Allows you to search the Users’ Guide.
Tip of the day
Shows Tip of the day dialog where many useful usage tips are displayed.
AmiBroker on the web
•
•
•
•
•
•
link to AmiBroker Home page
list of benefits for registered users
secure On-line order form
AmiBroker Mailing List
On-line formula library
On-line AFL function reference
Readme
Displays the contents of Readme file. Please note that all the recent changes in
beta releases are reported in Readme.
About AmiBroker
Shows the ’About’ window, which contains the information about program version
and user details.
Help menu
432
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
AFL Editor menu
AFL editor features separate menu consisting of the following choices:
1. File
where
•
•
•
•
•
•
New - clears the formula editor window
Open - opens the formula file
Save - saves the formula under current name
Save As.. - saves the formula under new name
Print - prints the formula
Exit - closes the editor
AFL Editor menu
433
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
2. Edit
where
•
•
•
•
•
•
•
•
Undo - un-does recent action (multiple-level)
Redo - re-does recent action (multiple-level)
Cut - cuts the selection and copies to the clipboard
Copy - copies the selection to the clipboard
Paste - pastes current clipboard content in the current cursor position
Select All - selects entire text in the editor
Find... - provides access to text search tool
Copy Error Message - copies current error message displayed in the bottom
of the editor window to the clipboard (option is active only when there are
any errors displayed after syntax check)
3. Tools
where
• Verify syntax - checks current formula for errors
• Apply indicator - saves the formula and applies current formula as a
chart/indicator ONCE
• Insert chart - saves the formula and applies current formula as a chart
MANY TIMES (inserts multiple times)
AFL Editor menu
434
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
• Send to Auto-Analysis - saves the formula and selects it as current formula
in Automatic Analysis window
• Scan - saves the formula and performs Scan in Automatic Analysis window
• Exploration - saves the formula and performs Exploration in Automatic
Analysis window
• Backtest - saves the formula and performs Backtest in Automatic Analysis
window
• Optimization - saves the formula and performs Optimization in Automatic
Analysis window
• Check - saves the formula and performs Check (if given formula references
future) in Automatic Analysis window
• Options: Auto-save formula before running analysis - when checked, any
click on Scan/Explore/Backtest/Optimize button in Automatic Analysis window
triggers automatic save of current formula.
4. Help
where
• Function reference - displays reference page for currently highligted AFL
function, more on this feature here.
• Parameter info - displays parameter tooltip for currently highlighted AFL
function, more on this feature here.
• AFL Language reference - displays language reference page.
• Function index by Name - displays alphabetical list of AFL functions.
• Function index by Category - displays categorized list of AFL functions.
• Help on Editor - displays this help page.
as well as context menu (available via RIGHT click over the formula):
AFL Editor menu
435
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
which essentially duplicates choices available from regular menu.
AFL Editor menu
436
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Automatic Analysis result list context menu
This menu shows up when you click with RIGHT mouse button over Automatic Analysis
result list.
Available choices:
• Show arrows for all raw signals - show buy/sell/short/cover arrows for all
raw (unfiltered) signals. If your formula is for example
buy = C > MA( C, 10 );
you will get a buy (solid green) arrow for all bars where close was above
10-bar moving average
• Show arrows for actual trades - show arrows only on trade entry/exit bars.
This shows arrows for ALL TRADES. If your formula is for example
buy = C > MA( C, 10 );
you will get a buy (solid green) arrow only for the very first bar when
close crossed above moving average and trade was initiated, and you won’t
get any subsequent buy arrows until a matching sell (trade exit) occurs.
Note that trade arrows represent all possible trades taken. Given trade may
not be taken by backtester if there are insufficient funds to enter it.
• Show current trade arrows - show entry/exit arrows for selected trade only.
This displays the arrows for currently selected trade (from the result
Automatic Analysis result list context menu
437
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
list). It represents trade actually taken.
• Add all results to watch list - adds all symbols from the result list to
the watch list of your choice. More on this here
• Add selected results to watch list - adds symbols from selected rows to the
watch list of your choice. More on this here
• Replace watch list with all results - empties the watch list and then adds
all symbols from the result list to the watch list of your choice. More on
this here
• Replace watch list with selected results - empties the watch list and then
adds symbols from selected rows to the watch list of your choice. More on
this here
• Clear result list - removes all rows from the result list
• Copy - copies result list to the Windows clipboard, so you can paste it to
some other application, like Excel for example
IMPORTANT NOTES:
1. Buy arrow is solid green, Sell arrow is solid red, Short arrow is hollow red,
Cover arrow is hollow green
2. Arrows are shown only on the charts that have "Show arrows" property turned
ON.
Automatic Analysis result list context menu
438
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Chart context menu
This context menu shows up when you click with RIGHT mouse button over chart
pane.
Available options:
• Parameters... - brings up Parameters dialog allowing you to modify
parameters of indicators, as well as colors, styles, scaling and axes
settings
• Edit Formula... - brings up Formula Editor allowing you to view/modify the
AFL code of indicator
• Close - closes chart pane
• Intraday ... - allows you to switch viewing time frame to one of available
intraday intervals
• Daily view - switches viewing interval to daily
• Weekly view - switches viewing interval to weekly
• Monthly view - switches viewing interval to monthly
• Pane
♦ Close - closes chart pane
♦ Arrange all - arranges panes to equal height
♦ Move up - moves selected chart pane up (switches pane vertical order)
♦ Move down - moves selected chart pane down (switches pane vertical
order)
♦ Maximize - maximizes selected pane so it fills entire screen
♦ Restore - restores selected pane to previous size
• Template
♦ Load... - loads single window chart template from the selected file
(more on templates and layouts here)
♦ Save... - saves single window chart template to the selected file
♦ Load default - loads default single window template
♦ Save as default - saves current single window setup as default
template
• Delete indicator - deletes one of drag-and-drop indicator sections found in
the code
Chart context menu
439
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
• Delete study - deletes selected manually drawn study (like trend line,
Fibonacci, Gann...) - more on this here
• Delete All studies - deletes all manually drawn studies (like trend line,
Fibonacci, Gann...)
• Properties - displays properties (coordinates, colors, etc) of manually
drawn study (like trend line, Fibonacci, Gann...) more on this here and
here.
Chart context menu
440
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Layouts context menu
Layouts context menu shows up when you click with RIGHT mouse button over layout
in the Workspace window, Layouts tab.
Available choices:
•
•
•
•
Open - loads selected layout
Save - saves current window layout under current name
Save As... - save current window layout under new name
Save as default - save current window layout as default (startup) layout
for given database
• Delete - delete selected layout
To learn more about Layouts please check Tutorial: Chart sheets and layouts
Layouts context menu
441
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Formula (chart) context menu
Formula (chart) context menu shows up when you click
with RIGHT mouse button over formula listed in the
Charts tab of Workspace pane (see picture on the left)
Available choices:
• Insert - inserts selected indicator into new chart pane.
Insert command internally creates a copy of the original formula file and
places such copy into hidden drag-drop folder so original formula will not
be affected by subsequent editing or overlaying other indicators onto it.
Double clicking on formula name is equivalent with choosing Insert command
from the menu.
• Insert Linked - inserts selected indicator into new chart pane directly
(i.e. linked to original).
Insert Linked command does not create any copy of the formula. Instead it
creates new chart pane that directly links to original formula. This way
subsequent editing and/or overlaying other indicators will modify the
original
• Overlay - overlay selected indicator onto selected chart pane
•
•
•
•
•
Overlay command internally appends additional code to the formula used by
the chart pane. If given chart pane was created usign Insert Linked, it
will modify original (linked) formula.
Analysis - show up Automatic Analysis window and pick selected formula
Edit - open Formula Editor window to edit selected formula
Rename - rename currently selected formula file
Delete - delete currently selected formula file
New
♦ Formula - creates new formula file in currently selected folder
♦ Folder - creates new subfolder under currently selected folder
Formula (chart) context menu
442
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
• Refresh - re-reads Formula directory and re-display formula tree
Formula (chart) context menu
443
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Layers context menu
Layers context menu shows up when you click with RIGHT
mouse button over layer list in the Layers tab of
Workspace pane.
Available options:
• Add layer - adds new layer
• Remove layer - removes selected layer.
Please note that you can not remove first 5 (built-in) layers
•
•
•
•
Show All - shows all not locked layers
Hide All - hides all not locked layers
Toggle - toggles visibility of not locked layers
allows you to lock 5 first (built-in) layers. When layer is
Lock built-in layers -
•
locked its visibility changes automatically when interval changes and you can not
show/hide it manually.
allows you to unlock 5 first (built-in) layers. Once layer
Unlock built-in layers is unlocked its visibility does not change automatically when interval changes and you can
show/hide it manually.
• Properties this launches properties box that allows you to rename layer and decide if given layer
should or should not be locked to interval displayed. If you mark "Lock visibility to
interval" box the layer will show/hide automatically depending on what interval is
currently displayed. You can define visibility for each layer using "Interval" combo and
"Show/hide automatically" buttons. Note that there is a *separate* visibility setting for
EACH interval. The layer properties box ALWAYS shows "monthly" interval at start but this
is just a startup condition you just switch to particular interval
and modify visibility.
To setup locked layer completely you have to set visibility for
every layer listed in the "Interval" combo-box. Simply select the interval and choose if
layer should be shown or hidden for this interval, select next interval and again choose
show or hide, select next and so on...until you define visibility for all intervals.
More information about what layers are and how to use them is in the Tutorial:
Using Layers section of the guide.
Layers context menu
444
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Real-time quote context menu
Time & Sales
Opens Time & Sales window that provides information about every bid, ask and
trade streaming from the market.
Easy Alerts
Opens Easy Alerts window that provides way to define realtime alerts executed
when bid/ask/last and other fields hit user-defined levels
Add Symbol
Adds current symbol to Real-Time Quote list
Add watch list...
Adds entire watch list to real-time quote window
Type-in symbols
Allows to type the symbols directly as comma-separated list
Insert empty line
Adds empty (separator) line - useful for grouping symbols
Remove Symbol
Removes highlighted line (symbol) from the Real-Time Quote list.
Remove All
Removes all symbols from real-time quote list
Hide
Hides Real-Time Quote list
Layers context menu
445
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Keyboard shortcuts
AmiBroker allows complete customization of the user interface, including keyboard
shortcuts. To define your own shortcuts use Tools->Customize menu, Keyboard tab.
Read more about it in the Tutorial: User Interface Customization.
Pre-defined keyboard shortcut list follows below, please note that if you used
keyboard customization features the list here may not be valid because some of
the entries may have been changed to your own.
Keyboard shortcut
Command
CTRL+0
VIEW_HOURLY
CTRL+1
VIEW_1MINUTE
CTRL+5
VIEW_5MINUTE
CTRL+6
VIEW_15MINUTE
CTRL+C
EDIT_COPY
CTRL+D
VIEW_DAILY
CTRL+E
CHART_EDITFORMULA
CTRL+H
VIEW_CROSSHAIR
CTRL+I
CHART_MORE_INDICATORS
CTRL+M
VIEW_MONTHLY
CTRL+N
FILE_NEW
CTRL+O
FILE_OPEN
CTRL+P
FILE_PRINT
CTRL+R
CHART_PARAMETERS
CTRL+S
FILE_SAVE
CTRL+V
EDIT_PASTE
CTRL+ADD (CTRL+’+’)
VIEW_ZOOM_IN
ALT+BACK
EDIT_UNDO
DELETE
EDIT_CLEAR
ALT+DELETE
EDIT_CLEAR_ALL
SHIFT+DELETE
EDIT_CUT
END
CHART_SCROLL_END
F1
HELP
SHIFT+F1
CONTEXT_HELP
F12
CHART_RANGE_BEGIN
CTRL+F12
CHART_RANGE_HIDE
Keyboard shortcuts
446
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
SHIFT+F12
CHART_RANGE_END
F3
STOCK_FIND
F4
QUICK_FIND
F5
VIEW_REFRESH_CHARTS
F6
NEXT_PANE
SHIFT+F6
PREV_PANE
HOME
CHART_SCROLL_BEGIN
CTRL+INSERT
EDIT_COPY
SHIFT+INSERT
EDIT_PASTE
ALT+LEFT
SYMBOL_PREV
CTRL+ALT+LEFT
VIEW_GO_PREV
SHIFT+ALT+LEFT
SYMBOL_PREV_TREE
PAGE_DOWN
CHART_SCROLL_PAGE_RIGHT
CTRL+PAGE_DOWN
VIEW_SHEET_NEXT
PAGE_UP
CHART_SCROLL_PAGE_LEFT
CTRL+PAGE_UP
VIEW_SHEET_PREV
ALT+RETURN
CHART_STUDY_PROPERTIES
ALT+RIGHT
SYMBOL_NEXT
CTRL+ALT+RIGHT
VIEW_GO_NEXT
SHIFT+ALT+RIGHT
SYMBOL_NEXT_TREE
CTRL+SUBTRACT (CTRL+’-’)
VIEW_ZOOM_OUT
CTRL+W
VIEW_WEEKLY
CTRL+X
EDIT_CUT
CTRL+Z
EDIT_UNDO
Keyboard shortcuts
447
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Import ASCII
AmiBroker has easy-to-use and flexible quotation import feature. This document
describes advanced concepts of AmiBroker ASCII importer. Novice users should
start with ASCII Import Wizard.
How does it work?
Quotation data may come from various sources so the format of the ASCII (i.e.
text based) file may be much different from one source to another. To handle all
those differences AmiBroker uses format definition commands that define the way
the text information is interpreted by the ASCII importer. The format definition
commands are keywords that begin with a dollar sign ’$’. These commands may be
embedded in the data file itself or, may be stored in the separate format
definition file for multiple use. Storing format definition commands in separate
file avoids the need to include the commands in every data file. The default
format definition file name is "default.format". This file, all other ".format"
files and "import.types" file (described later) should be stored in \Formats
subdirectory of AmiBroker’s current working directory. The defaults are
overridden by any commands included (embedded) in the data file itself.
So, when you use the "Import from ASCII" menu, AmiBroker first looks for the
format definition stored in "default.format" file and then parses the file you
have chosen. If there is no "default.format" file then it uses internal defaults
(described below).
You can modify "default.format" file to suit your needs. Moreover using OLE
Automation (Win32 version) or ARexx (Amiga) interface you can specify the name of
the format definition file which will be used instead of "default.format" file.
Format definition commands
The command keywords begin with a dollar sign ’$’’. Every line starting with
command is interpreted in special way. Here is the list of commands recognized by
AmiBroker’s built-in importer. Bold letters mark keywords.
Command
$ADDRESS
Arguments <string>
Define company address
address of company
Alias
Examples
$ADDRESS "One Microsoft Way"
Command
$AUTOADD
Arguments <number>
Import ASCII
Switch new ticker add mode
0 - do not add , 1 - add a new
stock when non-existing ticker
448
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
detected (default = 0)
Alias
Examples
$AUTOADD 1
Command
$ALLOWNEG
Arguments <number>
Allow negative numbers in prices
0 - do not allow negative values
(default), 1 - allow negative
values in prices. This
additionally switches off any
checking for OHLC relationship
so you can import any data into
OHLC fields.
when $ALLOWNEG is NOT specified
in the ASCII importer definition
AmiBroker performs the following
range checking and fixup on
open, low and high prices
if( open == 0 ) open = close;
if( high < max( open, close ) )
high = max( open, close );
if( low == 0 ) low = min( open,
close )
Alias
Examples
$ALLOWNEG 1
Command
$ALLOW99SECONDSConvert invalid second stamp
Arguments <onoff>
This flag works ONLY in
conjunction with $TICKMODE 1
(see below for details)
$ALLOW99SECONDS set to 1 will
convert all records with
invalid seconds (i.e greater
than 59)to 59s. So record
stamped 16:29:70 will be
treated as 16:29:59
Alias
Examples
Import ASCII
$ALLOW99SECONDS 1
449
AmiBroker 5.80 User’s Guide
Command
$APPENDNAME append string to the ticker
name (useful when you need to
join several fields together to
make unique stock symbol)
Arguments <string>
Alias
AmiBroker Reference Guide
string to append to the ticker
symbol
$APPENDTICKER
Examples
Command
$BREAKONERR Define on-error behaviour
Arguments <number>
0 - to continue, 1 - to break
import on error (default=0)
Alias
Examples
$BREAKONERR 1
Command
$CONT
Arguments <number>
Define continuous quotations
flag
<0 or 1> - continuous quotations
flag, this affects $AUTOADD 1
mode - if this is set, newly
added stocks are switched to
continuous quotation mode (this
means enabling candlestick
charts for example)
Alias
Examples
$CONT 1
Command
$CURRENCY
Arguments <string>
Define symbol’s currency
Defines currency of symbol
Alias
Examples
$CURRENCY EUR
or
$FORMAT NAME, CURRENCY
$OVERWRITE 1
$AUTOADD 1
Import ASCII
450
AmiBroker 5.80 User’s Guide
Command
$DATE_DMY
Arguments <number>
AmiBroker Reference Guide
Define date
The date in Canadian format
(DD-MM-YY). If there is no
argument given the date is taken
from the file name (without an
extension)
Alias
$DATE_CDN
Examples
$DATE_DMY 12-05-99
$DATE_CDN 12-05-1999
Command
$DATE_MDY
Arguments <number>
Define date
The date in US format
(MM-DD-YY). If there is no
argument given the date is taken
from the file name (without an
extension)
Alias
$DATE_USA
Examples
$DATE_MDY 05/12/99
$DATE_USA 05/12/99
Command
$DATE_YMD
Arguments <number>
Define date
The date in International format
(YY-MM-DD). If there is no
argument given the date is taken
from the file name (without an
extension)
Alias
$DATE_INT
Examples
$DATE_INT 99-05-12
$DATE_CDN 1999.05.12
Command
$DEBUG
Arguments <number>
Switch logging (debug) mode
0 - no error logging, 1 - log
errors to "import.log" file
(default=0)
Alias
Examples
Import ASCII
$DEBUG 1
451
AmiBroker 5.80 User’s Guide
Command
$FORMAT
Arguments DATE_MDY
AmiBroker Reference Guide
Define line format
(sequence and types of
fields)
date in US format:
MM-DD-YY (alias:
DATE_USA)
DATE_DMY
date in Canadian
format: DD-MM-YY
(alias: DATE_CDN)
DATE_YMD
date in International
format: YY-MM-DD
(alias: DATE_INT)
TIME
time in HH:MM:SS or
HH:MM or HHMM or HHMMSS
format
NAME
ticker name (alias:
TICKER)
ALIAS
symbol alias ($AUTOADD
and $OVERWRITE modes
only)
FULLNAME
symbol full name
($AUTOADD and
$OVERWRITE modes only)
OPEN
open price
HIGH
high price
LOW
low price
CLOSE
close price
ADJCLOSE
split-adjusted close
This is provided to
read adj. close column
from Yahoo. Works only
in conjunction with
CLOSE field. When both
CLOSE and ADJCLOSE are
present in the ASCII
format definition then
importer calculates
split factor by
dividing
ADJCLOSE/CLOSE. It then
Import ASCII
452
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
multiples OPEN, HIGH,
LOW and CLOSE fields by
this factor and divides
VOLUME field by this
factor. This
effectively converts
unadjusted prices to
split adjusted prices.
Split ratio gets locked
once ADJCLOSE drops
below 0.05.
Import ASCII
OPENINT
open interest
VOLUME
volume
VOL1000
volume in thousands
shares
VOLMIL
volume in millions
shares
VOLFACTOR
volume factor (number
of shares in a block)
default =1
TURNOVER
turnover
AUX1
AUX1 field (auxilliary
data)
AUX2
AUX2 field (auxilliary
data)
SKIP
skip (ignore) field
MARKET
specify a field that
contains market ID
(affects $AUTOADD and
$OVERWRITE modes only)
GROUP
specify a field that
contains group ID
(affects $AUTOADD and
$OVERWRITE modes only)
WATCHLIST
specify a field that
contains watch list
number (0-31) (affects
$AUTOADD and $OVERWRITE
modes only)
INFO
specify a field with
additional information
(WSE specific: nk, ns,
rk, rs, ok, os, zd, bd
)
REDUCTION
specify a field with
reduction rate in
453
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
percents (WSE specific)
ICB
(new in 5.60)
specify ICB code
For example if your
file looks as follows:
(format is symbol, full
name, ICB code)
AAN,AARON’S INC,5375
Then to import it usign
AmiBroker’s import
wizard use the
following
$FORMAT
Ticker,FullName,ICB
$OVERWRITE 1$
$SEPARATOR ,
$CONT 1
$GROUP 255
$AUTOADD 1
$NOQUOTES 1
GICS
specify GICS code
For example if your
file looks as follows:
(format is symbol, full
name, gics sub industry
code)
AAN,AARON’S
INC,25504060
Then to import it usign
AmiBroker’s import
wizard use the
following
$FORMAT
Ticker,FullName,GICS
$OVERWRITE 1$
$SEPARATOR ,
$CONT 1
$GROUP 255
$AUTOADD 1
$NOQUOTES 1
INDUSTRY
specify a field that
contains industry ID
(affects $AUTOADD and
$OVERWRITE modes only)
INDUSTRYNAME
Import ASCII
454
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
(new in 5.60) specifies
a field that contains
Industry Name.
AmiBroker will check if
given industry name
already exists and if
not, it will create a
new Industry and assign
imported stock to the
industry specified.
Also if SECTORNAME is
specified, it will
assign newly added
industry to specified
sector.
(affects $AUTOADD and
$OVERWRITE modes only)
SECTORNAME
(new in 5.60) specifies
a field that contains
Sector Name. AmiBroker
will check if given
sector name already
exists and if not, it
will create a new
Sector. Also if
INDUSTRYNAME is
specified, it will
assign newly added
industry to specified
sector.
(affects $AUTOADD and
$OVERWRITE modes only)
Import ASCII
APPENDTICKER
specify a field that
contains string that
should be appended to
the ticker name (useful
when you need to join
several fields together
to make unique symbol
symbol)
MARGIN
future contract margin
deposit (positive value
= dollars, negative
value - percent of full
value)
POINTVALUE
future contract point
value
455
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
ROUNDLOTSIZE
round lot size (trading
unit size)
TICKSIZE
tick size
ADVISSUES
number of advancing
issues
ADVVOLUME
volume of advancing
issues
DECISSUES
number of declining
issues
DECVOLUME
volume of declining
issues
UNCISSUES
number of unchanged
issues
UNCVOLUME
volume of unchanged
issues
ADDRESS
street address of
company
CURRENCY
specifies currency of
symbol
DIV_PAY_DATE
fundamental data
EX_DIV_DATE
fields. For more info
LAST_SPLIT_DATE
read Using Fundamental
LAST_SPLIT_RATIO
Data
EPS
EPS_EST_CUR_YEAR
EPS_EST_NEXT_YEAR
EPS_EST_NEXT_QTR
FORWARD_EPS
PEG_RATIO
BOOK_VALUE (requires
SHARES_OUT to be
specified as well)
BOOK_VALUE_PER_SHARE
EBITDA
PRICE_TO_SALES
(requires CLOSE to be
specified as well)
PRICE_TO_EARNINGS
(requires CLOSE to be
specified as well)
PRICE_TO_BV (requires
CLOSE to be specified
as well)
FORWARD_PE (requires
CLOSE to be specified
as well)
REVENUE
Import ASCII
456
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
SHARES_SHORT
DIVIDEND
ONE_YEAR_TARGET
MARKET_CAP (requires
CLOSE to be specified
as well - it is used
to calculate shares
outstanding)
SHARES_FLOAT
SHARES_OUT
PROFIT_MARGIN
OPERATING_MARGIN
RETURN_ON_ASSETS
RETURN_ON_EQUITY
QTRLY_REVENUE_GROWTH
GROSS_PROFIT
QTRLY_EARNINGS_GROWTH
INSIDER_HOLD_PERCENT
INSTIT_HOLD_PERCENT
SHARES_SHORT_PREV
FORWARD_DIV
OPERATING_CASH_FLOW
FREE_CASH_FLOW
BETA
Alias
Examples
$FORMAT TICKER DATE_MDY OPEN HIGH LOW CLOSE
VOLUME
$FORMAT TICKER, DATE_INT, CLOSE, VOLUME
$FORMAT SKIP, TICKER, SKIP, SKIP, DATE_INT,
OPEN, HIGH, LOW, CLOSE, TURNOVER
Command
$FULLNAME
Arguments <string>
Define full symbol name
full symbol name
Alias
Examples
$FULLNAME Apple Computer Inc.
Command
$GICS
Arguments <number>
Define GICS code (Global
Industry Category System)
this affects $AUTOADD 1 and
$OVERWRITE 1 modes - if this is
specified symbols are assigned
to given GICS category
Alias
Import ASCII
457
AmiBroker 5.80 User’s Guide
Examples
AmiBroker Reference Guide
Now you can import GICS symbol-code
assignments using ASCII importer.
$FORMAT command now supports GICS code
and there is $GICS command for single-symbol
files.
For example if your file looks as follows:
(format is symbol, full name, gics sub
industry code)
AAN,AARON’S INC,25504060
Then to import it usign AmiBroker’s import
wizard use the following
$FORMAT Ticker,FullName,GICS
$OVERWRITE 1$
$SEPARATOR ,
$CONT 1
$GROUP 255
$AUTOADD 1
$NOQUOTES 1
Command
$GROUP
Arguments <number>
Define group ID
this affects $AUTOADD 1 mode if this is specified, newly
added symbols are assigned to
group with given number.
Alias
Examples
Command
$HYBRID
Arguments <number>
Switch hybrid mode on/off
0 (off) or 1 (on). When this
flag is set, you can combine
quotations from multiple files for example one file can contain
only open prices and volume and
the other file can contain
high/low/close data. Useful
especially for Warsaw Stock
Exchange for combining the data
from fixing and later continuous
quotations.
Alias
Examples
Import ASCII
458
AmiBroker 5.80 User’s Guide
Command
$INDUSTRY
Arguments <number>
AmiBroker Reference Guide
Define industry ID
this affects $AUTOADD 1 mode if this is specified, newly
added symbols are assigned to
industry with given number.
Alias
Examples
Command
$MARKET
Arguments <number>
Define market ID
this affects $AUTOADD 1 mode if this is specified, newly
added symbols are assigned to
market with given number.
Alias
Examples
Command
$NAME
Arguments <ticker>
Alias
$TICKER
Examples
$NAME AAPL
$TICKER MSFT
Command
$NOQUOTES
Arguments <number>
Alias
$TICKER
Examples
$NAME AAPL
$TICKER MSFT
Import ASCII
Define ticker name
ticker name (symbol) (default =
file name without path and
extension)
Switch quotation data mode
0 - (default) accept only
quotation data (AmiBroker checks
for non-zero prices and valid
dates)
1 - switch off quotation data
checking - this allows importing
non-quotation data - for example
only ticker and full names
459
AmiBroker 5.80 User’s Guide
Command
$OVERWRITE
Arguments <number>
AmiBroker Reference Guide
Switch overwrite mode on/off
0 - off, 1 - on. When overwrite
mode is on then information
provided by GROUP, MARKET,
INDUSTRY, FULLNAME fields is
overwritten for existing symbols
(not only for newly added)
Alias
Examples
$OVERWRITE 1
Command
$PRICEFACTOR Define price factor
Arguments <number>
the factor by which price data
are multiplied (default = 1)
Alias
Examples
$PRICEFACTOR 100
Command
$RAWCLOSE2OI Put Raw Close price to OI field
Arguments <number>
0 - off, 1- on. (off by
default) - causes that
OpenInterest field gets
assigned CLOSE (raw close)
field value multiplied by 100
Alias
Examples
$RAWCLOSE2OI 1
Command
$RECALCSPLITS Recalculate splits
Arguments <number>
Import ASCII
0 - off, 1- on. (off by
default) causes that splits
are recalculated by AmiBroker
by the algorithm that tries to
construct correct adjusted
price, based on inaccurate
information provided by Yahoo.
Note that Yahoo provides only
2 decimal digits in adj. close
field therefore the more adj.
close approaches zero due to
adjustements the error grows.
460
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
The option $RECALCSPLITS 1 is
intended to address this
problem (at least partially).
It works as follows:
1. for each bar ratio
ADJCLOSE/CLOSE is calculated
2. if the ratio changes in two
consecutive bars by more than
10% it means that
split happened that bar. True
split ratio is guessed by
matching true fraction
in the format of X/Y, where X
and Y = 1..9, to the change in
ratios.
3. Then true split ratio is
used to adjust all past bars
until new split is detected.
Works only in conjunction with
ADJCLOSE
Alias
Examples
$RECALCSPLITS 1
Command
$RECALCVOL
Arguments <number>
Switch automatic index volume
recalculation
0 - off, 1 - on (base index
only), 2 - on (all indexes).
When this is on AmiBroker
calculates volumes for indexes
based on assignments to markets
and base indexes defined in
Categories window
Alias
Examples
$RECALCVOL 2
Command
$RECALCAD
Arguments <number>
Import ASCII
Switch automatic advance/decline
composite recalculation
0 - off, 1 - on. When this is on
AmiBroker calculates numbers and
volumes of issues advancing,
declining and unchanged based on
assignments to markets and base
indexes defined in Categories
461
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
window.
Alias
Examples
$RECALCVOL 2
Command
$ROUNDADJ
Arguments <decimaldigits>
Round split adjusted prices
to given number of
decimaldigits
decimaldigits - causes
split-adjusted prices (see
above) to be rounded to
’decimaldigits’ precision. By
default no rounding is done
Works only in conjunction
with ADJCLOSE
Alias
Examples
$ROUNDADJ 2
Command
$SEPARATOR
Arguments <separator
char>
Define field separator character
the character used to separate
data fields (default = space)
Alias
Examples
$SEPARATOR ,
$SEPARATOR ;
Command
$SKIPLINES
Arguments <number>
Define how many lines to skip
(ignore)
number of lines to skip (default
= 0)
Alias
Examples
$SKIPLINES 1
Command
$STRICT
Import ASCII
Switches on/off strict checking
if Open, High, Low prices are
greater than zero
462
AmiBroker 5.80 User’s Guide
Arguments <onoff>
AmiBroker Reference Guide
(default = 0)
Alias
Examples
$STRICT 1
Command
$TICKMODESwitches on/off tick mode
$TICKMODE is a special mode of importer that allows to import quotes that havedu
It makes two assumptions:
a) input data should come in the ascending time order (i.e. OLDER records first, LA
b) input data should consist of entire tick history because importer will DELETE any
Once again: Turning on
$TICKMODE 1
will DELETE ANY QUOTES that already exist in the database and then will import a
You have been warned.
For example data files like this:
MOL,0,20050606,162959,16400.0000,16400.0000,16400.0000,16400.0000,2MOL,
Can be imported using the following definition file:
$FORMAT Ticker, Skip, Date_YMD, Time, Open, High, Low, Close, Volume
$SKIPLINES 1
$SEPARATOR ,
$CONT 1
$GROUP 255
$AUTOADD 1
$DEBUG 1
$TICKMODE 1
Sometimes it happens that input files have invalid timestamps (seconds > 59).
For example:
MOL,0,20050606,162970,16400.0000,16400.0000,16400.0000,16400.0000,2
Please take a closer look at first line shown in this example it has time:16:29:70 (yo
So I had to add a special flag to the importer that works around such data errors.
Import ASCII
463
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
It is called $ALLOW99SECONDS 1 and will convert all records with invalid seconds
So record stamped 16:29:70 will be treated as 16:29:59
Now for tick mode to work with such incorrect records you would need to add two lin
$TICKMODE 1
$ALLOW99SECONDS 1
Arguments <onoff>
(default = 0)
Alias
Examples
$TICKMODE 1
Command
$TIMESHIFT
Arguments <number>
Define intraday time shift used
during import
number of hours to shift
date/time stamps (can be
fractional)
Alias
Examples
$TIMESHIFT 2
; will shift 2 hours forward
$TIMESHIFT -11.5
; will shift 11 and half hour backward
Command
$VOLFACTOR
Arguments <number>
Define volume factor
the factor by which volume data
is multiplied (default = 1)
Alias
Examples
$VOLFACTOR 10
Command
$WATCHLIST
Arguments <number>
Define watch list number
this affects $AUTOADD 1 and
$OVERWRITE 1 modes - if this is
specified, newly added symbols
are added to the watch list with
given number.
Alias
Examples
Import ASCII
464
AmiBroker 5.80 User’s Guide
Command
AmiBroker Reference Guide
$CLEANSECTORS Clean (wipe) existing
sector/industry structure
Arguments <number>
if this is turned on (1),
existing sector/ industry
structure will be deleted and
initialized with Sector 0, 1,
2, 3...63/ Industry 0...255
This command should only be
used in conjunction with
SECTORNAME, INDUSTRYNAME
$FORMAT fields to allow
setting up fresh industry
structure
Alias
Examples
See example below (importing sector/industry
structure)
Command
$SORTSECTORS Sort sector/industry structure
Arguments <number>
if this is turned on (1),
sector/ industry structure will
be sorted alphabetically after
importing.
This command should only be
used in conjunction with
SECTORNAME, INDUSTRYNAME
$FORMAT fields to allow setting
up fresh industry structure
Alias
Examples
See example below (importing sector/industry
structure)
Notes:
• for DATE_xxx you can use -, / or \ as day/month/year separators. You
can even omit separators at all if only you give a date in a 6 digit
(YYMMDD, MMDDYY, DDMMYY) or 8 digit format (YYYYMMDD, MMDDYYYY, DDMMYYYY).
• AmiBroker recognizes decimal as well as true fractions in price data. True
fractions must follow the whole value after at least single space. For
example you can specify: 5.33 or 5 1/3
AmiBroker is not limited to any kind of fraction, if you wish you can write even:
5 333/999
Import ASCII
465
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Comments
You can include comments in both format definition file and the data file(s).
Each line starting with * (asterisk) or ; (semicolon) or # (hash) is treated as a
comment and ignored by the ASCII importer.
Usage examples
What may look complicated from command list will become quite clear after some
examples. So I will give you four examples of how to write format definition
files. First example will show the definition for CSV (comma separated values)
quotes available from Yahoo’s finances site. Second example will show definition
for Metastock ASCII file format. Third example shows definition for Omega
SuperCharts ASCII file format. And fourth example will show the definition for
s-files used by DM BOS (Polish brokerage company).
Yahoo CSV
The data from Yahoo’s site looks as follows:
Date,Open,High,Low,Close,Volume
1-Feb- 0,104,105,100,100.25,2839600
31-Jan- 0,101,103.875,94.50,103.75,6265000
28-Jan- 0,108.1875,110.875,100.625,101.625,3779900
The first line gives us a hint about the meaning of the comma separated fields.
First field will hold the date. The remaining fields will hold open, high, low,
close prices and volume. Importer should skip the first line and parse all the
remaining lines that hold just comma-separated data. Appropriate format
definition file would look like this:
$FORMAT Date_DMY,Open,High,Low,Close,Volume
$SKIPLINES 1
$SEPARATOR ,
$DEBUG 1
$AUTOADD 1
$BREAKONERR 1
$DEBUG switches on error logging to "import.log" file and $BREAKONERR will cause
importer to stop after the first error found. $AUTOADD ensures that new ticker
will be added to the database if it is missing. Well... you may ask: how does it
know the ticker name? The answer is simple: if there is no field which defines
the ticker name, the importer takes the file name (without path and extension) as
a ticker. So if you are importing file "C:\My data\AAPL.CSV" AmiBroker will use
"AAPL" as a ticker name.
Metastock ASCII
The data in Metastock ASCII format looks as follows:
<ticker>,<per>,<date>,<high>,<low>,<close>,<vol>
Comments
466
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
AAP,D,1/17/2000,5483.33,5332.01,5362.3,0
AKS,D,1/17/2000,9868.45,9638.03,9687.62,0
FET,D,1/17/2000,3741.3,3540.2,3570.81,0
First field will hold the ticker name, second - time period ("D" means daily
data), third - quotation date. The rest will hold high, low, close prices and
volume. The importer should then skip the first line and parse all the remaining
lines that hold just comma-separated data. Appropriate format definition file
would look like this:
$FORMAT Ticker,Skip,Date_MDY,High,Low,Close,Volume
$SKIPLINES 1
$SEPARATOR ,
$DEBUG 1
$AUTOADD 1
$BREAKONERR 1
Skip in $FORMAT defines a field which should be ignored by the importer.
Omega SuperCharts ASCII
The data in Omega SC ASCII format looks as follows:
ticker,date,open,high,low,close,vol
AAP,20000117,5333.01,5483.33,5332.01,5362.3,3433450
This format is similar to previous ones, however the date is in YYYYMMDD format
without separators between year, month and day part. AmiBroker, however, can
handle such dates with ease. Appropriate format definition file would look like
this:
$FORMAT Name,Date_Int,Open,High,Low,Close,Volume
$SEPARATOR ,
$DEBUG 1
$SKIPLINES 1
$AUTOADD 1
$BREAKONERR 1
Skip in $FORMAT defines a field which should be ignored by the importer.
DMBOS S-files
The data in this format looks as follows:
0,29-02-00,12:05,MIDWIG,1069.1,,,+1.2,336002000,
0,29-02-00,12:05,NIF,48.6,,,+0.8,1763000,
0,29-02-00,12:05,WIG20,2300.3,,,+1.1,336002000,
0,29-02-00,12:05,WIG,21536.8,,,+0.2,336002000,
0,29-02-00,12:05,WIRR,2732.8,,,+1.6,16373000,
1,29-02-00,12:05,AGORA,144.00,,,+4.7,15802000,
1,29-02-00,12:05,AGROS,40.00,nk,72,+5.0,840000,
1,29-02-00,12:05,AMERBANK,28.00,,,+3.7,22000,
Usage examples
467
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
1,29-02-00,12:05,AMICA,41.50,nk,99,+2.2,564000,
This format is a little bit more complicated. For us useful fields are: 2nd date, 4th - ticker, 5th - close price, 9th - the turnover value (close * volume).
The remaining fields holds other information that is not useful for us.
Appropriate format definition file would look like this:
$FORMAT Skip,Date_DMY,Skip,Name,Close,Skip,Skip,Skip,Turnover
$SEPARATOR ,
$DEBUG 1
Importing Sector/Industry structure
Let’s assume we have a text file with Stock tickers, Full names, Sector name and
industry name listed line by line, as follows:
"DDD","3D Systems Corporation","Technology","Computer Software: Prepackaged
Software"
"MMM","3M Company","Health Care","Medical/Dental Instruments"
"SVN","7 Days Group Holdings Limited","Consumer Services","Hotels/Resorts"
"AHC","A.H. Belo Corporation","Consumer Services","Newspapers/Magazines"
"AIR","AAR Corp.","Capital Goods","Aerospace"
"AAN","Aaron’s, Inc.","Technology","Diversified Commercial Services"
"ABB","ABB Ltd","Consumer Durables","Electrical Products"
To import such file we use the following format definition:
$FORMAT Ticker, FullName,SectorName,IndustryName
$SEPARATOR ,
$AUTOADD 1
$NOQUOTES 1
$OVERWRITE 1
$CLEANSECTORS 1
$SORTSECTORS 1
$NOQUOTES 1 tells the importer that we will be importing non-quotation data.
$AUTOADD 1/$OVERWRITE 1 is required to automatically add new symbols and
overwrite existing symbol information. $CLEANSECTORS 1 wipes existing
stock/industry structure prior to importing and $SORTSECTORS 1 - sorts
sectors/industries after importing so they will be listed in alphabetical order
in the Symbol window. $FORMAT command just specifies the order and types of field
to import
AmiBroker will read such ASCII file one-by one, then it will check whenever given
sector name/industry name already exists, if not - it will create new
sector/industry. Then it will assign given symbol to specified sector/industry.
The result will be a database with new sector/industry structure being set up and
symbols assigned to proper sectors and industries.
Described functionality is used to implement Tools->Update US symbol list and
categories tool.
Usage examples
468
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Default behaviour
When importing ASCII files, AmiBroker attempts to open "default.format" file (in
the AmiBroker’s directory) to obtain the format definition. If such file is
missing the following default format is applied:
$FORMAT DATE_USA, OPEN, HIGH, LOW, CLOSE, VOLUME
$SEPARATOR
This means that by default ASCII importer will use space character as a separator
and will parse the following fields: date, open, high, low, close, volume. The
file name (without path and extension) will be used as a ticker name. All other
import parameters ($DEBUG,$AUTOADD, etc.) are set to zero.
User-definable file types and formats
Now AmiBroker can use not only default.format definition file but also other
user-specified files. File types, filters and format definition files are
specified in import.types file (example is included in the update package). Now
user can prepare/modify import.types file with the description of supported ASCII
formats and filters to use. The format of import.types file is:
<Descriptive name>|<File filter>|<definition file name>
Note vertical line characters between these three fields. Example import.types
file looks as follows:
Default ASCII (*.*)|*.*|default.format
Yahoo’s CSV (*.csv)|*.csv|yahoo.format
Metastock ASCII (*.mst)|*.mst|metastock.format
Omega SC ASCII (*.txt)|*.txt|omega.format
S-Files (s*.*)|s*.*|sfile.format
C-Files (c*.*)|c*.*|cfile.format
Sharenet DAT (*.dat)|*.dat|dat.format
If such file exists you will see your types in the "Files of type" combo-box and
when you select one - appropriate filter will be used and after selecting some
files and clicking OK - importer will use specified ".format" file.
In that way you can define as many text-based data formats as you like and
AmiBroker will be able to "understand" them all.
Ticker aliases
Now each ticker can have an alias assigned, so the AmiBroker’s built-in importers
can recognize that security by both ticker symbol and alias names. This is useful
when you are using two data sources that are using slightly different symbol
naming convention or if you want to give the symbols more intuitive name while
retaining the ability to use importers without problems.
Default behaviour
469
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
GICS categorisation
GICS is global industry classification standard, see
http://en.wikipedia.org/wiki/Global_Industry_Classification_Standard
for more details on GICS system.
GICS codes are from 2 to 8 digits. Such as 10 for energy sector or 351010 for
"Health Care Equipment & supplies" industry.
The codes are fixed even if new classifications are added at some point in the
future. It is important to understand that these codes work in hierarchical way.
NOTE: current databases DO NOT have GICS codes assigned to symbols.
As far as I know PremiumData http://www.premiumdata.net/ is planning to release
AmiBroker-compatible database with GICS support.
AmiBroker now reads GICS.txt file from its installation folder. It contains GICS
categories listed one by one in order of GICS code in the following format
GICS;Name;Description<CRLF>
GICS is numeric code from 2 digits upto 8 digits
Name is GICS category name
Description is GICS category description
These fields must be separated by semicolon
< CRLF> means carriage return/line feed characters (means "new line" - just press
ENTER/RETURN key if you are editing with text editor)
There must be only one category per line in GICS.txt file
The default GICS.txt file is supplied already.
ICB categorisation
ICB stands for Industry Classification Benchmark
(http://en.wikipedia.org/wiki/Industry_Classification_Benchmark).
AmiBroker allows also ICB 4-level classification system, but demo database does
not have symbols classified according to that standard. You can find ICB
classification codes in ICB.txt file inside AmiBroker folder.
NOTE: current databases DO NOT have ICB codes assigned to symbols.
ICB classification for NYSE stocks can be imported from
http://www.nyse.com/indexes/nyaindex.csv
AmiBroker now reads ICB.txt file from its installation folder. It contains ICB
categories listed one by one in order of ICB code in the following format
ICB;Name<CRLF>
ICB is numeric 4 digit code.
Name is ICB category name
GICS categorisation
470
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
These fields must be separated by semicolon
< CRLF> means carriage return/line feed characters (means "new line" - just press
ENTER/RETURN key if you are editing with text editor)
There must be only one category per line in ICB.txt file
The default ICB.txt file is supplied already.
GICS categorisation
471
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
AmiBroker’s OLE Automation Object Model
Important note about OLE automation:
OLE automation interface is provided to control AmiBroker from the OUTSIDE
process (such as windows scripting host). While it is possible to access
Broker.Application and underlying objects from AFL formulas you should be very
careful NOT to touch any user interface objects (Documents, Document, Windows,
Window , Analysis object) from AFL formula because doing so, you will be likely
"Sawing Off the Branch You’re Sitting On". Especially things like switching chart
tabs from currently running chart formula are totally forbidden. Changing user
interface objects via OLE from AFL that is currently running within those user
interface parts is recipe for disaster. You have been warned.
AmiBroker object model hierarchy. V5.50
Index of objects
•
•
•
•
•
•
•
ADQuotation
ADQuotations
(1)
Analysis
AnalysisDoc
AnalysisDocs
Application
Window
•
•
•
(2)
•
(2)
•
Windows •
Commentary
•
Document •
Documents •
Market
•
Markets
Quotation
Quotations
Stock
Stocks
(1)
- Analysis object is obsolete as of 5.50. It is left here for backward
compatibility and accesses Old Automatic Analysis window only
(2)
- AnalysisDoc object and AnalysisDocs collection are new objects introduced in
AmiBroker’s OLE Automation Object Model
472
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
v5.50 and allow to control New Analysis window
ADQuotation
Properties:
♦ Date As Date
♦ AdvIssues As Long
♦ AdvVolume As Single
♦ DecIssues As Long
♦ DecVolume As Single
♦ UncIssues As Long
♦ UncVolume As Single
Description:
ADQuotation class keeps one bar of advance/decline information
ADQuotations
Methods:
♦ Function Add(ByVal Date As Variant) As Object
♦ Function Remove(ByVal Date As Variant) As Boolean
Properties:
♦ Item(ByVal Date As Variant) As Object [r/o] [default]
♦ Count As Long
Description:
ADQuotations is a collection of ADQuotation objects
Analysis
This object is obsolete. It is provided only to maintain
compatibility with old code. Analysis object always accesses OLD
Automatic Analysis.
Properties:
♦ Property Filter(ByVal nType As Integer, ByVal pszCategory As
String) As Long [r/w]
Methods:
♦
♦
♦
♦
♦
ADQuotation
Sub Backtest([ByVal Type As Variant])
Sub ClearFilters()
Sub Edit([ByVal bForceReload As Variant])
Sub Explore()
Function Export(ByVal pszFileName As String) As Boolean
473
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
♦ Function LoadFormula(ByVal FileName As String) As Boolean
♦ Function LoadSettings(ByVal pszFileName As String) As Boolean
♦ Sub MoveWindow(ByVal Left As Long, ByVal Top As Long, ByVal
Width As Long, ByVal Height As Long)
♦ Sub Optimize([ByVal Type As Variant])
♦ Function Report(ByVal pszFileName As String) As Boolean
♦ Function SaveFormula(ByVal pszFileName As String) As Boolean
♦ Function SaveSettings(ByVal pszFileName As String) As Boolean
♦ Sub Scan()
♦ Sub ShowWindow(ByVal nShowCmd As Long)
♦ Sub SortByColumn(ByVal iColumn As Long, ByVal bAscending As
Integer, ByVal bMultiMode As Integer)
Properties:
♦ RangeMode As Long
♦ RangeN As Long
♦ RangeFromDate As Date
♦ RangeToDate As Date
♦ ApplyTo As Long
Description:
Analysis object provides programmatic control of automatic analysis
window
Notes:
Analysis.Backtest( Type = 2 ); - runs backtest
Type parameter can be one of the following values:
0 : portfolio backtest/optimize
1 : individual backtest/optimize
2 : old backtest/optimize
IT IS IMPORTANT TO NOTE THAT FOR BACKWARD COMPATIBILITY REASONS THE
DEFAULT BACKTESTER MODE
IS "OLD" BACKTEST. THEREFORE YOU MUST SPECIFY TYPE = 0 IF YOU WANT TO
GET PORTFOLIO BACKTEST.
Analysis.Optimize(Type = 2 ); - runs optimization
Type parameter can be one of the following values:
0 : portfolio backtest/optimize
1 : individual backtest/optimize
2 : old backtest/optimize
3 : walk-forward test (AmiBroker version 5.11.0 or higher)
Analysis.Report( FileName: String ) - saves report to the file or
displays it if FileName = ""
Analysis.ApplyTo - defines apply to mode: 0 - all stocks, 1 - current
stock, 2 - use filter
Analysis.RangeMode - defines range mode: 0 - all quotes, 1 - n last
quotes, 2 - n last days, 3 - from-to date
Analysis.RangeN - defines N (number of bars/days to backtest)
Analysis
474
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Analysis.RangeFromDate - defines "From" date
Analysis.RangeToDate - defines "To" date
Analysis.Filter( nType: short, Category : String ) - sets/retrieves
filter setting
nType argument defines type of filter 0 - include, 1 - exclude
Category argument defines filter category:
"index", "favorite", "market", "group", "sector", "index",
"watchlist"
AnalysisDoc
AnalysisDoc is a new object introduced in version 5.50. It allows to
access New Analysis project documents (apx extension) and perform
multithreaded scans/explorations/backtests/optimizations in New
Analysis window in asynchronous way. Asynchronous means that Run()
method only starts the process and returns immediatelly. To wait for
completion you must check IsBusy flag periodically (such as every
second) in your own code.
Properties:
♦ Property IsBusy As Boolean [r]
Methods:
♦ Sub Close()
♦ Function Export(ByVal pszFileName As String) As Long
♦ Function Run(ByVal Action As Long) As Long
Description:
AnalysisDoc object provides programmatic control of New Analysis
document/window.
IsBusy property allows to check whenever Analysis window is busy
doing analysis. You must check this flag periodically if you want to
wait for completion. Take care NOT to call this too often as it will
decrease performance. For best results check it every one second.
Also you need to check this flag if you are not sure whenever
Analysis window is busy before trying to call Export() or Run(),
otherwise these calls would fail if analysis is in progress.
Close( ) method closes Analysis document/window. If there is any
operation in progress it will be terminated. To prevent premature
termination, check IsBusy property.
Export( pszFileName ) method allows to export analysis result list to
either .HTML or .CSV file. Returns 1 on success (successfull export)
or 0 on failure (for example if analysis window is busy)
Run( Action ) method allows to run asynchronously
scan/explorations/backtest/optimizations.
Action parameter can be one of the following values:
AnalysisDoc
475
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
0 : Scan
1 : Exploration
2 : Portfolio Backtest
3 : Individual Backtest
4 : Portfolio Optimization
5 : Individual Optimization (supported starting from v5.69)
6 : Walk Forward Test
It is important to understand that Run method just starts the process
and returns immediatelly. It does NOT wait for completion.
To wait for completion you need to query IsBusy flag periodically
(such as every one second).
Run() returns 1 on success (successfully starting process) or 0 on
failure (for example if analysis window is busy)
The procedure to run automated backtest involves opening previously
saved Analysis project (it includes all settings that are necessary
to perform any action), call Run() and wait for completion.
Since currently you can have multiple analysis projects running,
there is an AnalysisDocs collection that represents all open Analysis
documents and allow you to open previously saved files (that contain
formula, settings and everything needed to run).
New AnalysisDoc object does not allow you to read/write settings for
the purpose - you are not supposed to manipulate UI while new
Analysis window is running. Correct way of using New Analysis window
is to open existing project file and run. If you want to modify the
settings, you should write/modify existing project file. The analysis
project file (.apx extension) is human-readable self-explanatory
XML-format file that can be written/edited/modified from any language
/ any text editor.
The following JScript example
a) opens analysis project from C:\Analysis1.apx file
b) starts backtest (asynchronously)
c) waits for completion
d) exports results
e) closes analysis document
AB = new ActiveXObject( "Broker.Application" ); // creates AmiBroker
object
try
{
NewA = AB.AnalysisDocs.Open( "C:\\analysis1.apx" ); // opens
previously saved analysis project file
// NewA represents the instance of New Analysis document/window
if ( NewA )
{
AnalysisDoc
476
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
NewA.Run( 2 ); // start backtest asynchronously
while ( NewA.IsBusy ) WScript.Sleep( 500 ); // check IsBusy
every 0.5 second
NewA.Export( "test.html" ); // export result list to HTML
file
WScript.echo( "Completed" );
NewA.Close(); // close new Analysis
}
}
catch ( err )
{
WScript.echo( "Exception: " + err.message ); // display error
that may occur
}
AnalysisDocs
AnalysisDocs is a new object introduced in version 5.50. It is a
collection of AnalysisDoc objects. Allows to Add new Analysis, Open
existing analysis project, and iterate thru analysis objects.
Methods:
♦ Function Add() As Object
♦ Sub Close()
♦ Function Open(ByVal FileName As String) As Object
Properties:
♦
♦
♦
♦
Item(ByVal Index As Long) As Object [r/o] [default]
Count As Long
Application As Object
Parent As Object
Description:
AnalysisDocs is a collection of AnalysisDoc objects.
Add method creates new Analysis document/window. The method returns
AnalysisDoc object.
Close method closes all open Analysis documents/windows. If any
analysis project is running it will be terminated immediatelly
Open method allows to open existing Analysis project file (.apx). The
method returns AnalysisDoc object.
Item property allows to access Index-th element of collection. The
AnalysisDocs
477
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
property returns AnalysisDoc object.
Count property gives number of open analysis documents.
Both Application and Parent properties point to Broker.Application
object
For example usage, see AnalysisDoc object description.
Application
Methods:
♦ Function Import(ByVal Type As Integer, ByVal FileName As
String, [ByVal DefFileName As Variant]) As Long
♦ Function LoadDatabase(ByVal Path As String) As Boolean
♦ Function LoadLayout(ByVal pszFileName As String) As Boolean
♦ Function Log(ByVal Action As Integer) As Long
♦ Sub Quit()
♦ Sub RefreshAll()
♦ Sub SaveDatabase()
♦ Function SaveLayout(ByVal pszFileName As String) As Boolean
Properties:
♦ ActiveDocument As Object
♦ Stocks As Object
♦ Version As String
♦ Documents As Object
♦ Markets As Object
♦ DatabasePath As String
♦ Analysis As Object
♦ Commentary As Object
♦ ActiveWindow As Object
♦ Visible As Integer
Description:
Application object is main OLE automation object for AmiBroker. You
have to create it prior to accesing any other objects. To create
Application object use the following code:
JScript:
AB = new ActiveXObject("Broker.Application");
VB/VBScript:
AB = CreateObject("Broker.Application")
AFL:
AB = CreateObject("Broker.Application");
Application
478
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Window
Methods:
♦ Sub Activate()
♦ Sub Close()
♦ Function ExportImage(ByVal FileName As String, [ByVal Width As
Variant], [ByVal Height As Variant], [ByVal Depth As Variant])
As Boolean
♦ Function LoadTemplate(ByVal lpszFileName As String) As Boolean
♦ Function SaveTemplate(ByVal lpszFileName As String) As Boolean
♦ Function ZoomToRange(ByVal From As Variant, ByVal To As
Variant) As Boolean
Properties:
♦ SelectedTab As Long
♦ Document As Object
Description:
Window object provides programmatic control over charting window.
Windows
Methods:
♦ Function Add() As Object
Properties:
♦ Item(ByVal Index As Long) As Object [r/o] [default]
♦ Count As Long
Description:
Windows is a collection of Window objects.
Commentary
Methods:
♦ Sub Apply()
♦ Sub Close()
♦ Function LoadFormula(ByVal pszFileName As String) As Boolean
♦ Function Save(ByVal pszFileName As String) As Boolean
♦ Function SaveFormula(ByVal pszFileName As String) As Boolean
Description:
Commentary object gives programmatic control over guru commentary
window.
Window
479
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Document
Methods:
♦ Sub Activate()
♦ Sub Close()
♦ Sub ShowMessage(ByVal Text As String)
Properties:
♦ Application As Object
♦ Parent As Object
♦ Name As String
♦ ActiveWindow As Object
♦ Windows As Object
Description:
Document object represents active document (of ’chart’ type). In
document-view architecture each document can have multiple windows
(views) connected. Name property defines currently selected symbol
for the document.
Documents
Methods:
♦ Function Add() As Object
♦ Sub Close()
♦ Function Open(ByVal Ticker As String) As Object
Properties:
♦
♦
♦
♦
Item(ByVal Index As Long) As Object [r/o] [default]
Count As Long
Application As Object
Parent As Object
Description:
Documents is a collection of document objects.
Market
Properties:
♦ Name As String
♦ ADQuotations As Object
Description:
Market represents market category and its related data (i.e.
per-market advance/decline information)
Document
480
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Markets
Properties:
♦ Item(ByVal Index As Integer) As Object [r/o] [default]
♦ Count As Integer
Description:
Markets is a collection of Market objects
Quotation
Properties:
♦ Date As Date
♦ Close As Single
♦ Open As Single
♦ High As Single
♦ Low As Single
♦ Volume As Single
♦ OpenInt As Single
Description:
Quotation class represents one bar of price data
Quotations
Methods:
♦ Function Add(ByVal Date As Date) As Object
♦ Function Remove(ByVal Item As Variant) As Boolean
♦ Function Retrieve(ByVal Count As Long, ByRef Date As Variant,
ByRef Open As Variant, ByRef High As Variant, ByRef Low As
Variant, ByRef Close As Variant, ByRef Volume As Variant, ByRef
OpenInt As Variant) As Long
Properties:
♦ Item(ByVal Item As Variant) As Object [r/o] [default]
♦ Count As Long
Description:
Quotations is a collection of Quotation objects. It represents all
quotations available for given symbol. Quotations collection is
available as a property of Stock object.
Stock
Properties:
♦ Ticker As String
♦ Quotations As Object
Markets
481
AmiBroker 5.80 User’s Guide
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
Markets
AmiBroker Reference Guide
FullName As String
Index As Boolean
Favourite As Boolean
Continuous As Boolean
MarketID As Long
GroupID As Long
Beta As Single
SharesOut As Single
BookValuePerShare As Single
SharesFloat As Single
Address As String
WebID As String
Alias As String
IsDirty As Boolean
IndustryID As Long
WatchListBits As Long
DataSource As Long
DataLocalMode As Long
PointValue As Single
MarginDeposit As Single
RoundLotSize As Single
TickSize As Single
WatchListBits2 As Long
Currency As String
LastSplitFactor As String
LastSplitDate As Date
DividendPerShare As Single
DividendPayDate As Date
ExDividendDate As Date
PEGRatio As Single
ProfitMargin As Single
OperatingMargin As Single
OneYearTargetPrice As Single
ReturnOnAssets As Single
ReturnOnEquity As Single
QtrlyRevenueGrowth As Single
GrossProfitPerShare As Single
SalesPerShare As Single
EBITDAPerShare As Single
QtrlyEarningsGrowth As Single
InsiderHoldPercent As Single
InstitutionHoldPercent As Single
SharesShort As Single
SharesShortPrevMonth As Single
ForwardDividendPerShare As Single
ForwardEPS As Single
EPS As Single
EPSEstCurrentYear As Single
EPSEstNextYear As Single
EPSEstNextQuarter As Single
OperatingCashFlow As Single
LeveredFreeCashFlow As Single
482
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
Description:
Stock class represents single symbol data. For historical reasons the
name of the object is Stock, but it can hold any kind of instrument
(including futures, forex, etc).
Stocks
Methods:
♦ Function Add(ByVal Ticker As String) As Object
♦ Function GetTickerList(ByVal nType As Long) As String
♦ Function Remove(ByVal Item As Variant) As Boolean
Properties:
♦ Item(ByVal Item As Variant) As Object [r/o] [default]
♦ Count As Long
Description:
Stocks is a collection of Stock objects. It is available as a
property of Application object.
Notes:
Stock.WatchListBits (long) - each bit 0..31 represents assignment to
one of 32 watch lists to add a stock to nth watch list write (JScript
example):
Stock.WatchListBits |= 1 << nth;
Stock.WatchListBits2 (long) - each bit 0..31 represents assignment to
one of watch lists numbered from 32..63 to add a stock to nth watch
list write (JScript example):
Stock.WatchListBits2 |= 1 << ( nth - 32 );
Stock.DataSource ( 0 - default, 1 - local only )
Stock.DataLocalMode ( 0 - default, 1 - store locally, 2 - don’t store
locally)
Practical Examples:
Example 1: Running simple backtest
AB = new ActiveXObject( "Broker.Application" ); // creates AmiBroker object
try
{
NewA = AB.AnalysisDocs.Open( "C:\\analysis1.apx" ); // opens previously saved
analysis project file
// NewA represents the instance of New Analysis document/window
if ( NewA )
Stock
483
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
{
NewA.Run( 2 ); // start backtest asynchronously
while ( NewA.IsBusy ) WScript.Sleep( 500 ); // check IsBusy every 0.5
second
NewA.Export( "test.html" ); // export result list to HTML file
WScript.echo( "Completed" );
NewA.Close(); // close new Analysis
}
}
catch ( err )
{
WScript.echo( "Exception: " + err.message ); // display error that may occur
}
Example 2: Execute commentary
AB = new ActiveXObject("Broker.Application");
AB.Commentary.LoadFormula("C:\\Program Files\\AmiBroker\\AFL\\MACD_c.afl");
AB.Commentary.Apply();
AB.Commentary.Save("Test.txt");
AB.Commentary.SaveFormula("MACDTest.afl");
//AB.Commentary.Close();
Stock
484
AmiBroker 5.80 User’s Guide
AmiBroker Reference Guide
AmiQuote’s OLE Automation Object Model
Index of objects
• Document
AmiQuote is SDI (single document) application therefore there is only one class Document - creatable using the following code:
JScript:
AB = new ActiveXObject("AmiQuote.Document");
VB/VBScript:
AB = CreateObject("AmiQuote.Document")
AFL:
AB = CreateObject("AmiQuote.Document");
Document
Methods:
♦
♦
♦
♦
♦
Function AddSymbols(ByVal pszSymbols As String) As Boolean
Function Download() As Boolean
Function GetSymbolsFromAmiBroker() As Boolean
Function Import() As Boolean
Sub MoveWindow(ByVal x As Long, ByVal y As Long, ByVal width As
Long, ByVal height As Long)
♦ Function Open(ByVal pszFileName As String) As Boolean
♦ Function RemoveAllSymbols() As Boolean
♦ Function RemoveSymbols(ByVal pszSymbols As String) As Boolean
♦ Function Save() As Boolean
♦ Function SaveAs(ByVal pszFileName As String) As Boolean
Properties:
♦
♦
♦
♦
♦
♦
♦
♦
♦
♦
DownloadInProgress As Boolean
ImportInProgress As Boolean
Source As Long
From As Date
To As Date
AutoImport As Boolean
AllSessions As Boolean
Interval As Long
RunEvery As Long
DestinationFolder As String
AmiQuote’s OLE Automation Object Model
485
AmiBroker 5.80 User’s Guide
AmiQuote’s OLE Automation Object Model
AmiBroker Reference Guide
486
Technical analysis guide
Introduction
Basic tools
Indicators
Introduction
Technical analysis is the examination of past price movements to forecast future
price movements. Technical analysts are sometimes referred to as chartists
because they rely almost exclusively on charts for their analysis.
Technical analysis is applicable to stocks, indices, commodities, futures,
currencies or any tradable instrument where the price is influenced by the forces
of supply and demand. Price refers to any combination of the open, high, low or
close for a given security over a specific timeframe. The time frame can be based
on intraday, daily, weekly or monthly price data and last a few hours or many
years. In addition, some technical analysts include volume or open interest
figures with their study of price action.
AmiBroker provides a comprehensive set of technical analysis tools that will be
presented in this chapter.
Technical analysis guide
487
AmiBroker 5.80 User’s Guide
Technical analysis guide
Basic tools
AmiBroker has following basic technical analysis tools:
•
•
•
•
•
•
•
Price charts
Trend lines
Moving averages
Fibonacci retracement
Fibonacci time zones
Regression channels
Bollinger bands
Basic tools
488
AmiBroker 5.80 User’s Guide
Technical analysis guide
Price charts
AmiBroker can display the prices using:
• line chart
this mode is used when current symbol uses price fixing and only close
price is available
• traditional bar chart
this mode is used when continuous trading is enabled, but open price is not
available (or equals to close price)
• Japanese Candlesticks
this mode is used when continuous trading is enabled with
open/close/high/low data
A line chart is the simplest type of chart. One price (close) is plotted for each
time period. A single line connects each of these price points. The main strength
of this chart type is simplicity.
Bar charts are one of the most popular types of charts used in technical
analysis. For each trading day a vertical line is plotted. The top of the
vertical line indicates the highest price a security traded at during the day,
and the bottom represents the lowest price. The closing price is displayed by the
mark on the right side of the bar and opening prices are shown on the left side
of the bar.
Developed by the Japanese in the 1600’s, candlestick charts are merely bar charts
that extenuate the relationship between open, high, low and closing prices. Each
candlestick represents one period of data (day-week) and consists of an upper
shadow, lower shadow and the body. The upper shadow is the highest price that the
stock traded at for the period while the lower shadow represents the lowest
price. The candlestick body is black when the close is less than the open or
white when the close is greater than the open. The top of the body is the opening
price if the candle is black and the candle is referred to as a long black
candle. If the candle is white, the top of the body is the closing price and the
candle is referred to as a long white candle.
Steven Nison’s articles that explain Candlestick charting appeared in the
December, 1989 and April, 1990 issues of Futures Magazine. The definitive book on
the subject is Japanese Candlestick Charting Techniques also by Steve Nison.
There are many different candlestick formations. Some are considered to be minor
formations while others are major. Candlestick charts dramatically illustrate
supply/demand concepts defined by classical technical analysis theories.
Major Candlestick Chart Formations:
Gravestone Doji: A doji (open and close are the same) and the high is
significantly higher than the open, high and closing prices. This formation
typically occurs at the bottom of a trend and signals a bullish reversal.
Dragon-fly Doji: A doji (open and close are the same) and the low is
Price charts
489
AmiBroker 5.80 User’s Guide
Technical analysis guide
significantly lower than the open, high and closing prices. This formation
typically occurs at the top of a trend and signals a bearish reversal.
Abandoned Baby Doji: A doji, which occurs at the bottom of a chart formation with
gaps on both sides of the doji.
Harami Cross: This formation signals a market top. It consists of a harami, which
is a long black line candlestick which precedes and engulfs a doji with no body.
Engulfing Pattern: A two-candle bullish formation consisting of a small long
black line engulfed by the second candle, a long white line.
Evening Star: A bearish pattern usually occurring at a top. The formation
consists of three candles. The first is a long white line followed by a star and
then a long black line. The star can be either black or white.
Dark Cloud Cover: A two candle formation whereby the first candle is a long white
line and the second candle is a long black line whose body is below the center of
the first candle. This is a bearish formation.
Price charts
490
AmiBroker 5.80 User’s Guide
Technical analysis guide
Trend lines
Technical analysis is built on the assumption that prices trend. Trendlines are
an important tool in technical analysis for both trend identification and
confirmation. A trendline is a straight line that connects two or more price
points and then extends into the future to act as a line of support or
resistance. Many of the principles applicable to support and resistance levels
can be applied to trendlines as well.
Up Trendline
An up trendline has a positive slope and is formed by connecting two of more low
points. The second low must be higher than the first for the line to have a
positive slope. Up trendlines act as support and indicate that net-demand (demand
less supply) is increasing even as the price rises. A rising price combined with
increasing demand is very bullish and shows a strong determination on the part of
the buyers. As long as prices remain above the trendline, the uptrend is
considered solid and intact. A break below the up trendline indicates that
net-demand has weakened and a change in trend could be imminent.
Down Trendline
A down trendline has a negative slope and is formed by connecting two or more
high points. The second high must be lower than the first for the line to have a
negative slope. Down trendlines act as resistance and indicate that net-supply
(supply less demand) is increasing even as the price declines. A declining price
combined with increasing supply is very bearish and shows the strong resolve of
the sellers. As long as prices remain below the down trendline, the downtrend is
considered solid and intact. A break above the down trendline indicates that
net-supply is decreasing and a change of trend could be imminent.
Scale Settings
High points and low points appear to line up better for trendlines when prices
are displayed using a semi-log scale. This is especially true when long-term
trendlines are being drawn or there has been a large change in price. AmiBroker
allows to set the scale as arithmetic or logarithmic (semi-log). An arithmetic
scale displays incremental values (5,10,15,20,25,30) evenly as they move up the
y-axis. A $10 movement in price will look the same from $10 to $20 or from $100
to $110. A semi-log scale displays incremental values in percentage terms as they
move up the y-axis. A move from $10 to $20 is a 100% gain and would appear to be
a much larger than a move from $100 to $110, which is only a 10% gain.
Please remember however that straight line in the log chart is no longer straight
in the linear scale, so trend lines drawn in one scale may look strange in the
other scale.
Validation
It takes two or more points to draw a trendline. The more points used to draw the
trendline, the more validity attached to the support or resistance level
Trend lines
491
AmiBroker 5.80 User’s Guide
Technical analysis guide
represented by the trendline. It can sometimes be difficult to find more than 2
points from which to construct a trendline. Even though trendlines are an
important aspect of technical analysis, it is not always possible to draw
trendlines on every price chart. Sometimes the lows or highs just don’t match up
and it is best not to force the issue. The general rule in technical analysis is
that it takes two points to draw a trendline and the third point confirms the
validity.
Trend lines
492
AmiBroker 5.80 User’s Guide
Technical analysis guide
Moving averages
The moving average is one of the most useful, objective and oldest analytical
tools around. Some patterns and indicators can be somewhat subjective, where
analysts may disagree on if the pattern is truly forming or if there is a
deviation that is might be an illusion. The moving average is more of a
cut-and-dry approach to analyzing stock charts and predicting performance, and it
is one of the few that doesn’t require a genius intelligence to interpret..
Moving average is an indicator that shows the average value of a security’s price
over a period of time.
To find the 50 day Simple Moving Average you would add up the closing prices (but
not always more later) from the past 50 days and divide them by 50. And because
prices are constantly changing it means the moving average will move as well.
Exponential Moving Average (EMA) - is calculated by applying a percentage of
today’s closing price to yesterday’s moving average value. Use an exponential
moving average to place more weight on recent prices. As expected, each new price
has a greater impact on the EMA than it has on the SMA. And, each new price
changes the moving average only once, not twice.
The most commonly used moving averages are the 15, 20, 30, 45, 50, 100, and 200
day averages. Each moving average provides a different interpretation on what the
stock price will do. There really isn’t just one "right" time frame. Moving
averages with different time spans each tell a different story. The shorter the
time span, the more sensitive the moving average will be to price changes. The
longer the time span, the less sensitive or the more smoothed the moving average
will be. Moving averages are used to emphasize the direction of a trend and
smooth out price and volume fluctuations or "noise" that can confuse
interpretation.
Different investors use moving averages for different reasons. While some use it
as their primary analytic tool others simply use the moving average as confidence
builder to back their investment decisions. Here are two other strategies that
people use moving averages for:
Filters
Filtering is used to increase your confidence about an indicator. There are no
set rules or things to look out for when filtering, just whatever makes you
confident enough to invest your money. For example you might want to wait until a
security crosses through its moving average and is at least 10% above the average
to make sure that it is a true crossover. Remember, setting the percentile too
high could result in "missing the boat" and buying the stock at its peak.
Another filter is to wait a day or two after the security crosses over, this can
be used to make sure that the rise in the security isn’t a fluke or unsustained.
Again, the downside is if you wait too long then you could end up missing some
big profits.
Moving averages
493
AmiBroker 5.80 User’s Guide
Technical analysis guide
Crossovers
Using Crossovers isn’t quite as easy as filtering. There are several different
types of crossover’s, but all of them involve two or more moving averages. In a
double crossover you are looking for a situation where the shortest MA crosses
through the longer one. This is almost always considered to be a buying signal
since the longer average is somewhat of a support level for the stock price.
For extra insurance you can use a triple crossover, whereby the shortest moving
average must pass through the two higher ones. This is considered to be an even
stronger buying indicator.
Moving averages
494
AmiBroker 5.80 User’s Guide
Technical analysis guide
Regression channels
Linear regression may sound intimidating, but the mathematical concept is a
simple one. All this technique does is fit a straight line through a finite
number of data points by minimizing the sum of the squared vertical distance
between the line and each of the points. In our context, this means that if time
is represented by days on the horizontal axis and the closing price
on those days is plotted as dots on the vertical axis (a normal closing price
chart), then we try to fit a straight line through those closing-price dots such
that the total sum of the squared vertical distance between each closing price
and the line are minimized. This would then be our best-fit line.
Raff regression channel Raff Regression Channels show the range prices can be
expected to deviate from a Linear Regression trend line. Developed by Gilbert
Raff, the regression channel is a line study the plots directly on the price
chart. The Regression Channel provides a precise quantitative way to define a
price trend and its boundaries. The Regression Channel is constructed by plotting
two parallel, equidistant lines above and below a Linear Regression trend line.
The distance between the channel lines to the regression line is the greatest
distance that any one high or low price is from the regression line.
Raff Regression Channels contain price movement, with the bottom channel line
providing support and the top channel line providing resistance. Prices may
extend outside of the channel for a short period of time. However, if prices
remain outside the channel for a long period of time, a reversal in trend may be
imminent.
Regression channels
495
AmiBroker 5.80 User’s Guide
Technical analysis guide
Fibonacci Retracement
Fibonacci Retracements/Extensions are displayed by first drawing a trendline
between two extreme points. After selecting Fibonacci Retracement tool from Draw
toolbar, a series of up to nine horizontal lines will be drawn at the Fibonacci
levels of 0.0%, 23.6%, 38.2%, 50.0%, 61.8%, 100%, 161.8%, 261.8% and 423.6%.
After a significant move (up or down), prices will often rebound and retrace a
significant portion of the original move. As the price retraces, support and
resistance levels will often occur near the Fibonacci Retracement levels.
Fibonacci retracement/extension tool works in 4 different modes depending on the
direction of trend line drawn:
•
•
•
•
NE - gives (old-style) retracement in up trend
SE - gives retracement in down trend
NW - gives extension in up trend
SW - gives extension in down trend
A controlling trend line drawn with dotted style can be used to delete Fibonacci
retracement study at once using right mouse button menu.
Fibonacci Retracement
496
AmiBroker 5.80 User’s Guide
Technical analysis guide
Fibonacci Time Zones
The Fibonacci Time Zones study consists of vertical lines at the Fibonacci
intervals of 1, 2, 3, 5, 8, 13, 21, 34, etc. The interpretation of Fibonacci Time
Zones involves looking for significant changes in price near the vertical lines.
Fibonacci Time Zones
497
AmiBroker 5.80 User’s Guide
Technical analysis guide
Bollinger bands
Bollinger Bands are envelopes which surround the price bars on a chart. Bollinger
Bands are plotted two standard deviations away from a simple short-term moving
average. This is the primary difference between Bollinger Bands and envelopes.
Envelopes are plotted a fixed percentage above and below a moving average.
Because standard deviation is a measure of volatility, the Bollinger Bands adjust
themselves to the market conditions. They widen during volatile market periods
and contract during less volatile periods. Bollinger Bands become moving standard
deviation bands. Bollinger Bands are displayed with a third line. This is the
simple (short-term) moving average line. The time period for this moving average
can vary. The default for short-term moving average in AmiBroker is 15 days.
An important thing to keep in mind is that Bollinger Bands do not generate buy
and sell signals alone. They should be used with another indicator. RSI, for
example, is quite good choice as a companion for Bollinger bands. When price
touches one of the bands, it could indicate one of two things. It could indicate
a continuation of the trend; or it could indicate a reaction the other way. So
Bollinger Bands used by themselves do not provide all of what technicians need to
know. Then RSI, which is an excellent indicator with respect to overbought and
oversold conditions, comes with help. Generally, when price touches the upper
Bollinger Band, and RSI is below 70, we have an indication that the trend will
continue. Conversely, when price touches the lower Bollinger Band, and RSI is
above 30, we have an indication that the trend should continue. If we run into a
situation where price touches the upper Bollinger Band and RSI is above 70
(possibly approaching 80) we have an indication that the trend may reverse itself
and move downward. On the other hand, if price touches the lower Bollinger Band
and RSI is below 30 (possibly approaching 20) we have an indication that the
trend may reverse itself and move upward. Avoid the trap of using several
different indicators all working off the same input data. If you’re using RSI
with the Bollinger Bands, don’t use MACD too. They both rely on the same inputs.
You might consider using On Balance Volume, or Money Flow. RSI, On Balance
Volume, and Money Flow, rely on different inputs.
Bollinger bands
498
AmiBroker 5.80 User’s Guide
Technical analysis guide
Indicators
What is an indicator?
An indicator is a mathematical calculation that can be applied to a security’s
price and/or volume fields. The result is a value that is used to anticipate
future changes in prices.
AmiBroker has following indicators built-in:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
ROC
RSI
MACD
CCI
OBV
NVI
MFI
Accumulation/Distribution
TRIX
Chaikin
Relative Strength
Ultimate Oscillator
Stochastic
TRIN (Arms Index)
AD-Line (Advance/Decline line)
Volume At Price histogram (Volume Profile)
Relative Performance
Indicators
499
AmiBroker 5.80 User’s Guide
Technical analysis guide
Accumulation/Distribution
Accumulation/Distribution is a momentum indicator which takes into account
changes in price and volume together. The idea is that a change in price coupled
with an increase in volume may help to confirm market momentum in the direction
of the price move.
Note the similarity of this formula to that of the stochastic; this is basically
a stochastic multiplied by volume. This means that if the security closes to its
high, the volume multiplier will greater than if the security closes nearer to
its low.
If the Accumulation/Distribution indicator is moving up the buyers are driving
the price move and the security is being accumulated. A decreasing A/D value
implies that the sellers are driving the market and the security is being
distributed. If divergence occurs between the Accumulation/Distribution indicator
and the price of the security a change in price direction is probable.
The Accumulation/Distribution Line formula is as follows:
Where I is yesterday’s Accumulation/Distribution value.
Accumulation/Distribution
500
AmiBroker 5.80 User’s Guide
Technical analysis guide
Advance-Decline line (AD-Line)
Line measuring advances and declines that reflects market breadth. In its
simplest form ADLine is a summation over time of the net daily difference between
the number of advancing issues and the number of declining issues. AmiBroker uses
slightly improved formula which takes into account also number of unchanged
issues. The exact AFL formula for AmiBroker’s ADLine is:
Difference = ( AdvIssues() - DecIssues() )/ ( UncIssues() + 1 );
DiffSqrt = IIF( Difference > 0, sqrt( Difference ), - sqrt( - Difference ) );
ADLine = Cum( DiffSqrt );
This is a classical indicator which tends to give a good reading of the overall
strength of the market. A break in the A/D line usually proceeds a break in
prices. Look for non-confirmation and divergence.
See also AFL Function reference: AFL Function: adline()
Advance-Decline line (AD-Line)
501
AmiBroker 5.80 User’s Guide
Technical analysis guide
ADX / Directional Movement Index
The ADX Indicator, otherwise known as Directional Movement Index.
The ADX is a trend following system. The average directional movement index, or
ADX, determines the market trend. When used with the up and down directional
indicator values, +DI and -DI, the ADX is an exact trading system. The standard
interpretation for using the ADX (blue line) is to establish a long position
whenever the +DI (green line) crosses above the -DI (red line). You reverse that
position, liquidate the long position and establish a short position, when the
-DI crosses above the +DI. In addition to the crossover rules, you must also
follow the extreme point rule. When a crossover occurs, use the extreme price as
the reverse point. For a short position, use the high made during the trading
interval of the crossover. Conversely, reverse a long position using the low made
during the trading interval of the crossover. You maintain the reverse point, the
high or low, as your market entry or exit price even if the +DI and the -DI
remain crossed for several trading intervals. This is supposed to keep you from
getting whipsawed in the market. For some traders, the most significant use of
the ADX is the turning point concept. First, the ADX must be above both DI lines.
When the ADX turns lower, the market often reverses the current trend. The ADX
serves as a warning for a market about to change direction. The main exception to
this rule is a strong bull market during a blow-off stage. The ADX turns lower
only to turn higher a few days later. According to the developer of the DMI, you
should stop using any trend following system when the ADX is below both DI lines.
The market is in a choppy sidewise range with no discernible trend. If you need
further explanation, please refer to the author’s original work. The book titled
New Concepts in Technical Trading Systems by J. Welles Wilder, Jr. explains this
indicator and several others.
ADX / Directional Movement Index
502
AmiBroker 5.80 User’s Guide
Technical analysis guide
CCI - Commodity Channel Index
A price momentum indicator developed by Donald R. Lambert - it measures price
excursions from the mean price as a statistical variation. The indicator works
quite well with commodities, stocks and mutual funds. It keeps trades neutral in
a sideways moving market, and helps get in the market when a breakout occurs.
A description of the CCI formula is as follows:
First, Calculate each periods mean. This is the high, plus the low, plus the
close, divided by 3.
Second, calculate the n period simple moving average of these means.
Third, from each periods mean price, subtract the n period simple moving average
of mean prices.
Fourth, Compute the mean deviation. This is the differences between each period’s
mean price and the n period simple moving average of those mean prices.
Fifth, Multiply the mean deviation by .015.
Sixth, the mean price, which we calculated in step three, is divided by .015
times the mean deviations from step 5.
Ordinarily, CCI ranges in value from +100 to -100. The rules are to buy and go
long when CCI crosses above +100 and close the long when CCI falls back below
+100. Conversely, sell short when CCI crosses below -100 and close the short when
CCI crosses back above -100.
CCI - Commodity Channel Index
503
AmiBroker 5.80 User’s Guide
Technical analysis guide
Chaikin Oscillator
Developed by Marc Chaikin back in the early 1970’s when opening prices were
eliminated from many newspaper listings making it more difficult to calculate
William’s OBV. Chaikin substituted the average price [(HIGH+LOW)/2] for William’s
opening price and created an oscillator using 10-period and 3-period exponential
moving averages of the resulting Accumulation/Distribution Line.
The basic premise of the Accumulation/Distribution Line is that the degree of
buying or selling pressure can be determined by the location of the close,
relative to the high and low for the corresponding period. There is buying
pressure when a stock closes in the upper half of a period’s range and there is
selling pressure when a stock closes in the lower half of the period’s trading
range.
Bullish Signals
There are two bullish signals that can be generated from the Chaikin Oscillator:
positive divergences and centerline crossovers. Because the Chaikin Oscillator is
an indicator of an indicator, it is prudent to look for confirmation of a
positive divergence, by a bullish moving average crossover for example, before
counting this as a bullish signal.
Bearish Signals
In direct contrast to the bullish signals, there are two bearish signals that can
be generated from the Chaikin Oscillator: a negative divergence and a bearish
centerline crossover. Allow a negative divergence to be confirmed by a bearish
centerline crossover, before a bullish signal is rendered.
The Chaikin Oscillator is good for adding momentum to the
Accumulation/Distribution Line, but can sometimes add a little too much momentum
and be difficult to interpret. The moving averages are both relatively short and
will therefore be more sensitive to changes in the Accumulation/Distribution
Line. Sensitivity is important, but one must also be able to interpret the
indicator.
Chaikin Oscillator
504
AmiBroker 5.80 User’s Guide
Technical analysis guide
MACD - Moving Average Convergence/Divergence
This indicator uses three exponential moving averages, a short or fast average, a
long or slow average and an exponential average of their difference, the last
being used as a signal or trigger line. To fully understand the basics of MACD
you must first understand simple moving averages. The Moving Average
Convergence/Divergence indicator measures the intensity of public sentiment and
is considered by Gerald Appel, its developer, to be a very good indicator
signaling market entry points after a sharp decline. This indicator reveal
overbought and oversold conditions and generates signals that predict trend or
price reversals. It provides a sensitive measurement of the intensity of public
sentiment and can be applied to the stock market, to individual stocks or to
mutual funds. In some instances, it can provide advance warning of reversals
allowing you to buy into weakness and sell into strength.
The Moving Average Convergence/Divergence indicator (MACD) is calculated by
subtracting the value of 26-day exponential moving average from a 12-day
exponential moving average. A 9-day exponential moving average (the "signal
line") is automatically displayed on top of the MACD indicator line.
The basic MACD trading rule is to sell when the MACD falls below its 9-day signal
line. Similarly, a buy signal occurs when the MACD rises above its signal line.
MACD - Moving Average Convergence/Divergence
505
AmiBroker 5.80 User’s Guide
Technical analysis guide
Money Flow Index
The Money Flow Index (MFI) attempts to measure the strength of money flowing in
and out of a security. It is closely related to the Relative Strength Index
(RSI). The difference between the RSI and Money Flow is that where RSI only looks
at prices, the Money Flow Index also takes volume into account.
Calculating Money Flow is a bit more difficult than the RSI.
First we need the average price for the day thenwe need the Money Flow:
Now, to calculate the money flow ratio you need to separate the money flows for a
period into positive and negative. If the price was up in a particular day this
is considered to be "Positive Money Flow". If the price closed down it is
considered to be "Negative Money Flow".
It is the Money Flow Ratio which is used to calculate the Money Flow Index.
The Money Flow ranges from 0 to 100. Just like the RSI, a stock is considered
overbought in the 70- 80 range and oversold in the 20-30 range.
The shorter number of days you use, the more volatile the Money Flow is. The
default is to use a 14 day average.
The interpretation of the Money Flow Index is as follows:
• Look for divergence/failure swings between the indicator and the price
action. If the price trends higher (lower) and the MFI trends lower
(higher), then a reversal may be imminent.
• Look for market tops to occur when the MFI is above a specific level (e.g.,
80). Look for market bottoms to occur when the MFI is below a specific
level (e.g., 20).
Money Flow Index
506
AmiBroker 5.80 User’s Guide
Technical analysis guide
Negative Volume Index
This indicator makes a very important assumption. It assumes that the
unsophisticated investor follows market trends thus pushing up volume as they
jump in on a rising security price. On the other hand, informed buying and
selling by those "in the know" occurs on quieter periods reflected by negative
volume changes on days of declining volume. This is an excellent bull market
trend predictor. This index simply measures the trend of prices during periods
when the volume is declining.
The price index is only adjusted on those days during which the volume has
decreased from the previous day. If the volume did not change or was positive,
the indicator remains unchanged. If the index rises, it means simply that the
price of the security has gone up on a day that the volume has dropped. A drop in
the index indicates that the price of the security has gone down while the volume
declined. (The change in the index is calculated as a percentage change in the
price).
This indicator can be compared to its longer period averages to reflect the
movement of smart money. If, for example current index readings are above a
six-month average, it can very well indicate an up trend for the market or the
security.
Negative Volume Index
507
AmiBroker 5.80 User’s Guide
Technical analysis guide
OBV - On Balance Volume
OBV was created by Joe Granville, the father of OBV analysis. This is a running
total of volume that relates price changes and volume and shows accumulation and
distribution action.
The classic OBV is calculated by adding todays total volume to a cumulative
total when price closes higher than yesterdays close and subtracting todays
total volume from the cumulative when the price closes lower than yesterdays
close. If price remains the same, then the OBV is not changed. The actual amount
of the price change is irrelevant and only the direction of change is significant
for these calculations.
This indicator defines trends by showing underlying strength of price movements
over time. A solid price trend is assumed to be accompanied with a stronger
volume movement in the same direction. OBV analysis assumes that volume trends
lead price trends and that OBV changes generally precede price changes. Look for
divergence or non-confirmation between price and volume movements. A stock that
is trending in an upward direction and starts to experience higher volume on days
of lower closing prices usually indicates an end to the current trend. Look for
changes or breakouts in OBV trends. Sell short when the OBV makes a downside
breakout and buy long when the on OBV upside breakouts.
OBV - On Balance Volume
508
AmiBroker 5.80 User’s Guide
Technical analysis guide
Parabolic SAR (Stop-And-Reverse)
Developed by Welles Wilder, creator of RSI and DMI, the Parabolic SAR sets
trailing price stops for long or short positions. Also referred to as the
stop-and-reversal indicator (SAR stands for "stop and reversal"), Parabolic SAR
is more popular for setting stops than for establishing direction or trend.
Wilder recommended establishing the trend first, and then trading with Parabolic
SAR in the direction of the trend. If the trend is up, buy when the indicator
moves below the price. If the trend is down, sell when the indicator moves above
the price.
The formula is quite complex, but interpretation is relatively straightforward.
The dotted lines below the price establish the trailing stop for a long position
and the lines above establish the trailing stop for a short position. At the
beginning of the move, the Parabolic SAR will provide a greater cushion between
the price and the trailing stop. As the move gets underway, the distance between
the price and the indicator will shrink, thus making for a tighter stop-loss as
the price moves in a favorable direction.
There are two variables: the step and the maximum step. The higher the step is
set, the more sensitive the indicator will be to price changes. If the step is
set too high, the indicator will fluctuate above and below the price too often,
making interpretation difficult. The maximum step controls the adjustment of the
SAR as the price moves. The lower the maximum step is set, the further the
trailing stop will be from the price. Wilder recommends setting the step at .02
and the maximum step at .20.
Parabolic SAR (Stop-And-Reverse)
509
AmiBroker 5.80 User’s Guide
Technical analysis guide
RS - Relative Strength (comparative)
Compares the performance trend of a stock or industry group relative to another
stock, group or index. This comparison removes the emotion from the marketplace.
Many times a drop in relative strength can indicate a coming drop in actual price
of the security. Do not confuse with Wilderss RSI.
The concept is to identify which stock or market sector is performing the best.
Assuming that trends will continue to persist for some time, it is more probable
that before a stock price will drop sharply it will first loose relative strength
against other stocks. This would indicate a sell prior to such a price drop. An
increase in relative strength does not necessarily indicate that the index is
heading up, but it does signal a buy alert.
RS - Relative Strength (comparative)
510
AmiBroker 5.80 User’s Guide
Technical analysis guide
RSI - Relative Strength Index
A technical indicator developed by Welles Wilder to help investors gauge the
current strength of a security price relative to its past performance. The RSI is
an excellent overbought/oversold indicator that can be used to predict trend
reversal points. Do not confuse this index with relative strength in its everyday
definition as used in comparing the movement of one security, index or group
against the movement of another security, index or group. Developed by J. Welles
Wilder, Jr. and first described in his book "New Concepts in Technical Trading
Systems", this is a momentum oscillator that measures the velocity of directional
price movement.
It compares a security highest highs and lowest lows over a period of time. RSI
is based upon the difference between the average of the closing price on up days
vs. the average closing price on the down days.
RSI=100-[100/(1+U/D)]
U = average of upward price closes (EMA of gains)
D = average of downward price closes (EMA of losses)
The ratio between up and down closing averages is in fact the makeup of the
index. The time period specified determines the volatility of the RSI. For
example, a 9-day time period will be more volatile than a 21-day time span. The
author (Wilder) uses an n value of 14 days but other values may be used that
better fit particular securities. The 9-day and 25-day RSIs have also gained
popularity. Because you can vary the number of time periods in the RSI
calculation, I suggest that you experiment to find the period that works best for
you.
The RSI is a price-following oscillator that ranges between 0 and 100. A popular
method of analyzing the RSI is to look for a divergence in which the market index
is making a new high, but the RSI is failing to surpass its previous high. This
divergence would be an indication of an impending reversal. When the RSI then
turns down and falls below its most recent trough, it is said to have completed a
failure swing. The failure swing would be considered a confirmation of an
impending reversal.
In Mr. Wilder’s book, he discusses five uses of the RSI in analyzing commodity
charts (these apply to indices as well):
1. Tops and Bottoms: RSI readings above 70 indicate the shares are overbought and
are likely to start falling. Readings below 30 indicate the shares are oversold
and a rally can be expected. (AmiBroker automatically draws horizontal lines at
these levels). The RSI usually forms these tops and bottoms before the underlying
price chart.
2. Chart Formations: The RSI often forms chart patterns (such as head and
shoulders or rising wedges) that may or may not be visible on the price chart.
3. Failure Swings: This is where the RSI surpasses a previous high (peak) or
RSI - Relative Strength Index
511
AmiBroker 5.80 User’s Guide
Technical analysis guide
falls below a recent low (trough).
4. Support and Resistance: The RSI shows, sometimes more clearly than the price
chart, levels of support and resistance.
5. Divergence: As discussed above, this occurs when the price makes a new high
(or low) that is not confirmed by a new RSI high (or low).
RSI - Relative Strength Index
512
AmiBroker 5.80 User’s Guide
Technical analysis guide
ROC - Price Rate Of Change
This indicator displays the rate-of-change of a securitys price. Change is
displayed as a percentage rather than as a ratio.
ROC is calculated by dividing the price change over the last n-periods by the
closing price n-periods ago. This gives you percentage that the price has changed
in the last n-periods.
When the 10-day ROC line is above the central line, the price is higher today
than it was 10 periods ago. When the ROC line is below the central line, the
price is lower today than it was 10 days ago. If the ROC line is above the
central line, the price is higher than it was 10 days ago. If the ROC line is
below the central line but rising, the price is still lower today than it was 10
days ago, but the range is narrowing.
The 12-day ROC is best used as a short to intermediate-term overbought/oversold
indicator. The higher the ROC, the more overbought the security; the lower the
ROC, the more likely a rally. However, as with all overbought/oversold
indicators, it is best to wait for the market to begin to correct (i.e., turn up
or down) before placing your trade. A market that appears overbought may remain
overbought for some time. In fact, extremely overbought/oversold readings usually
imply a continuation of the current trend.
The 12-day ROC tends to be very cyclical, oscillating back and forth in a fairly
regular pattern. Often, price changes can be anticipated by studying the previous
cycles of the ROC and relating the previous cycles to the current market.
The optimum overbought/oversold levels (e.g., +/-5) will vary depending on the
security being analyzed and overall market conditions. In strong bull markets, it
is usually beneficial to use higher levels, perhaps +10 and -5.
ROC - Price Rate Of Change
513
AmiBroker 5.80 User’s Guide
Technical analysis guide
Stochastic Slow
Stochastic is an oscillator that measures the position of a stock or security
compared with its recent trading range indicating overbought or oversold
conditions.
It displays current day price at a percentage relative to the securitys trading
range (high/low) over the specified period of time.
In a Slow Stochastic, the highs and lows are averaged over a slowing period. The
default is usually 3 for slow and 1 (no slowing) for fast. The line can then be
smoothed using an exponential moving average, Weighted, or simple moving average
%D. Confirming Buy/sell signals can be read at intersections of the %D with the
%K as well.
The Stochastic Oscillator always ranges between 0% and 100%. A reading of 0%
shows that the security’s close was the lowest price that the security has traded
during the preceding x-time periods. A reading of 100% shows that the security’s
close was the highest price that the security has traded during the preceding
x-time periods. When the closing price is near the top of the recent trading
range (above 80%), the security is in an overbought condition and may signal for
a possible correction. Oversold condition exists at a point below %20. Prices
close near the top of the range during uptrends and near the bottom of the range
during downtrends.
Stochastic Slow
514
AmiBroker 5.80 User’s Guide
Technical analysis guide
TRIN - Arms Index
Trading Index, a technical measure of advances and declines within the market.
TRIN takes into account the number and volume of issues that advanced in price,
and the number and volume of issues that declined in price. This index measures
the relative strength of volume associated with advancing stocks against the
strength of volume associated with declining stocks.
Exact AFL formula for TRIN is:
ArmsIndex = ( AdvIssues() / DecIssues() ) / ( AdvVolume() / DecVolume ) );
A TRIN value of 1 indicates that the ratio of up volume to down volume is equal
to the ratio of advancing issues to the declining issues and the market is in a
neutral condition. A neutral condition simply means that the up volume is equally
distributed over the advancing issues and that the down volume is equally
distributed over declining issues for the day.
This indicator, although simple in its formulation, requires much study in its
application. There are many variations applied to the TRIN. Many analysts use a
10-day moving average of TRIN as an indicator. AmiBroker plots two different
averages for TRIN with the default averaging periods of 15 and 45. A reading of
less than 1.0 usually indicates a bullish demand while a reading greater than 1
can signify a bearish market condition. It must be kept in mind that the
indicator behavior and its reading and interpretation depends on whether the
market is in a bullish or bearish phase. The actual time duration of this market
phase must also be considered. Do not attempt to make and buy or sell decisions
based on movements of this indicator by itself.
See also AFL Function reference: AFL Function: trin()
TRIN - Arms Index
515
AmiBroker 5.80 User’s Guide
Technical analysis guide
TRIX - TRIple eXponential
TRI-ple eXponential. TRIX displays the % rate-of-change of a triple exponentially
smoothed moving average of the closing price of a security.
TRIX is calculated as a one period rate of change of the third exponential moving
average pass of the closing price.
TRIX is designed to filter out insignificant cycles - those smaller than the
number of moving averages specified. The TRIX indicator oscillates around a zero
line. Trades should be placed when the indicator changes direction.
TRIX - TRIple eXponential
516
AmiBroker 5.80 User’s Guide
Technical analysis guide
Ultimate Oscillator
Larry Williams, the designer of the Ultimate Oscillator, wanted to address the
problems experienced with most oscillators when used over different lengths of
time.
Ultimate oscillator signals are the following: divergence and a breakout in the
Oscillator’s trend, as well as overbought and oversold levels.
The value of other oscillators can vary greatly depending on the number of time
periods used during the calculation. So, the Ultimate Oscillator, uses weighted
sums of three oscillators which represent short, intermediate, and long term
market cycles (7, 14, & 28-period), and it is plotted as a single line on a
vertical scale of 0 to 100.
The three components are based on Williams’s definitions of buying and selling
"pressure."
A trade should be initiated following a divergence and a breakout in the Ultimate
Oscillator’s trend.
Signals:
A Buy signal is generated when:
A positive or bullish divergence occurs between the Ultimate oscillator and the
price.
The Ultimate falls below 30 and then rises above the previous high established
during the divergence (the actual buy signal).
A Sell Signal is offered when:
A negative or bearish divergence occurs between the Ultimate and the price.
The Ultimate rises above 70 and then falls below the previous low established
during the divergence (the actual sell signal).
Closing existing positions:
Close long positions when the Ultimate exceeds 70.
Close short positions when the Ultimate goes below 30.
As with most indicators, it is good if these signals are confirmed by other
indicators before being acted upon.
Ultimate Oscillator
517
AmiBroker 5.80 User’s Guide
Technical analysis guide
VAP - Volume At Price histogram
Volume At Price histogram is also known as "Volume Profile" chart.
To turn it on simply go to Tools->Preferences and change Type of the VAP from
"NONE" to "Left-side solid area chart, behind" for example
VAP shows total volume of trading that occurred at given price level. VAP is
calculated from data bars that are currently visible.
Actual algorithm involves not ONE price but High-Low price RANGE.
AmiBroker DISTRIBUTES equally bar’s volume over High-Low range to produce VAP
histogram. For example if bar’s volume is 10000 and H-L range spans 3 ’lines" of
VAP histogram than each of 3 lines
involved gets added 10000/3 to produce statistics. This gives much more accurate
results than using single price
as some other implementations do.
To turn VAP on/off use: Tools->Preferences->Main chart
You can also add VAP to your own custom charts using PlotVAPOverlay AFL function.
VAP - Volume At Price histogram
518
AmiBroker 5.80 User’s Guide
Technical analysis guide
Relative Performance chart
Relative Performance chart compares the rate of price change of two or more
tradable instruments. Plot starts with 0% at the very first visible bar and shows
percentage change of closing price since that point for every symbol in the list.
Relative perfomrance charts are great for comparing dissimimilarly priced issues
(for example stocks and indices) since it displays percentage changes, not
absolute values. You can easily see which instruments perform better than others
and choose best performers for your trading.
You can adjust the list of symbols that are plotted in the Relative Performance
chart by clicking with RIGHT mouse button over the chart and choosing
"Parameters" item from the context menu. In the Parameters dialog you can enter a
comma-separated list of symbols that you want to get the chart for. There is no
limit on number of symbols you can enter, but please remember to separate symbols
by comma and not using spaces unless symbol itself has them.
Relative Performance chart
519
AmiBroker Formula Language (AFL)
AmiBroker is equipped with a powerful formula language allowing you to write
trading system rules, define your own indicators and custom commentaries. This
chapter explains the language, gives you detailed reference of built-in analysis
functions and shows how to use AFL-tools such as automatic analyzer and formula
editor .
• Language Reference
♦ Basics (lexical elements, predefined variables)
♦ Keywords
• Function Reference
♦ Alphabetical list of all AFL functions
♦ Categorized list of AFL functions
♦ AddToComposite function - creating multiple security statistics
♦ Equity functon - analysing your trading system performance
♦ Variable-period functions
• User-defined functions and variable scope
• AFL Tools
• AFL Scripting Host
• Component Object Model support in AFL
• Common coding mistakes
• Advanced portfolio backtester interface
• Adding custom backtester metrics
• Using Low-level graphics functions
See also: Tutorial: Understanding how AFL works
AmiBroker Formula Language (AFL)
520
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
AFL Reference Manual
Introduction
AFL is a special programming language used to define and create custom
indicators, scans, explorations, back-tests and guru commentaries.
Basics
Lexical elements
This chapter describes the different categories of word-like units (tokens)
recognized by the AFL language interpreter.
Whitespace
Whitespace is the collective name given to spaces (blanks), tabs, new line
characters and comments. Whitespace can serve to indicate where tokens start and
end, but beyond this function, any surplus whitespace is discarded.
Comments
Comments are pieces of text used to annotate a program. Comments are for the
programmer’s use only; they are stripped from the source code before parsing. The
are two ways to delineate comments: C-like comments and C++ like comments. A
C-like comment is any sequence of characters placed after the symbol pair /*. The
comment terminates at the first occurrence of the pair */ following the initial
/*. The entire sequence, including the four comment-delimiter symbols, is
replaced by one space. A C++ like comments are single-line comments that start by
using two adjacent slashes (//) in any position within the line and extend until
the next new line.
AFL does not allow nested comments.
Tokens
AFL recognizes five classes of tokens:
•
•
•
•
•
identifiers
constants
string-literals
operators
punctuators (also known as separators)
Identifiers are arbitrary names of any length given to functions and variables.
Identifiers can contain the letters (a-z, A-Z), the underscore character ("_"),
and the digits (0-9). The first character must be a letter.
AFL identifiers are NOT case sensitive.
Constants are tokens representing fixed numeric or character values. Numeric
AFL Reference Manual
521
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
constants consist of decimal integer and optionally: decimal point and decimal
fraction part. Negative numeric constants have unary minus (-) prefixed.
String constants, also known as string literals, form a special category of
constants used to handle fixed sequences of characters and are written as a
sequence of any number of characters surrounded by double quotes:
"This is literally a string"
The null (empty) string is written "". The characters inside the double quotes
can include escape sequences ("\n" - a new line escape sequence).
A Constant expression is an expression that always evaluates to a constant. They
are evaluated just as regular expressions are.
Punctuator (also known as separator) in AFL is one of the following characters:
(),;=.
Parentheses (open ( and close ) ) group expressions, isolate conditional
expressions and indicate function calls and function parameters:
d = c * ( a + b ) /* override normal precedence */
a= (b AND c) OR (d AND e) /* conditional expression */
func() /* function call no arguments */
The comma (,) separates the elements of a function argument list
The semicolon (;) is a statement terminator. Any legal AFL expression followed by
a semicolon is interpreted as a statement, known as expression statement. The
expression is evaluated and its value
is discarded (except Guru Commentaries where string values are written to output
window)
The dot (.) is a member access operator. It is used to call COM object methods.
If myobj variable holds the object, using dot operator we can call the methods
(functions) of myobj object:
myobj.Method();
The equal sign (=) separates variable declarations from initialization lists:
x = 5;
It also indicates the default value for a parameter (see built-in function
description):
macd( fast = 12; slow = 26 ) /* default values for fast and slow arguments)
Language structure
Each formula in AFL contains of one or more expression statements. Each statement
MUST be terminated by semicolon (;). In this way you are able to break long
expressions into several physical lines (in order to gain clarity) and AmiBroker
will still treat it like a single statement until terminating semicolon.
Examples:
x = ( y + 3 );
Language structure
/* x is assigned the value of y + 3
*/
522
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
x = y = 0;
/* Both x and y are initialized to 0 */
proc( arg1, arg2 );
/* Function call, return value discarded */
y = z = ( f( x ) + 3 ); /* A function-call expression
my_indicator =
*/
IIf( MACD() > 0,
Close - MA(Close,9),
MA( Close, 9 ) - Close );
/* one statement in several lines */
Identifiers
Identifiers in AFL are used to identify variables and functions.
There are some predefined identifiers referencing built-in arrays and functions.
The most important are price array identifiers. They identify specific price
fields that the formula should operate on. The valid price array identifiers are
open, high, low, close, volume, openint, average. Price array identifiers can be
abbreviated as shown in the following table. Note that these are not
case-specific.
Long name
Abbreviation
Open
O
High
H
Low
L
Close
C
Volume
V
OpenInt
OI
Avg
<none available>
Comment
(High+Low+Close)/3 - so called
"typical price"
Examples of the use of price array identifiers in formulas are shown below.
MA( Close, 10 ); IIf( H > Ref(H,-1), MA(H,20), MA(C,20) );
Operators
Comparision operators
Comparision operators are divided into two types:
• relational ( <, >, <=, >= )
• equality ( ==, != )
Symbol
Meaning
<
Less than
Language structure
523
AmiBroker 5.80 User’s Guide
>
Greater than
<=
Less than or equal to
>=
Greater than or equal to
==
Equal to
!=
Not equal to
AmiBroker Formula Language (AFL)
These operators give true (1) or false (0) value as a result of comparison.
Assignment operator
Symbol Meaning
=
Store the value of the second operand in the object
specified by the first operand (simple assignment).
The assignment operator assigns a value to a variable:
result = expression;
where result is variable identifier and expression is any numerical, array or
text expression.
As the = operator behaves like other operators, expressions using it have a value
in addition to assigning that value into variable. This means that you can chain
assignment operators as follows:
j = k = l = 0;
j, k, and l equal zero after the example statement is executed.
Attention: please DO NOT confuse assignment operator (=) with equality check (==)
These are two different operators and you must not use assignment (=) to check
for equality.
if( Name() = "MSFT" ) // WRONG !!! - variable assignment operator used instead of
equality check
{
}
if( Name() == "MSFT" ) // CORRECT - equality operator used properly
{
}
This is one of common coding mistakes listed here.
Arithmetic operators
Formulas can contain the following mathematical operators:
Language structure
524
AmiBroker 5.80 User’s Guide
Symbol
Meaning
+
Addition
-
Subtraction (or negative value)
*
Multiplication
/
Division
%
Modulus (or remainder) (AFL 1.7+)
^
Exponentiation (raising to a power)
|
Bit-wise "Or" (AFL 2.1+)
&
Bit-wise "And" (AFL 2.1+)
AmiBroker Formula Language (AFL)
The following formulas illustrate the use of operators in a formula:
var1 = ( H + L ) / 2;
var2 = MA(C,10)-MA(C,20) / (H + L + C);
var3 = Close + ((1.02 * High)-High);
Logical operators
Symbol Meaning
NOT
Logical "Not" - gives "True" when operand is equal to false
AND
Logical "And" - gives "True" result if BOTH operands are true
at the same time
OR
Logical "Or" - gives "True" result if ANY of operands is true
If a formula requires multiple conditions, you can combine the conditions with
AND and OR operators. For example, maybe you’d like to plot a +1 when the MACD is
greater than zero and the RSI is greater than 70:
Condition = MACD() > 0 AND RSI(14) > 70;
You can add as many conditions within a formula as you like.
Compound assignment operators
Introduced in version 5.00, the compound operatos are specifeid in the form of:
destinvar op= expr;
where destinvar is the variable, expr is the expression, and op is one of the
following artithmetic operators: +, -, *, /, %, &, |
The destinvar op= expr form behaves as:
destinvar = destinvar op expr;
Language structure
525
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
This is shortcut form for common assignment statements like k = k + 2; so you can
write it shorter as:
k += 2;
and it will work the same but little faster.
Full list of available assignment operators is here:
No Symbol Meaning
1
=
Store the value of the second operand in the object
specified by the first operand (simple assignment).
2
*=
Multiply the value of the first operand by the value
of the second operand; store the result in the object
specified by the first operand.
3
/=
Divide the value of the first operand by the value of
the second operand; store the result in the object
specified by the first operand.
4
%=
Take modulus of the first operand specified by the
value of the second operand; store the result in the
object specified by the first operand.
5
+=
Add the value of the second operand to the value of
the first operand; store the result in the object
specified by the first operand.
6
=
Subtract the value of the second operand from the
value of the first operand; store the result in the
object specified by the first operand.
7
&=
Obtain the bitwise AND of the first and second
operands; store the result in the object specified by
the first operand.
8
|=
Obtain the bitwise inclusive OR of the first and
second operands; store the result in the object
specified by the first operand
typeof() operator
The typeof operator is used in the following way:
typeof (operand)
The typeof operator returns a string indicating the type of the *unevaluated*
operand. operand is the string, variable, function identifier, or object for
which the type is to be returned.
When supplying identifier, it should be provided alone, without arithmetic
operators, without extra arguments and without braces.
If you want to check the type of value returned by the function, you must first
assign the return value to a variable and then use
Language structure
526
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
typeof( variable ).
Possible return values are:
•
•
•
•
•
•
•
•
•
•
"undefined" - identifier is not defined
"number" - operand represents a number (scalar)
"array" - operand represents an array
"string" - operand represents a string
"function" - operand is a built-in function identifier
"user function" - operand is a user-defined function
"object" - operand represents COM object
"member" - operand represents member function or property of COM object
"handle" - operand represents Windows handle
"unknown" - type of operand is unknown (should not happen)typeof operator
allows among other things to detect undefined variables in the following
way
if( typeof( somevar ) == "undefined" )
{
/// when somevar is undefined the code here will execute
}
The following sample COMMENTARY code shows the output of typeof() in some common
situations:
x = MACD();
y = LastValue( x );
function testfun() { return 1; };
printf( typeof( test ) + "\n" ); // the undefined variable
printf( typeof( 1 ) + "\n"); // literal number
printf( typeof( "checking" ) + "\n"); // literal string
printf( typeof( x ) + "\n"); // array variable
printf( typeof( y ) + "\n"); // scalar variable
printf( typeof( MACD ) + "\n"); // function identifier
printf( typeof( testfun ) + "\n" ); // user function identifier
Operator precedence and the parentheses
AFL supports parentheses in formulas.
Parentheses can be used to control the operation precedence (the order in which
the operators are calculated). AmiBroker always does operations within the
innermost parentheses first. When parentheses are not used, the precedence is as
follows (higher precedence listed first):
No Symbol
Meaning
1
++
Post-increment/pre-increment
(i++ works like i = i + 1)
2
--
Post-decrement/pre-decrement
Language structure
527
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
(i-- works like i = i - 1 )
3
[]
Array element (subscript) operator
4
^
Exponentiation
5
-
Negation - Unary minus
6
*
Multiplication
7
/
Division
8
%
Reminder (Modulo operator)
9
+
Addition
10
-
Subtraction
11
<
Less than
12
>
Greater than
13
<=
Less than or equal to
14
>=
Greater than or equal to
15
==
Equal to
16
!=
Not equal to
17
&
Bit-wise "And" (AFL 2.1+)
18
|
Bit-wise "Or" (AFL 2.1+)
19
NOT
Logical "Not"
20
AND
Logical "And"
21
OR
Logical "Or"
22
=
Variable assignment operator
23
*=
/=
%=
+=
-=
&=
|=
Compound assignment
The expression
H + L / 2;
(without parenthesis) would be calculated by AmiBroker as "L / 2" plus "H", since
division has a higher precedence. This would result in a much different value
than
(H + L)/2;
Language structure
528
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
A few words about increment/decrement operators. There are two kinds of them:
postfix and prefix.
The unary operators (++ and --) are called prefix increment or decrement
operators when the increment or decrement operators appear before the operand.
Postfix increment and decrement has higher precedence than prefix increment and
decrement operators. When the operator appears before its operand, the operand is
incremented or decremented and its new value is the result of the expression.
i = 5;
j = ++i; // i will be incremented first and result (number 6) will be assigned to
j.
The result of the postfix increment or decrement operation is the value of the
postfix-expression before the increment or decrement operator is applied. The
type of the result is the same as that of the postfix-expression but is no longer
an l-value. After the result is obtained, the value of the operand is incremented
(or decremented).
i = 5;
j = i++; // j will be assigned the value of 5 (before incrementation) and then i
will be incremented to 6.
Accessing array elements: [ ] - subscript operator
An array identifier followed by an expression in square brackets ([ ]) is a
subscripted representation of an element of an array object.
arrayidentifier [ expression ]
It represents the value of expression-th element of array.
BarCount constant gives the number of bars in array (such as Close, High, Low,
Open, Volume, etc). Array elements are numbered from 0 (zero) to BarCount-1.
To get the first bar you can use array[ 0 ], to get the last bar of array you can
use array[ BarCount - 1 ];
For example:
Close[ 5 ];
Represents the sixth element (bar) of the close array.
Close[ 0 ];
Represents the very first available bar of the close array.
High[ BarCount - 1 ];
Represents the last bar of High array.
Language structure
529
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
Compound statements (Blocks)
A compound statement consists of zero or more statements enclosed in curly braces
({ }). A compound statement can be used anywhere a statement is expected.
Compound statements are commonly called blocks.
{
statement1;
....
statementN;
}
(this is ’borrowed’ from C language, users of other programming languages are
used to use BEGIN for { and END for } )
if( Amount > 100 )
{
_TRACE("Amount above 100");
Balance = Balance + Amount;
}
else
Balance = Balance - Amount;
Built-in Functions
In addition to mathematical operators, AmiBroker contains over 70 built-in
functions that perform mathematical operations.
The following formula consists of a single function that gives the square roots
of the closing prices:
sqrt( Close );
The following formula consists of a single function that gives a 14-period RSI
indicator:
Graph0 = RSI(14);
The following formula consists of two functions. The result is the difference
between the MACD indicator and a 9-period exponential moving average of the MACD:
Graph0 = MACD() - EMA(MACD(),9);
All function calls must consist of function identifier (name) followed by a pair
of parentheses.
As has been eluded to in earlier examples, a function can be "nested" within a
function. The nested function can serve as the main function’s data array
Language structure
530
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
parameter. The following examples show functions nested within functions:
MA( RSI(15), 10 );
MA( EMA( RSI(15), 20), 10 );
The first example calculates a 10-period simple moving average of a 15-period
Relative Strength Index (RSI). The second example calculates a 20-period
exponential moving average of a 15-period RSI, and then calculates a 10-period
simple moving average of this moving average.
Conditional function IIF()
The iif() function is used to create conditional assignments. It contains three
parameters as shown in the following example.
dynamicrsi = IIf( Close > MA(C,10), RSI(9), RSI(14) );
The above "iif" statement reads (in English) as follows: If today’s close is
greater than today’s 10-day simple moving average of the close, then assign a
9-day RSI to the dynamicrsi variable, otherwise, assign a 14-day RSI. The next
formula assigns positive volume to volresult variable if the close is greater
than the median price. Otherwise, "negative volume" is assigned.
volresult = IIf( Close > (High+Low)/2, Volume, -Volume );
If you simply want an expression to be evaluated as either true or false, it can
be done without the use of the iif() function. The following formula will result
in either a 1 (true) or a 0 (false):
result = RSI(14) > 70;
The same done with iif() gives the same results, but the formula is longer.
result = IIf(RSI(14) > 70, 1, 0 );
Please note that IIF is a function - so the result of evaluation is returned by
that function and should be assigned to some variable.
IIf always evaluates both TRUE_PART and FALSE_PART, even though it returns only
one of them. Because of this, you should watch for undesirable side effects. IIF
function is NOT a flow-control statement. If you need flow control (conditional
execution of some code parts) you should look for if-else conditional statement
described later in this document.
The following example shows one common error made with IIF function:
IIf( condition, result = 7, result = 9 ); // THIS IS WRONG
Correct usage is:
result = IIf( condition, 7, 9 );
Language structure
531
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
/* 7 or 9 is *returned* and assigned to result variable depending on condition */
Variables
In order to shorten, simplify, enhance, and make the maintenance of complex
formulas easier, you may want to use variables. In fact using variables you can
significantly improve formula calculation speed. So it is strongly recommended to
use variables and there is no limit on number of variables you can define.
A variable is an identifier that is assigned to an expression or a constant. The
number of variables used in a formula is not limited. Variables must be assigned
before the variable is used in the formula. Variables cannot be assigned within a
function call.
User-defined variable names (identifiers) cannot duplicate names already used by
functions (e.g., ma, rsi, cci, iif, etc.) or predefined array identifiers (e.g.,
open, high, low, close, simple, o, c, l, h, s, a).
Reserved variables
AmiBroker uses some reserved variable names in its formulas, for example in
Auto-Analysis window you have to assign values to 2 variables named ’buy’ or
’sell’ to specify the conditions where "buy" and "sell" conditions occur. For
example (system that buys when MACD rises above 0 line, and sells when MACD falls
below 0 line)
Buy = Cross( MACD(), 0 );
Sell = Cross( 0, MACD() );
AmiBroker uses the following reserved variable names. Please note that variables
marked as obsolete should NOT be used in new coding. They are left for backward
compatibility only and new formulas should use modern functions like Plot() to
plot indicators and AddColumn() to define exploration columns.
Variable
Usage
Applies to
buy
defines "buy" (enter long position) trading rule
Automatic
Analysis,
Commentary
sell
defines "sell" (close long position) trading rule
Automatic
Analysis,
Commentary
short
defines "short" (enter short position - short sell)
trading rule
Automatic
Analysis
cover
defines "cover" (close short position - buy to cover)
trading rule
Automatic
Analysis
buyprice
defines buying price array (this array is filled in
with the default values according to the Automatic
Analyser settings)
Automatic
Analysis
Language structure
532
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
sellprice
defines selling price array (this array is filled in
with the default values according to the Automatic
Analyser settings)
Automatic
Analysis
shortprice
defines short selling price array (this array is
filled in with the default values according to the
Automatic Analyser settings)
Automatic
Analysis
coverprice
defines buy to cover price array (this array is
filled in with the default values according to the
Automatic Analyser settings)
Automatic
Analysis
title
defines title text (overrides any graphNname)
Indicators
tooltip
Obsolete in 5.40. Use Data window instead or use
Plot() with styleHidden if you want to add your
custom values to data tooltip.
Indicators
graphxspace
defines percentage extra space added at the top and
the bottom of the chart
Indicators
graphzorder
GraphZOrder variable allows to change the order of
plotting indicator lines. When GraphZOrder is not
defined or is zero (false) - old ordering (last to
first) is used, when GraphZOrder is 1 (true) reverse ordering is applied.
Indicators
exclude
If defined, a true (or 1) value of this variable
excludes current symbol from scan/exploration/back
test. They are also not considered in buy and hold
calculations. Useful when you want to narrow your
analysis to certain set of symbols.
Automatic
Analysis
roundlotsize
defines round lot sizes used by backtester (see
explanations below)
Automatic
Analysis
(new in
4.10)
ticksize
defines tick size used to align prices generated by
built-in stops (see explanations below) (note: it
does not affect entry/exit prices specified by
buyprice/sellprice/shortprice/coverprice)
Automatic
Analysis
(new in
4.10)
pointvalue
allows to read and modify future contract point value
(see backtesting futures)
CAVEAT: this AFL variable is by default set to 1
(one) regardless of contents of Information window
UNLESS you turn ON futures mode
(SetOption("FuturesMode", True ))
Automatic
Analysis
(new in
4.10)
margindeposit
allows to read and modify future contract margin (see
backtesting futures)
Automatic
Analysis
(new in
4.10)
positionsize
Allows control dollar amount or percentage of
portfolio that is invested into the trade (more
information available in the "Tutorial: Backtesting
Automatic
Analysis
(new in 3.9)
Language structure
533
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
your trading ideas")
positionscore
Defines the score of the position. More details:
"Tutorial: Portfolio Backtesting")
Automatic
analysis
numcolumns
Exploration only: defines the number of your own
columns (excluding predefined ticker and date
columns) and assign the column value to the variable
Automatic
Analysis
filter
Exploration only: controls which symbols/quotes are
accepted. If "true" (or 1) is assigned to that
variable for given symbol/quote it will be displayed
in the report.
Automatic
Analysis
So, for example, the following formula will accept
all symbols with closing prices greater than 50 :
filter = close > 50;
columnN
Exploration only: defines Nth column value. Example:
(obsolete)
columnNformat
(obsolete)
Automatic
Analysis
column0 = Close;
Exploration only: allows you to define the formatting
applied to numbers. 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. So, in our example, typing:
Automatic
Analysis
column0format = 1.4;
will give closing prices displayed with 4 decimal
digits.
(Note for advanced users: the integer part of this
number can be used to pad formatted number with
spaces - 6.0 will give no decimal digits but a number
space-padded upto 6 characters.)
columnNname
Exploration only: allows you to define the header
name. Assigning
Automatic
Analysis
(obsolete)
column0name = "Close";
will change the name of the first custom column from
the default "Column 0" to more appropriate "Close".
maxgraph
specifies maximum number of graphs to be drawn in
custom indicator window (default=3)
Indicators
graphN
(obsolete)
defines the formula for the graph number N (where N
is a number 0,1,2,..., maxgraph-1)
Indicators
graphNname
(obsolete)
defines the name of Nth graph line. This will appear
in the title of the chart pane
Indicators
(obsolete)
Language structure
534
AmiBroker 5.80 User’s Guide
graphNcolor
(obsolete)
AmiBroker Formula Language (AFL)
defines the color index of Nth graph line (color
indexes are related to the current palette - see
Preferences/Color)
Indicators
colorCustom1 = 0
colorCustom2 = 1
colorCustom3 = 2
colorCustom4 = 3
colorCustom5 = 4
colorCustom6 = 5
colorCustom7 = 6
colorCustom8 = 7
colorCustom9 = 8
colorCustom10 = 9
colorCustom11 = 10
colorCustom12 = 11
colorCustom13 = 12
colorCustom14 = 13
colorCustom15 = 14
colorCustom16 = 15
colorBlack = 16
colorBrown = 17
colorDarkOliveGreen = 18
colorDarkGreen = 19
colorDarkTeal = 20
colorDarkBlue = 21
colorIndigo = 22
colorDarkGrey = 23
colorDarkRed = 24
colorOrange = 25
colorDarkYellow = 26
colorGreen = 27
colorTeal = 28
colorBlue = 29
colorBlueGrey = 30
colorGrey40 = 31
colorRed = 32
colorLightOrange = 33
colorLime = 34
colorSeaGreen = 35
colorAqua = 35
colorLightBlue = 37
colorViolet = 38
colorGrey50 = 39
colorPink = 40
colorGold = 41
colorYellow = 42
Language structure
535
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
colorBrightGreen = 43
colorTurquoise = 44
colorSkyblue = 45
colorPlum = 46
colorLightGrey = 47
colorRose = 48
colorTan = 49
colorLightYellow = 50
colorPaleGreen = 51
colorPaleTurquoise = 52
colorPaleBlue = 53
colorLavender = 54
colorWhite = 55
graphNbarcolor
(obsolete)
defines the array that holds palette indexes for each
bar drawn
Indicators
graphNstyle
(obsolete)
defines the style of Nth graph. Style is defined as a
combination (sum) of one or more following flags:
Indicators
styleLine = 1 - normal (line) chart (default)
styleHistogram = 2 - histogram chart
styleThick =4 - fat (thick)
styleDots = 8 - include dots
styleNoLine = 16 - no line
styleLog = 32 - semi-logarithmic scale
styleCandle = 64 - candlestick chart
styleBar = 128 - traditional bar chart
styleNoDraw = 256 - no draw (perform axis scaling
only)
styleStaircase = 512 - staircase (square) chart
styleSwingDots = 1024 - middle dots for staircase
chart
styleNoRescale = 2048 - no rescale
styleNoLabel = 4096 - no value label
stylePointAndFigure = 8192 - point and figure
(new in 4.20):
styleArea = 16384 - area chart (extra wide histogram)
styleOwnScale = 32768 - plot is using independent
scaling
styleLeftAxisScale = 65536 - plot is using left axis
scale (independent from right axis)
Not all flag combinations make sense, for example
(64+1) (candlestick + line) will result in
candlestick chart (style=64)
Note on candlestick/bar charts: these styles use
indirectly O, H, L arrays in addition to graphN. So
ordinary candlestick price chart formula is
graph0=close; graph0style=64;.
Language structure
536
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
But if you want to draw something else than close
price you have to assign new values to predefined
O,H,L arrays.
graphNbarcolor
(obsolete)
defines the array of color indexes for the bars and
candlesticks in Nth graph ine (color indexes are
related to the current palette - see
Preferences/Color)
Indicators
SEE ALSO:
• KEYWORDS
• USER-DEFINABLE PROCEDURES, LOCAL/GLOBAL SCOPE
Language structure
537
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
Keywords
The following are keywords in AmiBroker Formula Language:
Loops:
• do (part of do-while statement)
• while
• for
Conditional execution / Flow control:
•
•
•
•
•
•
•
(part of if-else statement)
(part of if-else statement)
switch
break (part of the switch statement or for/while statements)
case (part of the switch statement)
continue (part of for/while statements)
default (part of switch statement)
if
else
Functions:
•
•
•
•
•
function
procedure
return
local (variable scope)
global (variable scope)
Keywords
538
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
break Keyword
The break keyword is a part of switch statement and an optional part of looping
for , do-while and while statements.
The break keyword terminates the smallest enclosing do, for, switch, or while
statement in which it appears.
break;
The break statement is used to exit an iteration or switch statement. It
transfers control to the statement immediately following the iteration
substatement or switch statement.
The break statement terminates only the most tightly enclosing loop or switch
statement. In loops, break is used to terminate before the termination criteria
evaluate to 0. In the switch statement, break is used to terminate sections of
code normally before a case label. The following example illustrates the use of
the break statement in a for loop:
i = 0;
while ( i < 10 )
{
i++;
// break at step 5
if( i == 5 )
{
break;
}
printf("Step " + i );
}
For an example of using the break statement within the body of a switch
statement, see The switch Statement.
Keywords
539
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
case Keyword
The case keyword is an integral part of switch-case statement.
Keywords
540
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
continue Keyword
The continue keyword is an optional part of for , do-while and while statements.
It stops the current iteration of a loop, and starts a new iteration.
continue;
You can use the continue statement only inside a while, do...while, or for loop.
Executing the continue statement stops the current iteration of the loop and
continues program flow with the beginning of the loop. This has the following
effects on the different types of loops:
while and do...while loops test their condition, and if true, execute the loop
again. for loops execute their increment expression, and if the test expression
is true, execute the loop again.
The following example illustrates the use of the continue statement:
i = 0;
while ( i < 10 )
{
i++;
// Skip 5
if( i == 5 )
{
continue;
}
printf("Step " + i );
}
Keywords
541
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
default Keyword
The default keyword is an integral part of switch-case statement.
Keywords
542
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
do Keyword
The do keyword is a part of do-while statement.
do-while Statement
The do-while statement lets you repeat a statement or compound statement until a
specified expression becomes false.
Syntax
do statement while ( expression ) ;
The expression in a do-while statement is evaluated after the body of the loop is
executed. Therefore, the body of the loop is always executed at least once.
The expression must have numeric or boolean type. Execution proceeds as follows:
1. The statement body is executed.
2. Next, expression is evaluated. If expression is false, the do-while
statement terminates and control passes to the next statement in the
program. If expression is true (nonzero), the process is repeated,
beginning with step 1.
This is an example of the do-while statement:
x=100;
do
{
y = sin( x );
x--;
} while ( x > 0 );
In this do-while statement, the two statements y = sin( x ); and x--; are
executed, regardless of the initial value of x. Then x > 0 is evaluated. If x is
greater than 0, the statement body is executed again and x > 0 is reevaluated.
The statement body is executed repeatedly as long as x remains greater than 0.
Execution of the do-while statement terminates when x becomes 0 or negative. The
body of the loop is executed at least once.
Keywords
543
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
else Keyword
The else keyword is an optional part of if-else statement.
if, else Statement
if( expression )
statement1
[else
statement2]
The if keyword executes statement1 if expression is true (nonzero); if else is
present and expression is false (zero), it executes statement2. After executing
statement1 or statement2, control passes to the next statement.
Example 1
if ( i > 0 )
y = x / i;
else
{
x = i;
y = abs( x );
}
In this example, the statement y = x/i; is executed if i is greater than 0. If i
is less than or equal to 0, i is assigned to x and abs( x ) is assigned to y.
Note that the statement forming the if clause ends with a semicolon.
When nesting if statements and else clauses, use braces to group the statements
and clauses into compound statements that clarify your intent. If no braces are
present, the compiler resolves ambiguities by associating each else with the
closest if that lacks an else.
Example 2
if ( i > 0 )
if ( j > i )
x = j;
else
x = i;
/* Without braces */
The else clause is associated with the inner if statement in this example. If i
is less than or equal to 0, no value is assigned to x.
Example 3
if ( i > 0 )
{
/* With braces */
if ( j > i )
x = j;
}
else
x = i;
Keywords
544
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
The braces surrounding the inner if statement in this example make the else
clause part of the outer if statement. If i is less than or equal to 0, i is
assigned to x.
Common misunderstandings
"New if-else problem"
Question:
Why I get the syntax error when I write: if( H > Ref(H,-1) )
Answer:
if-else statement changes flow of execution (opposite to IIF function that
evaluates all arguments and works on arrays) and you can not really write
if ( H >Ref(H,-1) )
because it has no meaning. It would translate to " If high array is higher than
high array shifted one bar" (see tutorial below). Flow control statement (such as
if-else) has to get SINGLE boolean value to make decision which execution path
should be taken. If you write H (or High) it means ARRAY (entire array).
if you write H[ i ] - it means i-th element of the array. The subscript operator
[ ] allows you to access individual array elements.
Instead you should write:
for( i = 1; i
{
if ( High[
{
x[ i ]
}
else
{
x[ i ]
}
}
< BarCount; i++ )
i ] > High[ i - 1 ] )
= High[ i ];
= Low[ i ];
this will translate to correct one "for EVERY BAR ’i’ assign i-th element of high
array to the i-th element of x array if i-th element of high array is higher than
the previous element, otherwise assign i-th of low array to the i-th element of x
array". The rule is: new if-else and while statements need single boolean value
(not array) to decide which execution path should be taken. If you want to use
them with arrays you have to iterate through bars using for loop (as shown
above).
On the other hand this can be implemented in single line using old-style array
operations and IIF function:
Keywords
545
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
x = IIf( High > Ref( High, -1 ), High, Low );
This works because IIF operates on ARRAYS as described in the tutorial.
As you can see in many cases old-style AFL provides much more compact form. I
always tried to explain this advantage of AFL but only a few realised that. New
control statements should be used where it is better to use them. As I tried to
explain during last years in 80% of cases ’old-style’ AFL provides the shortest
formula. Only remaining 20% of cases needed script. Those ’script-only’ cases now
can be coded in native AFL thanks to new for/while/if-else statements. And this
is correct usage of them - to replace script parts.
Keywords
546
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
for Statement
The for statement lets you repeat a statement or compound statement a specified
number of times. The body of a for statement is executed zero or more times until
an optional condition becomes false.
Syntax
for ( init-expression ; cond-expression ; loop-expression ) statement
Execution of a for statement proceeds as follows:
1. The init-expression, is evaluated. This specifies the initialization for
the loop. There is no restriction on the type of init-expression.
2. The cond-expression, is evaluated. This expression must have arithmetic
type. It is evaluated before each iteration. Three results are possible:
• If cond-expression is true (nonzero), statement is executed; then
loop-expression, if any, is evaluated. The loop-expression is
evaluated after each iteration. There is no restriction on its type.
Side effects will execute in order. The process then begins again
with the evaluation of cond-expression.
• If cond-expression is false (0), execution of the for statement
terminates and control passes to the next statement in the program.
This example illustrates the for statement:
myema[ 0 ] = Close[ 0 ];
for( i = 1; i < BarCount; i++ )
{
myema[ i ] = 0.1 * Close[ i ] + 0.9 * myema[ i - 1 ];
}
This example iterates all bars of close array to calculate exponential moving average.
For loop is extremely flexible.
loop-expression can be ANY kind of expression you wish. You can produce not only
regular series like this:
for( i = 0; i < BarCount; i = i + 3 ) // increment by 3 every iteration
but you can produce exponential series too:
for( i = 1; i < BarCount; i = i * 2 ) // produces series of 1, 2, 4, 8, 16, 32,
...
Keywords
547
AmiBroker 5.80 User’s Guide
Keywords
AmiBroker Formula Language (AFL)
548
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
function Keyword
The function keyword begins definition of the user-function.
User-definable functions allow to encapsulate user code into easy-to-use modules
that can be user in many places without need to copy the same code over and over
again.
Functions must have a definition. The function definition includes the function
body the code that executes when the function is called.
A function definition establishes the name, and attributes (or parameters) of a
function. A function definition must precede the call to the function. The
definition starts with function keyword then follows function name, opening
parenthesis then optional list of arguments and closing parenthesis. Later comes
function body enclosed in curly braces.
A function call passes execution control from the calling function to the called
function. The arguments, if any, are passed by value to the called function.
Execution of a return statement in the called function returns control and
possibly a value to the calling function.
If the function does not consist of any return statement (does not return
anything) then we call it a procedure.
Following is an example of function definition:
// the following function is 2nd order smoother
function IIR2( input, f0, f1, f2 )
{
result[ 0 ] = input[ 0 ];
result[ 1 ] = input[ 1 ];
for( i = 2; i < BarCount; i++ )
{
result[ i ] = f0 * input[ i ] +
f1 * result[ i - 1 ] +
f2 * result[ i - 2 ];
}
return result;
}
Plot( Close, "Price", colorBlack, styleCandle );
Plot( IIR2( Close, 0.2, 1.4, -0.6 ), "function example", colorRed );
In this code IIR2 is a user-defined function. input, f0, f1, f2 are formal
parameters of the functions.
At the time of function call the values of arguments are passed in these
Keywords
549
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
variables. Formal parameters behave like local variables.
Later we have result and i which are local variables. Local variables are visible
inside function only. If any other function uses the same variable name they
won’t interfere between each other.
Keywords
550
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
global Keyword
The global keyword declares global variable inside user-defined function. Global
variable is the variable that is visible/accessible inside the function AND
outside the function (at global formula level).
Due to the fact that AFL by default does not require to declare variables the
decision whenever given variable is treated as local or global is taken depends
on where it is FIRST USED.
You can however force AFL engine to require all variables to be declared using
local or global keywords on formula-by-formula basis by placing
SetOption("RequireDeclarations", True ); at the top of the formula.
If given identifier appears first INSIDE function definition - then it is treated
as LOCAL variable.
If given identifier appears first OUTSIDE function definition - then it is
treated as GLOBAL variable.
This default behaviour can be however overriden using global and local keywords
(introduced in 4.36) - see example 2.
Example (commentary):
k = 4; // this is GLOBAL variable
function f( x )
{
z = 3; // this is LOCAL variable
return z * x * k; // ’k’ here references global variable k (first used above
outside function)
}
z = 5; // this is GLOBAL variable with the same name as local variable in
function f
"The value of z before function call :" + WriteVal( z );
//
//
//
//
//
Now even if we call function
the value of our global variable z
is not affected by function call because
global variable z and local variable z are separate and
arguments are passed by value (not by reference)
"The result of f( z ) = " + WriteVal( f( z ) );
"The value of z after function call is unchanged : " + WriteVal( z );
Example 2: Using local and global keywords to override default visibility rules:
VariableA = 5; // implict global variable
Keywords
551
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
function Test()
{
local VariableA; // explicit local variable with the same identifier as
global
global VariableB; // explicit global variable not defined earlier
// may be used to return more than one value from the
function
VariableA = 99;
VariableB = 333;
}
VariableB = 1; // global variable
"Before function call";
"VariableA = " + VariableA;
"VariableB = " + VariableB;
Test();
"After function call";
"VariableA = " + VariableA + " (not affected by function call )";
"VariableB = " + VariableB + " (affected by the function call )"
Keywords
552
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
if Keyword
The if keyword is an required part of if-else statement.
if, else Statement
if( expression )
statement1
[else
statement2]
The if keyword executes statement1 if expression is true (nonzero); if else is
present and expression is false (zero), it executes statement2. After executing
statement1 or statement2, control passes to the next statement.
Example 1
if ( i > 0 )
y = x / i;
else
{
x = i;
y = abs( x );
}
In this example, the statement y = x/i; is executed if i is greater than 0. If i
is less than or equal to 0, i is assigned to x and abs( x ) is assigned to y.
Note that the statement forming the if clause ends with a semicolon.
When nesting if statements and else clauses, use braces to group the statements
and clauses into compound statements that clarify your intent. If no braces are
present, the compiler resolves ambiguities by associating each else with the
closest if that lacks an else.
Example 2
if ( i > 0 )
if ( j > i )
x = j;
else
x = i;
/* Without braces */
The else clause is associated with the inner if statement in this example. If i
is less than or equal to 0, no value is assigned to x.
Example 3
if ( i > 0 )
{
/* With braces */
if ( j > i )
x = j;
}
else
x = i;
Keywords
553
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
The braces surrounding the inner if statement in this example make the else
clause part of the outer if statement. If i is less than or equal to 0, i is
assigned to x.
Common misunderstandings
"New if-else problem"
Question:
Why I get the syntax error when I write: if( H > Ref(H,-1) )
Answer:
if-else statement changes flow of execution (opposite to IIF function that
evaluates all arguments and works on arrays) and you can not really write
if ( H >Ref(H,-1) )
because it has no meaning. It would translate to " If high array is higher than
high array shifted one bar" (see tutorial below). Flow control statement (such as
if-else) has to get SINGLE boolean value to make decision which execution path
should be taken. If you write H (or High) it means ARRAY (entire array).
if you write H[ i ] - it means i-th element of the array. The subscript operator
[ ] allows you to access individual array elements.
Instead you should write:
for( i = 1; i
{
if ( High[
{
x[ i ]
}
else
{
x[ i ]
}
}
< BarCount; i++ )
i ] > High[ i - 1 ] )
= High[ i ];
= Low[ i ];
this will translate to correct one "for EVERY BAR ’i’ assign i-th element of high
array to the i-th element of x array if i-th element of high array is higher than
the previous element, otherwise assign i-th of low array to the i-th element of x
array". The rule is: new if-else and while statements need single boolean value
(not array) to decide which execution path should be taken. If you want to use
them with arrays you have to iterate through bars using for loop (as shown
above).
On the other hand this can be implemented in single line using old-style array
operations and IIF function:
Keywords
554
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
x = IIf( High > Ref( High, -1 ), High, Low );
This works because IIF operates on ARRAYS as described in the tutorial.
As you can see in many cases old-style AFL provides much more compact form. I
always tried to explain this advantage of AFL but only a few realised that. New
control statements should be used where it is better to use them. As I tried to
explain during last years in 80% of cases ’old-style’ AFL provides the shortest
formula. Only remaining 20% of cases needed script. Those ’script-only’ cases now
can be coded in native AFL thanks to new for/while/if-else statements. And this
is correct usage of them - to replace script parts.
Keywords
555
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
local Keyword
The local keyword declares local variable inside user-defined function. Local
variable is the variable that is visible/accessible only inside the function.
Due to the fact that AFL by default does not require to declare variables the
decision whenever given variable is treated as local or global is taken depends
on where it is FIRST USED.
You can however force AFL engine to require all variables to be declared using
local or global keywords on formula-by-formula basis by placing
SetOption("RequireDeclarations", True ); at the top of the formula.
If given identifier appears first INSIDE function definition - then it is treated
as LOCAL variable.
If given identifier appears first OUTSIDE function definition - then it is
treated as GLOBAL variable.
This default behaviour can be however overriden using global and local keywords
(introduced in 4.36) - see example 2.
Example (commentary):
k = 4; // this is GLOBAL variable
function f( x )
{
z = 3; // this is LOCAL variable
return z * x * k; // ’k’ here references global variable k (first used above
outside function)
}
z = 5; // this is GLOBAL variable with the same name as local variable in
function f
"The value of z before function call :" + WriteVal( z );
//
//
//
//
//
Now even if we call function
the value of our global variable z
is not affected by function call because
global variable z and local variable z are separate and
arguments are passed by value (not by reference)
"The result of f( z ) = " + WriteVal( f( z ) );
"The value of z after function call is unchanged : " + WriteVal( z );
Example 2: Using local and global keywords to override default visibility rules:
VariableA = 5; // implict global variable
Keywords
556
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
function Test()
{
local VariableA; // explicit local variable with the same identifier as
global
global VariableB; // explicit global variable not defined earlier
// may be used to return more than one value from the
function
VariableA = 99;
VariableB = 333;
}
VariableB = 1; // global variable
"Before function call";
"VariableA = " + VariableA;
"VariableB = " + VariableB;
Test();
"After function call";
"VariableA = " + VariableA + " (not affected by function call )";
"VariableB = " + VariableB + " (affected by the function call )"
Keywords
557
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
procedure Keyword
The procedure keyword begins definition of the user-procedure.
Procedure is a function that does NOT return any value (does not have return
statement).
Consult function keyword help for more details.
Keywords
558
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
return Keyword
The return keyword allows to return the value from the function.
function RiseToAPowerOf2( x )
{
return x ^ 2;
}
At the end of the function we can see ’return’ statement that is used to return
the result to the caller. Note that currently return statement must be placed at
the very end of the function.
Consult function keyword help for more details.
Keywords
559
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
switch Statement
The switch and case statements help control complex conditional and branching
operations. The switch statement transfers control to a statement within its
body.
Syntax:
switch ( expression )
{
case constant-expression1 : statement;
case constant-expression2 : statement;
...
case constant-expressionN : statement;
default : statement;
}
Control passes to the statement whose case constant-expression matches the value
of switch ( expression ). The switch statement can include any number of case
instances, but no two case constants within the same switch statement can have
the same value. Execution of the statement body begins at the selected statement
and proceeds until the end of the body or until a break statement transfers
control out of the body.
You can use the break statement to end processing of a particular case within the
switch statement and to branch to the end of the switch statement. Without break,
the program continues to the next case, executing the statements until a break or
the end of the statement is reached. In some situations, this continuation may be
desirable.
The default statement is executed if no case constant-expression is equal to the
value of switch ( expression ). If the default statement is omitted, and no case
match is found, none of the statements in the switch body are executed. There can
be at most one default statement. The default statement, if exists, MUST come at
the end. Otherwise it may be executed before hitting conditions defined below it.
A case or default label is allowed to appear only inside a switch statement.
The type of switch expression and case constant-expression can be any. The value
of each case constant-expression must be unique within the statement body.
Otherwise first-match will be used.
Example:
for( n = 0; n < 10; n++ )
{
printf("Current n = %f\n", n );
switch(n) {
Keywords
560
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
case 0:
printf("The number is zero.\n");
break;
case 3:
case 5:
case 7:
printf("n is a prime number\n");
break;
case 2: printf("n is a prime number\n");
case 4:
case 6:
case 8:
printf("n is an even number\n");
break;
case 1:
case 9:
printf("n is a perfect square\n");
break;
default:
printf("Only single-digit numbers are allowed\n");
break;
}
More information can be found here: http://en.wikipedia.org/wiki/Switch_statement
Keywords
561
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
while Keyword
The while keyword is al part of while (described below) and do-while statements.
while Statement
The while statement lets you repeat a statement until a specified expression
becomes false.
Syntax
while ( expression ) statement
The expression must have arithmetic (numeric/boolean) type. Execution proceeds as
follows:
1. The expression is evaluated.
2. If expression is initially false, the body of the while statement is never
executed, and control passes from the while statement to the next statement
in the program.
If expression is true (nonzero), the body of the statement is executed and
the process is repeated beginning at step 1.
This is an example of the while statement:
i = 10;
while( i < 20 )
{
Plot( MA( Close, i ), "MA" + WriteVal( i, 0 ), colorBlack + i );
i = i + 1;
}
The example plots 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 - bar moving averages.
AFL Function Reference - Alphabetical list of functions
1. #include ( Miscellaneous functions) - preprocessor include command (AFL
2.2)
2. #include_once ( Miscellaneous functions) - preprocessor include (once)
command (AFL 2.70)
3. #pragma ( Miscellaneous functions) - sets AFL pre-processor option (AFL
2.4)
4. abs ( Math functions) - absolute value
5. AccDist ( Indicators) - accumulation/distribution
6. acos ( Math functions) - arccosine function
Keywords
562
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
7. AddColumn (Exploration / Indicators) - add numeric exploration column (AFL
1.8)
8. AddRankColumn (Exploration / Indicators) - add ranking column(s) according
to current sort set by SetSortColumns (AFL 5.70)
9. AddSummaryRows (Exploration / Indicators) - add summary row(s) to the
exploration output (AFL 3.2)
10. AddTextColumn (Exploration / Indicators) - add text exploration column (AFL
1.8)
11. AddToComposite ( Composites) - add value to composite ticker (AFL 2.0)
12. ADLine ( Composites) - advance/decline line (AFL 1.2)
13. AdvIssues ( Composites) - advancing issues (AFL 1.2)
14. AdvVolume ( Composites) - advancing issues volume (AFL 1.2)
15. ADX ( Indicators) - average directional movement index (AFL 1.3)
16. AlertIf ( Trading system toolbox) - trigger alerts (AFL 2.1)
17. AlmostEqual ( Math functions) - rounding error insensitive comparison (AFL
2.80)
18. AMA ( Moving averages, summation) - adaptive moving average (AFL 1.5)
19. AMA2 ( Moving averages, summation) - adaptive moving average (AFL 1.5)
20. ApplyStop ( Trading system toolbox) - apply built-in stop (AFL 1.7)
21. Asc ( String manipulation) - get ASCII code of character (AFL 2.80)
22. asin ( Math functions) - arcsine function
23. atan ( Math functions) - arc tan
24. atan2 ( Math functions) - calculates arctangent of y/x (AFL 2.90)
25. ATR ( Indicators) - average true range (AFL 1.3)
26. BarIndex ( Date/Time) - get zero-based bar number (AFL 2.3)
27. BarsSince ( Trading system toolbox) - bars since
28. BBandBot ( Indicators) - bottom bollinger band
29. BBandTop ( Indicators) - top bollinger band
30. BeginValue ( Date/Time) - Value of the array at the begin of the range (AFL
2.3)
31. CategoryAddSymbol ( Information / Categories) - adds a symbol to a category
(AFL 2.5)
32. CategoryCreate ( Information / Categories) - add new category (such as
watch list) (AFL 3.70)
33. CategoryFind ( Information / Categories) - search for category by name (AFL
3.0)
34. CategoryGetName ( Information / Categories) - get the name of a category
(AFL 2.5)
35. CategoryGetSymbols ( Information / Categories) - retrieves comma-separated
list of symbols belonging to given category (AFL 2.5)
36. CategoryRemoveSymbol ( Information / Categories) - remove a symbol from a
category (AFL 2.5)
37. CategorySetName ( Information / Categories) - set the name of category
(group, market, watch list, industry) (AFL 3.20)
38. CCI ( Indicators) - commodity channel index
39. ceil ( Math functions) - ceil value
40. Chaikin ( Indicators) - chaikin oscillator
41. ClipboardGet ( Miscellaneous functions) - retrieves current contents of
Windows clipboard (AFL 2.60)
42. ClipboardSet ( Miscellaneous functions) - copies the text to the Windows
clipboard (AFL 2.6)
43. ColorBlend ( Indicators) - blends (mixes) two colors (AFL 3.30)
Keywords
563
AmiBroker 5.80 User’s Guide
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
AmiBroker Formula Language (AFL)
ColorHSB ( Miscellaneous functions) - specify color using
Hue-Saturation-Brightness (AFL 2.80)
ColorRGB ( Miscellaneous functions) - specify color using Red-Green-Blue
components (AFL 2.80)
Correlation ( Statistical functions) - correlation (AFL 1.4)
cos ( Math functions) - cosine
cosh ( Math functions) - hyperbolic cosine function (AFL 2.80)
CreateObject ( Miscellaneous functions) - create COM object (AFL 1.8)
CreateStaticObject ( Miscellaneous functions) - create static COM object
(AFL 1.8)
Cross ( Trading system toolbox) - crossover check
Cum ( Moving averages, summation) - cumulative sum
Date ( Date/Time) - date (AFL 1.1)
DateNum ( Date/Time) - date number (AFL 1.4)
DateTime ( Date/Time) - retrieves encoded date time (AFL 2.3)
DateTimeAdd ( Date/Time) - adds specified number of
seconds/minutes/hours/days to datetime (AFL 3.40)
DateTimeConvert ( Date/Time) - date/time format conversion (AFL 2.90)
DateTimeDiff ( Date/Time) - get difference in seconds between two datetime
values (AFL 3.30)
DateTimeToStr ( String manipulation) - convert datetime to string (AFL 2.8)
Day ( Date/Time) - day of month (AFL 1.4)
DayOfWeek ( Date/Time) - day of week (AFL 1.4)
DayOfYear ( Date/Time) - get ordinal number of day in a year (AFL 2.4)
DaysSince1900 ( Date/Time) - get number of days since January 1st, 1900
(AFL 3.20)
DecIssues ( Composites) - declining issues (AFL 1.2)
DecVolume ( Composites) - declining issues volume (AFL 1.2)
DEMA ( Moving averages, summation) - double exponential moving average (AFL
2.0)
EMA ( Moving averages, summation) - exponential moving average
EnableRotationalTrading ( Trading system toolbox) - Turns on
rotational-trading mode of the backtester (AFL 2.5)
EnableScript ( Miscellaneous functions) - enable scripting engine
EnableTextOutput ( Miscellaneous functions) - enables/disables text output
in the Chart Commentary window (AFL 2.2)
EncodeColor (Exploration / Indicators) - encodes color for indicator title
(AFL 2.2)
EndValue ( Date/Time) - value of the array at the end of the selected range
(AFL 2.3)
Equity ( Trading system toolbox) - calculate single-symbol equity line (AFL
2.0)
Error ( Miscellaneous functions) - displays user-defined error message and
stops the execution (AFL 3.7)
EXP ( Math functions) - exponential function
ExRem ( Trading system toolbox) - remove excessive signals (AFL 1.5)
ExRemSpan ( Trading system toolbox) - remove excessive signals spanning
given number of bars (AFL 2.0)
fclose (File Input/Output functions) - close a file (AFL 2.5)
fdelete (File Input/Output functions) - deletes a file (AFL 2.70)
fdir (File Input/Output functions) - list directory content (AFL 3.70)
feof (File Input/Output functions) - test for end-of-file (AFL 2.5)
Keywords
564
AmiBroker 5.80 User’s Guide
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
AmiBroker Formula Language (AFL)
FFT ( Basic price pattern detection) - performs Fast Fourier Transform (AFL
2.90)
fgets (File Input/Output functions) - get a string from a file (AFL 2.5)
fgetstatus (File Input/Output functions) - retrieves file status/properties
(AFL 2.90)
FIR ( Moving averages, summation) - Finite Impulse Response filter (AFL
3.40)
FirstVisibleValue ( Indicators) - get first visible value of array (AFL
3.40)
Flip ( Trading system toolbox) - (AFL 1.5)
floor ( Math functions) - floor value
fmkdir (File Input/Output functions) - creates (makes) a directory (AFL
2.70)
fopen (File Input/Output functions) - open a file (AFL 2.5)
Foreign (Referencing other symbol data) - access foreign security data (AFL
1.5)
fputs (File Input/Output functions) - write a string to a file (AFL 2.5)
frac ( Math functions) - fractional part
frmdir (File Input/Output functions) - removes a directory (AFL 2.70)
FullName ( Information / Categories) - full name of the symbol (AFL 1.1)
GapDown ( Basic price pattern detection) - gap down
GapUp ( Basic price pattern detection) - gap up
GetAsyncKeyState ( Miscellaneous functions) - query the current state of
keyboard keys (AFL 3.60)
GetBacktesterObject ( Trading system toolbox) - get the access to
backtester object (AFL 2.60)
GetBaseIndex (Referencing other symbol data) - retrieves symbol of relative
strength base index (AFL 2.1)
GetCategorySymbols ( Information / Categories) - retrieves comma-separated
list of symbols belonging to given category (AFL 2.4)
GetChartBkColor ( Indicators) - get the RGB color value of chart background
(AFL 3.20)
GetChartID (Exploration / Indicators) - get current chart ID (AFL 2.3)
GetCursorMouseButtons ( Indicators) - get current state of mouse buttons
(AFL 2.80)
GetCursorXPosition ( Indicators) - get current X position of mouse pointer
(AFL 2.80)
GetCursorYPosition ( Indicators) - get current Y position of mouse pointer
(AFL 2.80)
GetDatabaseName ( Information / Categories) - retrieves folder name of
current database (AFL 2.3)
GetExtraData ( Miscellaneous functions) - get extra data from external data
source (AFL 1.9)
GetFnData ( Information / Categories) - get fundamental data (AFL 2.90)
GetOption ( Trading system toolbox) - gets the value of option in automatic
analysis settings (AFL 2.60)
GetPerformanceCounter ( Miscellaneous functions) - retrieves the current
value of the high-resolution performance counter (AFL 2.90)
GetPlaybackDateTime ( Date/Time) - get bar replay position date/time (AFL
3.0)
GetPriceStyle (Exploration / Indicators) - get current price chart style
(AFL 2.70)
Keywords
565
AmiBroker 5.80 User’s Guide
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
AmiBroker Formula Language (AFL)
GetRTData ( Miscellaneous functions) - retrieves the real-time data fields
(AFL 2.60)
GetRTDataForeign ( Miscellaneous functions) - retrieves the real-time data
fields (for specified symbol) (AFL 2.80)
GetScriptObject ( Miscellaneous functions) - get access to script COM
object (AFL 1.8)
GetTradingInterface ( Trading system toolbox) - retrieves OLE automation
object to automatic trading interfac (AFL 2.70)
GfxArc (Low-level graphics) - draw an arc (AFL 3.0)
GfxChord (Low-level graphics) - draw a chord (AFL 3.0)
GfxCircle (Low-level graphics) - draw a circle (AFL 3.0)
GfxDrawText (Low-level graphics) - draw a text (clipped to rectangle) (AFL
3.0)
GfxEllipse (Low-level graphics) - draw an ellipse (AFL 3.0)
GfxGetTextWidth (Low-level graphics) - get pixel width of text (AFL 2.80)
GfxGradientRect (Low-level graphics) - draw a rectangle with gradient fill
(AFL 3.0)
GfxLineTo (Low-level graphics) - draw a line to specified point (AFL 3.0)
GfxMoveTo (Low-level graphics) - move graphic cursor to new position (AFL
3.0)
GfxPie (Low-level graphics) - draw a pie (AFL 3.0)
GfxPolygon (Low-level graphics) - draw a polygon (AFL 3.0)
GfxPolyline (Low-level graphics) - draw a polyline (AFL 3.0)
GfxRectangle (Low-level graphics) - draw a rectangle (AFL 3.0)
GfxRoundRect (Low-level graphics) - draw a rectangle with rounded corners
(AFL 3.0)
GfxSelectFont (Low-level graphics) - create / select graphic font (AFL 3.0)
GfxSelectPen (Low-level graphics) - create / select graphic pen (AFL 3.0)
GfxSelectSolidBrush (Low-level graphics) - create / select graphic brush
(AFL 3.0)
GfxSetBkColor (Low-level graphics) - set graphic background color (AFL 3.0)
GfxSetBkMode (Low-level graphics) - set graphic background mode (AFL 3.0)
GfxSetCoordsMode (Low-level graphics) - set low-level graphics co-ordinate
mode (AFL 2.80)
GfxSetOverlayMode (Low-level graphics) - set low-level graphic overlay mode
(AFL 3.0)
GfxSetPixel (Low-level graphics) - set pixel at specified position to
specified color (AFL 3.0)
GfxSetTextAlign (Low-level graphics) - set text alignment (AFL 3.0)
GfxSetTextColor (Low-level graphics) - set graphic text color (AFL 3.0)
GfxSetZOrder (Low-level graphics) - set current low-level graphic Z-order
layer (AFL 2.80)
GfxTextOut (Low-level graphics) - writes text at the specified location
(AFL 3.0)
GicsID ( Information / Categories) - get GICS category information (AFL
3.40)
GroupID ( Information / Categories) - get group ID/name (AFL 1.8)
HHV ( Lowest/Highest) - highest high value
HHVBars ( Lowest/Highest) - bars since highest high
Highest ( Lowest/Highest) - highest value
HighestBars ( Lowest/Highest) - bars since highest value
Keywords
566
AmiBroker 5.80 User’s Guide
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
AmiBroker Formula Language (AFL)
HighestSince ( Lowest/Highest) - highest value since condition met (AFL
1.4)
HighestSinceBars ( Lowest/Highest) - bars since highest value since
condition met (AFL 1.4)
HighestVisibleValue ( Indicators) - get the highest value within visible
chart area (AFL 3.30)
HMA ( Moving averages, summation) - Hull Moving Average (AFL 3.40)
Hold ( Trading system toolbox) - hold the alert signal
Hour ( Date/Time) - get current bar’s hour (AFL 2.0)
IcbID ( Information / Categories) - get ICB category information (AFL 3.60)
IIf ( Trading system toolbox) - immediate IF function
IndustryID ( Information / Categories) - get industry ID / name (AFL 1.8)
InGICS ( Information / Categories) - test GICS membership (AFL 3.40)
InICB ( Information / Categories) - test ICB membership (AFL 3.60)
Inside ( Basic price pattern detection) - inside day
Int ( Math functions) - integer part
Interval ( Date/Time) - get bar interval (in seconds) (AFL 2.1)
InWatchList ( Information / Categories) - watch list membership test (by
ordinal number)
InWatchListName ( Information / Categories) - watch list membership test
(by name) (AFL 3.0)
IsContinuous ( Information / Categories) - checks ’continuous quotations’
flag state (AFL 2.60)
IsEmpty ( Miscellaneous functions) - empty value check (AFL 1.5)
IsFavorite ( Information / Categories) - check if current symbol belongs to
favorites (AFL 2.5)
IsFinite ( Miscellaneous functions) - check if value is not infinite (AFL
2.3)
IsIndex ( Information / Categories) - check if current symbol is an index
(AFL 2.5)
IsNan ( Miscellaneous functions) - checks for NaN (not a number) (AFL 2.3)
IsNull ( Miscellaneous functions) - check for Null (empty) value (AFL 2.3)
IsTrue ( Miscellaneous functions) - true value (non-empty and non-zero)
check (AFL 1.5)
LastValue ( Trading system toolbox) - last value of the array
LastVisibleValue ( Indicators) - get last visible value of array (AFL 3.40)
LineArray (Exploration / Indicators) - generate trend-line array (AFL 2.5)
LinearReg ( Statistical functions) - linear regression end-point (AFL 2.2)
LinRegIntercept ( Statistical functions) - (AFL 2.2)
LinRegSlope ( Statistical functions) - linear regression slope (AFL 1.4)
LLV ( Lowest/Highest) - lowest low value
LLVBars ( Lowest/Highest) - bars since lowest low
log ( Math functions) - natural logarithm
log10 ( Math functions) - decimal logarithm
Lookup ( Date/Time) - search the array for bar with specified date/time
(AFL 3.40)
Lowest ( Lowest/Highest) - lowest value
LowestBars ( Lowest/Highest) - bars since lowest
LowestSince ( Lowest/Highest) - lowest value since condition met (AFL 1.4)
LowestSinceBars ( Lowest/Highest) - barssince lowest value since condition
met (AFL 1.4)
Keywords
567
AmiBroker 5.80 User’s Guide
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
217.
218.
219.
220.
221.
222.
223.
224.
225.
AmiBroker Formula Language (AFL)
LowestVisibleValue ( Indicators) - get the lowest value within visible
chart area (AFL 3.30)
MA ( Moving averages, summation) - simple moving average
MACD ( Indicators) - moving average convergence/divergence
MarketID ( Information / Categories) - market ID / name (AFL 1.8)
Max ( Math functions) - maximum value of two numbers / arrays
MDI ( Indicators) - minus directional movement indicator (-DI) (AFL 1.3)
Median ( Statistical functions) - calculate median (middle element) (AFL
2.5)
MFI ( Indicators) - money flow index
MicroSec ( Date/Time) - get bar’s microsecond part of the timestamp
MilliSec ( Date/Time) - get bar’s millisecond part of the timestamp
Min ( Math functions) - minimum value of two numbers / arrays
Minute ( Date/Time) - get current bar’s minute (AFL 2.0)
Month ( Date/Time) - month (AFL 1.4)
mtRandom ( Statistical functions) - Mersene Twister random number generator
(AFL 3.0)
mtRandomA ( Statistical functions) - Mersene Twister random number
generator (array version) (AFL 3.0)
Name ( Information / Categories) - ticker symbol (AFL 1.1)
NoteGet ( Miscellaneous functions) - retrieves the text of the note (AFL
2.6)
NoteSet ( Miscellaneous functions) - sets text of the note (AFL 2.6)
Now ( Date/Time) - gets current system date/time (AFL 2.3)
NumToStr ( String manipulation) - convert number to string (AFL 2.5)
NVI ( Indicators) - negative volume index
Nz ( Miscellaneous functions) - Null (Null/Nan/Infinity) to zero (AFL 2.3)
OBV ( Indicators) - on balance volume
Optimize ( Trading system toolbox) - define optimization variable (AFL 1.7)
OptimizerSetEngine ( Trading system toolbox) - select external optimization
engine (AFL 3.20)
OptimizerSetOption ( Trading system toolbox) - set the value of external
optimizer engine parameter (AFL 3.20)
OscP ( Indicators) - price oscillator
OscV ( Indicators) - volume oscillator
Outside ( Basic price pattern detection) - outside bar
Param (Exploration / Indicators) - add user user-definable numeric
parameter (AFL 2.3)
ParamColor (Exploration / Indicators) - add user user-definable color
parameter (AFL 2.3)
ParamDate (Exploration / Indicators) - add user user-definable date
parameter (AFL 2.60)
ParamField (Exploration / Indicators) - creates price field parameter (AFL
2.70)
ParamList (Exploration / Indicators) - creates the parameter that consist
of the list of choices (AFL 2.70)
ParamStr (Exploration / Indicators) - add user user-definable string
parameter (AFL 2.3)
ParamStyle (Exploration / Indicators) - select styles applied to the plot
(AFL 2.70)
ParamTime (Exploration / Indicators) - add user user-definable time
parameter (AFL 2.60)
Keywords
568
AmiBroker 5.80 User’s Guide
226.
227.
228.
229.
230.
231.
232.
233.
234.
235.
236.
237.
238.
239.
240.
241.
242.
243.
244.
245.
246.
247.
248.
249.
250.
251.
252.
253.
254.
255.
256.
257.
258.
259.
260.
261.
262.
263.
264.
AmiBroker Formula Language (AFL)
ParamToggle (Exploration / Indicators) - create Yes/No parameter (AFL 2.70)
ParamTrigger (Exploration / Indicators) - creates a trigger (button) in the
parameter dialog (AFL 2.70)
PDI ( Indicators) - plus directional movement indicator (AFL 1.3)
Peak ( Basic price pattern detection) - peak (AFL 1.1)
PeakBars ( Basic price pattern detection) - bars since peak (AFL 1.1)
Percentile ( Statistical functions) - calculate percentile (AFL 2.5)
PercentRank ( Indicators) - calculate percent rank (AFL 3.40)
PlaySound ( Miscellaneous functions) - play back specified .WAV file (AFL
3.40)
Plot (Exploration / Indicators) - plot indicator graph (AFL 1.8)
PlotForeign (Referencing other symbol data) - plot foreign security data
(AFL 2.2)
PlotGrid (Exploration / Indicators) - Plot horizontal grid line (AFL 2.3)
PlotOHLC (Exploration / Indicators) - plot custom OHLC chart (AFL 2.2)
PlotShapes (Exploration / Indicators) - plots arrows and other shapes (AFL
2.3)
PlotText ( Indicators) - write text on the chart (AFL 2.80)
PlotTextSetFont ( Basic price pattern detection) - write text on the chart
with user-defined font (AFL 2.80)
PlotVAPOverlay (Exploration / Indicators) - plot Volume-At-Price overlay
chart (AFL 2.4)
PlotVAPOverlayA ( Indicators) - plot multiple-segment Volume-At-Price chart
(AFL 3.20)
PopupWindow ( Miscellaneous functions) - display pop-up window (AFL 3.0)
Prec ( Math functions) - adjust number of decimal points of floating point
number
Prefs ( Miscellaneous functions) - retrieve preferences settings (AFL 1.4)
printf ( String manipulation) - Print formatted output to the output
window. (AFL 2.5)
PVI ( Indicators) - positive volume index
Random ( Statistical functions) - random number (AFL 1.9)
Ref ( Trading system toolbox) - reference past/future values of the array
RelStrength (Referencing other symbol data) - comparative relative strength
(AFL 1.3)
RequestTimedRefresh ( Indicators) - forces periodical refresh of indicator
pane (AFL 2.90)
RestorePriceArrays (Referencing other symbol data) - restore price arrays
to original symbol (AFL 2.5)
RMI ( Indicators) - Relative Momentum Index (AFL 2.1)
ROC ( Indicators) - percentage rate of change
Round ( Math functions) - round number to nearest integer
RSI ( Indicators) - relative strength index
RWI ( Indicators) - random walk index
RWIHi ( Indicators) - random walk index of highs
RWILo ( Indicators) - random walk index of lows
SAR ( Indicators) - parabolic stop-and-reverse (AFL 1.3)
Say ( Miscellaneous functions) - speaks provided text (AFL 2.90)
Second ( Date/Time) - get current bar’s second (AFL 2.0)
SectorID ( Information / Categories) - get sector ID / name (AFL 1.8)
SelectedValue (Exploration / Indicators) - retrieves value of the array at
currently selected date/time point (AFL 2.1)
Keywords
569
AmiBroker 5.80 User’s Guide
265.
266.
267.
268.
269.
270.
271.
272.
273.
274.
275.
276.
277.
278.
279.
280.
281.
282.
283.
284.
285.
286.
287.
288.
289.
290.
291.
292.
293.
294.
AmiBroker Formula Language (AFL)
SetBacktestMode ( Trading system toolbox) - Sets working mode of the
backtester (AFL 3.0)
SetBarFillColor ( Indicators) - set bar/candlestick/cloud chart fill color
(AFL 3.1)
SetBarsRequired ( Miscellaneous functions) - set number of previous and
future bars needed for script/DLL to properly execute (AFL 2.1)
SetChartBkColor ( Indicators) - set background color of a chart (AFL 2.80)
SetChartBkGradientFill ( Indicators) - enables background gradient color
fill in indicators (AFL 2.90)
SetChartOptions (Exploration / Indicators) - set/clear/overwrite defaults
for chart pane options (AFL 2.70)
SetCustomBacktestProc ( Trading system toolbox) - define custom backtest
procedure formula file (AFL 2.70)
SetForeign (Referencing other symbol data) - replace current price arrays
with those of foreign security (AFL 2.5)
SetFormulaName ( Trading system toolbox) - set the name of the formula (AFL
2.5)
SetGradientFill ( Indicators) - set the colors of a gradient fill plot (AFL
3.60)
SetOption ( Trading system toolbox) - sets options in automatic analysis
settings (AFL 2.3)
SetPositionSize ( Trading system toolbox) - set trade size (AFL 2.70)
SetSortColumns (Exploration / Indicators) - sets the columns which will be
used for sorting in AA window (AFL 2.90)
SetTradeDelays ( Trading system toolbox) - allows to control trade delays
applied by the backtester (AFL 2.1)
ShellExecute ( Basic price pattern detection) - execute a file (AFL 3.40)
sign ( Math functions) - returns the sign of the number/array (AFL 2.50)
Signal ( Indicators) - macd signal line
sin ( Math functions) - sine function
sinh ( Math functions) - hyperbolic sine function (AFL 2.80)
sqrt ( Math functions) - square root
StaticVarCompareExchange ( Miscellaneous functions) - atomic interlocked
static variable compare-exchange operation (AFL 3.50)
StaticVarCount ( Miscellaneous functions) - get the total number of static
variables in memory (AFL 3.30)
StaticVarGenerateRanks ( Miscellaneous functions) - generate ranking of
multiple symbols and store it to static variables (AFL 3.70)
StaticVarGet ( Miscellaneous functions) - gets the value of static variable
(AFL 2.60)
StaticVarGetRankedSymbols ( Miscellaneous functions) - retrieve a list of
ranked symbols from static variables (AFL 3.70)
StaticVarGetText ( Miscellaneous functions) - gets the value of static
variable as string (AFL 2.60)
StaticVarInfo ( Miscellaneous functions) - get the information about static
variable(s) (AFL 3.60)
StaticVarRemove ( Miscellaneous functions) - remove static variable (AFL
2.80)
StaticVarSet ( Miscellaneous functions) - sets the value of static variable
(AFL 2.60)
StaticVarSetText ( Miscellaneous functions) - Sets the value of static
string variable. (AFL 2.60)
Keywords
570
AmiBroker 5.80 User’s Guide
295.
296.
297.
298.
299.
300.
301.
302.
303.
304.
305.
306.
307.
308.
309.
310.
311.
312.
313.
314.
315.
316.
317.
318.
319.
320.
321.
322.
323.
324.
325.
326.
327.
328.
329.
330.
331.
332.
AmiBroker Formula Language (AFL)
Status ( Miscellaneous functions) - get run-time AFL status information
(AFL 1.65)
StdErr ( Statistical functions) - standard error (AFL 1.4)
StDev ( Statistical functions) - standard deviation (AFL 1.4)
StochD ( Indicators) - stochastic slow %D
StochK ( Indicators) - stochastic slow %K
StrCount ( String manipulation) - count the occurrences of substring within
a string (AFL 3.20)
StrExtract ( String manipulation) - extracts given item (substring) from
comma-separated string (AFL 2.4)
StrFind ( String manipulation) - find substring in a string (AFL 2.5)
StrFormat ( String manipulation) - Write formatted output to the string
(AFL 2.5)
StrLeft ( String manipulation) - extracts the leftmost part (AFL 2.0)
StrLen ( String manipulation) - string length (AFL 1.5)
StrMid ( String manipulation) - extracts part of the string (AFL 2.0)
StrReplace ( String manipulation) - string replace (AFL 2.90)
StrRight ( String manipulation) - extracts the rightmost part of the string
(AFL 2.0)
StrToDateTime ( String manipulation) - convert string to datetime (AFL
2.80)
StrToLower ( String manipulation) - convert to lowercase (AFL 2.80)
StrToNum ( String manipulation) - convert string to number (AFL 2.5)
StrToUpper ( String manipulation) - convert to uppercase (AFL 2.80)
Study ( Miscellaneous functions) - reference hand-drawn study (AFL 1.5)
Sum ( Moving averages, summation) - sum data over specified number of bars
tan ( Math functions) - tangent function (AFL 1.0)
tanh ( Math functions) - hyperbolic tangent function (AFL 2.80)
TEMA ( Moving averages, summation) - triple exponential moving average (AFL
2.0)
ThreadSleep ( Miscellaneous functions) - suspend thread for specified
number of milliseconds (AFL 3.50)
TimeFrameCompress (Time Frame functions) - compress single array to given
time frame (AFL 2.5)
TimeFrameExpand (Time Frame functions) - expand time frame compressed array
(AFL 2.5)
TimeFrameGetPrice (Time Frame functions) - retrieve O, H, L, C, V values
from other time frame (AFL 2.5)
TimeFrameMode (Time Frame functions) - switch time frame compression mode
(AFL 2.80)
TimeFrameRestore (Time Frame functions) - restores price arrays to original
time frame (AFL 2.5)
TimeFrameSet (Time Frame functions) - switch price arrays to a different
time frame (AFL 2.5)
TimeNum ( Date/Time) - get current bar time (AFL 2.0)
Trin ( Composites) - traders (Arms) index (AFL 1.2)
TRIX ( Indicators) - triple exponential smoothed price
Trough ( Basic price pattern detection) - trough (AFL 1.1)
TroughBars ( Basic price pattern detection) - bars since trough (AFL 1.1)
TSF ( Statistical functions) - time series forecast (AFL 2.2)
Ultimate ( Indicators) - ultimate oscillator
UncIssues ( Composites) - unchanged issues (AFL 1.2)
Keywords
571
AmiBroker 5.80 User’s Guide
333.
334.
335.
336.
337.
338.
339.
340.
341.
342.
343.
344.
345.
346.
347.
348.
349.
350.
351.
352.
353.
354.
355.
AmiBroker Formula Language (AFL)
UncVolume ( Composites) - unchaged issues volume (AFL 1.2)
ValueWhen ( Trading system toolbox) - get value of the array when condition
met (AFL 1.1)
VarGet ( Miscellaneous functions) - gets the value of dynamic variable (AFL
2.60)
VarGetText ( Miscellaneous functions) - gets the text value of dynamic
variable (AFL 2.80)
VarSet ( Miscellaneous functions) - sets the value of dynamic variable (AFL
2.60)
VarSetText ( Miscellaneous functions) - sets dynamic variable of string
type (AFL 2.80)
Version ( Miscellaneous functions) - get version info (AFL 1.9)
Wilders ( Moving averages, summation) - Wilder’s smoothing (AFL 1.4)
WMA ( Moving averages, summation) - weighted moving average (AFL 2.0)
WriteIf (Exploration / Indicators) - commentary conditional text output
WriteVal (Exploration / Indicators) - converts number to string
XYChartAddPoint (Exploration / Indicators) - add point to exploration
scatter (XY) chart (AFL 3.60)
XYChartSetAxis (Exploration / Indicators) - set the names of X and Y axes
in exploration scatter charts (AFL 3.60)
Year ( Date/Time) - year (AFL 1.4)
ZIG ( Basic price pattern detection) - zig-zag indicator (AFL 1.1)
_DEFAULT_NAME (Exploration / Indicators) - retrive default name of the plot
(AFL 2.70)
_DT ( Date/Time) - convert string to datetime (AFL 3.40)
_N (Exploration / Indicators) - no text output (AFL 2.1)
_PARAM_VALUES (Exploration / Indicators) - retrieve param values string
(AFL 2.70)
_SECTION_BEGIN (Exploration / Indicators) - section begin marker (AFL 2.70)
_SECTION_END (Exploration / Indicators) - section end marker (AFL 2.70)
_SECTION_NAME (Exploration / Indicators) - retrieve current section name
(AFL 2.70)
_TRACE ( Miscellaneous functions) - print text to system debug viewer (AFL
2.4)
AFL Function Reference - Categorized list of functions
Basic price pattern detection
•
•
•
•
•
•
•
•
•
•
•
•
FFT - performs Fast Fourier Transform (AFL 2.90)
GapDown - gap down
GapUp - gap up
Inside - inside day
Outside - outside bar
Peak - peak (AFL 1.1)
PeakBars - bars since peak (AFL 1.1)
PlotTextSetFont - write text on the chart with user-defined font (AFL 2.80)
ShellExecute - execute a file (AFL 3.40)
Trough - trough (AFL 1.1)
TroughBars - bars since trough (AFL 1.1)
ZIG - zig-zag indicator (AFL 1.1)
AFL Function Reference - Categorized list of functions
572
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
Composites
•
•
•
•
•
•
•
•
•
AddToComposite - add value to composite ticker (AFL 2.0)
ADLine - advance/decline line (AFL 1.2)
AdvIssues - advancing issues (AFL 1.2)
AdvVolume - advancing issues volume (AFL 1.2)
DecIssues - declining issues (AFL 1.2)
DecVolume - declining issues volume (AFL 1.2)
Trin - traders (Arms) index (AFL 1.2)
UncIssues - unchanged issues (AFL 1.2)
UncVolume - unchaged issues volume (AFL 1.2)
Date/Time
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
BarIndex - get zero-based bar number (AFL 2.3)
BeginValue - Value of the array at the begin of the range (AFL 2.3)
Date - date (AFL 1.1)
DateNum - date number (AFL 1.4)
DateTime - retrieves encoded date time (AFL 2.3)
DateTimeAdd - adds specified number of seconds/minutes/hours/days to
datetime (AFL 3.40)
DateTimeConvert - date/time format conversion (AFL 2.90)
DateTimeDiff - get difference in seconds between two datetime values (AFL
3.30)
Day - day of month (AFL 1.4)
DayOfWeek - day of week (AFL 1.4)
DayOfYear - get ordinal number of day in a year (AFL 2.4)
DaysSince1900 - get number of days since January 1st, 1900 (AFL 3.20)
EndValue - value of the array at the end of the selected range (AFL 2.3)
GetPlaybackDateTime - get bar replay position date/time (AFL 3.0)
Hour - get current bar’s hour (AFL 2.0)
Interval - get bar interval (in seconds) (AFL 2.1)
Lookup - search the array for bar with specified date/time (AFL 3.40)
MicroSec - get bar’s microsecond part of the timestamp
MilliSec - get bar’s millisecond part of the timestamp
Minute - get current bar’s minute (AFL 2.0)
Month - month (AFL 1.4)
Now - gets current system date/time (AFL 2.3)
Second - get current bar’s second (AFL 2.0)
TimeNum - get current bar time (AFL 2.0)
Year - year (AFL 1.4)
_DT - convert string to datetime (AFL 3.40)
Indicators
•
•
•
•
•
•
•
AccDist - accumulation/distribution
ADX - average directional movement index (AFL 1.3)
ATR - average true range (AFL 1.3)
BBandBot - bottom bollinger band
BBandTop - top bollinger band
CCI - commodity channel index
Chaikin - chaikin oscillator
AFL Function Reference - Categorized list of functions
573
AmiBroker 5.80 User’s Guide
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
AmiBroker Formula Language (AFL)
ColorBlend - blends (mixes) two colors (AFL 3.30)
FirstVisibleValue - get first visible value of array (AFL 3.40)
GetChartBkColor - get the RGB color value of chart background (AFL 3.20)
GetCursorMouseButtons - get current state of mouse buttons (AFL 2.80)
GetCursorXPosition - get current X position of mouse pointer (AFL 2.80)
GetCursorYPosition - get current Y position of mouse pointer (AFL 2.80)
HighestVisibleValue - get the highest value within visible chart area (AFL
3.30)
LastVisibleValue - get last visible value of array (AFL 3.40)
LowestVisibleValue - get the lowest value within visible chart area (AFL
3.30)
MACD - moving average convergence/divergence
MDI - minus directional movement indicator (-DI) (AFL 1.3)
MFI - money flow index
NVI - negative volume index
OBV - on balance volume
OscP - price oscillator
OscV - volume oscillator
PDI - plus directional movement indicator (AFL 1.3)
PercentRank - calculate percent rank (AFL 3.40)
PlotText - write text on the chart (AFL 2.80)
PlotVAPOverlayA - plot multiple-segment Volume-At-Price chart (AFL 3.20)
PVI - positive volume index
RequestTimedRefresh - forces periodical refresh of indicator pane (AFL
2.90)
RMI - Relative Momentum Index (AFL 2.1)
ROC - percentage rate of change
RSI - relative strength index
RWI - random walk index
RWIHi - random walk index of highs
RWILo - random walk index of lows
SAR - parabolic stop-and-reverse (AFL 1.3)
SetBarFillColor - set bar/candlestick/cloud chart fill color (AFL 3.1)
SetChartBkColor - set background color of a chart (AFL 2.80)
SetChartBkGradientFill - enables background gradient color fill in
indicators (AFL 2.90)
SetGradientFill - set the colors of a gradient fill plot (AFL 3.60)
Signal - macd signal line
StochD - stochastic slow %D
StochK - stochastic slow %K
TRIX - triple exponential smoothed price
Ultimate - ultimate oscillator
Information / Categories
•
•
•
•
•
CategoryAddSymbol - adds a symbol to a category (AFL 2.5)
CategoryCreate - add new category (such as watch list) (AFL 3.70)
CategoryFind - search for category by name (AFL 3.0)
CategoryGetName - get the name of a category (AFL 2.5)
CategoryGetSymbols - retrieves comma-separated list of symbols belonging to
given category (AFL 2.5)
• CategoryRemoveSymbol - remove a symbol from a category (AFL 2.5)
AFL Function Reference - Categorized list of functions
574
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
• CategorySetName - set the name of category (group, market, watch list,
industry) (AFL 3.20)
• FullName - full name of the symbol (AFL 1.1)
• GetCategorySymbols - retrieves comma-separated list of symbols belonging to
given category (AFL 2.4)
• GetDatabaseName - retrieves folder name of current database (AFL 2.3)
• GetFnData - get fundamental data (AFL 2.90)
• GicsID - get GICS category information (AFL 3.40)
• GroupID - get group ID/name (AFL 1.8)
• IcbID - get ICB category information (AFL 3.60)
• IndustryID - get industry ID / name (AFL 1.8)
• InGICS - test GICS membership (AFL 3.40)
• InICB - test ICB membership (AFL 3.60)
• InWatchList - watch list membership test (by ordinal number)
• InWatchListName - watch list membership test (by name) (AFL 3.0)
• IsContinuous - checks ’continuous quotations’ flag state (AFL 2.60)
• IsFavorite - check if current symbol belongs to favorites (AFL 2.5)
• IsIndex - check if current symbol is an index (AFL 2.5)
• MarketID - market ID / name (AFL 1.8)
• Name - ticker symbol (AFL 1.1)
• SectorID - get sector ID / name (AFL 1.8)
Lowest/Highest
•
•
•
•
•
•
•
•
•
•
•
•
HHV - highest high value
HHVBars - bars since highest high
Highest - highest value
HighestBars - bars since highest value
HighestSince - highest value since condition met (AFL 1.4)
HighestSinceBars - bars since highest value since condition met (AFL 1.4)
LLV - lowest low value
LLVBars - bars since lowest low
Lowest - lowest value
LowestBars - bars since lowest
LowestSince - lowest value since condition met (AFL 1.4)
LowestSinceBars - barssince lowest value since condition met (AFL 1.4)
Math functions
•
•
•
•
•
•
•
•
•
•
•
•
•
abs - absolute value
acos - arccosine function
AlmostEqual - rounding error insensitive comparison (AFL 2.80)
asin - arcsine function
atan - arc tan
atan2 - calculates arctangent of y/x (AFL 2.90)
ceil - ceil value
cos - cosine
cosh - hyperbolic cosine function (AFL 2.80)
EXP - exponential function
floor - floor value
frac - fractional part
Int - integer part
AFL Function Reference - Categorized list of functions
575
AmiBroker 5.80 User’s Guide
•
•
•
•
•
•
•
•
•
•
•
•
AmiBroker Formula Language (AFL)
log - natural logarithm
log10 - decimal logarithm
Max - maximum value of two numbers / arrays
Min - minimum value of two numbers / arrays
Prec - adjust number of decimal points of floating point number
Round - round number to nearest integer
sign - returns the sign of the number/array (AFL 2.50)
sin - sine function
sinh - hyperbolic sine function (AFL 2.80)
sqrt - square root
tan - tangent function (AFL 1.0)
tanh - hyperbolic tangent function (AFL 2.80)
Miscellaneous functions
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
#include - preprocessor include command (AFL 2.2)
#include_once - preprocessor include (once) command (AFL 2.70)
#pragma - sets AFL pre-processor option (AFL 2.4)
ClipboardGet - retrieves current contents of Windows clipboard (AFL 2.60)
ClipboardSet - copies the text to the Windows clipboard (AFL 2.6)
ColorHSB - specify color using Hue-Saturation-Brightness (AFL 2.80)
ColorRGB - specify color using Red-Green-Blue components (AFL 2.80)
CreateObject - create COM object (AFL 1.8)
CreateStaticObject - create static COM object (AFL 1.8)
EnableScript - enable scripting engine
EnableTextOutput - enables/disables text output in the Chart Commentary
window (AFL 2.2)
Error - displays user-defined error message and stops the execution (AFL
3.7)
GetAsyncKeyState - query the current state of keyboard keys (AFL 3.60)
GetExtraData - get extra data from external data source (AFL 1.9)
GetPerformanceCounter - retrieves the current value of the high-resolution
performance counter (AFL 2.90)
GetRTData - retrieves the real-time data fields (AFL 2.60)
GetRTDataForeign - retrieves the real-time data fields (for specified
symbol) (AFL 2.80)
GetScriptObject - get access to script COM object (AFL 1.8)
IsEmpty - empty value check (AFL 1.5)
IsFinite - check if value is not infinite (AFL 2.3)
IsNan - checks for NaN (not a number) (AFL 2.3)
IsNull - check for Null (empty) value (AFL 2.3)
IsTrue - true value (non-empty and non-zero) check (AFL 1.5)
NoteGet - retrieves the text of the note (AFL 2.6)
NoteSet - sets text of the note (AFL 2.6)
Nz - Null (Null/Nan/Infinity) to zero (AFL 2.3)
PlaySound - play back specified .WAV file (AFL 3.40)
PopupWindow - display pop-up window (AFL 3.0)
Prefs - retrieve preferences settings (AFL 1.4)
Say - speaks provided text (AFL 2.90)
SetBarsRequired - set number of previous and future bars needed for
script/DLL to properly execute (AFL 2.1)
AFL Function Reference - Categorized list of functions
576
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
• StaticVarCompareExchange - atomic interlocked static variable
compare-exchange operation (AFL 3.50)
• StaticVarCount - get the total number of static variables in memory (AFL
3.30)
• StaticVarGenerateRanks - generate ranking of multiple symbols and store it
to static variables (AFL 3.70)
• StaticVarGet - gets the value of static variable (AFL 2.60)
• StaticVarGetRankedSymbols - retrieve a list of ranked symbols from static
variables (AFL 3.70)
• StaticVarGetText - gets the value of static variable as string (AFL 2.60)
• StaticVarInfo - get the information about static variable(s) (AFL 3.60)
• StaticVarRemove - remove static variable (AFL 2.80)
• StaticVarSet - sets the value of static variable (AFL 2.60)
• StaticVarSetText - Sets the value of static string variable. (AFL 2.60)
• Status - get run-time AFL status information (AFL 1.65)
• Study - reference hand-drawn study (AFL 1.5)
• ThreadSleep - suspend thread for specified number of milliseconds (AFL
3.50)
• VarGet - gets the value of dynamic variable (AFL 2.60)
• VarGetText - gets the text value of dynamic variable (AFL 2.80)
• VarSet - sets the value of dynamic variable (AFL 2.60)
• VarSetText - sets dynamic variable of string type (AFL 2.80)
• Version - get version info (AFL 1.9)
• _TRACE - print text to system debug viewer (AFL 2.4)
Moving averages, summation
•
•
•
•
•
•
•
•
•
•
•
•
AMA - adaptive moving average (AFL 1.5)
AMA2 - adaptive moving average (AFL 1.5)
Cum - cumulative sum
DEMA - double exponential moving average (AFL 2.0)
EMA - exponential moving average
FIR - Finite Impulse Response filter (AFL 3.40)
HMA - Hull Moving Average (AFL 3.40)
MA - simple moving average
Sum - sum data over specified number of bars
TEMA - triple exponential moving average (AFL 2.0)
Wilders - Wilder’s smoothing (AFL 1.4)
WMA - weighted moving average (AFL 2.0)
Statistical functions
•
•
•
•
•
•
•
Correlation - correlation (AFL 1.4)
LinearReg - linear regression end-point (AFL 2.2)
LinRegIntercept - (AFL 2.2)
LinRegSlope - linear regression slope (AFL 1.4)
Median - calculate median (middle element) (AFL 2.5)
mtRandom - Mersene Twister random number generator (AFL 3.0)
mtRandomA - Mersene Twister random number generator (array version) (AFL
3.0)
• Percentile - calculate percentile (AFL 2.5)
• Random - random number (AFL 1.9)
AFL Function Reference - Categorized list of functions
577
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
• StdErr - standard error (AFL 1.4)
• StDev - standard deviation (AFL 1.4)
• TSF - time series forecast (AFL 2.2)
String manipulation
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Asc - get ASCII code of character (AFL 2.80)
DateTimeToStr - convert datetime to string (AFL 2.8)
NumToStr - convert number to string (AFL 2.5)
printf - Print formatted output to the output window. (AFL 2.5)
StrCount - count the occurrences of substring within a string (AFL 3.20)
StrExtract - extracts given item (substring) from comma-separated string
(AFL 2.4)
StrFind - find substring in a string (AFL 2.5)
StrFormat - Write formatted output to the string (AFL 2.5)
StrLeft - extracts the leftmost part (AFL 2.0)
StrLen - string length (AFL 1.5)
StrMid - extracts part of the string (AFL 2.0)
StrReplace - string replace (AFL 2.90)
StrRight - extracts the rightmost part of the string (AFL 2.0)
StrToDateTime - convert string to datetime (AFL 2.80)
StrToLower - convert to lowercase (AFL 2.80)
StrToNum - convert string to number (AFL 2.5)
StrToUpper - convert to uppercase (AFL 2.80)
Trading system toolbox
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
AlertIf - trigger alerts (AFL 2.1)
ApplyStop - apply built-in stop (AFL 1.7)
BarsSince - bars since
Cross - crossover check
EnableRotationalTrading - Turns on rotational-trading mode of the
backtester (AFL 2.5)
Equity - calculate single-symbol equity line (AFL 2.0)
ExRem - remove excessive signals (AFL 1.5)
ExRemSpan - remove excessive signals spanning given number of bars (AFL
2.0)
Flip - (AFL 1.5)
GetBacktesterObject - get the access to backtester object (AFL 2.60)
GetOption - gets the value of option in automatic analysis settings (AFL
2.60)
GetTradingInterface - retrieves OLE automation object to automatic trading
interfac (AFL 2.70)
Hold - hold the alert signal
IIf - immediate IF function
LastValue - last value of the array
Optimize - define optimization variable (AFL 1.7)
OptimizerSetEngine - select external optimization engine (AFL 3.20)
OptimizerSetOption - set the value of external optimizer engine parameter
(AFL 3.20)
Ref - reference past/future values of the array
SetBacktestMode - Sets working mode of the backtester (AFL 3.0)
AFL Function Reference - Categorized list of functions
578
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
• SetCustomBacktestProc - define custom backtest procedure formula file (AFL
2.70)
• SetFormulaName - set the name of the formula (AFL 2.5)
• SetOption - sets options in automatic analysis settings (AFL 2.3)
• SetPositionSize - set trade size (AFL 2.70)
• SetTradeDelays - allows to control trade delays applied by the backtester
(AFL 2.1)
• ValueWhen - get value of the array when condition met (AFL 1.1)
Exploration / Indicators
• AddColumn - add numeric exploration column (AFL 1.8)
• AddRankColumn - add ranking column(s) according to current sort set by
SetSortColumns (AFL 5.70)
• AddSummaryRows - add summary row(s) to the exploration output (AFL 3.2)
• AddTextColumn - add text exploration column (AFL 1.8)
• EncodeColor - encodes color for indicator title (AFL 2.2)
• GetChartID - get current chart ID (AFL 2.3)
• GetPriceStyle - get current price chart style (AFL 2.70)
• LineArray - generate trend-line array (AFL 2.5)
• Param - add user user-definable numeric parameter (AFL 2.3)
• ParamColor - add user user-definable color parameter (AFL 2.3)
• ParamDate - add user user-definable date parameter (AFL 2.60)
• ParamField - creates price field parameter (AFL 2.70)
• ParamList - creates the parameter that consist of the list of choices (AFL
2.70)
• ParamStr - add user user-definable string parameter (AFL 2.3)
• ParamStyle - select styles applied to the plot (AFL 2.70)
• ParamTime - add user user-definable time parameter (AFL 2.60)
• ParamToggle - create Yes/No parameter (AFL 2.70)
• ParamTrigger - creates a trigger (button) in the parameter dialog (AFL
2.70)
• Plot - plot indicator graph (AFL 1.8)
• PlotGrid - Plot horizontal grid line (AFL 2.3)
• PlotOHLC - plot custom OHLC chart (AFL 2.2)
• PlotShapes - plots arrows and other shapes (AFL 2.3)
• PlotVAPOverlay - plot Volume-At-Price overlay chart (AFL 2.4)
• SelectedValue - retrieves value of the array at currently selected
date/time point (AFL 2.1)
• SetChartOptions - set/clear/overwrite defaults for chart pane options (AFL
2.70)
• SetSortColumns - sets the columns which will be used for sorting in AA
window (AFL 2.90)
• WriteIf - commentary conditional text output
• WriteVal - converts number to string
• XYChartAddPoint - add point to exploration scatter (XY) chart (AFL 3.60)
• XYChartSetAxis - set the names of X and Y axes in exploration scatter
charts (AFL 3.60)
• _DEFAULT_NAME - retrive default name of the plot (AFL 2.70)
• _N - no text output (AFL 2.1)
• _PARAM_VALUES - retrieve param values string (AFL 2.70)
• _SECTION_BEGIN - section begin marker (AFL 2.70)
AFL Function Reference - Categorized list of functions
579
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
• _SECTION_END - section end marker (AFL 2.70)
• _SECTION_NAME - retrieve current section name (AFL 2.70)
File Input/Output functions
•
•
•
•
•
•
•
•
•
•
fclose - close a file (AFL 2.5)
fdelete - deletes a file (AFL 2.70)
fdir - list directory content (AFL 3.70)
feof - test for end-of-file (AFL 2.5)
fgets - get a string from a file (AFL 2.5)
fgetstatus - retrieves file status/properties (AFL 2.90)
fmkdir - creates (makes) a directory (AFL 2.70)
fopen - open a file (AFL 2.5)
fputs - write a string to a file (AFL 2.5)
frmdir - removes a directory (AFL 2.70)
Low-level graphics
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
GfxArc - draw an arc (AFL 3.0)
GfxChord - draw a chord (AFL 3.0)
GfxCircle - draw a circle (AFL 3.0)
GfxDrawText - draw a text (clipped to rectangle) (AFL 3.0)
GfxEllipse - draw an ellipse (AFL 3.0)
GfxGetTextWidth - get pixel width of text (AFL 2.80)
GfxGradientRect - draw a rectangle with gradient fill (AFL 3.0)
GfxLineTo - draw a line to specified point (AFL 3.0)
GfxMoveTo - move graphic cursor to new position (AFL 3.0)
GfxPie - draw a pie (AFL 3.0)
GfxPolygon - draw a polygon (AFL 3.0)
GfxPolyline - draw a polyline (AFL 3.0)
GfxRectangle - draw a rectangle (AFL 3.0)
GfxRoundRect - draw a rectangle with rounded corners (AFL 3.0)
GfxSelectFont - create / select graphic font (AFL 3.0)
GfxSelectPen - create / select graphic pen (AFL 3.0)
GfxSelectSolidBrush - create / select graphic brush (AFL 3.0)
GfxSetBkColor - set graphic background color (AFL 3.0)
GfxSetBkMode - set graphic background mode (AFL 3.0)
GfxSetCoordsMode - set low-level graphics co-ordinate mode (AFL 2.80)
GfxSetOverlayMode - set low-level graphic overlay mode (AFL 3.0)
GfxSetPixel - set pixel at specified position to specified color (AFL 3.0)
GfxSetTextAlign - set text alignment (AFL 3.0)
GfxSetTextColor - set graphic text color (AFL 3.0)
GfxSetZOrder - set current low-level graphic Z-order layer (AFL 2.80)
GfxTextOut - writes text at the specified location (AFL 3.0)
Referencing other symbol data
•
•
•
•
•
Foreign - access foreign security data (AFL 1.5)
GetBaseIndex - retrieves symbol of relative strength base index (AFL 2.1)
PlotForeign - plot foreign security data (AFL 2.2)
RelStrength - comparative relative strength (AFL 1.3)
RestorePriceArrays - restore price arrays to original symbol (AFL 2.5)
AFL Function Reference - Categorized list of functions
580
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
• SetForeign - replace current price arrays with those of foreign security
(AFL 2.5)
Time Frame functions
• TimeFrameCompress - compress single array to given time frame (AFL 2.5)
• TimeFrameExpand - expand time frame compressed array (AFL 2.5)
• TimeFrameGetPrice - retrieve O, H, L, C, V values from other time frame
(AFL 2.5)
• TimeFrameMode - switch time frame compression mode (AFL 2.80)
• TimeFrameRestore - restores price arrays to original time frame (AFL 2.5)
• TimeFrameSet - switch price arrays to a different time frame (AFL 2.5)
AFL Function Reference - Categorized list of functions
581
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
#include
- preprocessor include command
Miscellaneous functions
(AFL 2.2)
SYNTAX
#include
RETURNS
nothing
FUNCTION
Includes external AFL files into your formula. Note 1: include
statement need SINGLE backslashes in the path (this is quite the
opposite to normal AFL sting
parsing)
Note 2: using #include command may slow down formula execution even
considering the fact that AmiBroker tries to include only once and
cache pre-processed text
Note 3: that currently no error message is given if #include fails
and this code
is experimental.
Note 4: nesting #include commands is now supported (version 5.10 and
above)
Note 5: by default files #included are cached by the AmiBroker. To
turn off caching use
#pragma nocache
before any #include statements. #include now accepts new way of
specifying file names to include:
#include <filename.afl>
(note < > braces instead of " " ) if you specify the file name this
way AmiBroker will look for the file in "standard include path" that
is definable using new prefs setting in Tools->Preferences->AFL It
makes much shorter to write includes and you can move include folder
now without changing all AFL codes using #includes.
For example if you have set standard include path to
"C:\AFL\MyIncludes" and write in your formula:
#include <common.afl>
AmiBroker will look for C:\AFL\MyIncludes\common.afl file
Also now #include reports file(s) not found in regular error message
box.
EXAMPLE
#include "C:\Program Files\AmiBroker\AFL\common.afl"
SEE ALSO
#pragma() function
References:
The #include function is used in the following formulas in AFL on-line library:
#include - preprocessor include command
582
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
More information:
Updated on-line reference
#include- preprocessor include command
583
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
#include_once
- preprocessor include (once) command
Miscellaneous functions
(AFL 2.70)
SYNTAX
#include ’’formula file path’’
RETURNS
nothing
FUNCTION
Includes external AFL files into your formula. Similar to #include
but #include_once performs inclusion only once per formula. So if
single formula has multiple #include_once commands for the same file
(for example because of drag-and-drop overlay) it prevents syntax
errors that could occur due to repeated definitions of functions in
included file. More information can be found in #include command
docs.
EXAMPLE
#include_once ’’myfile.afl’’
SEE ALSO
#include() function
References:
The #include_once function is used in the following formulas in AFL on-line
library:
More information:
Updated on-line reference
#include_once - preprocessor include (once) command
584
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
#pragma
- sets AFL pre-processor option
Miscellaneous functions
(AFL 2.4)
SYNTAX
#pragma optionname
RETURNS
NOTHING
FUNCTION
Sets various AFL pre-processor options. Pre-processor is a part of
AFL engine that processes formulas BEFORE they are executed.
Currently the only task of pre-processor is to include external
files via #include command.
#pragma allows to change pre-processor behaviour.
Currently the only option available via #pragma is nocache
#pragma nocache
causes that #included files are not cached so they are re-read with
every execution
#pragma nocache
must be placed before any #include commands. Note: between ’#pragma’
and ’nocache’ there must be exactly SINGLE space
Note 2: disabling caching may slow down execution of the formula
(especially in indicators) !!!
EXAMPLE
#pragma nocache
#include "myfile.afl"
SEE ALSO
#include() function
References:
The #pragma function is used in the following formulas in AFL on-line library:
More information:
Updated on-line reference
#pragma - sets AFL pre-processor option
585
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
abs
- absolute value
SYNTAX
abs( NUMBER )
abs( ARRAY )
RETURNS
NUMBER
ARRAY
FUNCTION
Calculates the absolute value of the NUMBER or ARRAY.
EXAMPLE
The formula "abs( -15 )" will return +15; the formula "abs( 15)"
also returns +15.
Math functions
SEE ALSO
References:
The abs function is used in the following formulas in AFL on-line library:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Absolute Breadth Index
Adaptave Zones O/B &O/S Oscillator
Adaptive Laguerre Filter, from John Ehlers
ADXbuy
Against all odds
Analytic RSI formula
Another FIb Level
Application of Ehler filter
AR_Prediction.afl
Auto Trade Step by Step
Auto-Optimization Framework
AutoTrader Basic Flow - updated April 15, 2009
AutoTrader Basic Flow - updated Nov 18, 2008
Better Bollinger Bands
Bullish Percent Index 2 files combined
Candle Identification
Candle Pattern Function
Candle Stick Analysis
CandleStick Comentary--Help needed
Candlestick Commentary
Candlestick Commentary Modified
Candlestick Commentary-modified
CandleStochastics
CCT Kaleidoscope
Chandelier Exit
com-out
Coppock Trade Signal on Price Chart
Coppock Trade Signal v1.1
Cybernertic Hilbert Sine Wave
Demand Index
Double top detection
Dynamtic Momentum Index
Ed Seykota’s TSP: EMA Crossover System
abs - absolute value
586
AmiBroker 5.80 User’s Guide
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
AmiBroker Formula Language (AFL)
Elder Triple Screen Trading System
Future Plotting of Time and Price
Future Plotting of Time and Price
Gann Swing Charts in 3 modes with text
Harmonic Patterns
Head &Shoulders Pattern
Heatmap V1
Hilbert Sine Wave
Hilbert Sine Wave Support &Resistance
Hilbert Sine Wave with Hull Moving Average
Hilbert Study
Hurst Constant
John Ehler
MA Difference 20 Period
MACD commentary
MACD indicator display
Market Breadth Chart-In-Chart
Market Direction
MDYtoXLSerialDays and XLSerialDaysToDateNum
Modified Head &Shoulder Pattern
MultiCycle 1.0
Multiple Ribbon Demo
Multiple sinus noised
Nonlinear Ehlers Filter
nth ( 1 - 8 ) Order Polynomial Fit
Option Calls, Puts and days till third friday.
Parametric Chande Trendscore
Pattern Recognition Exploration
prakash
Range Expansion Index
Raw ADX
Rebalancing Backtest avoiding leverage
RSI of Weekly Price Array
SectorRSI
Sine Wave Indicator
TD REI
The Mean RSIt
The Mean RSIt (variations)
tomy_frenchy
Triangle exploration using PFChart
Trigonometric Fit - TrigFit with AR for cos / sin
Tushar Chande’s Projected Range
TWS auto-export Executions-file parser
ValueChart
Vertical Horizontal Filter
Vertical Horizontal Filter (VHF)
Vic Huebner
Visi-Trade
Volatility Quality Index
Woodie’s CCI Panel Basic
Woodie’s CCI Panel Full Stats
abs - absolute value
587
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
More information:
Updated on-line reference
abs- absolute value
588
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
AccDist
- accumulation/distribution
SYNTAX
AccDist()
RETURNS
ARRAY
FUNCTION
Calculates the Accumulation/ Distribution indicator.
Indicators
EXAMPLE
SEE ALSO
References:
The AccDist function is used in the following formulas in AFL on-line library:
• accum/dist mov avg crossover SAR
• Bollinger band normalization
More information:
Updated on-line reference
AccDist - accumulation/distribution
589
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
acos
- arccosine function
SYNTAX
acos( x )
RETURNS
NUMBER, ARRAY
FUNCTION
Returns the arccosine of NUMBER or ARRAY. The acos function returns
the arccosize of x in the range 0 to pi radians. If x is less than
-1 or greater than 1, acos returns an indefinite.
Math functions
EXAMPLE
SEE ALSO
COS() function
References:
The acos function is used in the following formulas in AFL on-line library:
• Woodie’s CCI Panel Basic
• Woodie’s CCI Panel Full Stats
• Woodie’s Price Panel With Woodie’s Pivots
More information:
Updated on-line reference
acos - arccosine function
590
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
AddColumn
- add numeric exploration column
Exploration / Indicators
(AFL 1.8)
SYNTAX
AddColumn( array, name, format = 1.2, textColor = colorDefault,
bkgndColor = colorDefault, width = -1, barchart = Null )
RETURNS
NOTHING
FUNCTION
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. (Note for
advanced users: the integer part of this number can be used to pad
formatted number with spaces - 6.0 will give no decimal digits but a
number space-padded upto 6 characters.)
Next two parameters allow to modify text and background color.
special format constants:
• formatDateTime - produces date time formated according to your
system settings
AddColumn( DateTime(), "Date / Time", formatDateTime );
• formatChar - allows outputting single ASCII character codes:
Example (produces signal file accepted by various other
programs):
Buy=Cross(MACD(),Signal());
Sell=Cross(Signal(), MACD());
Filter=Buy OR Sell;
SetOption("NoDefaultColumns", True );
AddColumn( DateTime(), "Date", formatDateTime );
AddColumn( IIf( Buy, 66, 83 ), "Signal", formatChar );
• width parameter allows to control pixel width of the column
• ’barchart’ parameter accepts values from 0...100 represening
percentage width of bar chart displayed in a cell the in-cell
bar chart is drawn with bkcolor (background color).
EXAMPLE
1. Simple column showing close price
addcolumn( Close, "Close price", 1.4 );
2. Colorful output
Filter =1;
AddColumn( Close, "Close", 1.2 );
AddColumn( MACD(), "MACD", 1.4 , IIf( MACD() > 0, colorGreen,
colorRed ) );
AddTextColumn( FullName(), "Full name", 77 , colorDefault, IIf(
AddColumn - add numeric exploration column
591
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
Close < 10, colorLightBlue, colorDefault ) );
3. Barchart example Filter=1;
AddColumn( Close, "Close" );
rank = PercentRank( Close, 100 );
Color = ColorHSB( rank * 64/100, 255, 255 );
AddColumn( rank, "100-day percent rank", 1.2, colorDefault, Color,
-1, rank );
SEE ALSO
ADDTEXTCOLUMN() function
References:
The AddColumn function is used in the following formulas in AFL on-line library:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Advanced MA system
ADXbuy
AFL Example
AFL Example - Enhanced
Alert Output As Quick Rewiev
Appel’s ROC or The Triple Momentum Timing Model
Aroon Indicators
Auto-Optimization Framework
AutoTrade using an Exploration
Average Dollar Price Volatility Exploration
Black Scholes Option Pricing
Bottom Fisher Exploration
Bull Fear / Bear Fear
Bullish Percent Index 2 files combined
Calculate composites for tickers in list files
CAMSLIM Cup and Handle Pattern AFL
Commodity Selection Index (CSI)
Count Tickers in Watchlist
CVR--severe filter
Ed Seykota’s TSP: EMA Crossover System
Ed Seykota’s TSP: Support and Resistance
ekeko price chart
Elder Impulse Indicator V2
End Of Year Trading
Follow the Leader
Gordon Rose
half-automated Trading System
IBD relative strength database Viewer
ICHIMOKU SIGNAL TRADER
Intraday Average Volume
Intraday Fibonacii Trend Break System
Intraday Trend Break System
JEEVAN’S SRI CHAKRA
Market Facilitation Index VS Volume
mitalpradip
Monthly bar chart
MS Darvas Box with Exploration
AddColumn- add numeric exploration column
592
AmiBroker 5.80 User’s Guide
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
AmiBroker Formula Language (AFL)
NRx Exploration
nth ( 1 - 8 ) Order Polynomial Fit
Ord Volume
Pattern_-_Rectangle_Base_Breakout_on_High_Vol 2
Position Sizer vers2, stocks and CFDs
Price Persistency
Ranking and sorting stocks
Relative Strength
Robert Antony
RSI Double-Bottom
RSI Trendlines and Wedges
RUTVOL timing signal with BB Scoring routine
Sainath Sidgiddi
SAR-ForNextBarStop
SectorRSI
Simple Candle Exploration
STD_STK Multi
StochD_StochK Single.afl
Stops Implementation in AFS
Strength and Weakness
TAZ Trading Method Exploration
testing multiple system simulataneously
Three Day Balance Point
Trend Detection
Trend exploration with multiple timeframes
Trend Exploration: Count Number of New Highs
Trend Exploration: Slope Moving Average
Triangle exploration using PFChart
Triangular Moving Average new
Using From and To dates from Auto Analysis in Code
Volume - compared with Moving Avg (100%)
Weekly chart
Weighted Index
William’s Alligator System II
More information:
Updated on-line reference
AddColumn- add numeric exploration column
593
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
AddRankColumn
- add ranking column(s) according to current sort
set by SetSortColumns
SYNTAX
AddRankColumn()
RETURNS
NOTHING
FUNCTION
The function adds ranking column(s) according to current sort set by
SetSortColumns to exploration result list.
EXAMPLE
Filter = 1;
AddColumn( Close, "Close" );
AddColumn( Volume, "BI" );
AddSummaryRows( 31 + 32, 1.5 );
Exploration /
Indicators
(AFL 5.70)
AddRankColumn(); // without prior sorting AddRankColumn just adds
line number
SetSortColumns( -4 );
AddRankColumn(); // rank according to 4th column (descending)
SetSortColumns( -3 );
AddRankColumn(); // rank according to 3rd column (ascending)
SEE ALSO
SetSortColumns() function
References:
The AddRankColumn function is used in the following formulas in AFL on-line
library:
More information:
Updated on-line reference
AddRankColumn - add ranking column(s) according to current sort set by SetSortColumns
594
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
AddSummaryRows
- add summary row(s) to the exploration output
Exploration / Indicators
(AFL 3.2)
SYNTAX
AddSummaryRows( flags, format = 0, onlycols = 0, ...)
RETURNS
NOTHING
FUNCTION
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.
If default value of zero is used (or parameter not specified) the
default formatting of "maximum precision" is used - upto 15 digits
are printed
onlycols - defines for which columns you want to display summary row
values. Note that if you do not specify any columns - ALL will be
printed.
If you are using onlycols, you can define upto 10 columns, columns,
like in SetSortColumns are numbered starting from 1. For example:
AddSummaryRows( 1, 1.2, 3, 5, 7, 9 );
Display sum for columns: 3, 5, 7, and 9.
Generally you should call this funciton only once, using combination
of flags desired. But it is possible to call AddSummaryRows multiple
times and the result will be "accumulation" (i.e. bitwise OR) in
case of "flag" parameter. format and onlycols are always overwritten
by last call.
EXAMPLE
Filter=1;
AddColumn(V, "Volume" );
AddSummaryRows( 31, 1.2 );
// add Total, Average, Min, Max, and Count rows (1+2+4+8+16)=31 with two decimal places summary rows are added at the top of the
list
SEE ALSO
AddColumn() function , AddTextColumn() function
AddSummaryRows - add summary row(s) to the exploration output
595
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
References:
The AddSummaryRows function is used in the following formulas in AFL on-line
library:
More information:
Updated on-line reference
AddSummaryRows- add summary row(s) to the exploration output
596
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
AddTextColumn
- add text exploration column
Exploration / Indicators
(AFL 1.8)
SYNTAX
AddTextColumn( string, name, format = 1.2, textColor = colorDefault,
bkgndColor = colorDefault, width = -1 )
RETURNS
NOTHING
FUNCTION
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
EXAMPLE
addtextcolumn( GroupID( 1 ), "The name of the group");
SEE ALSO
ADDCOLUMN() function
Comments:
Tomasz
Janeczko
Please note that AddTextColumn takes single string as a
parameter, so you can only display text that does NOT vary on
bar-by-bar basis.
2005-08-10
06:35:35
References:
The AddTextColumn function is used in the following formulas in AFL on-line
library:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
AFL Example
AFL Example - Enhanced
Alert Output As Quick Rewiev
AutoTrade using an Exploration
Average Dollar Price Volatility Exploration
Bottom Fisher Exploration
Dave Landry PullBack Scan
Elder Impulse Indicator V2
Elder Triple Screen Trading System
IBD relative strength database ranker
ICHIMOKU SIGNAL TRADER
Intraday Fibonacii Trend Break System
Intraday Trend Break System
Market Facilitation Index VS Volume
MS Darvas Box with Exploration
NRx Exploration
Relative Strength
Scan New High and New Low
Trend exploration with multiple timeframes
Trend Exploration: Count Number of New Highs
Trend Exploration: Slope Moving Average
Triangular Moving Average new
William’s Alligator System II
AddTextColumn - add text exploration column
597
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
• WLBuildProcess
More information:
Updated on-line reference
AddTextColumn- add text exploration column
598
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
AddToComposite
- add value to composite ticker
SYNTAX
AddToComposite( array, ’’ticker’’, ’’field’’, flags =
atcFlagDefaults )
RETURNS
NOTHING
FUNCTION
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. It is advised to use
~comp (tilde at the beginning)
newly added composites are assigned to group 253 by default and
have "use only local database" feature switched on for proper
operation with external sources possible field codes: "C" - close ,
"O" - open, "H" - high, "L" - low, "V" - volume, "I" - open
interest, "1" - Aux1 field, "2" - Aux2 field, "X" - updates all OHLC
fields at once
Composites
(AFL 2.0)
flags - contains the sum of following values
• atcFlagDeleteValues = 1 - deletes all previous data from
composite symbol at the beginning of scan (recommended)
• atcFlagCompositeGroup = 2 - put composite ticker into group
253 and EXCLUDE all other tickers from group 253 (avoids
adding composite to composite)
• atcFlagTimeStamp = 4 - put last scan date/time stamp into
FullName field
• atcFlagEnableInBacktest = 8 - allow running AddToComposite in
backtest/optimization mode
• atcFlagEnableInExplore = 16 - allow running AddToComposite in
exploration mode
• atcFlagResetValues = 32 - reset values at the beginning of
scan (not required if you use atcFlagDeleteValues)
• atcFlagDefaults = 7
(this is a composition of atcFlagResetValues |
atcFlagCompositeGroup | atcFlagTimeStamp flags)
• atcFlagEnableInPortfolio = 64 - allow running AddToComposite
in custom portfolio backtester phase
• atcFlagEnableInIndicator = 128 - allow running AddToComposite
in indicator mode
AddToComposite function also detects the context in which it is run
(it works ONLY in scan mode, unless atcFlagEnableInBacktest or
atcFlagEnableInExplore flags are specified) and does NOT affect
composite ticker when run in Indicator or Commentary mode, so it is
now allowed to join scan and indicator into single formula.
AddToComposite - add value to composite ticker
599
AmiBroker 5.80 User’s Guide
EXAMPLE
AmiBroker Formula Language (AFL)
AddToComposite( MACD() > 0, "~BullMACD", "V");
Graph0 = Foreign("~BullMACD", "V");
// Now you can use the same formula in scan AND indicator
SEE ALSO
References:
The AddToComposite function is used in the following formulas in AFL on-line
library:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
30 Week Hi Indicator - Calculate
52 Week New High-New Low Index
Bad Tick Trim on 5 sec database
Bullish Percent Index 2 files combined
Bullish Percent Index 2004
Calculate composites for tickers in list files
Compare Sectors against Tickers
Detailed Equity Curve
Heatmap V1
Improved NH-NH scan / indicator
Index of 30 Wk Highs Vs Lows
Market Direction
Overbought issues, Oversold issues
RUTVOL timing signal with BB Scoring routine
SectorRSI
Stochastic Divergences, PDI, NDI
Stochastic OSI &OBI
The Mean RSIt
The Mean RSIt (variations)
The Relative Slope Pivots
Trending or Trading ?
Weighted Index
WLBuildProcess
More information:
Updated on-line reference
AddToComposite- add value to composite ticker
600
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
ADLine
- advance/decline line
SYNTAX
ADLine()
RETURNS
ARRAY
FUNCTION
Calculates Advance/Decline line indicator
EXAMPLE
adline()
Composites
(AFL 1.2)
SEE ALSO
References:
The ADLine function is used in the following formulas in AFL on-line library:
More information:
Updated on-line reference
ADLine - advance/decline line
601
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
AdvIssues
- advancing issues
SYNTAX
AdvIssues()
RETURNS
ARRAY
FUNCTION
Returns the number of advancing issues for a given market (the one
that currently analysed stock belongs to)
EXAMPLE
advissues()
Composites
(AFL 1.2)
SEE ALSO
References:
The AdvIssues function is used in the following formulas in AFL on-line library:
•
•
•
•
Absolute Breadth Index
Breadth Thrust
McClellan Oscillator
McClellan Summation Index
More information:
Updated on-line reference
AdvIssues - advancing issues
602
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
AdvVolume
- advancing issues volume
SYNTAX
AdvVolume()
RETURNS
ARRAY
FUNCTION
Returns the volume of advancing issues for a given market (the one
that currently analysed stock belongs to)
EXAMPLE
advvolume()
Composites
(AFL 1.2)
SEE ALSO
References:
The AdvVolume function is used in the following formulas in AFL on-line library:
More information:
Updated on-line reference
AdvVolume - advancing issues volume
603
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
ADX
- average directional movement index
SYNTAX
adx( period = 14 )
RETURNS
ARRAY
FUNCTION
Calculates Average Directional Index indicator
EXAMPLE
adx(), adx(20)
Indicators
(AFL 1.3)
SEE ALSO
References:
The ADX function is used in the following formulas in AFL on-line library:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Advanced MA system
ADX Indicator - Colored
ADXR
babaloo chapora
Bollinger band normalization
Bull Fear / Bear Fear
Dave Landry Pullbacks
DMI Spread Index
ekeko price chart
Gordon Rose
Heatmap V1
ICHIMOKU SIGNAL TRADER
Index and ETF trading
Mndahoo ADX
Multiple Ribbon Demo
Perceptron
swing chart
TAZ Trading Method Exploration
TrendingRibbonArrowsADX
More information:
Updated on-line reference
ADX - average directional movement index
604
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
AlertIf
- trigger alerts
Trading system toolbox
(AFL 2.1)
SYNTAX
AlertIf( BOOLEAN_EXPRESSION, command, text, type = 0, flags =
1+2+4+8, lookback = 1 );
RETURNS
nothing
FUNCTION
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. If it is empty the alert text is simply displayed in the
Alert output window (View->Alert Output). Other supported values of
command string are:
SOUND the-path-to-the-WAV-file
EMAIL
EXEC the-path-to-the-file-or-URL
SOUND command plays the WAV file once.
EMAIL command sends the e-mail to the account defined in the
settings (Tools->Preferences->E-mail). The format of the e-mail is
as follows: Subject: Alert type_name (type) Ticker on Date/Time
Body: text
EXEC command launches external application or file or URL specified
after EXEC command. are attached after file name and text is
attached at the end
3. Text defines the text that will be printed in the output window
or sent via e-mail or added as argument to the application specified
by EXEC command
4. Type defines type of the alert. Pre-defined types are 0 default, 1 - buy, 2 - sell, 3 - short, 4- cover. YOu may specify
higher values and they will get name "other"
5. Flags control behaviour of AlertIF function. This field is a
combination (sum) of the following values:
( 1 - display text in the output window, 2 - make a beep (via
computer speaker), 4 - don’t display repeated alerts having the same
type, 8 - don’t display repeated alerts having the same date/time)
By default all these options are turned ON.
6. lookback parameter controls how many recent bars are checked
EXAMPLE
Buy = Cross( MACD(), Signal() );
Sell = Cross( Signal(), MACD() );
AlertIf - trigger alerts
605
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
Short = Sell;
Cover = Buy;
AlertIF( Buy, "EMAIL", "A sample alert on "+FullName(), 1 );
AlertIF( Sell, "SOUND C:\\Windows\\Media\\Ding.wav", "Audio alert",
2 );
AlertIF( Short, "EXEC Calc.exe", "Launching external application", 3
);
AlertIF( Cover, "", "Simple text alert", 4 );
Note EXEC command uses ShellExecute function and allows not only EXE
files but URLs too.
SEE ALSO
References:
The AlertIf function is used in the following formulas in AFL on-line library:
•
•
•
•
•
•
•
•
•
•
AFL Example - Enhanced
Alert Output As Quick Rewiev
Basket Trading System T101
CCI(20) Divergence Indicator
Intraday Fibonacii Trend Break System
Intraday Trend Break System
JEEVAN’S SRI CHAKRA
RI - Auto Trading System
Stock price AlertIf
Trading ATR 10-1
More information:
Updated on-line reference
AlertIf- trigger alerts
606
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
AlmostEqual
- rounding error insensitive comparison
SYNTAX
AlmostEqual( x, y, ulps = 5 )
RETURNS
NUMBER
ARRAY
FUNCTION
This is a helper function for comparing floating point numbers. It
returns True if x and y are equal or almost equal upto defined
accurracy (ulps). It is recommended to use this function instead of
equality check (==) as it leads to more reliable comparisons and
less headache caused by IEEE floating pointacurracy issues.
Math functions
(AFL 2.80)
Parameters:
• x, y - the numbers or arrays to be compared,
• ulps stands for "units in last place" and represents maximum
relative error of the comparison. Since 32 bit IEEE floating
point numbers have accurracy of 7 significant digits, 1 unit
in last place(ulp) represents relative error of 0.00001 %. The
default value of ulps parameter is 5 which gives roughtly
0.00005% "comparison sensitivity".
Thanks to Bruce Dawson for his fast routine.
EXAMPLE
if( 1/3 == 0.3333333 )
{
printf("32-bit Floating point IEEE exact equality\n");
}
if( AlmostEqual( 1/3, 0.3333333 ) )
{
printf("Numbers are almost equal\n");
}
SEE ALSO
References:
The AlmostEqual function is used in the following formulas in AFL on-line
library:
More information:
Updated on-line reference
AlmostEqual - rounding error insensitive comparison
607
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
AMA
- adaptive moving average
Moving averages, summation
(AFL 1.5)
SYNTAX
ama( ARRAY, SMOOTHINGFACTOR )
RETURNS
ARRAY
FUNCTION
calculates adaptive moving average - simliar to EMA() but smoothing
factor could be time-variant (array).
EXAMPLE
The example of volatility-weighted adaptive moving average formula:
graph0 = ema( close, 15 );
fast = 2/(2+1);
slow = 2/(30+1);
dir=abs(close-ref(close,-10));
vol=sum(abs(close-ref(close,-1)),10);
ER=dir/vol;
sc =( ER*(fast-slow)+slow)^2; graph0 = ama( close, sc );
SEE ALSO
Comments:
Tomasz Janeczko
output = AMA( input, factor )
2006-04-26 20:13:15
is equivalent to the following looping code:
for( i = 1; i < BarCount; i++ )
{
output[ i ] = factor[ i ] * input[ i ] + ( 1 - factor[ i
] ) * output[ i - 1 ];
}
References:
The AMA function is used in the following formulas in AFL on-line library:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Application of Ehler filter
Auto-Optimization Framework
Automatic Linear Trend Channel
Automatic Linear Trend Channel 2
automatic trendlines using fractal patterns
Better Bollinger Bands
Bman’s HaDiffCO
candlestick chart for Volume/RSI/OBV
CCI 14 DrBobStyle
CCI 50 DrBob Style
com-out
Heatmap V1
Heikin Ashi Candles
Heikin-Ashi(Koma-Ashi) with Moving Average
Heinkin-Ashi
Hilbert Study
AMA - adaptive moving average
608
AmiBroker 5.80 User’s Guide
•
•
•
•
•
•
•
•
AmiBroker Formula Language (AFL)
IFT of RSI - Multiple TimeFrames
INTRADAY HEIKIN ASHI new
Intraday Volume EMA
Pivots for Intraday Forex Charts
shailu lunia
Vikram’s Floor Pivot Intraday System
Woodie’s CCI Panel Full Stats
Woodie’s Heikin-Ashi Panel
More information:
Updated on-line reference
AMA- adaptive moving average
609
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
AMA2
- adaptive moving average
Moving averages, summation
(AFL 1.5)
SYNTAX
ama2( ARRAY, SMOOTHINGFACTOR, FEEDBACKFACTOR )
RETURNS
ARRAY
FUNCTION
calculates adaptive moving average - simliar to EMA() but smoothing
factor could be time-variant (array).
AMA2 has a separate control of feedbackfactor which is normally
(1-SMOOTHINGGFACTOR). Internally this function works like this:
today_ama = SMOOTHINGFACTOR * array + FEEDBACKFACTOR * yesterday_ama
EXAMPLE
The example of volatility-weighted adaptive moving average formula:
graph0 = ema( close, 15 );
fast = 2/(2+1);
slow = 2/(30+1);
dir=abs(close-ref(close,-10));
vol=sum(abs(close-ref(close,-1)),10);
ER=dir/vol;
sc =( ER*(fast-slow)+slow)^2; graph0 = ama2( close, sc, 1-sc);
SEE ALSO
References:
The AMA2 function is used in the following formulas in AFL on-line library:
•
•
•
•
Candle Stick Analysis
Cycle Period
Intraday Volume EMA
mitalpradip
More information:
Updated on-line reference
AMA2 - adaptive moving average
610
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
ApplyStop
- apply built-in stop
Trading system toolbox
(AFL 1.7)
SYNTAX
ApplyStop( type, mode, amount, exitatstop, volatile = False,
ReEntryDelay = 0 )
RETURNS
nothing
FUNCTION
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 - trailing stop,
3 = stopTypeNBar - N-bar stop
mode =
0 - disable stop (stopModeDisable),
1 - amount in percent (stopModePercent), or number of bars for N-bar
stop (stopModeBars),
2 - amount in points (stopModePoint);
3 - amount in percent of profit (risk)
amount =
percent/point loss/profit trigger/risk amount.
This could be a number (static stop level) or an array (dynamic stop
level)
ExitAtStop
ExitAtStop = 0 - means check stops using only trade price and exit
(1)
at regular trade price
(if you are trading on close it means that only close price will be
checked for exits and exit will be done at close price)
ExitAtStop = 1 - check High-Low prices and exit intraday on price
equal to stop level on the same bar when stop was triggered
ExitAtStop = 2 - check High-Low prices but exit NEXT BAR on regular
trade price.
volatile decides if amount (or distance) (3rd parameter) is sampled at the
trade entry and remains fixed during the trade (Volatile = FALSE old behaviour) or if can vary during the trade (Volatile = TRUE)
(allows single line Chandelier exit implementation)
(2)
ReEntryDelay how many bars to wait till entering the same stock is allowed.
ApplyStop - apply built-in stop
611
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
Note on using stops:
Scenario 1:
you trade on next bar OPEN and want to exit intraday on stop price
Correct settings:
ActivateStopsImmediately turned ON
ExitAtStop = 1
Trade delays set to one
Trade price set to open
Scenario 2:
you trade on today’s close and want to exit intraday on stop price
Correct settings:
ActivateStopsImmediately turned OFF
ExitAtStop = 1
Trade delays set to zero
Trade price set to close
Scenario 3:
you trade on next day OPEN and want to exit by stop on OPEN price
when PREVIOUS day H-L range hits stop
Correct settings:
ExitAtStop = 2 (NEW)
Trade delays set to one
Trade price set to open
• a) (if you want to have stops executed AFTER regular signals,
so cash from stopped out positions is NOT available to enter
trades the same day)
ActivateStopsImmediately turned ON
• b) (if you want to have stops executed BEFORE regular signals,
so cash from stopped out positions IS available to enter new
trades the same day)
ActivateStopsImmediately turned OFF
Scenario 4:
you trade on today’s close and want to exit only when today’s close
price hits the stop level
Correct settings:
ActivateStopsImmediately turned OFF
ExitAtStop = 0
Trade delays set to zero
Trade price set to close
LIMITATIONS:
ApplyStop - apply built-in stop
612
AmiBroker 5.80 User’s Guide
EXAMPLE
•
(1)
•
(2)
AmiBroker Formula Language (AFL)
ExitAtStop = 0 uses SellPrice/CoverPrice variables in
backtestRegular mode only, in other modes it uses trade prices
from the Settings dialog (not overridable via
SellPrice/CoverPrice)
Volatile stops (Volatile=True) work only in backtestRegular
mode
/* max loss stop optimization */
ApplyStop(stopTypeLoss,
stopModePercent,
Optimize( "max. loss stop level", 10, 2, 30, 1 ),
True );
/* single-line implementation of Chandelier exit */
ApplyStop(stopTypeTrailing, stopModePoint, 3*ATR(14), True, True );
/* N-bar stop */
ApplyStop( stopTypeNBar, stopModeBars, 5 );
SEE ALSO
Comments:
Herman van den Bergen
[email protected]
2003-02-23 09:53:51
If you are trading at the Close with zero delays be sure to unmark "Activate Stops
Immediately" in Settings.
Corey Saxe
[email protected]
2003-03-01 23:33:13
For visual conformation of ApplyStop function, add the following lines below your
ApplyStop formula in Indicator Builder:
Equity(1); // THIS EVALUATES STOPS
Plot(Sell==4,"ApplyStop Sell",colorRed,1|styleOwnScale);
Plot(Cover==4,"ApplyStop Cover",colorGreen,1|styleOwnScale);
Tomasz Janeczko
tj --at-- amibroker.com
2004-08-28 03:14:12
If two or more different stops are triggered on the VERY SAME bar then they are
evaluated in this fixed order:
Fixed Ruin stop (loosing 99.96% of the starting capital)
Max. loss stop
Profit target stop
Trailing stop
N-bar stop
Graham Kavanagh
[email protected]
2004-09-30 21:55:42
from equity comments
Depending on kind of the stop various values
are written back to sell/cover array to enable you to distinguish if given signal
was generated by regular rule or by stop.
1 - regular exit
ApplyStop- apply built-in stop
613
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
2 - max. loss
3 - profit target
4 - trailing
5 - n-bar stop
6 - ruin stop
Tomasz Janeczko
tj --at-- amibroker.com
2005-03-01 17:10:39
ExitAtStop has a new meaning for N-BAR stop type.
If ExitAtStop = 0 then N-bar stop has the lowest priority (so if for example profit
target stop is hit on the same bar then profit target is evaluated first)
If ExitAtStop = 1 then N-bar stop has highest priority and it is evaluated before
all other stops.
The same effect is obtained by checking "Has priority" box in AA Settings window.
Tomasz Janeczko
tj-/nospam/@amibroker.com
2006-01-13 11:41:32
ApplyStop function is designed to be used to simulate
stop orders placed at the exchange or simulated by the brokerage
Please read this how such stops operate:
http://www.interactivebrokers.com/en/trading/orders/stop.php?ib_entity=uk
http://www.interactivebrokers.com/en/trading/orders/trailingStops.php?ib_entity=uk
References:
The ApplyStop function is used in the following formulas in AFL on-line library:
•
•
•
•
•
•
•
•
•
•
•
•
ATR Study
AutoTrade using an Exploration
danningham penetration
Ed Seykota’s TSP: EMA Crossover System
Follow the Leader
Index and ETF trading
RUTVOL timing signal with BB Scoring routine
SectorRSI
The D_oscillator
The Three Day Reversal
Trend Continuation Factor
Vivek Jain
More information:
Updated on-line reference
ApplyStop- apply built-in stop
614
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
Asc
- get ASCII code of character
SYNTAX
Asc( string, pos = 0 )
RETURNS
NUMBER
FUNCTION
Returns the ANSI character code corresponding to the first letter in
a string (if position is not specified) or code of character at
specified position. If you don’t specify position (pos argument)
then first character is used. Negative values of pos reference
characters counting from the end of string.
String manipulation
(AFL 2.80)
Useful for creation of exploration that displays single letters for
signals instead of numbers.
EXAMPLE
Buy = Cross(MACD(),Signal());
Sell = Cross(Signal(),MACD());
Filter = Buy OR Sell;
AddColumn( IIf( Buy, Asc("B"), Asc("S")), "Signal", formatChar );
SEE ALSO
AddColumn() function
References:
The Asc function is used in the following formulas in AFL on-line library:
• AFL_Glossary_1
• AutoTrade using an Exploration
• Ed Seykota’s TSP: Support and Resistance
More information:
Updated on-line reference
Asc - get ASCII code of character
615
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
asin
- arcsine function
SYNTAX
asin( x )
RETURNS
NUMBER, ARRAY
FUNCTION
Returns the arcsine of NUMBER or ARRAY. The asin function returns
the arcsine of x in the range -pi/2 to pi/2 radians. If x is less
than -1 or greater than 1, asin returns an indefinite
Math functions
EXAMPLE
SEE ALSO
SIN() function
References:
The asin function is used in the following formulas in AFL on-line library:
More information:
Updated on-line reference
asin - arcsine function
616
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
Math functions
atan
- arc tan
SYNTAX
atan( NUMBER ),
atan( ARRAY )
RETURNS
NUMBER
ARRAY
FUNCTION
Returns the arc tangent of NUMBER or ARRAY. The value is returned in
radians
EXAMPLE
The formula "atan( 1.00 )" returns PI/4
SEE ALSO
References:
The atan function is used in the following formulas in AFL on-line library:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Andrews Pitchfork
Andrews PitchforkV3.3
AR_Prediction.afl
Cybernertic Hilbert Sine Wave
DMI Spread Index
Dominant Cycle Phase
Heatmap V1
Hilbert Sine Wave
Hilbert Sine Wave Support &Resistance
Hilbert Sine Wave with Hull Moving Average
Hilbert Study
John Ehler
Moving Average "Crash" Test
Multiple sinus noised
Schiff Lines
Signal to Noise
Sine Wave Indicator
Smoothed Adaptive Momentum
Trigonometric Fit - TrigFit with AR for cos / sin
Woodie’s CCI Panel Basic
Woodie’s CCI Panel Full Stats
Woodie’s Price Panel With Woodie’s Pivots
More information:
Updated on-line reference
atan - arc tan
617
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
atan2
- calculates arctangent of y/x
Math functions
(AFL 2.90)
SYNTAX
atan2( y, x )
RETURNS
NUMBER or ARRAY
FUNCTION
atan2 returns the arctangent of y/x. If x is 0, atan2 returns 0. If
both parameters of atan2 are 0, the function returns 0. atan2
returns a value in the range -PI to +PI radians, using the signs of
both parameters to determine the quadrant of the return value.
EXAMPLE
ffc = FFT(data,Len);
for( i = 0; i < Len - 1; i = i + 2 )
{
amp[ i ] = amp[ i + 1 ] = sqrt(ffc[ i ]^ 2 + ffc[ i + 1 ]^2);
phase[ i ] = phase[ i + 1 ] = atan2( ffc[ i + 1], ffc[ i ] );
}
SEE ALSO
atan() function
References:
The atan2 function is used in the following formulas in AFL on-line library:
More information:
Updated on-line reference
atan2 - calculates arctangent of y/x
618
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
Indicators
(AFL 1.3)
ATR
- average true range
SYNTAX
atr( period )
RETURNS
ARRAY
FUNCTION
Calculates Average True Range indicator
EXAMPLE
atr(7)
SEE ALSO
Comments:
Bob Jagow
[email protected]
2003-02-06 23:37:50
For other MAs, use ATR(1) to get the True Range.
Tomasz Janeczko
tj --at-amibroker.com
2005-02-03 06:46:39
Note that original formulation of ATR (the one that AmiBroker
implements)
uses WILDERS smoothing (not simple moving average)
E.g., MA(ATR(1),period), WMA(ATR(1),period), etc.
For more details check this page:
http://stockcharts.com/education/IndicatorAnalysis/indic_ATR.html
References:
The ATR function is used in the following formulas in AFL on-line library:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Pivots And Prices And Swing Volume
Alternative ZIG function
Alternative ZIG type function, multi TF
AR_Prediction.afl
ATR Study
AutoTrade using an Exploration
BB squeeze
Bollinger - Keltner Bands
Bollinger Band Gap
Bow tie
Chandelier Exit
Chandelier Exit
Chandelier Exit or Advanced Trailing Stop
Chandelier Plugin
Channel/SRand trendlines
Commodity Selection Index (CSI)
Gann Swing Charts in 3 modes with text
Gartley 222 Pattern Indicator
Gordon Rose
Hull Range Indicator
Jesse Livermore Strategy
Keltner Channel
mitalpradip
Perceptron
ATR - average true range
619
AmiBroker 5.80 User’s Guide
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
AmiBroker Formula Language (AFL)
Peterson
PF Chart - Close - April 2004
Pivots And Prices
Point &figure Chart India Securities
Position Sizing and Risk Price Graph
Position Sizing and Risk Price Graph - 2
Random Walk Index, base formula included
Raw ADX
Renko Chart
SectorRSI
SF Entry,Stop, PT Indicator
STARC Bands
Steve Woods’ Cum. Vol. Float + Cum. Vol. Channels
STO &MACD Buy Signals with Money-Management
Stop-loss Indicator bands
Super Trend Indicator
Tracking Error
Tracking Error
Trading ATR 10-1
Trigonometric Fit - TrigFit with AR for cos / sin
TTM Squeeze
Vivek Jain
Volatility Quality Index
Volatility System
VSTOP (2)
VSTOP (3)
Weinberg’s The Range Indicator
More information:
Updated on-line reference
ATR- average true range
620
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
BarIndex
- get zero-based bar number
SYNTAX
BarIndex()
RETURNS
ARRAY
FUNCTION
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.
EXAMPLE
ThisIsLastBar = BarIndex() == LastValue( BarIndex() );
SEE ALSO
CUM() function
Date/Time
(AFL 2.3)
Comments:
Tomasz Janeczko
tj --at-amibroker.com
2004-07-23 07:07:29
When QuickAFL is ON, the BarIndex() may not be equal
with array item index.
Actual array item
corresponding to bar index can be found this way:
bi = BarIndex();
arrayitem = SelectedValue( bi ) - bi[ 0 ];
"Close at selected bar:" + Close[ arrayitem ];
Rolly
[email protected]
2007-11-03 14:12:22
BarIndex() returns an array and LastValue() returns a
number. The API’s example compares the two to give the
boolean ThisIsLastBar. How could an array be compared
with a number? How could it work? Please explain.
Tomasz Janeczko
tj at amibroker dot
com
2007-11-04 09:14:21
That’s simple - it compares each array element to a
number and produces array as a result. Detailed
explanation in User’s Guide: Tutorial: Understanding AFL
References:
The BarIndex function is used in the following formulas in AFL on-line library:
•
•
•
•
•
•
•
•
•
•
2 Timeframes Candlestick Bar Chart
3TF Candlestick Bar Chart
Adaptive Price Channel
Alternative ZIG function
Alternative ZIG type function, multi TF
Andrews Pitchfork
Andrews PitchforkV3.3
Another FIb Level
AR_Prediction.afl
Auto-Optimization Framework
BarIndex - get zero-based bar number
621
AmiBroker 5.80 User’s Guide
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
AmiBroker Formula Language (AFL)
Automatic Trendlines using multiple timeframes
babaloo chapora
Basket Trading System T101
BEANS-Summary of Holdings
Bullish Percent Index 2004
Candle Identification
Candle Stick Analysis
Candle Stick Demo
CCI(20) Divergence Indicator
Chandelier Exit
Channel/SRand trendlines
Chart Zoom
com-out
Congestions detection
crMathLib
Cycle Highlighter
Cycle Highlighter (auto best-fit)
Cycle Period
Date_To_Num(), Time_To_Num()
Elder safe Zone Long + short
Fast Refreshed KAGI Swing Charts (Price Swing)
Fibonacci Calculations &Speed Resistance
Fibonacci Internal and External Retracements
FirstBarIndex(), LastBarIndex()
Future Plotting of Time and Price
Future Plotting of Time and Price
Gann Swing Charts in 3 modes with text
Gordon Rose
Graphical sector analysis
Graphical sector stock amalysis
Heikin-Ashi(Koma-Ashi) with Moving Average
Hurst "Like" DE
Intraday Fibonacii Trend Break System
Intraday Range and Periods Framer
Intraday Trend Break System
Inverted Plotted Volume Overlay Indicator
JEEVAN’S SRI CHAKRA
Linear Regression Line w/ Std Deviation Channels
MACD indicator display
Market Profile
MFE and MAE and plot trades as indicator
Multiple Ribbon Demo
Multiple sinus noised
nth ( 1 - 8 ) Order Polynomial Fit
PF Chart - Close - April 2004
Pivot Finder
Point &figure Chart India Securities
Probability Density &Gaussian Distribution
Rea Time Daily Price Levels
Relative Strength Multichart of up to 10 tickers
Schiff Lines
shailu lunia
BarIndex - get zero-based bar number
622
AmiBroker 5.80 User’s Guide
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
AmiBroker Formula Language (AFL)
Square of Nine Roadmap Charts
suresh
tomy_frenchy
Trend Detection
Trend exploration with multiple timeframes
Trend Exploration: Slope Moving Average
Trend Lines from 2 points
Trigonometric Fit - TrigFit with AR for cos / sin
Using From and To dates from Auto Analysis in Code
Visible Min and Max Value Demo
VWAP - Volume Weighted Average Price
WLBuildProcess
Woodie’s CCI Panel Full Stats
Zig Zag Indicator with Valid Entry and Exit Points
ZigZag Retracements
More information:
Updated on-line reference
BarIndex- get zero-based bar number
623
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
Trading system toolbox
BarsSince
- bars since
SYNTAX
BarsSince( ARRAY )
RETURNS
ARRAY
FUNCTION
Calculates the number of bars (time periods) that have passed since
ARRAY was true (or 1)
EXAMPLE
barssince( macd() < 0 )
SEE ALSO
References:
The BarsSince function is used in the following formulas in AFL on-line library:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Pivots And Prices And Swing Volume
Alternative ZIG function
Alternative ZIG type function, multi TF
Andrews PitchforkV3.3
AR_Prediction.afl
Auto-Optimization Framework
Automatic Linear Trend Channel
Automatic Linear Trend Channel 2
Automatic trend channel
automatic trendlines using fractal patterns
Automatic Trendlines using multiple timeframes
Awsome Oscilator
Buyer Seller Force
CCI 14 DrBobStyle
CCI 50 DrBob Style
CCI Woodies Style
CCI(20) Divergence Indicator
Channel/SRand trendlines
Cole
Commodity Channel Index
Connors TPS
ConnorsRSI
Cycle Highlighter
Cycle Highlighter (auto best-fit)
Divergences
ekeko price chart
Elder Impulse Indicator V2
FastStochK FullStochK-D
Fib Fan Based on ZZ
Follow the Leader
Fund Screener
Gann Swing Chart
Gann Swing Charts in 3 modes with text
Heatmap V1
Intraday Average Volume
BarsSince - bars since
624
AmiBroker 5.80 User’s Guide
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
AmiBroker Formula Language (AFL)
IntraDay Open Marker
Intraday Volume EMA
Lagging MA-Xover
MACD commentary
MACD indicator display
Market Profile
mitalpradip
Moving Averages NoX
MO_CrashZone
Performance Check
Peterson
Positive Bars Percentage
prakash
Price Persistency
Rea Time Daily Price Levels
Relative Strength Index
Schiff Lines
Stochastic Divergence, negative
Stochastic Divergence, positive
Stochastic Divergences, PDI, NDI
Stochastic Fast%K and Full
Stops Implementation in AFS
TD sequential
TD Sequential
The Fibonaccian behavior
The Three Day Reversal
Trade day of month
Trend Analysis_Comentary
Triangular Moving Average
Triangular Moving Average new
Trigonometric Fit - TrigFit with AR for cos / sin
Trix Bars number
VWAP - Volume Weighted Average Price
VWAP versus Average Price
Williams Alligator system
Woodie’s CCI Panel Basic
Woodie’s CCI Panel Full Stats
Zig Zag Indicator with Valid Entry and Exit Points
ZigZag Hi Lo Barcount
More information:
Updated on-line reference
BarsSince- bars since
625
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
BBandBot
- bottom bollinger band
SYNTAX
BBandBot( ARRAY, periods = 15, width = 2 )
RETURNS
ARRAY
FUNCTION
Calculates the bottom Bollinger Band of ARRAY shifted down width
standard deviations (using periods averaging range ).
EXAMPLE
bbandbot( close, 10, 2 )
Indicators
SEE ALSO
References:
The BBandBot function is used in the following formulas in AFL on-line library:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
babaloo chapora
Bman’s HaDiffCO
bolingerbands
Bollinger - Keltner Bands
Bollinger band normalization
bonlinger bands
Congestions detection
ekeko price chart
Intraday Fibonacii Trend Break System
INTRADAY HEIKIN ASHI new
prakash
RUTVOL timing signal with BB Scoring routine
TTM Squeeze
Volatility Breakout with Bollinger Bands
More information:
Updated on-line reference
BBandBot - bottom bollinger band
626
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
BBandTop
- top bollinger band
SYNTAX
BBandTop( ARRAY, periods = 15, width = 2 )
RETURNS
ARRAY
FUNCTION
Calculates the top Bollinger Band of ARRAY shifted up width standard
deviations (using periods averaging range ).
EXAMPLE
bbandtop( close, 10, 2 )
Indicators
SEE ALSO
References:
The BBandTop function is used in the following formulas in AFL on-line library:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
babaloo chapora
Bman’s HaDiffCO
bolingerbands
Bollinger - Keltner Bands
Bollinger Band Gap
Bollinger band normalization
bonlinger bands
Congestions detection
ekeko price chart
Intraday Fibonacii Trend Break System
INTRADAY HEIKIN ASHI new
prakash
RUTVOL timing signal with BB Scoring routine
TTM Squeeze
Volatility Breakout with Bollinger Bands
More information:
Updated on-line reference
BBandTop - top bollinger band
627
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
BeginValue
- Value of the array at the begin of the range
SYNTAX
BeginValue( ARRAY )
RETURNS
NUMBER
FUNCTION
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.
Date/Time
(AFL 2.3)
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 > < markers will appear above date axis.
EXAMPLE
1. Simple commentary:
WriteVal( BeginValue( DateTime() ), formatDateTime );
WriteVal( EndValue( DateTime() ), formatDateTime );
"Precentage change of close is " +
WriteVal( 100 * (EndValue( Close ) - BeginValue( Close
))/BeginValue( Close ) ) + "%";
2. Get the number of bars in the range and calculate some stats for
that range:
Period = EndValue( BarIndex() ) - BeginValue( BarIndex() );
StandardDeviationInTheRange = EndValue( StDev( Close, Period ) );
SEE ALSO
ENDVALUE() function
References:
The BeginValue function is used in the following formulas in AFL on-line library:
•
•
•
•
•
•
•
•
Adaptive Price Channel
Another FIb Level
Congestions detection
Elder safe Zone Long + short
Futures - Dollar Move Indicator
nth ( 1 - 8 ) Order Polynomial Fit
Relative Strength Multichart of up to 10 tickers
Trend Lines from 2 points
More information:
Updated on-line reference
BeginValue - Value of the array at the begin of the range
628
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
CategoryAddSymbol
- adds a symbol to a category
Information / Categories
(AFL 2.5)
SYNTAX
CategoryAddSymbol( symbol, category, number )
RETURNS
NOTHING
FUNCTION
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.
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.
ignored for categoryFavorite, categoryIndex
The meaning of index parameter is different for GICS and ICB
categories - the index for categoryGICS and categoryICB is actually
GICS/ICB code. Such as 10 for energy sector or 351010 for "Health
Care Equipment &supplies" industry. The codes are fixed even if new
classifications are added at some point in the future. This means
that you won’t need to change AFL codes even if new classifications
are added. But it is important to understand that these codes work in
hierarchical way. So
GetCategorySymbols( categoryGICS, 10 )
will return all symbols belonging to energy sector, including those
in 10101010 - Oil &Gas Drilling sector as well as 10102050 - Coal
&Consumable Fuels; for example. See
http://en.wikipedia.org/wiki/Global_Industry_Classification_Standard
for more details on GICS system
http://en.wikipedia.org/wiki/Industry_Classification_Benchmark for
more details on ICB system
CategoryAddSymbol - adds a symbol to a category
629
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
EXAMPLE
// the code adds symbols with last day volume > 100000
// to the watch list number 1
if( LastValue( V ) > 100000 )
{
CategoryAddSymbol( "", categoryWatchlist, 1 );
}
SEE ALSO
CategoryGetName() function , CategoryGetSymbols() function
References:
The CategoryAddSymbol function is used in the following formulas in AFL on-line
library:
• Calculate composites for tickers in list files
• Heatmap V1
• WLBuildProcess
More information:
Updated on-line reference
CategoryAddSymbol- adds a symbol to a category
630
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
CategoryCreate
- add new category (such as watch list)
Information / Categories
(AFL 3.70)
SYNTAX
CategoryCreate("name", category )
RETURNS
STRING
FUNCTION
CategoryCreate( "name", category ) - adds new category (currently
supports only adding watchlists)
newwl = CategoryCreate( "name", categoryWatchlist );
This will add (create new) watch list with "name" (if it does not
exist) or will return existing "name" watch list
newwl will hold new watch list index.
Currently only creation of watch list is supported by this function.
EXAMPLE
newwl = CategoryCreate( "name", categoryWatchlist );
SEE ALSO
CategoryAddSymbol() function , CategoryFind() function ,
CategoryGetName() function , CategoryGetSymbols() function ,
CategoryRemoveSymbol() function , CategorySetName() function
References:
The CategoryCreate function is used in the following formulas in AFL on-line
library:
More information:
Updated on-line reference
CategoryCreate - add new category (such as watch list)
631
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
CategoryFind
- search for category by name
Information / Categories
(AFL 3.0)
SYNTAX
CategoryFind( ’’name’’, category )
RETURNS
NUMBER
FUNCTION
It allows to search for category by name. It takes category name and
kind as parameters and returns INDEX (ordinal number).
For example it allows to find watch list index by name.
Supported categories:
•
•
•
•
•
•
•
•
•
categoryMarket
categoryGroup
categorySector
categoryIndustry
categoryWatchlist
categoryFavorite
categoryIndex
categoryGICS
categoryICB
The index (in the example below watch list number) can be later used
in functions that need the index (like CategoryGetSymbols).
EXAMPLE
wlnumber = CategoryFind("MyWatch List 1", categoryWatchlist );
mysymbols = CategoryGetSymbols(categoryWatchlist, wlnumber );
SEE ALSO
CategoryAddSymbol() function , CategoryGetName() function ,
CategoryGetSymbols() function , CategoryRemoveSymbol() function
References:
The CategoryFind function is used in the following formulas in AFL on-line
library:
More information:
Updated on-line reference
CategoryFind - search for category by name
632
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
CategoryGetName
- get the name of a category
Information / Categories
(AFL 2.5)
SYNTAX
CategoryGetName( category, number)
RETURNS
STRING
FUNCTION
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.
ignored for categoryFavorite, categoryIndex
The meaning of index parameter is different for GICS and ICB
categories - the index for categoryGICS and categoryICB is actually
GICS/ICB code. Such as 10 for energy sector or 351010 for "Health
Care Equipment &supplies" industry. The codes are fixed even if new
classifications are added at some point in the future. This means
that you won’t need to change AFL codes even if new classifications
are added. But it is important to understand that these codes work in
hierarchical way. So
GetCategorySymbols( categoryGICS, 10 )
will return all symbols belonging to energy sector, including those
in 10101010 - Oil &Gas Drilling sector as well as 10102050 - Coal
&Consumable Fuels; for example. See
http://en.wikipedia.org/wiki/Global_Industry_Classification_Standard
for more details on GICS system
http://en.wikipedia.org/wiki/Industry_Classification_Benchmark for
more details on ICB system
EXAMPLE
CategoryGetName( categoryWatchlist, 1 );
SEE ALSO
CategoryGetSymbols() function
CategoryGetName - get the name of a category
633
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
References:
The CategoryGetName function is used in the following formulas in AFL on-line
library:
• In Watch List
More information:
Updated on-line reference
CategoryGetName- get the name of a category
634
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
CategoryGetSymbols
- retrieves comma-separated list of symbols belonging
to given category
SYNTAX
CategoryGetSymbols( category, index, mode = 0 )
RETURNS
STRING
FUNCTION
Retrieves comma-separated list of symbols belonging to given category
Supported categories:
•
•
•
•
•
•
•
•
•
•
Information /
Categories
(AFL 2.5)
categoryMarket
categoryGroup
categorySector
categoryIndustry
categoryWatchlist
categoryFavorite
categoryIndex
categoryGICS
categoryICB
categoryAll (new in 5.50) - means all symbols in the database (
index is a market/group/industry/sector/watchlist number:
0..255 for categoryMarket, categoryGroup, categoryIndustry
0..63 for categorySector
no limit for categoryWatchlist.
ignored for categoryFavorite, categoryIndex
mode - (new in 5.50) mode parameter decides what field is retrieved:
• 0 (default value) - ticker symbol
• 1 - full name
The meaning of index parameter is different for GICS and ICB
categories - the index for categoryGICS and categoryICB is actually
GICS/ICB code. Such as 10 for energy sector or 351010 for "Health
Care Equipment &supplies" industry. The codes are fixed even if new
classifications are added at some point in the future. This means
that you won’t need to change AFL codes even if new classifications
are added. But it is important to understand that these codes work in
hierarchical way. So
GetCategorySymbols( categoryGICS, 10 )
will return all symbols belonging to energy sector, including those
in 10101010 - Oil &Gas Drilling sector as well as 10102050 - Coal
&Consumable Fuels; for example. See
http://en.wikipedia.org/wiki/Global_Industry_Classification_Standard
for more details on GICS system
http://en.wikipedia.org/wiki/Industry_Classification_Benchmark for
more details on ICB system
CategoryGetSymbols - retrieves comma-separated list of symbols belonging to given category 635
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
Use StrExtract function to extract individual symbols from the list.
EXAMPLE
/* note: if given watch list contains lots of symbols
** performance may be poor
** AVOID SUCH CODES IN REAL-TIME MODE !
*/
function CreateAverageForWatchList( listnum )
{
// retrive comma-separated list of symbols in watch list
list = CategoryGetSymbols( categoryWatchlist, listnum );
Average = 0; // just in case there are no watch list members
for( i = 0; ( sym = StrExtract( list, i ) ) != ""; i++ )
{
f = Foreign( sym, "C" );
if( i == 0 ) Average = f;
else Average = Average + f;
}
return Average / i; // divide by number of components
}
Plot( CreateAverageForWatchList( 1 ), "Avg of WL 1", colorGreen );
Example 2, retrieving all symbols tickers and full names // to get
all ticker symbols
CategoryGetSymbols( categoryAll, 0 );
//to get full names of all symbols use:
CategoryGetSymbols( categoryAll, 0, 1 );
SEE ALSO
GETCATEGORYSYMBOLS() function , StrExtract() function , INWATCHLIST()
function , CategoryGetName() function
References:
The CategoryGetSymbols function is used in the following formulas in AFL on-line
library:
•
•
•
•
•
•
•
•
•
AFL_Glossary_1
Basket Trading System T101
Calculate composites for tickers in list files
Graphical sector stock amalysis
Heatmap V1
IB Backfiller
IBD relative strength database ranker
Optimal Weights
Relative Strength
More information:
Updated on-line reference
CategoryGetSymbols- retrieves comma-separated list of symbols belongingto given category
636
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
CategoryRemoveSymbol
- remove a symbol from a category
SYNTAX
CategoryRemoveSymbol( symbol, category, number )
RETURNS
NOTHING
FUNCTION
Removes the symbol from given category.
Information / Categories
(AFL 2.5)
Note that for markets, groups, industries ’removing’ means moving
from given category to category with number zero, 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.
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.
ignored for categoryFavorite, categoryIndex
The meaning of index parameter is different for GICS and ICB
categories - the index for categoryGICS and categoryICB is actually
GICS/ICB code. Such as 10 for energy sector or 351010 for "Health
Care Equipment &supplies" industry. The codes are fixed even if new
classifications are added at some point in the future. This means
that you won’t need to change AFL codes even if new classifications
are added. But it is important to understand that these codes work in
hierarchical way. So
GetCategorySymbols( categoryGICS, 10 )
will return all symbols belonging to energy sector, including those
in 10101010 - Oil &Gas Drilling sector as well as 10102050 - Coal
&Consumable Fuels; for example. See
http://en.wikipedia.org/wiki/Global_Industry_Classification_Standard
for more details on GICS system
http://en.wikipedia.org/wiki/Industry_Classification_Benchmark for
CategoryRemoveSymbol - remove a symbol from a category
637
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
more details on ICB system
EXAMPLE
// the code removes the symbols with last day volume < 1000
// from the watch list number 1
if( LastValue( V ) < 1000 )
{
CategoryRemoveSymbol( "", categoryWatchlist, 1 );
}
SEE ALSO
CategoryAddSymbol() function , CategoryGetName() function ,
CategoryGetSymbols() function
References:
The CategoryRemoveSymbol function is used in the following formulas in AFL
on-line library:
• Calculate composites for tickers in list files
• Heatmap V1
• WLBuildProcess
More information:
Updated on-line reference
CategoryRemoveSymbol- remove a symbol from a category
638
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
CategorySetName
- set the name of category (group, market, watch
list, industry)
SYNTAX
CategorySetName( name, category, number )
RETURNS
NOTHING
FUNCTION
Function sets the name of category (group,market, watch list,
industry)
Information /
Categories
(AFL 3.20)
Arguments;
• name - a new name for the category (in case of watch lists it
has to be unique)
• category - type of category, one of the following:
categoryMarket, categoryGroup, categorySector,
categoryIndustry, categoryWatchlist, categoryGICS, categoryICB
• number - the number (index) of the category 0.255 for market,
group industry, 0..32 for sectors, 0...unlimited for watch
lists
Please note that the function will NOT create watch list of given
index if one does not exist.
The meaning of index parameter is different for GICS and ICB
categories - the index for categoryGICS and categoryICB is actually
GICS/ICB code. Such as 10 for energy sector or 351010 for "Health
Care Equipment &supplies" industry. The codes are fixed even if new
classifications are added at some point in the future. This means
that you won’t need to change AFL codes even if new classifications
are added. But it is important to understand that these codes work in
hierarchical way. So
GetCategorySymbols( categoryGICS, 10 )
will return all symbols belonging to energy sector, including those
in 10101010 - Oil &Gas Drilling sector as well as 10102050 - Coal
&Consumable Fuels; for example. See
http://en.wikipedia.org/wiki/Global_Industry_Classification_Standard
for more details on GICS system
http://en.wikipedia.org/wiki/Industry_Classification_Benchmark for
more details on ICB system
EXAMPLE
CategorySetName( "Testing", categoryWatchList, 1 );
SEE ALSO
CategoryAddSymbol() function , CategoryFind() function ,
CategoryGetName() function , CategoryGetSymbols() function ,
CategoryRemoveSymbol() function
CategorySetName - set the name of category (group, market, watch list, industry)
639
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
References:
The CategorySetName function is used in the following formulas in AFL on-line
library:
More information:
Updated on-line reference
CategorySetName- set the name of category (group, market, watchlist, industry)
640
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
CCI
- commodity channel index
SYNTAX
CCI( periods = 14 )
CCIa( array, periods = 14 )
RETURNS
ARRAY
FUNCTION
Calculates the Commodity Channel Index (using periods averaging
range ).
Second version (CCIa) accepts input array, so CCI can be applied to
array different than close. (CCIa exists in AFL 2.2+ only (v.4.20+))
EXAMPLE
CCI( 14 )
CCIa( High, 14 );
Indicators
SEE ALSO
Comments:
Tomasz Janeczko
tj --at-amibroker.com
2003-09-03 04:24:35
CCI uses internally ’Avg’ built-in price array.
’Avg’ is also known as typical price:
Avg = ( H + L + C ) /3
So
CCI( period ) is equivalent to CCia( Avg, period ).
Therefore if you want to calculate CCI from Foreign ticker
you should overwrite Avg array,
instead of OHLC:
Avg = ( Foreign("!VIX", "H") + Foreign("!VIX", "L") +
Foreign("!VIX", "C") ) / 3;
cc = CCI(period);
Alternativelly use CCIa that takes array directly:
cc = CCIa( Foreign("!VIX", "H") + Foreign("!VIX", "L") +
Foreign("!VIX", "C") ) / 3, period);
References:
The CCI function is used in the following formulas in AFL on-line library:
•
•
•
•
•
•
•
•
Adaptave Zones O/B &O/S Oscillator
Auto-Optimization Framework
CCI 14 DrBobStyle
CCI 50 DrBob Style
CCI Woodies Style
CCI(20) Divergence Indicator
CCI/DI+- COMBO indicator
Commodity Channel Index
CCI - commodity channel index
641
AmiBroker 5.80 User’s Guide
•
•
•
•
•
•
•
AmiBroker Formula Language (AFL)
JEEVAN’S SRI CHAKRA
Price with Woodies Pivots
RSIS
The Stochastic CCI
Woodie’s CCI Panel Basic
Woodie’s CCI Panel Full Stats
Woodies CCI
More information:
Updated on-line reference
CCI- commodity channel index
642
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
Math functions
ceil
- ceil value
SYNTAX
ceil( number )
ceil( array )
RETURNS
NUMBER,
ARRAY
FUNCTION
Calculates the lowest integer that is greater than NUMBER or ARRAY.
EXAMPLE
The formula ceil( 6.2 ) returns 7; the formula ceil(-6.2) returns
-6.
SEE ALSO
FLOOR() function , INT() function , ROUND() function
References:
The ceil function is used in the following formulas in AFL on-line library:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
AR_Prediction.afl
Bullish Percent Index 2 files combined
Bullish Percent Index 2004
Gann Swing Charts in 3 modes with text
JEEVAN’S SRI CHAKRA
Market Profile
Murrey Math Price Lines
N-period candlesticks (time compression)
PFChart - High/Low prices Sept2003
PFchart with range box sizes
PF Chart - Close - April 2004
Point &figure Chart India Securities
Renko Chart
Triangle exploration using PFChart
Trigonometric Fit - TrigFit with AR for cos / sin
More information:
Updated on-line reference
ceil - ceil value
643
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
Chaikin
- chaikin oscillator
SYNTAX
chaikin( fast = 9, slow = 14 )
RETURNS
ARRAY
FUNCTION
Calculates the Chaikin Oscillator with averaging parameters: fast,
slow
Indicators
EXAMPLE
SEE ALSO
References:
The Chaikin function is used in the following formulas in AFL on-line library:
More information:
Updated on-line reference
Chaikin - chaikin oscillator
644
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
ClipboardGet
- retrieves current contents of Windows
clipboard
SYNTAX
ClipboardGet()
RETURNS
STRING
FUNCTION
Retrieves current contents of Windows clipboard
Miscellaneous functions
(AFL 2.60)
EXAMPLE
"Contents of the Windows clipboard" + ClipboardGet();
SEE ALSO
ClipboardSet() function
References:
The ClipboardGet function is used in the following formulas in AFL on-line
library:
More information:
Updated on-line reference
ClipboardGet - retrieves current contents of Windows clipboard
645
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
ClipboardSet
- copies the text to the Windows clipboard
Miscellaneous functions
(AFL 2.6)
SYNTAX
ClipboardSet( ’’Text’’ );
RETURNS
NUMBER
FUNCTION
Copies the "text" to the Windows clipboard.
Returns True (1) on success and 0 on failure
EXAMPLE
// this can be used to put dynamically-constructed texts into
// clipboard
//
ClipboardSet( "The price of " + FullName() + " is " + Close );
SEE ALSO
ClipboardGet() function
References:
The ClipboardSet function is used in the following formulas in AFL on-line
library:
More information:
Updated on-line reference
ClipboardSet - copies the text to the Windows clipboard
646
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
ColorBlend
- blends (mixes) two colors
SYNTAX
ColorBlend( colorFrom, colorTo, factor = 0.5 )
RETURNS
NUMBER
FUNCTION
The function blends (mixes) colorFrom with colorTo with ’factor’
proportion using the following algorithm
Indicators
(AFL 3.30)
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.
EXAMPLE
This function makes it easy to lighten or darken colors like this:
function ColorLighten( color )
{
return ColorBlend( color, colorWhite, 0.5 );
}
function ColorDarken( color )
{
return ColorBlend( color, colorBlack, 0.5 );
}
SEE ALSO
ColorRGB() function , ColorHSB() function
References:
The ColorBlend function is used in the following formulas in AFL on-line library:
•
•
•
•
•
2 Timeframes Candlestick Bar Chart
3TF Candlestick Bar Chart
Fib Fan Based on ZZ
Ichimoku Kinko Hyo
Intraday Trend Break System
More information:
Updated on-line reference
ColorBlend - blends (mixes) two colors
647
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
ColorHSB
- specify color using Hue-Saturation-Brightness
SYNTAX
ColorHSB( hue, saturation, brightness )
RETURNS
NUMBER
FUNCTION
The function allows to specify color out of 16 million color (24
bit) palette using Hue, Saturation and Brightness parameters.
Miscellaneous functions
(AFL 2.80)
The return value is a number that can be used in Plot, PlotOHLC,
PlotForeign, AddColumn, AddTextColumn functions to specify chart or
column color.
Parameters:
• hue - represents gradation of color within the optical
spectrum (as in rainbow)
• saturation represents "vibrancy" of the color
• brightness represents brightness.
Each parameter ranges from 0 to 255, where 0 represents 0%
saturation/brightness or 0 degree hue in HSV color wheel, and 255
represents 100% saturation/brightness or 360degrees hue in HSV color
wheel.
When you modify hue from 0 to 255 you will see consecutive rainbow
colors starting from red, through yellow and green to blue and
violet.
For more information about HSB color space please read:
http://en.wikipedia.org/wiki/HSB_color_space
EXAMPLE
// Example 1:
// 3-d multicolor multiple moving average cloud chart
side = 1;
increment = Param("Increment",2, 1, 10, 1 );
for( i = 10; i < 80; i = i + increment )
{
up = MA( C, i );
down = MA( C, i + increment );
if( ParamToggle("3D effect?", "No|Yes" ) )
side = IIf(up<=down AND Ref( up<=down, 1 ), 1, 0.6 );
PlotOHLC( up,up,down,down, "MA"+i, ColorHSB( 3*(i - 10),
Param("Saturation", 128, 0, 255 ),
side * Param("Brightness", 255, 0, 255 ) ), styleCloud |
styleNoLabel );
}
ColorHSB - specify color using Hue-Saturation-Brightness
648
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
// Example 2:
///////
//Color-parade exploration
Filter=1;
for( i = 0; i < 256; i = i + 16 )
AddColumn( C, "C", 1.2, colorDefault, ColorHSB( ( BarIndex() + i )
% 256, 255-i, 255 ) );
SEE ALSO
ColorRGB() function , PLOT() function , AddColumn() function
References:
The ColorHSB function is used in the following formulas in AFL on-line library:
•
•
•
•
•
Animated BackGround
Animated BackGround 1.1
Brian Wild
IchimokuBrianViorelRO
Market Profile
More information:
Updated on-line reference
ColorHSB- specify color using Hue-Saturation-Brightness
649
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
ColorRGB
- specify color using Red-Green-Blue components
SYNTAX
ColorRGB( red, green, blue )
RETURNS
NUMBER
FUNCTION
The function allows to specify color out of 16 million color (24
bit) palette using Red, Green, Blue components.
Miscellaneous
functions
(AFL 2.80)
The return value is a number that can be used in Plot, PlotOHLC,
PlotForeign, AddColumn, AddTextColumn functions to specify chart or
column color.
Parameters:
red, green, blue - represent color component values in range 0..255
each
For more information about RGB color model please read:
http://en.wikipedia.org/wiki/RGB_color_model
EXAMPLE
Plot( MA(C,10), "Light Red", ColorRGB( 255, 128, 128 ) ); Plot(
MA(C,20), "Light Green", ColorRGB( 128, 255, 128 ) ); Plot(
MA(C,30), "Light Blue", ColorRGB( 128, 128, 255 ) );
SEE ALSO
ColorHSB() function , PLOT() function , AddColumn() function
References:
The ColorRGB function is used in the following formulas in AFL on-line library:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
ALJEHANI
Alternative ZIG function
Automatic Linear Trend Channel
Automatic Linear Trend Channel 2
Automatic trend channel
Automatic Trendlines using multiple timeframes
Channel/SRand trendlines
Continuous Contract Rollover
Cycle Period
Fib Fan Based on ZZ
Heatmap V1
Hurst "Like" DE
Intraday Range and Periods Framer
Meu Sistema de Trading - versªo 1.0
Multiple Ribbon Demo
Perceptron
Probability Density &Gaussian Distribution
Rebalancing Backtest avoiding leverage
TD Sequential
VSTOP (2)
VSTOP (3)
ColorRGB - specify color using Red-Green-Blue components
650
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
• VWAP versus Average Price
• WILSON RELATIVE PRICE CHANNEL
More information:
Updated on-line reference
ColorRGB- specify color using Red-Green-Blue components
651
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
Statistical functions
(AFL 1.4)
Correlation
- correlation
SYNTAX
correlation( ARRAY1, ARRAY2, periods )
RETURNS
ARRAY
FUNCTION
Calculates correlation between ARRAY1 and ARRAY2 using periods range
For more information about correlation please check this:
http://en.wikipedia.org/wiki/Correlation
EXAMPLE
// the line below calculates
// Correlation between Close price AND AND Close price 5 days back
Correlation( Close, Ref( Close, -5 ), 5 );
//
//
//
//
Built-in correlation can be re-coded with
basic AFL functions like MA (moving average) - which
is equivalent for "expected value" statistic term
and few basic arithmetic operations
function Correl( x, y, number )
{
nom= MA( x * y, number ) - MA( x, number ) * MA( y, number );
denom = sqrt( MA( x ^ 2, number ) - MA( x, number ) ^ 2 ) *
sqrt( MA( y ^ 2, number ) - MA( y, number ) ^ 2 );
return nom/denom;
}
Graph0=Correlation( C, Ref( H, -2 ), 10 ); // built-in
Graph1=Correl( C, Ref( H, -2 ), 10 ); // re-coded;
SEE ALSO
References:
The Correlation function is used in the following formulas in AFL on-line
library:
•
•
•
•
•
•
•
•
Alpha and Beta and R_Squared Indicator
correlerror
crMathLib
Cycle Highlighter
Cycle Highlighter (auto best-fit)
Inter-market Yield Linear Regression Divergence
R-Squared
Trend Exploration: Count Number of New Highs
Correlation - correlation
652
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
More information:
Updated on-line reference
Correlation- correlation
653
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
Math functions
cos
- cosine
SYNTAX
cos( NUMBER )
cos( ARRAY )
RETURNS
NUMBER
ARRAY
FUNCTION
Returns the cosine of NUMBER or ARRAY. Assumes that the NUMBER or
ARRAY values are in radians.
EXAMPLE
cos( C )
SEE ALSO
atan() function , SIN() function
References:
The cos function is used in the following formulas in AFL on-line library:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
AR_Prediction.afl
Cybernertic Hilbert Sine Wave
Cycle Period
Hilbert Sine Wave
Hilbert Sine Wave Support &Resistance
Hilbert Sine Wave with Hull Moving Average
John Ehler
Luna Phase
Sine Wave Indicator
Smoothed Adaptive Momentum
Trigonometric Fit - TrigFit with AR for cos / sin
Woodie’s CCI Panel Basic
Woodie’s CCI Panel Full Stats
Woodie’s Price Panel With Woodie’s Pivots
More information:
Updated on-line reference
cos - cosine
654
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
cosh
- hyperbolic cosine function
SYNTAX
cosh( NUMBER )
cosh( ARRAY )
RETURNS
NUMBER,
ARRAY
FUNCTION
Returns the hyperbolic cosine of NUMBER or ARRAY. This function
assumes that the ARRAY values are in radians.
Math functions
(AFL 2.80)
EXAMPLE
SEE ALSO
References:
The cosh function is used in the following formulas in AFL on-line library:
More information:
Updated on-line reference
cosh - hyperbolic cosine function
655
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
CreateObject
- create COM object
Miscellaneous functions
(AFL 1.8)
SYNTAX
createobject(
RETURNS
OBJECT
FUNCTION
Creates the instance of "Server.Class" COM object. The return value
should be assigned to a variable that is used latter for calling the
methods of the object.
Note: this function creates the instance of the object everytime the
formula is executed (the object is released automatically at the end
of the formula - no explicit freeing is necessary)
EXAMPLE
myobj = CreateObject("MyOwnActiveX.Class1");
myobj.Method( 1, 2, Close ); // call the method of myobj COM object
SEE ALSO
CREATESTATICOBJECT() function
References:
The CreateObject function is used in the following formulas in AFL on-line
library:
•
•
•
•
•
•
•
•
AFL to Python COM Link
AFL-Excel
Auto Export to Gif
Calculate composites for tickers in list files
Chart Zoom
Heatmap V1
LoadAB.vbs
SectorRSI
More information:
Updated on-line reference
CreateObject - create COM object
656
AmiBroker 5.80 User’s Guide
CreateStaticObject
- create static COM object
AmiBroker Formula Language (AFL)
Miscellaneous functions
(AFL 1.8)
SYNTAX
createstaticobject(
RETURNS
OBJECT
FUNCTION
Creates the single static instance (one per AmiBroker session) of
"Server.Class" COM object. The return value should be assigned to a
variable that is used latter for calling the methods of the object.
This function is useful for "heavyweight" COM object like QuotesPlus
ActiveX for example.
Note: this function creates the instance of the object only once
when the formula is executed for the first time. Then the object is
cached internally for all consecutive calls. It is also shared if
multiple formulas use the same object using CreateStaticObject call.
The object is automatically released when AmiBroker is closed.
EXAMPLE
myobj = CreateStaticObject("MyOwnActiveX.Class1");
myobj.Method( 1, 2, Close ); // call the method of myobj COM object
SEE ALSO
CreateObject() function
References:
The CreateStaticObject function is used in the following formulas in AFL on-line
library:
More information:
Updated on-line reference
CreateStaticObject - create static COM object
657
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
Cross
- crossover check
Trading system toolbox
SYNTAX
Cross( ARRAY1, ARRAY2 )
RETURNS
ARRAY
FUNCTION
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)
EXAMPLE
cross( close, ema(close,9) )
SEE ALSO
References:
The Cross function is used in the following formulas in AFL on-line library:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Adaptive Centre of Gravity
Adaptive Cyber Cycle
Adaptive Relative Vigour Index
AFL Example
AFL Example - Enhanced
AFL-Excel
Against all odds
ALJEHANI
Aroon The Advisor
AR_Prediction.afl
ATR Study
Auto-Optimization Framework
automatic trendlines using fractal patterns
AutoTrader Basic Flow - updated Nov 18, 2008
Awsome Oscilator
Basket Trading System T101
Bow tie
Brian Wild
Bull Fear / Bear Fear
CandleStick Comentary--Help needed
CCI(20) Divergence Indicator
Centre of Gravity
Chandelier Exit
Chandelier Exit
Chandelier Exit or Advanced Trailing Stop
Channel/SRand trendlines
com-out
Commodity Channel Index
Connors TPS
correlerror
Customised Avg. Profit %, Avg. Loss % etc
Cyber Cycle
DateNum_DateStr
Cross - crossover check
658
AmiBroker 5.80 User’s Guide
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
AmiBroker Formula Language (AFL)
Demand Index
Dinapoli Guru Commentary
DMI Spread Index
Dynamic Momentum Index
Dynamic Momentum Index
Dynamtic Momentum Index
Ed Seykota’s TSP: EMA Crossover System
Effective Swing Indicator
ekeko price chart
Ema bands
EMA Crossover
FastStochK FullStochK-D
Fisher Centre of Gravity
Fisher Cyber Cycle
Fisher Oscillator
Fisher Relative Vigour Index
Follow the Leader
Fund Screener
Gann HiLo Indicator and System
Gann Swing chart v41212
hassan
Heatmap V1
Heikin Ashi Delta
Hilbert Sine Wave Support &Resistance
ICHIMOKU SIGNAL TRADER
IchimokuBrianViorelRO
Index and ETF trading
Indicator Explorer (ZigZag)
Intraday Fibonacii Trend Break System
Intraday Trend Break System
Lagging MA-Xover
MACD commentary
MACD optimize
Meu Sistema de Trading - versªo 1.0
mitalpradip
Modified Head &Shoulder Pattern
Multiple Ribbon Demo
Performance Check
Plot the Equity Curve without Backtesting?
prakash
regavg
Relative Momentum Index (RMI)
Relative Strength Index
Relative Vigour Index
RI - Auto Trading System
RUTVOL timing signal with BB Scoring routine
Sainath Sidgiddi
Scale Out: Futures
Sine Wave Indicator
STO &MACD Buy Signals with Money-Management
Stochastic Centre of Gravity
Stochastic Cyber Cycle
Cross - crossover check
659
AmiBroker 5.80 User’s Guide
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
AmiBroker Formula Language (AFL)
Stochastic Fast%K and Full
Stochastic optimize
Stochastic Relative Vigour Index
Stochastic RSI
Stochastics Trendlines
Stock price AlertIf
Stops Implementation in AFS
Stops on percentages
Support and Resistance
swing chart
TD Moving Average 2
The D_oscillator
Trailing Stop Loss
Trend Analysis_Comentary
Trend exploration with multiple timeframes
Trend Exploration: Slope Moving Average
Trend Following System
Trend Trigger Factor
TrendingRibbonArrowsADX
Triangular Moving Average new
Trigonometric Fit - TrigFit with AR for cos / sin
Using From and To dates from Auto Analysis in Code
VAMA
Visualization of stoploses and profit in chart
Vivek Jain
Volatility
Volatility Breakout with Bollinger Bands
Volume Occilator
Volume Oscillator
Williams Alligator system
More information:
Updated on-line reference
Cross- crossover check
660
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
Moving averages, summation
Cum
- cumulative sum
SYNTAX
Cum( ARRAY )
Cum( Value )
RETURNS
ARRAY
FUNCTION
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.
To enable QuickAFL with such formulas now Cum() function does NOT
affect required bars count (previously it forced all bars).
This change may lead to different results when comparing with old
versions. If you are interested in getting old behaviour and use all
bars just add:
SetBarsRequired( sbrAll )
anywhere in your formula.
EXAMPLE
The formula cum( 1) calculates an indicator that rises one point for
each day since the beginning of the chart - this is an equivalent of
bar number - especially useful if you want to detect the last bar:
ThisIsLastBar = cum( 1 ) == lastvalue( cum( 1 ) );
SEE ALSO
SUM() function
Comments:
Graham Kavanagh
[email protected]
2004-08-09 07:49:35
Sum adds up the last "n" number of bars. It sums
whatever you put into the first part of the sum
formula.
Cum(1) adds 1 to the previous value of Cum, so the
first bar is 1 and it just keeps adding one to the last
bar value of cum(1).
You can use Cum to add anything, like how many times
you get rising days in the entire chart:
Rise = C>O; //this gives results of 0 or 1
TotalRise = Cum(Rise);
You could limit this as well to time periods, or any
other condition Example would be one for total rise
Cum - cumulative sum
661
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
days since 1995:
RecentRise = C>O and Year()>=1995; //this gives results
of 0 or 1
TotalRise = Cum(RecentRise);
If you wanted to know how many rising days in the last
12 bars you would use:
LastRises = Sum(Rise,12);
Hope this helps
References:
The Cum function is used in the following formulas in AFL on-line library:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
AR_Prediction.afl
Auto-Optimization Framework
Automatic Linear Trend Channel
Automatic Linear Trend Channel 2
Automatic Trend-line
automatic trendlines using fractal patterns
Baseline Relative Performance Watchlist charts V2
Buff Volume Weighted Moving Averages
Bullish Percent Index 2 files combined
Candle Stick Analysis
Color Display.afl
Cycle Highlighter
Cycle Highlighter (auto best-fit)
Dave Landry PullBack Scan
Demand Index
Double top detection
ekeko price chart
Fast Refreshed KAGI Swing Charts (Price Swing)
Fib Fan Based on ZZ
Fibonacci Internal and External Retracements
Fund Screener
Gann Swing Chart
Head &Shoulders Pattern
Hurst Constant
Intraday Fibonacii Trend Break System
Linear Regression Line &Bands
Linear Regression Line w/ Std Deviation Channels
McClellan Summation Index
Modified Head &Shoulder Pattern
Modified Momentum Finder DDT-NB
Modified-DVI
Monthly bar chart
Moving Average "Crash" Test
Multiple sinus noised
Cum- cumulative sum
662
AmiBroker 5.80 User’s Guide
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
AmiBroker Formula Language (AFL)
N-period candlesticks (time compression)
nth ( 1 - 8 ) Order Polynomial Fit
Pattern Recognition Exploration
Prashanth
Price Persistency
Projection Oscillator
QP2 Float Analysis
R-Squared
Random Walk
Regression Analysis Line
RSI Trendlines and Wedges
RSIS
Square of Nine Roadmap Charts
Steve Woods’ Cum. Vol. Float + Cum. Vol. Channels
Steve Woods’ Cumulative Vol. Percentage Indicator
Stochastics Trendlines
TD Sequential
Trend Exploration: Count Number of New Highs
Triangle exploration using PFChart
Triangular Moving Average
Triangular Moving Average new
Trigonometric Fit - TrigFit with AR for cos / sin
Volatility Quality Index
Weekly chart
Williams Alligator system
More information:
Updated on-line reference
Cum- cumulative sum
663
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
Date/Time
(AFL 1.1)
Date
- date
SYNTAX
date()
RETURNS
STRING
FUNCTION
It is used to display the selected date in commentary /
interpretation window
EXAMPLE
date()
SEE ALSO
References:
The Date function is used in the following formulas in AFL on-line library:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
AccuTrack
ADX Indicator - Colored
AFL Example
AFL Example - Enhanced
AFL_Glossary_1
Against all odds
Another FIb Level
Bullish Percent Index 2004
Candle Stick Demo
candlestick chart for Volume/RSI/OBV
CCI 14 DrBobStyle
CCI 50 DrBob Style
CCI Woodies Style
Chart Zoom
Color Coded Short Term Reversal Signals
Commodity Channel Index
Congestions detection
Continuous Contract Rollover
DateNum_DateStr
Dinapoli Guru Commentary
Double Smoothed Stochastic from W.Bressert
Elder safe Zone Long + short
Elder Triple Screen Trading System
Elder’s SafeZone Stop
ElderSafeZoneStopLong
ElderSafeZoneStopShort
EMA Crossover Price
Fibonacci Calculations &Speed Resistance
Fibonacci Internal and External Retracements
Future Plotting of Time and Price
Future Plotting of Time and Price
Futures - Dollar Move Indicator
Futures - Dollar Move Today Indicator
hassan
Heikin Ashi Candles
Date - date
664
AmiBroker 5.80 User’s Guide
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
AmiBroker Formula Language (AFL)
Heinkin-Ashi
Intraday Fibonacii Trend Break System
Intraday Trend Break System
JEEVAN’S SRI CHAKRA
lastNDaysBeforeDate
MA Difference 20 Period
MACD commentary
MACD Histogram - Change in Direction
Main price chart with Rainbow &SAR
Market Facilitation Index VS Volume
MFE and MAE and plot trades as indicator
Nick
PF Chart - Close - April 2004
Pivot Point and Support and Resistance Points
Pivots for Intraday Forex Charts
Plot the Equity Curve without Backtesting?
Position Sizing and Risk Price Graph
Position Sizing and Risk Price Graph - 2
Price with Woodies Pivots
Probability Calculator
Relative Strength Index
Relative Strength Multichart of up to 10 tickers
Shares To Buy Price Graph
Super Trend Indicator
Support Resistance levels
Trading ATR 10-1
Triangular Moving Average new
Woodie’s CCI Panel Basic
Woodie’s CCI Panel Full Stats
Woodie’s Price Panel With Woodie’s Pivots
Woodies CCI
Zig Zag Indicator with Valid Entry and Exit Points
ZigZag Retracements
More information:
Updated on-line reference
Date- date
665
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
DateNum
- date number
SYNTAX
datenum()
RETURNS
ARRAY
FUNCTION
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
EXAMPLE
datenum();
Date/Time
(AFL 1.4)
SEE ALSO
References:
The DateNum function is used in the following formulas in AFL on-line library:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
BEANS-Summary of Holdings
Bullish Percent Index 2004
Continuous Contract Rollover
DateNum_DateStr
Date_To_Num(), Time_To_Num()
Fund Screener
Gordon Rose
IBD relative strength database ranker
IBD relative strength database Viewer
Intraday Range and Periods Framer
lastNDaysBeforeDate
MDYtoXLSerialDays and XLSerialDaysToDateNum
MFE and MAE and plot trades as indicator
PF Chart - Close - April 2004
Rea Time Daily Price Levels
Steve Woods’ Cum. Vol. Float + Cum. Vol. Channels
Steve Woods’ Cumulative Vol. Percentage Indicator
suresh
TWS auto-export Executions-file parser
Weekly chart
Zig Zag Indicator with Valid Entry and Exit Points
More information:
Updated on-line reference
DateNum - date number
666
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
DateTime
- retrieves encoded date time
SYNTAX
DateTime()
RETURNS
ARRAY
FUNCTION
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.
Date/Time
(AFL 2.3)
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. Any other comparisions (less than/greater then) using
normal operators > < can lead to wrong results, therefore to compare
two datetime numbers you should use DateTimeDiff( arg1, arg2 ) which
will return positive values if arg1 > arg2 and negative values if
arg1 < arg2.
EXAMPLE
1. Simple date/time column
AddColumn( DateTime(), "Date / Time", formatDateTime );
2. Example (produces signal file accepted by various other
programs):
Buy=Cross(MACD(),Signal());
Sell=Cross(Signal(), MACD());
Filter=Buy OR Sell;
SetOption("NoDefaultColumns", True );
AddColumn( DateTime(), "Date", formatDateTime );
AddColumn( IIf( Buy, 66, 83 ), "Signal", formatChar );
SEE ALSO
References:
The DateTime function is used in the following formulas in AFL on-line library:
•
•
•
•
•
•
•
•
•
•
•
•
•
AFL_Glossary_1
AutoTrade using an Exploration
babaloo chapora
BEANS-Summary of Holdings
Chart Zoom
Congestions detection
Ed Seykota’s TSP: EMA Crossover System
Ed Seykota’s TSP: Support and Resistance
Fast Refreshed KAGI Swing Charts (Price Swing)
Futures - Dollar Move Indicator
Gann Swing Charts in 3 modes with text
Gordon Rose
IBD relative strength database ranker
DateTime - retrieves encoded date time
667
AmiBroker 5.80 User’s Guide
•
•
•
•
•
•
•
•
•
•
•
AmiBroker Formula Language (AFL)
Improved NH-NH scan / indicator
Intraday Range and Periods Framer
PF Chart - Close - April 2004
Pivot Finder
Relative Strength Multichart of up to 10 tickers
Scale Out: Futures
shailu lunia
Trend Exploration: Count Number of New Highs
Trend Exploration: Slope Moving Average
TWS trade plotter
ValueChart
More information:
Updated on-line reference
DateTime- retrieves encoded date time
668
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
DateTimeAdd
- adds specified number of seconds/minutes/hours/days to
datetime
SYNTAX
DateTimeAdd( datetime, amount, interval = inDaily )
RETURNS
NUMBER or ARRAY
FUNCTION
The function adds specified amount of ’intervals’ to input datetime
array. Allows for example to calculate datetime 5 days back or 13
months into the future.
Date/Time
(AFL 3.40)
INPUT:
• datetime - scalar or array - the datetime value to add to (for
example returned by Now(), DateTime() or StrToDateTime/_DT or
ConvertDateTime functions)
• amount - number of ’intervals’ to add
(seconds/minutes/hours/days/etc - depending on interval
parameter)
• interval - specifies unit you want to add, supported units are
in1Second, in1Minute, inHourly, inDaily, inWeekly, inMonthly,
inQuarterly, inYearly
RETURNS:
datetime (scalar or array) - returned type depends on input
EXAMPLE
// Example 1:
x = Now( 5 ) ;
printf("11 days from now " + DateTimeToStr( DateTimeAdd( x, 11,
inDaily ) ) ) ;
// Example 2 (commentary):
x = Now(5);
printf( " now is " + DateTimeToStr( x ) );
for( shift = -12; shift <= 12; shift++ )
{
printf("%g seconds from now is " + DateTimeToStr( DateTimeAdd( x,
shift, 1 ) ) + "n", shift );
printf("%g minutes from now is " + DateTimeToStr( DateTimeAdd( x,
shift, in1Minute ) ) + "n", shift );
printf("%g hours from now is " + DateTimeToStr( DateTimeAdd( x,
shift, inHourly ) ) + "n", shift );
printf("%g days from now is " + DateTimeToStr( DateTimeAdd( x,
shift, inDaily ) ) + "n", shift );
printf("%g weeks from now is " + DateTimeToStr( DateTimeAdd( x,
shift, inWeekly ) ) + "n", shift );
printf("%g months from now is " + DateTimeToStr( DateTimeAdd( x,
DateTimeAdd - adds specified number of seconds/minutes/hours/days to datetime
669
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
shift, inMonthly ) ) + "n", shift );
printf("%g quarters from now is " + DateTimeToStr( DateTimeAdd( x,
shift, inQuarterly ) ) + "n", shift );
printf("%g years from now is " + DateTimeToStr( DateTimeAdd( x,
shift, inYearly ) ) + "nn", shift );
}
SEE ALSO
DateTimeDiff() function , DateTimeToStr() function ,
DateTimeConvert() function , DateTime() function
References:
The DateTimeAdd function is used in the following formulas in AFL on-line
library:
More information:
Updated on-line reference
DateTimeAdd- adds specified number of seconds/minutes/hours/days todatetime
670
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
DateTimeConvert
- date/time format conversion
SYNTAX
DateTimeConvert( format, date, time = Null )
RETURNS
NUMBER or ARRAY
FUNCTION
The function allows to convert from DateTime format to DateNum and
TimeNum and vice versa.
Date/Time
(AFL 2.90)
format parameter controls the direction of conversion:
• format = 0 - converts DateTime format to DateNum format,
example
mydatenum = DateTimeConvert( 0, DateTime() );// - this returns
DateNum
date argument should be in datetime formattime argument in
this case should not be used
• format = 1 - converts DateTime format to TimeNum format,
example:
mytimenum = DateTimeConvert( 1, DateTime() ); // - returns
timenum
date argument should be in datetime formattime argument in
this case should not be used
• format = 2 - converts from DateNum and optionally TimeNum to
DateTime format, example:
mydatetime = DateTimeConvert( 2, DateNum(), TimeNum() );
date argument should be in datenum formattime argument
(optional) should be in timenum format. In case of EOD data
you can skip time argument:
mydatetime = DateTimeConvert( 2, DateNum() );
• format = 3 - (AB5.0 or higher) converts DateTime format to
Seconds (00..59) example:
myseconds = DateTimeConvert( 3, DateTime() );
date argument should be in datetime, formattime argument in
this case should not be used
• format = 4 - (AB5.0 or higher) converts DateTime format to
Minutes(00..59) example:
myminute = DateTimeConvert( 4, DateTime() );
date argument should be in datetime, formattime argument in
this case should not be used
• format = 5 - (AB5.0 or higher) converts DateTime format to
Hours (00..23) example:
DateTimeConvert - date/time format conversion
671
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
myhour = DateTimeConvert( 5, DateTime() );
date argument should be in datetime, formattime argument in
this case should not be used
EXAMPLE
mydatenum = DateTimeConvert( 0, DateTime() );// - this returns
DateNum
mytimenum = DateTimeConvert( 1, DateTime() ); // - returns timenum
mydatetime = DateTimeConvert( 2, DateNum(), TimeNum() );
mydatetime = DateTimeConvert( 2, DateNum() );
SEE ALSO
DateNum() function , DateTime() function , DateTimeToStr() function
, Day() function , DayOfWeek() function , DayOfYear() function ,
TIMENUM() function , MONTH() function , YEAR() function , HOUR()
function , MINUTE() function , SECOND() function
References:
The DateTimeConvert function is used in the following formulas in AFL on-line
library:
More information:
Updated on-line reference
DateTimeConvert- date/time format conversion
672
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
DateTimeDiff
- get difference in seconds between two datetime values
SYNTAX
DateTimeDiff( arg1, arg2 )
RETURNS
NUMBER or ARRAY
FUNCTION
DateTimeDiff( arg1, arg2 ) which will return positive values if arg1
> arg2 and negative values if arg1 < arg2.
Date/Time
(AFL 3.30)
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.
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. Any
other comparisions (less than/greater then), using normal operators
> < may sometimes lead to wrong results (if one of dates compared is
pre-1964), therefore to compare two datetime numbers reliably you
should use DateTimeDiff.
EXAMPLE
SEE ALSO
DateTime() function
References:
The DateTimeDiff function is used in the following formulas in AFL on-line
library:
• Improved NH-NH scan / indicator
More information:
Updated on-line reference
DateTimeDiff - get difference in seconds between two datetime values
673
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
DateTimeToStr
- convert datetime to string
String manipulation
(AFL 2.8)
SYNTAX
DateTimeToStr( NUMBER )
RETURNS
STRING
FUNCTION
Converts number representing date/time value (for example obtained
using GetCursorXPosition(), Now(), DateTime() functions) to the
corresponding STRING (text).
EXAMPLE
ToolTip="X="+DateTimeToStr(GetCursorXPosition())
+"nY="+GetCursorYPosition();
SEE ALSO
DATETIME() function , NOW() function , StrToDateTime() function
References:
The DateTimeToStr function is used in the following formulas in AFL on-line
library:
•
•
•
•
•
•
•
•
AFL_Glossary_1
AutoTrade using an Exploration
Chart Zoom
Congestions detection
Fast Refreshed KAGI Swing Charts (Price Swing)
Gann Swing Charts in 3 modes with text
GFX ToolTip
Scale Out: Futures
More information:
Updated on-line reference
DateTimeToStr - convert datetime to string
674
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
Day
- day of month
SYNTAX
day()
RETURNS
ARRAY
FUNCTION
Returns the array with days (1-31)
EXAMPLE
writeif( day() < 3, "Beginning of the month", "The rest of the
month" );
Date/Time
(AFL 1.4)
SEE ALSO
References:
The Day function is used in the following formulas in AFL on-line library:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Pivots And Prices And Swing Volume
Auto Trade Step by Step
CoinToss ver 1
Daily High Low in Advance
Days to Third Friday
Expiry day/days - Last thursday of month
Expiry Thursday for Indian markets
Export All Daily Data to TXT with MS import format
Export EOD or Intraday to .csv file
Export Intraday Data
Heatmap V1
Intraday Average Volume
IntraDay Open Marker
Intraday Strength
Intraday Volume EMA
Luna Phase
Lunar Phases - original
LunarPhase
Market Profile
N-period candlesticks (time compression)
Next Date Format
Option Calls, Puts and days till third friday.
Positive Bars Percentage
Relative Strength Multichart of up to 10 tickers
Trade day of month
VWAP - Volume Weighted Average Price
VWAP with standard deviation bands
Wolfe Wave Patterns
More information:
Updated on-line reference
Day - day of month
675
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
DayOfWeek
- day of week
SYNTAX
dayofweek()
RETURNS
ARRAY
FUNCTION
Returns the array with day of week (0-6):
0 - Sunday
1 - Monday
...
5 - Friday
6- Saturday
EXAMPLE
buy = dayofweek() == 1; // buy on Monday
sell = dayofweek() == 5; // sell on Friday
Date/Time
(AFL 1.4)
SEE ALSO
References:
The DayOfWeek function is used in the following formulas in AFL on-line library:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Basket Trading System T101
Days to Third Friday
Ed Seykota’s TSP: EMA Crossover System
Expiry day/days - Last thursday of month
Expiry Thursday for Indian markets
Fast Refreshed KAGI Swing Charts (Price Swing)
MO_CrashZone
Option Calls, Puts and days till third friday.
RSI of Weekly Price Array
Sainath Sidgiddi
Stochastic of Weekly Price Array
Time Frame Weekly Bars
Weekly chart
Weekly Trend in Daily Graph
More information:
Updated on-line reference
DayOfWeek - day of week
676
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
DayOfYear
- get ordinal number of day in a year
SYNTAX
DayOfYear()
RETURNS
ARRAY
FUNCTION
Returns the calendar day number counting from beginning of the year
January 1st is 1. Maximum number returned is 366
EXAMPLE
Filter=1;
AddColumn(DayOfYear(),"Day of Year");
SEE ALSO
DAYOFWEEK() function
Date/Time
(AFL 2.4)
References:
The DayOfYear function is used in the following formulas in AFL on-line library:
• End Of Year Trading
More information:
Updated on-line reference
DayOfYear - get ordinal number of day in a year
677
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
DaysSince1900
- get number of days since January 1st, 1900
SYNTAX
DaysSince1900()
RETURNS
ARRAY
FUNCTION
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.
Date/Time
(AFL 3.20)
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. Excel’s DATEVALUE function starts
counting from one but it includes Feb 29, 1900 which did not exist
and this adds extra one day for all dates starting from Mar 1st,
1900.
The function can be used for calculations that involve calendar days
as opposed to trading days and replaces previously proposed AFL
solution http://www.amibroker.com/kb/2007/03/15/calendar-day-index/
Now RefDays can be implemeted as follows (see example)
EXAMPLE
SetBarsRequired( 365, 0 );
function RefDays( Array, Days )
{
td = DaysSince1900();
result = Null;
if( Days < 0 )
{
for( i = BarCount -1; i >= -Days; i = i - 1 )
{
backday = td[ i ] + Days; // Days is negative
for( j = -Days/2; j < i; j++ )
{
if( td[ i - j ] <= backday )
{
result[ i ] = Array[ i - j ];
break;
}
}
}
}
return result;
}
Plot( C, "C", colorRed );
Plot( Ref( C, -252 ), "Close 252 bars back", colorBlue );
DaysSince1900 - get number of days since January 1st, 1900
678
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
Plot( RefDays( C, -365 ), "Close 365 days back", colorGreen );
SEE ALSO
Date() function , DateNum() function , DateTime() function ,
DateTimeConvert() function
References:
The DaysSince1900 function is used in the following formulas in AFL on-line
library:
More information:
Updated on-line reference
DaysSince1900- get number of days since January 1st, 1900
679
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
DecIssues
- declining issues
SYNTAX
DecIssues()
RETURNS
ARRAY
FUNCTION
Returns the number of declining issues for a given market (the one
that currently analysed stock belongs to)
EXAMPLE
DecIssues()
Composites
(AFL 1.2)
SEE ALSO
References:
The DecIssues function is used in the following formulas in AFL on-line library:
•
•
•
•
Absolute Breadth Index
Breadth Thrust
McClellan Oscillator
McClellan Summation Index
More information:
Updated on-line reference
DecIssues - declining issues
680
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
DecVolume
- declining issues volume
SYNTAX
DecVolume()
RETURNS
ARRAY
FUNCTION
Returns the volume of declining issues for a given market (the one
that currently analysed stock belongs to)
EXAMPLE
DecVolume()
Composites
(AFL 1.2)
SEE ALSO
References:
The DecVolume function is used in the following formulas in AFL on-line library:
More information:
Updated on-line reference
DecVolume - declining issues volume
681
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
DEMA
- double exponential moving average
Moving averages, summation
(AFL 2.0)
SYNTAX
dema( ARRAY, periods )
RETURNS
ARRAY
FUNCTION
Calculates double exponentially smoothed average - DEMA. The
function accepts time-variable periods.
EXAMPLE
DEMA( Close, 5 )
SEE ALSO
MA(), EMA(), WMA(), TEMA()
Comments:
Tomasz Janeczko
tj --at-amibroker.com
2003-02-06
13:51:31
DEMA can be implemented via EMA:
Len=10;
Graph0= 2 * EMA( C, len ) - EMA( EMA( C, len ), Len );
// for comparison only
Graph1=DEMA(C,Len);
Tomasz Janeczko
tj --at-amibroker.com
2003-04-27
15:43:17
Note to the comment above:
EMA and DEMA use different initialization method. DEMA[ 0 ] is
initialized with first value of input array, while EMA[ len ]
is initialized with simple moving average to match output with
Metastock.
Therefore they will converge at 2 * Len bars from Graph0 start
( 6 * Len bars since beginning of the data).
Tomasz Janeczko
tj --at-amibroker.com
2003-04-27
15:48:11
DEMA can also be implemented using new for looping:
Len = 20;
Plot( DEMA( Close, Len ), "Built-in DEMA", colorRed );
factor = 2 / (Len + 1 );
e1 = e2 = Close[ 0 ]; // initialize
for( i = 0; i < BarCount; i++ )
{
e1 = factor * Close[ i ] + ( 1 - factor ) * e1;
e2 = factor * e1 + ( 1 - factor ) * e2;
myDema[ i ] = 2 * e1 - e2;
}
Plot( myDema, "Dema in loop", colorBlue );
Tomasz Janeczko
tj --at--
... and can be implemented using AMA:
DEMA - double exponential moving average
682
AmiBroker 5.80 User’s Guide
amibroker.com
2003-04-27
15:51:03
AmiBroker Formula Language (AFL)
Len = 20;
Factor = 2/(Len+1);
e1 = AMA( Close, Factor );
e2 = AMA( e1, Factor );
Plot( DEMA( Close, Len ), "Built-in DEMA", colorRed );
Plot( 2*e1 - e2, "AMA-implemened DEMA", colorBlue );
Tomasz Janeczko
tj --at-amibroker.com
2003-04-27
16:26:06
For more information on DEMA see:
Stocks & Commodities V. 12:1 (11-19): Smoothing Data With
Faster Moving Averages by Patrick G. Mulloy.
References:
The DEMA function is used in the following formulas in AFL on-line library:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
AFL to Python COM Link
Auto-Optimization Framework
Average Price Crossover
babaloo chapora
DEBAJ
Dynamic Momentum Index
Dynamic Momentum Index
Hull with DEMA
JEEVAN’S SRI CHAKRA
Lagging MA-Xover
Moving Averages NoX
Support Resistance levels
The D_oscillator
The Saturation Indicator D_sat
Trend Detection
More information:
Updated on-line reference
DEMA- double exponential moving average
683
AmiBroker 5.80 User’s Guide
AmiBroker Formula Language (AFL)
EMA
- exponential moving average
Moving averages, summation
SYNTAX
ema( ARRAY, periods )
RETURNS
ARRAY
FUNCTION
Calculates a periods exponential moving average of ARRAY
EXAMPLE
ema( close, 5 )
SEE ALSO
MA() function , TEMA() function , AMA() function , AMA2() function ,
DEMA() function , WMA() function , WILDERS() function
Comments:
Nigel Rowe
[email protected]
2003-04-27
18:05:14
See the comments attached to DEMA for a discussion on the
differences in the way EMA and others are initialised.
EMA is initialised from a simple MA of equivalent length. (For
compatability with some other strange TA software.) The others
are initialised from the first value.
References:
The EMA function is used in the following formulas in AFL on-line library:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
accum/dist mov avg crossover SAR
AccuTrack
Advanced MA system
ADXbuy
AFL Example
AFL Example - Enhanced
AFL to Python COM Link
Against all odds
Andrews PitchforkV3.3
AR_Prediction.afl
ATR Study
Auto-Optimization Framework
Average Price Crossover
babaloo chapora
Bad Tick Trim on 5 sec database
Balance of Power
balance of power
BB squeeze
BMTRIX Intermediate Term Market Trend Indicator
Bollinger - Keltner Bands
Bollinger band normalization
Breadth Thrust
Bull/Bear Volume
candlestick chart for Volume/RSI/OBV
CCI 14 DrBobStyle
CCI 50 DrBob Style
EMA - exponential moving average
684
AmiBroker 5.80 User’s Guide
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•