AmiBroker is the ideal program for you to use to chart and develop trading systems for your favorite markets — stocks, mutual funds, exchange traded funds, commodities, or Forex. It is powerful, flexible, inexpensive, and easy to use. This book is for: • • •
Someone new to AmiBroker looking for detailed instructions and examples to get set up and started. An experienced AmiBroker user who wants a printed reference to commonly used tools. Someone looking for an introduction to the AFL language, and using AmiBroker to write trading systems.
Topics covered include: ״ ״ ״ • ״
Writing trading systems Testing trading systems Optimizing trading systems Validating trading systems
Installing AmiBroker Setting up free databases Setting up subscription databases Setting up real-time databases Charting stocks, funds, futures Applying chart tools
Chapter 3 - 3 0 Minutes to Useful Results ־has 10 example projects t h a t parallel the tutorials, each of which can be done in just a f e w minutes. 1. 2. 3. 4. 5.
Chart a Stock Apply a Trendline Plot a Moving Average Make a Watchlist Run an Exploration
6. 7. 8. 9. 10.
Run a Single Stock Backtest Run a Portfolio Backtest Optimize a Trading System Perform Walk Forward Validation Scan for Buy and Sell Signals
Dr. Howard Bandy has both the formal education a n d practical experience required to write this book. He has degrees in mathematics, physics, engineering, and computer science. He was a university professor of computer science and mathematics, vicepresident and designer of the major product for a company that produced p r o g r a m s for stock selection and timing, and senior research analyst for a commodity trading advisor where he held a Series 3 license. He is the author of the very well received Quantitative Trading Systems - a book that uses AmiBroker to illustrate more advanced trading system topics. He is a regular and popular speaker and author on topics of trading system design and testing. $US 39.95 ISBN
This is the book you need if you are looking for a step-by-step introduction to AmiBroker. 9
978-097918381-2
1 o u r 1y 1odo i c
Introduction to
AmiBroker
Introduction to
AmiBroker Advanced Technical Analysis Software for Charting and Trading System Development Howard B. Bandy Blue Owl Press
Copyright © 2008 by Howard B. Bandy All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise without the prior written permission of the copyright holder, except brief quotations used in a review. AmiBroker is a trademark of AmiBroker and Tomasz Janeczko. Windows, Excel, and Notepad are trademarks of Microsoft. Premium Data is a trademark of Norgate Investor Services. QP3 and QP Feed are trademarks of Quotes Plus. DTN IQ Feed is a trademark of DTN.
ISBN-10: 0979183812 ISBN-13: 9780979183812 LCCN: 2008905105 Published by Blue Owl Press 3700 S. Westport Avenue, #1876 Sioux Falls, SD 57106 Published 2008 Printed in the United States 12 11 10 09 08 10 9 8 7 6 5 4 3 2 1
DISCLAIMER
This book is an educational document. Nothing in this book is intended as, nor should it be construed to be, investment advice. The views expressed herein are the personal views of Dr. Howard B. Bandy. Neither the author nor the publisher, Blue Owl Press, have any commercial interest in any of the products mentioned. All of the products described were purchased by the author at regular retail prices. Investing and trading is risky and can result in loss of principal. Neither this book in its entirety, nor any portion thereof, nor any follow-on discussion or correspondence related to this book, is intended to be a recommendation to invest or trade mutual funds, stocks, commodities, options, or any other financial instrument. Neither the author nor the publisher will accept any responsibility for losses which might result from applications of the ideas expressed in the book or from techniques or trading systems described in the book. The programs used as examples have been tested and are believed to be correct. Even so, this book may contain typographical errors and other inaccuracies. Past performance, whether hypothetical, simulated, backtested, or actual, is no guarantee of future results. Results will depend on the specific data series used. Please verify the accuracy and correctness of all programs before using them to trade.
ACKNOWLEDGEMENTS
Tomasz Janeczko, author of AmiBroker. Thank you for creating an outstanding program, and for graciously allowing use of materials published in the AmiBroker user documentation. Bruce Robinson and William Barack. Thank you for the many stimulating discussions, encouraging comments, and conference presentations, all of which helped motivate and shape this book. Robert Grigg. Thank you for the many stimulating discussions and exchange of ideas, and for raising awareness of AmiBroker in Australia. Particular thanks for permission to use the schematic of AmiBroker that you developed.
Contents
Preface and Introduction
xiii
Section I — Getting Started
1
Chapter 1 — Overview of AmiBroker
3
Chapter 2 — Installation
11
AmiBroker in Trial Mode
13
Default Database
13
Block Diagram of Database
14
Database Setup - End-of-Day Free Database Using AmiQuote
14 15
Subscription Data Providers Database Setup - Intra-Day and Real-Time Data
31 41
Free Intra-Day Historical Data
41
Delayed Real-Time Data
43
Real-Time Data
44
Tick Data
53
Chapter 3 — 30 Minutes to Useful Results
55
Example 1 - Chart a Stock
57
Example 2 - Apply a Trendline
61
Example 3 - Plot a Moving Average
65
Example 4 - Make a Watchlist
69
Example 5 - Run an Exploration
72
Example 6 - Run a Single Stock Backtest
78
Example 7 - Run a Portfolio Backtest
87
Example 8 - Optimize a Trading System
91
Example 9 - Perform Walk Forward Validation
98
Example 10 - Scan for Buy and Sell Signals
103
Section II — Charting
105
Chapter 4 — AmiBroker Chart Structure
107
Windows Layouts
108
Block Diagram
Ill
Chapter 5 - The GUI - Graphical User Interface Charts
113 116
Display a New Price Series
116
Default Chart
117
Active Pane
117
Price and Value Axis
117
Date and Time Axis
118
Scroll Through Dates
118
Pane Size
118
Zoom
119
Bar Interval (Periodicity)
119
Select a Quote
120
Mark a Range
120
Remove the Range Markers
120
Add a New Pane
121
Close Any Pane
121
Reorder the Panes
121
Chart Pane Context Menu
122
Parameters
122
Edit Formula
127
Properties
129
Pull-down Menus
130
File Menu
131
Edit Menu
134
View Menu
135
Insert Menu
139
Format Menu
141
Symbol Menu
142
Analysis Menu
146
Tools Menu
147
Window Menu
149
Help Menu
150
Toolbars
151
Tools for General Use
151
Tools for Drawing
154
Study Tools
157
Add Icons to Toolbar
159
Tabbed Menus
160
Re-dockable Menus
160
Auto-hiding Sliding Menus
160
Layouts, Layouts Tabbed Menu, Layouts Context Menu
162
Layers, Layers Tabbed Menu, Layers Context Menu
163
Symbols, Symbols Tabbed Menu, Symbols Context Menu ...165 Charts (Formulas) Tabbed Menu, Charts Context Menu
168
Notepad, Notepad Tabbed Menu, Notepad Context Menu ..170 Interpretation, Interpretation Tabbed Menu
171
Alert Output, Alert Output Context Menu
172
Real-Time Quote Window, Context Menu
173
Time and Sales Window
175
Categories
177
Group - Market - Sector - Industry
177
Category Membership
177
Category Assignment
178
Watchlists
179
Adding Watchlists
180
Removing Watchlists
180
Adding Symbols to Watchlists
181
Sorting Symbols in a Watchlist
182
Removing Symbols from Watchlists
183
Erasing Watchlists
183
Hiding and Unhiding Empty Watchlists
184
Using Watchlists in Automatic Analysis Window
184
Importing a Watchlist from a File
186
Exporting a Watchlist to a File
187
Renaming Watchlists
187
Charts (Formulas)
190
Basic Operations
190
Averages
195
Bands
198
Basic Charts
200
Custom
203
Equity
203
Include
204
Indicators
205
Systems
224
Section III — Analysis
227
Chapter 6 - Technical Analysis
229
Chapter 7 - Trading System Development
233
Define the Objective Function
234
Decide What to Trade and How to Trade It
235
Design the Trading System
235
Determine the Length of the In-Sample Period
236
Determine the Length of the Out-Of-Sample Period
236
Decide What to Optimize
237
Perform Walk Forward Runs
237
Evaluate the Out-Of-Sample Results
238
Trade the System
239
Monitor the Results
239
In Summary
239
Chapter 8 - AFL - AmiBroker Formula Language AFL Editor
242 243
Pull-Down Menus
243
AFL Editor Toolbar
246
AFL Editor Context Menu
248
AFL Language
249
Arrays
249
BarCount
250
Array Operations
250
Language Basics
252
Operators
253
Operator Precedence
254
Array Subscript Operator
256
Compound Statements (Blocks)
256
Conditional If IIF)
256
Variables
257
Reserved Variables
257
User Defined Functions, Procedures, Scope
258
Local, Global
259
Flow Control
261
Flags
269
AFL Function Reference
271
Lowest / Highest
271
Math Functions
275
Moving Averages, Summation
285
Statistical Functions
289
Basic Price Pattern Detection
294
Composites
300
Indicators
304
Exploration / Indicators
319
Date / Time
342
Time Frame Functions
352
Information / Categories
361
Referencing Other Symbol Data
372
File Input / Output Functions
378
String Manipulation
386
Trading System Toolbox
394
Low-level Graphics
421
Miscellaneous Functions
443
Chapter 9 - Analysis
477
Quick Review
478
Automatic Analysis
481
Main Window
481
Settings Button
484
Explore Button
493
Backtest Button
496
Context Menu
502
File Button
508
Equity Button
508
Report Button
509
Optimize Button
511
Walk Forward
518
Commentary
524
Chapter 10 - Write It Yourself
529
Appendix A — Glossary
545
Appendix B — Industries and Sectors
557
Appendix C — Resources
561
Appendix D — Block Diagram
567
Index
569
Order Information
591
Preface and Introduction
This book is intended to be a tutorial. Topics included and detail covered involved compromises b e t w e e n elementary and advanced, narrow and broad, superficial and in-depth. Those chosen are practical examples of tasks that you will be p e r f o r m i n g regularly. For additional tutorials, watch the on-line tutorial videos, available at http://www.amibroker.com/tutorials. For a more complete reference, see the AmiBroker User's Guide and the AmiBroker Reference, both available at http://www. amibroker.com. This book is task oriented, rather t h a n software oriented. M a n y operations can be performed in more than one way. W h e n m a k i n g a choice, clarity was chosen over efficiency. This book is not intended to be read cover-to-cover, as a novel would be read. It is intended to be a series of tutorials and reminders covering operation of AmiBroker. The examples use a lot of screen capture images, annotated w i t h n u m bered steps, highlights, and arrows. The book includes reference to all the functions, indicators, and tools d o c u m e n t e d in the User's Guide and in the Help system. INTENDED AUDIENCE
People wanting: •
Description of AmiBroker.
•
Description of the capabilities of AmiBroker.
•
Tutorial on installing and setting up AmiBroker.
•
Tutorial on setting up databases w i t h free data. xiii
xiv
Introduction to AmiBroker •
Tutorial on setting up subscription end-of-day databases.
•
Tutorial on setting up real-time data feeds.
•
Tutorial on the basic charting.
•
Tutorial and reference on the Graphical User Interface - GUI.
•
Tutorial on applying formulas and indicators to charts.
•
Tutorial on the AmiBroker Formula Language - AFL.
•
Introduction to technical analysis.
•
Introduction to design of trading systems.
•
Tutorial on backtesting trading systems.
•
Tutorial on optimizing trading systems.
•
Tutorial on validating trading systems.
•
Examples of trading systems.
•
Printed reference for AmiBroker structure, menus, tools.
ASSUMPTIONS
While this book is intended to be a tutorial on AmiBroker, the reader is expected to be reasonably familiar with: •
Computer operations.
•
Basic techniques used with the Windows operating system, such as the menu system, drag-and-drop, navigating through the file system.
•
A basic text editor, such as Windows Notepad.
•
A spreadsheet, such as Excel.
•
Basic trading methods and terminology.
W H A T YOU WILL FIND IN THIS BOOK
An overview of AmiBroker - its features and capabilities. Tutorials describing the installation of AmiBroker, setting up databases using free end-of-day and intraday data, setting up databases using subscription end-of-day data (for US and Australian markets), and setting up databases using subscription real-time data. SECTION I - GETTING STARTED.
There are ten examples of useful things you can do with AmiBroker in just a few minutes, even if you are using the trial version. These range from manipulating the charts to applying on-screen indicators to testing and optimizing trading systems. Everything is laid out, click-byclick, with screen captures to illustrate each step.
Preface and Introduction Each of the m e n u s and toolbars that work with charting is expanded and explained. SECTION II - CHARTING.
TOPICS INCLUDE:
•
Displaying charts.
•
Adding visual studies, such as trendlines, to a chart.
•
Adding formulas and technical indicators to a chart.
•
Using parameters with indicators.
S E C T I O N I I I — A N A L Y S I S . The Analysis section begins with a short introduction to technical analysis and trading system development.
That is followed by an introduction to AFL - AmiBroker Formula Language, including its structure and syntax. AFL is used to write code to create your own custom charts and trading systems. This section is part tutorial, part programming manual, part reference manual. The use of the Automatic Analysis tools, including backtest, optimization, and walk forward validation, are explained. Several ready-to-use programs you can use as starting points for your own system development are included. THE APPENDIXES. INDEX.
Provide reference material.
Menus, commands, tools, and techniques are extensively in-
dexed. W H A T Y O U WILL N O T FIND I N T H E T H I S BOOK
AmiBroker has so much to offer that this book could easily have been expanded by several hundred pages. Readers looking for coverage of topics such as the Custom Backtester, Dynamic Data Exchange, lowlevel graphics, scripting, and the Automated Trading Interface will have to wait for another book. Readers looking for coverage of topics such as different types of trading systems, trading system testing, trading system validation, and the creation of C++ routines and Dynamic Link Libraries are referred to the author's companion book, Quantitative Trading Systems (see Appendix C, Resources). SOME
CONVENTIONS
AmiBroker can be used with any tradable, including stocks, mutual funds, closed end funds, exchange traded funds, commodities, futures,
xvi
Introduction to AmiBroker
and Forex. For ease of writing and reading, the terms stock, symbol, issue, or ticker are often used to mean any tradable issue. When it is important to distinguish between different tradables, specific details are given. AmiBroker is distributed and used world-wide. With the exception of setting up the database to reflect the local tradables and exchanges, most of the operations of AmiBroker are independent of location. The author resides in the United States and most of his experience is with trading in the US, which may shape some of the perspective of this book. Apologies in advance for any inadvertent mistakes or misleading statements due to his limited background - no discrimination of any kind is intended. VERSIONS USED
AmiBroker 5.10.0 and later. AmiQuote 2.00. AmiBroker is regularly expanded and improved. During the life of this edition of this book, the features, capabilities, screens, and commands, will undoubtedly change somewhat. Every attempt was made to write in such a way that the book will be useful for a long time and will not soon become obsolete as new versions of the program are released. But there will be changes in the program that are not reflected in the book. For the latest and official documentation, please refer to the latest editions of the AmiBroker User's Guide, the on-line help files, and the tutorials, all of which can be found on the AmiBroker web site: http://www. nmibroker.com. THE AUTHOR
Dr. Howard Bandy: •
Has university degrees in mathematics, physics, engineering, and computer science.
•
Has specialized in artificial intelligence, applied mathematics, modeling and simulation.
•
Was professor of computer science and mathematics, and a university dean.
•
Designed and programmed a well-known program for stock selection and timing.
•
Was a senior research analyst for a CTA trading firm.
Section I
Getting Started
1 2 Introduction to AmiBroker
AmiBroker
You are visitor #
573881
e J a n u a r y 1st, 2002
for Windows 95/98/Me/NT/2k/XP mws
\ ttawrfed 1
i
««M18st
subpart
j finks
Technical analysis software you've been dreaming of... Search !keyword
Welcome Features Testimonials Download AmiBroker Ami Quote Purchase Benefits Standard vs. Professional Edition
New! AmiBroker 5.10 Featuring automatic Walk-Forward Testing, Multi-monitor floating charts, symbol and interval linking, drag-and-drop indicator creation, True Portfolio Backtesting and Optimization with scaling and multiple currency handling, free Fundamental data, Multiple Time-Frame support, 3D optimization charts, new Account manager, automated trading interface, volume profile, object-oriented ןcharting, drawing layers, multi-window layouts, f formula-based alerts, easy-to-use formula editor, equity function, unique composite indicators, built-in web research browser, direct link to : eSignal, Interactive Brokers, IQFeed, myTrack, FastTrack, QP2. TC2000, any DDE compliant feed, MS and more . > Download FREE TRIAL
Buy ori-lirie
First
Impression
Features Customer Testimonials ^ y Re^ster ל AmiBroker list i e n t e r y o u r email
AmiBroker works with
Signal (REAL TIME quotes)
!׳FEED (REAL TIME quotes)
Standard
AFKIUATES
Support User's Guide AFL Library AFL Reference Other materials Knowledge Base
Q u o t e s Plus (EOD quotes) RECOMMENDED
Professional
$279
l Custom'*^ *! one-time fit ן- ""iX.;׳ indicators ^1IWllffH; «• - •־'יי J
interactive Brokers Interactive Brokeis (REALTIME quotes)
DevLog (News blog) Users' KB
Reasons why we are better than competition • FEATURE RICH - the most complete set of features available plus we add new features every day on user request.
AmiBroker YahooGroup Wish list Current to-do list Suggest a feature
International Czech version Polish version
• SPEED - highest quality technical analysis software running 10 times faster than other competing products • RELIABILITY and ACCURACY - thoroughly tested and used every day by community of thousands of traders, fund managers, etc Our backtester can reproduce virtually any trading strategy with real-life accuracy • FLEXIBLE - you won't be limited by the software anymore With AmiBroker the limit is just your imagination. AmiBroker is Incredibly tweakable and can be adjusted to fit your personal trading needs • COST-EFFECTIVE ־not only license fee is iow but also you get four consecutive free upgrades, free support, free plug-ins and add-ons, and last but not least, you can also use FREE DATA from a number of sources AmiBroker is one of the best investments you can make to improve your trading
http://wwzv.amibroker.com
myTrack (REAL TIME quotes) TCEOOO.com (EOD quotes)
INVESTORS־ FastTrack (EOD quotes) Click h e r e f o r c o m p l e t e list of supported data soutces
Swdfaap f׳art*a» Methods
Check n e w book "Quantitive Trading Systems" by Howard B. B a n d y .
Chapter 1
Overview of AmiBroker
AmiBroker is a powerful, comprehensive trading system development platform. It has cutting edge charting and graphics, and fast, flexible and powerful portfolio-level backtesting, optimization, and automated walk forward validation. Its purpose is to help investors and traders identify profitable opportunities to buy and sell. It includes an extensive library of technical indicators that can be plotted along with the price chart as well as tested for profitability in a trading system. It has all the tools needed to chart, test, and trade stocks, mutual funds, commodifies, and Forex. AmiBroker has two primary modes of operation - charting and formula evaluation. The data it works with are the price and volume records of buy and sell transactions for stocks, mutual funds, and other tradable issues. In its charting mode, historical price and volume data are displayed on the computer monitor along with technical indicators. The analyst looks for promising patterns and conditions.
3
12
Introduction to AmiBroker
In its formula evaluation mode, patterns, conditions, and rules are described using a programming language and written into a computer program. The program analyzes the price and volume data and reports on the profitability of the rules. When profitable trading systems have been found, it scans the group of stocks that are of interest to the trader and lists the current buy and sell signals. If desired, AmiBroker can send orders based on these signals directly to a broker for execution. AmiBroker is unique among trading system development platforms in that the same code displays the indicators, tests the profitability, issues the buy and sell signals and sends the orders. It is an easy transition from chart to analysis to execution. AmiBroker r u n s under Windows, including versions 95, 98, Millennium, 2000, NT, XP, and Vista. Both 32 bit and 64 bit operating systems are supported. Any system that runs Windows efficiently will run AmiBroker efficiently. PROFESSIONAL A N D STANDARD EDITIONS
•
Both support intraday as well as end-of־day data
•
Standard meets most needs
•
Professional is required for Tick charts ־ MAE / MFE charts • 64 bit Unlimited real-time quotes
D A T A FEEDS
•
Accepts data from any exchange in the world
•
Close integration with major subscription data vendors Quotes Plus • TC 2000 FastTrack eSignal myTrack • IQFeed Interactive Brokers Any DDE-enabled data feed
Overview of AmiBroker •
AmiQuote downloader provides access to free end-of-day quotes from major world exchanges
•
Built-in importer for MetaStock format data
•
ASCII import wizard reads any data format
DATABASES
•
End-of-day data
•
Intraday data
•
Any number of databases
•
Any number of symbols
•
Add or remove issues
•
Split and distribution adjustment
•
Unlimited history of price quotes
•
Quotation editor
•
Company information
•
Fundamental information
PERFORMANCE
•
Fast execution of AFL code
•
Fast chart drawing
•
Robust and stable
CHARTING
•
Multiple chart panes
•
Multiple time frames
•
Live updating
•
Intraday, daily, weekly, monthly
•
Line, bar, candlestick
•
Fast zooming and scrolling
•
Custom or automatic scaling
•
Built-in indicators Simple moving average Exponential moving average Adaptive moving average • Rate of change (ROC) Wilder's Relative Strength Indicator (RSI)
5
12
Introduction to AmiBroker
•
Moving Average Convergence-Divergence Oscillator (MACD) On Balance Volume (OBV) Commodity Channel Index (CCI) Money Flow Index (MFI) Bollinger Bands Stochastics Parabolic Stop and Reverse (SAR) Relative strength
•
Overlay indicators over price charts
•
Overlay indicators over other indicators
•
Configurable indicators
•
Drag and drop tools
•
Chart study tools Trend lines Regression channels Text on chart Fibonacci retracements Gann squares
•
Chart studies are saved with the chart
•
Charts independently scalable
A F L ( A M I B R O K E R FORMULA LANGUAGE)
•
Designed for charting and trading
•
Over 200 built-in building-block functions Pattern-detection Averages Statistical Pre-defined indicators Data manipulation Trade management Extensive library of pre-written code
• •
Create your o w n indicators, trading systems, and commentaries
•
Single code base for indicators, systems, commentaries
•
User-defined functions
•
Unlimited variables
Overview of AmiBroker •
Unlimited nesting of function calls
•
Local and global variables
•
Multiple time frames
•
Indicator builder Create and plot indicators Control axes, scales, color, line style
•
Show Buy and Sell signals on charts
•
Code stored in clear-text
•
Built-in formula editor
•
Any editor can be used
•
Debugging, tracing, and profiling tools
•
Extendable through Dynamic Link Libraries (DLL)
ALERTS
•
Formula-based alerts
•
Display to screen
•
Play sound
•
Send e-mail
•
Send order to automated trade execution
SCANNING
•
Review your database for your buy and sell signals
•
Time window can be specified
EXPLORING
•
Search your database for conditions you specify
•
Report results
•
Multiple-key sorting
BACKTESTING
•
Test profitability of trading system
•
Single issue or group of issues you define
•
Long, short, or both
•
Buy and sell arrows on charts
•
Built-in trailing exits and stops
•
Realistic slippage and commission
7
12
Introduction to AmiBroker •
Portfolio level fully supported
•
Position sizing
•
Optimization Full search of parameter space Non-exhaustive search Particle Swarm Optimization (PSO) Covariance Matrix Adaptation Evolutionary Strategy (CMAE) Single issue or portfolio
•
3-D presentation of results
•
Multiple time frame
•
Equity curve creation
•
Equity curve input to trading system
•
Walk forward testing
•
Over 20 built-in metrics
•
User-definable metrics
•
Fast execution
•
Detailed reporting
•
Report explorer
•
Export results for further analysis
AUTOMATED TRADING
•
Interfaces to on-line brokers
SCRIPTING
•
Jscript (JavaScript)
•
VBScript (Visual Basic Scripting)
•
Scripts embeddable in AFL programs
•
OLE (Object Linking and Embedding) Automation
•
Call COM (Component Object Model) objects from AFL
•
Create and automate database management tools
CONFIGURABILITY
•
Almost everything is configurable and customizable
•
Charts can be arranged as you wish them to be
•
Not tied to a specific exchange or data provider
•
Indicators are parameter driven
Overview of AmiBroker ACCOUNT MANAGER •
Track your investments
•
Calculate commissions, dividends, deposits, withdrawals
INTERNET INTEGRATION •
Built-in web browser for company research
•
Configurable settings
PERFORMANCE •
Very fast redrawing of charts
•
Fast execution of AFL code
PRICING (AS OF AUGUST 2 0 0 8 ) •
Fully functional, no cost 30 day trial
•
New one-time license: • Standard Edition: $199 Professional Edition: $279
•
Free upgrades for one year from purchase
•
Renewal license (to continue upgrades): half price
ORDERING •
Visit http://wzvw.mnibroker.com/order.html. This secure site accepts your payment using any major credit card, check, or bank transfer.
DELIVERY •
After paying the registration fee, you will receive a personalized keyfile by e-mail. Installing the keyfile converts your trialware version to a registered version. No other downloads are required. No other delivery method is supported.
SUPPORT •
Unlimited support for installation issues via e-mail
•
Unlimited support for basic usage issues via e-mail
•
Interactive help anywhere in AmiBroker (F1 key)
•
AmiBroker website support page http://www.amibroker.com/support.htrnl
9
1
2
Introduction to AmiBroker
On-line video tutorials (the URL is for one example - there are many) http://www.amibroker.com/video/uicustomize.html On-line Users Guide http://www.amibroker.com/guide/ Knowledge base - provided by AmiBroker h tip:!'/www. amibroker. cotn/kb/ Users Knowledge Base - provided by user community h tip:/lwww.amibroker.org/userkb/ Yahoo discussion forum - over 7700 members - over 1000 messages a month http://finance.groups.yahoo.com/group/amibroker/
Chapter 2
Installation
AmiBroker runs under Windows, including versions 95, 98, Millennium, 2000, NT, XP, and Vista. Both 32 bit and 64 bit operating systems are supported. All versions of AmiBroker - trial and registered, standard and professional, end-of-day and real-time - begin with a visit to the AmiBroker web site and downloading the installation file. Using your Internet browser, visit http://www.amibroker.com, then select the download tab. Select either the file for a New and complete installation or an Upgrade installation. If this is your first installation of AmiBroker, choose the New installation. Download the file to your computer - the New installation is about 7 MB. When the download is complete, double-click the installation file (AmiBroker510.exe, or the latest version) to r u n the AmiBroker Setup Wizard. Follow the directions and answer the prompts.
11
12
Introduction to AmiBroker
AmiBroker for Windows 95/98/Me/NT/2k/XP
• NEW! AmiBroker 5.10 (official release) S t o c k charting and a n a l y s i s program, t r i a l w a r e , 32-bit W i n d o w s version. W o r k s on both 32 ־and 64 ־bit Windows. U n i v e r s a l i n s t a l l e r f o r BOTH S t a n d a r d a n d P r o f e s s i o n a l v e r s i o n s . If you are using Windows 95, Internet Explorer 4 or higher must be installed. Find out more
File
Version
NEW!
5.10
[AmiBroker 5.10!
(5.10.2)
NEW! AmiBroker 5.10 UPGRADE ONLY
5.10 (5.10.2)
Release date
Size
J u n e 15, 2008
7MB
J u n e 15, 2008
6MB
Platform
Description
W i n d o w s Vista, W i n d o w s XP, W i n d o w s 2000, W i n d o w s Me, W i n d o w s NT, W i n d o w s 98, Windows 95
NEW AmiBroker 5.10 official release, S t a n d a r d & Professional Editions, Full s e t u p with program, help and e x a m p l e files. Self E x t r a c t i n g EXE S u i t a b l e f o r FIRST TIME REGISTERED a n d FREE TRIAL users.
All s y s t e m s UPGRADE ONLY
M E W AmiBroker 5.10 official r e l e a s e , S t a n d a r d & Professional Editions, U p g r a d e d i s t r i b u t i o n with program, help files. S e l f - E x t r a c t i n g EXE T h i s is FOR U S E R S OF PREVIOUS VERSIONS.
Both AmiBroker and this author recommend accepting the default options and file locations during installation. When the installation is complete, launch AmiBroker. The installation will have created an AmiBroker icon on your desktop. Just double-click that. When AmiBroker starts, it displays a message that it is Standard Edition and Unregistered. This is the trial version, but will be instantly converted to Registered (and Professional Edition, if you requested that) when your AmiBroker Registration file is processed. In the mean time, AmiBroker is ready for your use in Trial mode.
Installation
M i ״i glle
gdlt
yiew
Insert
Fjymat
־» םu® m i > יי
harts
םיx
-V-nteb ; \ Utytn '. j Charts J Averages J Bands J Basic Charts J Custom בEquity J Include J Indicators J Systems / Example / ExampleRotational
Symbol
Analysis O
look i
ffilndow 5.•
״
ו3
Help : י !נסי׳s A f !
'J "DJI (Daily) x / "DJI - Daily 8/31/2007 Open 13240 8, Hi 13472 3. Lo 13240 8, Close 13357 7 (0 9%) Vol"27.316.100 M^cio&e/16) = 13.1
12,837,1, (Version 5.10.2. Build date Jun 15 2008) UNREGISTERED- DOES NOT SAVE CHANGES! Advanced technical analysis sottwa Copyright ® 1995-2008 AmiBroker.cc 1
Kebfuan,
interpretation
For more information visit;
http //www.amibroker a
Technical support:
[email protected]
Bug reports
[email protected]
This progra
;s Microsoft active scripting technologies
August־ ״•״>״J | | |
™Wl»l
ג׳
ם י
Interpretation jffoiapad I Price Date: 8/31/2007 Price and moving averages: ~DJI(DOW JONES INDUSTR) has : closed above Its Short time movng average. Short Bme movng average is currently below mid-time, AND below long dme moving averages. The relationship between price arid moving averages is: neutral
,,.. 111 i l l
120 0; ^ 60.0j«׳ 0 0! ®
mm ^ roi *
| 1׳DJI-RSI( 15) = 51.59
vY
M
• M :\ Sheet 1 / 1. ׳
/
70 O t )
wv^
1 . •'>. V.I 1e
. ־:J»>•! 1• \ Sheet ? \ Sheet 0 / -
A -:
Help,!; SS.FJ..
AMIBROKER IN TRIAL M O D E
AmiBroker in trial mode is fully functional with a few exceptions. •
The trial version will run only 30 days. To r u n longer than that, it must be registered.
•
When processing multiple symbols, the maximum in the trial version is five; the registered version handles an unlimited number.
•
Changes, particularly to the database, will not be saved. Also, if you modify one of the chart panes, the changes you made will not be saved when AmiBroker closes.
DEFAULT DATABASE
When you install AmiBroker, a small database is also installed. Its name is DATA and it contains end-of-day price history for the stocks in the Dow Jones Industrial Average and for the average itself. The date range is short and the quotes are not up-to-date. But it is useful for verifying that the installation was successful and for investigating AmiBroker. You can use AmiBroker and the default database while in trial mode.
12
Introduction to AmiBroker
Chapter 3 - 3 0 Minutes to Useful Results, has some suggestions. You will probably want a longer history and more issues. You can have as many databases as you wish. D A T A is one. You can expand it or add other databases. BLOCK D I A G R A M OF DATABASE
As the block diagram shows, AmiBroker has two levels of database files. The native database is maintained by AmiBroker and AmiQuote, and can be modified by you using the Quote Editor within AmiBroker. The D A T A database is an AmiBroker native database.
AmiBroker native database AmiBroker
application
f / J r Write quotation d a t a R e a d / w r i t e other data
D a t a source switch ׳.•jJJST
R e a d quotation data
When you subscribe to a data provider, that provider will set up an external database that they exclusively maintain. As AmiBroker needs quotes to place on a chart or process in a backtest, the Data Plug-in reads the external database and passes the data to AmiBroker. DATABASE SETUP - E N D ־O F - D A Y
Setting up a database is a two step operation. Step one is establishing the database within AmiBroker and specifying which tickers will be stored in it. Step two is filling the database with historical price quotations. Depending on the processes being used, you may be aware of the two separate steps, or they may be combined and appear to you as a single step. If you will be subscribing to a data service, such as Quotes Plus, the installation procedure for that service will set up a database specifically
Installation
15 ו
for quotes from that service and will be maintained by that service. We will discuss setting up a Quotes Plus database in a few pages. If you want to use one of the free data providers, such as Yahoo, you can either expand DATA or create a new database. The following pages describe how to do that. FREE DATABASE USING A M I Q U O T E
AmiQuote is a companion program to AmiBroker that manages downloading of price quotes, from either Yahoo or msn, and storing those quotes in the AmiBroker database. Return to http://www.amibroker.com and download the setup file for AmiQuote. The current version is 2.00. Double-click aq2000.exe and follow the installation instructions, accepting the defaults.
AmiBroker for Windows 95/98/Me/WT/2k/XP
• AmiQuote Internet stock downloader program - companion to AmiBroker, trialware, 32-bit Windows version. If you are using Windows 95, Internet Explorer 4 or higher must be installed. Find out more
File
NEW! AmiQuote 2.00
Version
2.00
Release date
April 23. 2008
Size
94KB
Alternative sites
Description AmiQuote 2.00 Self-extracting archive. Now supports Yahoo, Yahoo Fundamentals, Google Finance (NEW), MSN Money Central and Forex. Fundamental data import faeture requires AmiBroker 4.81 or higher.
If the only information about the stocks that you want is their ticker symbol, then continue with the method described in the next few paragraphs. If you want to have the ticker and full name, and perhaps the industry sector identification, read the next section, Ticker Only; then read the section, Ticker and Full Name, that follows. It is a good idea to decide this before the database is filled with historical quotes.
12
Introduction to AmiBroker
Ticker Only Begin by deciding which issues you want in your database. Find or ereate a list of their tickers. This does not need to be the final list - you will be able to add additional tickers and historical data at any time in the future. For example, you might want all the stocks in the Russell 1000 index - the 1000 largest capitalization stocks listed on US exchanges. (According to the Russell Investments website, http://10ww.russell.c0m, the Russell 1000 represents approximately 92% of the US equities market. That website also has a list of the current components of all the Russell indices.) Visit http://www.IntroductionToAmibroker.com/resources for links to up-to-date lists of members of various categories. If you want to keep a copy of the original tributed, here is how to make a copy of it.
DATA
database as it was dis-
1. Using Windows Explorer, navigate to the AmiBroker directory. If you accepted all the defaults during installation, it is C:\Program Files\AmiBroker. 2. With Explorer, using the File menu, click New, then Folder. A folder named New Folder will be created. 3. Using Explorer, rename that to the name you want for the original database, for example DataAsDistributed. 4. Using AmiBroker and its File menu, click SaveDataBaseAs, select the folder you just created, DataAsDistributed, click OK. AmiBroker will make a copy of the DATA database in the folder DataAsDistributed. Continuing on to update the database named the Russell 1000.
DATA
with the tickers in
1. Using a simple text editor, such as NotePad, or a spreadsheet, create a file with one ticker per line. The tickers should be in all capital letters. Each ticker must be spelled the same as your data provider spells it. Save that file in the AmiQuote directory with a meaningful file name, such as RussELLlOOO.tls. If you accepted all the defaults during installation, that directory is C:\Program Files\AmiBroker\AmiQuote. Tls files are ordinary text files that are recognized by AmiBroker and AmiQuote as containing lists of ticker symbols. 2. Open AmiBroker. 3. Using the AmiBroker File menu, click Open Database, select the DATA database, click OK.
Installation
ו7
4. Leave AmiBroker open as the next steps are performed. 5. Decide the date you want the historical data to begin. If you plan to do extensive trading system development, I suggest having at least ten years of data available. The characteristics of the markets changed after the October 1987 crash, so data before that date has limited value in developing systems for current conditions. A starting date (From Date) of 1/1/1995 might be reasonable. Use today's date for the end date (the To Date). 6.
Using the Windows Start menu, select the AmiQuote program and run it. You will find it under All Programs > AmiBroker > AmiQuote > AmiQuote.
7. Using AmiQuote's File menu, select Open. Then select the file with the tickers you want to get historical data for, R U S S E L L I O O O . tls, and click Open. H AmiQuote
« ct ט
ca ! •
i Source: Si j!
-
Untitled
—
From:
-
. •
•>
*א
¥
jYahoo Historical { 1/ 1/1995
Automatic import
M (EOD. stocks, funds. US & International (50))
jJ
0
To:
j 7/26/2008
״־J —f
p*
פ
^ervel (Quote.com/Forex):
״יj Run eveiy:
j י
r ״All s e s s i o n s (Quote.com only)
Look in: ji-S AmiQuote
jpJ
m-
® ct 6
C^ Download JSl RUSSELL2000.TLS DJINDUSTRIALS.tls >§ SPlOO.tls :^DJTRANS.tls SPSectorETF.tls DXJTIL.tls Cj FTSElOO.tls 3 NASDAQlOO.tls ':<*3 NEWTICKERS.TLS ^
i
S
B
I
IRUSSELL.1000.TLS Files of type:
!AmiQuote Ticker list (*.tls)
פ
Ready
Be sure that AmiBroker is r u n n i n g and that the database you want updated is the current database. The name of the database in current use is displayed in the status bar in the bottom right-hand corner of the AmiBroker window. If necessary, use the AmiBroker File menu and open the desired database.
*
Introduction to AmiBroker
18
Be sure that AmiQuote's Automatic Import box is Checked. 9. Click the Green Triangle to begin the download. 9
AmiQuote - RUSSELL1000.TLS
File
o־
Edit
y
View
Tools
Help
• « ->
^ fM
[Yahoo Historical From:
J 1/ 1/1995
׳Automatic import
(EOD. stocks, funds, US & Interne jr]
To:
| 7/26/2008
T]
p~
) Status ₪A
Waiting.
0AA
Waiting.
0AAP
Waiting.
0AAPL
Waiting.
0ABC
Waiting.
0ABI
Waiting.
0ABII
Waiting.
r71 a b t
You have asked for over 10,000 years of data, each with 252 sets of Open, High, Low, Close, and Volume. Depending on the speed of your Internet connection, it will take a few minutes to a few hours for the download to complete. 10. AmiQuote will inform you of the progress of the download. If the amount of data stretches the capacity of your communications or your patience, divide the R U S S E L L I O O O I I S file into several smaller files and work with each part in turn. As soon as the data for any individual stock has been downloaded, it is immediately available for use within AmiBroker. You may continue to work with AmiBroker while downloading proceeds. When the download is complete, scroll through the Ticker List in AmiQuote. If there were problems with any of the tickers, there will be messages displayed. A common problem is that the spelling of the ticker in the tls file is not the same as the spelling the data provider uses. In this case, note that Russell Corporation used a period when specifying the Class A stock. Yahoo uses a dash character. Make a list of all the tickers that did not download properly and create a file named N E W T I C K E R S . tls. Add the tickers of any other stocks you want. Using the same procedure, have AmiQuote download the new tickers.
Installation
19 ו
O AmiQuote-RUSSELL1000.TLS File
Edit
a
U
Source: From: 1
view
Tools
I
Help f
j Y a h o o Historical
M (EOD, stocks, funds, US & International (50))
| 1/ 1/1995
To:
1 7/22/2008
׳יI —'
Automatic import Ticker •
^erval _״ (Quote.com/Fore j
All s e s s i o n s (
| Status
1
Imported
ben
Error during download. Yahoo! - 404 Not Found. Either the symbo...
0BFB •
bg
Imported
•
bgc
Imported
•
bhi
Imported
A good source for researching companies and verifying tickers that will be downloaded from Yahoo is the Yahoo financial site, http://finance.yahoo.com/ 11. Close AmiQuote. 12. In AmiBroker, using the File menu, click Save Database. Ticker and Full Name If you want AmiBroker to know the full name of each issue in addition to its ticker symbol, the names must be loaded into the database. One way to do that starts with a text file, similar to the RussELLlOOO.tls file described above, but including the full name of the issue along with the ticker symbol. Optionally, the industry group number can also be included and will be used to place each ticker in its correct category. Each line of this file has the ticker, full name, and industry group number, all separated by commas, and saved in a file with a name such as R1000FuLLNAME.txt (txt, not tls, as you will see in a minute). g TextPad - [C:\Documents arid Settings\Howard\My Docur
n
| File
ם
Edit
& ט
Search 1
m
R1000FULLNAME.T...
View a n
Tools
Macros
1 1 to m o
Configure
o
<•=
+ :
Window
2 IT
Help
®
A,AGILENT TECHNOLOGIES I N C , 2 5 AA,ALCOA I N C , 5 3 AAP,ADVANCE AUTO PARTS I N C , 8 AAPL,APPLE I N C , 2 0 ABC,AMERISOURCEBERGEN CORP,52 ABI,APPLERA CORP A P P L I E D , 5 2 A B I I , A B R A X I S BIOSCIENCE I N C , 1 1 ABT,ABBOTT LABORATORIES,51 ACAS,AMERICAN CAP S T R A T E G I E S , 3 0
Appendix B, Industries and Sectors, has a list of the industries and their respective group numbers. There is no simple way to assign an industry, and its associated industry number, to each ticker. At times, a
12
Introduction to AmiBroker
database of a large number of stocks (such as all US stocks), sometimes including a program to set up a database that is complete with industry number assignments, will appear on one of the AmiBroker discussion forums (see the links in the Appendix C, Resources). These quickly become obsolete with the addition of new stocks and changes to existing ones. If you are very interested in assigning industry numbers to stocks, here are two alternative ways. One. Download the lists of components of each of the Standard & Poor's sector exchange traded funds. One sector at a time, form a watchlist of the members. (See Watchlists, page 179.) Using AmiBroker's Symbol menu, select Organize Assignments and assign all the members of the watchlist the same Sector Number. Two. Subscribe to one of the commercial data providers (see the links in the Appendix C, Resources). In the process of setting up their database, they will assign each stock to its proper market, industry, and group. Most of the services will store additional information, such as number of shares outstanding, dividend, and so forth, that you would have difficulty finding yourself. With R1000FU1_LNAME.txt, the file containing the ticker symbol, full name, and optionally the industry number ready, you are ready to establish the database. This must be done before symbols are entered in any other way and before quotes are downloaded. A simple jscript program, I N D U S T R I E S . ] S (courtesy of Tomasz Janeczko), can be used to read the txt file and establish the database. (The program listing of INDUSTRIES.JS is in Appendix C, Resources, and is in the download materials associated with this book.) Warning: If your database is already established and has historical price data, Do Not r u n this script - it will result in a badly confused database. Use this script only to establish a new database before loading historical quotes into it. In order to run the script: 1. Using Windows Explorer, create a new folder under the AmiBroker directory to hold the new database. Assume it is NEWRIOOO.
2. Run AmiBroker, use the File menu, Open Database, select N E W R I O O O , click OK.
Installation 3. Copy or move
RlOOOFuixNAME.txt
4. Copy or move
INDUSTRIES.JS
5. Double click
21 ו
to your Windows Desktop.
to your desktop.
INDUSTRIES.]S.
The script tells you that the script is started. Click OK. After a short time, less than one minute, the script tells you it is finished. Click OK. Verify that the script worked by using AmiBroker Symbols menu. Expand the All category and note that there are 1000 tickers listed. If you supplied industry codes, expand the Sectors category and note that the tickers have been assigned to sectors. There are no quotes yet. L AmiBroker - [A - AGILENT TECHNOLOGIES INC - Daily] Q. File
Edit
View
Insert
Far mat
Symbol
Analysis
D a ־׳B S l J t l l x ^ o o e i , A Symbols
Window fcjelp
-
fA K
9-i
נ • י
fSymbols j Layouts j Layers 1 Charts j ® • All שO Markets f f l C j Groups Q Sectors שLJ Watch lists Q Favourites O Indexes
Iools
Not enouqh data available. To plot any chart at least 3 data bars are needed, but there are only 0 bars in
To fill the database with historical quotes: 1. Create a .tls file containing the tickers from the first column of R1000FuLLNAME.txt. Name it R U S S E L L I O O O I I S . 2. Follow the directions given in the section above, Ticker Only, to have AmiQuote retrieve historical data from Yahoo. 3. In AmiBroker, using the File menu, click Save Database. 4. Exit AmiBroker. Additional Symbols Whenever you want to add issues to your database, use this procedure: 1. Enter their ticker symbols, one per line, in the file NEwTicKERs.tls. (It is convenient to keep all tls files in the AmiQuote directory.) 2. With AmiBroker running, open the database you want to add to. 3. Run AmiQuote. 4. Using AmiQuote's File menu, open NEwTicKERs.tls.
12
Introduction to AmiBroker 5. Set the From Date and To Date. 6. Check the Automatic Import box. 7. Click the Green Arrow to begin the download. 8. When the download is finished, close AmiQuote. 9. In AmiBroker, Save database.
If you want to record the full name of the issue: 1. In AmiBroker, using the Symbol menu, select Information. The information window for this stock will open. 2. Edit the Full Name field. If you want to assign categories: In AmiBroker either: 1. Using the Symbol menu, select Information. 2. In the Categories section, make whatever assignments you wish for the one ticker you are working with. Or: 1. Using the Symbol menu, select Organize Assignments. 2. Make whatever assignments you wish for the list of tickers you select. Data Updates Once the database has been established and the historical data loaded, maintaining the data by adding the latest quotes is very easy. In AmiBroker, using the Tools menu, select AutoUpdateQuotes. AmiBroker will examine the database that is open, determine the date range needed to bring the quotes for all the issues in this database up to current date, and call AmiQuote to do the download. Since only a few days data is needed for each ticker, the process takes only a short time. . AmiBroker - ["DJI - DOW JONES INDUSTR - Daily] File
Edit
• & y m
Vtew
Insert
Format
&
Symbols
• י
I Symbols j Layouts j Layer? j Charts J Si Q All Si LJ Markets ®•C3 Groups Si CJ Sectors ffi LJ Watch lists
Symbol 0
x
־
Analysis & o 05 -
~DJI (Daily A
l o o Is | Window fcfelp J Database Purify... ןIndicator Maintenance...
DJI - Daily 7/21/2 Gp• Bar Replay S&J Preferences... ייSave preferences Plug-ins... § Customize... Auto-update quotes (AmiQuote only)
B Q Indexes
| Sharenet Down loader f Cleanup database
Installation
23 ו
Sources of Free Data The examples above illustrate using Yahoo as the source of historical data. There are other sources. For US markets, m s n also provides free end-of-day historical data. If you wish to use that source, use the pull down menu in AmiQuote to select msn instead of Yahoo. Keep in mind that consistency is important. Different data suppliers will have different ways of preparing and presenting the data. For example, the volume multiplier may be different, or the ticker spelling may be different. After you load your database with quotes from one supplier, keep the database up-to-date using that same supplier. ASCII Import There are two methods of importing ASCII data: the ASCII Import Wizard (file menu, Import Wizard), and the full ASCII Importer (file menu, Import ASCII). The wizard is good for one-off imports. Its features are a subset of the full importer. If you will be importing the same files regularly, set up the full importer. (Note: the ASCII Import Wizard can create a format definition file for later use with the ASCII Importer.) Before you start, decide which database you want the imported data to go into. If you are just practicing, create a test database and open it. Do not import into your high quality database until you are confident the import procedure is working correctly Download the data files and, if necessary, unzip or expand them. Open the files using a text editor such as Notepad. There should be one quote per line, fields separated by space, semicolon, or comma. There may be a header line describing the fields. If not, identify the fields yourself. If necessary, go to the site from which the data was obtained and read their documentation. The date field is the trickiest. The wizard understands many formats. If your data is in one of them, all you need to do is identify the order of month, day, and year. The codes are DMY, MDY, YMD. If your data does not follow one of the recognized date formats, you will need to reformat the date (for example, by using a spreadsheet) and rewrite the data file before proceeding. The year can be either four digits or two (the final two of the year). The month can be either two digits or three characters (such as Dec or Jan).
12
Introduction to AmiBroker
The day is two digits. The separator can be / (slash), \ (backslash), - (minus), or not separated at all. Assume the date for one quote is December 31, 2000. YMD formats that are recognized include: 20001231 2000-12-31 2000/12/31 2000-Dec-31 001231 00-12-31 00/12/31 00\12\31 If your data has a ticker symbol as a field in each line, the data will be stored under that symbol. If there is not an explicit ticker, the file name will be used. If your data file is downloaded as, for example, IBM.csv, the data will be stored as IBM. If your data file is downloaded with a generic name, such as TABLE.CSV (Yahoo uses this file name for all its individual downloads), rename it before proceeding.
Installation
25 ו
Yahoo Historical Data Download The Yahoo site is a good place to get stock and index historical data. http:Hfinance.yahoo.com Using the investing tab, select stocks. Under research tools, click historical quotes to get this page. Follow these steps to download the historical data for a stock or index: 1.
Enter the ticker (say it is XOM)
2. Click GO 3. The screen will display the most recent data 4. Click Download to Spreadsheet On your desktop, or wherever your default directory to receive downloads is, you will find a file named TABLE.CSV. 5. Rename TABLE.CSV to XOM.csv. Use capital letters if you want your symbol to be in capitals. 6. Proceed to import XOM.csv into AmiBroker using either the ASCII Import Wizard or Import ASCII
12
Introduction to AmiBroker Yahoo'
My yahoo!
Malt : Mot* ׳י
Make Y! My Home Pa 9 e
Y A H O O ? , FINANCE Dow • 0.79Q׳b Nasdaq •V 0.10 ״o HOME
H«,
"V? Search
! :1 GET QUOTES j
Sign Ou«:
H-»lp
WEB SEARCH
Tws, Aits) 12. 20&S.
N E W S & OPINION
howardhandy v
I
P E R S O N A L FINANCE
fT - U.S. Markets close in lhr 36mins.
MY P O R T F O L I O S
»Finance Search
Exxon Mobil Corp. (XOM)
i t 2109PM ETi 7 7 . 6 9 4 0 . 6 0 % ) 0.47 ) ־
^ Q Q •j׳ FREE
Summary
TRADES
fiftMBy
Real-Time ECN • Historical Prices Charts Interactive Basic Chart
Historical Prices
Get Historical Prices for:
SET DATE RANGE Start Date:
Jan
j 2
End Date:
Aug
׳
(§) Daily O Weekly O Monthly O Dividends Only
12
News & Info Headline
Company Profile Kev Statistics Competitors
Date
Open
11־Aug-08
78.52
High 78.95
11-Aug-08
Low 77.04
Close
I
| Next | Last
Volume
Adj Close*
78.16 24,566.800
7816
$ 0.40 Dividend
Industry
8־Aug08־
76.90
78.85
76.31
78.72 29,318,400
78.32
Components
7-Aug08־
78.68
79.11
77.31
77.44 25,346,700
77.05
Analyst Coverage Analyst Opinion Analyfl; Estimates Research Reports
6-Aug08־
78.50
78.65
77.24
78.33 30,790,600
77.93
5-Aug-08
76.50
78.35
76.21
78.35 40,087,100
77.95
4-Aug08־
79.63
80.13
76.14
76.60 37,887,200
76.21
Star Analysts
1-Aug08־
80.55
81.10
79.45
79.72 28,766,900
79.31
Ownership Maior Holders
31-JUI-08
81.82
82.55
80.19
80.43 40.872,900
80.02
30־Jul08־
80.90
84 76
80.53
84.38 36.410,700
83.95
Transactions
29-Jul-08
80.83
81.20
79.75
80.90 25.869,900
80.49
Insider Roster
28-Jul08־
81.87
82.23
80.65
80.68 24.017,500
80.27
Financials tnsgrne Statttmtni; Balance Sheet
25-JUI-08
81.01
82.41
80.76
81.70 27,553,800
81.28
24-JUI-08
81.20
81.95
79.73
80.80 36,789,400
80.39
23-JUI-08
82.98
83.00
80.60
80.99 31,083,500
80.58
22-JUI-08
82.56
83.23
81.57
82.86 27,909,100
82 44
Cash Flow
21־Jul08־
81.84
82.98
81.11
82.98 24,802,500
82.56
14־May08־
89.85
90.99
89.59
89.91 24,178,900
89.45
13-May-08
88.87
89.95
88.53
89.68 21,165,000
89.22
12-May-08
88.43
89.47
87.60
89.19 23,053,200
88.74
9-May08־
89.37
89.59
87.97
88.82 24,054,700
88.37:
9־May08־ 8-May-08
$ 0.40 Dividend I 89.00
89.95
88.52
89.93 24,332,000
89.08
ice adjusted for dividends and splits. 1• ! ־i! | p! 9v ןNext ןLast ^ Down load T o S p r e a d s h e e t — — — — — — —
as Add to Portfolio
v Set Alert
Set Historical Prices for Another Symbol:
>.3 ־Email to a Friend 1[ 00 J Symbol Looku:
יStock S c r e e n e i יMergers & Acquisitions
ASCII Import Wizard The following steps illustrate how to use the ASCII Import Wizard. Before beginning, a database named T E S T has been created and opened. It already has a few symbols and data for them. Data has been down-
Installation
27 ו
from Yahoo for two stocks, GE and XOM, but not yet imported. Since Yahoo downloads all data using the file n a m e TABLE.CSV, the d o w n loaded file was renamed between downloads, so the files are GE.csv loaded
a n d XOM.csv.
1. Using the File menu, select Import Wizard. 2. W h e n the dialog box opens, click Pick Files. 3. Navigate to the directory holding the files you have downloaded.
W e l c o m e to t h e ASCII Import W i z a r d ! M e a s e click the button b e l o w t o o p e n file d i a l o g a n d s e l e c t the files y o u want to import. N o t e that y o u c a n s e l e c t multiple files b y p r e s s i n g S H I F T o r C T R L k e y while s e l e c t i n g the files u s i n g the m o u s e .
Y o u h a v e s e l e c t e d the following file(s):
J> My Recent Documents
pj§ CL. t>ct ® DX.txt © GC.txt GE.CSV ^ IBM. CSV XOM. CSV !®YHOO.csv
Desktop
ע
My D o c u m e n t s
My C o m p u t e r
Open My Network Places
Files of t y p e :
ASCII flies ( ־txt* CSV * pro - dn. ־stc. ׳־־stk) חO p e n as read-only
4. Since the files have identical formats, you can process multiple files in one pass, so select both GE.csv and XOM.csv. (Click one file, press the Control key and click the other.) 5. Click Open. The Define Fields dialog box will open. 1. Note the format of the data in the .csv files. 2. Using the pull-down menus, define the fields for each element of data. Each element in the entire row of data must be defined.
1
2
Introduction to AmiBroker
Select SKIP to ignore data in the csv file that you do not want in your AmiBroker database. 3. Select comma as the separator. 4. Skip 1 line ־the header. 5. Check Automatically add new symbols. 6. Click Next. Define fields H e r e you c a n define the fields in the d a t a file. U s e c o m b o - b o x e s to select appropriate field type. Hover the m o u s e a b o v e the controls to s e e additional hints. Column 1 !YMD
|
Column 2 IjOpen
Column 3
Column 4 ij Low
| High
י
Column 5 i Close
Column 6 v
Volume v !!Skip
| More columns
Separator:
C o m m a (,)
v |
Group:
Group 255
׳י
Watch list:
v
Skipfirst:
|1|
0 Log errors
!
Additional commands:
F71 Automatically a d d new symbols * H I Calculate c o m p o s i t e s [~~1 No quotation d a t e I
I Allow negative prices
D a t a file sample: Date.Open.High,Low,Close,Vo)ume,Adj Close 2008-08-1 "1.78.52,78.95,77.04,78.16.24566800.78.16 2008-08-08.76.90.78.85.76.31.78.72.29318400.78.32 י 2008-08-07.78.68,79.11,77.31,77.44,25346700,77.05
Help
The Additional Settings screen will come up. It is on this screen that you can save the format settings that you just used. They will not help for future uses of the ASCII Import Wizard, but they will be available in the full ASCII importer. To do this, Check Add current settings to ASCII importer definitions, and give meaningful Description and File Name. You will see your format as we look at the full ASCII Importer in the next section. 7.
Click Finish.
Installation
29 ו
Additional settings Now you are r e a d y to import the tile(s) P l e a s e c h e c k additional settings below if you wont to u s e current format in the future
f l A d d current settings to ASCII importer definitions Importer settings
I
< Back
[[
Finish
J
|
Cancel
|
|
Help
The data will be converted from ASCII, imported into the open database, and be immediately ready for use in AmiBroker. ASCII Importer The full ASCII Importer is much more efficient, has more capabilities, and is more complex. Rather than having to fill in a form each time you want to import an ASCII file, you can set up a format definition file, or use one of the pre-defined files. The file that was created for the import done manually using the wizard in the previous section is: # Format definition file generated automatically # by A m i B r o k e r ' s A S C I I I m p o r t W i z a r d SFORMAT Date_YMD, Open, High, Low, Close, Volume, Skip SSKIPLINES 1 $SEPARATOR , $CONT 1 $GROUP 255 $AUTOADD 1 $DEBUG 1
12
Introduction to AmiBroker
The definition files are stored in the C:\Program Files\AmiBroker\Formats directory. By copying the format file that you will be using regularly to be DEFAULT.FORMAT, all that is necessary to import ASCII files is: 1.
Using the File Menu, select Import ASCII. File ןEdit
View
Insert
Format
[Jew
•
Open...
Ctr l+O
Qlose Open Database... S a v e Database S a v e Database As... Save
u
Ctrl+S
S a v e As... S a v e All D a t a b a s e settings,,,
&
Import Wizard.,,
rif
Import ASCII.
210
Import MetaStock data...
a
Print Preview
m Print...
Ctrl+P
Print Setup...
2. On the Open screen, select the file you want to import. 3. Click Open.
U j My R e c e n t Documents
0 Desktop
; !gjCL.txt [email protected] © GC.txt f&GE.CSV ! !®IBM.CSV !®XOM.CSV : ? S y h o o .CSV
My D o c u m e n t s
My C o m p u t e r
Open
File n a m e : My Network Places
: Files of type:
! y a h o o (*")־ F~10pen as read-only
The file will be converted, imported, and made available within AmiBroker for immediate use. The options available for controlling the processing of ASCII data are extensive. Read about them all in the AmiBroker User's Guide.
Installation
31 ו
SUBSCRIPTION DATA PROVIDERS
Free data has a cost to you - the cost of checking the data for missing quotes, bad values, unadjusted splits, and so forth, and correcting those problems. Subscription data services, such as Quotes Plus, Premium Data, CSI, and others, provide that maintenance for you and deliver cleaner, more consistent data with less effort on your part. End-of-day stock data costs about $40 per month - more for some services, less for others. Some end-of-day vendors include mutual f u n d s at no charge; others charge extra. Commodities and futures data is an additional cost, depending in part on the fees the exchanges that clear those trades and report that data charge. Some subscription vendors provide custorn indices, custom indicators, and have a wider selection of issues - and often charge an extra amount for those. Some services charge a one-time fee for loading the historical data, others do not. If you plan to use a subscription service, be aware that each service has its own database format. Once you begin with one subscription service, they will be the only service that can keep your data up-to-date. The installation procedure for each service will be unique to that service, but it is generally simple and well documented. Typically, the installation does three things for you: 1. Establishes the external database and the communications between the database and AmiBroker. 2. Loads the definitions of the tickers, including the ticker symbol, the full name, and the industry assignment. 3. Loads the historical price data. After the close of trading each day, you initiate communication with the data vendor. The database is brought up-to-date, and errors and inconsistencies are corrected and re-downloaded, all automatically. Some vendors provide intraday updating - treating the latest price as though it is the closing price. At subsequent updatings, the earlier prices are replaced by the more recent ones. Quotes Plus End-of-Day Data Here is the procedure to set up a Quotes Plus subscription end-of-day database. Each data provider will have their own specific details and methods,
12
Introduction to AmiBroker
but the end result is the same - an end-of-day database that is established a n d loaded with historical data by the data vendor. Tickers, full names, industry associations, and other information related to that stock are all provided by the vendor, stored in the external database for that subscription, and m a d e available to AmiBroker through an interface that is transparent to you as a user. 1.
Begin with a visit to Quotes Plus' website: http://www.qp2.com/ joomla/index.php.
2. Pull d o w n the Products menu, select QP3, and click Free Trial. Quotes Plus Financial c/ata and software for and commodity traders %V
stock
B Q H
Home
© 3. Fill in the contact information. You will receive an email from Quotes Plus containing a User ID, Password, and the URL link to a d o w n l o a d utility. 4. Follow the link to the download utility a n d download the Qp3Setup.exe file. 5. Execute that file to start the installation of the database and download of the historical quotation data. This is the first screen you will see. E W e l c o m e t o t h e Internet installer f o r Q u o t e s P l u s 3.1
You will be required to enter your Quotes Plus User ID and Password in order to download the data files from the web Please collect that information now. It is strongly recommended that you exit all Windows programs before continuing with this installation If you have any other programs running, please click Cancel, close the programs, and run this setup again Otherwise, click Next to continue
As you follow the instructions, you will be asked for your User ID a n d Password.
33 ו
Installation 6.
Select the data files you want. Q u o t e s Plus Setup Please select the data files that you want to install. The program files will always be installed Program Features Include data for US stocks and indexes on the Nasdaq. NYSE and Amex exchanges.
0 Mutual Fund data P?| Commodity Data Files • Stock Picker Pro
(781.3MB)
Space required for Data Files: 1.07 GB
| ך
tjex* >
j !
Cancel
I
7. Accept the defaults for the location of the program (which you will use to keep the data up-to-date) and the data files. The path to the program will be C:\Program Files\Quotes Plus, and to the data files will be C:\Quotes Plus Data. 8. When the download is complete, click Finish. If you selected the stock data, mutual f u n d data, and commodities data, the total data transmitted will be about 260MB. If that will strain your communications capabilities, Quotes Plus will mail you a CD. C O N N E C T THE DATABASE TO A M I B R O K E R .
In AmiBroker, from the File menu, select New, and Database. Working in the top half of the Database settings window: 1. In the Database Folder box, enter the name you want for your new database. 2. Check Load this database at startup. 3. Click Create. Database settings AmiBroker d a t a b a s e maintains infromation a b o u t symbols, industry groups, watch lists. It is n e c e s s a r y even if you a r e using external d a t a General Database folder: C:\Program F1les\Am1Broker\QP End of Day
_ 0 Load this d a t a b a s e at s t a r t u p
5
j
Browse...
1
C r e a t e
Data s o u r c e Data s o u r c e : Local d a t a s t o r a g e :
Number of b a r s : (260 daily b a r s is a b o u t o n e year w o r t h ) Base time interval:
1 (approx. 2 5 0 days, 7 KB per symbol) | End-Of-Day
I Intraday settings
12
Introduction to AmiBroker
Now working in the bottom half of the Database settings window: 1. Pull down the Data Source menu and select Quotes Plus data Plug-in. 2. Click Enable Local data storage. 3. Enter 1000 for the Number of bars. 4. Click Configure. Database settings AmiBroker database maintains Infromation about symbols, industry groups, watch lists. It is necessary even if you are using external data General Database folder:
p ] Load this database a t startup
: Data source - • : |
Data source: Local data storage:
(3)Enable ( r e c o m m e n d e d ) - — O Disable
Number of bars: (260 daily bars is about one year worth)
;
Base time interval:
iEnd-Of-Day
1000
:
©
(approx. 3 years, 31 KB per symbol)
Configure
Intraday settings
On Configuration: 1. Select the categories you want in the database. 2. Click Retrieve. Wait while the data is retrieved. 3. Click Close. Quotes Plus plugin configuration D a t a b a s e setup Select c a t e g o r i e s to retrieve (all items belonging to given c a t e g o r y will be a d d e d to the d a t a b a s e ) : -0 ®
Stocks Indexes
0 Sector/industiy a s s i g n m e n t s 0 Mutual funds 0 C a s h futures 0 Commodity futures (continuous)
I Volume Crossover
חOnly symbols with issue_status » 0 0 Exclude symbols without q u o t e s
•e Options |
| U n a d j u s t e d (raw) d a t a
Back on Database settings, Click OK.
Installation
35 ו
Your Quotes Plus database is now established, loaded with historical quotes, installed in AmiBroker, and ready for use. To load a chart: 1. In AmiBroker, using the Symbols menu, expand the All category (click the + sign). 2. Click on any of the ticker symbols. The data for that ticker will load into the main chart window. 3. In AmiBroker, Save database. Norgate Premium Data ־End-of-Day Norgate Investor Service provides quality end-of-day data for stock markets in Australia (ASX), Asia (SGX), and the United States (NYSE, NASDAQ, AMEX, OTC-BB, PinkSheets). Extensive historical data is available, including data for delisted stocks (an important feature for those interested in studying survivorship bias). The 900 lian and
data integrates very well with the symbol lists, and includes over pre-built and automatically maintained watchlists for the Austraand US databases. Hourly snapshot data is available for the ASX SGX.
Data is provided in MetaStock data format. (If you are installing Premium Data as an AmiBroker database, you will not be aware of the format of the external database.) Norgate also provides end-of-day data for 86 liquid futures markets. Futures data is available in individual, spliced continuous, and backadjusted continuous contract forms. All the fields required for serious backtesting (margin, point value, tick size, etc.) are populated. Data is provided in ASCII and MetaStock data formats. Norgate is in the process of improving their integration with AmiBroker. A new native AmiBroker data plugin that will provide additional speed and features is under development. Visit http://www.premiumdata. net/support/amibroker.php for the latest details. Free trials are available.
12
Introduction to AmiBroker
The next pages discuss setting up Norgate end-of-day data for the Australian stock market. 1 .
Sign up for a subscription or free trial at their web site: http://www.prefniwndata.net. F u t u r e s a n d FOREX End o f D a y D a t a i n M e t a S t o c k D a t a a n d ASCII D a t a f o r m a t s - Mozilla F i r e f o x File
Edit
View V
History
Bookmarks ^
Tools
http / www prerrnurndata.net/
* >
• Customize Links (j Free Hotmail Q Windows Marketplace jj Windows Media Q Windows # Snaglt HJ'
:
j Window [autoscroil]
v
O
Help
; Ask for File Name
•ט
n iQl Login Lj BookFlnder.com: Sear...
*׳
NORGATE INVESTOR SERVICES Products & Services
Help, Support & Resources
»־
Corporate Information
S T O C K M A R K E T E N D O F DAY D A T A
F O R E I G N E X C H A N G E END OF DAY D A T A
N o r g a t e Investor S e r v i c e s p r o v i d e s quality e n d - o f - d a y d a t a for stock markets in Australia (ASX), Asia (SGX) and USA (AMEX, N A S D A Q , N Y S E . Q T C - B B , P i n k S h e e t s ) E x t e n s i v e h i s t o r i c a l d a t a is available Hourly s n a p s h o t d a t a is available for t h e A S X a n d S G X . D a t a i s provided i n M e t a S t o c k d a t a format.
Foreign E x c h a n g e (FOREX) data covers 82 currency pairs on an e n d - o f - d a y b a s i s D a t a is provided in ASCII a n d M e t a S t o c k d a t a f o r m a t s Extensive historical c u r r e n c y d a t a b a c k t o 1 9 9 1 i s available
S t o c k d a t a i s o r g a n i s e d into s e c u r i t y t y p e s ( e q u i t i e s , i n d i c e s , w a r r a n t s , o p t i o n s ) a n d c a n b e o r g a n i s e d into c u s t o m f o l d e r s w h i c h allow y o u t o s e g r e g a t e s u c h a s index participation, s e c t o r , i n d u s t r y g r o u p , d i v i d e n d - p a y i n g - s h a r e s W o r l d Indices a r e p r o v i d e d f r e e with a n y s u b s c r i p t i o n . Recent additions S u r v i v o r s h i p - b i a s - f r e e historical d a t a b a c k t o 1 9 5 0 including delisted s t o c k s for U S m a r k e t s F U T U R E S M A R K E T E N D OF DAY DATA D a t a is a l s o p r o v i d e d f o r 86 highly liquid f u t u r e s m a r k e t s in A u s t r a l i a ( S F E ) , Asia (HKEX, K S E , S G X ) , C a n a d a (Mx, W C E ) , E u r o p e (Eure*, I F F F u t u r e s Hun:[׳.״:-׳, I.II I I ) •1! וווII!״ US (CBOT, CME, C O M E X . KCBT, NYMEX, ICE F u t u r e s U S ) C o v e r a g e i n c l u d e s p r e c i o u s metals, c u r r e n c i e s , i n d e x e s , i n t e r e s t r a t e s , b o n d s , e n e r g y c o m m o d i t i e s , agricultural c o m m o d i t i e s . F u t u r e s d a t a is available in individual, s p l i c e d continuous and back-adjusted continuous contract forms and e x t e n s i v e historical d a t a is available D a t a is p r o v i d e d in ASCII and MetaStock data formats
WHY PAY FOR DATA? T h e r e ' s plenty of f r e e d a t a available on the Internet. However, in o r d e r t o k e e p t h e d a t a fully m a i n t a i n e d for c o r p o r a t e a c t i o n s (delistings, splits, c o n s o l i d a t i o n s , dilutions, m e r g e s , c o d e c h a n g e s , n a m e c h a n g e s , d e f e r r e d s e t t l e m e n t history m e r g e s , capital r e t u r n s ) , y o u will n e e d t o s p e n d s e v e r a l h o u r s e a c h m o n t h t w e a k i n g y o u r d a t a b a s e You n e e d t o a s k yourself w h e t h e r y o u w a n t to be a t r a d e r or a d a t a b a s e m a n a g e r
FREE TRIAL In o r d e r for y o u to test o u r d a t a s e r v i c e s , we o f f e r a fully functional f r e e trial T h e trial allows y o u to test a six month trial d a t a history for all of o u r m a r k e t s plus t h r e e w e e k s of daily u p d a t e s . Simply s e l e c t w h i c h m a r k e t s y o u wish t o trial a n d y o u will be u p d a t i n g within a matter of m i n u t e s
Done
2. You will receive an e-mail with your user name and password, and a link to the download page. 3. Go to that web page and login. 4. The services you have subscribed to will be noted in the download screen. You will need to download at least three files: A. Program Installer B. History Installer C. AmiBroker Setup.
Installation
37 ו
Premium Data / DataTools / Premium Forex Downloads
File Type
Size
Description/FileNarrie
Appro* Download Time for 56K Modem/1 5Mbps Broadband
Click below to DOWNLOAD from
Stocks Program Installer
Premium Data & Premium Charts setup premiumdaia exe
3.1 MB
14 mins/1 mins
East Coast USA Server W e s t Coast USA Server Australian Server European Server
History Installer
Australian Securities Exchange (Stocks) Database - Limited 12 month history for all currently listed stocks, except tor listed, 7.3 MB codes starting with , A' which have full history, lnsta!IHist1>rj,AS*.tri»l.2tBB080e.«jB
34 mins/1 mins
East Coast USA Server W e s t Coast USA Server Australian Server European Server
AmiBroker Files The following files are applicable for users of the AmiBroker charting software ONLY Only download them if you have AmiBroker installed on your PC, More information about these files can be found at AmiBroker FAQ AmiBroker A S X Workspace Setup with ©ICS classifications, AmiBroker groups and extensive watchlists Setup ArnBrok8r-ASX-PrBmtumDaia־y1 41.exe
0.8 MB
4 rnins/1 mins
East Coast USA Server W e s t Coast USA Server Australian Server European Server
Market Analyst Files The following files are applicable for users of the Market Analyst charting software ONLY, Only download them if y o u have Market Analyst installed on your PC,
Market Analyst
All versions of Market Analyst have a bug related to dates prior to January 1900 This historical installer replaces just the W o r l d Indices with data that extends after this date This file is only required if you have Market Analyst installed on your 2.3 MB computer. This file is NOT applicable the HomeTrader version of Market Analyst as it has no MetaStock reading capabilities BislallHlstory WorlfcaiMS MwkatAmilyst aWOBlO me
10 mins/1 tnins
Ea^t Cojjst LISA Server W e s t Coast USA Server Australian Server European Server
To download a program or history installer, click on the corresponding server closest to you (Australia. Europe or USA) Choose to Save the file to your Windows Desktop, or to some other location where you can find it readily
Click on the server nearest to you (Australia, Europe or USA). 5. Save the files and accept all the defaults for file locations. 6. The Program Installer and History Installer must be in the same subdirectory on your computer. 7. Insure that AmiBroker is not running. 8. Locate the program installer, run it and follow the prompts. The program installer will recognise the history installer and offer to install the history for you as part of the process. If the files are too large for your communications, you may prefer to order a data history CD which will be sent out to you by ordinary mail.
1 2 Introduction to AmiBroker Execute the files in this order: 1) Program Installer. 2) Historical Data Installer. 3) AmiBroker Setup. W ׳Norgate Premium Data File
Edit
©
B
View a
re$;
c
Favorites 0
Tools
,j C:\Documents and Sett1ngs\Howard\pesktop\Norgate Premium Data x
Folders [ | j $ Desktop a at m
Help
\ י © ־ ׳ ־/ ) s e a r c h ! ^ Folders |
My Documents y My Computer
Name
*
CpAmiBroker-ASX-PremiumData-vl.41.exe יי ]lpInstellHistory.ASX.tr ial.20080808.exe — ^gj setup. pre m iu mdata.exe
Size : Type 844 KB Application 3,223 KB Application
My Network Places jgl Recycle Bin
ש
ASCII Downloads
i!
Misc Folders
yBSSSSSSSS ij~) Quotes Plus Setup
£ i C i Unused Desktop Shortcuts
When the AmiBroker Setup runs, it will open a browser-based FAQ page explaining how to install the interface necessary for AmiBroker to use the Premium Data files.
© e
Installation
39 ו
AmiBroker Setup will establish a database in the AmiBroker directory, but it will not be usable yet. Here is how to connect the two:
Look in:
My R e c e n t
&
Documents
Desktop
J
My Documents
Q AmiBroker
0 ,t
m -
O AmiQuote QASX-PremiumData QCodeGen !OData O DataAsD istr touted I^DataRusselllOO• OeSignal JQ For mats iQFormulas QlntraDay Q Layouts ii^j Notes O P i Continuous Contracts © P I Data Q Plug ins O Q P End of Day O Reports O Scripts
My Computer
My Network Places
File name:
|
OperT"
Files of type:
10. Start AmiBroker. 11. Using the Tools menu, click ASX-Premium Data. This will r u n a script with seven stages that takes several minutes. Tools | Window
yelp
׳Database Purify,,, i: Indicator Maintenance,,, Bar Replay &
Preferences... Save preferences Plug-ins... Customize... | Auto-update quotes (AmiQuote only) | Sharenet Downloader f Cleanup database ASX-PrerniumData
12
Introduction to AmiBroker 12. Using the File menu, select Open Database, select ASXPremiumData, click OK. Browse for Folder Please select workspace directory C :\Program F i les\A m Broker\ASX-Pre rn iu mData £9
AmiBroker as Q AmiQuote CodeGen SB Si Data DataAsDistributed m fcg DataRusselllOOO eSignal ^ Formats Si Q Formulas ® IntraDay
13. Here is AmiBroker with BHP in the chart window. L AmiBroker - [BHP - BHP BILLITON LIMITED ORDINARY - Daily] File
Edit
• » B @
View
Insert
Format
«
Symbol O
Analysis
!0013
Window
Help
O [
<1! te>
BHP (Daily) • BHP - Dally 8/13/2008 O p e n :-a; 65. Hi 37,1 0 36 :6׳, C l o s e 36 76 ( 1 2%) Vol 11,177.735 a - [ ! . : ׳ ׳ ״: ׳I5j = 37 66, Mid MA(f
A, A"
'•rAh
1־/
>
50.0: 48.0 48.0
A^^־..
^
EliHAil
39.7846
I&IHII
V^/l
V
38 4063n H37.65870 35 5447D
1
Sep
'Oct
'Nov
'Dec
'2008
'Feb
1
'Mar
1
Apr
May
'Jun
'Jul
'Aug
| BHP - MACD(12,26) _ = J .03, Signal( 12,26,9) = - 1 . 0 8 , EMA(MACD( 12.26), 15) = - 1 4 1
I B0 1 20; 0 60
ttlllllli.
= 48 96,; •
BHP - RSI(15) = 41 54, EMA(RSI(15),15) = 41 75
•
= 35 18 p,
1
fSep .
1
"• 1 l
• ••י
• F 1
05ז
,
Nov
1
Dec
'2608
' S h e e t 1 , S h e e t 2 ןSheet 3 ^ Sheet •4
Teb f
1
Tviaf
Apr
Titey
Sheet 5 \ Sheet 6 ), sheet 7 , 1
1
h.
1
Jun
Qui
lAug
. 1
ן י י:.׳'׳- • 1 • ז.ו,.ו^י. -
r\
: . F1
,1.1 ,1:.g
Installation
41 ו
DATABASE SETUP - INTRADAY A N D REAL-TIME D A T A
Intraday data is data with bars shorter than a full trading day. Taking great care and using a data vendor that supports it, it is possible to combine intraday and end-of-day data in the same database. But most AmiBroker users who use intraday data maintain a separate intraday database. The next few pages describe setting up intraday and real-time data. FREE INTRADAY HISTORICAL DATA
If you are interested in developing systems with intraday data, but are not ready to commit to a real-time data subscription, you can download intraday bars into an AmiBroker database and work with them. If your systems test out to be profitable, you will eventually need real-time data to execute them. There are several sources of free intraday historical data. Visit http:// www.lntroductionToAmiBroker.com/resonrces and scroll down to the data area for links to some of them. AN Futures sells intraday data for the emini S&P 500, e-mini NASDAQ 100, e-mini Russell 2000, Euro, and Yen in 1 minute bar and tick resolution. Visit them at: http://wzow.anfutures. com/. They have a demo file, ES0206MG.csv with 1 minute bars for the e-mini S&P June 2002 contract - 3/6/2002 through 6/12/2002. The third column is the date, with 20306 meant to be 2002, March, 6. ES01MIG.I,20306.15:50.1165.5,1165.5,1165.5.1165.5,8.1159.5 ES01MIG.I,20306.15:51.1165.5.1165.5,1165.5,1165.5.3.1159.5 ES01MIG.I,20306.15:52.1165.5,1165.5.1165.5,1165.5,9,1159.5 ES01MIG,I,20306,15:53.1164.25,1164.25.1164.25,1164.25,6.1158.25 ES01MIG.I,20306,15:54,1162.25,1162.25,1162.25,1162.25,1.1156.25 ESOIMIO.I,20306,15:55,1164.5,1164.5,1164.5,1164.5.3.1158.5 ES01MIG.1,20306.16:20.1164.25.1164.25,1164.25,1164.25,1.1158.25 ES01MIG.I.20306.16:21,1164.1164,1164.1164,1.1158 ESOIMIG.I,20306,16:24,1164.25.1164.25,1164.25,1164.25,1.1158.25
AmiBroker can accept many date formats, but not that one, so a spreadsheet is used to transform the date into one of the acceptable formats and 20306 becomes 2002-03-06. The Excel formula to do this is: =״200&״LEFT(C1,1)&״-&״MID(C1,2,2)&״-&״MID(C1,4,2), where the 20306 is in cell CI. Make a copy of the original data file, replace the date, and save it with a new name, for example E S 0 2 0 6 M O D . C S V . The following procedure will set up a database into which we will load the e-mini S&P intraday data. This is the same procedure used to set up the Quotes Plus end-of-day database, so the illustrations will be omitted.
12
Introduction to AmiBroker 1. In AmiBroker, from the File menu, select New, then Database.
Working first in the top half of the window: 2. In Destination Folder, choose a meaningful name for the database - such as IntraDay. 3. Uncheck Load this database at startup. 4. Click Create. Now working in the bottom half of the window: 1. Data Source: (local database) 2. Local data storage: Enable 3. Number of bars: 100000 4. Base time interval: 1 minute 5. Accept the defaults for Intraday settings 6.
Click OK
The database is established, but has no data in it. The ASCII importer will load the data from the csv file using the ASCII Import Wizard in the following procedure: 1. In AmiBroker, from the File menu, select Import Wizard. 2. Click Pick Files. 3. Navigate to the location of your modified file and select it. 4. Click Open. 5. Click Next. 6. Fill in the fields. Here you can define the fields in the d a t a file. U s e c o m b o - b o x e s to select appropriate field type. Hover the m o u s e a b o v e the controls to s e e additional hints. Column 1
Column 2
Column 3
Column 4
Column 5
Column 6
Column 8
Column 9
Column 10
Column 11
Skipfirst:
[0
Separator:
jComma(.)
1
Group:
| Group 255
•
Watch list
Column 7
Column 12
j lines.
0 LL oo g errors ® [*/!Automatically a d d new symbols
•ו
חCalculate
Additional commands:
composites
F 1 N o quotation d a t a P |־Allow negative prices
D a t a file sample: ES01 MIG.I.2002-03-06.15:50.1165 5.1165.5.1165.5.1165.5,8.1159 5 | ES01 MIG.I.2002-03-06,15:51.1165.5.1165.5,1165.5.1165.5.3.1159.5 IES01 MIG.I.2002-03-06.15:52.1165.5,1165.5.1165.5.1165.5.9.1159.5 ;ES01 MIG.I.2002-03-06.15:53.1164.25.1164.25,1164 25.1164 25,6.1158.25
I
< Back
|[
Next >
]
j
Cancel
)
[
Help
Installation
43 ו
7. Click Next. 8. Click Finish. The data will be imported and the active chart will display the intraday data you just loaded.
9.
In AmiBroker, Save Database.
If you were going to import data from this vendor regularly, you cou Id set up a macro in the spreadsheet to convert the date field, and set up a custom ASCII format in AmiBroker specifically for that file format. But, eventually, you will need a real-time data feed to create 1 minute bars throughout the trading day. DELAYED REAL-TIME D A T A
Some data vendors offer real-time data that has been delayed 15, 20, or 30 minutes. It is priced lower than non-delayed real-time data, and often is free. From the perspective of a developer of trading systems, about the only reasons to use delayed real-time data are to try out a data service or to build up a tick-based database. And, since most of the high quality data services have a trial period, you can try the real thing for the same amount of effort. Trying to place trades using delayed real-time data is dangerous to your wealth — a lot can happen in 15 minutes.
44
Introduction to AmiBroker
REAL-TIME D A T A
Real-time data can be expensive. Prices range from about $50 to several h u n d r e d per month for the basic service which includes a limited number of tickers. There are additional charges for extra services, such as charting packages, Level II quotes, or getting data for a larger number of issues. Exchange fees, which are set by the exchange that clears trades for the tickers listed by them, are also added. There are different levels of exchange fees for professional and non-professional traders. Exchange fees can add up to several hundred dollars a month. Most real-time data vendors have trial periods, but the exchange fees charged during the trial are usually not refundable. Also, check your Internet communications capacity and your communication vendor's fair use policy. Monitoring about ten symbols in the real-time quote window causes traffic of about 50 MB per hour. Done every trading day of the month, this will exceed the fair use limits of some vendors. As mentioned earlier, some vendors support combining end-of-day and intraday data in the same database. But that can be tricky. These steps describe separate intraday databases. Quotes Plus Real-Time Data The procedure to set up a real-time data feed using Quotes Plus is: 1. Begin with a visit to Quotes Plus' website: http://www.qp2.corn/ joomla/index.php. 2. Pull down the Products menu, select QPFeed, and click Free Trial.
3. Fill in the contact information. You will receive an email from Quotes Plus containing a User ID, Password, and the URL link to a download utility.
Installation
45 ו
4. Follow the link to the download utility and download the qpfeed_setup.exe file. 5. Execute that file to start the installation. 6. Enter your User ID and Password when requested. 7. Accept all the defaults. 8. Click Finish to the final dialog and the program will close. The procedure to connect AmiBroker to the QPFeed is: 1. Start AmiBroker. 2. You will see a message saying that there is a new plug-in from qpfeed. Click OK. —
:
•
ז
: — —
— י: :
IE
ל
AmiBroker You are using following NON-CERTIFIED third-party plugins:
qpfeed_ami.dll - qpFeed Real Time Data Plug-in, vl.0.92 by Quotes Plus www.quotes-plus.com 1
AmiBroker.com makes NO REPRESENTATIONS on features / performance of such third party plugins. Entire use of non-certified third-party plugins is AT YOU? OWN RISK. This message will not appear anymore unless you install new non-certified plugins
1
3.
°K
|
Using the File menu, select New, then Database.
Working in the top half of the box: 1. In the Database folder box, enter the n a m e you want for your new real-time database. 2. Check or uncheck, as you wish, Load this database at startup. 3. Click Create. AmiBroker database maintains infromation about symbols, industry groups, watch lists, It is necessary even if you are using external data General Database folder: - וC:\program Files'\Arn!Broker\0P RealTime J v ] ׳Load this database at startup
j
Browse...
I
Create
Data sourc8 Data source: Local data storage:
Number of bars: (260 daily bars is about one year worth) Base time interval:
J
End-Of-Day Inlraday settings
(approx. 19 years, 156 KB per symbol)
j 1"
©
12
Introduction to AmiBroker
Now working in the bottom half of the Database settings box: 1. Pull down the Data Source menu and select QPfeed Real Time Data Plugin. 2. Click Enable local data storage. 3. Enter 25000 for number of bars. 4. Pull d o w n the Base Time Interval menu and select 1 minute. 5. Click Configure. The configuration menu will appear. 6. Select the categories you want to receive. 7. Check Exclude symbols without quotes. 8. Click Retrieve. 9. Click Close. Return to the Database settings screen. 10. Click OK. Database settings AmiBroker database maintains infromation about symbols, industry groups, watch lists. It is necessary even if you are using external data General Database folder:
[
| Load this database at startup
Data source Data source: Local data storage:
Number of bars: (260 daily bars is about one year worth)
Quotes Plus plugin configuration D a t a b a s e setup Select c a t e g o r i e s to retrieve (all items belonging to given c a t e g o r y will be a d d e d to the d a t a b a s e ) :
0 -
0
Stocks
[y*l Indexes חSector/industry a s s i g n m e n t s [ I Mutual funds חCash futures I
| Commodity futures (continuous)
!Volume Crossover ׳יי
PI Only s y m b o l s with issue_status = 0 0 ־־Exclude s y m b o l s without q u o t e s
•Q Options חU n a d j u s t e d (raw) d a t a
Installation
47 ו
At this point, you have a database established to store 1 minute bars and the QPFeed ready to supply data. To bring up a chart: 1. Using theAmiBroker Symbol menu, select New. 2. Type in a symbol, say SPY. In a few seconds the chart will appear. ix AmiBroker - [SPY - S6 P DEP RECEIPTS - 1 - m i n u t e ] צEfe D
tf
Edit e
j
yiew ft
Insert
Format
;,
Charts
Symbol O
6
Analysis O S !
Help
lools SPY
SPY ( 1 - m i n u t e ) x S P Y - 1 - m i n u t e 8 / 1 4 / 2 0 0 8 2 : 0 5 : 0 0 PM O p e n 1 2 9 . 7 9 . Hi 1 2 9 . 8 4 . Lo 129 7 8 " c i 0 s e 129^8 ( 0 . 0 % ) Vol
Averages | f DEMA - Double / DispMA - Displ; / EMA - Exponen / Linear Regress / MA - Simple M! / TEMA - Triple f f / TSF - Time Sei / Wllders - Wilde / WMA - Weight! !3: D Bands / Bollinger Bands / Keltner Bands / Percent Bands S LJ Basic Charts / Open Interest ( / Price / Price (all in on< / Price (foreign) / Relative Perfor / Volume / Volume (color) / Volume At Pric! tei LJ Custom / AlertlfTest / ATC Trading Fi / Liquidity / RelativeStrengl / SimpleSystem / SimpleSystem f Unnamed 1 / Unnamed 2 י
'8/13/2008 >
For Help, press F1
>13:00
'13:45
'14:30
'15:15
1
8/14/2008'10:30
•I \ S h e e t 1 / ׳S h e e t 2 \ Sheet 3 \ Sheet 4 \ Sheet 5
"11:15
'12:00
Sheet c - s M
>12:45
'13:30
<
Undefined, Undefined, Services, Advertising 9 QP RealTime
Introduction to AmiBroker
48
DTN IQ Real-Time Data The procedure to set up a real-time data feed using DTN IQ Feed is: 1.
Visit the DTN IQ Feed web site at: http://www.iqfeed.net ) W e l c o m e to l a F e e d ! - Fast, Reliable, Affordable. Datafeeds and API. - Mozilla Firefox File
Edit
״
View
History
,;ן,'׳״
Bookmarks ,'
Tools
Help
: : /http://www.1qfeed.net
Snagit 123' j I Windowjautoscroll] v Ask for File Name #
iOFEED If you want customer service that answers the phone, your best bet is IQFeed. I cannot stop praising them or their technical support. They are always there for you, and they are quick. I have used ****** too but the best value is iQFeed." - Comment from Public Forum "With HUGE volume on AAPL and RIMM (or 2 days, everyone in a trading room was whining about freezes, crashes and lag with **»**״, RealTick, TS and Cyber. InvestorRT with IQFeed was rock solid. I mean SOLD!" - Comment from Public W e l c o m e to IQFeed! You are about to find out how nice it is to work with a company like DTN! It all starts with our Sales Reps who will make sure you are setup with the data you need at the best price possible. We know you expect "service after the sale" too! Our 800M Customer Supportl'me is nearly always answered on the first ring, we respond to emails within 1 hour, and we offer real-time chat on our website. You won't find a company more committed to ensuring your success as a trader/ A b o u t IQFeed
For T r a d e r s 13
For D e v e l o p e r s
Have a Q u e s t i o n for S a l e s ? Call 800-475-4755 Email [email protected]
D
mm
GUCKTOCHAT
ONLINE
NMI
Support
i
Developers
— Sen/ices
Symbol Guide
Fees
/ /
Compatible S o f t w a r e G e t F r e e Trial N o w Add S e r v i c e s $ 1 0 0 Referral Credit
'
Symbol Look-Up
Developer Login Developer Registration
4
Download Client Support F o r u m s Live C h a t Contacts Other Products
ONLINE
2. Click Get Free Trial Now. Complete the application forms. The trial is exactly the same as the subscription version. The trial turns into a subscription at the end of the trial period, unless you call to cancel it. DTN will send an e-mail with your User ID and PIN. 3. Return to that web site and Click Download Client. The current version is a file named iqfeed_client_4_4.exe, and is about 3 MB.
Installation 4.
49 ו
Run iqfeed_client_4_4.exe. Accept al I the defaults. When you click finish on the final screen, the iqfeed program will be installed on your computer. f IQFeed Client 4.4.0.3 Setup
ffih
D ' ' ״SI
W e l c o m e to the IQFeed Client 4.4.0.3 Setup W i z a r d This wizard will guide you through Ihe installation of IQFeed Client 4.4.0.3. It is recommended that you close all other applications before starting Setup, This will make it possible to update relevant system files without having to reboot your computer, Click Next to continue.
|
Next >
j
[
Cancel
|
To set up an AmiBroker real-time database using DTN IQFeed: 1.
In AmiBroker, using the File menu, select New, then Database.
Working in the top half of the box: 1. In the Database folder box, enter the name you want for your new real-time database. 2. Check or uncheck, as you wish, Load this database at startup. 3. Click Create.
Introduction to AmiBroker 1w working in the bottom half of the Database settings box: 1. Pull down the Data Source menu and select DTN IQfeed data Plugin. 2. Click Enable local data storage. 3. Enter 25000 for number of bars. 4. Pull d o w n the Base Time Interval menu and select 1 minute. 5. Click Configure. The configuration menu will appear. 6. Note that DTN IQ has a bad tick filter. Accept the defaults. Click OK Return to the Database settings screen. 7. Click OK. Database settings AmiBroker database maintains infromation about symbols, industry groups, watch lists. It is necessary even if you are using external data General Database folder:
Installation The IQ Connect Login will appear. 8. Enter your Login. 9. Enter your Password or PIN. 10. Click Connect. Your computer will communicate with the DTN IQ server. IQ. Connect Login
g]
4.4
־Login: ]229999
— P a s s w o r d or P i n : j****
Quit
F~ S a v e L o g i n A n d P a s s w o r d / P i n F
Automatically Connect
Idle
As your agreement for the receipt and use of market data
י׳
provides, D T N , the Securities Markets and Content P r o v i d e r s (1) r e s e r v e all r i g h t s t o t h e d a t a t h e y m a k e a v a i l a b l e ; (2) d o n o t g u a r a n t e e t h a t d a t a ; a n d ( 3 ) s h a l l n o t
To bring up a chart: 1. Using theAmiBroker Symbol menu, select New. 2. Type in a symbol, say SPY.
m
Enter a new symbol name Enter one or more tickers to odd (comma separated)
1 1
1
1 Cancel
1
51 ו
Introduction to AmiBroker
52
In a few seconds the chart will appear. Add other symbols, open the Realtime Quote Window, and continue. A AmiBroker - [OQQ.Q - POWERSHRS QQQ TR SR1 ETF - 1 -minute] & צle
Format
Edit
•
y0
Symbols
ן י
%
x
Symbol 0 <>
l-M
Analysis O 3
Xools
Window
QQQQ
;
Help
׳י.,
ft ־fe׳
!
Ss A S>
ihdwm
9,i.
•i QQQQ (1 m i n u t e ) x J Q Q Q Q - 1 - m i n u t e 8 / 1 5 / 2 0 0 8 10:41:00 AM O p e n 4 8 . 2 8 . Hi 4 8 . 3 . Lo 4 8 . 2 6 , C l o s e 4 8 . 2 9 (0
Vol 156.271
g CJ All • * * # • # $ -t
QQQQ SPY XLB XLE XLF XLI XLK XLP
4 8 SOD
48.400 48.3129
• XLU # XLV # XLY Li £_] Markets ® D Groups S r C l Sectors IS D Watch lists 55 SP Sectors # XLB # XLE # XLF f XLI # XLK # XLP # XLU # XLV # XLY S3 L_J Favourites • QQQQ • SPY LJ Indexes
"8/14/2008" 18 00 :::
t
or Help, press F1
'08:00
' 0 8 30
״U9 0 0 1 0 9 : 1 5
' 0 9 4 5 1 1 0 00' 10:15' 10:30
S
h
e
e
t
<
Realtime Quote
T...
£
QQQQ SPY XLB XLE XLF XLI XLK XLP XLU XLV XLY
• :
'8/15/2008
•I \ Sheet 1 ^ S h e e t 2 ^ S h e e t 3 ^ Sheet4 ^ S h e e t 5 ^
Open
?
Low
High
Last: Change
% Ch...
Volume
Trad...
Bid
Bid size
X
48.35
48.57
48,00
48.29
0.04
+0.08%
48,622,947
1,200
48.28
108,800
48.29 J
129.93
130.50
129.30
130.00
0.46
+0.36%
68,989,474
100
130.00
30,900
130.01 |
39.55
39.55
38.94
39,03
־0.57
־1.44%
2,663,618
400
39.03
100
39.04 1
71.84
71.87
70.33
70.33
-1,82
-2,52%
11,757,690
100
70.33
500
70.34 J
21.28
21.64
21.13
21.43
0,22
+1,04%
56,124,772
4,715
21.42
51,800
21.43 J
35.59
35.77
35.43
35.71
0.26
+0.ד3%
1,233,746
100
35.70
52,200
35.71 ;
23,68
23.79
23.52
23.71
0.07
+•0,30%
1,473,548
600
23,71
7,900
23,72 |
28,72
28,98
28.65
28.98
0.28
+0.98%
100
28,98
45,700
28.99 J
36,92
37.09
36.83
36.85
0.03
+0.08%
956,108
100
36,85
4,300
36,86 J
33.21
33,61
33.21
33.54
0.26
+0.78%
1,075,601
197
33.54
61,900
30.96
31,41
30.96
31.24
0,38
+1,23%
1,616,266
100
31.24
8,200
N \ List 1 ^ L i s t 2 \
List 3
\.Ust4X List 5
648,612
s
Ask j 111
^
m p
3 3 , 5 5 J HII 31,25 J
/ ^ List 6 V List
>
<
Undefined, Undefined, Services, Advertising # IQ RealTime
01:
••
״
Installation
53 ו
T I C K DATA
Tick data refers to market data that represents the time and transaction price, and perhaps the volume, of every trade. Depending on the exchange and the data vendor, the tick data stream may also include other information, such as changes in the bid price, the asked price, the volume on each side. Just as it is possible to make display bars that represent a given amount of time, say 1 minute, it is possible to display bars that represent a given number of ticks, say 15 ticks. In the opinion of this author, tick data is not appropriate for use by individuals and small trading companies. The highest quality tick data includes an information packet for every transaction. Some of the difAcuities with tick data include: high cost; very high volume of transactions; erroneous transactions (called bad ticks - see example below); dropping of transactions when exchange activity increases (fast market conditions) or when communications capacity is reached. . AmiBroker - [SPY - Sa P DEP RECEIPTS -1 -minute] 2 Eiie
Edit
yiew
Insert
Format
D«B0
Symbol
®
Analysis
Tools
Window
8 1 , SPY
Help
י,
m
SPY ( 1 - m i n u t e ) x °
J S P Y - l - m i n u t e 8 / 1 4 / 2 0 0 8 2:29:00 PM O p e n 129.72, Hi 129.76, Lo 129 69, C l o s e 129 7 ( - 0 . 0 % ) Vol 144,361 MA(CI0se,15)
i7i
130.20;
/ik
128.S3B0 •0
-t?
60
#
s u a 129 4 0
kSi 129.00 126.00 126 6 0 j 1fB/14/20Q8 9/14/20Q8'1 12:45 12:45 •
TFi^
rfMO
T345
!14:15
T^OO
•I \ S h e e t 1 ^ Sheet 2 ^ Sheet 3 '). s h e e t 1 \ 5heet 5 ). S h e e t 6 ^ Sheet 7 \ s h - s - I
Realtime Quote T״, £ Open XLB XLE XLF XLI XLK XLP XLU XLV XLY
39,64 72.90 20.46 35.07 23.41 28.54 37.17 32.91 30.04 •
' 1T3M : 9 0O
\\ | ץList
-eip, press F
High
Low
Last
Change
% Ch...
Volume
39.80 74.38 21.26 35.73 23,75 28.89 37.17 33.57 31.28
39.06 71.36 20,38 34,89 23,28 28.35 36.65 32.89 30.01
39.48 72.32 21.05 35.47 23.66 28.74 36.87 33.41 30.97
־0.20 -1.18
־0.50% ־1.61%
8,075,...
0.48
+2.33%
0.15
+0,42%
0.20
+0,85%
0.17
+0.60%
90,46... 5,628,... 3,419,... 3,427,... 2,594,.,, 2,453,... 4,008,...
/ L i s t 2 V List 3
־0.27
־0.73%
0.11
+D.33%
0,57
+1.87%
\List4\ LBt5X
Trad...
28,17...
List 6 \ List 7 \ List 8
X: 8/14/2008 1:06:00 PM, Bar: 2491 Y: 129.5398
150 100 500 100 200 100 110 100 100
X u<
<
Bid
Bid size
Ask
39.47 72.32 21,04 35.47 23.66 28.73 36.87 33.40 30.96
31
39.48 72.33 21.05 35.48 23.67 28.74 36.88 33.41 30.97
36
2,581 191 73 959 364 21 380
Asks...
52w ...
52v>.
9 3 356
128 1,199 77 25 804 185 ,נ
Undefined. Undefined, Services, Advertising > QP ReafTime
>::
jfc
54
Introduction to AmiBroker
Tick data is best used by larger organizations that have high capacity equipment, redundant data feeds, and staff devoted to monitoring and correcting the data. To use tick data in AmiBroker, the Professional version is requ i red. If you want to experiment with very frequent data, try working with 1 minute bars instead of tick data. This book will not discuss tick data further.
Chapter 3
30 Minutes to Useful Results
You have installed AmiBroker and the Data database. This chapter describes ten things you can do with AmiBroker - even while it is in Trial Mode - each in only a few minutes. •
Example 1 - Chart a Stock
•
Example 2 - Apply a Trendline
•
Example 3 - Plot a Moving Average
•
Example 4 - Make a Watch list
•
Example 5 - Run an Exploration
•
Example 6 - Run a Single Stock Backtest
•
Example 7 - Run a Portfolio Backtest
•
Example 8 ־Optimize a Trading System
•
Example 9 - Perform Walk Forward Validation
•
Example 10 - Scan for Buy and Sell Signals
None of these is intended to be a complete description of the features used in the example. But working through them should give you a bet55
56
Introduction to AmiBroker
ter feeling for the capabilities and ease of use of AmiBroker, and provide some experience as you read about other features. Examples build. Later examples assume you can perform tasks described in earlier examples.
57
30 Minutes to Useful Results EXAMPLE 1 - C H A R T A STOCK
In this example, you will chart a stock, change its periodicity, chart a new stock, scroll, and zoom. ^
gg.
To start AmiBroker, either:
Mozilla Firefbx
Jasc Paint Shop Pro 8
PowerPoint
AmiBroker
A
iA
•
Double-click the AmiBroker icon that was placed on your desktop during installation.
•
Using the Windows Start menu, select AmiBroker, then AmiBroker.
©
S
Windows Explorer
Excel
lH
AmiQuote
J j ^ AmiBroker —— i l l Read M e Snaglt 8
| § | Release N o t e s
Dragon NaturallySpe..
[ | g User's Guide
AmiBroker will display the default chart window.
0le
Edit
yiew
Insert
Fermat
Symbol
Analysis
Q ^ B S I
OB,
Symbols
Window
Help
- <5
״ יa,
0נ1
! g>
£.-
/ /
a • J I (Daily) » "DJI - Daily 8 / 3 1 / 2 0 0 7 O p e n 1 3 2 4 0 . 9 , Hi 1 3 4 7 2 3, Lo 1 3 2 4 0 . 8 , C l o s e 1 3 3 5 7 7 (0.9%) Vol 2 7 , 3 1 6 , 1
I 5ym.,, | Lay,,, j La a U All l«t LJ Markets & Cj Groups iji l_J Sectors ® U Watrh lists O Favourites 8
lools
" * 14,00• 13.178:2
I Indexes « "Oil
I2.837.1j
12,400;
12,000: 1
Interpretation
ז
x
1
Feb
1
Mar
Fen Help. pre ׳;׳, F 1
Jun
1
TJUT
Aug 180.0
120,0!
/Y
Price Date: 8 / 3 1 / 2 0 0 7
1
1
May
1 " D J I - M A C D ( 1 2 , 2 6 ) = - 4 9 1 6 , S i g n a l ( 1 2 , 2 8 , 9 X = - 8 2 64
Interpretation 'v :• :׳, :
Price a n d moving averages: A D J I ( p O W JONES INDUSTR) h a s closed a b o v e its S h o r t time moving average, S h o r t time moving average is currently below mid-tjme, AND below long time moving a v e r a g e s . The relationship b e t w e e n price a n d moving a v e r a g e s is: neutral in
1
Apr
80,01
JSfiijllllilllUUiii... ,
1
ייI] || 111 " י י111111 י
1
If " ״
•DJI - R S I ( 1 5 ) = 51 59
vq
יגpf
r va
w
M 1
..
Feb
ן.
\״i ׳ Hvlir
1
*Apr
1
May
1
־J u n
rJ 1
Jul
\ SHEET 1 J^ Sheet 2 ^ Sheet 3 ^ Sheet 4 ^ Sheet 5 ^ Sheet יs i - 1 NYSE, Git!׳.:
v 1
yy
Aug <
•vIvhm־t1:-.1ru|
The chart window has three panes. The top pane has the price of the Dow Jones Industrial Average in candlestick format. Applied to those
58
Introduction to AmiBroker
prices are several indicators - some moving averages and a set of Bollinger Bands. The middle pane has an MACD indicator. The bottom pane has an RSI indicator. The prices are from the data that is installed in the default database named DATA. The chart is displaying Daily data, one bar for each trading day. To display the data in weekly format, click the Weekly view icon in the View toolbar. 4 AmiBroker - [׳DJI - DOW JONES INDUSTR - Daily] E'le
Edit
םe & y @
!$ew
m
Insert
Symbol
Analysis
Iools
\A£indow
Help
X
Symbols
י
ןSym... j Lay...
Format
X x
jlay
M CA AH its • Markets ?1 LJ Groups » - C 3 Sectors !1 D Watch lists : i_J Favourites S LJ Indexes •
׳TOI
Interpretation Interpretation j Notepad Price Date: 8 / 3 1 / 2 0 0 7 Price a n d m o v i n g averages: A D3I(DOW JONES INDUSTR) h a s c l o s e d a b o v e its S h o r t t i m e moving average. S h o r t time moving a v e r a g e is c u r r e n t l y b e l o w m i d - t i m e , AND b e l o w l o n g time m o v i n g a v e r a g e s . T h e relationship b e t w e e n pr r i c e a n d m o v i nעg
,
a v e r a g e s is: n e u t r a l in
v
1
Feb :
I
1
Mar
•
1
Apr
May
1
Jun
Qui
'Aug
M \ S h e e t 1 ^ Sheet 2 ^ Sheet 3 ^ Sheet 4 ^ Sheet 5 \ Sheet- s M
Weekly quotation view
<
NYSE, Group 4, Services, Advertising
To choose a new symbol to plot: 'L AmiBroker - [ ' D J I - DOW JONES & File D
Edit
» ־H @
View #
Insert
Format
Symbols
9 x
; Symbols j layouts 1 layers j Charts. j
# AXP # BA # CAT # ׳DD $ ]WAIT DISNEY-DISNE^ # GM
$ HD # HON # HPQ
Symbol
^
*־""" י י
£ ״
DJI
1. Click the Symbols tabbed menu. 2. Expand the All category by clicking on the + sign. The list will expand to show all of the ticker symbols in the database. 3. Click one of the entries, say DIS.
30 Minutes to Useful Results
59
Since the charts were last displayed using weekly bars, they remain in weekly bars when the new symbol is plotted. Return the chart to daily bars by clicking on the Daily view icon in the View toolbar.
Using the Scroll Bar in the lower right corner of the window, scroll back in time (to the left) to display earlier data. 70.D
/A W 1AL / ^ xjJA V y M 1
1
Jul
Xsh־s,S \-
5
.,
Aug <
, Recreational Acth • Data
•m
o
h d
30.0
h״
*
Using the Zoom In icon on the View toolbar, zoom in to see fewer data bars, but in more detail.
Zoom back out using the Zoom Out icon on the View toolbar. (There is no graphic for this step.)
60
Introduction to AmiBroker
To exit AmiBroker, using the File pull-down menu, select Exit.
• ; F i l e ןEdit 0
View
Insert
Formal
* New
Syrrj S" ׳Open,., 1
fsyri
Ctrl+O
Close
Ef&l Open Database... ^
Save Database ׳Save Database As...
yl
Save
Ctrl+S
Save As... 0
Save AH Database settings... Import Wizard... Import ASCII...
i SIB': Import MetaStock data... | #
Print...
|
Print Preview
Intel
Print Setup...
| Intd Pric D3t;
Ctrl+P
Send chart via E-mail 1 Data
61
30 Minutes to Useful Results EXAMPLE 2 - APPLY A TRENDLINE
In this example, you will apply a trendline, resize panes, and move a trendline. Start AmiBroker and plot the data for GE (General Electric) using Daily bars. L AmiBroker [ ־GE - GEN ELECTRIC CO - Daily] '.m r j l e D
^
Edit B
I
Viev׳.׳ ג
Insert
Fgrmat
S5״toi8.X.
•־
Symbol O
9
Symbols
x
! Symbols 1 l a y o u t ! Layers• Charts i S C j All #
«
O
Analysis ffl
,
JOG It
Window
Help 1 «<־
GE
!
fe
9 *
/ •• ל< יי, •i t> ;
, OE (Daily) x GE -Daily 3/31/2007 O p e n 3B 3, Hi 39 09 I
3
סE 49 C l o s e 33 S7 [
2 % ) Vol 3 7 3 . 5 3 0 M s
A." 1
־׳DJI
38.7614 ס
0 AA •
41.0:
E M S
AXP
• BA 0 C 0 CAT •
DD
38.88480
<# DIS 0 EK
36.0
0 GE 35 0
0 GM 0 HD
34.0
* HON 0 HPQ
"TApT
TET
'May
0 80
? X j •GE - M A C D ( 1 2 , 2 6 ) = - 0 , 0 5 , S i g n a l ( 1 2 , 2 6
Interpretation
0 60
! Interpretation : Notepad
0 40
Price Date: a / 3 1 / 2 0 0 7 Price a n d m o v i n g a v e r a g e s : GE(GEN ELECTRIC C O ) h a s c l o s e d a b o v e its S h o r t time m o v i n g average. S h o r t time m o v i n g a v e r a g e Is c u r r e n t l y below mid-time, AND a b o v e long time moving a v e r a g e s . T h e relationship b e t w e e n price a n d m o v i n g a v e r a g e s Is; n e u t r a l iri s h o r t - t e r m , a n d n e u t r a l 1 חmid-long term.
| G E - R S I ( 1 5 ) = 51.23
'Apr N
Bollinger B a n d s :
1
.heel I , -
'May ,
ן. ׳
Our ו
,
heet 4
1
Tjul .
•H
.
Aug
.
:
UV'.-i , Group 1, Conglomerates, Conglomer * Data
1r Help, pre!
Resize the panes to give the chart more screen real estate. ... ־
V x Charts j
GE (Daily) x
GE- Daily8/31/2007 0ן
A
H- -
V ? X
1
V
1 1 Feb Mar •GE-MACD(12,28) = -0
1. Move your m o u s e slowly across the vertical bar between the top p a n e and the Symbols window. Watch for the cursor to change from a single large arrow to two small a r r o w s on either side of two vertical lines. 2. W h e n you have the n e w cursor, leftclick, hold the m o u s e button d o w n , d r a g the vertical divider to the left, release the mouse.
Introduction to AmiBroker
62
Pick the points you want to use for your trendline. One technique is to connect two or more bottoms. For this example, we will use the low on April 24, 2007 and the low on July 11, 2007. That line passes very close to the bottom on June 8, 2007, so the line is supported by three bottoms. Use your mouse to select the Extended Trendline Tool from the Draw toolbar.
•MMhtCi _
<1 t> 83MA(CI0se,15;
41.0 39 78140
E0QB390'
S3|U
m
I ;
36.99460 36.0 35.0 34.0
The cursor will change to a small crosshairs. Position the cursor at the low on April 24, 2007. The ToolTip box will display the information about the bar your cursor is hovering over. When it is in the correct place, left-click your mouse. I, AmiBroker - [GE - GEN ELECTRIC CO - Daily] צ
Eite
Insert
i׳iew
Edit
Format
Symbol
Analysis
m yjy ׳, >: י״o 0 a - ge
D
? X
Symbols
S... •L. . I L... j C ״. f
' .M '!I (Daily) X j
___
!aols
Window
Help
_ _____
^
^
> ־־־OJI # AA ^ AXP
! | |
$ BA #
|
C
# CAT
!
* DD
|
# DIS
! j
# EK • GE
j
# GM
j
# HD
I
V
* HON <
j
»
Interpretation
? X
Open: 34.5497 High: 34.6887 Low: 3 4 . 3 0 1 5 Close: 3 4 . 5 1 Volume: 3 7 4 2 8 3 O p e n Int.: 0 Close = 3 4 . 5 1 MA (Close, 15) = 3 4 . 8 1 6 7 Mid MA (Close,45) = 3 4 . 7 9 1 6 Long MA(Close, 100) = 3 5 . 5 6 3 7 BBT0p(CI0se,15,2) = 35.2138 BBB0t(Cbse,15,2) = 34.4196 Volume() = 3 7 4 2 8 3
| Interpr... I Notepad ן Price Date: 4/24/2007 Price a n d moving averages: GE(GEN ELECTRIC C O ) h a s closed b e l o w its S h o r t time m o v i n g average. Short time moving a v e r a g e is For Help, p r e s s F1
J״fx ׳י״
1
*־
:
GE - D a i l y 4 / 2 4 / 2 0 0 7 O p e n 34 5 4 9 7 , Hi 34 6 8 8 7 , Lo 34 3 0 1 5 , C l o s e 34 51 j-0 1 % j , V • ! 3 7 4 , 2 0 3 MA(C In e 15
A
• a - 0 3 AH
1
Feb >
Mar
1
Apr
1
May
'Jun
'Jul
^ S h e e t 1 ^ S h e e t 2 ^ S h e e t 3 ^ S h e e t 4 ^ S h e e t 5 ^ S h e e t 6 ^ Sh•• s > I
X: 4 / 2 4 / 2 0 0 7 , Bar: 6 6 0
Y: 34.3944
V 1
Aug <
NYSE, Group 1, Conglomerates, Conglomer if Data
30 Minutes to Useful Results
63
Move your mouse, with no buttons held down, to the low on July 11, 2007. The ToolTip will tell you where you are. AmiBroker [ ־GE - GEN ELECTRIC CO - Daily] File
Edit
View
Insert
Format
DtSHS # VM,^,.."' Symbols
יX
Symbol
Analysis
»« 8 9 ־
Xools
Window
׳J
Help
־־
«
C GE (Daily) ׳
i s . . . j L... ו ץ [ c . . . ןGE - Daily 4/24/2007 O p e n 34.5497, Hi 34 6 8 8 7 , L0 34 3 0 1 5 . C l o s e 34.51 (-0.1%) Vol 3 7 4 . 2 8 3 MA(Close,15: yv - i_J Al * ׳t)JI • AA • AXP * BA • C • CAT DD • DIS EK Open: 37.8 # GE High: 38.24 # GM Low: 37.73 HD Close: 38.2 <* HON Volume: 332874 ׳י Open Int.: 0 Close = 38.2 MA (Close, 15) = 38.348 Interpretation יx [ GE - MACD( 12,26) Mid MA (Close,45) = 37.5109 Interpr... I Notepad j = 36.1766 Price A: jj = 38.9042 BBBot(Close, 15,2) = 37.7918 Date: Volume() = 332874 4/24/2007 » f r o - ' n i r p 1 ־״ Price and moving averages: GE(GEN ELECTRIC CO) has closed below its Short time moving average. Short time moving average is •I \ S h e e t 1 Sheet 2 ^ Sheet 3 For Help, press F1
X: 7/11/2007, Bar: 714
Y: 37.7459
39.78WG fcfelilifcH
3• 7b,•'3 36.99460 36.0 35.0 34.0
NYSE, Group 1, Conglomerates, Conglorner » Data
When you are satisfied with the position of your second point, left-click your mouse. The trendline will be d r a w n between the two points you selected and extended to both the right and left. You will see two small red squares at the points you used to define the trendline.
64
Introduction to AmiBroker
If you want to move one of the end points, hover your mouse over the red square until it becomes a two-headed arrow. Then left-click, drag the square to the position you want, and release the mouse button. If you want to move the whole trendline, hover your mouse over the trend line between the two red squares until it becomes a four-headed arrow. Then left-click, drag the trendline to the position you want it, and release the mouse button. The trendline will maintain its angle and be parallel to its original position. Scroll, zoom, change to weekly - do whatever you want to with the chart - the trendline will remain anchored at the two red squares and change with the chart. If you have a registered version of AmiBroker, the trendline will be saved when you exit. If you are unregistered, no changes are saved. The techniques for placing and moving a trendline apply to most of the tools on the Draw toolbar. Exit AmiBroker.
30 Minutes to Useful Results
65
EXAMPLE 3 - PLOT A M O V I N G AVERAGE
In this example, you will insert a new pane with a new price series, overlay it with a moving average, and modify the moving average. Start AmiBroker. You will see the normal chart window with three panes. If necessary, resize the panes so that you can see the Charts tabbed menu. Follow these steps to insert a price series in a new pane into the window: 1. Click the Charts tab. 2. Expand the Basic Charts category by clicking on the +. 3. Right-click Price, which brings up the context menu. 4. Left-click Insert.
Q t f o o
0
a
M a
x
m Ci Averages A !3) Q Bands •53 C3 Basic Charts / Open Interest (futures j
/ /
Vd Vq
LJ Custo Ss Qj Equity! D Includ
Ar1a|
ysis
Rename Delete New
Interpretation
Rafr־sh
Interpretatloi 1 ! j w j g j a u Price Date: 6/5/2007
Note the tip at the bottom of the w i n d o w that tells you what this command will do.
66
Introduction to AmiBroker
A new pane is opened as the bottom pane and the price series is plotted in candlestick format. A properties dialog box is also opened. Click OK to close it. Move your mouse slowly over the divider between the new pane and the one above it until the cursor changes to two parallel lines with two small arrows. Use this cursor to resize the new pane to make it bigger.
1
Jul
,1K!
Aug־
¥,i
A
Left-click in the new pane to be certain that it is active (or selected, or has the focus). Follow these steps to apply an Exponential Moving Average to the Price series: 1. Click the Charts tab. 2. Expand the Averages category. 3. Right-click EMA - Exponential Moving Average, which brings up the context menu. 4. Left-click Overlay. £ AmiBroker - [GE - GEN ELECTRIC tssi File
Edit
View
• & y m mi
Insert
Charts
Format
י
Symbol
0 <
x
Symb... | Layouts [ l a y e r s | Charts : ! Averages / DEMA - Double Expone / DispMA - Displaced Mc Linear Regression - li / MA - Simple Moving
—w* 1H
/ TEMA - Triple Expon! / T S F - Time S e r i e s F1| / Wilders - Wilders Mc / WMA - Weighted Moi
Analysis
s Q j Bands
Edit
!« i_i Basic C h a r t s
Rename
® C3 C u s t o m
Delete
H i Equity
New
An exponential moving average, based on the price series, is plotted in the same pane and with the same scale as the price series.
30 Minutes to Useful Results
67
A properties dialog box is also opened. Properties of: Price Parameters
Axes S
O EMA Price field
Close
Periods
15
Color
•
Red
Style
If you are satisfied with the parameter values, Click OK. If you want to change one or more of them, follow these steps. To change the length of the moving average, click in the area to the right of the Periods field. Then either: • Type a numeric value for the length. • Use the slider to adjust the length.
Properties of: Pi ice Parameters
Axes
• EMA Price field Periods j
Color
Cllse j[!5 M
St/le
As you change the length of the moving average, the line that plots the moving average changes immediately to reflect the n e w length parameter. Move the slider and watch the red line. As the length is shorter, the moving average responds quickly and hugs the prices more closely. As the length increases, the moving average is smoother, but lags behind when the price series changes.
68
Introduction to AmiBroker
To change the color of the line used to plot the moving average, click in the area to the right of the Color field. A color chart will appear and you can choose the color you prefer.
Parameters
Axes & Grid
B EMA Price tield
Close
Periods
15
Color Style
| V Red
•••••••• •
a
•
•
•
•
•
p • ם • • • ם •••••••ם.
•
ט
DC
Mere...
To change the type of line, click in the area to the right of the Style field. A pull-down menu will give you choices such as dashed, dotted, and thick. Properties of: Price Parameters B
Axes a Grid
EMA
Price tield
Close
Periods
15
Color
•
Red
•
Thick
•
Dashed
SVte
י *
The Axes and Grid Tab also has some parameters that can be changed, but skip them for now. If you have a registered version of AmiBroker, the window, including the new pane with the price series and moving average, will be saved when you exit. If you are unregistered, no changes are saved. The techniques used to modify the moving average are also applicable to many of the indicators on the Charts tabbed menu. Exit AmiBroker.
30 Minutes to Useful Results
69
EXAMPLE 4 - M A K E A WATCHLIST
In this example you will make a watchlist, modify it, and use it to display the charts of each member. Start AmiBroker. Follow these steps to learn about Watchlist Number 0: 1. Click on the Symbols tabbed menu. 2. Expand the Watchlist category. 3. Hover your mouse over List 0. L AmiBroker [ ־AA ־ALCOA INC - Daily] File
g
Edit
View
Insert
g
*
y
Fgrmat
Symbol
O
Symbols
An;
O 3
* י
j Symbols j Layouts j Layers j Charts j
<8 O
All i±i CJ Markets
A:;
® l _ | Groups !£ LJ S e c t o r s ׳־S t 3 Watch lists LisLQ 1 Lis 1Watchlist #0: List 0 (0 symbols)] ז CJ List z ״ ץ CJ List 3
| 1 |
A message informs you that there are 0 symbols in List 0. Follow these steps to add three ticker symbols to Watchlist 0: 1. Right-click List 0. The context menu will open. 2. Left-click Type-in symbols.
02 File D
Edit
&» &
View
&
Insert
v
^ IS
Fgrmat x
׳ x
Symbols Symbols ! Lay >־uts ! Layers ] Charts }
A,
a םAll bt LJ Markets 1B CJ Groups ;*> LJ S e c t o r s S - D Watch lists •
List
D List L J List D
Add selected symbol R e m o v e selected symbol
List
Import...
L J List
Export...
LJ List
E r a s e (make empty)
L J List Q
List
Sort alphabetically
LJ List Hide Empty watch lists Interpretation Interpretation
New watchlist... Delete watchlist
Symbol 0
0
70
Introduction to AmiBroker
A dialog box will open, inviting you to Type symbols into watchlist. Type symbols into watchlist Enter o n e or m o r e tickers to a d d ( c o m m a separated)
1. Type in IP,DD,AA. Use all capital letters and separate the symbols with commas. 2. Click OK. Expand Watchlist 0 and note that it now has three members. ! Symbols j Layouts : Layers I Charts 1־ U All H a Markets S r G j Groups IS CJ Sectors 58 03 Watch lists
s€a|§0j $ IP # DD • AA L3 List 1 • List 2 ! D List 3 : Q3 List 4 • List 5 D List 6
Rename Watchlist 0 to something more meaningful, say Basic Materials: 1. Click the name, List 0. 2. Wait a few seconds. 3. Click List 0 again. The name field will be selected. Symbols j Layouts | Layers J Charts ffl L J if C3 & Q i® LJ e CJ B
All Markets Groups Sectors Watch lists ® # IP # DD ׳# AA D List 1 C3 List 2 •••03 List 3 CJ List 4 D List 5 C3 List 6
30 Minutes to Useful Results
71
4. Type the new name, Basic Materials. 5. Press Enter. The watchlist has been renamed. Symbols j l a y o u t s I !..avers | Chart? l O All iii CJ Markets as L_J Groups d Sectors a Q Watch lists •
IP
•
DD
•
AA
D List 1 D List 2 U List 3 Q List 4 123 List 5 CJ List 6
Add a symbol to the watchlist: 1. Right-click the name of the watchlist, Basic Materials. A context menu opens. 2. Left-click Type in symbols. A dialog box opens. 3. Type in the additional symbol(s), say XOM. The watchlist has four members. Symbols I Layouts j Layers ; Charts ; i® U All Hi C3 Markets [_J Groups i£ U S e c t o r s B D Watch lists B
Basic Materials •
*
DD
AA INTL
I
PAPER]
# XOM O List 1 0 נList 2 LJ List 3 •
List 4
12 נList 5
To use the watchlist to rapidly review the charts of its members: 1. Left-click the first member of the list, IP. The chart for International Paper will be displayed. 2. Press the keyboard cursor-down-arrow key. The chart of the next member, DuPont, will be displayed. 3. Continue through the watchlist. Exit AmiBroker.
72
Introduction to AmiBroker
EXAMPLE 5 ־R U N AN EXPLORATION
In this example, you will use the Formula Editor, and write and r u n an Exploration. For this exploration, the AFL program checks a watchlist to see how many stocks are at new 10 day highs or new 10 day lows. There is also a short introduction to Automatic Analysis. Start AmiBroker. FORMULA EDITOR
First, use the Formula Editor to write and save an AFL program. Open the Formula Editor: 1. Click the Analysis pull-down menu. 2. Click Formula Editor. The Editor window will open. i AmiBroker - [AA - ALCOA INC - Daily] I
tj Pile
םa;
Edit ט
fip
Yiew
<3
Insert
Format
-
Symbol ©
Analysis [ l o o l s
UV
י
t
a׳ !j!t
<
Window
Hi
Quick Review.., Automatic Analysis... Commentary,,. Formula Editor... AFL Code Wizard
^
j
3. Expand the Editor window enough to give yourself room to work. 4. Type the AFL code into the window so that it matches the example below. L. [C:\Program Files\AmiBroker\Formulas\Custo1^\Exam... Fife
Edit
look
D lit W / / // //
S
Help l o S i B
E x a m p l e 5 . a fl Exploration C h e c k s f o r new
'
10
day
high
or
L i q u i d i t y = MA( C * V , 2 1 ) ; N e w l O D a y H i g h = H i g h > = HHV( H i g h , N e w l O D a y L o w = L o w <= LLV( Low, 10 Filter
=
Liquidity
AddColumn( AddColumn(
tjf
'".,Examples
>=
10
10 );
day
•3־
low
);
1000000;
NewlODayHigh, "10 Day H i g h 1 . 0, ; )״ NewlODaylow, "10 Day Low", 1 . 0 );
S e n d to automatic analysis window
30 Minutes to Useful Results
73
5. Using the Editor's File pull-down menu, select Save As. 6. The Save In directory should already be Custom. If it is not, navigate to: C:\Program Files\AmiBroker\Formulas\Custom. 7. For the File Name, type Example5.afl. 8. Click Save. (This works even if you are using an unregistered version of AmiBroker.)
Any time you want to modify or edit this program: 1. Use the Formula Editor's File menu, select Open. 2. Choose Example5.afl. 3. Click Open. EXPLORATION
Next, use Example5.afl as an Exploration. 1.
Using the Analysis pull-down menu, select Automatic Analysis. [ & AmiBroker - [AA - ALCOA INC - Daily] 1 m Ejte |
םa
Edit 9
view ט
Insert
m <
FQrrnat
Symbol o
Analysis | Tools
• » <£cf !
Window
Ht
Quick Review... Automate Analysis... Commentary... Formula Editor...
' *v AFL Code Wizard
א
74
Introduction to AmiBroker
In the Formula File area: (In this example, the program you want to use is already loaded, so the next few steps are not necessary. But, you need to know how to load an afl program into Automatic Analysis. These steps show how to load whatever program you want to use. We will re-load Example5.afl.) 1. Click Pick. Automatic Analysis - Example1! afl ןC:\Program Files\AmiBroker\Formulas\Custom\Example5.afl
!
r^ni Ed! 1
Range
Apply 40
a
O ® ייsymbols
: O " quotations n
| (3) current symbol
.
| O
j (g> u s e filter
[_£j
! ® n last d a y s
'®s' quotations
Ofrom:
f l Run every: • Wait for backfill (RT only) f ~ l Sync chart on select Results
Ready
Navigate to the AmiBroker\Formulas\Custom directory. (You are probably already there, but use the usual techniques to move around in the directory structure.) 3. Select Example5.afl. 4. Click Open. 2.
:ggAlertlfTestafl ||g!ATC Trading Figure_17_l 1.afl My R e c e n t Documents
i§|! Liquidity, afl j Re lativeStrength. afl i^SimpleSystem l.afl [^SimpleSystem.afl
Desktop
m
My Documents
My Computer
E x a m p l e s afl My Network Places
Files of type•
AFL Files r afl) F l Open a s read-only
30 Minutes to Useful Results
75
As you can tell from the Formula File box, you now have Example5.afl loaded into Automatic Analysis. ummz
L Automatic Analysis - Example5.afl !
Formula file !C:\Program F1les\Am1Broker\Formulas\Custom\Example5.a
Range
O ® ייs y m b o l s
O oil quotations
־1 [ I
O ייlost quotations (5) u s e filter I
1
I Run every:
Define... j
j
5minj
<§)n last d a y s Qfrom: to;
• Wait for backfill (RTonly)
n
־
|
8/18/2008 : 8/18/2008
ן
1
Back Test
[
Report...
v I j
Q S y n c chart on s e l e c t
Scan
|
Pick ]( [
ייj ־י
I > I
Parameters
j
Ready
Explore
] ] j]"־
Optimize
ri־ Settings...
H I j
Close
Results j Ticker
Edit
ש Date/...
10 D a y High
10 D a y Low
.
A
Automatic Analysis is the screen from which you will run the formulabased analysis techniques. These are the quantitative techniques, as compared with the visual and graphical techniques of applying trendlines and looking for chart patterns. There are four major components of Automatic Analysis: •
Explore - used to search for conditions that are interesting, and produce reports with columns of data. For example, search for all instances of the stochastic oscillator being below 20 for two days. Compute and report the price change over the next three days.
•
Backtest - used to test a trading system using historical data. Backtests can be performed on individual stocks or on portfolios of stocks. You have complete control over the account size, how many positions are held at any time, how much to invest in each position, when to buy, and when to sell. The output is a report, a plot showing arrows at the the buy and sell points, and a plot of the account equity.
•
Optimize - used to select the best values for the parameters in the trading system. In a moving average crossover trading system, optimization could be used to select the best values for the lengths of the moving averages.
•
Scan - after the system has been designed and is ready to be traded, scan through the symbols that are in the universe of possible holdings to see if there are new buy or sell signals.
Introduction to AmiBroker
76
Depending on what instructions you have written in your afl program, you may be able to r u n exactly the same program in all of the Automatic Analysis components. Chapter 9, Analysis, goes into each of these in much more detail. For now, fill in just what is necessary to complete the Exploration. In the Apply to area: 1. Click use filter. 2. Click Define. A Filter settings dialog box will appear. 3. Click the Exclude tab. 4. Click Clear. 5. Click the Include tab. Click Clear again. 6. Using the Watchlist pull-down menu, select the Basic Materials watchlist. 7. Click OK.
Formula tile i C:\Program FilesVAmiBroker\Formulas\Custom\Example5.afl Apply to |
O all symbols
i
Q current symbol Define...
* )®ךu s e filter
5min
Market:
• Wait for backfill (RT only)
Group:
חS y n c chart on select
Sector:
Results Ticker
Industry: Date/...
10 D a y Hit
Watch list: Favourites: Indexes:
Ready
:Basic Materials
30 Minutes to Useful Results
77
In the Range area: 1. Click n last days. 2. For n=, enter 2. L Automatic Analysis - Example5.afl Formula
file_
_
i C:\Program Files\AmiBrokeAFormulas\Custom\Example5.efl Range
Apply to
1
O all quotations
all symbols O current
O י׳las! quotations
(5) u s e filter
n last d a y s Qfrom
[~l Run every: • Wait for backfill (RT only)
•EZ
8/16/2008
V
8/1 a/2008
V
חSync chart on select
[ |
Scan
] [
Back Test >| | Report.
r]
Explore Optimize
j !ך*־
F i ! 1 ' ־
ו
h I 1
|
Parameters ] j
Settings...
j
Class
Results
ש
| Ticker
Date/...
10 D a y High
10 D a y Low
;Ready
1.
Click Explore. L. Automatic Analysis - Example5.afl Formula file
] 0
jC:\Program Files\AmiBroker\Formulas\Custom\Example5.afl
|
Apply to
Range
Q a l l symbols
O all quotations
[
O current symbol ®usefilter
O חlast quotations
| Back Test
[ Define..
| Run every:
<§) n last d a y s O
51
•
Wait for backfill (RT only)
•
S y n c chart on select
f r o m
: : ! ! !
Dote/
AA AA DD DD IP IP XOM XOM
8/30/2007 8/31/2007 8/30/2007 8/31/2007 8/30/2007 8/31/2007 8/30/2007 8/31/2007
Report...
:( ]־י ~| ך
Qptimize^ File Settings."
₪
Results Ticker
I 8/18/2008
Explor^^ [
10 D a y High
10 D a y Low
0 0 0 0 0 1 1 1
0 0 0 0 0 0 0 0
N u m b e r of rows: 8
The results of the Exploration appear in the Results window. IP reached a new 10 day high on 8/31/2007 (the last day of data), and XOM reached a new high the final day and the day before. Exit AmiBroker.
Introduction to AmiBroker
78
EXAMPLE 6 - RUN A SINGLE STOCK BACKTEST
In this example, you will use the Formula Editor to write the AFL code for a simple trading system, run the code as a Backtest on the historical data of one stock, review the results, plot the Buy and Sell arrows, plot the Equity Curve. Start AmiBroker. Using the Automatic Analysis pull-down menu, select the Formula Editor. The Formula Editor will open, ready to accept your new AFL program. Type it in so it matches this one: £1 [C:\Program Files\AmiBroker\Formulas\Custom\Exam... I File
Edit
loot
tjolp
םa y . m 4 ft! © «
Example6A
// // // //
ExamplefiA. A trading crossover Buy when t
f/ // // // //
c r o s s e s u p t h r o u g h t h e s l o w e r mov average. S e l l when t h e f a s t e r moving avera c r o s s e s down t h r o u g h t h e s l o w e r moving average.
FastMA =
MA(
SlowMA =
MA(
Buy Sell
Cross( =
Cross(
afl system based on the of two moving a v e r a g e s . he f a s t e r moving averag
C,
5
C,
) ;
20
);
FastMA, SlowMA,
SlowMA FastMA
); );
Ln 11, Col 1
Save it in the Custom directory as Example6A.afl. In setting up Automatic Analysis, you need to load the file you want processed. Example 5 showed one way to do that. Here is another - a shortcut that coordinates Formula Editor with Automatic Analysis. Formula Editor has a toolbar. The rightmost icon in the toolbar is an exclamation point. If you hover your mouse over it, the tooltip says Analysis. When you click that icon, the file that is open in Formula Editor is loaded into Automatic Analysis and Automatic Analysis is opened. This makes for an easy cycle of editing and analyzing. After the edit, click the Analysis icon and go directly on with the analysis.
30 Minutes to Useful Results 96 L [C:\Program FilesVAmiBroker\Formulas\Custom\Exam... j_ Elfe
Edit
D < H // // 11 // // // // // /'/
tools
Help
& Mt.:B
n £* j 6xample6A
Example6A. a f l A t r a d i n g system based on the c r o s s o v e r of two moving averages. Buy when t h e f a s t e r m o v i n g a v e r a g e crosses up through the slower movin average. S e l l when t h e f a s t e r moving a v e r a g e c r o s s e s down t h r o u g h t h e s l o w e r moving average.
FastMA =
MA(
C,
5
SlowMA =
MA(
C,
20
Buy Sell
=
Cross( =
); );
FastMA,
Cross(
SlowMA
SlowMA,
FastMA
); );
S e n d to automatic analysis window
BACKTEST
In the Formula file area, load Example6A.afl. Make CAT, Caterpillar Corporation, the active symbol and display it the chart window with daily bars. To run the backtest: 1. In the Apply to area, click current symbol. 2. In the Range area, click all quotations. 3. Click Backtest (ignore the pull-down menu for now). i Automatic Analysis - Example6A.afl F o r m u l a file
••
C:\Program FiIes\AmiBroke 1\F0rmulas\Custom\ExampIe6A.afI Apply to
Range
O oil s y m b o l s
®״ &ח
— c u r r e n t symbol Q u s e f i l t e r ^ ^ n D e f i "
r-^f000'^
6
|
•
Wait for backfill ( R T only)
•
S y n c chart on s e l e c t
'otions
quotations
O חlost d a y s
r5 m m"י:
^Jt*fRun every:
quo
lsst
O from tc
Results ! Ticker
j i Ready
Trade
Date
Price
Ex d a t e :
E x P...
%
Profit
% Profit
Shares
>
80
Introduction to AmiBroker
The trade-by-trade results appear in the Results window. fx Automatic Analysis - Example6A.afl C\־Prograrr1 r!l(?-v\Arn1Brol־:eAFt',1׳rriuh?s\,Custorn\E».am|:1l6׳BA.0fl A p p l y to
Range
O ® ייs y m b o l s
( £ ) all q u o t a t i o n s
!
( § ) current s y m b o l
I
o u s e filter
Explore J
Q n last q u o t a t i o n s 1
Def
] n
r~|.Run every:
Back Test
-
Report...
j"
0 n last d a y s :
Ofrom
7/ 1/2004
to
1/ 1/2007
• Wait for backfill ( R T only)
[
Optimize
Equity
|י
Settings...
חS y n c chart on s e l e c t
s
Results Ticker
Trade
CAT CAT CAT CAT CAT CAT CAT CAT CAT CAT CAT CAT CAT CAT CAT CAT CAT CAT CAT CAT
Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long
Date
Phce
Ex. d a t e
10/29/2004 12/13/2004 2/4/2005 4/26/2005 5/5/2005 7/13/2005 9/1/2005 11/4/2005 1/4/2006 3/17/2006 4/6/2006 5/4/2006 6/21/2006 a/2/2006 9/6/2006 10/5/2006 11/17/2006 1/29/2007 3/22/2007 7/12/2007
39.38 4596 4514 43.85 4434 4927 56.46 53.34 59.03 76.23 75 65 77.74 71.48 70.09 68.49 67.6 60 6 3 61 18 65 98 83.74
12/9/2004 1/6/2005 3/22/2005 5/2/2005 6/29/2005 8/22/2005 10/4/2005 12/20/2005 3/10/2006 3/31/2006 4/27/2006 5/17/2006 7/13/2006 8/11/2006 9/12/2006 10/23/2006 12/18/2006 3/1/2007 6/29/2007 7/26/2007
Ex. P... 44 73 45 76 46.52 43.62 47 69 54.35 57 29 56 51 70.95 71.81 74 04 74 88 68 75 66.4 64.54 60.12 61 61 63.36 77 97 7829
% chg
Profit
% Profit
Sht
13.59% -0 44% 3 06% -0.52% 756% 10.31% 1.47% 5.94% 20.19% -580% -2.13% -3.68% -3.82% -5 2 6 % -5 7 7 % -11.07% 1 62% 3.56% 18.17% -6 5 1 %
1.358 56 -4943 345 74 -61 13 87594 1.285.69 20221 829.50 2,985.97 -1.030.52 -356.32 -602 84 -602.81 -799.20 -829.41 -1.499.53 194 81 436 40 2.304 89 -975.49
13.59% -0.44% 306% -052% 756% 10 31% 1.47% 5.94% 2019% -5.80% -2.13% -3.68% -3.82% -5.26% -5.77% -11 0 7 % 1 62% 356% 18.17% -6.51%
253. 24־. 250. 265 261 253 24:
;(20 rows) Profit - 4 0 1 3 02 (40.13%). C A R - 12 01 %. M a x S y s D D - -6922.14 (-37.04%). CAR/MDD
32
261 250 23: 221 210 220 216. 209 200 198 200 19! 178
0 ־. # winners = 10 (E
In addition to the trade־by־trade results, there are three ways you might like to review the results ־the report, buy and sell arrows, and equity curve. Each will be discussed in turn. REPORT
1.
Click Report. fx Automatic Analysis - Example6A.afl F o r m u l a file | C:\Program Files\AmiBroker\Formulas\Custom\Example6A.afl Apply to j
Range
O all s y m b o l s
Scan
I (*)allquotations
® c u r r e n t symbol
|
O u s e filter
| 0 rt last clays
O
Qfrom:
P I Run e v e r y :
to: I
• Wait for backfill ( R T only)
j
last q u o t a t i o n s ־״
1
; 7/ 1/2004 1/
[
1/2007
[
[1 ־־־S y n c chart on s e l e c t
Back Test
j י
B e p ^ * ־1 Eguity Parameters
־1
Explore Optimize
Trade
1 CAT CAT CAT CAT
Long Long Long Long
Date
Price
Ex. d a t e
10/29/2004 12/13/2004 2/4/2005 4/26/2005
39 38 45 96 4514
12/9/2004 1/6/2005 3/22/2005 5/2/2005
43.85
Ex. P . 44 73 45 76 46.52 4362
.
File
|׳
Settings
j
Close
Results ; Ticker
| י
%chg
Profit
% Profit
13 5 9 % -0.44% 3.06% -0.52%
1.358 56 -49.43 345 74 -61.13
13 5 9 % -0 4 4 % 3 06% -0 5 2 %
ם Sht
253׳ 24:: 250 265:
30 Minutes to Useful Results
81
The report gives results summarized by all trades, long trades, short trades; all trades, winning trades, losing trades; and a series of overall fitness metrics, and risk and reward statistics. jjjjHI
I Example6A - Backtest Report - HtmlView File
View y
Help
m
t
Statistics | Charts | Trades | Formula | Settings | Symbols Statistics AH t r a d e s
Long t r a d e s
Short trades
Initial capital
10000.00
10000.00
10000.00
Ending capital
14013.02
14013.02
10000.00
Net Profit
4013.02
4013.02
0.00
Net Profit %
40.13 %
40.13 %
0.00%
Exposure %
58.06 %
58.06 %
0.00 %
Net Risk Adjusted Return %
69.12%
69.12 %
N/A
Annual Return %
12.01 %
12.01 %
0.00 %
Risk Adjusted Return %
20.68 %
20.68 %
N/A
Afltrades
20
20 (100.00 %)
0 (0.00 % )
Avg. Profrt/Loss
200.65
200.65
N/A
Avg. Profit/Loss %
2.02 %
2.02%
N/A
22.80
22.80
N/A
10 (50.00 %)
10 (50.00 %}
0 (0.00 %}
Total Profit
10819.71
10819.71
0.00
Avg. Profit
1081.97
1081.97
N/A
8.55 %
8.55%
N/A
34.40
34.40
N/A
5
5
0
2985.97
2985.97
0.00
Avg. Bars Held Winners
Avg. Profit % Avg. Bars Held Max. Consecutive Largest win * bars in largest win
46
46
0
10 (50.00 %)
10 (50.00 %)
0 (0.00 % )
Total Loss
־6806.68
-6806.68
0.00
Avg. Loss
-680.67
-680.67
N/A
Avg. Loss %
-4.50 %
-4.50 %
N/A
11.20
11.20
N/A
Losers
Avg. Bars Held Max. Consecutive Largest loss * bars in largest loss
7
7
0
-1499.53
-1499.53
0.00
13
13
0
Max. trade drawdown
־2121.00
-2121.00
0.00
Max. trade % drawdown
־15.27%
־15.27 %
0.00%
Max. system drawdown
-6922.14
־6922.14
0.00
Max. system % drawdown
-37.04 %
-37.04 %
0.00%
Recovery Factor
0.58
0.58
N/A
CAR/MaxDD
0.32
0.32
N/A
RAR/MaxDD
0.56
0.56
N/A
Profit Factor
1.59
1.59
N/A
Payoff Ratio
1.59
1.59
N/A
1754.93
1754.93
0.00
Standard Error Risk-Reward Ratio
0.59
0.59
N/A
17.85
17.85
0.00
Ulcer Performance Index
0.37
0.37
N/A
Sharpe Ratio of trades
0.65
0.65
0.00
0.0185
0.0185
-l.#IND
Ulcer Index
K-Ratio
Introduction to AmiBroker
82
B U Y A N D SELL A R R O W S
In order to see the green buy arrows and red sell arrows: 1. Right-click in the top pane of the chart window - the pane with the price series. A context menu will open. 2. Left-click Parameters. 4 AmiBroker - [CAT - CATERPILLAR INC - Daily]
A parameter dialog box will open. 1. Click the Axes & Grid tab. 2. Scroll down until you find Show trading arrows. Click in the area to the right until it is set to Yes. 3. Click OK. Properties of: Price P a r a m e t e r s j Axes & Grid י Show % values Levels Format
0 ־D e c i m a l (auto)
\ B Miscellaneous S h o w trading a r r o w s W r a p title i|
Vert, q u o t e m a r k e r
No Show
־1
30 Minutes to Useful Results
83
Return to the Results window. 1. Right-click any row in the results table. A context menu will open. 2. Left-click Show arrows for actual trades. Lx Automatic Analysis - Exampie6A.afl F o r m u l a file C:\Program Files\AmiBroket\FDrmulas\Custom\Example6A.afl A p p l y to
Range
O a"
( * ) all q u o t a t i o n s
symbols
( • ) current s y m b o l O u s e filter I
O I
De<
n
O חlast d a y s Ofrom
Run e v e r y
• Waitforbacktill
Scan | flack Test
last q u o t a t i o n s
7/ 1/2004 i 1/ 1/2007
(RTonly)
[
Beport
|
Eauity
Explore
File
Parameters
j |
Settings..
|
Close
|
ש
Results Ticker CAT CAT CAT CAT CAT CAT CAT CAT CAT CAT CAT CAT i~A־T
Trade Long Long Long Long Long Long Long Long Long Long Long Long
| ־J
Optimize
*i!
|
Q S y n c ctiart on s e l e c t
[ -j I
Ex. d a t e 2 ןj 4,
s h o w current trade arrows
7,
Add all results to w a t c h list.
'
Ex. P.
S h o w a r r o w s for all r a w signals
Add selectEd results to watch list...
^
Replace watch list with the results...
^
Replace w a t c h list with selected results.. ;
c:
Clear results list Copy
% chg
•׳. Prow She -49.43 an » -61 נ י 875 94 1.285.69 202 21 829.50 2.985 97 -1.030.52 -356 32 -602.84 -602.81
-0.44% ׳•*׳ -0.52% 7 56% 10.31% 1.47% 5.94% 20.19% -580% -2.13% - 3 6B% -3.82% -ש
24:j asnj 265 261. 253 } 24: 261J 250 23: 221. 210. 220J
84
Introduction to AmiBroker
Move the Automatic Analysis window out of the way. You will see the green upward-pointing arrows at the bars where Buy signals occurred and red downward-pointing arrows at the bars where the sell signals occurred. & AmiBroker - [CAT - CATERPILLAR INC - Daily] File
Edit
View
Insert
Fgrmat s
x
D Symbols
9 x
Sy mho Is | Layou tes 3 All # # # # # # # # # # 0 # #
Symbol O '
Analysis O II -
! 0 0 Is
Window
־-AT
; CAT (Daily) x CAT - Daily 4/18/2007 Open 67.8282. Hi 69.2658. Lo 67.8282, Close
fi
נכץ׳1 AA AXP BA C CAT DD DIS EK GE GM HD HON
Interpretation Interpretation ׳,־
Help
1
י :,->.J
Date: 4/18/2007 Price and moving averages: CAT(CATERPILLAR INC) has closed above its Short time moving average, Short time moving average is currently above mid-time, AND above long time moving averages. The relationship between price and moving averages is: bullish in short-term, and bullish in mid-long term.
A r r o w s at buy a n d sell p o i n t s
1
Feb
14 i i For Help, press F1
'Mar H !
, Apr ! ץS h e e t 1
1 'May Jun Qui Sheet 2 ^ Sheet 3 ^ Sheet 4 \ Sheet 5 \ s*
NYSE, Group 1, Capital Goods, Constr, 8. Ac f Data
30 Minutes to Useful Results
85
EQUITY CURVE
1. In Formula Editor, open Example6A.afl. 2. Add the lines necessary to make it like the code shown below. 3. Save it as Example6B.afl. 4. Click the Apply indicator icon in the toolbar. . [C:\Program Files\AmiBroker\Formulas\Custom\Examp... £110
Edit
D G? U // // // // // // // // //
Tools #
Help
jL
Efe ©
*י
Exarnple6B
ExampleoB.afl A •trading system based on t h e c r o s s o v e r of two moving averages. Buy when t h e f a s t e r moving a v e r a g e c r o s s e s up through the slower moving average. S e l l when t h e f a s t e r moving a v e r a g e c r o s s e s down t h r o u g h t h e s l o w e r moving average.
FastMA =
MA(
C,
5
SlowMA =
MA(
C,
20
Buy
=
Cross( =
Sell Plot(
C,
"C",
); );
FastMA,
Cross(
SlowMA
SlowMA,
);
FastMA
colorBlack,
e = Equity(); P l o t ( e, " e q u i t y " ,
|Apply indicator
);
styleCandle
colorGreen,
);
stylel-ine
|
styleOvmScale
);
S a v e a n d display c h a r t
A new pane will appear as the bottom pane in the chart window. It contains two plots ־the price series as black candlesticks, and the equity for an account that started at $10,000 as a green line. The final equity for CAT is $14,013. C A T - C = 6 8 . 7 8 , equity = 13,221 87
A • A ft
׳״ry
/
i ,**.f ״
t
\
»5 0 70 מ
נ
65 I - ׳
r w 1
־F e b 1 Mar
^pr
•••••׳ 1
!vfay
1
Jun
Qui
׳Aug"
86
Introduction to AmiBroker
Using the Symbols tabbed menu, click on any symbol. Symbols j Layouts I Layers j C h a r t s j a
ם
All $ 1 נכר׳ י
•
c \ J
* C|BOEING co|
4>
Du
# DIS 4 EK # GE • GM 0 HD F HON * HPQ
Note that the bottom pane will show the new price chart and the equity curve that results from applying that trading system to that symbol. It is not necessary to click Backtest ־when the new symbol is selected, all of the indicators in all of the panes are recomputed and re-displayed, including the result of applying the trading system. The final equity is in the green box in the right-hand margin.
>
B A - C = 93 2 1 , e q u i t y = 1 2 . 9 1 2 17
, //VS,,/1"' ws^f• Feb
n®r
104.0
p g g i
W f•־
°
0 5 / 96 0 92.0 80.0
f h 1
108.0
1
Apr
Exit AmiBroker.
׳Miy
Tun
Qui
1
Aug
30 Minutes to Useful Results
87
EXAMPLE 7 - RUN A PORTFOLIO BACKTEST
This example will apply a trading system to a portfolio and view the portfolio equity. Start AmiBroker. Using the Formula Editor: 1. Open Example6A.afl. 2. Change it to make it agree with the program shown below. 3. Save the new program as Example7A.afl. '
L. [C:YProgram Files\AmiBroker\Formulas\Custom\Examp.. I
Eile
Edit
D t f U
Ioob
Help
#
151
*י
«
Example7A
* ׳>״9 ״
// // // // if //
Example7A.afl A t r a d i n g system based on the c r o s s o v e r of two moving a v e r a g e s . Buy when t h e f a s t e r moving a v e r a g e c r o s s e s up through the slower moving average.
// // /'/
S e l l when t h e f a s t e r c r o s s e s down t h r o u g h moving average.
// //
This version for use with
Buy = Cross( Sell = Cross(
!
moving average the slower
adds m u l t i p l e a portfolio.
SetOption( "MaxOpenPositions", P o s i t i o n S i z e = 2 / •10;־ F a s t M A = M A ( C, S l o w M A = M A ( C,
Is 1
positions
2
);
5 ) ; 20 );
FastMA,
S l o w M A );
SlowMA,
S a v e the file
FastMA
);
Ln 12, Col 1
4. Click the Analysis icon. ExampleTA is loaded into Automatic Analysis as the Formula File. 5. In the Apply to area, check Use filter. 6. Click Define. 7. Clear all fields. 8. On the Include tab, Watchlist entry, select Basic Materials. 9. Click OK. 10. In the Range area, check All quotations.
Introduction to AmiBroker 11. Click the Settings button. The Backtester Settings dialog box will open. 12. Click the Report tab. 1) Click Trade list. 2) Click OK. Backtester settings General: T r a d e s
Stops ; Report Portfolio :'Walk-Forward i
Reporting Result list shows:
@ T r a d e I1f?t
״׳
O Detailecnog O Summary Risk-free rate for Sharpe ratio:
j5
Distribution charts spacing (%)
j5
0 MAE/MFE distribution charts (Professional Edition only) חGenerate detailed reports for each symbol in individual backtest (slow) |v1 Include trade list in the report @ Warn before running time-consuming optimizations
13. Click Backtest. The Results window shows trades. , Automatic Analysis - Example7A.afl Formula file ; i C:\Program Files\AmiBrokeAFormulas\Custom\Example7A afl
O a " symbols
;
Pick ] | Edit
Range
Apply to Q current symbol : ®usefilter
Scan
! {«> all quotations O
, |
Def
n
O n last d a y s Qfrom:
n Run e v e i y
to:
• Wait for backfill (RT only)
Explore
Back Test :]־׳י
׳Qst quotations
Beport..
: 7/ 1/2004
יי
]
Optimize
j"]
File
|׳י
V
Eguity
v
*
[ 1/ 1/2007
Parameters
Fl Sync chart on select
'I
Settings...
|
Close
Results
|
ש
Ticker
Trade
AA DD XOM AA XOM AA AA DD DD XOM XOM XOM IP IP XOM IP IP XOM IP AA AA
Leng Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long
Date 11/1/2004 11/2/2004 1/18/2005 3/17/2005 1/7/2005 4/11/2005 5/9/2005 5/6/2005 5/20/2005 5/31/2005 7/8/2005 7/25/2006 7/20/2005 8/11/2005 8/11/2005 8/22/2005 9/7/2005 9/1/2005 10/27/2005 10/24/2005 1/27/2006
Price
Ex. date
31 87 41.09 50.22 30.9 59.62 30.51 28.88 46.42 45 73 55.35 58.5 59.03 31.64 30.91 60 32 30 74 30 91 61 04 27 91 2368 31.15
!1/3/2004 1/7/2005 3/15/2005 3/23/2005 4/13/2005 4/15/2005 5/11/2005 5/13/2005 5/25/2005 6/30/2005 7/18/2005 8/4/2005 8/9/2005 8/15/2005 8/19/2005 8/23/2005 9/22/2005 10/4/2005 1/5/2006 1/17/2006 2/21/2006
Ex. Pr.. 3127 4545 59.13 29.75 57 96 28.68 27 95 45.02 45 49 566 57 27 57,63 30.9 30 68 58 21 29 92 29 96 59 92 33.39 2898 38 2
%chg
Profit
% Profit -1 88% 10.61% 17 74% -3.72% -2.78% -600% -3.22% -3.02% -0.52% 2.26% -2.10% -2.37% -2.34% -0.74% -3.50% -2.67% -3 07% -1.83% 19 63% 22 38% -3 05%
-1:8854 " -94 13 530.51 10 61% 17 74% 925 81 -3.72% -211.43 -155.24 -2 78% -6.00% -332.05 -171 69 ־3.22% -3.02% - ו60 80 -0.52% -27,1 ו ו16.35 2,26% -2.10% -ו09.55 -2.37% -120.61 -2.34% -120.57 -074% -37 46 -176 12 -3,50% -2.67% -131.45 -3 07% -148.55 -1 83% -89.22 19 63% 931 32 22 38% 1.061.64 -3 05% -175.05
>
e ;(38 rows) Profit = 1439.75 ( 1 '4.40%), CAR 4,62% ־. MaxSysDD 1 9 . 1 8 % - ) 2 2 4 1 . 9 0 - ־
St 151 12 10 18: 93 18־ 18. 11• 11: S3 89 86. 16: 16: 83. 161 151 79. 16! 21 1B•
)
. CAR/MDD 0.24 ־. *winners 2 ) 1 0 ־E
89
30 Minutes to Useful Results
Looking carefully at the results, there are times when there are two positions, times when there is only one, and times when there are none. When processing a portfolio backtest, AmiBroker starts out with 100% cash and knows the maximum number of positions it can hold simultaneously (2 in this case). The code in ExampleTA tells AmiBroker to divide the available f u n d s into two, giving each 50%. The trading system is applied to each of the ticker symbols in the watchlist. When the first (in chronological order) buy signal occurs, one position is taken and as many shares as possible are purchased with 50% of the funds. Whenever there is a sell signal for that symbol, those shares are sold and the cash made available for another purchase. In the mean time, when the next buy signal occurs, the remaining 50% is used to buy shares in that stock. The buying and selling, using f u n d s and returning funds, continues for the length of time specified. Plotting the portfolio equity gives a graphic view of the process. 1.
Click the Equity button. ״£, Automatic Analysis - Example7A.afl C:\Program Fi!es\AmiBroker\Formu!as\Custom\Example7A.afl Apply to
Range
O
© a l l quotations
symbols
O current symbol ©usefilter
1
Scan
] | [
O n last quotations I Defini
O n last d a y s Ofon1׳:
[ I ] Run eveiy •
Wait for backfill (RT only)
•
Sync chart on select
Beport... 7/ 1/2004
Eflui
1/ 1/2007
"
Explore
K
AA DD ; XOM AA
Trade Long Long Long Long
^Ptek
-~־־״־mfr
File Settings
₪
Results Ticker
*־,j
Qptimize
Date
Price
Ex. date
11/1/2004 11/2/2004 1/18/2005 3/17/2005
"31 87 41.09 50.22 30.9
11/3/2004 1/7/2005 3/15/2005 3/23/2005
Ex. Pr... 31.27 45.45 59.13 29.75
% chij
Profit
-1.88% 10.61% 17.74% -3.72%
-94 13 53051 925 B1
% Profit
St
4 88% 151 10.61 So 12 1 ?74% 10 72% 3• 43 211 ־IB
A new pane opens at the bottom of the chart window. The two positions are evident, one above the other. When a stock position is held, the plot is blue. When cash is held, the plot is green. The chart shows the ebb and flow of positions - sometimes two, other times one, other times none. The dark brown area at the bottom shows the drawdown. For this run, the final equity was $11,439. The d r a w d o w n when the test period ended was $831. Drawdown is the decrease in equity from the highest high equity value.
90
Introduction to AmiBroker i W - 1 •.••• -
B.000
-
4.000
-
2.000
-
0
Final Equity
B B E 1
Drawdown Blue Securities Held
Green Cash Held
To read the report for this run, click the Report button. This run was made allowing a maximum of two simultaneous positions. The code can be modified to study the effect of allowing fewer or more positions. Using Formula Editor, modify Example7A to agree with the code that follows, and save it as Example7B.afl.
File
Edit
• (£ U
l o o Is #
*
Help % §§
*י
Example7B
׳ נ־&• ׳>״
// // if // // //
Bxample7B.afl A ־trading system c r o s s o v e r of two Buy w h e n t h e f a s t crosses up throug average.
// // /./ // /I
S e l l when t h e f a s t e r moving a v e r a g e c r o s s e s down t h r o u g h t h e s l o w e r moving average. This version adds m u l t i p l e p o s i t i o n s for use with a p o r t f o l i o .
•
_ ׳
ba3ed on the moving averages. e r moving average h t h e slower moving
N u m P o s = 3; SetOption( "MaxOpenPositions", PositionSize = - 1 0 0 / NumPos;
NumPos
) ;
F a s t M A = M A ( C, 5 ) ; S l o w M A = MA( C , 20 ); Buy Sell
־ =
Cross( Cross(
FastMA, SlowMA,
SlowMA FastMA
Print t h e active d o c u m e n t
); );
Ln 1, Col 1
Now just change the value of NumPos, click Analysis, and look at the equity chart. Exit AmiBroker.
30 Minutes to Useful Results
91
EXAMPLE 8 - OPTIMIZE A TRADING SYSTEM
In this example, the moving average crossover system introduced in Example 6 is studied in more detail. The values for the two moving average lengths were guesses. In this example they will be chosen through an optimization process. An optimization is an organized search, done in such a way that a large number of alternative values of parameters are considered. For each set of values, the trading system is tested. The report produced at the conclusion of the optimization lists the profitability and other statistics for each of the sets of values tested. The hope is that the best set of values will continue to be profitable in the future. Start AmiBroker. Using Formula Editor: 1. Open Example6B.afl. 2. Change it to agree with the code shown below. 3. Save the new program as Example8A.afl. L [C:\Program Files\AmiBroker\Formulas\Custom\Examp... Eile
Edit
D 0? y // // // // // // // // // //
Ioote
Help
#
m
*י
׳
:
ExampleBA
׳
Example8A.afl A trading system based on t h e c r o s s o v e r of two moving averages. Buy when t h e f a s t e r moving a v e r a g e c r o s s e s up through the slower moving average. S e l l when t h e f a s t e r moving a v e r a g e c r o s s e s down t h r o u g h t h e s l o w e r moving average. Parameters are introduced.
FastMALength SlowMALength
= =
FastMA =
MA(
C,
FastMALength
MA(
C,
SlowftALength
jSlowMA Buy
=
Sell p l o t (
=
Cross( =
Cross(
C,
"C",
5; 20;
FastMA, SlowMA,
); );
FastMA
colorBlack,
e = Equity(); P l o t ( e, "equity",
Formula n a m e
SlowMA
);
);
styleCandle
colorGreen,
);
styleXine
|
styleOwnScale
);
Introduction to AmiBroker
92
Compare the statements that were changed. Example6B:
FastMA = MA ( C, 5 );
Example8A:
FastMALength = 5; FastMA = MA ( C, FastMALength);
A numeric value is assigned to a variable FastMALength, then that variable is used to calculate the moving average. Computationally, Example6B and Example8A are the same. But using the variable gives some flexibility. OPTIMIZE FUNCTION
AmiBroker has a built-in function, Optimize, that has this format: V = Optimize ("Name", Default, Initial, Final, Increment);
• •
V is a variable that will be assigned one value at a time, and a series of values as the search takes place. Name is the name of the variable as it will appear in the reports.
•
Default is the value that will be assigned to V if the run is only a backtest (or Explore or Scan), not an optimization.
•
Initial is the first value to be tested during the optimization.
•
Final is the last value to be tested.
•
Increment is the step taken from one iteration to the next.
For e x a m p l e , V = Optimize ("Length", 5, 1, 20, 1);
•
If only a backtest is being run, V will be assigned the value 5.
•
If an optimization is being run, V will be assigned 20 values, one for each optimization pass. The first will be 1, then 2, then 3, and so forth, with the final value assigned to V being 20. From 1 to 20 in steps of 1.
EXAMPLE8B.AFL
Using the Formula Editor, modify Example8A so that it agrees with the code shown below. Then save it as Example8B.afl.
30 Minutes to Useful Results
L
93
[C:\Program Files\AmiBrakertFormulas\Cu5tom\Examp... Q Eite
Edit
D G? U
loots m
Help
$
fe®
*״ז י
ExampleBB
Ky>®~
// // // // // //
Example8B.afl A t r a d i n g system based on the c r o s s o v e r of two moving a v e r a g e s . Buy when t h e f a s t e r m o v i n g a v e r a g e c r o s s e s up through t h e slower moving average.
// // // //
S e l l when t h e f a s t e r c r o s s e s down t h r o u g h moving average.
// // //
This v e r s i o n can be optimized to f i n d t h e b e s t v a l u e s f o r t h e two moving average l e n g t h s .
FastMALength = SlowMALength =
Optimize( Optimize(
"FMA", " 3MA",
=
MA(
C,
FastMALength
SlowMA
=
MA(
C,
SlowMALength
Sell
=
Cross( =
Cross(
P l o t ( C,
"C",
FastMA,
SlowMA
SlowMA,
e = Equity(); P l o t ( e, " e q u i t y " ,
5, 1, 2 0 , 2,
31, 30,
2 2
); );
.
—
styleOwnScale
);
); ); );
FastMA
colorBlack,
׳-
moving average the slower
FastMA
Buy
f
);
styleCandle
colorGreen,
);
styleLine
|
Redo the previously u n d o n e action
Note there are two Optimize statements. The first will assign values from 1 to 31 in steps of 2 to the variable n a m e d FastMALength. The second will assign values of 2 through 30 by steps of 2 to the variable named SlowMALength. There are 16 different values in the first statement, 15 different values in the second statement. To do the complete search, FastMALength will be set to 1, then all 15 values of SlowMALength tried; following that, FastMALength will be set to 3, then all 15 values of SlowMALength will be tried; and so forth until all 240 combinations have been tested. To perform the Optimization test, in Automatic Analysis: 1. In Formula File, load Example8B.afl. 2. Load CAT as the current ticker symbol. 3. In Apply to, click Current symbol. 4. In Range, set the From date to 7/1/2004. 5. In Range, set the To Date to 1/1/2007. 6. Click Optimize.
94
Introduction to AmiBroker ix Automatic Analysis - Example8B.afl
I
Scon
[ Back T e s t 1
|
•
Parameters
Pick
||
j
Explore
-־j I
Edit
Qptirmje
•1 |
File 1
• | |
Settings
|
Close
| 'j'1
₪ 20 1 36 1 37 38 21 19 70 5 33 2 17 23 10 <
Net % Protit
Exposure %
CAB
RAR
111.54 79.87 7646 7393 71.72 71.40 6885 64 73 5986 5576 5336 51 99 51 61 51 39 49.55
42 02 42.88 41 85 5 3 34 41.34 4014 40 48 4425 39.79 41 34 55.06 47.17 5540 39.79 37.56
3843 29 02 27 95 2715 26 45 2635 2553 24.19 2258 21 21 2039 19.93 19 79 19.72 19 08
9144 67 68 66.78 50 90 63 98 65.64 63 06 54 66 56 74 51 30 37.04 4224 35.73 49.56 50.80
11,15420 7.987.36 7.615 61 7.392.98 7.17218 7.139.61 6.88511 6.47293 5.985 59 5,57568 5.33569 5.199 32 5.160.86 5.139.33 4.95463
Max Trad -1.B20 09 -2.965.61 -1,199 83 -2.881.61 -2.054.86 -2,096.10 -2.31475 -1.10318 -1.781.53 -2.603.77 -61951 -2.178.75 -838.41 -2,09872 -1.987.13
Wax. Trad -9 5 0 - ו4.52 - ו ו34 -14.52 -14 94 -13.20 -1138 -9.50 -13 20 -1176 -5 05 -1152 -5.39 -14 25 -143B
Max S y s -3.06452 -2.965.64 -2,551.97 -3.259.96 -2.391.20 -2,096.10 -2.11510 -2.62496 -1 781.53 -3.183 61 -1.628 39 -2.478 75 -1,736.33 -2.096 72 -1,987.13
liiill
:Number of rows: 240
The Results window will fill with 240 rows, one for each combination of FastMALength and SlowMALength. Sort the results according to some measure of the goodness that you like. In general, the measure of goodness is called a fitness function or an objective function. There are several fitness functions in the resuits that both reward equity growth and penalize drawdown. These include CAR/MDD, RAR/MDD, RRR, Ulcer Performance Index, and Kratio. The results, sorted by RAR/MDD are shown in the next image.
30 Minutes to Useful Results
95
Click the header of any column to sort by that column. IT
L Automatic Analysis - ExampleSB.afI 1
Formula tile
1 [ Pick]
C:\Program Files\AmiBroker\Formu!as\Custom\Example8B afl Apply to
Range
0 B.I! symbols
O all quotations Q n last quotations
(*)current symbol O u s e ti Iter
I
Define...
Q R u n every:
|
5minl
O n last d a y s
| 2
""
® f r o m : 1/2004 /7 ן
V:
Q Edit
|
Explore
| gack Test
| ־״־
Optimize
1 ׳.
-
1 1
V
| V 1/2007
to:
Q Wait for backfill (RT only)
Scan
I
j י
I
:..,...
ה־ר־ LU
Recovery
-15.44 -14.52 -14.61 -13.20 -15.01 -15.23 -12.43 -11 56 -17 43 -9.77 -13 20 -13 20 -13.23 -14.3B -14.25
|
File
LI Sync chart on select
< Sys.
mm
CAFVMDD
3 64 2.69 3 41 3.36 2 85 3.00 2 80 2.99 2 99 3.28 3.04 2.62 2.51 2 49 2.45
RAR/MDD
2 49 200 1.80 1.71 170 1.74 ו33 1.60 1.60 2.09 1.44 1.30 1.32 1.33 1 38
^ ' ־P r o f i t Factor 5 92 466 449 4 30 4 20 4 20 408 4 04 3 83 379 3.61 3.60 354 3.53 348
Payoff Ratio
3 44 233 3 42 2.24 2 76 2.71 6 85 2.25 2.23 1.72 2.20 3.40 3.13 2.88 2.94
1.35 0.73 0 98 1.19 0.99 090 2.16 1.35 0.98 2.05 1.30 1.13 0 87 075 1.08
Standard ..
RF
1.023 79 1 015 34 51873 558 75 584 17 600.27 34785 564 45 677 65 687 43 404 85 531.09 451 23 585.82 604 84
<
י
4 : 4 5. 3. 4 4 4 4 4 3. 5. 3. 4 י 3. v >
J
Number of rows: 240
Scrol I over to the far right and note the values of FMA and SMA that correspond to the best fitness value. They are FMA = 7, SMA = 4. L Automatic Analysis - ExampleSB.afI :C:\ProqramFiles\Arn1Broker\Formulas\Custom\Example8B.efl Apply to
Range
O ®1 יsymbols
O a " quotations
,
current symbol (5)
O * O u s e filter [ j
Run every: [~| L • Wait for backfill (RT only)
n
j j Pick j [ Edit [ Explore Optimize
lost quotations
O חlast days ®from:
7/ 1/2004
I
Settings...
j
V 1/2007
• Sync chart on select
B
Results
I52 :66 !76 .91 40 :85 11 !24 !86 69 :06 :73 :94 91 :11 <
t of losers
% of Losers
L Tot. Loss
L. Avg. Loss
13 12 6 17 9 9 6 15 18 31 19 5 5 6 7
28 26 24 00 22 22 34 69 26 47 25.00 24 00 37 50 30 51 54 39 37 25 26,00 21 74 20.69 26.92
-4.575.35 -6.019.73 -2.948 70 -4.820.87 -3.909 51 -4,183.41 -760.38 -3.82514 -6.227 60 -7,385.95 -4,137.23 -1,031.02 -2.118.45 -2,635.39 -2,652.17
-351 95 -501.64 -491 45 -283.58 -434.39 -464.82 -126.73 -255.01 -345.98 -238.26 -217 75 -366.20 -423 69 -439.23 -37888
L Avg %... -2 20 -300 -3 31 -2.10 -3.02 -3.27 -1 00 -2 14 -2.52 -1 77 -1.82 -299 -3,32 -3.58 -2 90
L Avg. Ba. 8.38 10.25 16.33 7,29 12.22 13.22 5.33 9.33 5 72 4.06 6 42 16.80 19.60 18.67 17.57
FMA
SMA
7 7 11 11 9 9 27 13 7 1 9 21 19 19 13
2 6 10 4 6 26 12 6 6 8 4 4 2 4
>
A
v
, .
Number of rows: 240
Return to Example8B.afl and enter those values as the defaults in the two optimize statements.
Introduction to AmiBroker
96
, [C:\Program File5\AmiBroker\Formulas\Custam\Examp... ]_ File ם
Edit
^
ט
Tools
•
Help «o c*
i
Example8B
/! 11 // /./ //
Example8B.afl A t r a d i n g system based on t h e c r o s s o v e r of two moving averages. Buy when t h e f a s t e r moving a v e r a g e c r o s s e s up t h r o u g h t h e slower moving
// // //
S e l l when t h e f a s t e r c r o s 3 e s down t h r o u g h moving average.
// Ii //
This version can be optimized to find the b e s t v a l u e s f o r t h e two moving average lengths.
FastMALength = SlowMALength =
moving average the slower
Optimize( Optimize(
"FMA", "3MA",
FastMA
=
MA(
C,
FastMALength
SlowMA
=
MA(
C,
SlowMALength
Buy =
Cross( =
Sell Plot(
FastMA,
Cross( "C",
C,
31, 30,
2 2
); );
); );
FastMA
colorBlack,
e = Equity(); P l o t ( e, "equity",
1, 2,
);
SlowMA
SlowMA,
7, 4,
);
styleCandle
colorGreen,
);
styleLlne
|
styleOvmScale
);
1. Save the program. 2. In Formula Editor, click Apply Indicator icon. Look at the chart showing the equity curve. It shows a final equity of $21,154. C A T - C = 75 77, e q u i t y = 2 1 , 1 5 4 . 2 0
אv Vs1 " י A> r'1 '״W
7
Feb
׳Mar
85.0 BOO I E
<
15 0
"
V
70 0 65.0 1
Apr
' May
'Jun
יJul
'Aug
But the right side of the equity curve is flat. That is because the optimization was r u n up to 1/1/2007. The data from 1/1/2007 through the end of the file, 8/31/2007, was saved to do an out-of-sample test. 1. In Automatic Analysis, set the To Date to 8/31/2007. 2. Click Backtest. The final equity is $22,447. C A T - C = 75 77. equity = 2 2 , 4 4 7 . 3 3
-•F\tjf\ f ^ A,All
.w יJ/׳׳
J
m l j N
ן
y!׳y
*5 0 70 0
' ..L
•
"
1
.; י יJ , " - ' ! . « •
65 0
li/V
|t 111 ,
Mar
,
Apr
'May
TJun
Qui
'Aug
30 Minutes to Useful Results
97
The system was optimized using in-sample data from 7/1/2004 through 1/1/2007. Those results are good. In-sample results are always good. We do not stop playing with the trading system until they are good. The real test of a trading system is how well it performs on data that was not used during the optimization - the out-of-sample data. The resuits from this test are encouraging - the out-of-sample test was profitable. AN
IMPORTANT OBSERVATION
Take another look at the results of the optimization. The length of the "fast" moving average is 7; the length of the "slow" moving average is 4. Traditional technical analysis tells us that we should buy when the fast moving average crosses up through the slow moving average. The resuit of the optimization run in this example suggests that is not always the case. In this example, we are buying when the fast moving average crosses down through the slow moving average. Buy when the fast moving average is rising is a trend following system - buy when recent prices are rising faster than older prices. This works well for very stable price series, such as high-yield bond funds. Buy when the fast moving average is falling is a mean reversion system - buy when prices are weak, anticipating that they will return to their mean. This works well for very active price series. Exit AmiBroker.
Introduction to AmiBroker
98
EXAMPLE 9 - PERFORM W A L K FORWARD VALIDATION
In this example, you will use the walk-forward technique to validate a trading system. In applying technical analysis, several assumptions are made: •
Patterns exist that precede profitable trading opportunities.
•
The trading system can detect those patterns.
•
The patterns persist beyond the in-sample period used to develop the system for a long enough time that we can trade profitably.
When any trading system is developed, the process involves searching through a set of data, looking for the patterns. The data that is searched is called the in-sample data. The results obtained by using the system on the in-sample data are always good. The system developer does not stop looking until the results are good. The proof that a trading system has found a recognizable pattern, and has not just mined the data, is performance on data that has never been used to develop the system. That never-before-used data is called the out-of-sample data. The walk forward process consists of several iterations of: 1. Developing a system over a set of in-sample data. 2. Testing the profitability over a set of out-of-sample data. 3. Stepping forward in time to a new set of in-sample data and a new set of out-of-sample data. The combined results of all the out-of-sample data are used to decide whether the system recognizes profit potential or not. There are two major advantages to using walk forward testing: •
The in-sample period can be relatively short, giving the system an opportunity to stay in synchronization with the underlying market.
•
Each transition from in-sample to out-of-sample gives the developer one more data point. Eventually, when trades are made with real money, the decision to trade is a decision to trust the in-sample results. The greater the number of steps in the walk forward process, the greater the number of transitions from insample to out-of-sample the developer has seen. Each successful transition raises confidence that the system is a good one.
30 Minutes to Useful Results The following graphics might help understand the process.
The decision whether to trade the system or go back to the drawing board is made after reviewing all the out-of-sample results.
Decision — trade or return to development
Concatenated out-of-sarhple results
99
100
Introduction to AmiBroker
Start AmiBroker. Load CAT using daily data. Load Example8B.afl. No changes to the afl code are necessary. In Automatic Analysis: 1.
Click Settings. L Automatic Analysis - ExampleSB.afl C : \ P r o g r a m FilesVAmiBroker\Formulas\Custom\Example8B.afl A p p l y to |
Range
O oil s y m b o l s
C a l l quotations
!
( » ) current s y m b o l
j
O
u s e
'''
i
t e r
0 n lost q u o t a t i o n s
i O
n
lost d a y s
®from:
Run every:
־״r
[ Back Test
,
*[ י
j
u
7/ 1/2004
Settings..!
I 8/31/2007
• W a i t for backfill ( R T only)
,,-
Qptimize
©
חS y n c c h a r t on s e l e c t
B
Results No.
N e t Profit
N e t % Profit
Exposure %
CAR
RAR
Max. Trad...
Max. Trad..
Max.Sys..
Max S j
2. Click the Walk-Forward tab. 3. Click Easy mode. 4. Set Start date to 7/1/2004. 5. Set End date to 1/1/2005. 6. Set Last date to 7/1/2007. 7. Set Step to 6. 8. Use pull-down menu to select Months. Note that the in-sample and out-of-sample periods have been calculated and are listed in the window. 9. From the pull-down menu for Optimization target, select RAR/MDD. 10. Click OK.
101
30 Minutes to Useful Results Backtester settings General
Trades:! Stops
Report
- ( * ) E a s y m o d e (EOD)
Portfolio
Walk-Fotward ׳
O E a s y m o d e (intraday)
O Advanced mode
Back on Automatic Analysis: 1 Left-click the arrow next to Optimize to open the pull-down menu. 2.
Click Walk-Forward Optimization. , Automatic Analysis - ExampleSB.afl F o r m u l a file :C:\Program Files\AmiBroker\Formulas\Custom\Example8B.afl A p p l y to
Range
Q a l l symbols
O ®II q u o t a t i o n s
( i ) current s y m b o l O
u s e
; Define...
f"׳er
f~1 Run e v e r y :
5min
•
W a i t for backfill ( R T only)
•
S y n c chart on s e l e c t
O " last q u o t a t i o n s O חlast d a y s
j (S)from:
7/ 1/2004
V
8/31/2007
View 3D optimization g r a p h Old (v4.4) Optimizer
Results No.
N e t Profit
N e t % Profit
Exposure %
CAR: RAR
Max. Trad...
Max. Trad...
Max. S y s ..
The optimization runs will start. There will be six steps. Each in-sampie period is six months long. The first in-sample period starts 7/1/2004. The sixth in-sample period ends 7/1/2007. The out-of-sample periods are also six months long and each immediately follows an in-sample period. There are five full out-of-sample periods. The sixth out-of-sample period begins 7/1/2007 and ends with the end of the data on 8/31/2007. As the walk forward runs progress, pairs of lines are created and displayed in a tabbed window. The first line of each pair gives the results
Introduction to AmiBroker for the in-sample period. The second line gives the results for the associated out-of-sample period. y CAT
<1 P
i§ Walk F o r w a r d x :
Address file :///C :/Program%20Files/AmiBroker/WalkForward.htm ־יQ G O
Completed.
Mode
Begin
End
CAR
RAH
Max. S y s % D r a w d o w n
IS
7/1/2004
1/1/2005
189
456.77
4.57
3.75
15.52
413.85
-0.19
82.70
2205.33
25
24
oos
1/1/2005
7/1/2005
1
435.SO
4.3S
42.86
9.08
21.19
-8.87
1.02
2.39
25
24
IS
1/1/2005
7/1/2005
2
1394.11
13.94
46.03
30.49
66.24
-5.81
5.24
11.39
3
2
oos
7/1/2005
1/1/2006
1
2046.48
20.46
45.67
45.27
99.12
-9.06
S.00
10.94
3
2
IS
7/1/2005
1/1/2006
5
3170.10
31.70
35.43
73.71
208.04
-4.70
15.68
44.24
9
2
OOS
1/1/2006
7/1/2006
1
532.24
5.32
36.00
11.22
31.16
-14.76
0.76
2.11
9
2
IS
1/1/2006
7/1/2006
1
3400.91
34.01
54.40
82.26
151.22
-4.13
19.93
36.63
1
2
OOS
7/1/2006
1/1/2007
1
-1194.34
-11.94
45.24
־22.85
-50.50
-15.85
־1.44
־3.19
1
2
IS
7/1/2006
1/1/2007
19
1869.60
18.70
52.38
41.83
79.87
-5.03
8.33
15.89
5
4
OOS
1/1/2007
7/1/2007
1
517.73
5.18
41.94
10.97
26.16
-6.27
1.75
4.17
5
4
IS
1/1/2007
7/1/2007
159
64S. 06
6.4S
9.68
13.76
142.17
-1.03
13.42
138.64
29
20
OOS
7/1/2007
1/1/2008
1
־273.43
־2.73
34.09
-15.52
-45.52
-6.7S
-2.30
-6.74
29
20
NO. N e t Profit N e t % Profit E x p o s u r e %
CAR/MDD RAR/MDD
FMA SMA
Ignore the in-sample profitability. Add up the Net Profit from all the out-of-sample periods: $435 + 2046 +532 -1194 + 517 - 273 = $2063. $10,000 became $12063 in 2.666 years. The average percentage of time a position was held was 41%. The annual percentage return while in a position is 17.8%. All out-of-sample. Look at the values that the optimization chose for FMA and SMA. They are: 25/24,3/2,9/2,1/2,5/4, and 29/20. In five of the six periods, the system itself chose to be a mean reversion system. The one period it chose to be a trend following system was the period of its biggest out-of-sample loss. It appears that trend following using a moving average crossover to signal entries and exits does not work well for CAT, but mean reversion is promising. Because of the limited number of securities and the limited length of the historical data, the results achieved were not spectacular. When you have installed a more complete database, you will find systems and symbols that give better results than these. This is an example, not a ready־to-use trading system. Although the results of this example are reasonable there are many factors beyond those described that should be taken into consideration in system design, testing, and validation. Do Not trade this system without performing your own tests and validations. Exit AmiBroker.
30 Minutes to Useful Results
ו03
EXAMPLE 10 - SCAN FOR BUY AND SELL SIGNALS
In this example, you will use the Scan feature to check for buy or sell signals. Due to the limitations of the trial mode, it will be difficult to demonstrate realistic results of the Scan feature. Assume that Example8B is a validated trading system for all of the symbols in watchlist Basic Materials. Scan combines a trading system with a watchlist to give a report telling you what buy and sell signals were generated for the symbols in the watchlist. The period of time this report covers is under your control, but it is usually just one or two days. Start AmiBroker. Load IP using daily data. Load Example8B.afl. In Automatic Analysis: 1.
Use filter and select the Watchlist Basic Materials. L Automatic Analysis - ExampleSB.afl Formula file I C:\Program Files\AmiBrokeAFormulas\Custom\Example8B.afl Range O a l l quotations Q n l a s t quotations ״- J in]
O Run e v e i y
lOtom:
TT0i*backfili (RT only)
[
Beport...
[
Efluity
f
חSync chart on select Results
Parameters
!'1
File
;י
Settings... ]
Close ש
Ticker I DD I XOM
ן
Date Buy Buy
6/30/2007 B/30/2007 8/31/2007
Close 36.1500 181400 85.7300
2. Set n last days with n = 2. 3. Click Scan. The results appear in the results window. AA and DD had Buy signals on 8/30; XOM had a Buy signal on 8/31. Exit AmiBroker.
Introduction to AmiBroker
Section II
Charting
Introduction to AmiBroker
Chapter 4
AmiBroker Chart Structure
In the earlier portion of this book, rather loose reference was made to databases, layouts, windows, charts, panes, drawing objects, and so forth. To fully understand AmiBroker, it is necessary to understand the structure into which these components fit. •
The top level component is a Layout.
•
Each Layout is associated with a single Database when that layout is active.
•
Each Layout consists of one or more Windows.
•
Each Window has data for one Symbol.
•
Each Window displays with one Periodicity.
•
Each Window contains one or more Sheets.
•
Each Sheet contains one or more Panes.
•
Each Pane contains one or more Chart, Formula, or Tool.
You can have as many layouts as you wish. But only one layout can be active (open) at a time.
107
1 108
Introduction to AmiBroker
Layouts can be local or global. Local layouts are associated only with a specific database. Each local layout is stored in the database directory it is associated with, in the file named broker.workspace. Global layouts can be used with more than one database. Global layouts are stored in the AmiBroker\Layouts subdirectory. WINDOW LAYOUTS
A window layout (that is, an AmiBroker window layout) is a complete set of one or more windows. Each window displays data for its own symbol, has its own display interval, its own size on the monitor, its o w n set of charts, its o w n panes, and its own charts and formulas. The image below shows a 2-window layout. Each window has a different stock and a different set of indicator panes. •wtgg gite Edit yiew insert Format Symbol Analysis Iools window Help םa s o 8 mJ: Layouts
••>
•
0 ׳
X
sS
o a .
-
6 ,־v • ״. & \
AA (Daily) X
v •
/ / o .
־CM (Ddilyi
XOM - Daily 4/7/2008 Open 89 32. Hi 89 95, Lo 88 69, Close 88 92 (0 2%) Vol 19.586,200 MA(Ciose,15) = 86 57, Mid MA(C:lose,45) = 86 04,
׳2008 'February XOM - RSI( 15) = 57 37 .
1
March
A
,
L
D08 V |! Opens currently selected window layout
\
,
1
May
Jun
א1 ו/־
H a A
'׳I ,
1
April
,
February March April / ;» '•ייet ? ^ Sheet 3 ^ Sheet 4 ^ Sheet_
V v
?8.67180
"Jul
,/1""י
,
May TJun S l ^ t 6 S i ^ e e t 7 ^ She^ 8 y • s -1 NYSE, Common Stocks, Materials, Mrwng-N •< ׳QPEnd of Day
You can have an unlimited number of single or multiple-window layouts. Each can be a custom set up; they do not need to share anything. Switch between them by double clicking on the layout's name in the layouts tab. The active layout can be automatically saved whenever the database is switched or AmiBroker is exited. To set this, use the Tools menu > Pref-
AmiBroker Chart Structure
109
erences > Miscellaneous. In the Auto-save area, Check the Layouts box. Information saved in layouts include: window sizes and positions, bar interval, symbol, chart sheets, panes, charts, formulas. Preferences Charting
Colors
Editor
Date
Intraday
Miscellaneous
Alerts
AFL
;; Currencies
Display options PI Price d a t a tooltips
D a t a tip auto-hide timeout (sec): !
f~1 Show interpretation in tooltips I
| Add full n a m e to ticker in ticker box
f | Add full n a m e to ticker in tree @ Full-name tooltips in symbol tree [
5j
T h o u s a n d separator:
| Display chart timing ( a d v a n c e d )
U s e alternate row colors Decimal p l a c e s in RT quote window: Decimal p l a c e s in chart titles/tools:
@
o 12
Arial, 9 pt
Axis Font: Additional settings
Auto-arrange charts @
• No minimum size for resizing dialogs
Auto-tile multiple chart windows Q
fH Display plugin activity I
Ask t o s a v e c h a n g e d d a t a
| Case-sensitive ticker symbols
When non-existing symbol is typed-in Auto-save @ Templates
P I Preferences
0 Layouts
Apply
You can switch between multiple windows (within a layout) using either the Window menu and selecting the desired window from the list at the bottom of the menu, or using the new MDI tabs. ymbol
Analysis
0 0 ־
8 0. ,
100 Is
Help
QQQQ
* QQQQ (Daily) x
צQQQQ (Weekly)
QQ.QQ. - POWERSHARES QQQ TRUST-UNIT SER 1 - Daily
To begin with, a single window layout will probably be sufficient. You will need a multi-window layout if you want to : •
Display charts for more than one ticker symbol
•
Display charts of different periodicity
•
Display charts showing different range of bars.
While not necessary, you may want a multi-window layout in order to be able to float a window and move it to a second monitor. Most of the concepts and techniques that are described in the pages that follow are applied to the active pane and are independent of the layout structure.
Introduction to AmiBroker
Sheet Sheet 1 2 1
1
Sheet N 1
Sheet Sheet 1 2
Sheet N
Pane 1
| Pane 1
| Pane 1
| Pane 1 | | Pane 1
| Pane 1 |
Pane 2
| Pane 2
| Pane 2
| Pane 2 \ | Pane 2
| Pane 2 |
Pane 3
| Pane 3
| Pane 3 |
1 Pane 3 1 | Pane 3
| Pane 3 |
| Pane N |
| Pane N | | Pane N |
| Pane N |
Pane IM
| Pane N
AmiBroker Chart Structure 128 BLOCK D I A G R A M
On the left is a block diagram view of layouts, their components, and their relationship to databases. One layout is shown. You can have as many layouts as you want. Only one layout can be open and active at a time. To make another active: • Save the current database • Open the new database • Select the layout you want to use Everything shown on the block diagram will change to reflect the new layout / database combination - all windows, sheets, panes, tools, watchlists. To reiterate: • •
The top level component of the AmiBroker structure is the layout. Each layout can be associated with any number of databases (there is no limit). Only one database is open and active when a layout is active.
•
Some layouts ־local layouts - are associated with only one database. Other layouts - global layouts - are associated with two or more databases, but only one at a time.
•
Each layout consists of one or more windows. Only one window can be active at a time. All of the windows associated with the layout are listed in the windows menu. If you choose a multi-window layout, all the windows will be visible; otherwise only the active window is visible. You can change back and forth from window to window as you wish.
•
Each window displays data for one symbol at a time.
•
Each window displays data in one time frame at a time.
•
Each window contains one or more sheets (there is no limit). Only one sheet can be active at a time. To make another sheet active, click its tab. All sheets display the same range of dates.
•
Each sheet contains one or more panes (there is no limit).
•
Each pane contains one or more displays of price data, manually applied tools, or formulas. Only one pane can be active at a time. To make another pane active, click anywhere in it.
Introduction to AmiBroker
Chapter 5
The GUI — Graphical User Interface
113
1 114
Introduction to AmiBroker
W h e n y o u start A m i B r o k e r u s i n g a n e n d - o f - d a y database, h e r e i s w h a t you see.
Pull-down
Menus ־File, Edit, View, Insert, Format, Symbol, Analysis, Tools, Window, Help
Tabbed
Xfoolbars - Standard
Menus -
\
\
N
י
Ticker \
Tools \
Format
!
t•
A n . ׳B r o k e r - (SPY - SPDR VR-UNIT SER 1 - Daily]
Symbols^^® a
— * •—׳
י-
..*י״׳
/
.<>,
Toolbars -
j SPY -Daily 7/24/2008 Open 128.35. Hi 128.41, Lo 125 16, Close 12551 (-2.1%) Vol 248,608,896 MA(CI0se,15) = 125 24, Mid MA(CI0se.45) = 131
A
Layers׳ Charts׳
'560! A
^יע
m
\
™ ־r ׳
-Draw
v
Chart Area 'Apr 'May 'Jun 'Jul 'Aug 'Sep SPY - MACD( 12,26) = -1.77. Signal( 12,26.9) = -2 44
'Oct
'Nov
'Dec
'2008
'Feb
'Mar
'Apr
'May
'Jun
'Jul
-Fibonacci
Notepad Interpretation
״,-« 7 ־3.0;^: !
SPY - RSI( 15) = 42 45
tSr
! Date: 7/24/2008
m
! The RSI, written by נ. Welles Wilder n 1978, can be used In ! several different ways to ; analyze a chart, : Tops and Bottoms: For Help, press F1
4
1
1 Apr 'May Jun t y: slifi't 1 .
1
Jul
1
Aug
1
Sep
'Oct
1
Nov
1
Dec
1
2008
1
Feb •
TMar ׳Apr - <
׳May
Amex, ETF, Financal, Fin-ETF
Status Bar׳
FIGURE 5 . 1 - A M I B R O K E R C H A R T W I N D O W
r
Jun
1
Jul
Graphical User Interface
Chart Title,
וו5
Price / Data Tooltip
צSPY (Daily) X j ! SPY - Daily 7/24/2008 Open 120.35, Hi 128.41. Lo 125.16, Close 125.51 (-2.1%) Vol 248.608,896 MA(CI0se.15) = 125 24 J^Tid MA(CI0se,45) = 131
Date: 2/25/2008 Value: 155.125 Open: 135.54 High: 137,65 Low: 134.78 Close: 137.33 Volume: 190023200 Open Int.: 0 Close = 137.33 MA (Close, 15) = 135.109 Mid MA (Close,45) = 138.621 Long MA (Close, 100) = 144.8 BBTop (C lose, 15,2) = 137.821 BBBot(C lose, 15,2) = 132.396 Volume() = 1.90023e+008
Price Chart, with volume
,
Apr
1
May
1
J1S
Qui
TOg
'Sep
^jct
'Nov
Tiec
'2008
fFeb
OSsr
׳Apr
Htfiay
B >\Price
Axis
•un
TjuT
Value Axis
y
H [\ S h e e t 1 ^ S h e e t 2 \ Sheet 3 '). Sheet 4 \ Sheet 5 \ Sheet 6 '). Sheet 7 \ Sheet 8 / ׳s - 1
Chart Sheets ^
Date / Time Axis'
Scroll Bar
FIGURE 5 . 2 - M A I N C H A R T I N G A R E A , E N D - O F - D A Y DATABASE
Introduction to AmiBroker
1 116 CHARTS
This chapter describes the AmiBroker Chart Window and the Chart Area, and the tools that are available. This is a beginners guide to charting. If an AmiBroker feature is missing from this book, it is either a new feature or an advanced topic. For more information, please see the AmiBroker User's Guide. The AmiBroker charting engine uses object-oriented manipulation of all drawings, and standard Windows techniques. You can move, resize, cut, copy, paste, and delete all charts and drawing objects with ease. DISPLAY A N E W PRICE SERIES
Use one of these methods: Use the Symbols Tabbed menu. Find the symbol you want in any of the categories of which it is a member. (It will always be a member of "All".) Click the Ticker symbol. All panes in the active layout will be loaded with the data for the new symbol, and all indicators will be recalculated using that data.
Layouts j Layers j Charts• j Symbols : i C l All B b t•: ־.
LJ C3 CJ •_j L_J
Markets Groups Sectors Watch lists Favourites SPY
!£: L3 Indexes
Using the Symbol pulldown menu, select Find. The Symbol Finder will open. Fill in either the ticker or the name. Select the ticker you want, click OK. The new symbol will be loaded. י
Analysis ! 8 .
p
Tools
־־
Window
Help
ENTER.
•
_
Usm2 the Ticker toolbar v(see rigure 5.1)," O fc>
T T •
!1
\1•י־ד׳
ו
ו
1ו
/
״־־ד
־ז
select all of the letters in the old ticker, type in the new ticker erasing the old one, press The new symbol will be loaded.
For more details, see Chart Pane Context Menu, page 122.
Graphical User Interface 5 ו ו DEFAULT C H A R T
Figure 5.2 shows a typical default chart window. Every chart w i n d o w is a component of a Layout. You can have as many layouts as you wish. Figure 5.1 shows the chart window of a typical default layout. You have a great deal of control over what is included in your default charts and how they appear. Use the Tools > Preference menu to set your preferences. These two figures will be used as illustrations for this section. This layout consists of a single window with eight chart sheets. Each window can have as many sheets as you wish. Using the tabs along the bottom edge, you can select which sheet you want to be active. In Figure 5.2, Sheet 1 is the active sheet and contains three panes. A sheet can have as many panes as yoti wish. The upper pane contains the price in candlestick format, a simple moving average of the closing price with a short period, a simple moving average with a medium period, a simple moving average with a long period, a set of Bollinger bands, volume bars, an exponential moving average of the close with a short period, an exponential moving average with a long period, and interpretation code. The middle pane contains the MACD indicator, an exponential moving average of the MACD indicator, and interpretation code. The bottom pane contains the RSI indicator, an exponential moving average of the RSI indicator, and interpretation code. A C T I V E PANE
At any time, you wi 11 have one active layout, of which one window is active, of which one sheet is active, of which one pane is active. Saying that a chart or pane is active is the same as saying it is selected or has the focus. PRICE AND VALUE A X I S
At the right-hand side of each pane, there is a vertical axis. (See Figure 5.2.) It displays the price (if a price series is being plotted) or value (if an indicator or formula is being plotted). The colored boxes give the values of the last data point visible on the chart. They are color-coded to correspond with the color of the line that is used to plot them. Unless you turn it off in the Tools > Preferences menu, a box containing
Introduction to AmiBroker Tooltip (see Figure 5.2) will display information about that bar of that pane that is at the point of your cursor whenever the cursor is paused over any pane. D A T E AND T I M E A X I S
At the bottom of some panes is a date and time axis. (See Figure 5.2.) You have control over whether the dates are displayed, but they are always there and are used to synchronize the data displayed in each of the panes. To toggle the display of the dates on and off, see Chart Pane Context Menu, page 122. SCROLL T H R O U G H DATES
There are several ways to scroll (to change the date range of the data that appears in the pane): •
At the bottom, right-hand side you will see a scroll bar. (See Figure 5.2.) Clicking and holding the scroll bar, then moving your mouse, you will make different date ranges of data visible in the pane.
•
You can use the right and left arrows next to the scroll bar. Each click of an arrow scrolls by a single bar.
•
If your mouse has a wheel, rolling the wheel scrolls the window.
As the display scrolls, every pane of every sheet will be redrawn so that the date range displayed is the same in every one of them. Every pane will be rescaled so the data is displayed as efficiently as possible. (Just rescaled; all the calculation was done for all the dates before the panes were displayed the first time.) PANE SIZE
As you move your mouse slowly up and down, you will cross pane boundaries. When the cursor changes from an ordinary , ^ -Jui־ arrow to a set of two parallel lines with small arrows pointing up and down, you can click and drag the boundary to change the sizes of the panes separated by that boundary.
Graphical User Interface 5 ו ו ZOOM
There are several ways to Zoom (increase or decrease the number of bars of data being displayed). •
Use the icons in the View toolbar. (See Figure 5.1.)
•
Using the View menu, select Zoom, then In or Out.
•
View > Zoom > All will display all the quotes in your history file. View > Zoom > Range will zoom to the range you have set. (See Mark a Range, page 120.)
• •
Hold the Control key while rolling the wheel on your mouse. When you have the amount of zoom you want, click the mouse anywhere in the chart.
BAR INTERVAL (PERIODICITY)
There are several ways to change periodicity. •
Use the icons in the View toolbar. (See Figure 5.1.)
•
Using the View menu, select Daily, Weekly, or Monthly. If you have an intraday database, you can select any bar size that is the same as or longer than your base time interval. If the intraday bar size you want is not on the menu, you can define it using the Tools menu > Preferences > Intra-day.
When you change the periodicity for any pane, all panes on all sheets for the active chart window will be changed and synchronized. If you want to have different periodicities for the same symbol, open a second chart window, creating a multi-window layout. (Use the File menu > New > Chart.) The new chart will open with the same ticker. Change the periodicity as you wish. You can tile the windows so that you can see, for example, both the daily chart and weekly chart. You can save the tiled view as a new layout. Whenever you open that layout, the daily and weekly display will be loaded.
Introduction to AmiBroker SELECT A Q U O T E
Move your mouse to the date you are interested in and click anywhere in any pane. A vertical line will appear through all panes at the bar you selected. If that is close to, but not exactly the one you wanted, use the Keyboard Left Arrow and Right Arrow (the cursor keys) to move one bar at a time. The chart title will display the date (and time) of the selected bar. M A R K A RANGE
Set a bar range by either: •
Double-click one end of the range, then double-click the other end of the range.
•
Select the desired bar for the left (older) end. Press F12. Select the desired bar for the right end. Press S H I F T + F 1 2 .
The left end of the range will be marked with a vertical line and a small green bar at the bottom of that line. The right end will be marked by a vertical line and a small red bar at the bottom of that line. Once the range is established, double-clicking outside the range will extend the range in that direction. Double-clicking inside the range will move the closer end to the bar being double-clicked. Date ranges can be zoomed-to by using the View menu > Zoom. Date ranges can also be referenced from an AFL program using the functions BeginValue and EndValue. REMOVE THE RANGE MARKERS
Either: •
Press
•
Double-click either the left or right vertical line.
CTRL+F12.
Graphical
User
Interface
5
ו
ו
A D D A NEW PANE
Use one of these methods:
Layouts I Layers j Charts j Symbol;׳, j: m LJ Averages & C J Bands !» CJ Basic Charts /
Open Interest (futures)
/
s
s
/ Price (all in o n e ) / Price (foreign) /
Relative P e r f o r m a n c e
f
Volume
/
Volume (color)
/
Volume At Price
; 1 C j Custom LJ Equity CJ Include CJ Indicators ; £ £ j QTS Book Ss LJ QTS Book Code b: LJ Systems
To have that pane display a price series or a formula, use the Charts Tabbed menu, select the formula you want, right click it, click Insert. If you are planning to apply an indicator to the price series, select Price as the formula. Follow the first method, but double-click the formula you want (instead of right-click and insert). Alternatively, you can insert a new blank pane and then fill it later. Use the File menu > New > Pane. The new pane will appear as the bottom pane of the active window and will have no price or formula in it.
CLOSE A N Y PANE
Use one of these methods: •
|
•
Click on the pane you want to close to make it the active pane. Right-click, bringing up the context menu, choose Pane, then Close. Using the View menu, choose Pane, then Close.
•
Using the View Toolbar: 1. Click in the pane you want to close. 2 ;־. Click the Close Pane icon.
REORDER THE PANES
Right-click on the pane you want to move either up or down. From the context menu, choose Pane, then Move Up or Move Down. The pane will exchange places with the one next to it. To move a pane several locations, repeat the operation.
Introduction to AmiBroker
1 122
C H A R T PANE C O N T E X T M E N U j
Parameters Edit formula
x
Close Intraday
Weekly view
m
Monthly view Pane Template Symbol Link | Interval Link : Delete Indicator Delete study
This context menu shows up when you right-click over any pane. It gives a great deal of control over the items shown in the pane. The parameters submenu gives access to the formulabased indicators. The properties submenu gives access to the manually placed indicators. The content and level of detail of both these menus depends on what indicators have been placed in the pane.
Delete all studies Properties...
Edit Formula opens the AFL Formula Editor with the formula loaded.
PARAMETERS
•
Parameters - Opens the Parameters dialog allowing you to modify parameters of indicators, as well as settings of colors, styles, scaling, and axes. Depending on the charts, formulas, and studies applied to the pane, there could be a lot of options. A pane was created and the formula Price (all in one) inserted into it. The context menu shown here is for that formula.
5וו
Graphical User Interface .........
r
Parameters j Axes •
Grid |
1
B
:
.
ך
B Axes •
Black
Scaling
Style Tooltip shows
.
Parameters Axes & Grid !
Price Color
.
Properties of: Price
Properties of: Price
All V a l u e s
MA
j
Price field
Close
Periods
15
Color
•
• Red
Style Q Mid MA
fl
Maximum
A
Show d a t e axis?
Yes
Grid Show middle lines
Yes
Show upper/lower limits
No
Show % v a l u e s
No
Close
Levels
AS
Format
Color
•
Style | B Long MA
47148769 Linear
Periods
•
34.412201
Type
Price field
Blue
Automatic
Minimum
0 - Decimal (auto)
Miscellaneous Show trading arrows
Yes
W r a p title
No
Price field
Close
Vert, quote marker
Periods
100
File
Color
H Bright green
Chart
Show
path
ft
Fo rm ul as\D rag-dro p\Pr
ID
ft
1023
Style j • BBands Price field
Close
Periods
15
Width
2
Color
B Light grey
Style B Volume Color Style
CiLavender Histogram Thick NoLabel 0...
: פPrice Interpretation Short Time MA
MA(CI0se,15)
Mid Time MA
Mid MA(CI0se,45)
Long Time MA
Long MA(CI0se,100)
BBTop
BBT0p(CI0se.15,2)
BBBottom
BBB0t(CI0se,15,2)
I
j Reset all I
I
OK
®I
J
Scroll your mouse up and down and note that most of these parameters can be changed. Some of the more important ones are described here. The parameters over which you have control are the parameters of the code in the formula. This is closely related to the Edit Formula menu described on page 127.
to AmiBroker Colors Every color parameter will have a pull-down menu that brings up a color chart. You can select the color you want by clicking the sample. If you w a n t more control over the color, click More and this w i n d o w will open, allowing complete specification of the color.
Parameters j Axes 8 Gri פPrice Color Style
mm
Tooltip shows • MA
• «
mm
m
m;ר
Price field Periods Color
1 ׳i ־t ׳: •
* • •
•
•
r.
• • • ס
••:״::
a •
»
Style | פMid MA Priro fiolH
More...
Periods B MA Price field Periods Color
Close !י5 •
ד-~־
Periods Color Style
־z z i J j
פMA Price field
־־־־
Red
Style
Close fT5 • Red
Click in the middle of the field to the right of the word Periods. The box allowing you to change the length of the period will open to show a slider in the right portion and a text box in the left portion. Either use your mouse to slide the slider, or select and change the numeric value to the length you want. Watch the plot of the line change as you change the value of the period.
5וו
Graphical User Interface Price Field Parameters : Axes 8 Grid: •
Price Color
•
Black
Style Tooltip shows
All Values
0 MA Price field
Close
Periods
15
Color
•
Red
Style • Mid MA Price field
Close
Periods
45
Color
•
W h e n the Price Field subm e n u is d r o p p e d d o w n (in this case for the Long MA formula), it allows you to choose the field to take the m o v i n g average of. Choices include everything that w a s placed in the p a n e before Long MA.
Blue
Style \ B Long MA Price field
Close
Periods
Open High Low Close Average Volume Openlnt • Close MA(CI0se,15) Mid MA(CI0se,45)
Color Style B BBands Price field Periods Width Color Style פVolume Color
y
Style
Histogram Thick NoLabel 0.
Lavender
פPrice Interpretation Short Time MA
MA(CI0se,15)
Mid Time MA
Mid MA(CI0se,45)
Long Time MA
Long MA(CI0se,100)
BBTop
BBT0p(CI0se,15,2)
BBBottom
BBB0t(CI0se,15,2)
Compare by dropping down the Price Field of the formula MA or Mid MA. Since MA w a s placed before Mid MA, and Mid MA w a s placed before Long MA, any of Close, MA, or Mid MA can be used as the Price Field.
Axes and Grid Axes gives control over the vertical scale used for plotting. If you click on Scaling, it will switch f r o m automatic to custom. The locks will disappear f r o m the M i n i m u m and M a x i m u m fields, allowing you to set whatever range you wish. Parameters | Axes & Grid j
Parameters j Axes & Grid j Q Axes
פAxes
Scaling Minimum
1
Maximum
i
Automatic
Scaling
34.412201
Minimum
I Custom
$ ן
34.412201
47.148769
Maximum
Type
Linear
Type
Linear
Show d a t e axis?
Yes
Show d a t e axis?
Yes
47.148769
Type Linear alternates with Logarithmic. Show Date Axis is either Yes or No. Set this to Yes if you want to display the date and time axis as part of the pane.
Introduction to AmiBroker
1 126
Grid gives control of horizontal lines. Levels pull-down menu allows you to select automatic horizontal lines at some standard levels. The choices include levels that are often used to evaluate indicators, particularly oscillator-type.
Parameters ! Axes a Grid Automatic
Scaling Minimum
A
34.412201
Maximum
ft
47148769
Type
Linear
Show d a t e axis?
Yes
B Grid Show middle lines
Yes
Show upper/tower limits
No
Show % v a l u e s
No
Levels •
Format
•
0
Miscellaneous Show trading arrows
• •
10/90 20/80
W r a p title
•
30/70
• •
50 -100/+100
Vert, quote marker File path
A
Chart ID
a
Parameters J Axes & Grid j B Axes Scaling
Format pull-down menu allows you to change between decimal and fractional display of prices.
Automatic
Minimum
A
34.412201
Maximum
A
47.148769
Type
Linear
Show d a t e axis?
Yes
a Grid Show middle lines
Yes
Show upper/lower limits
No
Show % v a l u e s
No
Levels Format •
Miscellaneous Show trading arrows W r a p title Vert, quote marker File path
A
Chart ID
A
0 ־O e a m a l (auto) • 0 - Decimal (auto) 4-1/4ths 8-1/8ths 16-1/16ths 32-1/32ths 64 - 1/64ths 128-1/128ths 320 - 1/320ths
Parameters ! Axes a Grid •
Axes
j
Show Trading Arrows must be set to Yes to have the green buy and red sell arrows display on the chart in the pane.
Automatic
Scaling Minimum
A
Maximum
A
34.412201 47.148769
Type
Linear
Show d a t e axis?
Yes
פGrid Show middle lines
Yes
Show upper/lower limits
No
Show % v a l u e s
No
Levels Format פ
0 - Decimal (auto)
Miscellaneous Show trading arrows
Yes
W r a p title
No
Vert, quote marker
Show
File path
A
Formulas\Drag-drop\Pr...
Chart ID
A
1023
$
Graphical User Interface
5וו
EDIT FORMULA
•
Edit Formula - Opens the Formula Editor allowing you to view or modify the AFL code of indicator. The Formula Editor is described in detail in another section. But it is instructive to look at a portion of the code for the formula Price (all in one) that was used to illustrate the Parameters entry above, page 122 and following.
Elle
Edit
Iools
1 ? םu - m ׳:; ׳.
Help
Lfc ta
׳-:;...(;־
"MA"
־׳
: ״
F'rice (all חןo n e )
•01*
);
P = PararaField( ״Price Periods = Param( "Perio P l o t ( MA{ P , P e r i o d s ) , ParamColor( "Color", ParamStyle( "Style" ) : EKO ( ) ;
field", 1־ ); ds", 1 5 , 2 , ZOO, 1 ); !>!5S'AtJJ,T * J A M S ( ) , colarCyclo ), | styleHoRescale );
Insert Clipboard c o n t e n t s
(
•
Close - closes the chart pane.
•
Intraday ־Allows you to switch the periodicity or viewing time frame to one of the available intraday intervals.
•
Daily view - Switches the viewing interval to daily.
•
Weekly view - Switches the viewing interval to weekly.
•
Monthly view - Switches the viewing interval to monthly.
•
Pane
Pane
•
X
Qlose
IN
Arrange all Move Up Move DOWQ Maximize
Close - Closes chart pane Arrange all - Arranges all the panes to be equal height Move up - Moves the selected chart pane up (switches pane vertical order) Move d o w n - Moves the selected chart pane d o w n (switches pane vertical order) Maximize - Maximizes the selected pane so it fills entire screen Restore - Restores the selected pane to its previous size (after using maximize)
1 28
1
Template
Introduction to AmiBroker Template - The complete set of chart sheets, together with their names, panes, sizes, locations, formulas is called a template. Load - Loads a single-window chart * Load... template from the selected file Save... Load default Save - Saves a single-window chart temSave as default plate to the selected file Load default - Loads the default single window template Save as default - Saves the current single-window setup as the default template Symbol Link - Links two or more windows by symbol. When the symbol is changed in any one of these windows, it will change in all of them. Interval Link - Links two or more windows by display interval or periodicity. W h e n the interval is changed in any one of these windows, it will change in all of them. Delete indicator - Deletes one of the drag-and-drop indicator sections found in the code. A submenu will expand to list the indicators that can be deleted. Delete study - Deletes the selected manually drawn study, such as trend line or Fibonacci. Delete All studies - Deletes all the manually drawn studies.
Graphical User Interface
ו ו5
PROPERTIES
•
Properties - Displays properties of the manually d r a w n studles.
The chart shows a regression channel applied to a price series. Q Q Q Q - Daily 7/30/2000 Open 45.46, Hi 45.02, Lo 44 B8. Close 45 57 (0 5%)
V
1
,
2008
1
February
1
March
1
V • • ׳ ׳
,
April
May
Uun
'Jul
Select the Regression study (move the cursor over the middle line until it becomes a four-direction arrow), and right-click, bringing up the context menu, then click Properties. Properties
Properties
General ןRegression channel
i General j Regression channel j
Position:
Channel type
StartX:
I |/10/2008
(§) Raff channel
start v:
!42 ברכו
O Standard Error channel
EndX: EndV:
O Standard Deviation channel
5/14/2008
Width:
491783
|1
Lines Lock position
!>/] U s e common color and style
•
Show
Color
Style
0 Upper line
J J ^J
;Regu(ar
@ Lower line Thick line Dotted line
Study ID: Layer:
Left extend Default layer
Right extend
Study ID
[ Regular
•
• • • Help
|
| U s e as default
Extension factor:
Help
The General tab lets you refine the starting and ending point, place the study on a specific Layer (see Layers, page 163), extend the study to the left and right, change the color and thickness of the lines.
Introduction to AmiBroker
The Regression tab lets you control the type of the regression, the width of the channels, the color and thickness of the lines. It also lets you assign a study identifier to the upper and lower boundaries. The study identifier can be used to test for conditions such as prices moving above the upper boundary. PULL-DOWN
MENUS
Pull-down menus, also called drop-down menus, are menus of comm a n d s or options that appear when you select an item with a mouse. The item you select is generally at the top of the display screen, and the menu appears just below it, as if you had pulled it down. There are ten pull-down menus arranged across the top of the AmiBroker Chart Window (see Figure 5.1.)
Graphical User Interface 5 ו ו FILE M E N U
• File | Edit
yiew
Insert
Format
New Open...
• Ctrl+O
Qlose Open Qatabase... Save Database
y
Ctrl+S
Save As... m
Save All Database settings...
&
Import Wizard...
a
Import ASCII..,
m
Import MetaStock data...
m
Print...
a
Ctrl+P
Print Preview Print Setup.., Send chart via E־mail 1 QP End of Day 2 Data 3 IntraDay 4 DataAsDistributed E!
Analysis
•
Database...
m
Account
12 Default Chart D Blank Qhart a Blank Pane e
Save Database As... Save
Symbol
Web Research
Ic
New Database — Creates a new AmiBroker database, and launches the database settings window. Default Chart - Creates a new chart window, including all its sheets, using the default template. It's possible to select the symbols and time frame independently in each of the windows opened. Blank Chart - Creates a new completely blank chart window, including all its sheets. This is useful if you want to create a multi-window layout. This is important if you want to have indicators that have independent parameters from the other windows that you have created. (See Window Layouts, page 108.)
Blank Pane - Creates a new blank chart pane in the acfive sheet. Account - Creates a new Account Manager account. Web Research - Creates a new web research window. Information about the current symbol will be automatically loaded.
Introduction to AmiBroker •
Open - Opens an existing document (account, database or HTML file). You can pick the document type from "Files of type" combo in the Open > File selector window.
•
Close - Closes the current active document window.
•
Open Database - Allows you to open an existing AmiBroker database. Select the database folder and press OK.
•
Save Database - Saves the current database.
•
Save Database As - Saves the current database with a new name in a new folder.
•
Save - Saves the current document (account or HTML file).
•
Save As - Saves the current document with a new name.
•
Save All - Saves all documents currently open.
•
Database settings - Opens the database settings dialog that allows you to specify database parameters when setting up a database; or change your database parameters or intraday settings for an existing database.
•
Import Wizard ־Launches the 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
Graphical User Interface
ו ו5
predefined import formats. •
Import MetaStock data - Launches the Metastock importer window. Note: The Metastock importer should be used only if you want to import MS data to a native, local AmiBroker database once. If you want AmiBroker to read the Metastock database directly on a regular basis, set up your database with the MetaStock Plugin.
•
Print - Print the currently displayed charts.
•
Print Preview - Displays how the information will look when printed.
•
Print Setup - Opens the Print Setup dialog box.
•
Send chart via e-mail - AmiBroker creates a .png image of the currently displayed chart and uses your default mailing program (e.g. Outlook Express) to send the file as an attachment.
•
List of AmiBroker databases. Click on any database name to open it. • QP End of Day • Data IntraDay DataAsDistributed
•
Exit - Closes the AmiBroker program.
Introduction to AmiBroker
1 34
EDIT MENU Edit \ View
Insert
Fgrmat
On Undo
Ctrl+Z
& %
Cut
Ctrl+X
Copy
Ctrl+C
•
Undo - Undo the last operation performed on chart studies such as trendlines. This option will be unavailable if no study has been drawn or moved.
•
Cut - Cut a study from the chart and hold it in the clipboard.
•
Copy - Copy a study from the chart to the clipboard.
•
Paste - Paste the contents of the clipboard to the current chart.
•
Delete - Delete a study from the chart without holding a copy in the clipboard.
•
Delete All - Delete all objects from the current chart pane.
•
Image Copy as Bitmap ־Copies the current chart window into the clipboard in .bmp format Copy as Metafile - Copies the current chart window into the clipboard in metafile format Export to file - Saves the current chart window in .png format to a disk location you choose Send by e-mail - Create a .png image of the current chart window and send it as an e-mail using your default e-mail utility
•
Delete quotation - Deletes the currently selected bar from the database for the current ticker symbol.
•
Delete session - Deletes the currently selected bar from all symbols in the database.
•
Properties - Opens a study properties dialog. (See Chart Pane Context Menu, page 122.)
•׳X X
Delete
Del
Delete All
Alt+Del
Image
•
Delete quotation Delete session
&
Properties
Image
Alt+Enter
•
Copy As Bitmap Copy As Metafile Export to file 0
Send by E-mail
Graphical User Interface
ו35
VIEW M E N U View | pisert
+
F®־mat
Crosshair
Symbol
Analysis
!ools
ע
Crosshair — Turns crosshair on and off. Price chart style
Ctrl+H
j
Price chart style
0
Daily
>
Intraday
E
•
Weekly
Ctrl+W
«
Monthly
Ctrl+M
200 m
Line Line with dots
Ctrl+D
m
Auto
Candlesticks
Auto — Uses settings in Tools > Preference Line — Line chart Line with dots — Line chart with dots at closing price Candlesticks — Candlestick chart • Bars - OHLC Bar chart Intraday — Controls size of intraday bars and day - night sessions.
Bars •
History
•
Pane
•
Risk/yield map
E E
E E
Symbols Layouts Lasers Charts Interpretation Realtime Quote Alert Output Notepad Symbol Information l i m e a Sales Toolbars
Ml
Refresh
• F5
Refresh All
Day/Night h
Hourly
Ctrl+O
1®
15-minute
Ctrl+6
5 ־minute
Ctrl+5
©
!-minute
Clr 1+1
3-minute 7-minute 10-minute 12-minute 20־minute
Show 24 hours trading
*
< *
Show day session only (RTH) Show night session only Show day and night s e s ions Filter Weekends
£00m
•
In
Ctrl+Num +
Out
Ctrl+Num ־
All Normal Range I
Shorter bars Taller bars
Daily — Displays daily bars. Weekly — Displays weekly bars. Monthly — Displays monthly bars. Zoom • In — Reduces number of bars displayed Out — Increases number of bars displayed All — Displays all available bars Normal —Displays the default number of bars (Tools > Preference > Charting) Range — Displays the bars in the selected range Shorter bars — Reduces the vertical size of the bars Taller bars — Increases the vertical size of the bars
Introduction to AmiBroker (§
f-
History
Pane
•
•
O
Back
o
Forward
X
Ctrl+Alt+Left Arrow
•
History — Move back and forth between charts recently viewed in a browser-like way.
•
Pane Close — Closes the currently selected chart pane Arrange all — Arranges all the displayed charts Move down — Moves the currently selected chart down one pane Move up — Moves the currently selected chart up one pane Maximize — Maximizes the currently selected chart pane Restore — Restores the chart layout after using maximize Risk / yield map — Displays Risk / yield map of all the symbols in the database. Risk / yield map calculates average the 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.
Ctrl+Alt+Right Arrow
Close
no Arrange all Move Down Maximize
•
•
Symbols — Displays or hides the symbol tree (the Symbols tabbed menu) with categories.
•
Layouts — Displays or hides the Layouts tabbed menu.
Graphical User Interface
Toolbars
»
j Standard i j Ticker V j Tools • דFormat ; Draw
E View E Fibonacci & Gann IT • Status Bar
5וו
•
Layers — Displays or hides the Layers tabbed menu.
•
Charts — Displays or hides the list of charts, formulas, and indicators (the Charts tabbed menu).
•
Interpretation — Displays or hides the interpretation window
•
Realtime Quote —Displays or hides the real-time quote window
•
Alert output — Displays or hides the Alert O u t p u t window. The window displays messages generated by formula based alert.
•
Notepad — Displays or hides the Notepad window that allows you to store free-text notes about the active ticker symbol.
•
Symbol information — Displays or hides the Information window.
•
Time & sales — Displays or hides the time & sales window.
•
Toolbars Standard — Display or hide the standard toolbar Ticker — Display or hide the ticker toolbar Tools — Display or hide the tools toolbar Format — display or hide the format toolbar • Draw — display or hide the draw toolbar
Introduction to AmiBroker View — displar or hide the view toolbar Fibonacci & Gann — Display or hide the Fibonacci & Gann toolbar Status Bar —Display or hide the status bar •
Refresh — Refreshes the chart window.
•
Refresh all — Refreshes the chart window and re-reads the contents of all the categories in symbols tree.
Graphical User Interface 5 ו ו INSERT M E N U
The insert menu and the draw toolbar duplicate each other for many features. For more detailed description, see Draw Toolbar, page 154. Insert : Format S
!rend line
/ /
Raj
Symbol
•
Extended line
— I
»
Horizontal line
•
vertical Ibe Earallel lines Regression Channel Andrews' Pilrhfbrk Triangle
ם
Rectaogle
o
Ellipse
•
Horizontal line - Draws a horizontal line.
•
Vertical line - Draws a vertical line.
•
Parallel lines - Draws parallel trend lines.
Arc m
Cycle
d!>< Test tj
Zig-zag
1•
ArrQw Fibonacci Gann
» '
Trend line - Draws a trend line. Ray - Draws a ray - a right-extended trend line. Extended line - Draws a trend line that is extended on both right and left.
Regression Channel - Draws Raff, standard deviation, and standard error channels. Andrews' Pitchfork - Draws an Andrews' pitchfork. Triangle - Draws a triangle. Rectangle - Draws a rectangle. Ellipse - Draws an ellipse. Arc - Draws an arc. Cycle - Draws time cycles. Text - Places custom text. Zig-zag ־Draws a series of connected trend lines. Arrow - Draws a line that ends with an arrow.
Introduction to AmiBroker ::::::
Retracement
11!
l i m e zones
Ji-
Fan
׳si
Arc
•
Fibonacci studies Retracement Time zones Fan Arc Extension Time Extension Lines
•
Gann studies Fan Square
Extension HI
Sam
3
Time Extension Lines
Ean S3
Square
Graphical User Interface
ו ו5
FORMAT M E N U
This menu operates on the drawing tool that is active. The format menu and the draw toolbar duplicate each other for many features. For more detailed description, see Draw Toolbar, page 154.
Format | Symbol
•
Anal׳
•
Thick - Changes the formatting to thick.
•
Dotted - Changes the formatting to dotted.
•
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. The snap to price % threshold can be set in the 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.
Thick Dotted
V
Left extend
/
Right extend Snap to price
Introduction to AmiBroker SYMBOL M E N U Symbol
%
Analysis
!••is
Windc
•
New - Add new symbols to the database. After selecting this function you will be prompted for new ticker symbol. Symbols should be 26 characters or shorter and entered in all capital letters.
•
Delete - Removes the currently selected symbol from the database. Note that this operation can not be undone.
•
Split - Allows you to perform a stock split. The program will try to determine the split date and ratio by analyzing the quotations. If there is just a single quotation after the split this should work, if not you will be asked for a split date and ratio. You can specify a split using following expression: x->y which means that x shares before split become y shares after it. For example 2->3 means that 2 shares become 3 after the split. It is also possible to perform a reversesplit. For example 2->l, which means that 2 shares are joined together into 1 share.
•
Merge - This function allows you to merge two tickers. It is used 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). Select the
New... Delete
¥
Split... Merge...
M
Find
e
Information...
F3
Quote Editor,.. Favourites
•
Watch list
•
Real Time Quote
•
Categories... Organize a s s i g n m e n t s . , , Qa leu late composites..,
Graphical User Interface
5וו
new ticker (after name change) and use Symbol > Merge. Then choose the 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. •
Find - Opens the Symbol Finder window that allows you to quickly search the database for a symbol by typing the first letters of its full name or its ticker.
•
Information ־Opens the Information window for the symbol, which allows you to change the information related to the symbol.
•
Quote Editor - Opens the Quote Editor window that allows you to edit, delete and add quotations in your database. Note that you can edit the AmiBroker native database, but not the external database.
Introduction to AmiBroker • Favourites
• Remove selected symbol * Erase (make empty)
• If"
Wairh list
•
I Add selected symbol... Remove selected symbol.,. Iype־in symbols... Import... Export... Erase (make empty)... Sort alphabetically... Hide empty watchlists New watchlist... ־Delete watchlist...
Favorites Add selected symbol - Adds the current symbol to the Favorites category. Remove selected symbol - Removes the current symbol from the Favorites category. Erase (make empty) - Removes all entries from the Favorites category. Watch list Add selected symbol - Adds the current symbol to the watchlist you select. Remove selected symbol Removes the current symbol from the watchlist(s) you select. Type-in symbols - Add symbol(s) to a watchlist. Import - Import symbols to a watchlist from a .tls file. Export - Export the list of symbols in a watchlist to a .tls file. Erase (make empty) - Remove all symbols from a watchlist. Sort alphabetically - Sort the symbols in a watchlist into alphabetical order. Hide empty watch lists - In the symbol tree, show only those watchlists that are not empty. • New watchlist - Create a new watchlist. Delete watchlist - Removes
Graphical User Interface
5וו
the selected watchlists. Does not delete the symbols from the database. See Watchlists, page 179. Real Time Quote
Real Time Quote
Add selected symbol - Add the current symbol to the real-time quote list. Add watchlist - Add all the symbols in a watchlist to the real-time quote list. Type in symbol(s) - Type the symbols to be added. Insert empty line - Add an empty (separator) line. Remove all symbols - Remove all symbols from the real-time quote list. Categories - Opens the Categories w i n d o w that allows you to define the names of markets, groups, sectors, industries, and watchlists. (See Categories, page 177.) Organize assignments - Opens the Assignment organizer window that allows you to change the category assignments for symbols or to delete multiple symbols from the database. Calculate composites - Opens the Composite recalculation window that allows automatic calculation of number and volu m e of advancing/declining/ unchanged issues or volume numbers for indices.
Introduction to AmiBroker ANALYSIS M E N U
This is the workhorse menu of AmiBroker. After you have visually examined the chart and want to test the profitability of your ideas, you will use Analysis extensively. Each of these options has its own section in Chapter 9. analysis [1001s
yyridow
hi
•
Quick Review - Opens the Quick review window that provides overall market information like: daily symbol quotes, daily/weekly/monthly/ quarterly/yearly returns comparison table.
•
Automatic Analysis - Opens the Automatic Analysis window that enables you to perform explorations, backtests, optimizations, or scans.
•
Commentary - Displays the Commentary window which allows you to read comments generated by the technical indicators and describing the current conditions.
•
Formula Editor - Opens the Formula Editor window that enables you to write your own formulas.
•
AFL Code Wizard - Opens the AFL Code Wizard - Creates trading system AFL code from plain English sentences.
Quick Review.,, י
Automatic Analysis...
&
Commentary...
A
Formula Editor.,.
S.
AFL Code Wizard
Graphical User Interface
ו ו5
TOOLS M E N U
•
Database Purify - Checks the database to detect missing or extra quotes, possible splits or invalid OHLC relationships.
•
Indicator Maintenance - Opens the Indicator Maintenance wizard to clean up unused indicator space.
•
Bar Replay - Opens the Bar Replay tool which allows replay of historical data.
•
Preferences - Opens the Preferences w i n d o w which allows you to configure the AmiBroker program.
•
Save Preferences - Saves all the preferences changes (the information is stored in broker, prefs file).
•
Plug-ins - Opens the Plugins window. It contains the lists of all loaded plug-in DLLs. It can be used for inspecting which plug-ins are active and unloading unnecessary plug-ins.
•
Customize - Opens the Customize tools dialog which allows you to define custom tools that can be invoked from Tools menu.
•
Auto-update quotes - Invokes AmiQuote to update the historical quotes from the latest data in the file up to today.
Introduction to AmiBroker •
Sharenet Down loader - Launches the script which downloads the quotations from Sharenet (South Africa only).
•
Cleanup database - Launches the script that allows you to find non-traded stocks in the database. The script automatically scans the database and checks the latest quotation date. If it is old enough, the script will display warning message and let you decide whether the stock should be deleted or not. Additionally, the script can generate a list of "old" stocks and save it to the text file. The detailed information is available in the 05-2000 issue of the newsletter. (See Appendix C, Resources, for newsletter references.)
Graphical User Interface WINDOW
I Window | Help %
Cascade
Q
Tile Horizontally
Cascade - Cascades the open chart windows.
•
Tile Horizontally - Tiles the open chart windows horizontally.
•
Tile Vertically - Tiles the open chart windows vertically.
•
Arrange Icons - Aligns the windows nicely at the bottom of the AmiBroker window. Arrange icons works only if: You created more than two windows (via Window > New or Window > New Linked) • You have minimized them You moved the minimized boxes
•
Normal - Switches the chart window to "normal" (nonfloating) state.
•
Floating - Switches the chart window to floating state.
•
List of open windows. Click any entry to make it active.
_
Arrange Icons
113 Normal . Floating [ 7 | IQQQQ - POWERSHARES QQQ TRUST-UNIT SER 1 - Daily [
MENU
•
! [D Tile Vertically ן
ו ו5
: 2 SPY - SPDR TR-UNIT SER 1 - Daily
•
QQQQ
•
SPY
Introduction to AmiBroker
1 50
HELP M E N U
•
Help Contents - Displays the Contents page of the AmiBroker User's Guide.
•
Search - Allows you to search the User's Guide.
•
Tip of the Day - Shows Tip of the Day dialog where many useful usage tips are displayed.
•
Web Links - All open your default web browser AmiBroker Home Page - AmiBroker Home Page. Why Register - Purchasing and registering information. • Register On-line - Purchasing and registering information. Mailing list - Opens Yahoo AmiBroker Forum. On-line AFL Library - Library of AFL code, mostly contributed by users. AFL Function Reference - On-line reference for AFL functions.
•
Read Me - Using your browser, displays the contents of the Readme file describing features of the latest version of AmiBroker.
•
About AmiBroker - Shows the 'About ׳window, which contains the information about program version and user details.
Help 1 ^ M
Help Contents Search Ti£ of the Day... Web links :: Read Me
f
About AmiBroker...
>
AmiBroker Home Page Why register? Register On-line Mailing list On-line AFL library AFL Function Reference
Graphical User Interface 5 ו ו TOOLBARS
A toolbar is a n a r r o w panel in a graphical user interface where buttons and icons can be placed. The icons are associated with m e n u s and programs, and the toolbar gives a convenient way of keeping c o m m o n l y used tools handy. All of the tools on all of the toolbars are available f r o m other menus. The toolbars are strictly for your convenience. The icons and p r o g r a m s shown in the screen capture images are the defaults. Add a n d remove icons to simplify your use of AmiBroker. Toolbars can be modified by the user: a d d i n g and removing icons as desired; undocked and re-docked in a more convenient location; in view or hidden. To set any of the toolbars to be in view or hidden, use the View menu, select Toolbars. TOOLS FOR GENERAL USE
Standard Toolbar • a* a m a - o © a, I I I I I I I I I I I I I jI
? c a 1 z * J i J > . ( u ( u « g j > < c u a . ״••־•־ כ ד
o
U
כד י-
o
w o c
Z
Ol/>״Q- u S. 4 ׳ כrn 3 " - a •43 %
1/1
ם
o
gwa.
u_ - ם
(!)U
> §־s
Introduction to AmiBroker There are a lot of icons that can be added to the Standard Toolbar. Click the Toolbar Options icon to open the Add or Remove Buttons menu. [p] D ! p] ^ y 3rt
Format
© X
Symbol
Analysis
*•י
lools
Window
,SPY
h ן
New
Ctrl+N
Open
Ctrl+O
Save
Ctrl+S
Save All
t
& ׳a
Help Topics About AmBroker Home page Save
Print
Ctrl+P
Cut
Ctrl+X
0
New database
Copy
Ctrl+C
a
Default Chart
Paste
Ctrl+V
Delete
a
Open Database
New Account
Del
e
New Web Research
Undo
Ctrl+Z
ם
New chart
Back
Ctrl+Alt+Left Arrow
a
New c h a r t Pane
Forward
Ctrl+Alt+Right Arrow
IS
Symbol information
•
Quote Editor
SI
Print Preview
ש
a m
Import Wizard
Click Toolbar Options to get to t h e choices a v a i l a b l e for icons
<0
ASCII import MetaStock import
g]
Organize assignments
B
Send image
ם
Export chart image to PNG file
a
Copy image to clipboard
ש
Properties
Alt+Enter
•
New symbol
a
Split
SI ₪
Find symbol New Window
•
New Linked Cascade Windows Tile Horizontally Tile Vertically Help keyword search
B
•
• geset Toolbar
Ticker Toolbar The ticker toolbar is one of the quickest ways to load a new symbol into the existing charts. Tools Toolbar 5*
ftr
!
feAM,
I I I I I ־I סI> י 1 > מ( > מ.
15 8 ״ • ״o 15 ״
E JS a, L. ע ו ו ןu E 3 5, יי־ i f •5 o E -
*
ט < | ׳ o ׳
4
> כ י ־
Graphical
User
View Toolbar •
» ₪ •
-
1 I I I I I I II
c
• nj — —
cOQ
1 .< .< < -< ״ -37: c c
2E ™I
S o t N
)
»
ra.o
> o ,a o
5 0 L
U S
Icons can be added to the View Toolbar. V׳ ד ׳י v׳
Zoom in (+SHIFT zoom o u t +CTRL normal, +SHIFT+CTRL to ... Zoom out
e i
Ctrl+Num -
Intraday
Z
1
Hourly
Ctrl+O
d
Daily view
Ctrl+D
y
w
Weekly view
Ctrl+W
•י
•
Monthly view
Ctrl+M
E
e
New Web Research Close pane
״ Arrange charts ש
+
©
i
Crosshair Refresh
Ctrl+H F5
Shorter bars
«
Taller bars
*
Day session
24 24-hours trading c
Night session
*
Day and night sessions
© ®
l־minute
Ctr 1+1
5-minute
Ctrl+5
15 ־minute Reset Toolbar
Ctr 1+6
Interface
5
ו
ו
Introduction to AmiBroker T O O L S FOR DRAWING
There are three toolbars that are used to place studies on price charts. They are the D r a w i n g Tools, Fibonacci and Gann Tools, and Formatting Tools. They m a k e placement and modification of studies very easy, and are much more efficient than using the Insert and Format pull-down m e n u s where they also reside. Toolbar Docking You can un-dock these f r o m their original positions and re-dock them a n y w h e r e you wish. To do that, move your cursor over the string of dots at the top of the toolbar; it will change to a four-direction arrow. Using normal drag and d r o p technique, place the toolbar wherever you w a n t it.
Draw Toolbar - Fibonacci Toolbar ־Format Toolbar The Drawing and Fibonacci Toolbars let you select and place a tool; the Formatting Toolbar lets you m o d i f y the properties of the study tool, such as color and line style.
s / / I
Select A r r o w is the first tool - at the top, or left if you have docked the toolbar horizontally, s h o w n as a Red Arrow. It is used to select objects that have already been d r a w n so that they can be moved or resized.
י ס
c m g ־o o סו t\ & i
To d r a w a study object on the chart:
H « A ) ׳
1. Select Select the the desired desired tool. tool c
= J
c
!111
(j
^
2. Move the mouse to the position you want to start drawing. V)
'<-> o % o B t £I 4 ־ £ 11 ^ iZ — ro o ? E °
3. ־
Left-click the mouse.
. I f the d r a w i n g needs only one point, you will see the lines appear. If it needs a second point, move the m o u s e to the position you w a n t the second point. You can either hold the left button d o w n while m o v i n g the mouse, or not; either works. " 5. Left-click again (or release the mouse button).
Graphical User Interface
וו5
To modify a study object on the chart: 1. Select the study. Usually just hovering your mouse around the object is adequate. If there are multiple studies in close proximity using the Select Arrow to select the study. The control points will appear as small squares. These are used to resize the object. of the control meaning that middle of the meaning that
2. If your cursor is near one points, it will change to a two-direction arrow, the object can be resized. If your cursor is in the object, it will change to a four-direction arrow, the object can be moved.
The Format Toolbar has icons to: •
Change the color of the study.
^
•
Make the lines thick.
S
•
Make the lines dotted.
• •
Snap the study to the nearest price. Set the price using the Tools menu, select Preferences, on the Charting tab. Extend the study to the left.
•
Extend the study to the right.
ר
i
Preferences Charting
Colors
Editor
Date
Intraday
Miscellaneous
Alerts
AFL
::Currencies
General ןד־־ןShow vertical line between d a y s
0 Show v a l u e labels
(i ntrad ay)/ye a r s (E 0 D)
0 E n a b l e scroll bar zoom
F1 Showvertical line between months
0 'New Look1 charts
• Quote selection only by CTRL+LMB
159!
Default number of quotations in a chart: Blank b a r s in right margin: Candlesticks i U s e distinct color for b o d y outline and s h a d o w s Drawing 0 Return to select m o d e after drawing 0 Auto-select last drawn object
S n a p to price % threshold:
Miscellaneous 0 Ask for p a r a m e t e r s of newly inserted indicators 0 Ask for confirmation when deleting indicator sections • Ask for confirmation when closing indicator p a n e Number of chart s h e e t s (from next run):
OK
j |
Cancel
\ |
Apply
| ]־־־
Help
Introduction to AmiBroker Techniques used to manipulate the study and drawing tools follow Windows. •
To select the object, move the mouse over the object so the four-directional arrow cursor appears. Click once. The sizing handles will appear.
•
To de-select the object, click in any blank chart space.
•
To re-size the object, click on the sizing handle and drag it to the desired location.
•
To move the object, click on any part of the object other than the sizing handles and move it to the desired location.
•
To delete object, select it, then press the Delete key on the keyboard. Alternatively, use the Edit menu and select Delete.
•
To copy the object to the clipboard, select it, then press Ctrl+C. Alternatively, use the Edit menu and select Copy; or use the Copy toolbar button.
•
To cut the object, select it, then press Ctrl+X. Alternatively, use the Edit menu and select Cut; or use the Cut toolbar button.
•
To paste the object from the clipboard, press Ctrl+V. Alternatively, use the Edit menu and select Paste; or use the Paste toolbar button. The pasted object will be drawn in the 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. You can select the color and style of the object before drawing a new object. Deselect previous object (if any), change color / style selections, and draw new object.
•
To modify the properties of an object, first select it, then open the Properties ciialog box.
•
To delete all objects in the pane, use the Edit menu and Delete All.
Graphical
User
Interface
5
ו
ו
STUDY TOOLS
Trend line, Ray, Extended, Vertical, Horizontal These tools give different flavors of the basic trend line, Trend line gives a line segment, Ray gives right-extended trend line, Extended gives trend line that is extended automatically f r o m both left- and right- sides. Vertical and Horizontal are self-explaining. Arrow Similar to Trend line but ends w i t h an a r r o w Zig-zag Draws a series of connected trend lines. To end d r a w i n g press the ESC key. Parallel This tool draws a series of parallel trend line segments. First you d r a w a trend line as usual. A second line parallel to the first is automatically created and you can move it a r o u n d with the mouse. Once you click on the chart it is placed in that position. A third parallel line appears that can be placed somewhere else. A n d so forth. W h e n you have all the parallel lines you need, either press ESC key or choose the Select tool. Regression channels Three kinds of regression channels are available: •
Raff regression channel.
•
Standard error channel.
•
Standard deviation channel.
All these channels are based on linear regression trend line. They differ in the method used for setting the distance f r o m the trend line to the upper and lower channel lines. "Study ID" column defines study identifier that can be used in your custom formulas to detect crossovers. If necessary, you can change these IDs by simply editing these fields. For more information on Study IDs check the Tutorial: Using studies in AFL formulas. More information on regression channels is available f r o m the AmiBroker User's Guide.
Introduction to AmiBroker Fibonacci and Gann studies There are m a n y options, parameters, and preferences. Please refer to the AmiBroker User's Guide for details. Triangle Triangle tool is self-explanatory. To d r a w a triangle: 1. Left-click at the first point. 2. Hold the left mouse button a n d drag to the second point. 3. Release the mouse button. 4. Move the cursor to the third point. 5.
Click once.
Andrews' Pitchfork A n d r e w s ' pitchfork is a study using parallel trendlines. To construct the study, choose three starting points. The first is a major peak or trough on the left side of the chart display. The second and third are chosen to be a major peak and a major trough to the right of the first point. Leftclick at the first point, hold d o w n and drag to the second point, then release m o u s e button and drag to the third point and click once. 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. This line is called the h a n d l e of the pitchfork. The second and third trend lines are d r a w n by AmiBroker beginning at the starting points and parallel to the handle. Cycles Click at the starting point of the cycle and drag to the end of the cycle. Vertical lines will be d r a w n on the chart extending that cycle length to both the right and left.
Graphical User Interface
ו59
A D D ICONS T O TOOLBAR
If you do not see an icon you want on a toolbar, you can turn it on. For example, assume you want the close pane icon on the view toolbar. 1. Click the Toolbar Options icon at the bottom of the View Toolbar. It will open the Add or Remove Buttons menu. 2. Select View. 3. Select Close Pane. 171 # Zoom in (+SHIFT zoom out, +CTRL normal, +SHIFT+CTRL to .,, Ctrl+Num H e Zoom out 0 1 Intraday Ctrl+0 E: * Hourly Ctrl+D B * Daily view Ctrl+W E ״Weekly view Ctrl+M Fl - Monthly view e New Web Research H x Close pane • m Arrange charts +
Crosshair
ש
Refresh
1
F5
Shorter bars
•
Taller bars
24
24-hours trading
*
Day session
c
Ctrl+H
Night session
*
Day and night sessions
0
1-minute
Ctrl+1
<2> 5-minute
Ctrl+5
®
Ctr 1+6
15-minute Reset Toolbar
Because the View Toolbar is at the right edge of the screen, these menus open right to left.
1 160
Introduction to AmiBroker
TABBED M E N U S
AmiBroker has several "tabbed" menus. These can be "torn off" from their present location and re-docked wherever you want them. And they can be set to slide to the side of the window (in an auto-hiding technique) giving more screen real estate to the charts. The next few pages describe the "tabbed" menus and windows. They include menus Layouts, Symbols, Layers, Charts, Notepad, and Interpretation, and windows Symbol Information, Real-time Quote, Alert Output, Time and Sales. RE-DOCKABLE MENUS
All of these tabbed menus are implemented as "tear-off tabs" and can be re-docked wherever you wish. To re-dock a menu into any side of the application or as a tab simply click on docking window's caption bar and drag it. Docking stickers will appear. Drag the pane until the cursor is over one of the docking stickers, then release. The pane will dock in that position. (See figure on next page.) When you re-dock the pane back into its original location, it may not be in the same order relative to the other tabs. A U T O - H I D I N G SLIDING MENUS 9 X
Symbols I Layouts j Layers Chart? j Symbols it! C l SB LJ Sft GJ (& Cl !1 LJ it; CJ
Markets Groups Sectors Watch lists Favourites Indexes
O
L AmiBroker - [QQ.QQ עFile
£drt
^
View #
Insert H i ®
״q q q q (Daily)
F >
*
7/30/20DB O
If there is a pin in the upper right h a n d corner of a tabbed menu, that menu may be set to auto-hide. Autohiding brings the menu out when you want it, and lets it slide out of the way and off the chart's real estate when you do not need it. To set Auto-hiding On, just click the pin. The pin icon will turn from upright to sideways and the menu will be auto-hiding, as in the illustration to the left. Click the tab and the menu will slide out.
Graphical User Interface L
A m i B r o k e r - [ Q Q Q Q - P O W E R S H A R E S Q Q Q T R U S T - U N I T SER 1
J QQQQ [Daily
ו ו5
- Daily]
IjlJUU (Daily) X
Q Q Q Q - Dally 4/18/2008 O p e n 46.51, Hi 46:
Cursor
Docking stickers
45.4371 45 1608
44.00M 0
For Help, ! y e s s F1
Nasdaq, ETF, Financial, Fin-ETF
* QP End of Day
1 62
Introduction to AmiBroker
LAYOUTS, LAYOUTS TABBED M E N U , LAYOUTS C O N T E X T M E N U
Layouts are the highest level of the AmiBroker chart structure. They are described in Chapter 4, AmiBroker Chart Structure. Layouts Tabbed Menu The Layouts tabbed m e n u shows which layouts are available for use with the database that is open (local layouts), and which are available with any database (global layouts). Show or hide the Layouts tabbed m e n u using View > Layouts.
1
Layouts
Layouts | Layers j Charts, j Symbols | Ss LJ Local layouts •
Default
0
Vanilla
The Yellow icon shows which layout is currently open and active.
& CJ Global layouts «
Daily_Weekly
•
Default
•
Local layouts
•
T w o Broad
Double-click any entry to open it and make it the active layout.
Layouts Context Menu The Layouts context menu opens w h e n you right-click in the Layouts tabbed menu. I2532331SI Open
•
Save S a v e As... Save as default Delete
•
O p e n - loads selected layout. Save - saves current w i n d o w layout u n d e r current name. Save As... - save current w i n d o w layout under n e w name. Save as default - save current w i n d o w layout as default (startup) layout for given database. Delete - delete selected layout.
Graphical
User
Interface
5
ו
ו
LAYERS, LAYERS TABBED M E N U , LAYERS C O N T E X T M E N U
Layers are like pieces of transparent plastic. You can put d r a w i n g s on them. Showing or hiding a layer allows you to display or hide the drawings placed on that layer without affecting the d r a w i n g s placed on other layers. Layers Tabbed Menu The Layers tab lists the pre-defined layers. j Layouts j Layers J Charts j Symbols j ₪ • 0 • P • • • • 0 •
Default layer Intraday layer Dally layer Weekly layer Monthly layer Custom layer 1 Custom layer 2 Custom layer 3 Custom layer 4 Custom layer 5 Weekly stuff
The checkboxes on the left side of each layer control layer visibility. If the box is checked, then that layer is visible; if it is unchecked, that layer is invisible. Show or hide the Layers tabbed m e n u using View > Layers.
The first five layers are built-in and special. They are: 1. Default layer - always visible. 2. Intraday layer - visible only w h e n viewing intraday charts. 3. Daily layer - visible only w h e n viewing daily charts. 4. Weekly layer - visible only w h e n viewing weekly charts. 5. Monthly layer - visible only w h e n viewing monthly charts. The visibility of these five is controlled by the charting interval selected, and cannot be changed using the checkboxes. The r e m a i n i n g layers can be shown or hidden by m a r k i n g the checkbox. To draw a study on a given layer: 1. Select the layer by clicking on its name. 2. Draw the study as usual. You can move a study f r o m one layer to another using the Properties menu of the study (not the Properties of the layer). That is, right-click the study, choose Properties, select the layer you w a n t this study to be on.
1 164
Introduction to AmiBroker
Layers Context Menu W h e n you right-click on a layer name, you will see the context menu containing the following options: Add layer R e m o v e layer S h o w All Hide All Toggle Lock built-in layers Unlock built-in layers
Add layer - A d d s a new layer. Remove layer - Removes the selected layer. Note that you cannot remove any of the first five, builtin layers. Show all layers - Shows all non-locked layers. Hide all layers - Hides all non-locked layers. Toggle - Toggles the visibility of all non-locked layers. Lock built-in layers - Lock the first five, built-in layers. W h e n these layers are locked, their visibility changes w h e n the charting interval changes. Unlock built-in layers - Unlocks the first five layers. The visibility now d e p e n d s on the checkbox. •
Layer properties
!*/]Lock visibility to selected interval Visibility Interval •
Monthly
•
Weekly
M
Daily
•
Daylight
•
Hourly
F " | 15-minute 5 ח- m i n u t e r~1
*
Properties - Launches the properties box that allows you to r e n a m e layers, and decide if the layer should be locked to the charting interval displayed. There is a separate visibility setting for each interval. Check the boxes where you w a n t the layer to be visible and uncheck those where you do not.
Graphical User Interface
וו5
SYMBOLS, SYMBOLS TABBED M E N U , SYMBOLS C O N T E X T M E N U K B Layouts I l a y e r s j Charts | Symbols j נAII נMarkets כGroups J Sectors £ U Undefined ti LJ Capital Goods a Svc !1
Consumer Goods
The Symbols Tabbed m e n u displays the ticker symbol of all issues in the active database. Each symbol may be a m e m b e r of several categories. The ticker will be listed in every category to which it belongs. (See Categories, page 177.) Show or hide the Symbols tabbed m e n u using View > Symbols.
6 LJ Telecommunications H D Utilities J Watch lists fe CJ Passed Test N LJ Best Results is U DJ30 y; D Russell 1000 t LJ Russell 2000 i LJ SP100 B D NASDAQ 100 t: LJ SPSectorETFs J Favourites • ^
S2SSI SPY
J Indexes
Symbols Context Menu The Symbols context menu opens w h e n you right-click in the Symbols tabbed menu. •
Add to favorites - Add the active symbol to the Favorites category.
•
Remove f r o m favorites - Remove the acfive symbol f r o m the Favorites category
•
Erase favorites - Remove all m e m b e r s of the Favorites category f r o m that category (not f r o m the database).
•
Web research - O p e n a new w i n d o w in the AmiBroker C h a r t window, and use the built-in browser to display a page of information about the active symbol. (See figure next page.)
Symbols I Layouts li h ti is -
LJ _l CJ • CJ * g
| Chat is j Symbols j
All Markets Groups Sectors Watch lists D Passed Test Q Best Results • Bf ־ ־ » A f Mc
IT: U נ ם3 ס t. טRusse
. טSPIOO
Remove from favourites Erase favourities Web Research
WA ״, !TET
ii LJ NASD* * טSPSec טFavour iter • QQQQ V SPY I Indexes
Delete
Introduction to AmiBroker
1 166
4 AMIBROKER - [Q.Q.QQ - HEADLINES (Y! FINANCE)] a Ells
edit
yiew
Insert
Symbol
Fgrmat
״D<«HAP •JLS&SJS. © © 9
Symbols
x
L... All
as ם
Markets Sectors
•Si •C3 Undefinec
® CJ Consume! Li Q Energy
QQQQ
& D Financial
4 8 , 1 6
׳^י
s
X
d CJ P a s s e d Tt & • 0 3 Best R e s t i D DJ30 ii LJ Russell 1C Russell
2C
I! Q SPIOO י
m [J NASDAQl
:
CJ SPSector( Favourites QQQQ SPY
J 8
, V־
s ®BiijCharts
Volume:
11
123,116,000
SO
N
D 08 F
n a
M J J
in 1 400 2 11 200 ־ n =
Price Average 50-day:
$46.23
Price Average 200-day:
$46.96 169,813,000
Return on Equity (1 year):
162,861,800
Return on Assets (X year):
52wk low (3/17/2008):
$41.05
Bid:
$48.16
Ask:
$48.17
$ 18.73B
Shares Out:
389.00M
1 Per S h a r e Data Earnings (1 year):
Return on Investment (1 year):
Price/Earnings (1 year): Price/Book (1 year): |
Market Cap:
/\1
A
Fiscal Year-End: n / a
Vol Average 200-day:
$55.07
(800) 983-0903
Company at a Glance
Volume Average 50-day: S2wk high (10/31/2007):
Phone:
Exchange Traded Funds
42
I Share Related I t e m s
ii D Indexes
M
Price/Cash Flow (1 year):
Bill
Gross Margin (1 year): j
Operating Margin (1 year): Profit Margin (1 year):
Realtime Quote f =or Help, p r e s s F
ן
A data as of Close 8/15/2008 |
-0.19%
P o w e r S h a r e s QQQ T r u s t S e r i e s I 301 W. Roosevelt Road Wheaton It 60187
1 54
S £ j Watch lists
• 0
e
Company I n f o r m a t i o n 8/15^08
QQQQ D a i l y ״ ״
® CJ T e l e c o m r
S D
\
0 . 0 9 ־Percent Change:
Price and Volume
fr-Oi utilities
i•
45^׳
C o m p a n y Profile
ii LJ Techno lot
1
!
* B3**1• "^״
Change:
S 1 C 3 Materials
:
Help
®
(NASOAQ GM)
PowerShares QQQ
Last:
S3 Cil Health Ca
,
' m
& q q q q - H e a d l i n e s (VI Fin..
a QQQQ (Hail•/
m Cl Capital Gc 1 ! ןD Consumei
1
Window
Company Profile
S i £ j Groups
1
Tools
QQQQ
Address Headlines (Yl Finance)
« U
!
Analysis
0 13 ,
Nasdaq, ETF, Financial, F
t QP End of Day
•
Watchlist - The expanded menu is shown on the next page.
•
Add to Real-time quote window - Add the active symbol to the real-time quote window.
•
Delete - Delete the active symbol from the database. Use with care - this action cannot be "undone".
Graphical User Interface
5וו
Watchlist Submenu Add selected symbol Remove selected symbol Type-in symbols... Import,.. Export... Erase (make empty) Sort alphabetically Hide Empty watchlists New watchlist.,, Delete watchlist
Add selected Symbol - Add the active symbol to a watchlist. A dialog box will open so you can choose which watchlist. Remove selected symbol - Remove the active symbol from one or more of the watchlists of which it is a member. Type in symbols - Opens a dialog box and allows you to type in a comma separated list of symbols to add to a watchlist. Import - Opens a dialog box and allows you to specify a list of symbols to be added to a watchlist. Export - Export the tickers of a watchlist to a text file. Erase (make empty) - Remove all entries from a watchlist. Sort Alphabetically - Sort the symbols in a watchlist into alphabetical order. Hide Empty Watchlists - A toggle to either hide or display watchlists that have no members. New Watchlist - Establishes a new watchlist at the end of the list of existing watchlists. Uses a name you specify. Delete Watchlist - Deletes the watchlists that are selected. (See Watchlists, page 179.)
Introduction to AmiBroker
1 168
C H A R T S (FORMULAS) TABBED M E N U , CHARTS C O N T E X T M E N U
Layouts ןlayer? | Charts יSymbols j j Averages / DEMA - Double Exponential Moving Average / DispMA - Displaced Moving Average / EMA - Exponential Moving Average / Linear Regression - Least Squares Moving Average / MA - Simple Moving Average / TEMA ־Triple Exponential Moving Average / TSF ־Time Series Forecast / Wilders ־Wilders Moving Average / WMA - Weighted Moving Average D Bands f Bollinger Bands f Keltner Bands / Percent Bands 1ג Basic / Open Interest (futures) / Price / Price (all in one) / Price (foreign) / Relative Performance / Volume / Volume (color) / Volume At Price ] Custom f AlertlfTest / ATC Trading Figure_17_ll / Liquidity / RelativeStrength / SimpleSystem / SimpleSystem 1 j Equity 3 Include J Indicators / ABI - Absolute Breath Index / AccDist ־Accumulation Distribution / AD Price - Williams Advance Decline of Price / AD Ratio ־Advance Decline Ratio f ADLine - Advance Decline Line / ADX - Directional Movement Index / ASI - Accumulation Swing Index / ATR - Average True Range / Beta / Breadth Thrust f CCI - Commodity Channel Index / Chaikin - Chaikin Oscillator
The Charts Tabbed Menu gives access to the charts, formulas, and indicators that can be applied to the chart panes. Show or hide the Charts tabbed menu using View > Charts. A later section, Charts (Formulas), Charts page 190, lists the formulas and indicators, explains them, and shows how to apply them in more detail.
Charts Context Menu Right-click any entry to display the context menu. • \ Symbols 1 Layouts Layers j Charts i j is C3 Averages i • • ® Bands S C |־Basic Charts / Open Interest (futures) / Price f f5T89Bjfl • ! I S I S Insert / Price (for Insert Linked / Relative / Volume Overlay / Volume Analysis / Volume it;• Q Custom Edit ffi C3 Equity Rename D Include Delete ;!••£ נIndicators i! Oil QTS Book New D QTS Book Cc g• Q Systems Refresh / Example / ExampleRotational
•
Insert - inserts a copy of the selected indicator into a n e w pane. The copy of the original formula file is created and placed in a hidden drag-drop folder. The original formula will not be affected by subsequent use or editing, and other formulas can be applied to the same chart without conflict. Double clicking on a formula n a m e is equivalent to choosing Insert f r o m the menu. Insert Linked - Inserts the selected indicator into a n e w pane directly. Insert Linked does not create a copy of the formula. Instead, it ere-
Graphical User Interface
5וו
ates a new pane that is directly linked to the original formula. Any modifications to the original formula will be applied to the one being inserted. •
Overlay - Overlay the selected indicator into the selected (active) pane. The overlay command appends additional code to the formula used by the pane. If the given pane was created using Insert Linked, it will modify the original (linked) formula. If there are several data series in the pane being overlaid, a dialog box will appear and you will be able to select which one is to be overlaid.
•
Analysis - Opens the Automatic Analysis window with the selected formula chosen.
•
Edit - Opens the Formula Editor with the code for the selected formula loaded.
•
Rename - Rename the selected formula.
•
Delete - Delete the selected formula.
•
New Formula - Creates a new formula file in the selected folder. Folder - Creates a new subfolder under the selected folder.
•
Refresh - Re-reads the Formula directory and re-displays the formula tree.
See the section Charts (Formulas), page 190.
Introduction to AmiBroker N O T E P A D , NOTEPAD TABBED M E N U , NOTEPAD C O N T E X T M E N U
Notepad window 4 AmiBroker - [MSFT - MICROSOFT CORP-COM 'm £ite
Edit
View
& םa m §־
Insert
F'ormat
Notepad MSFT - Microsoft - pays $ 43
* י
Symbol
Analysis
©©.a
Iool
IMSFT (Daily) x MS FT - Daily 3/9/2007
The Notepad w i n d o w allows you to store free-text notes about a particular security. Type any text into the Notepad w i n d o w (no editor required). It will be associated with whatever ticker symbol is in the active w i n d o w and automatically saved. The text will appear in the Notepad w i n d o w whenever that symbol is in the active window.
Notes are global, not database specific, and are saved in C:\Program Files\AmiBroker\Notes subfolder as ordinary text files. Notes can be also written and read using AFL langauge NoteSet and NoteGet functions. AmiBroker Notepad, one of the Tabbed menus, should not be confused with Microsoft Notepad, a general p u r p o s e text editor that is a component of Microsoft Windows. Show or hide the Notepad tabbed m e n u using View > Notepad. Notepad Context Menu QQQQ Is the NASDAQ 100 tracking
Select All OpenlME
The Notepad context m e n u opens when you rightclick over the Notepad window. The m e n u is a basic editing m e n u with options to cut, copy, paste.
Graphical User Interface
וו5
INTERPRETATION, INTERPRETATION TABBED M E N U , INTERPRETATION C O N T E X T M E N U
Interpretation Window Interpretation
י
I Price Date: 3/18/2008 Price and moving averages: MSFT(MlCROSOFT CORP-COM) has dosed above its Short j time moving average. ־Short time moving average is currently below mid-time, AND ׳below long time moving averages. The relationship between price and moving averages is: neutral in short-term, and bearish in mid-long term. ! Bollinger Bands: ! MSFT(MICROSOFT CORP-COM) has closed below upper band by 0.3%. Bollinger Bands are 37.6% narrower than normal. The current width of the bands (alone) does not suggest anything conclusive about the future volatility or movement I of prices. This commentary is not a recommendation to buy or sell. Use at your own risk.
The Interpretation w i n d o w shows chart-sensitive commentaries that are created by the execution of an AFL program. To add an interpretation, see C o m m e n t a r y and Interpretation, page 524. Show or hide the Interpretation tabbed m e n u using View > Interpretation.
Interpretation Context Menu
past־ Select All
The Interpretation context m e n u o p e n s w h e n you right-click over the Interpretation window. The m e n u is a basic editing menu with options to cut, copy, paste.
1 72
Introduction to AmiBroker
ALERT OUTPUT, ALERT O U T P U T CONTEXT M E N U
Alert Output Window 9
Alert Output T cker
Date/Time
Text
4 AAPL 4 ־ADSK
7/29/2008 7/29/2008
MA Cross - Sell MA Cross - Sell
4׳ | -f 4 4 4׳ 4׳
-j.
׳fBBIi ALTR AMAT AMGN AMLN AMZN APOL ATVID
Delete iss7j Delete All |ss 7/2972008" ״MATross 7/29/2008 MA Cross 7/30/2008 MA Cross 7/29/2008 MA Cross 7/29/2008 MA Cross —
Sell Sell Sell Sell Sell Sell Sell
The Alert O u t p u t Window receives the messages sent by the Alertlf function as an AFL program runs. Show or hide the Alert O u t p u t wind o w using View > Alert Output.
Alert Output Context Menu The Alert O u t p u t Context m e n u gives only two choices: •
Delete - Delete the selected row
•
Delete All - Delete all rows in the window.
וו5
Graphical User Interface REAL-TIME Q U O T E , REAL-TIME Q U O T E C O N T E X T M E N U
Real-Time Quote Window 4 AmiBroker - [XLY - CONSUMER DIS SS SPDR - 1 - m i n u t e ] צEHe
Edit
View
&םy&
Insert
Format
m
o
Symbol
oa=
Analysis
!ools
Window
& « •י
XLY
Help a
&
1
*!
^ j y
:m
׳
j
b
d
w
2 XLY ( 1 - m i n u t e ) : XLY - 1 - m i n u t e 8 / 1 4 / 2 0 0 8 2 : 2 2 : 0 0 PM O p e n 3 1 . 0 5 . Hi 3 1 . 0 5 . Lo 31, C l o s e 31 ( - 0 . 1 % ) Vol 13.247 M A ( C I 0 s e , 1 5 ) = 3 1 . 0 2 , Mid
J
1
'8/13/2008 y
13:00 113:30 114 00' 14 30 115 00115:30 '8/14/2008
(• \ S h e e t 1
Realtime Quote T... Sf Open XLB XLE XLF XLI XLK XLP XLU XLV XLY i
39.64 72.90 20.46 35.07 23.41 28.54 37.17 32.91 30.04 i
•
•1 V - i s t
For Help, press Fl
/ Sheet 2 ץSheet 3
1
1 0 : 3 0 1 1 1 : 0 0 ' 1 1 : 3 0 ' 12:01' 12:30 1 1 3 0 0
Sheet 4 \ Sheet 5 ^ Sheet 6 ^ Sheet 7 \ Sh - 5 - 1
High
Low
Last
Change
% Ch...
Volume
Trad... !
39.80 74.38 21.26 35.73 23.75 28.89 37.17 33.57 31.28
39.06 71.36 20.38 34.89 23.28 28.35 36.65 32.89 30.01
39.49 72.36 21.06 35.50 23,67 28,76 36,94 33,43 31,00
" -0.19 ־1.14 0.49 0.18 0.21 0.19 -0.20 0.13 0.60
־0.48% ־1.55% +2.33% +0.51% •>•0.90% +0.67% -0,54% +0.39% + 1.97%
8,013,... 27,44... 89,40... 5,579,... 3,320,.., 3,385,.,, 2,479,,,. 2,394,... 3,955,...
100 100 1,800 100 100 100 100 100 300
A « 2 Y U S . 3 ^ List 4 . u s t s X List 6 \ u s t 7 \ List X; 8/13/2008 3:02:00 PM, Bar: 2465 Y: 31.0864
8 L
\ <
Bid 39.49 72.36 21.06 35.50 23.66 28.76 36.93 33.41 31.00
1
13:45114
<
Bid size I 30 70 850 130 524 195 195 274 115
Ask 39,50 72.37 21.07 35.51 23,67 28.77 36.94 33,42 31.01
Asks...
52w ... i 52\a
"""""I'D"'' 5 1,855 116 237 205 39 261 164 ׳A--j
i
: Undefined, Undefined, Services, Advertisinc > QP RealTi me
The Real-Time Quote w i n d o w shows the tick-by-tick information about the symbols that have been added to the window. Fields depend somewhat on the data provider, but include: •
Prices for the session - Open, High, Low, Last.
•
Change from previous close.
•
Percent change from previous close.
•
Volume for the session.
•
Last trade volume.
•
Bid price and size.
•
Asked price and size.
Show or hide the Real-Time Quote w i n d o w using View > Real-Time Quote.
Introduction to AmiBroker Real-Time Quote Context Menu The Real-Time Quote context m e n u opens when you right-click in the Real-Time Quote window. •
Time a n d Sales - O p e n s the Time a n d Sales w i n d o w that provides information about every bid, ask, and trade.
•
Easy Alerts - O p e n s the Easy Alerts w i n d o w that provides a way to define real-time alerts executed w h e n bid, ask, or last hit user-defined levels.
•
Add Symbol - A d d s the current symbol to the RealTime Quotes list.
•
Add Watchlist - A d d s all the symbols in a watchlist to the Real-Time Quotes list.
•
Type in Symbol - O p e n s a dialog so you can type in a symbol to add.
•
Insert Empty Line - Inserts a blank row in the RealTime Quote w i n d o w to help visual organization of the window.
•
Remove Symbol - Removes the symbol in the highlighted line f r o m the Real-Time Quote window.
•
Remove All - Removes all symbols from the RealTime Quote list.
•
Hide - Hides the Real-Time Quote list and window.
Time a Sales... Easy alerts Add symbol Add watch list.,. Type-in symbol(s) Insert empty line Remove symbol Remove All Hide
Graphical User Interface 5 ו ו T I M E AND SALES L Time & Sales SPY Time 10:36:00 10:36:00 10:36:00 10:36:00 10:36:00 10:36:00 10:36:00 10:36:00 10:36:00 10:36:00 10:36:00 10:36:1X1 10:36:00 10:36:00 10:36:00 10:36:00 10:36:00 10:36:CC
Type
Price
Bid Bid Bid Ask Ask Trade Bid Ask Trade Trade Bid Ask Ask Bid Bid Trade Trade Bid
129.B6 129.86 129.86 129.87 129.87 129.87 129.86 129.87 129.87 129.87 129.86 129.87 129.87 129.86 129.86 129.87 129.B7 129.86
•o Size
15700 15100 14300 1300 1100 100 14400 700 200 100 14300 1100 1300 14200 13600 100 100 13600
<
m A
V
The Time a n d Sales w i n d o w displays information about every bid, ask and trade streaming f r o m the market. Each row displayed represents either a new trade, a n e w bid, or a n e w ask that is sent by the streaming data source. Each line in the time and sales w i n d o w is marked with color to m a k e it easier to distinguish b e t w e e n various conditions.
>
Coloring rules are: •
Light green background m e a n s a new ask.
•
Light red background m e a n s a new bid.
•
Normal (white) background m e a n s a n e w trade.
•
Red text for the bid price, ask price, or size m e a n s that the value is less than the previous value of the same category. For example, if the bid price is written in red letters, that m e a n s that the n e w bid is lower t h a n the previous bid.
•
Green volume field m e a n s that the volume of last trade, or ask or bid size, is greater t h a n the last.
•
Black text for the bid/ask price/size/volume m e a n s that the value is the same.
•
Red last trade price m e a n s the trade occurred at or below the current bid.
•
Green last trade price m e a n s the trade occurred at or above the current ask.
•
Black last trade price m e a n s the trade occurred inside the current bid-ask range.
Introduction to AmiBroker Time and Sales Context Menu The Time and Sales Context Menu appears w h e n you right-click in the Time and Sales Window.
HfflBBBBB Time
Type
10:37:16 10:37:16 10:37:16 10:37:16 10:37:16 10:37:16
Bid Bid Ask Ask Bid Bid
10:37:16 10:37:16 10:37:16 10:37:16 10:37:16 10:37:16 10:37:16 10:37:16 10:37:16 10:37:16 10:37:16
Bid Ask Ask Bid Bid Bid Bid Bid Bid Bid Bid
Price
Size
129.89 129.89 129.90 129,90 129.89 129.89
10000 10200 *000 3900 10400 10600
A
* Show Trades * Show Bid / Ask Quotes Clear display 129,89 129.89 129.89 129.89 129.89 129.89
18100 18800 19800 20300 205C0 20700
Show Trades - W h e n checked, displays trades. Show bid / ask Quotes - When checked, displays bid and ask prices. Clear display - Clears the window.
Graphical User Interface 5 ו ו CATEGORIES
AmiBroker has the ability to assign ticker symbols to different categories, and then use categories as filters, selecting symbols based on membership in a particular category. There are two types of categories: 1. Those with mutually exclusive membership: groups, markets, sectors, and industries. This m e a n s that a symbol m u s t belong to exactly one group, one market, one sector, and one industry at a time. 2. Those with free membership: watchlists, favorites, and indexes. This m e a n s that a symbol may belong to any n u m b e r (including zero) of watchlists, and, optionally, belong or not belong to the favorite and index categories. GROUP - M A R K E T - SECTOR - INDUSTRY
For stocks, each stock belongs to one industry. It belongs to one sector based on its industry and on an assignment table - each industry belonging to exactly one sector. For example: GM (General Motors) belongs to the "Auto & Truck M a n u f a c t u r e r s " industry, and this implies that GM belongs to "Consumer/Cyclical" sector. AmiBroker can h a n d l e up to 32 sectors and up to 256 industries. The predefined list of industries and sectors is in A p p e n d i x B. You can define your o w n sectors and industries to use in place of those. For more details, see the AmiBroker User's Guide. CATEGORY MEMBERSHIP
Categories are displayed u n d e r the Symbols Tabbed menu. Although the icons look like normal folders used by W i n d o w s Explorer, categories do Not work like folders. The difference is f u n d a m e n t a l . In the W i n d o w s file structure, a file appears only once in a given tree as a leaf. In the AmiBroker symbol trees, any symbol may show up multiple times - once as a leaf in every category to which it belongs.
1 178
Introduction to AmiBroker
A single symbol belongs to m a n y categories at the same time. For example AAPL (Apple Inc.) will belong to these categories: •
All
•
Stocks g r o u p
•
Nasdaq market
•
Information sector
•
Comp-Computer Mfg industry
A n d it m a y belong to these categories: •
Any n u m b e r of watchlists
•
Perhaps the favorite category
•
Perhaps the index category
The special category called All lists all symbols present in the database. CATEGORY ASSIGNMENT
You can assign a symbol to an industry using either: • •
Symbol Pull-down m e n u > Information, then edit the Categories you wish to change. Symbol Pull-down m e n u > O r g a n i z e assignments, then use the Assignments Organizer.
The first m e t h o d is fine if you w a n t to change single symbol settings. The latter is better if you w a n t to move multiple symbols from one category to another.
Graphical User Interface
וו5
W A T C H LISTS
Watchlists are lists of symbols that have s o m e t h i n g in common. Watchlists are used to define the universe of symbols that should be used w h e n procedures are run. You will use t h e m a lot, and there are m a n y techniques for m a n a g i n g them. Examples of watchlists you might use are: •
Components of the S&P 100.
•
Components of the NASDAQ 100.
•
Sector ETFs.
•
C o m m o d i t y ETFs.
•
Stocks that passed your favorite filter.
Watchlists differ from other kinds of categories (groups, markets, industries, sectors) in that you can assign a single symbol to more than one watchlist - in fact, to as m a n y watchlists as you w a n t to. Symbol* Layouts j Layers [ Charts j Symbols * CJ All & LJ Markets '*j LJ Groups ii (_J Sectors & LJ Watch lists i D List 2 ©•D30נם $ • • • • • » • • • • • • • • • • • •
MMM AA AXP AIG T BAC BA CAT CVX C KO DD XOM GE GM HPQ HD INTC IBM
The m e m b e r s of each watchlist are s h o w n in the symbol tree. O p e n the Symbol Tabbed m e n u a n d expand Watch lists. Watchlists are associated with a single database. They are one symbol per line, and have the file extension .tls. The .tls files can also be opened by AmiQuote. They are stored as text files in the Watchlists folder in the subdirectory of the database they are used with. The folder contains any n u m b e r of .tls files defining watchlists themselves; and it also contains the file n a m e d index.txt that defines the order of watchlists. You can create as m a n y watchlists as you want, and n a m e them whatever you want. You add your o w n .tls files to that subdirectory, and AmiBroker will automatically u p d a t e index.txt, and add any new watchlists it finds.
All watchlists are local, there are no global watchlists. If you w a n t to use the same watchlist with several databases, copy the .tls files to those database subdirectories. When you open the default symbol tree and e x p a n d the watchlist category, you will see 64 watchlists, n u m b e r e d 0 t h r o u g h 63, all initially empty. You can populate these and r e n a m e them, or you can add n e w watchlists.
Introduction to AmiBroker
1 180 A D D I N G WATCHLISTS
You can add watchlists in several ways: •
Use the Symbol m e n u > Watch List > N e w Watchlist.
•
From the watchlist context menu.
Symbol ! Analysis
!00Is
Windc j layouts ' Layers j Chart?- i Symbols
New...
J NASDAQIOO • ATVID • ADBE • AKAM • ALTR
Delete Split...
ft
Merge,.. Find
e
Information.,,
m
Quote Editor...
F3
Favourites
>
Wairh list
•
Add selected symbol...
Real Time Quote
•
Remove selected symbol...
Categories..,
lype-in symbols.,,
Organize assignments...
Import...
Calculate composites...
Export... Erage (make empty)... Sort alphabetically...
• • • • • • • • • • •
I AN A('• AF AA AN AC. Bill BB Bli BR
Add to favourites Erase favour ities Web Research Add selected symbol Remove selected symbol Type-in symbols,,. Import,.. Export.., Erase (make empty)
Hide empty watchlists New watchlist... Delete watchlist...
Sort alphabetically Hide Empty watchlists New watchlist... Delete watchlist
REMOVING WATCHLISTS
Similarly, you can remove watchlists in those same ways using the Delete watchlist option. If these m e n u items do not appear, use the Tools > Customize > Options, then press the Reset button for new m e n u items to appear.
Graphical User Interface
5וו
A D D I N G SYMBOLS TO WATCHLISTS
You can add a single symbol to a watchlist by right-clicking the symbol in the symbol tree (in any of the categories except watchlist) and choos־ ing Watch List > Add selected symbol. Symbols
• GMKT (Daily) X
| Layouts j Layers "׳harts ןSymbols ;
| GMKT - Daily 7/30/2008 Open 21 65. Hi 2
i •־Technology :.!if 03 '3 O Internet-Retailing v AAC • ABTL • AMTD • AMZN • BFLY • BIDZ 0 DGC • DSCM • EBAY • ETFC • EXPE * Add to favourites
• HC
Web Research
IN • ן • • Kl • LC • LC
Add selected symbol
—־
Remove selected symbol Type-in symbols,,. Import,,,
Delete
Export... Erase (make empty) Sort alphabetically < ׳Hide Empty watchlists New watchlist.,, Delete watchlist
A watchlist selector w i n d o w will appear. Select w a t c h list(s) List• List 1 List 2 List 3 List 4 ListS List 6 List 7 List 8 DJ30 Russell 1000 Russell 2000
|
Cancel Hint: You can select multiple fists here by holding SHIFT/CTRL key.
|
Select the list you w a n t to add the symbol to. Note that you can add one symbol to multiple lists in one operation by holding the CTRL key while clicking on the list items. After clicking OK the selected symbol appears in the watchlist(s).
Introduction to AmiBroker You can also type-in symbols directly into the watchlist using Symbol > Watch list > Type-in. You will be asked to select a watchlist, then to type in the list of symbols, each symbol separated from the next by a comma. Use uppercase letters. Symbol I Analysis %
lools
Wind )w
Help
New...
&
! ^ /ft ^ ^
Enter one or more tickers to a d d ( c o m m a separated)
;; Delete £
Split...
AA. AXP. GM. F. IBM
,'•I Merge... (Mil Find
F3
O
Information...
03
Quote Editor,.. Favourites
•
Wafch li*t :
>
1 Real Time Quote
Add selected symbol.,.
•
Remove selected symbol...
יCategories,,,
Type- in sy mbo Is... •
Organize assignments.., | Calculate composites..,
;; Import... I
Export... ןErase (make empty),.. Sort alphabetically...
j"*"! Hide empty watchlists New watchlist... I Delete watchlist..,
You can also right click the watchlist n a m e in the workspace tree to t y p e in symbols directly into the watchlist. S LJ Watch lists a OS®* Add selected symbol Remove selected symbol Type-in symbols... Import,,, Export... Erase (make empty) Sort alphabetically * Hide Empty watchlists New watchlist... Delete watchlist
SORTING SYMBOLS IN A WATCHLIST
1 €3 I I P *
Add selected symbol Remove selected symbol Type-in symbols... Import.,. Export.,, Erase (make empty) Sort alphabetically
׳׳Hide Empty watchlists New watchlist.., Delete watchlist
Watchlists remember the order in which symbols were added. If you sort a result list in some order and then you ,, add symbols to watchlist ״the order will be kept in the watchlist. You can ask AmiBroker to sort the watchlist into alphabetic order. Select the watchlist, right-click, and select Sort alphabetically.
Graphical
User
Interface
5
ו
ו
REMOVING SYMBOLS FROM WATCHLISTS
Removing symbols from the watchlist is as easy as a d d i n g them. Rightclick the Watchlist n a m e and select Remove Selected Symbol. & U 1 List 2 •
QQQQ
• 0. » U D330 « Mr • A^ • A} • AI •
• » • •
Add to favourites Erase favour ities
|
' H B™־׳ Ci C\
Add selected symbol Remove selected symbol Type-in symbols...
[
Import...
• c —
Export,,,
• • • • • • • •
Erase (make empty)
KO DD XOM GE GM HPQ HD INTC
Sort alphabetically * ׳Hide Empty watchlists New watchlist,,, Delete watchlist
ERASING WATCHLISTS
Sometimes you may w a n t to clear (or erase) the whole watchlist. Using the Symbol menu, Watch list, Erase (make empty) option. In the watchlist selector w i n d o w mark the list(s) you w a n t to clear and click OK. You will be asked to confirm. Symbol [analysis
%
Iools
yVindow
New... Qelete
?'
, **r I asip
£
Split... Merge...
M
Fnd
O
Information.,.
F3
Quote EditDr... Favour ites
•
&ateh list
•
Add selected symbol.,.
Real Time Quote
Remove selected symbol.,.
Categories,,,
lype-in symbols.,.
Organize assignments.
import,,.
Calculate composit8s..
Export,.. Sort alphabetically... E
Hide empty watchlists New watchlist... Qelete watchlist.,,
י
1 184
Introduction to AmiBroker
H I D I N G AND U N H I D I N G EMPTY WATCHLISTS
By default all watchlists, including those that have no symbols in them, are s h o w n in the symbol tree. You can hide e m p t y lists. Right-click on any symbol or watchlist n a m e in the symbol tree, and select ״Hide Empty watchlists". To un־hide, use the same m e n u and remove the check mark. 1• Ci List 4 , :
Q List 5 •DI List 6 ׳call® LJ List:
S C3 DJ31
Add selected symbol R e m o v e selected symbol
p r
Type-in symbols...
•
׳
Import...
•
׳
Export...
•
1
• '
Erase (make e m p t y )
4> [ • >
S o r t alphabetically
& c
Hide Empty watehlists
^
New watchlist,..
^ y
Delete watchlist
Kjg>g*|f
USING WATCHLISTS IN A U T O M A T I C ANALYSIS W I N D O W
The results of scanning, backtesting, and exploration can be added to a watchlist. After r u n n i n g your analysis, you will have a list of results. Sort those results as you wish. Select the lines of the symbols you want in a watchlist. (The lines do not need to be contiguous. Hold the CONTROL key while clicking the m o u s e on any lines in any order.) Rightix Automatic Analysis - Example.afl Formula tile !C:\Program Files\AmiBroker\Formulas\Systems\Example.afl : A p p l y to
Range
;
O ® ייs y m b o l s
O oil quotations
!
Q current s y m b o l
ן
®usefilter
[
ן
o חlast quotations De<
•
Run every
•
Wait tor backfill ( R T only)
( • ) חlost d a y s
O 'rom:
| Back Test n -
[ 9/ 1/2004 f 1/
־־
5
—
״
»
־ ן Equity
1/2006
[ I ] S y n c chart o n s e l e c t Results
CGRB ICO <
13.574.38 30.897.31
13.57 30.98
Add selected results to watch list.. Replace watch list with the results. Replace watch list with selected results...
:(1978 rows) Prolit •-17810.38 (-1 7 8 1 ' / . ) , C A R - - 1 3 ;
Clear results list Copy
ן ן
S c a n
Ex
•*,j j ן ך
Pl0fe
Optimize ־ — ־ Settings...
Graphical User Interface
5וו
clicking brings up a dialog box that gives several choices. The four we are interested in at this time are: •
Add all the results to watch list. There are 1978 rows. Selecting this option will add the symbols for all 1978 rows to the watchlist. Duplicates will be eliminated.
•
Add selected results to watch list. This option will add eight symbols to the watchlist. Duplicates will be eliminated.
•
Replace watch list with the results. Make the watchlist empty, then save the 1978 symbols in it. Keep the symbols in the order they are in the results window.
•
Replace watch list with selected results. Make the watchlist empty, then save the eight symbols in it.
After you have m a d e your choice from a m o n g these four options, you will have an o p p o r t u n i t y to select the watchlist(s) to receive the symbols.
m ListO List 1 List 2 List 3 List 4 List 5 List 6 List 7 List 8 DJ30 Russell 1000 Russell 2000
Cancel Hint: You can select multiple lists here by holding SHIFT/CTRL key.
Introduction to AmiBroker
1 186
IMPORT A W A T C H L I S T FROM A FILE
Using the Symbol menu, choose Watchlist, then Import. Select the watchlist you w a n t to use. Ignore the file button ־you cannot change it. S y m b o l ! analysis
V
3:
lools
B!ndow
New...
Uelp
י ׳
Delete
» ar ! i i f i l ־£
List 1 List 2 List 3 List 4 List 5 List 6 List? Lists DJ30
Split... Merge...
H O
Find
F3
Information... Quote Editor... Favourites
>
'Watchlist Real Time Quote ••ן
»j
Add selected symbol,..
•
Remove selected symbol...
Categories...
lype-in symbols...
Organize assignments.,,
־F Export..,
Calculate composites,..
•
Select watch list(s)
•״--יי ״י*׳יו'״״״ ' י
[
Russell 1000 Russell 2000 Import/Export from/to:
®Fife. e t e r n a l 43ts s a r c t j
Erase (make empty)... Sort alphabetically... Hide empty watchlists New watchlist... Delete watchlist...
1. Navigate to the file you w a n t to import. 2. Select that file. 3. Click Open.
Look in:
m
My R e c e n t Documents
CB
Desktop
My Documents
a st יש
! 3 AmiQuote Q Down load $ DJINDUSTRIALS. tls DJTRANS.tls $ DJUTIL.tls FTSElOO.tls $ NASDAQ 100.tls NEWTICKERS. TLS ® R1000FULLNAME. TLS ® RUSSELL1000. TLS $ RUSSELL2000. TLS 3 ׳SP100,tls ^ s s s n i z a —
Si
My Computer
My Network Places
File n a m e :
!SPSectorETF.tls §
Files of type:
[Ticker List ("־.tls;*lst)
Cancel
Hint: You can select multiple lists here by holding SHIFT/CTRL key.
&
\
|
Graphical
User
Interface
5
ו
ו
The file type dialog shows the file t y p e that can be imported without need to convert t h e m first - .tls, .txt, .csv, and .1st. The first three should have one ticker symbol per line a n d no other fields. .1st files are QuotesPlus standard, comma separated list files that have the ticker symbol in the first column and some additional data in r e m a i n i n g columns. AmiBroker reads just first column and ignores the rest.
You can also start the import process by right-clicking the n a m e of a watchlist in the symbols tree. The m e n u that comes up has an " I m p o r t " option. EXPORT A WATCHLIST TO A FILE
Choose Symbol > Watchlist > Export. Select the watchlist you w a n t to export. Select the directory, file name, and file extension for the exported data. The file format will be ASCII, with one ticker symbol per line. You can also start the export process by right-clicking the n a m e of a watchlist in the symbols tree. The m e n u that comes up has an "Export" option. RENAMING WATCHLISTS
The formal way begins by pulling d o w n the Symbols m e n u and selecting Categories. Symbol | Analysis
!00Is
Organize assignments... Calculate composites..
yvindc
Introduction to AmiBroker
1 188 In the categories box:
1. Select the Watch lists tab. 2. Select the list to be renamed. 3. Click Edit Name. 4. Type in the n a m e you want, say Passed Test. 5.
Click OK.
Symbols
Q IBM (Daily) x IBM - Daily 7/30/2008 Open 126 4 2 . Hi 128. Lo 127.08, Close 128 86 (O S ,)Vol 5.779.400 N
; Layouts i Layers : Charts- : Symbols m C l AH ii! LJ Markets i£ CJ Groups 8s CJ Sectors 1i iU Watch lists Sp Q| LlstO i • List 2 it! D 030נ ® LJ Russell 1000 ftO Russell 2000 m CJ SPIOO m LJ NASDAQ 100 afr. Q SPSectorETFs S CJ Favourites • QQQQ £ SPY is CJ Indexes
J!׳t
Markets : Groups
Sectors : Industries Watch lists *
j Name j • [MB P " : • List 1 ^ ^ ־ ־s ^ " — ^ — • — ־
j : ! j I i ! ! ! I
• List 3 ^ ^ ^ ^ י י י •$ List A • List 5 • List 6 * List 7 • List 8 • DJ30 # Russell 1000 • Russell 2000 •> SP100 • NASDAG100 • SPSectorETFs # List 15 • List 1 6 ^ ^ ׳ Edit n a m e
)f
The watchlist is renamed. Symbols j Layouts | Layers | Charte• J Symbols ts Q All e Cj Markets is CJ Groups B D Sectors 2 CJ Watch lists €3 Passed Test i D List 2
Graphical User Interface
5וו
The informal way uses no menus, just W i n d o w s techniques. 1. Using the Symbol Tabbed menu, expand Watchlists. 2. Left-click the list you want to rename. 3. Left-click again, but not so quickly that W i n d o w s interprets it as a double-click. 4. The n a m e of the watchlist will be selected. | layouts ןLayers : Charts i Symbols י is! םAll IB CJ Markets ® CJ Groups Si-LJ Sectors a D Watch lists Si CJ Passed Test * U DJ30 ffi D Russell 1000 m CJ Russell 2000 M U SPIOO (£ D NASDAQ 100
5. Type in the n a m e you want. 6. Press Enter or click on any other watchlist name. 7. The watchlist is renamed.
layouts ! Layers S Charts j Symbols j 1 C3 All ! D Markets i LJ Groups 1-03 Sectors ׳CJ Watch lists ® CJ Passed Test Hi m Ci DJ30 lis D Russell 1000 i D Russell 2000 IS U SP100
Introduction to AmiBroker CHARTS (FORMULAS)
There are two t y p e s of tools that can be placed on charts: •
Those that can be placed a n d adjusted manually. They appear on the Toolbars and on the Insert menu, and were discussed in the previous section.
•
Those that are based on formulas, are computed, have parameters that specify their relationship to the charts they are applied to, and are adjusted using their parameters rather than manually. A set of these tools has been pre-programmed, is ready-to-use, and appears on the Charts tabbed menu. To m i n i m i z e confusion, the tools located on the Charts tabbed m e n u will be referred to in general as formulas and indicators. This section discusses basic operations of these tools.
An earlier section (page 190) briefly described the Charts tabbed m e n u and its context menu. A n d a later section (page xxx) will describe creating your o w n formulas and indicators using the AFL language. BASIC OPERATIONS
Insert ־Insert a New Indicator To display a n e w indicator in a separate pane, either: L_J A v e r a g e s C3 Bands 0 3 Basic C h a r t s / Open Interest (futures) / faTj!^^ / P r i i H H I i n H I n s e r t Linked / Pri! Overlay Re: f Vo Analysis / Vol / vo Edit 8• t _ l Gusto( Rename is CJ Equity! Delete C 3 Includ: 8• 03 Indica; New g t _ j Q T S ej S CJ Q T S EJ si •03 S y s t e fr / Example f ExampleRotational /
•
Using the Charts tabbed menu, locate the indicator you want, then double-click the indicator's name.
•
Using the Charts tabbed menu, locate the indicator you want, then right-click the indicator's n a m e bringing up the context menu. Click Insert.
Using either method, a n e w pane will be ereated, the indicator inserted and displayed, and a parameters dialog opened. If you wish, you can change the properties of the indicator, such as the color of its plot or the values of the parameters used in its calculation.
See Example 3, page 65, for more information and screen capture images.
Graphical User Interface
ו ו5
Insert Linked The difference between Insert a n d Insert Linked is: When the Insert method is used to place an indicator in a pane, a copy of the indicator is placed. Any changes m a d e to the original of the indicator will not affect the copy already placed. When the Insert Linked m e t h o d is used, the original code is placed. Any changes m a d e to the original code will be reflected in the indicator already placed. Delete an Indicator Right-click the p a n e the indicator is in, bringing up the context menu. Choose Delete indicator, then Click the n a m e of the indicator to be deleted.
Parameters Edit formula x
E
Close Intraday
•
Daily view
w
Weekly view
m
Monthly view Pane
•
Template
•
Symbol Link
•
Interval Link
•
Delete indicator
•
Price EMA
!;
[f
Drag and Drop 1. Load the price series you w a n t to study in a pane. 2. Make that pane the active pane. 3. O p e n the Charts tabbed menu. Locate the indicator or formula you w a n t to use. 4. Drag that indicator onto the price series and d r o p it. The cursor t u r n s into a drag and d r o p cursor whenever it passes over any pane where d r o p p i n g it would be m e a n i n g f u l . 5. Adjust the placement, properties, a n d parameters as necessary.
Introduction to AmiBroker Overlay One Indicator on Another Locate the indicator you w a n t to overlay in the Charts tabbed menu. Left-click the n a m e of the indicator, drag the indicator to the desired pane, hover over the series you w a n t the indicator applied to, and drop. A properties dialog box will open. Verify that the indicator is being applied properly. For example, create a 15 day m o v i n g average of the 14 day RSI: 1. Using the Charts tabbed menu, select Price, double-click, creating a n e w p a n e with the price series in candlestick format. 2.
Using the Charts tabbed menu, select RSI, drag it to the pane w i t h the n e w price series, d r o p it.
Q Q Q Q - Daily 8 / 1 4 / 2 0 0 8 O p e n 4 7 . 5 4 , Hi 4 8 . 4 6 , Lo 4 7 . 4 9 , C l o s e 48 25 (1 2 % ) R S I ( 1 5 ) = 62
2008
1
Feb
Hviar
3.
;
P
M
f
Price field : C l o s e
Style
Ouri
t
B EMA
Color
lay
Qui
׳Aug'
Using the Charts tabbed menu, select EMA, drag it to the pane w i t h the price and RSI, d r o p it. A Properties dialog box will open. There are two series that the moving average could be applied to - Close and RSI. Select RSI.
Parameters : Axes & Grid j
Periods
lApr
Open High Low Close Average Volume Openint • Close
s - ! M
1 I
Graphical
User
Interface
5
ו
ו
The pane shows the price, the RSI, a n d the m o v i n g average of the RSI. Q Q Q Q - Daily 0 / 1 4 / 2 0 0 8 O p e n 47 54, Hi 4B 4 6 , Lo 47 4 9 , C l o s e 40 25 (1 2 % ) R S I ( I S ) = 65 66.0
60 0
BBBn
119 0 42.0
36 0
30.0 1
1
F e b Mar fApr iMay • u n Qui !Aug 2
0
0
0
־
־
Also see Example 3, page 65. Change Parameters Right-click the pane the indicator is in. The context m e n u will appear, click Parameters. The Properties box will appear. Find the parameter you w a n t to change, and change it. For example, to change the example just above to an 11 day RSI with a 3 day moving average: The properties box shows the indicators in that p a n e that have changeable parameters. Properties of: Price Parameters
Axes 8 Grid
0 Price Color
• Block
Style •
RSI Periods
15
Color
• Red
Style •
EMA Price field
RSI(15)
Periods
15
Color
•
Blue
Style
Change the Period associated with RSI to 11, and the Period associated with EMA to 3.
1 194
Introduction to AmiBroker
Q Q Q Q - Daily 8 / 1 4 / 2 0 0 8 O p e n 4 7 . 5 4 , H i 4 8 4 6 , L o 4 7 4 9 , C l o s e 4 8 2 5 ( 1 . 2 % ) RSI( 11) = 6 7
2008
1
Feb
r
Mar
fApr
^
1
Jun
TJj
Also see Example 3, page 65. A D J U S T THE SCALE OF AN I N D I C A T O R
If you have a p a n e with t w o (or more) indicators, and they use different scales, one of t h e m will be difficult to interpret. To give an indicator its o w n scale: 1. Right-click in the pane w i t h the indicators. The context menu will appear. 2. Click Parameters. The Properties box will appear. Resize the box so you can see the details of all the indicators. 3. Click Style - the Style parameter has an option to give each indicator its o w n scale. 4.
Click OwnScale for each of the indicators you want to change. Properties of: Price Parameters I Axes & Grid i B Price Color
•
Black
Style םRSI Periods Color
15 •
Red
•
Thick
*
Style 0 MACD Fast avg
•
Dashed
Slowavg
•
Hidden
Signal avg
•
NoLabel
MACD color MACD style Signal color
•
Blue
Histogram color
•
Black
Histogram style
Histogram NoLabel
Signal style
Graphical User Interface
5וו
AVERAGES
___
Charts j Symbols j Layouts j Layers : Charts : ai C3 Averages / DEMA - Double Exponential Moving Average / DispMA - Displaced Moving Average / EM A - Exponential Moving Average / Linear Regression - Least Squares Moving Average / MA - Simple Moving Average / TEMA - Triple Exponential Moving Average / TSF - Time Series Forecast / Wilders - Wilders Moving Average / WMA - Weighted Moving Average &-G3 Bands
MA - Simple Moving Average The simple moving average is the average of as m a n y bars as are specified by the Period. This m o v i n g average has a lag of half of the length of the period. That is, a 15 day simple m o v i n g average is the average of 15 days, centered 8 days ago. DispMA - Displaced Simple Moving Average The displaced simple moving average is a simple m o v i n g average displaced in time. If the displacement is positive, the average is moved forward in time and plotted to the right of where the undisplaced simple moving average would be. If the displacement is negative, the average is moved backward in time and plotted to the left of the undisplaced moving average. The screen capture shows a 15 day simple m o v i n g average and a 15 day moving average displaced by -8 days. This illustrates the effect of lag.
Simple Moving Average MA(C, 15)
Simple Moving Average Displaced -8 days
1 196
Introduction to AmiBroker
EMA - Exponential Moving Average The exponential moving average is the s u m of two terms - one the contrihution of the latest bar of data, the other the contribution of the value of the indicator at the previous bar. The definition is recursive. The smoothing factor, a, determines h o w important the most recent data is and h o w fast the effect of earlier data dies away. Today's value = a * Today's data + (1-a) * Yesterday's value We can talk about exponential m o v i n g averages having a length just as simple moving averages do. The relationship between the n u m b e r of days, n, in the exponential average and the smoothing factor, a, is: a = 2 / (n + 1). EMA[i] = a * C[i] + (1-a) * EMA[i-l], For a 15 day exponential m o v i n g average, a = 2/(15+1) = 0.125. Today's n e w data is weighted 12.5% and the value the exponential moving average h a d yesterday is weighted 87.5%. The chart below illustrates. DEMA ־Double Exponential Moving Average The DEMA uses a differencing technique to remove lag from the indicator. Note that it follows the changes in price more quickly (that is, it has less lag), but it is less smooth. There is a trade-off between lag and smoothness. TEMA - Triple Exponential Moving Average The TEMA uses a more extreme technique to remove even more lag. The screen image compares the three exponential moving averages, all of which use 15 as the value for the period.
Exponential Moving Average EMA(C,15)
Double Triple Exponential Exponential Moving Moving Average Average DEMA(C, 15) T E M A ( C , 1 5 )
Graphical User Interface
5וו
Linear Regression - Least Squares Moving Average The linear regression indicator computes and plots the end point of a linear regression using the n u m b e r of data points given as a parameter. The image shows a 15 period linear regression. 51. D
׳Q Q Q Q - Daily 8 / 1 4 / 2 0 0 8 O p e n 47 54, Hi 48 4 6 , Lo 47 4 9 , C l o s e 48 25 (1 2 % ) Linear R e g r e
50.0 p 9
0
• 1 47 0 46 0 45 0 44 0 43 0 42 0 2008
'Feb
׳Mar
lApr
fMay
•un
]סכי
41 0
fAmf־
TSF - Time Series Forecast The time series forecast indicator computes and plots the end point of a time series forecast using the n u m b e r of data points given as a p a r a m eter. The technique is very similar to the linear regression method. The image shows a 15 period time series forecast. Q Q Q Q - Daily 8 / 1 4 / 2 0 0 8 O p e n 4 7 54, H i 4 8 4 6 . L o 4 7 4 9 , C l o s e 4 8 2 5 ( 1 2 % ) T S F ( C I 0 s e . 1 [I-
5 11. 0
[
50_0 10
S SP E L S H 3.0 i 0׳ 47 0 46 0 45 0 44 0 43 0 42 0 2008
1
41 0 Feb
Hta
lApr
fMiy
fj^j
Hjuj
׳Aug"
Wilders ־Wilders Moving Average Wilders moving average for a given period, n, is equivalent to an exponential moving average with period 2*n־l. The image shows a 15 period Wilders moving average. Q Q Q Q - Daily 8 / 1 4 / 2 0 0 8 O p e n 4 7 5 4 H i 4 8 4 6 , L o 4 7 . 4 9 C l o s e 4 8 . 2 5 ( 1 . 2 % ) W i l d e r s ( C l n s
A/A
51 0 50 0
״
•
49 0 B8.0 ft•
47 0
Bio 450 44.0 43 0 42 0 2008
1
41 0 Feb
lMir
lApr
^ז
[j^
IjJj
1 ^ ־
Introduction to AmiBroker
1 198
WMA ־Weighted Moving Average The n-period weighted m o v i n g average gives the most recent data point a multiplying weight of n, the next older a weight of n-1, and so on to the nth older point getting a value of 1. The s u m of all the terms is divided by the s u m of all the weights. The image shows a 15 period weighted m o v i n g average. 51 0
Q Q Q Q - Daily 8 / 1 4 / 2 0 0 8 O p e n 4 7 5 4 . H i 4 8 4 6 , L o 4 7 . 4 9 , C l o s e 4 8 2 5 ( 1 2 % ) W M A ( C l o s e
500 H
/v
yV
,14־
2008
1
Feb
Hvlar
49 0 u
o
mgo
,1
'I
46.0 45 0 44 0 43.0 42 0
lApr
rjun
Tj^j
41 0
BANDS
1 Symbols j Layouts f Layers j Charts j i® C3 Averages ₪ LJ Bands / Bollinger Bands / Keltner Bands / Percent Bands iii -83 Basic Charts
Bollinger Bands Bollinger bands, developed and popularized by John Bollinger, are envelopes that s u r r o u n d the price bars on a chart. They are plotted some n u m b e r of s t a n d a r d deviations (often 2) away from a simple average (often 15 bars). The length of the m o v i n g average is also the n u m b e r of data points in the s t a n d a r d deviation. Because standard deviation is a m e a s u r e of volatility, the Bollinger b a n d s adjust themselves to the market conditions. They widen d u r i n g volatile market periods and contract d u r i n g less volatile periods. Bollinger b a n d s become moving standard deviation bands. The image shows Bollinger b a n d s 2.0 standard deviations away f r o m a 15 day simple m o v i n g average.
Graphical User Interface
5וו
Keltner Bands Keltner bands, developed by Chester Keltner, are similar to Bollinger bands in that they m e a s u r e and respond to volatility. Keltner b a n d s are set some multiple (often 2) of the ATR (Average True Range) from a simple moving average (often 15 bars). (See ATR in the description of functions.) The n u m b e r of bars in the ATR and the n u m b e r of bars in the average are usually the same. The image shows Keltner b a n d s 2 times the 15 day ATR away from the 15 day simple m o v i n g average.
Percent Bands Percent b a n d s are set a given percentage of the average above and below that average. The image shows percent b a n d s set 2 percent above and below the 15 day simple moving average.
Introduction to AmiBroker
1 200 BASIC C H A R T S
j Symbols j Layouts \ layers j Charts | !is D A v e r a g e s m
Bands
63 G3 Basic C h a r t s / Open Interest (futures) /
Price
/ Price (all in o n e ) /
Price (foreign)
/
Relative P e r f o r m a n c e
/
Volume
/
Volume (color)
/
Volume At Price
Open Interest Plots the o p e n interest field. Mainly used with f u t u r e s contracts. Price Plots the price series as candlesticks. Price (all in one) Plots the price series, Bollinger bands, and m o v i n g averages. Price (foreign) Plots the price series using the Foreign function. W h e n the price series is plotted u s i n g the Price function (as the two above) and the active symbol changes, the plot will change to reflect the n e w symbol. W h e n the price series is plotted using the Price (foreign) function, it will not change. This is u s e f u l for plotting a reference symbol, then cycling t h r o u g h a watchlist of symbols a n d viewing the comparison. In the image, SPY w a s plotted using Price (foreign), and given its o w n scale. Then the active ticker w a s changed to QQQQ.
Price ( f o r e i g n )
Graphical User Interface
5וו
Relative Performance Plots the relative performance of the issues plotted. Double-click Relative Performance. A Properties box will open. Type in the symbols you want to compare. The active symbol will be automatically added to the list. Click OK. Properties o f : Relative Performance Parameters
Axes S Grid
O Relative Performance Tickers
00Q0.AAPL|
| Reset all |
|
OK
A new pane will open and the prices of the symbols you entered plotted. All prices will be normalized to 1.00 at the left side of the pane. The lines show the relative performance for the period displayed in the pane. Scroll to see other time periods. Click t h r o u g h a watchlist to see other issues relative to those symbols you entered.
Volume Volume opens a n e w pane and plots the volume. Volume (color) Volume (color) opens a n e w pane and plots the volume using colored bars. If the close w a s higher than the open, the bar is green, otherwise red.
1 202
Introduction to AmiBroker
Volume at Price Plots a histogram of volume per price. The p a n e n e e d s to have both price a n d volume. This already exists in the top pane, but that is crowded. To display volume at price in a pane of its own: 1. Double-click Price. A n e w p a n e will open with the price plotted. 2. Right-click Volume, then click Overlay. The volume will be added to the pane. 3. Right-click Volume at Price, then click Overlay. A properties box will open. Properties o f : Price ParametErs j Axes a Grid! B V o l u m e At Price 300
Lines Width
I 50
Color
•
.-ל
Side
Lett
Z־order
Behind
־־
Red
| Reset all j
ji
OK laiil
4.
Adjust the parameters as you w a n t them. Lines specifies the n u m b e r of histogram bars. Width specifies h o w far across the p a n e the longest histogram bar reaches. Click OK. MSFT- Daily 8/22/2008 Open 27.23, Hi 27 88, Lo 27 22. Close 27 B4 (2 4%) Volume() = 47 34 0 32.D 30.0 3* 26 0 2008
,
Mar
!Apr
'May
Uim
• J u l
,
A u g
Graphical User Interface
5וו
CUSTOM
The Custom category is a category that you can use to store whatever formulas you want. The Customs category w a s used to keep the examples used in chapter 3 of this book organized. Symbols j Layouts j Layer•׳: j Charts j B• CJ !•:'_] B Cl -i CJ
tU
Averages Bands Basic Charts Custom / AlertlfTest / ATC Trading Figure_17_ll / ExamplelO / Example5 / Example6 / Example6A / Example6B / Example6XB / Example7A / Example7B / Example8 / Example8A f Example8B / Liquidity / RelativeStrength / RelStr42 f SimpleSystem / SimpleSystem 1 Equity
EQUITY
Individual Individual Equity plots the equity curve using the data f r o m the most recently run trading system. Double-click Individual. A properties box will open asking if you w a n t to display Buy a n d Hold. Click OK. The formula plotted here has been changed to show the equity as a line. The default plots as an area.
1 204
Introduction to AmiBroker
IS and OOS Equity This formula is used with the walk forward testing. Two lines are plotted. O n e is the equity curve that results f r o m taking all the In-Sample trades. The other is the equity curve that results from taking all the Out-of-Sample trades. Use of this formula is described in Chapter 9, Analysis. Portfolio Portfolio Equity plots the equity curve f r o m the most recent backtest. The plot shows w h e n positions are held (blue color), w h e n cash is held (green color), and d r a w d o w n (brown color). Also see Example 7, page 87.
1
1
'2005
'2DD6
1 1 1 1
Include The Include category holds code that can be included with an AFL prog r a m at the time it is r u n .
Graphical User Interface
5וו
INDICATORS
An extensive list of formulas and indicators that can be applied to charts. Symbols j Layouts j Layerg, ; Charts [ si L_] Averages e - G 3 Bands % C_j Basic Charts v, £1 Custom t r Q i Equity L.3 Include g LJ Indicators / ABI - Absolute Breath Index / AccDist - Accumulation Distribution / AD Price - Williams Advance Decline of Price / AD Ratio - Advance Decline Ratio : / ADLine - Advance Decline Line / ADX - Directional Movement Index / ASI - Accumulation Swing Index / ATR - Average True Range / Beta / Breadth Thrust / CCI - Commodity Channel Index / Chaikin - Chaikin Oscillator / DPO - Detrended Price Oscillator / DVI - Daily Volume Indicator / EOM - Ease Of Movement / HPI - Herrick Payoff Index / MACD - Moving Average Convergence Divergence / Market Facilitation Index / Mass Index f MFI - Money Flow Index / Momentum / NVI - Negative Volume Index / OBV - On Balance Volume / OSCP - Price Oscillator / OSCV - Volume Oscillator
/ PVI ־Positive Volume Index / PVT - Price Volume Trend / RMI - Relative Momentum Index / ROC - Rate Of Change (%) / RS ־Comparative Relative Strength / RSI ־Relative Strength Index / RSIa ־Relative Strength Index (custom array) / RWI - Random Walk Index / RWIHI - Random Walk Index of Highs / RWILO - Random Walk Index of Lows / SAR - Parabolic Stop And Reverse / STIX / Stochastic %D / Stochastic %K / Stochastic Momentum / TRIN ־Traders Index / TRIX - Triple Exponential f TVI ־Trade Volume Index / Ultimate - Ultimate Oscillator / Volatility (Chaikin) / Volatility (Wilder) / Volume Oscillator / William's % R / ZIG - Zig-zag Indicator l® C1 IntroBook ffi Q QTS Book
ABI - Absolute Breadth Index Absolute Breadth Index is an indicator developed by N o r m a n Fosback. It is calculated by taking the absolute value of the difference b e t w e e n the n u m b e r of advancing issues and the n u m b e r of declining issues. Any universe may be used. Large n u m b e r s suggest volatility is increasing, which may precede significant changes in stock prices in the coming weeks. The formula s h o w n below has been adapted to use the Quotes Plus symbols for the NYSE n u m b e r of advancing issues a n d n u m b e r of declining issues. function {
AbsoluteBreadthlndex()
return abs((Foreign("!NY-A","C")
-
Foreign("!NY-D","C")));
} P l o t ( A b s o l u t e B r e a d t h l n d e x ( ) , _DEFAULT_NAME(), ParamColor("Color", ColorCycle ) );
1 206
Introduction to AmiBroker
The chart shows the ABI plotted along with !NYA, the NYSE Composite Index. !NY/
1
r
I 1
J
t
H
Daily 5 / 1 8 / 2 0 0 5 O p e n 7 0 3 4 . 6 ' , Hi 71 22 6 9 , L o 7 034 64, C I • e 7 1 1 3 . 2 (1.1%) ABI()
m
November
•
'1 '2005
'February
'March
fi
'April
tfl]c|fg 1,600
1,200
BOO
400 i •May
0
AccDist - Accumulation Distribution A m o m e n t u m indicator that attempts to gauge supply and d e m a n d by d e t e r m i n i n g whether investors are generally accumulating (buying) or distributing (selling) a certain stock. It is calculated using the following formula: AccDistFn = ((Close - Low) - (High - Close)) / (High - Low) * volume; AD Price ־Williams Advance Decline The Williams Advance Decline, developed by Larry Williams, compares today's price and yesterday's price, adjusted by the true range and s u m m e d into a cumulative indicator. Practitioners suggest looking for divergences. AD Ratio - Advance Decline Advance Decline ratio divides the n u m b e r of advancing issues by the n u m b e r of declining issues. ADLine - Advance Decline ADLine is a s u m m a t i o n of the net daily difference between the n u m b e r of advancing issues and the n u m b e r of declining issues. AmiBroker uses a slightly improved formula that also takes into account the num-
Graphical User Interface
5וו
ber of u n c h a n g e d issues. The AFL formula for AmiBroker's ADLine is: D i f f e r e n c e = ( A d v l s s u e s ( ) - D e c l s s u e s ( ) )/ ( U n c l s s u e s ( ) + 1 D i f f S q r t = I I F ( Difference > 0, s q r t ( Difference ), - s q r t ( ־D i f f e r e n c e ) ); ADLine = Cum( D i f f S q r t );
);
ADX - Directional Movement ADX, average directional movement index, w a s developed by Welles Wilder and is intended to indicate the market trend. W h e n used with the up and d o w n directional indicator values, +DI and -DI, ADX can be used as a 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). ADX is widely referenced. Be certain to test it carefully before using it to trade. The ADX calculation introduces a lot of lag into the signals, and the trading system suggested is not profitable on most issues. The image shows ADX, PDI, MDI a n d a price series.
ASI - Accumulation Swing The accumulation swing index (ASI) is a variation of Welles Wilder's swing index. It plots a r u n n i n g total of the swing index value of each bar. The swing index is a value f r o m 0 to 100 for an up bar and 0 to -100 for a d o w n bar. The swing index is calculated by using the current bar's open, high, low and close, as well as the previous bar's open and close.
1 208
Introduction to AmiBroker
ATR - Average True Range Average True Range is a m e a s u r e of volatility. The daily (or single bar) m e a s u r e is the difference b e t w e e n true high and true low. True high is defined as the m a x i m u m of this bar's high and the previous bar's close. True low is defined as the m i n i m u m of this bar's low and the previous bar's close. The daily ATR values are typically averaged over a n u m b e r of bars. For example, ATR(15) is the average of the most recent daily ATR and the previous 14 values. The image shows a price series a n d the ATR(15) indicator.
AArt Ww V׳AA
XLB - Daily 8 / 3 1 / 2 0 0 4 O p e n 26 53, Hi 26.7, L• 26 4 3 , C l o s e 26.61 (0.3%) A T R ( 1 5 ) = 0.36
t
,
Aug ׳S e p
,
1
Oct
Nov
V>
'/wA,,
••m
י
Dec
'2004
1
Feb
1
Mar
24 0
\ j
v
j 1
26.0
׳Af/
:'
.V
27.1
lApr
1
May
1
Jun
Qui
22 0 1
Aug
Sep
Beta Beta is the slope of the regression line between the issue being studied a n d a base issue. It is the multiplier that gives the ratio of the change in the issue being studied for every change in the base issue. W h e n beta is greater t h a n 1.00, the issue being studied moves a greater percentage t h a n the base issue. W h e n beta is less than 1.00, the issue being studied moves a smaller percentage than the base issue. A u s e f u l analysis technique is to build a trading system using a base issue that is relatively s m o o t h and easy to model. Then m a k e the trades in some other issue, usually in the same i n d u s t r y or sector, that has a beta greater t h a n 1.00. Here is the code to compute beta. The base issue has been set to XLE, the S&P Sector ETF tracking the energy sector. //
betatest.af1
f u n c t i o n Beta( BaseSymbol, N ) { Chg = ROC( C, 1 ) ; ChgBase = ROC( F o r e i g n ( BaseSymbol, "C" ), 1
);
5וו
Graphical User Interface r e t u r n ( N * Sum( Chg * ChgBase , N ) - Sum( Chg, N) * Sum( ChgBase, N ) ) / ( N * Sum( ChgBase A 2 , N ) - Sum( ChgBase, N )
A
2 );
} symbol = ParamStr(
"Symbol",
"XLE"
);
P l o t ( Beta( symbol, P a r a m ( " P e r i o d s " , 21, 2, 100 ) ), _DEFAULT_NAME(), ParamColor( " C o l o r " , C o l o r C y c l e )
);
The image shows a plot of beta for the symbol DNR, D e n b u r y Resources, which has had a beta of greater t h a n 1.00 relative to XLE for most of the last two years.
1
J 1A 'S 1O 'N 'D '2807 'M 1A 'M 1J 1J 1A 'S '0 'N 'D '2008 'M 1A 1M 1J 1J
1
A
Breadth Thrust The Breadth T h r u s t indicator is a market m o m e n t u m indicator developed by Dr. Martin Zweig. The Breadth T h r u s t is calculated by taking a 10-day exponential moving average of the advancing issues divided by the advancing plus declining issues. Here is the NYSE composite a n d the breadth t h r u s t indicator.
1 210
Introduction to AmiBroker
CCI ־Commodity Channel Index The C o m m o d i t y C h a n n e l Index, developed by Donald Lambert, is based on the relationship b e t w e e n the asset's price, a moving average of the asset's price, and n o r m a l deviations f r o m that average. There are 4 steps involved in the calculation of a 20 period CCI: 1. Calculate the last period's Typical Price (TP) = (H+L+C)/3 where H = high, L = low, and C = close. 2. Calculate the 20-period Simple Moving Average of the Typical Price (SMATP). 3. Calculate the Mean Deviation. First, calculate the absolute value of the difference b e t w e e n the last period's SMATP and the typical price for each of the past 20 periods. Add all of these absolute values together and divide by 20 to find the Mean Deviation. 4. The final step is to combine the Typical Price (TP), Simple Moving Average of the Typical Price (SMATP), Mean Deviation, and a Constant (.015) in the following formula: CCI = ( Typical Price - SMATP ) / (.015 X Mean Deviation ) Here is a plot of the CCI and the NYSE Composite. INYA- Daily 8/22/2008 Open 0314 14. Hi 8388.79. Lo 8314 14. Close 8373.55 (0.7%) CCI(
״Jun
1
Aug 'Sep 1Oct
1
Nov 'Dec 120081Feb 1Mar 'Apr
1
May 'Jun
1
Jul
lAug"
Chaikin - Chaikin Oscillator The Chaikin Oscillator w a s developed by Marc Chaikin in the 1970s w h e n o p e n i n g prices were not widely available. It begins with an accumulation - distribution, then takes two moving averages.
Graphical
User
Interface
5
ו
ו
DPO - Detrended Price Oscillator The AmiBroker formulation of the detrended price oscillator is the closing price divided by the moving average of the price, w i t h the moving average shifted by half its period (to center it).
DVI - Daily Volume Indicator The daily volume indicator begins by computing the midpoint of the day's price as half the high plus low. It multiplies the difference b e t w e e n the close and the midpoint by the volume and accumulates that. EOM - Ease of Movement The Ease of Movement indicator begins by computing the midpoint of the day's prices as half the high plus low. A ratio of the volume to the difference between the high a n d low is computed a n d called the box size. Ease of movement is the midpoint change divided by the box size.
1 212
Introduction to AmiBroker
HPI - Herrick Payoff Index The Herrick Payoff Index indicator, developed by John Herrick, determines the a m o u n t of m o n e y flowing into or out of a f u t u r e s contract. The value increases a n d decreases with the average price for each day, with the trading volume, changes in the n u m b e r of open contracts, and changes in the average price. The value of each n e w day is combined with the value of the previous day using the multiplying factor. MACD ־Moving Average Convergence Divergence The MACD was developed by Gerald Appel in the 1960s. It is constructed in steps. 1. Take the difference b e t w e e n two exponential moving averages, often 12 days (or bars) a n d 26 days. This is the MACD line. 2. C o m p u t e an exponential moving average, often 9 days, of the MACD. This is the Signal line. 3. C o m p u t e the difference b e t w e e n the MACD line and the Signal. This is the MACD Histogram. 4.
Plot the two lines and the histogram.
QQQQ - Daily 12/28/2005 Open 41 06. Hi 41 23, Lo 40 87, Close 40 89.(:0.1%) MACD( 12. Af.
-0 20 -0 40 -0 60 Nov
1
2005 1Feb
1
Mar
lApr
1
May
'Jun
Qui
[Aug
1
Sep
1
Oct
1
Nov
1
Dec
Market Facilitation Index The Market Facilitation Index w a s developed by Bill Williams. It is computed as the price difference (high m i n u s low), that divided by volume. AmiBroker plots it as it would plot volume, but with the bars colored by the value of the Market Facilitation Index.
Graphical
User
Interface
5
ו
ו
Mass Index Mass Index begins by computing the difference b e t w e e n the high a n d low, taking an exponential moving average of that, then taking another exponential moving average, and finally accumulating those values. MFI - Money Flow Index Money Flow Index is essentially a volume-weighted RSI. The code to compute MFI is: NumDays = 14; T y p i c a l = ( H + L + C ) / 3; MF = T y p i c a l * V; PMF = Sum( I I f ( T y p i c a l > Ref( T y p i c a l , -1 ), MF, 0 ), NumDays ); NMF = Sum( I I f ( T y p i c a l < Ref( T y p i c a l , -1 ), MF, 0 ), NumDays ); MFITest = 100 * PMF / ( PMF + NMF ); P l o t ( MFITest, " M F I T e s t " , c o l o r G r e e n , s t y l e L i n e ) ; QQQQ - Daily 4/10/2DD3 Open 25 46. Hi 25 77. Lo 25 3. Close 25 77 (t 2%) MFITest = 45
"Mir
'May
'Jun
וJul
,
Aug
,
Sep 'Oct
,
Nov
1
Dec '2003 'Feb
1
Mar
lAjjr
Momentum M o m e n t u m is the difference between the price today and the price some n u m b e r of days ago. NVI - Negative Volume Indicator Negative Volume Indicator, developed by N o r m a n Fosback, is an accumulating indicator that a d d s to its r u n n i n g total w h e n today's volume is less than yesterday's volume.
1 214
Introduction to AmiBroker
OBV - On Balance Volume On-balance volume, developed by Joe Granville in 1963, is a momenturn indicator that measures positive and negative volume flow. •
If today's close is greater than yesterday's close, then today's volume is added to yesterday's OBV, and is considered up volume.
•
If today's close is less t h a n yesterday's close, then today's volu m e is subtracted f r o m yesterday's OBV a n d it is considered d o w n volume.
•
A n d if today's close is equal to yesterday's close then today's OBV is equal to yesterday's OBV.
2008
OSCP
1^ףק^ו
j
[
j
H ijul r ^ g "
Price Oscillator
Price Oscillator is the difference of t w o exponential m o v i n g averages of price. The lengths u s e d for this image are 9 and 18.
OSCV - Volume Oscillator Volume Oscillator is the difference of two exponential moving averages of volume. The lengths used for this image are 9 and 18.
Graphical
User
Interface
5
ו
ו
PVI - Positive Volume Index Negative Volume Indicator, developed by N o r m a n Fosback, is an accumulating indicator that a d d s to its r u n n i n g total w h e n today's volume is greater than yesterday's volume. PVT - Price Volume Trend Price Volume Trend is a s u m m a t i o n index that adds the volume times the one-day percentage change in the price to its r u n n i n g total. RMI ־Relative Momentum Relative M o m e n t u m Index, developed by Roger Altman in 1993, is a modification of the Relative Strength Index (see below). While the relafive strength index always compares price changes 1 day apart, the relative m o m e n t u m index compares changes any n u m b e r of days apart. That n u m b e r of days is a parameter to the index. For a given lookback period, say 14, RMI(14,1) is identical to RSI(14). C h a n g e the second parameter and watch the change in the index.
1 216
Introduction to AmiBroker
ROC - Rate of Change Rate of C h a n g e compares the price to the price some n u m b e r of days ago. For example, ROC(C,15) gives the percentage price change from 15 days ago to today.
RS ־Comparative Relative Strength Comparative Relative Strength compares a security's price change with that of a base security. W h e n the Comparative Relative Strength indicator is moving up, it shows that the security is p e r f o r m i n g better than the base security. W h e n the indicator is m o v i n g down, it shows that the security is p e r f o r m i n g worse t h a n the base security. In this image, XLK is the current symbol and Q Q Q Q is the base. The plot shows that XLK is p e r f o r m i n g worse than QQQQ. XLK- RS(OQQQ) = 490.63 •VTVW ,
540.0
%
530.0
v W u
520.0 510 0 500 0
M L May
'Jul 'Aug 'Sep'Oct
Nov 'Dec'2008'Feb 'Mar 'Apr 'May 'Jun 'Jul
'Aug
M
o
RSI - Relative Strength Indicator Relative Strength Index is an oscillator that compares the u p w a r d strength with the d o w n w a r d strength over a lookback period.
Graphical User Interface
5וו
To calculate the RSI: 1. Decide on the lookback period, call it N. 2. For each day, calculate the u p w a r d change, U, a n d the d o w n w a r d change, D over a one day period: If C>Ref(C,-l), U = C- Ref(c,-1), D = 0 If C < Ref(C,-l), U = 0, D = Ref(C,-l) - C If C == Ref(C,-l), U = 0, D = 0 3. Compute the N day exponential moving average of the U series, call it EU. 4. Compute the N day exponential m o v i n g average of the D series, call it ED. 5.
RSI = 100 * EU / (EU + ED)
This image shows the 14 day RSI. XLK- Daily 8/22/200B Open 23.23, Hi 23 48, Lo 23.17, Close 23 3 (1 4%) RSI(14) = 54 53
Aa
A
^A
,
..
tt j # r -
1
May
Jul
1
Aug
1
Sep'Oct 1Nov 1Dec'2008'Feb 1Mar 1Apr 'May'Jun 1Jul
1
Aug
RSIa ־Relative Strength Indicator The RSI formula always uses the closing price. The RSIa formula allows you to specify the series. RWI - Random Walk Index The Random Walk Index measures the difference b e t w e e n a straight line connecting two prices and the path taken by the trades between the two. This RWI has parameters 9 and 40. XLE - Daily 8/29/2008 Open 75 89. Hi 75 98. Lo 74 35. Close 74 65 (-0 5%) PW1(3.40) = 0 32 90 0 85.8
1 1 1 V > ׳f ' v
•f
/ W
׳1
'׳וויי 2008
75 0
!Mar
'Apr
'May
•un
Qui
w
70 0 1
Aug
1 218
Introduction to AmiBroker
RWIHI - Random Walk Index RWI using high prices. RWILO - Random Walk Index RWI using low prices. SAR - Parabolic Stop and Reverse SAR is a generic term m e a n i n g Stop A n d Reverse. Some trading systems are designed so that they always have a position, either long or short. The exit f r o m a long position is the entry to the short position, and vice versa. Hence the n a m e stop and reverse. The Parabolic Stop and Reverse system is a combination of two ideas - a stop and reverse system, and a parabolic trailing exit or stop. The parabolic trailing exit is plotted by the series of dots that follow below a long position and above a short position. The dots establish exit points. And, if the system is being used as a stop and reverse system, entry points in the other direction. The formula has two variables: the step and the m a x i m u m step. The higher the step is set, the more sensitive the indicator will be to price changes. The m a x i m u m step controls the adjustment of the SAR as the price moves. The lower the m a x i m u m step is set, the further the trailing stop will be f r o m the price. Wells Wilder, developer of the indicator, r e c o m m e n d s setting the step at .02 and the m a x i m u m step at .20. Those values are used in the plot that follows. XLK- Daily 8/22/200B Open 23 23. Hi 23 48. Lo 23 17, Close 23 3 (1 4%) SAR(0.02,0 2) ' ־
"12008
>15?
׳Apr
fMiy
•un
Cjui
׳Aug
Graphical
User
Interface
5
ו
ו
STIX STIX is the exponential m o v i n g average of the advance-decline ratio.
Stochastic %K Stochastic is a term m e a n i n g random in the more general sense, a poor n a m e for this indicator which is not r a n d o m at all, but is a position-inrange indicator (PIR). There is some controversy over w h o developed the indicator, but George Lane is usually given credit. The work w a s done in the 1960s. Position-in-range indicators have a lookback period, say it is N days or bars. Within the lookback period, identify the lowest of the values of interest and the highest of the values of interest. The PIR is the position the current value has within the range of lowest to highest. The general formula is: PIR = (current - lowest) / (highest - lowest) The PIR can be unsealed (so it ranges from 0.00 to 1.00), scaled so that it is a percentage (ranging f r o m 0 to 100), scaled as an oscillator a r o u n d 0 (ranging from -1 to + 1), and so forth. The Stochastic %K has two parameters - the lookback period a n d a smoothing factor (the series is the close). Say they are 15 a n d 3. The calculation starts out computing a PIR of the close using a 15 day lookback. It then takes a 3 day moving average.
20GB
1
Mar
lApr
Tviay
1
Jun
Qui
1
Aug
1 220
Introduction to AmiBroker
Stochastic %D The Stochastic %D a d d s an additional smoothing to the Stochastic %K. There are three parameters ־the lookback, the first smoothing, the second smoothing. Say they are 15, 3, a n d 3. Here is the plot showing both the %K (lighter line) and %D (heavier line). XLK- Daily B/22/200B Open
Stochastic %K(1:
Stochastic Momentum Stochastic M o m e n t u m is a position-in־range indicator. It is formed by subtracting the current value f r o m the midpoint of the highest high and lowest low, and dividing that by the difference between the highest high and lowest low. Both numerator and denomination are smoothed twice. Here is the plot of stochastic m o m e n t u m with parameters 15, 3, and 3.
TRIN - Traders Index Trin, Traders Index, is sometimes called the A r m s ' Index after its developer, Richard Arms. It measures the advancing and declining volume and compares that with the n u m b e r of advancing and declining issues. It can be used with any universe of issues, but is most often used for a broad market.
Graphical
User
Interface
5
ו
ו
The formula for the NYSE TRIN using Quotes Plus symbols is: Armslndex = ( F o r e i g n ( " ! N Y - A " , "C") / F o r e i g n ( " ! N Y - D " , "C") / ( F o r e i g n ( " ! N Y - A V " , "C") / F o r e i g n ( " ! N Y - D V " , " C " ) ); P l o t ( Armslndex, " T r i n " , colorRed ) ; Plot ( 1 . 0 , " " , c o l o r B l u e , s t y l e L i n e ) ;
)
Note two u n u s u a l features of TRIN: •
High values are associated with weakness.
•
The indicator is not symmetric a r o u n d 1.0.
Here is a plot of TRIN and the NYSE Composite Index.
TRIX - Triple Exponential TRI-ple exponential. TRIX is calculated as a one period rate of change of the third exponential moving average pass of the closing price. The image is TRIX applied to monthly data for the XLF ETF.
1 222
Introduction to AmiBroker
Ultimate ־Ultimate Oscillator Ultimate Oscillator, developed by Larry Williams in 1985, is the weighted s u m of three oscillators, each looking back a different time period. C o m m o n l y used lookbacks are 7,14, and 28. The oscillators used can be simple stochastic oscillators; or they can more complex, using concepts similar to true range and m e a s u r i n g buying pressure in each time period. Here is the Ultimate Oscillator with parameters 7, 14, and 28 and the SPY ETF. SPY- Daily 8/22/2008 Open 128 67, Hi 129 65, Lo 127 8. Close 129 65 (1 4%) Ultimate(7,1
"2008
fMir
!Apr
t y ^
tj^j
HjJJ]
Volatility (Chaikin) Chaikin Volatility is calculated by first taking an exponential moving average of the difference between the high and low, using an n day period. Then taking a rate of change between the current value and the one n days ago. Here is the 10 day Chaikin Volatility.
Graphical User Interface
5וו
Volatility (Wilder) Wilder Volatility is simply ATR - Average True Range. Here is Wilder Volatility for 10 days. SPY-Daily 8/22/2008 Open 128 67, Hi 129.65. Lo 127 8. Close 128.65(1 4%)Volatility(! 0)
\
ff V. 2008
T S a r > A p r T v i a y
,
Jun
A
l :
, s ״to
3.80 3.40 3 20 3.00 2.80
1
Jul
Volume Oscillator Volume Oscillator is the difference b e t w e e n t w o exponential m o v i n g averages of the volume. SPY - Volume Oscillator(!2,26} = -11.29, Volume: Hi = 167,687,600.00
15.0
A
10.0
50 00
00B
Tviar
1
Apr
Tviay
• u n U u i
'Aug
William %R Williams %R, developed by Larry Williams, is an u n s m o o t h e d position-in-range indicator. Note that the scale is inverted relative to the other PIR indicators. There is one parameter, the lookback period - 14 days for this example.
1 224
Introduction to AmiBroker
ZIG - ZigZag Indicator The Zig Zag indicator has a single parameter - a percentage value, say 5. It connects highest values (of the close, in this case) and lowest values in such a way that there is no price change greater t h a n 5 percent between two connected points.
The zig-zag indicator looks into the future, therefore cannot be used in trading systems. It is, however, an excellent tools for studying the profit potential of an issue. SYSTEMS
You can store any formulas you w a n t to in any subdirectory you want to. But, for convenience a n d organizational value, the Systems directory is u s e d for formulas that are trading systems. That is, they have Buy and Sell (and p e r h a p s Short a n d Cover) statements. Two trading system examples are installed w h e n AmiBroker is installed. Example Example.afl uses the MACD indicator to signal w h e n to buy and when to sell. Here is the code: Buy = Cross( MACD(), S i g n a l ( ) ); S e l l = Cross( S i g n a l ( ) , MACD() ); // t r a d e on next bar open SetTradeDelays( 1, 1, 1, 1 ); BuyPrice = S e l l P r i c e = Open; / / t r a d e s i z e : 25% o f c u r r e n t p o r t f o l i o e q u i t y S e t P o s i t i o n S i z e ( 25, spsPercentOfEquity ) ;
The first two lines generate the buy a n d sell signals. Buy when the MACD line rises t h r o u g h the Signal line. Sell w h e n the two lines cross the other direction. Refer back for descriptions of these two functions.
Graphical User Interface
5וו
The next two lines determine w h e n the trades will take place. Signals are calculated after trading has completed for the day. The trades are to be taken after a 1 bar delay and at the O p e n i n g price. And the final two lines state that a m a x i m u m of 25% of available capital should be used to take any single position. Trading systems will be discussed in more detail in Chapter 9, Automatic Analysis. Example Rotational ExampleRotational.afl uses a technique called rotational trading. In your research and testing, you have f o u n d some metric that can be computed for every symbol every day, where larger values of that metric indicate larger gains in price in the future. Call that metric PositionScore. For this example, issues that have done poorly over the past year are given high scores. Every day, compute PositionScore for all the issues you want to trade. Take initial positions in the four issues that have the highest scores. Sell any issue that is not one of the top six, replacing it with the highest ranking issue that you do not already hold. / / Simple example o f r o t a t i o n a l t r a d i n g system // This is c o n t r a r i a n s t r a t e g y / / i t buys 4 " w o r s t " s t o c k s - t h e ones t h a t s u f f e r e d t h e most i n l a s t year / / ( 4 s t o c k s having w o r s t 252-bar r a t e - o f - c h a n g e ) // // 4 p o s i t i o n s MaxPositions = 4; SetOption("MaxOpenPositions", MaxPositions ); S e t O p t i o n ( " W o r s t R a n k H e l d " , M a x P o s i t i o n s + 2 ); S e t P o s i t i o n S i z e ( 100 / M a x P o s i t i o n s , s p s P e r c e n t O f E q u i t y ); // t r a d e on next day open SetTradeDelays( 1, 1, 1, 1 BuyPrice = Open; SetBacktestMode(
);
backtestRotational
);
/ / o f f s e t t i n g b y l a r g e p o s i t i v e number // makes sure t h a t our score is always p o s i t i v e and we d o n ' t enter short trades P o s i t i o n S c o r e = 10000 - ROC( C, 252 );
Introduction to AmiBroker
Section III
Analysis
Introduction to AmiBroker
Chapter 6
Technical Analysis
229
1 230
Introduction to AmiBroker
Decisions to buy and sell a n y t h i n g - stocks, m u t u a l funds, cars, houses, jewelry - are m a d e for a variety of reasons and use a variety of decision m a k i n g techniques. W h e n it comes to securities, there are three broad categories of decision making: •
F u n d a m e n t a l analysis
•
C h a r t analysis
•
Quantitative analysis
uses information about the financial health of the organization, derived f r o m financial statements, reports by the management, estimates of f u t u r e revenue and expenses, and so forth. The efficient market hypothesis postulates that all the information that can be k n o w n about an organization has already been taken into account a n d is always already reflected in the price of its shares. Trading decisions are m a d e using one of the models based on the market being efficient, such as the Capital Asset Pricing Model. F U N D A M E N T A L ANALYSIS
The t w o branches of technical analysis - chart analysis and quantitative analysis - believe that the markets are somewhat inefficient, and that there is information in the historical price and volume data that can be recognized and can lead to profitable transactions. For both, several things m u s t be true in order to be profitable trading: •
The markets m u s t be inefficient.
•
There m u s t be patterns in the price and volume that precede profitable trading opportunities.
•
The patterns m u s t occur often enough to be profitable enough to overcome trading costs.
•
The analyst m u s t be able to recognize those patterns, either visually or t h r o u g h computer programs.
•
The patterns must persist long enough beyond the period being analyzed so that trades can be made.
A N A L Y S I S uses visual examination of the price and volume searching for patterns such as head-and-shoulders, trendlines, support a n d resistance levels. Often, the recognition of important patterns is a subjective judgement of the analyst. As demonstrated in the earlier chapters, AmiBroker has an o u t s t a n d i n g complement of charting tools to aid the chart analysts. CHART
Technical Analysis
23 ו
used in the sense of analysis of price and volu m e information, relies on writing a set of rules into a computer program, then r u n n i n g that program as a component of a trading system development platform. Trading system p r o g r a m s have the same characteristics as general p u r p o s e computer programs, in that they have variables and constants, read and write data, can p e r f o r m numeric calculations and string manipulation, have flow control statements, have subroutines and functions, and so forth. In addition, trading system programs have special features to deal with financial data and trading. They can process the data streams with the daily sets of open, high, low, close, and volume. They have special functions to h a n d l e the buying of shares, selling of shares, and accounting for the profits. Q U A N T I T A T I V E ANALYSIS,
AmiBroker is a trading system development platform. It has special features and specialized functions to deal with the price data, the purchase and sale of shares (or whatever is being analyzed and traded), the accounting and reporting related to the trading account. Of particular importance is a trading system development platform's ability to search for patterns (backtest), its ability to automatically search for the best sets of rules (optimize), and its ability to p e r f o r m statistical tests to measure the likelihood of a set of rules being profitable in the f u t u r e (validation). AmiBroker excels at all these tasks, a n d each will be discussed in the chapters to come.
Introduction to AmiBroker
Chapter 7
Trading System Development
233
234
Introduction to AmiBroker
All traders need confidence that their system will be profitable when traded. For any trader, the w a y to build confidence is to practice. O n e advantage that traders w h o use mechanical systems have over those w h o use graphical m e t h o d s is that the mechanical system is (or, at least, can be) objective, rule-based, judgement free, and testable. You will be writing a trading system, testing it using historical data, then following the rules to place actual trades. The period of time, and the data associated w i t h that time, that you use to develop and test your system is called the in-sample period and the in-sample data. The period of time, and the data associated with that time, that follows the insample period and has never been tested or evaluated by the system is called the out-of-sample data. Actual trades are always out-of-sample. The process of validating a trading system is one of observing the profitability and behavior of the system in the out-of-sample period after it leaves the in-sample period. The transition you m a k e going from testing your system in-sample to trading it out-of-sample is one data point in the validation of your system. Your confidence level will be m u c h higher if you have observed m a n y of these transitions. The ten step outline presented here is designed to build your confidence that your system will be profitable. For a more extensive discussion of trading system development, including expansion of the topics presented in this outline, please see Quantitative Trading Systems. 1.
DEFINE THE OBJECTIVE FUNCTION
An objective function is a metric of your o w n choosing that you use to r a n k the relative p e r f o r m a n c e of t w o or more alternative trading systems. The phrase "of your o w n choosing" is critical. Your objective function m u s t accurately reflect w h a t is important to you. If you prefer long holding periods and i n f r e q u e n t trading, your objective function m u s t rate systems that hold for weeks to m o n t h s higher t h a n systems that hold for a few days. If you prefer high equity gain without regard to d r a w d o w n over lower, but smoother, gain your objective function must reflect that. I believe the psychology of trading experts w h o try to help traders become comfortable with the systems they trade have it backwards. If
Trading System Development
235
you decide ahead of time w h a t you want, and design trading systems that satisfy your wishes, and if you have the confidence built through the validation process, you are g u a r a n t e e d to be comfortable with your system. AmiBroker reports the score for m a n y metrics w i t h each test run. If one of these standard, built-in metrics meets your needs, use it. If you w a n t something else, you can create a custom metric a n d use it. For many people, r e w a r d i n g equity g r o w t h while penalizing d r a w d o w n is important. If you agree, consider using one of the s t a n d a r d metrics that does that: RAR/MDD (risk adjusted a n n u a l rate of r e t u r n / m a x i m u m drawdown), CAR/MDD (compound a n n u a l rate of r e t u r n / m a x i m u m drawdown), K-ratio, Ulcer Performance Index, RRR (risk-reward ratio). 2.
DECIDE W H A T TO TRADE AND H O W TO TRADE IT
If you have a day job, you probably w a n t to use daily data, r u n your trading system in the evening, and place your trades the next day. Or, you may be able to watch the market d u r i n g the day a n d w a n t to place your trades intra-day or at the close. You m a y have a preferred g r o u p of stocks or m u t u a l f u n d s . Be certain your system works well with your choices. 3.
DESIGN THE TRADING SYSTEM
A trading system is a combination of a model a n d a set of data. The model is contained in the AFL code you write. The data is the price data of the ticker symbol your code processes. The model contains the intelligence. It is looking for the patterns in the data a n d testing the profitability of buying and selling. A model consists of several parts: filter or setup, entry, exit, trailing stop, position size, portfolio composition, and so forth. In much of the literature, the entry is emphasized. But the other components are more important. A model is a static representation of a d y n a m i c process. Once you are done coding and testing, the model does not change. It may be cleverly designed and have self-adapting parameters, but it is still static. The market being modeled is d y n a m i c and ever changing. Your model is looking for a particular pattern or set of conditions, after which it expects a profitable trade. As long as the model a n d the market remain in synchronization, the system will be profitable. W h e n the t w o fall out of
236
Introduction to AmiBroker
sync, the system will be less profitable or unprofitable. It is u s e f u l to think of the data as comprised of two components - signal and noise. The pattern your model is looking for is the signal portion of the data. Everything your model does not recognize is the noise portion of the data. Your goal, as a designer of trading systems, is to accurately recognize the signal and ignore the noise. O u r h o p e is that:
4.
•
We can build a model,
•
That recognizes some inefficiency,
•
And use that model to trade profitably,
•
As long as the model and reality stay in sync. DETERMINE THE LENGTH OF THE IN-SAMPLE PERIOD
There are two views about h o w m u c h time and data should be used to develop the system. Some w a n t a long time. They feel that the system will experience a variety of conditions and be better able to h a n d l e changes in the future. The risk is that conditions vary so much in the in-sample period that the system will not learn any of it well. Some w a n t a short time. They feel that the system will be better able to synchronize itself and learn very well. The risk is that the system may learn a temporary pattern that does not persist beyond the in-sample period. Another way to view this is that the system has fit itself to the noise because the signal is too weak. A system that has fit to the noise, p e r f o r m s well in-sample, but does not perform well out-of-sample is sometimes described as a system that is curve-fit, or over-fit, to the data. The proper length of the in-sample period is impossible to state in general. It is very much a function of both the model and the data. The only way to determine the length of the in-sample period is to r u n some tests. 5.
DETERMINE THE LENGTH OF THE OUT-OF-SAMPLE PERIOD
The length of the out-of-sample period is: As long as the model and the market remain in sync and the system remains profitable. There is no general relationship b e t w e e n the length of the out-of-sample period and the length of the in-sample period.
Trading System Development 6.
237
DECIDE W H A T T O OPTIMIZE
To optimize m e a n s to search a lot of alternatives and choose the best of them. Optimization is not a bad thing; in fact, it is a necessary step in system development. If you were to think up a new trading system and write the AFL code for it, it would include logic a n d parameters that were first guesses. You could test that system as it stands, and then either trade it or erase it and start over. But you are unlikely to do that. More likely, you will try other logic and other parameters values. If you are trying a few hand-picked alternatives, you might as well r u n an optimization and try t h o u s a n d s of alternatives. Give yourself a chance to find the best system. Anything you would consider c h a n g i n g in your system - a different parameter value or an alternative logic statement - is a candidate to be optimized. 7.
PERFORM WALK FORWARD RUNS
While there is nothing special about optimizing, there is something very special about a walk forward run. You saw these d i a g r a m s in Chapter 3, Example 9, but they are w o r t h looking at again.
255
Introduction to AmiBroker
The walk forward process is several iterations of: 1. O p t i m i z e in-sample. 2. Choose the best according to your objective function. 3. Use those values and test out-of-sample. 4.
Step f o r w a r d by the length of the out-of-sample period.
Continue this process until you have used the last full in-sample period. 8.
EVALUATE THE OUT-OF־SAMPLE RESULTS
Either trade the system or send it back to development.
Note the importance of having an objective function you trust. The set of parameters used to test out-of-sample are the parameters that are at the top of the results list, after the list has been sorted by your objective function. The process is automatic and objective. All the decisions were m a d e in earlier steps. You will never even see what the second choice is; the first choice is always used. Each walk forward step is one data point you will use in the validation of your system.
Trading System Development 9.
239
TRADE THE SYSTEM
Using the set of parameters that are at the top of the list after the last optimization, buy and sell w h e n the system gives signals. Take all the signals. If you have some way to decide which signals to take and which to skip, that logic belongs in the trading system and should go t h r o u g h the validation process. On the last day of what would have been the out-of-sample period, reoptimize. Pick the top-ranked parameter values and continue to trade. 10.
MONITOR THE RESULTS
Each trade signaled after development has finished, and each trade you actually take, is an out-of-sample trade. You can compare the statistics for your trades with statistics for the out-of-sample results f r o m the walk forward runs. If your results d r o p below w h a t is statistically expected, stop trading the system. Either paper-trade it to see if it recovers; or re-optimize ahead of schedule, then paper-trade it and observe its performance. IN SUMMARY There are no guarantees. The best we can hope for is a high level of u n derstanding and confidence gained t h r o u g h the validation process.
Introduction to AmiBroker
Chapter 8
AFL
AmiBroker Formula Language
242
Introduction to AmiBroker
AFL is AmiBroker Formula Language - the code that takes your ideas and puts them in the form that AmiBroker understands. Formulas, indicators, explorations, and trading systems are all written in AFL. AFL is a component of AmiBroker, and is installed automatically in all versions of AmiBroker. AFL is a procedural programming language, similar to Visual Basic, C, C++, Pascal, and Fortran. As such, it has language features for: •
Computation of numerical expressions.
•
Evaluation of logical expressions.
•
Declaration and use of data storage.
•
Definition of data structures.
•
Reading data into the program.
•
Writing data out from the program.
•
File manipulation.
•
Program control.
•
Built-in and user-defined functions.
AFL could be used for general purpose computing. But its unique capabilities come from the additional features designed to work with financial time series and trading systems. These include: •
Language and procedures to deal with financial quotations, such as open, high, low, close, volume, and open interest.
•
Language and procedures to deal with trading system orders, such as buy, sell, short, and cover.
•
The ability to plot or chart financial data, such as price, technical indicators, and buy and sell arrows.
•
Powerful array processing capabilities. Much of the data used in trading systems is organized in time-ordered series, which AmiBroker stores in arrays and manipulates with array-oriented procedures.
AFL files are clear-text files, not proprietary or encoded in any While any text editor can be used to create and modify them, the Formula Editor is designed specifically to work with AFL files. chapter begins with a discussion of the AFL Editor, the Formula
way. AFL This Edi-
Following that is a description and discussion of the AFL Language, including the language features and built-in functions.
AFL - AmiBroker Formula Language
243
A F L EDITOR (FORMULA EDITOR) The AFL Editor, or Formula Editor, is the editor that is built-in to AmiBroker. It is used to write AFL p r o g r a m s that will display custom indicators and test trading systems. It has four pull-down menus, a toolbar, and a context m e n u of its own. [C:VProgram Files\AmiBroker\Formulas\Custom\ATC Tr. File
Edit
D. G? a ־ 7
1001$
Help
#
tfc ©
.X
"*־< י
SirapleDiffusionlnde
ATC Trading Fig
-
I _ ׳
ail
// // // // //
Create a simple diffusion index using -Advlss, -Declss, and ^ C o u n t e r t h a t w e r e c r e a t e d i n a n e a r l i e r r u n . Since those data series w i l l not change u n t i l another day of data is added to the database, t h e r e i s n o n e e d t o r e c a l c u l a t e thera f o r e v e r y r u n .
//
There
is
no
AddToC.omposite
statement
in
this
program.
SetTradeDelays(0,0,0,0); B u y P r i c e = C; S e l l P r i e e = C; // Read t h e d a t a s e r i e s c o n t a i n i n g t h e // advancing issues, declining issues, // total issues. AdvXss = F o r e i g n ( " ~ A d v I s 3 " , " V " ) ; D e c l s s = F o r e i g n ( ״ ׳ ״D e c l s s " , "V") ;
number and
of
Redo the previously undone action
PULL-DOWN MENUS
• E1I8 1 Edit
•
New
si
Open
»
File Menu Iools
Save Save As...
m
Print Exit
N e w - Clears the AFL w i n d o w O p e n - O p e n s an existing AFL file Save ־Saves the contents of the w i n d o w u n d e r the current n a m e Save As - Saves the contents u n d e r a n e w name Print ־O p e n s the Print dialog box to send the AFL to a printer Exit - Close the editor
244 •
Introduction to AmiBroker Edit Menu
X i Cut ^
Copy
Select an Elnd... Replace Prettify Selection
Undo - un-does last action (multi-level) Redo - re-does recent action (multi level) Cut - Moves selected text to the clipboard Copy - Copies selected text to the clipboard Paste - Copies clipboard to cursor location Select All - Selects the entire file Find - Opens search dialog Replace - Opens search and replace dialog Prettify Selection - Reformats selected text to a consistent standard; adjusts indents and spacing Copy Error Message - After checking AFL syntax, if there is an error, copies that error message to the clipboard
If you get the error message shown below when trying to run prettify, get AStyle.dll from this url: http://1vww.amibroker.com/bin/astyle.cill and copy it to the AmiBroker directory: C:\\Program Files\AmiBroker !1
AFL - AmiBroker Formula Language •
Tools Menu Verify Syntax - Check AFL code for errors Apply Indicator ־Saves the file, then applies it one time. (If you click again, no new pane is opened.) Insert Chart - Saves the file, then applies it many times. (If you click again, another new pane is opened.) Send to Auto-Analysis - Saves the file, makes it the selected file for Automatic Analysis, opens Automatic Analysis, and waits for your action. Scan - Saves the file, makes it the selected file for Automatic Analysis, and r u n s the Scan process Exploration - Saves the file, makes it the selected file for Automatic Analysis, and runs the Explore process Backtest - Saves the file, makes it the selected file for Automatic Analysis, and r u n s the Backtest process Optimization - Saves the file, makes it the selected file for Automatic Analysis, and r u n s the Optimize process Code Check & Profile - Saves the file, makes it the selected file for Automatic Analysis, and runs the Code Check and Profile process. Code Check tests for "future leaks" where the code peaks into the future. Profile lists the operations required to r u n the code and estimates the execution time. Options - There is only one option - Autosave formula. When checked, the file will be saved before being sent to Automatic Analysis for processing.
1001s | deip Verify syntax •L3
Aeply Indicator insert chart
1
Send to Auto-Analysis Scan Exploration Backtest Optimization Code Check 8 Profile Options
245
•
H
Auto-save formula before running analysis
246
Introduction to AmiBroker Help Menu Function Reference - Displays the AFL reference page for the function highlighted. Pressing the F1 key is equivalent. Parameter info - Display a Tooltip containing the complete function prototype, including parameters. AFL Language Reference - Displays the AFL Language Reference section of the User's Guide, describing AFL in general. Function index by name - Displays the available AFL functions, sorted alphabetically. Function Index by Category - Displays the available AFL functions, grouped by category. Help on Editor - Displays User's Guide entry for the AFL Editor
bBlp I Function reference Parameter info ו
AFL Language Reference Function index by Name
t Function lnde« by Category Heip on Editor
A F L EDITOR TOOLBAR -י
New
aste
Print
Open
Cut
Save
, ATC Trading Fig
T
Copy
|.
I
Name
Undo Redo
Analysis Check Apply
New - Clears the AFL w i n d o w Open - Opens an existing AFL file Save - Saves the contents of the window under the current name. Pull-down menu gives a choice of the default "save" or "save as". y
Save j Save As.,,
•
Print - Opens the Print dialog box to send the AFL to a printer
•
Cut - Moves selected text to the clipboard
AFL - AmiBroker Formula Language
247
•
Copy - Copies selected text to the clipboard
•
Paste - Copies clipboard to cursor location
•
Undo - Un-does last action (multi-level)
•
Redo - Re-does recent action (multi-level)
•
Name - An edit field to allow you to name the formula. Save will use this name.
•
Check - Check AFL code for errors. Same as Verify Syntax.
•
Apply - Saves the file, then applies it to the chart. Usually a plot. Pull-down menu gives choice of the default "apply" (to an existing pane) or "insert" (into a new pane).
>₪__ [־ »E3
Apply indicator Insert indicator
•
Analysis - Saves the file, makes it the selected file for Automatic Analysis. Pull-down menu selects action. No specific choice (the defau It) - AA performs in the mode it last performed. Scan - Perform a Scan Exploration - Perform an Exploration Backtest - Perform a Backtest Optimization - Perform an Optimization Check - Check for future leak.
248
Introduction to AmiBroker
A F L EDITOR C O N T E X T M E N U Cut
Ctrl+X
Copy
Ctrl+C
Paste
Ctrl+V
Delete
Del
Undo
Ctrl+Z
Redo
Ctrl+Y
Select All
Ctrl+A
Find
Ctrl+F
Print Parameter into Function reference
F1
Cut - Moves selected text to the clipboard Copy - Copies selected text to the clipboard Paste - Copies clipboard to cursor location Delete - Deletes selected text Undo - Un-does last action (multi-level) Redo - Re-does recent action (multi-level) Select All - Selects the entire file Find - Opens search dialog Print - Opens the Print dialog box to send the AFL to a printer Parameter info - Display a Tooltip containing the complete function prototype, including parameters. Function reference - Displays the AFL reference page for the function highlighted. Pressing the F1 key is equivalent.
AFL - AmiBroker Formula Language
249
A F L LANGUAGE ARRAYS
In computer science an array is a data structure consisting of a g r o u p of elements that are accessed by indexing. Each element has the same data type and the array occupies a contiguous area of storage. Arrays are so important to AmiBroker that they will be introduced first - before other data structures and before the general description of the AFL language. In AmiBroker, the Open, High, Low, Close, Volume, and O p e n Interest are stored in arrays. All other formulas a n d indicators that are used must be computed using the OHLCVI data. Take a look at the data. Make IBM the selected issue. Its price chart will appear. Using the Symbol menu, select Quote Editor. There is a row for each bar and a column for each data field. W h e n plotL Quotations editor Mode
Date
( * ) Current symbol/all quotes Q All symbols/single quote (very slow)
Ticker: Date: Time: Open: High: Low: Oose: Volume: Open Int.:
!0 £Z
IBM IBM IBM IBM IBM IBM IBM IBM IBM IBM IBM IBM IBM IBM IBM IBM IBM IBM IBM
7/30/2006 7/29/2006 7/28/2008 7/25/2008 7/21/2008 7/23/2006 7/22/2008 7/21/2008 7/18/2008 7/17/2008 7/16/2008 7/15/2008 7/11/2008 7/11/2008 7/10/2008 7/9/2008 7/8/2008 7/7/2008 7/3/2008
Close
Open
128.86 12812 127.66 126.25 126.53 130 129.52 130 128.66 129.89 126 52 125 91 123.2 121.54 122.12 12318 120.4 123 88 121.5 11954
126.51 127 69 129 129.3 129.78 127.5 129.83 125.42 126 39 122.81
High
Low
Volume
129 128.17 12811 129.9 130.93 130 33
127.09 126.25 126.13 126 128.8 128 29 127 26
5.779.100 5.979.300 6,096.700 7.565.100 6.916.600 10.230.500 11.128.500 7.760.100 16.317.700 12,299.500 9.699.000 10,713,900 8.317,300 8.813.900 10,053,500 9.506,600 9,813,700 9,131.100 6,117,600
130 129.9 130 126 96 126.89 1215 121.25 12371 123 51 1215 123.99 122.61 120.78
121 123.51 121 8 120.66 121.11 120.55 119.8 119 99
127.61 12512
121
122.25 119 9
121.21 120 57 120.66 120.1 120.55 119.62 117 69
Open Int
ted on a chart, the date axis has the oldest at the left of the chart and most recent at the right. When the data is read f r o m the database into memory, an array is ereated for each field - Date, O, H, L, C, V, OI. The array for each of them has one element for each bar. The elements are referenced (identified) by their position in the array - their index. The oldest element is stored in the first array element and has index 0. Each newer bar (newer element) has an index n u m b e r 1 greater t h a n its left neighbor. The set of
250
Introduction to AmiBroker
all seven data fields for a given bar form a data record. All elements of a record have the same index number. When using end-of-day data, each bar holds the data for one day; the number of bars and the number of days will be the same. BARCOUNT
Look at the entire array, say for the closing price. When the data is loaded into memory, the number of data points is counted. That number is stored in a special variable n a m e d BarCount. The elements of the Close array are numbered from 0 to BarCount-1. There is no element whose index is BarCount. Trying to refer to an element whose index number is less than 0, or BarCount or greater, results in an "index out of bounds" error. Oldest
Most Recent
Index
BarCount 1 BarCount-2 A total of BarCount elements, indexed from 0 to BarCount-1
When the price series is loaded from the database to memory, that established not only the length of those OHLCV arrays, but of all arrays. The default number of elements in every array is BarCount. When you compute an array indicator, such as the simple moving average, the resulting array also has BarCount elements; and they are also indexed from 0 through BarCount-1. When you program AFL and use looping, you will need to be aware of the array indexing and of the BarCount variable. ARRAY OPERATIONS
In order to use an indicator, like the 25-day moving average, the value of that average must be computed for each day. The average is the sum of the 25 days up to (earlier than) and including the day being processed, divided by 25. Beginning with index number 24, every day has a 25-day moving average. For elements 0 through 23 there is not enough data to compute a 25 day average. AmiBroker is unique in that it uses a very efficient array-processing technique to compute the 25-day moving average, giving the value for all the data elements in a single array in a single processing step. Com-
AFL - AmiBroker Formula Language
251
puted once, they are available whenever they are needed for further analysis. The formula to compute the moving average and store it so it can be used is: MyAverage = MA ( C, 25 );
•
MA is the AFL function that computes the simple moving average.
•
C, or Close, tells the function to take the moving average of the Closing price.
•
25 is the number of bars (days) in the average.
•
MyAverage is the location where the result is stored.
The key point is that this is an array operation. Close and MyAverage are arrays, and MA is a function that works with arrays (and only with arrays). When people get confused with AFL, it is often over whether a function works with arrays or scalars (single values). The description of MA, the function that computes the simple moving average, called the syntax of the function, tells us what it uses as input and what it returns as results. Syntax: MA (
ARRAY,
periods );
Returns: ARRAY
Description: Calculates a Simple Moving Average of length periods of turns the result as an array.
ARRAY.
Re-
For example: MAofClose = MA ( C l o s e , 20 );
Close is an array. MA is an array operation that computes the moving average for every element in the Close array The result is also an array. The result returned from the function must be stored in a variable that is an array. All of these arrays have the same length - the length that was established when the data was read from the database and stored in the Close array.
252
Introduction to AmiBroker
LANGUAGE
BASICS
Keep in mind that this is an introductory explanation. There are features of AmiBroker and AFL that are not explained, or even mentioned, here. For more information, please see the AmiBroker AFL Reference, which is a component of the AmiBroker User's Guide. An AFL program consists of the following elements: are word-like units recognized by the AFL language proces-
TOKENS
sor. is the collective name given to spaces, tabs, line breaks, and comments. Whitespace serves to separate tokens. Excess whitespace is discarded. That means that if a single whitespace character is permitted, you can have any number of them, including extra line breaks to aid program readability. WHITESPACE
are text used to document a program. They are for the programmer's use only - they are stripped out of the code before it is processed. There are two ways to denote text as being a comment: COMMENTS
•
// - two adjacent slashes - the remainder of the line is a comment.
•
1**1 - two, two-symbol pairs - everything between the opening /* and the closing */ is a comment.
Comments may not be nested. TOKENS.
AFL recognizes five classes of tokens:
•
identifiers
•
constants
•
string-literals
•
operators
•
punctuators
Identifiers are arbitrary names, of any length, given to variables and functions. Identifiers must begin with a letter, may contain letters (a-z, A-Z), digits (0-9), and the underscore ("_"). AFL identifiers are not case sensitive. The identifiers MyMovingAverage and mymovingaverage are treated as being the same. Constants are tokens representing fixed numeric or character values. Numeric constants consist of decimal integer and, optionally, decimal
AFL - AmiBroker Formula Language
253
point and decimal fractional part. Negative numeric constants are preceded by the m i n u s sign. String literals, or string constants, are a sequence of any characters surrounded by double quotes ("). "This is a string literal" Operators are the arithmetic, relational, and assignment operators, such as +, -, <. They will be covered in more detail below. Punctuators are any of the following characters: (),;=. are constants, variables, or other terms that are operated u p o n by operators. TERMS
are combinations of constants, variables, terms, and operators that can be evaluated a n d result in a single value — a scalar (single number), string, or array. EXPRESSIONS
S T A T E M E N T S consist of one or more expressions, an assignment operator, and a variable. The expressions are evaluated and assigned to the variable. Each statement m u s t be terminated by a semicolon.
Operators are used to test the relation b e t w e e n t w o expressions. The result of the test will be either True (1) or False (0). The operators are: COMPARISON OPERATORS
•
<
Less than
•
>
Greater than
•
<=
Less than or equal to
•
>=
Greater than or equal to Equal to
• •
!=
Not equal to
A S S I G N M E N T O P E R A T O R is used to store the value on the right side in the variable on the left side. The operator is the = character. For example:
B = A + 14; The right h a n d side is evaluated to a single result by a d d i n g A a n d 14 together. The result is stored in the variable B. Note the difference between "=" and "==". The single = is an assignment. The double == tests equality.
254
Introduction to AmiBroker
combine one or more terms to produce a term or expression. They include: A R I T H M E T I C OPERATORS
+
Addition
-
Subtraction (including unary minus)
*
Multiplication
/
Division
%
Modulus (remainder)
A
Exponentiation (raise to a power)
1
Bit-wise Or
&
Bit-wise And
LOGICAL OPERATORS
work with logical constants and logical variables.
They include: •
NOT
Logical Not of a single operand
•
AND
Logical And of two operands
•
OR
Logical Or of two operands
LOGICAL CONSTANTS
are True and False.
•
False is represented by numeric zero.
•
True is represented by numeric 1. Actually any non-zero value, positive or negative, evaluates to True.
C O M P O U N D A S S I G N M E N T O P E R A T O R S perform an arithmetic operation followed by an assignment operation. The most commonly used are:
•
++ Post increment (increment the variable and store it back) i++ means add 1 to i. More completely, it means take the value of i, add 1, assign the result to i.
•
— Post decrement (decrement the variable and store it back) i— means subtract 1 from i.
•
+= Add the value of the operand (variable) on the left plus the value of the operand on the right, then store the resu It back in the variable on the left, j += 2; Add 2 to j.
•
-= Subtract the value of the operand on the right from the value of the operand (variable) on the left, then store the result in the variable on the left. k-= 5; Subtract 5 from k.
•
*= Multiply the value of the operand (variable) on the left by the value of the operand on the right, then store the result back in the variable on the left, m *= i; Multiply m by i.
AFL - AmiBroker Formula Language •
255
/= Divide the value of the operand on the left (variable) by the value of the operand on the right, then store the result back in the variable on the left, x /= y; Divide x by y.
When in doubt, write out the calculation you want using ordinary arithmetic operators. The possible confusion is not worth the execution efficiency. Operator Precedence Parentheses can be used to control the order in which the operations take place. Those operations that are in the innermost parentheses are done first, then working outward. W h e n there are no parentheses to explicitly define the order, this precedence is followed (highest ranked are listed first and done first): 1.
++
Post increment
2.
-
Post decrement
3.
[]
Array element operator
4.
A
Exponentiation
5.
־
Unary m i n u s
6.
*
Multiplication
7.
/
Division
8.
%
Modulo
9. +
Addition
10.
Subtraction
־
11. <
Less than
12. >
Greater than
13.
<=
Less than or equal to
14.
>=
Greater t h a n or equal to
15.
= =
Equal to
16. 1=
Not equal to
17. &
Bit-wise A n d
18. 1
Bit-wise Or
19. NOT
Logical Not
20. A N D
Logical And
21. OR
Logical Or
22.
Assignment
23.
=
C o m p o u n d assignment (all operators)
256
Introduction to AmiBroker
In addition to h a v i n g ++ be a post increment operator, it can be a pre increment operator, j = i++ uses ++ as a post increment operator, j is assigned the value of i, then i is incremented, j = ++i uses ++ as a pre increment operator, i is incremented, then the n e w value of i is assigned to j. Use parentheses to insure that the calculations are carried out in the order y o u intend. If H is 110 a n d L is 106, (H+L)/2 is 108. H+L/2 is 163, because the division takes place before the addition. Array Subscript Operator An entire array is referenced by using its n a m e without qualification, as in M M = O; To reference a particular element of an array, use the [] operator. For example, to reference the most recent closing price, use C[BarCount-l]. B A R C O U N T , as you will recall f r o m the earlier discussion, is the n u m ber of elements in the OHLCV arrays, and all other arrays derived from those. The first element of every array is index 0, the final element is index BarCount-1.
Compound Statements (Blocks) A c o m p o u n d statement consists of zero or more statements within curly brackets {}. A c o m p o u n d statement can be used anywhere a statement can be used. Built-in Functions In addition to the arithmetic operators, AmiBroker has over 70 built-in functions that p e r f o r m mathematical operations. Functions accept zero or more a r g u m e n t s enclosed in parentheses, and r e t u r n zero or one values. The built-in functions will be discussed later in this chapter. Conditional If The conditional if function has the form IIF(exp, Tp, Fp); Note that IIF is a function - it r e t u r n s a value. The expression exp is evaluated to either True or False. If True, r e t u r n Tp, if False, r e t u r n Fp. Note that IIF is Not a program flow control statement. That is, it does not operate like the traditional IF statement. IIF is a function and it returns a value.
AFL - AmiBroker Formula Language
257
Variables A variable is an identifier and its associated data structure and storage. •
You can define and use as m a n y variables as you wish; there is no limit.
•
Each variable m u s t be assigned a value before it can be used further.
•
Variables used in the m a i n p r o g r a m cannot be assigned values in functions.
•
User-defined variables m a y not duplicate n a m e s already defined by built-in functions (such as EMA), predefined arrays (such as Open), keywords (such as If), or reserved w o r d s (such as Buy).
•
It is good p r o g r a m m i n g practice to define variables, give them m e a n i n g f u l names, assign values to the variables, then use the variables in subsequent calculations a n d function calls.
Reserved Variables AmiBroker uses some variable n a m e s a n d reserves those. You m a y not use these identifiers for variables you define: buy
•
pointvalue
sell
•
margindeposit
short
•
positionsize
cover
•
positionscore
buyprice
•
numcolumns
sellprice
•
filter
shortprice
•
maxgraph
coverprice
•
columnN, where N is a digit
title
•
columnNformat
tooltip
•
columnNname
graphxspace
•
graphN, where N is a digit
graphzorder
•
graphNname
exclude
•
graphNcolor
roundlotsize
•
graphNbarcolor
ticksize
•
graphNstyle
258
Introduction to AmiBroker
U S E R - D E F I N E D F U N C T I O N S , PROCEDURES, SCOPE
User-definable functions make it possible to encapsulate user code into easy-to-use modules that can be used in many places without the 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. The function definition establishes the name and parameters of a function. The function must be defined prior to the call to the function. The definition is a single line of code that begins with the keyword function, is followed by the function name, and then the list of parameters enclosed in parentheses. The function b o d y enclosed in curly braces, follows using as many statements as you wish. When the function is invoked or called by the calling program, control passes to the called function. Variables are passed for the arguments. Each argument corresponds to a parameter. The function performs its calculations, including executing the return statement. If there is a resuit to be returned, it is passed back to the calling program. If the function does not have any return statement (does not return anything) then we call it a procedure. Following is an example of a function, a 2nd order smoother: / / the f i r s t l i n e i s the d e f i n i t i o n o f the f u n c t i o n f u n c t i o n I I R 2 ( i n p u t , fO, f 1 , f 2 ) // the remaining l i n e s are the body of the f u n c t i o n { result[ 0 ] = input[ 0 ] ; r e s u l t [ 1 ] = i n p u t [ 1 ]; f o r ( i = 2; i < BarCount; i++ ) { r e s u l t [ i ] = fO * i n p u t [ i ] + f1 * r e s u l t [ i - 1 ] + f2 * r e s u l t [ i - 2 ];
}
}
// t h i s f u n c t i o n returns an array return result;
/ / t h i s i s the main, o r c a l l i n g , program P l o t ( Close, " P r i c e " , c o l o r B l a c k , s t y l e C a n d l e ) ; P l o t ( I I R 2 ( Close, 0 . 2 , 1 . 4 , - 0 . 6 ) , " f u n c t i o n example", c o l orRed );
AFL - AmiBroker Formula Language
259
IIR2 is a user-defined function. There are four formal parameters: input, fO, fl, £2. The calling p r o g r a m prepares actual arguments, one a r g u m e n t corresponding to each format parameter. At the time of the function call the values of a r g u m e n t s are passed (by value, not by n a m e or by reference). Formal parameters behave like local variables and have the numeric values that were passed to them. They are u n d e f i n e d (have no numeric values) until the function is called. A n d w h e n the r e t u r n statement is executed, they become u n d e f i n e d again. They have no memory. Within the body of the function, local variables n a m e d result and i are defined and used. Local variables are visible inside the function only. If any other function uses the same variable n a m e the t w o will not interfere with each other. Local, Global AFL does not require that variables be declared before they are used. The first use of a variable determines whether it is local or global. If a given identifier appears first inside a function, then it is treated as a local variable to that function. If a given identifier appears first outside the function, but is used within the function, then it is treated as a global variable and it carries whatever value it had at the time of the call into the function. Since this can cause problems that are difficult to debug, there are t w o keywords, local and global, that can be used to force the scope. See the following example. k = 4;
/ / t h i s i s a g l o b a l v a r i a b l e because o f i t s f i r s t use
f u n c t i o n f( x ) { z = 3; // t h i s is LOCAL v a r i a b l e r e t u r n z * x * k; // , k ' here r e f e r e n c e s g l o b a l v a r i a b l e k ( f i r s t used above o u t s i d e f u n c t i o n ) } z = 5;
// t h i s is GLOBAL v a r i a b l e w i t h t h e same name // as the l o c a l v a r i a b l e in f u n c t i o n f
"The value of z b e f o r e f u n c t i o n c a l l :" + W r i t e V a l ( z ); / / C a l l i n g the f u n c t i o n w i l l not a f f e c t t h e / / the v a l u e o f our g l o b a l v a r i a b l e z // because the g l o b a l v a r i a b l e z and
260
Introduction to AmiBroker / / l o c a l v a r i a b l e z are s e p a r a t e and // arguments are passed by v a l u e (not by r e f e r e n c e ) "The r e s u l t of f( z ) = " + W r i t e V a l ( f( z )
);
"The v a l u e of z a f t e r f u n c t i o n c a l l is unchanged : Val( z );
" + Write-
Example 2: Using local and global keywords to override default visibility rules: VariableA = 5; // i m p l i c t g l o b a l v a r i a b l e function Test() { l o c a l VariableA;
// // global VariableB; // // // //
}
e x p l i c i t local variable w i t h t h e same i d e n t i f i e r a s g l o b a l e x p l i c i t global variable not d e f i n e d e a r l i e r may be used to r e t u r n more than one v a l u e from t h e f u n c t i o n
V a r i a b l e A = 99; V a r i a b l e B = 333;
VariableB = 1 ;
// global variable
"Before f u n c t i o n c a l l " ; "VariableA = " + VariableA; "VariableB = " + VariableB; Test(); "After function c a l l " ; " V a r i a b l e A = " + V a r i a b l e A + " ( n o t a f f e c t e d by f u n c t i o n c a l l )"; " V a r i a b l e B = " + V a r i a b l e B + " ( a f f e c t e d by the f u n c t i o n c a l l )"
At the end of the function we can see the return statement that is used to return the result to the caller. Currently the return statement must be placed at the very end of the function. It is also possible to write a procedure (a function that returns nothing (void)) procedure S i n e P l o t t e r ( {
Freq, C o l o r l n d e x )
pname = " L i n e " + W r i t e V a l ( C o l o r l n d e x , 1 . 0 ) ; a r r a y = s i n ( Cum( Freq * 0.01 ) ); P l o t ( a r r a y , pname , colorRed + C o l o r l n d e x ,
} f o r ( n = 1; n < 10; n++ ) {
s t y l e T h i c k );
AFL - AmiBroker Formula Language S i n e P l o t t e n ( n/2+Cum(0.01),
261
n );
} Although there are two separate keywords function and procedure, AmiBroker currently treats them the same (they both accept return values but do not require them), but in the future the rules might be enforced. That will require use of the return statement only in functions. So it is advisable to use the function keyword in the case where your function returns any value and the procedure keyword if it does not. Note that recursion (having a function call itself from within itself) is not presently supported. FLOW C O N T R O L
If you are using the array-oriented features of AFL, then most of the code you write will start at the top of the program and flow to the bottom of the program without interruption. None of the flow control statements or tests accept arrays as arguments. The flow control statements are: •
do ... while
•
for
•
if... else
•
switch
•
while
There are two typical uses for flow control statements: 1. You want to perform some task that may or may not operate on entire arrays for each of several values of a variable. For example, write to a file the results of r u n n i n g tests with values for a particular argument of 5, 7, 9, and 11. 2. You want to step through the data that is in one or more of the arrays, such as the array of closing prices, and make some decision based on what you find. To do this requires that the program use looping. Each of the five flow control statements will be illustrated with an example. The optional statements that can be used with the flow control are also explained.
262
Introduction to AmiBroker
break The break keyword is a part of switch statement and an optional part of looping for, do-while, a n d while statements. The break keyword terminates the smallest enclosing do, for, switch, or while statement in which it appears. The syntax is: 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; w h i l e ( i < 10 ) { i++; // break at step 5 i f ( i == 5 ) { break;
}
p r i n t f ( " S t e p " + i );
}
continue The continue statement is an optional part of for, do-while, and while statements. It stops the current iteration of a loop, and starts a n e w iteration. The syntax is: 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 a n d continues p r o g r a m flow with the b e g i n n i n g of the loop.
AFL - AmiBroker Formula Language
263
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; w h i l e ( i < 10 ) { i++; // S k i p 5 i f ( i == 5 ) { continue;
}
printf("Step " + i
);
}
do ... while The syntax (general form) of the do ... while statement is: do { statements | while (expression); do and while are keywords. They are always spelled exactly the same way and used in the same way. j statements } is any executable statement or statements, enclosed in a set of curly brackets. The curly brackets are mandatory. (expression) is any expression that can be evaluated to either True or False. The parentheses are mandatory. The final semicolon is m a n d a tory. When this part of the p r o g r a m is reached, the statements are executed in order. There may be flow control statements included. Eventually the end of the statement code will be reached. The expression is evaluated. If the result is True, then the statements in the body will be executed again, starting f r o m the beginning, with the variables retaining their most recent values. If the result is False, then the do ... while is finished and p r o g r a m flow continues to the statement following it.
264
Introduction to AmiBroker / / i n i t i a l i z e c o n t r o l v a r i a b l e s t o prepare f o r t h e d o l e n g t h = 5; // the do . . . while do {
. . . while
p r i n t f (" something i n t e r e s t i n g " + NumToStr(length) + \ " n " ) ; l e n g t h = l e n g t h + 2;
}
w h i l e ( l e n g t h <= 1 3 ) ; / / whatever code comes a f t e r t h e d o
. . . while
The output of the printf will have lines for lengths of 5, 7, 9, 11, and 13. The syntax of the for statement is: for (initial; conditional; loop-expression) j statements; } for is a keyword. (initial; conditional; loop-expression) control the loop. Before the first execution of the statements in the body, initial is executed. Immediately, and before every execution of the body, conditional is tested. If the result of the test is True, execute the statements in the body of the loop. If the result is False, then program flow continues to the statement following the for. After each execution of the statements in the body, execute the loop-expression. / / prepare myemaJO] = // the f o r for ( i=1; {
}
f o r the f o r loop Close[0] ; loop i < BarCount; i + + )
myema[i] = 0 . 1 * C 1 0 s e [ i ] + 0 . 9 * m y e m a [ i - 1 ] ;
/ / whatever code comes a f t e r t h e f o r l o o p P l o t (C, " C " , c o l o r B l a c k , s t y l e C a n d l e ) ; P l o t (myema, "MyEma", c o l o r R e d , s t y l e L i n e ) ;
AFL - AmiBroker Formula Language
265
if... else The syntax for the if... else statement is: if (expression) statementl [ else statement2] or, more symetrically: if (expression) { statementl; 1 else I statement2;
} if and else are keywords. The portion in the [ ] in the first explanation is optional (the brackets are not m e a n t to indicate an array index). The else is optional. The second explanation includes the else portion, which will have an e m p t y statement if there is no action to take. (expression) is evaluated. If it is True, statementl is executed. If it is False and there is an else clause, statement2 is executed. If it is False and there is no else clause, no action is taken. For example: i = 1; i f ( i > 1) p r i n t f ( " i i s big else printf
\n");
( " i i s small
\n");
if... else statements can be nested. For example: i = 2;
j = 4;
if
( i > 1) i f (j > i) p r i n t f ( " i i s big \ n " ) ; else p r i n t f ( " i i s small \ n " ) ;
The question immediately arises: "which if gets the else?" The best answer, from good p r o g r a m m i n g practice, is to use a full complement of braces so the question never arises. The answer to the question as it
266
Introduction to AmiBroker
stands is: the else goes with the closest if that does not already have an else. The spacing on the page does not enter into the discussion at all. Don't let ambiguity into your p r o g r a m s - use a full set of braces. The fully braced equivalent to the example above is: i = 2;
= נ4;
if {
( i > 1) if {
(j
> i)
printf
( " i is big
\n") ;
printf
( " i i s small
}
else {
}
\n");
}
else {
}
Run each of these. (Use the C o m m e n t a r y w i n d o w for quick and dirty testing.) First as they stand, then with j set to 0. Important note. The values being compared in the expression part of the if ... else are scalars - single values. If ... else can only be used on scalars, not on arrays. You can test to determine whether H[i] > H[i-1]. But you cannot test whether H > Ref(H,־l). The first is testing two single numbers, and the result is clearly either True or False. The second is testing two arrays, and the result is not defined. switch The syntax of the switch statement is: switch (expression) { case constant-expressionl: 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 n u m b e r of case instances, but no two case constants within the same
AFL - AmiBroker Formula Language
267
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 the first match will be used. Example: f o r ( n = 0; n < 10; n++ ) { p r i n t f ( " C u r r e n t n = % f \ n " , n ); switch(n) { case 0: p r i n t f ( " T h e number i s z e r o . \ n " ) ; break; case 3: case 5: case 7: p r i n t f ( " n i s a prime n u m b e r \ n " ) ; break; case 2: p r i n t f ( " n is a prime n u m b e r \ n " ) ; case 4: case 6: case 8: p r i n t f ( " n i s a n even n u m b e r \ n " ) ; break; case 1: case 9: p r i n t f ( " n is a perfect square\n"); break; default: p r i n t f ( " O n l y s i n g l e - d i g i t numbers are a l l o w e d \ n " ) ; break;
}
268
Introduction to AmiBroker
while The while statement lets you repeat a statement until a specified expression becomes false. The syntax of the while statement is: while (expression) statement; The expression must have an arithmetic (numeric or logical) type. Execution proceeds as follows: 1.
The expression is evaluated.
A. If the 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. B. If the expression is true (nonzero), the body of the statement is executed and the process is repeated b e g i n n i n g at step 1. This is an example of the while statement: i = 10; w h i l e ( i < 20 ) { P l o t ( MA( C l o s e , i ), "MA" + W r i t e V a l ( i, 0 ), c o l o r B l a c k + i ); i = i + 1;
} The example plots 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 - bar moving averages.
AFL - AmiBroker Formula Language
269
FLAGS
In order to reduce the size of computer programs, early computer scientists devised the use of flags to allow one computer storage location (originally a byte or word, now a byte, word, or generic variable) to store the on or off state of many variables. For example, assume the mouse has three buttons: left, right, and center. Each button can be either up or d o w n (unclicked or clicked), and more than one may be clicked at one time. The state of any button could be stored by assigning 0 if that button is up or unclicked, 1 if that button is down or clicked. The state of all three buttons could be stored in three variables, for example: LeftButton = 0; RightButton = 1; CenterButton = 0; By using flags, the states of all three buttons can be stored in one variable. Imagine a storage scheme to be a series of bits (binary digits). Let the first bit (right-most, when actually using bits) represent the state of the left button, the second bit represent the state of the right button, and the third bit represent the state of the center button. Continuing with the bit analogy, the value or weight of each position increases by a factor of 2 moving right to left. The right-most bit posi-
Third bit
Second bit
Right most bit
Center Button
Right Button
Left Button
No b u t t o n s c l i c k e d
0
0
0
0
Right b u t t o n c l i c k e d
0
1
0
2
Center button clicked
1
0
0
4
Left and Right b u t t o n s c l i c k e d
0
1
1
3
T h e " V a l u e " of each bit p o s i t i o n
4
2
1
Flag Value
270
Introduction to AmiBroker
tion has a position value of 1, the next a value of 2, then 4, 8, 16, and so on. Combining the up or d o w n state with the value of the bit position, the left button is coded as 1 (the value of its bit position) times either 0, if it is up, or 1, if it is down. The right button is coded as 2 (the value of its bit position) times either 0 or 1. The center button is coded as 4 (the value of its bit position) times either 0 or 1. So the state of all three buttons is stored in one variable, say MouseButtons, by adding together the values for the three individual buttons. To describe the states of three buttons in terms of flags, we say that: 0 means no button is d o w n 1 means the left button is d o w n 2 means the right button is down 4 means the center button is d o w n The possible combinations range from 0 (no buttons down) to 7 (all three buttons down). If both the left and right buttons are down, we can store this using the statement: MouseButtons = 3;
If we want to test that only the right mouse button is down, we might use this statement: RightDown = MouseButtons == 2;
IIF (MouseButtons == 2, sometruething, otherfalsething); The flag concept can be used for both storing values and retrieving them. It is often used to specify the desired states of a large number of binary variables. See Graph Styles, for example.
AFL - AmiBroker Formula Language
271
A F L FUNCTION REFERENCE AmiBroker has several h u n d r e d functions available for you to use as you write your AFL programs. This section of the book lists all of them, and describes some of the ones you might find most useful. For more information, including descriptions of those not fully described here, please see the AmiBroker User's Guide, AFL Function Reference. The functions have been g r o u p e d together according to their p r i m a r y use. Note carefully what data structure each function returns. Most are arrays. LOWEST/HIGHEST
HHV - Highest high value Syntax: HHV (
ARRAY,
periods )
Returns: ARRAY
Function: Calculates the highest value in the A R R A Y over the preceding periods (periods includes the current day). Example: The formula "HHV( close, 4)" r e t u r n s the highest closing price over the preceding four periods. "HHV( high, 8)" r e t u r n s the highest high price over the preceding eight periods.
HHVBars - Bars since highest high Syntax: HHVBars (
ARRAY,
periods )
Returns: ARRAY
Function: Calculates the n u m b e r of periods that have passed since the A R R A Y reached its periods period peak. Example: The formula "HHVBars( close, 30 )" r e t u r n s the n u m b e r of periods that have passed since the closing price reached its 30-period peak.
272
Introduction to AmiBroker
Highest - Highest value Syntax: Highest
(ARRAY)
Returns: ARRAY
Function: Calculates the highest value in the loaded in the chart.
ARRAY
since the first day
Example: The formula Highest( MFI(14)) returns the highest Money Flow Index value. Highest ( Close ) returns the highest closing price.
HighestBars - Bars since highest value Syntax: HighestBars
(ARRAY)
Returns: ARRAY
Function: Calculates the number of periods that have passed since the ARRAY'S highest value. Example: The formula "HighestBars( close )" returns the number of periods that have passed since the closing price reached its highest peak.
HighestSince - Highest value since condition met Syntax: HighestSince(
EXPRESSION, ARRAY,
Nth = 1 )
Returns: ARRAY
Function: Returns the highest ARRAY value since on the Nth most recent occurrence.
EXPRESSION
was true
Example: HighestSince( Cross( macd(), 0 ), Close, 1 ) returns the highest close price since macd() has crossed above zero.
AFL - AmiBroker Formula Language
273
HighestSinceBars ־Bars since highest value since condition met Syntax: HighestSinceBars(
EXPRESSION, ARRAY,
Nth = 1 )
Returns: ARRAY
Function: Returns the number of bars that have passed since highest A R R A Y value since EXPRESSION was true on the Nth most recent occurrence. Example: HighestSinceBars( Cross( macd(), 0 ), Close, 1 ) returns the number of bars passed since the highest close price was detected from the time when macd() has crossed above zero.
LLV - Lowest low value Syntax: LLV(
ARRAY,
periods )
Returns: ARRAY
Function: Calculates the lowest value in the A R R A Y over the preceding periods (periods includes the current day). Example: The formula "LLV( close, 14 )" returns the lowest closing price over the preceding 14 periods.
LLVBars - Bars since lowest low Syntax: LLVBars(
ARRAY,
periods)
Returns: ARRAY
Function: Calculates the number of periods that have passed since the A R R A Y reached its periods period trough. Example: The formula "LLVBars( close,50 )" returns the number of periods that have passed since the closing price reached its 50 period trough.
274
Introduction to AmiBroker
Lowest - Lowest value Syntax: Lowest( ARRAY ) Returns: ARRAY
Function: Calculates the lowest value in the ARRAY. Example: The formula Lowest( RSI(14)); returns the lowest Relative Strength Index value. Lowest ( close ) returns the lowest closing price.
LowestBars - Bars since lowest Syntax: LowestBars( A R R A Y ) Returns: ARRAY
Function: Calculates the number of periods that have passed since the ARRAY'S lowest value. Example: The formula "LowestBars( Close )" returns the number of periods that have passed since the closing price reached its lowest point.
LowestSince - Lowest value since condition met Syntax: LowestSince( EXPRESSION, ARRAY, Nth = 1 ) Returns: ARRAY Function: Returns the lowest ARRAY value since EXPRESSION was true on the Nth most recent occurrence. Example: LowestSince( Cross( MACD(), 0 ), Close, 1 ) returns the lowest close price since MACD() has crossed above zero.
AFL - AmiBroker Formula Language
275
LowestSinceBars - Bars since lowest value since condition met Syntax: LowestSinceBars( EXPRESSION, ARRAY, Nth = 1 ) Returns: ARRAY
Function: Returns the number of bars that have passed since lowest ARRAY value since EXPRESSION was true on the Nth most recent occurrence. Example: LowestSinceBars( Cross( MACD(), 0 ), Close, 1 ) returns the number of bars passed since the lowest close price was detected from the time when MACD() has crossed above zero.
M A T H FUNCTIONS
abs - absolute value Syntax: abs( NUMBER) a b s ( 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. The formula "abs(C-Ref(C,-l))" will return the array containing the absolute value of the day to day point change.
acos - arccosine function Syntax: acos( x ) Returns: NUMBER, ARRAY
276
Introduction to AmiBroker
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. Example: The formula "acos(0.916)" returns 0.413.
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 up to defined accuracy (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 point accuracy issues. Parameters: x, y - the numbers or arrays to be compared, ulps stands for ״units in last place" and represents maximum relafive error of the comparison. Since 32 bit IEEE floating point numbers have accuracy 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 roughly 0.00005% "comparison sensitivity". Thanks to Bruce Dawson for his fast routine. Example: i f ( 1/3 == 0.333333 ) p r i n t f ( " 3 2 - b i t F l o a t i n g p o i n t IEEE exact e q u a l i t y \ n " ) ; else printf
("The numbers are not e x a c t l y equal \ n " ) ;
i f ( AlmostEqual( 1 / 3 , 0.3333333 )
)
p r i n t f ( " N u m b e r s are almost e q u a l \ n " ) ;
Run it again with: if( 4/2 == 2 )
AFL - AmiBroker Formula Language
277
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 Example: The formula "asin ( 0.5 )" returns 0.524.
atan - arctangent function Syntax: atan( N U M B E R ) 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 0.785, Pi/4.
atan2 - arctangent of y/x 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.
278
Introduction to AmiBroker
Example:
f f c = FFT(data,Len); f o r ( i = 0; i < Len - 1; i = i + 2 ) { amp[ i ] = amp[ i + 1
]A2);
] = s q r t ( f f c [ i ]' 2
phase[ i ] = phase[ i + 1
+
ffc[ i + 1
] = atan2( f f c [ i + 1 ] , f f c [ i ]
); }
ceil ־ceiling value Syntax: ceil( ceil(
NUMBER ) 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.
cos - cosine function Syntax: COS( NUMBER ) c o s ( ARRAY )
Returns: NUMBER ARRAY
Function: Returns the cosine of NUMBER or ARRAY. Assumes that the NUMBER or ARRAY values are in radians. Example: The formula "cos( 0.5 )" returns 0.878.
AFL - AmiBroker Formula Language
279
cosh - hyperbolic cosine function Syntax: cosh( N U M B E R ) cosh( ARRAY ) Returns: NUMBER ARRAY
Function: Returns the hyperbolic cosine of NUMBER or ARRAY. This function assumes that the ARRAY values are in radians. Example: cosh ( 0.5 ) returns 1.128.
exp - exponential function Syntax: e x p ( NUMBER ) e x p ( ARRAY )
Returns: NUMBER ARRAY
Function: Calculates e raised to the NUMBER or ARRAY power. Example: exp (0.5 ) returns 1.649.
floor - floor value Syntax: floor( NUMBER ) floor( ARRAY ) Returns: NUMBER ARRAY
Function: Calculates the highest integer that is less than NUMBER or ARRAY.
Example: The function floor( 18.9 ) returns 18. The formula floor( -19.9 ) returns -20.
280
Introduction to AmiBroker
frac - fractional part Syntax: frac( N U M B E R ) frac( ARRAY ) Returns: NUMBER ARRAY
Function: Eliminates the integer portion of NUMBER or ARRAY and returns the fractional part. Example: The formula frac( 12.4 ) returns 0.4. The formula frac(-15.7 ) returns -0.7.
int - integer part Syntax: int( NUMBER) i n t ( ARRAY )
Returns: NUMBER ARRAY
Function: Removes the fractional portion of NUMBER or ARRAY and returns the integer part. Example: The formula "int( 10.7 )" returns 10. The formula "int(-19.8 )" returns -19.
log - natural logarithm Syntax: l o g ( NUMBER ) l o g ( ARRAY )
Returns: NUMBER ARRAY
Function: Calculates the natural logarithm of NUMBER or ARRAY. Example: log ( 9.5 ) returns 2.251.
AFL - AmiBroker Formula Language
281
loglO - decimal logarithm Syntax:
loglO( loglO(
NUMBER ) ARRAY )
Returns: NUMBER ARRAY
Function: Calculates the decimal logarithm of
NUMBER
or
ARRAY.
Example: loglO ( 9.5 ) returns 0.978.
Max - Maximum value of two numbers / arrays Syntax: M a x ( NUMBERl, NUMBER2 ) M a x ( ARRAY1, A R R A Y 2 )
Returns: NUMBER ARRAY
Function: Returns the largest of the two parameters. Example: The formula "Max( Close, 10 )" returns either the closing price or 10, whichever is greater. The formula "Max(-14, 13)" always returns 13.
Min - Minimum value of two numbers / arrays Syntax: M i n ( NUMBERl, NUMBER2 ) M i n ( ARRAY1, A R R A Y 2 )
Returns: NUMBER ARRAY
Function: Returns the smallest of the two parameters. Example: The formula "min( Close, 10 )" returns the closing price or 10, whichever is less. The formula "min(-14, 13)" always returns -14.
282
Introduction to AmiBroker
Prec - Adjust number of decimal places Syntax: Prec( NUMBER, precision) Prec( ARRAY, precision ) Returns: NUMBER ARRAY
Function: Truncates NUMBER or ARRAY to precision decimal places. Example: The formula "prec( 10.12981, 2 )" returns 10.120. The formula "prec( 10.12981, 4 ) ״returns 10.12980.
round - Round number to nearest integer Syntax: round( NUMBER ) round( ARRAY ) Returns: NUMBER ARRAY
Function: Rounds NUMBER or ARRAY to the nearest integer. Example: The formula "round( +11.5 )" returns +12. The formula "round( -11.4 )" returns -11.
sign - Returns the sign of the number or array Syntax: sign( x ) Returns: ARRAY NUMBER
Function: The sign function returns 1 if x value is greater than zero, -1 if the x is less than zero and 0 if x equals zero, x can be a number or array. Example: sign (-2.5) returns -1.
AFL - AmiBroker Formula Language
283
sin - sine function Syntax: s i n ( NUMBER ) s i n ( ARRAY )
Returns: NUMBER ARRAY
Function: Returns the sine of NUMBER or ARRAY. This function assumes that the NUMBER or ARRAY values are in radians. Example: You can plot a sine wave using the formula "sin(cum(0.05))." Increasing the value in this formula (i.e., "0.05") will increase the frequency of the sine wave.
sinh - hyperbolic sine function Syntax: sinh( N U M B E R ) sinh( ARRAY ) Returns: NUMBER ARRAY
Function: Returns the hyperbolic sine of NUMBER or ARRAY. This function assumes that the NUMBER or ARRAY values are in radians. Example: sinh ( 0.92) returns 1.055.
sqrt - square root Syntax: sqrt( NUMBER ) sqrt( ARRAY ) Returns: NUMBER ARRAY
Function: Calculates the square root of NUMBER or ARRAY. The square root of a negative number returns NAN (Not a Number). Example: The formula "sqrt( 16 )" returns 4
284
Introduction to AmiBroker
tan - tangent function Syntax: t a n ( NUMBER) t a n ( ARRAY)
Returns: NUMBER ARRAY
Function: Returns the tangent of NUMBER or ARRAY. This function assumes that the NUMBER or ARRAY values are in radians Example: tan (1.0 ) returns 1.557.
tanh - hyperbolic tangent function Syntax: tanh( N U M B E R ) tanh( ARRAY ) Returns: NUMBER ARRAY
Function: Returns the hyperbolic tangent of NUMBER or ARRAY. This function assumes that the NUMBER or ARRAY values are in radians. Example: tanh ( 0.8 ) returns 0.664.
AFL - AmiBroker Formula Language
285
M O V I N G AVERAGES, S U M M A T I O N
AMA - Adaptive moving average Syntax: AMA(
ARRAY,
SmoothingFactor )
Returns: ARRAY
Function: Calculates adaptive moving average - similar to EMA() but smoothing factor could be time-variant (array). Example: The example of volatility-weighted adaptive moving average formula: Plot (C,"C", c o l o r B l a c k , s t y l e C a n d l e ) ; Plot(EMA( Close, 15 ), "EMA", c o l o r R e d , s t y l e L i n e ) ; fast = 2/(2+1); slow = 2 / ( 3 0 + 1 ) ; dir=abs(Close-Ref(Close,-10)); vol=Sum(abs(Close-Ref(Close,-1)),10); ER=dir/vol; sc =( E R * ( f a s t - s l o w ) + s l o w ) " 2 ; Plot(AMA( Close, sc ), "AMA", c o l o r B l u e , s t y l e L i n e ) ;
AMA2 - Adaptive moving average 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-SmoothingFactor). Internally this function works like this: today_ ama = SmoothingFactor * array + FeedBackFactor * yesterday am a
286
Introduction to AmiBroker
Example: The example of volatility-weighted adaptive moving average formula: Plot (C,"C", colorBlack,styleCandle); Plot(EMA( C l o s e , 15 ), "EMA", c o l o r R e d , s t y l e L i n e ) ; fast = 2/(2+1); slow = 2 / ( 3 0 + 1 ) ; dir=abs(Close-Ref(Close,-10)); vol=Sum(abs(Close-Ref(Close,-1)),10); ER=dir/vol; sc =( E R * ( f a s t - s l o w ) + s l o w ) " 2 ; P l o t ( AMA2( C l o s e , s c , 1 - s c ) , " A M A 2 " , c o l o r B l u e , s t y l e L i n e ) ;
Cum - Cumulative sum Syntax: c u m ( NUMBER ) c u m ( ARRAY )
Returns: NUMBER ARRAY
Function: Calculates a cumulative sum of the ARRAY from the first period in the chart. 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 ));
DEMA - Double exponential moving average Syntax: D E M A ( ARRAY, p e r i o d s )
Returns: ARRAY
Function: Calculates double exponentially smoothed average - DEMA. The function accepts time-variable periods. Example: DEMA( Close, 5 )
AFL - AmiBroker Formula Language
287
EMA - exponential moving average Syntax: E M A ( ARRAY, p e r i o d s )
Returns: ARRAY
Function: Calculates a periods exponential moving average of ARRAY. Example: EMA( close, 5 )
MA - Simple moving average Syntax: M A ( ARRAY, p e r i o d s )
Returns: ARRAY
Function: Calculates a periods simple moving average of ARRAY. Example: MA(CLOSE, 5)
Sum - Sum data over specified number of bars Syntax: S u m ( ARRAY, p e r i o d s )
Returns: ARRAY
Function: Calculates a cumulative s u m of the ARRAY for the specified number of lookback periods (including today). Example: The formula "Sum( Close, 14 )" returns the s u m of the preceding 14 closing prices. A 14-period simple moving average could be written "sum(C,14) / 14.״
288
Introduction to AmiBroker
TEMA - Triple exponential moving average Syntax: T E M A ( ARRAY, p e r i o d s )
Returns: ARRAY
Function: Calculates triple exponentially smoothed average ־TEMA. The function accepts time-variable periods. Example: TEMA( Close, 5 )
Wilders - Wilder's smoothing Syntax: Wilders( ARRAY, periods ) Returns: ARRAY
Function: Calculates Wilder's average of the ARRAY using periods averaging range Example: Wilders( close, 10 );
WMA - Weighted moving average Syntax: W A M ( ARRAY, p e r i o d s )
Returns: ARRAY
Function: Calculates weighted average. 5 day weighted average gives weight of 5 to the most recent quote, 4 to the previous quote, down to 1 for the 5-bar back quote. The function accepts time-variable periods. Example: WMA( Close, 5 )
AFL - AmiBroker Formula Language
289
STATISTICAL FUNCTIONS
Correlation - Correlation Syntax: Correlation(
ARRAY1, ARRAY2,
periods )
Returns: ARRAY
Function: Calculates correlation between periods range.
ARRAY1
and
ARRAY2
using
Example: Calculate the 25 period correlation between Close price and Close price 5 days back with this statement, Correlation( Close, Ref( Close, -5 ), 25 ); / / B u i l t - i n c o r r e l a t i o n can b e re-coded w i t h // basic AFL f u n c t i o n s l i k e MA (moving average) - which / / i s e q u i v a l e n t f o r "expected v a l u e " s t a t i s t i c term // and few basic a r i t h m e t i c o p e r a t i o n s f u n c t i o n C o r r e l ( x, y, number ) { nom = MA( x * y, number ) - MA( x, number ) * MA( y, number ); denom = s q r t ( MA( x A 2, number ) - MA( x, number ) A 2 ) * s q r t ( MA( y A 2, number ) - MA( y, number ) A 2 ); r e t u r n nom / denom; } P l o t ( C o r r e l a t i o n ( C, Ref( H, colorRed,styleLine);
-2 ), 10 ), " b u i l t - i n " ,
P l o t ( C o r r e l ( C, Ref( H, -2 ), 10 ), " r e - c o d e d " , colorBlue,styleLine);
LinearReg ־Linear regression end-point Syntax: LinearReg(
ARRAY,
periods )
Returns: ARRAY
Function: Calculates linear regression line end-point value according to a + b * x (where a and b are intercept and slope of linear regression line) from the ARRAY using periods range. Example: LinearReg( Close, 10 );
290
Introduction t o AmiBroker
LinReglntercept - Intercept of the linear regression line Syntax: LinReglntercept(
ARRAY,
periods)
Returns: ARRAY
Function: Calculates intercept of linear regression line - the "a" coefficient in a + b*x (LinRegSlope calculates b) from the ARRAY using periods range. Example: DaysBack = 10; L r i = L i n R e g I n t e r c e p t ( C , Daysback); P l o t ( Close, " C l o s e " , c o l o r B l a c k , s t y l e C a n d l e ) ; Plot ( L r i , "LRI", colorRed,styleLine|styleOwnScale);
LinRegSlope - Linear regression slope Syntax: LinRegSlope( ARRAY, periods ) Returns: ARRAY
Function: Calculates linear regression line slope from the periods range.
ARRAY
Example: DaysBack = 10; Lrs = LinRegSlope(C, Daysback); P l o t ( Close, " C l o s e " , c o l o r B l a c k , s t y l e C a n d l e ) ; P l o t ( L r s , "LRS", c o l o r B l u e , s t y l e L i n e | s t y l e O w n S c a l e ) ;
using
AFL - AmiBroker Formula Language
291
Median - Calculate median (middle element) Syntax: Median(
ARRAY,
period )
Returns: ARRAY
Function: The Median function - finds median (middle element) value of the ARRAY over period elements. Example: / / l i s t o n l y symbols which volume i s g r e a t e r than // median Volume from past 50 days F i l t e r = Volume > Median( Volume, 50 ); AddColumn( V, "Volume" );
mtRandom - Mersene Twister random number generator (single number version) Syntax: mtRandom( seed = N u l l ) Returns: NUMBER
Function: mtRandom( seed = N u l l ) - returns a single random number (scalar) in the range [0,1) seed is the random generator seed value. If you don't specify one, the random number generator is automatically initialized with current time as a seed that guarantees unique sequence. If you want a repeatable sequence, you must supply your o w n seed. Both functions use Mersene Twister mtl9973ar-cok algorithm. (Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura.) Mersene Twister has a period of 2A19973 (approximately 2.9*10A6012) and is vastly superior to C-runtime pseudo-random generator available via Random() function.
292
Introduction to AmiBroker
mtRandomA - Mersene Twister random number generator (array version) Syntax: mtRandomA( seed = N u l l ) Returns: ARRAY
Function: mtRandom( seed = N u l l ) - returns an array of random numbers in the range [0,1)
Percentile - Calculate percentile Syntax: Percentile(
ARRAY,
period, rank )
Returns: ARRAY
Function: The Percentile function gives rank percentile value of the array over last period bars. rank is 0..100 - defines percentile rank in the array Performance note: the implementation of percentile function involves sorting that is a relatively slow process even though the quicksort algorithm is used. Examples: // Example 1: // show bars when ' c u r r e n t ' Day Volume ranks w i t h i n // TOP 30% of volumes of l a s t 100 bars / / ( i s above 70th P e r c e n t i l e ) F i l t e r = Volume > P e r c e n t i l e ( Volume, 100, 70 ); // Example 2: // show bars when ' c u r r e n t ' Day Volume ranks w i t h i n // BOTTOM 30% of volumes of l a s t 100 bars / / ( i s below 30th p e r c e n t i l e ) F i l t e r = Volume < P e r c e n t i l e ( Volume, 100, 30 );
AFL - AmiBroker Formula Language
293
Random - Random number Syntax: Random( seed = N u l l ) Returns: ARRAY Function: Returns an array of random values in 0..1 range. To get a single random value use LastValue( Random()). Seed initializes the random number generator. This allows either a reproducible series of pseudo-random numbers - the same seed always produces the same random number series - or a random series. If the seed is not specified, the series is random. If the seed is the number 1, the series is reproducible. Any other value for seed sets the generator to a random starting point. Examples: FIN = Random(); // generates d i f f e r e n t sequences RM = Random(1); // generates t h e same sequence
StdErr - Standard error Syntax: StdErr( ARRAY, p e r i o d s ) Returns: ARRAY
Function: Calculates the standard error function (standard error of linear regression estimate) of the ARRAY over periods bars. Example: StdErr( close, 10 );
StDev - Standard deviation Syntax: StDev( ARRAY, periods) Returns: ARRAY
Function: Calculates the moving standard deviation of the ARRAY over periods bars Example: StDev( close, 10 );
1צu
Introduction to AmiBroker TSF - Time series forecast Syntax: TSF(
ARRAY,
periods)
Returns: ARRAY
Function: Calculates the time series forecast indicator (similar to LinearReg but differs by the value of lin reg slope) Example: P l o t ( Close, " P r i c e " , c o l o r B l u e , s t y l e C a n d l e ) ; P l o t ( TSF(C10se,5), "Time S e r i e s F o r e c a s t " , colorRed );
BASIC PRICE PATTERN D E T E C T I O N
FFT - Performs Fast Fourier Transform Syntax: FFT( array, len = 0 ) Returns: ARRAY
Function: The function performs the FFT (Fast Fourier Transform) on the last 'len' bars of the array. If len is set to zero, then FFT is performed on entire array. The len parameter must be even. Result: The function returns an array that holds FFT bins for the first 'len' bars. There are len/2 FFT complex bins returned, where bin is a pair of numbers (complex number): first is real part of the complex number and second number is the imaginary part of the complex number. result = FFT( array, 256 ); where: Oth bin (result[0] and resultfl]) represents DC component, 1st bin (resultfl ] and result[2]) represents real and imaginary parts of lowest frequency range and so on up to result[ len - 2 ] and result[ len -1 ] The remaining elements of the array are set to zero.
AFL - AmiBroker Formula Language
295
// FFT.afl SetBarsRequired(100000,100000); Len = Param("FFT L e n g t h " , 1024, 64, Len = Min( Len, BarCount );
10000, 10 );
x = Barlndex(); x1 = x - BarCount + Len; i n p u t = C; a = L a s t V a l u e ( L i n R e g l n t e r c e p t ( i n p u t , Len - 1 ) ); b = L a s t V a l u e ( LinRegSlope( i n p u t , Len - 1 ) ); Lr = a + b * x1; data = i n p u t
- L r ; / / de-trending
f f c = FFT(data,Len);
f o r ( i = 0; i < Len - 1; i = i + 2 ) { amp[ i ] = amp[ i + 1
] = s q r t ( f f c [ i ]' 2
+
ffc[ i + 1
]"2);
);
phase[ i ] = phase[ i + 1
] = atan2( f f c [ i + 1 ] , f f c [ i ]
auto = ParamToggle("Auto dominant c y c l e " , " N o | Y e s " , sbar = Param( "Which FFT b i n " , 1, 0, 50 ); s k i p b i n l = ParamToggle("Skip 1st FFT b i n " ,
"No|Yes",
1
); 1
);
i f ( auto ) { sbar = i n t ( LastValue(ValueWhen( amp == L a s t V a l u e ( H i g h e s t ( I l f ( s k i p b i n l AND x < 4, 0 , amp ) ) ) ־x / 2 )) ); } fv = S t a t u s ( " f i r s t v i s i b l e b a r " ) ; t h i s b a r = Ref( i n t ( x / 2 ) = = s b a r , - f v ) ; Plot( Ref(amp,-fv), " a m p l i t u d e ( b i n " + Ref( i n t ( x / 2 ) , - f v ) + " ) " , I l f ( t h i s b a r , colorRed, colorBlack ) , s t y l e A r e a ) ; P l o t ( I l f ( BarCount - B a r l n d e x ( ) < Len, d a t a , N u l l ) , " d e - t r e n d e d i n p u t ("+Len+" b a r s ) " , c o l o r O r a n g e , s t y l e L e f tAxisScale ); P l o t ( cos( phase[ sbar * 2 ] + ( s b a r ) * x1 * 2 * 3.1415926 / Len ) , " dominant c y c l e "+ L e n / ( s b a r ) + " ( " + sbar + " b i n ) b a r s " , c o l o r B l u e , styleOwnScale ); GraphZ0rder=1; GraphXSpace = 10;
1צu
Introduction to AmiBroker GapDown ־Gap down Syntax: GapDown() Returns: ARRAY
Function: Returns a "1" or "true" on the day a security's prices gap down. Otherwise the result is "0". A gap down occurs if yesterday's low is greater than today's high. Example: GD = GapDown();
GapUp - Gap up Syntax: GapUp() Returns: ARRAY
Function: Returns a "1" or "true" on the day a security's prices gap up. Otherwise the result is "0". A gap up occurs if yesterday's high is less than today's low. Example: GU = CapUp();
Inside - Inside day Syntax: Inside() Returns: ARRAY
Function: Returns a "1" or "true" when an inside day occurs. Gives "0" otherwise. An inside day occurs when today's high is less than yesterday's high and today's low is greater than yesterday's low. Example: ID = Inside();
AFL - AmiBroker Formula Language
297
Outside - Outside day Syntax: Outside() Returns: ARRAY
Function: Returns "true" (or 1) when an outside day occurs. An outside day is when today's high is greater than yesterday's high and today's low is lower than yesterday's low. Example: Outside()
Peak - Peak Syntax: Peak(
ARRAY,
change, n = 1)
Returns: ARRAY
Function: Returns the value of A R R A Y n-th peak(s) ago. This uses the Zig Zag function (see Zig Zag) to determine the peaks, n =1 would return the value of the most recent peak, n =2 would return the value of the 2nd most recent peak. Example: Peak(Close,5,l) Notes: •
Zig, Peak, and Trough functions work correctly for arrays containing data greater than zero.
•
This function is based on Zig-Zag indicator and may look into the future.
1צu
Introduction to AmiBroker PeakBars - Bars since peak Syntax: PeakBars(
ARRAY,
change, n =
1)
Returns: ARRAY
Function: Gives the number of bars that have passed from the n-th peak. This uses the Zig Zag function (see Zig Zag) to determine the peaks, n =1 would return the number of bars that have passed since the most recent peak, n =2 would return the number of bars that have passed since the 2nd most recent peak. Example: PeakBars( Close,5,1) Notes: • •
Zig, Peak, and Trough functions work correctly for arrays containing data greater than zero. This function is based on Zig-Zag indicator and may look into the future.
Trough - Trough Syntax: Trough(
ARRAY,
change, n =
1)
Returns: ARRAY
Function: Gives the value of A R R A Y n-th trough(s) ago. This uses the Zig Zag function (see Zig Zag) to determine the troughs. Example: Trough( Close,5,1) Notes: • •
Zig, Peak, and Trough functions work correctly for arrays containing data greater than zero. This function is based on Zig-Zag indicator and may look into the future.
AFL - AmiBroker Formula Language
299
TroughBars - Bars since trough Syntax: TroughBars(
ARRAY,
change, n =
1)
Returns: ARRAY
Function: Returns the number of bars that have passed from the n-th trough. This uses the Zig Zag function (see Zig Zag) to determine the troughs. Example: TroughBars( Close,5,1) Notes: •
Zig, Peak, and Trough functions work correctly for arrays containing data greater than zero.
•
This function is based on Zig-Zag indicator and may look into the future.
Zig - Zig-zag indicator Syntax: Zig(
ARRAY,
change)
Returns: ARRAY
Function: Calculates the minimum % change Zig Zag indicator. Caveat: this function is based on Zig-Zag indicator and may look into the future - this means that you can get unrealistic results when back testing trading system using this indicator. This function is provided rather for pattern and trend recognition formulas. Example: Zig( Close,5) Notes: • ״
Zig, Peak, and Trough functions work correctly for arrays containing data greater than zero. This function is based on Zig-Zag indicator and may look into the future.
1צu
Introduction to AmiBroker COMPOSITES
AddToComposite ־Add value to composite ticker Syntax: AddToComposite( array, "ticker", "field", flags = atcFlagDefaults ) Returns: NOTHING
Function: Allows you to create composite indicators with ease. The parameters are: • 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 tilde as the first character of the symbol (~comp) •
"field" - 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, "X" ־updates all OHLC fields at once
•
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 atcFlagDefaults = 7 (this is a composition of atcFlagResetValues I atcFlagCompositeGroup I atcFlagTimeStamp flags) atcFlagEnablelnBacktest = 8 - allow running AddToComposite in backtest/optimization mode atcFlagEnablelnExplore = 16 ־allow running AddToComposite in exploration mode atcFlagResetValues = 32 - reset values at the beginning of scan (not required if you use atcFlagDeleteValues) atcFlagEnablelnPortfolio = 64 - allow running AddToCom-
AFL - AmiBroker Formula Language
301
posite in custom portfolio backtester phase atcFlagEnablelnlndicator = 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 atcFlagEnablelnBacktest or atcFlagEnablelnExplore flags are specified. And it does not affect composite ticker when run in Indicator or Commentary mode, so it is possible to combine scan and indicator into a single formula. Example: AddToComposite( MACD() > 0, "-BullMACD", "V;)״ AddToComposite is an extremely powerful function. An extensive discussion of it is beyond the scope of this book. There is an excellent reference and tutorial, Introduction to the AmiBroker AddToComposite(), a 32 page pdf document, written by Herman van den Bergen in 2002. You can find it at: http://www.amibroker.org/3rdparty/Intr0T0Atc.pdf.
ADLine - Advance/decline line Syntax: ADLine() Returns: ARRAY
Function: Calculates the Advance/Decline line indicator Example: ADLine()
Advlssues - Advancing issues Syntax: Advlssues() Returns: ARRAY
Function: Returns the number of advancing issues for a given market (the one that the current stock belongs to) Example: Advlssues()
1צu
Introduction to AmiBroker AdvVolume - Advancing issues volume Syntax: AdvVolume() Returns: ARRAY
Function: Returns the volume of advancing issues for a given market (the one that the current stock belongs to) Example: AdvVolume()
Declssues ־Declining issues Syntax: Declssues() Returns: ARRAY
Function: Returns the number of declining issues for a given market (the one that the current stock belongs to) Example: Declssues()
DecVolume - Declining issues volume Syntax: DecVolume() Returns: ARRAY
Function: Returns the volume of declining issues for a given market (the one that the current stock belongs to) Example: DecVolume()
AFL - AmiBroker Formula Language
303
Trin - Traders (Arms) index Syntax: Trin() Returns: ARRAY
Function: Calculates TRIN (Arms Index) indicator. Example: Trin() NOTE: All built-in a/d indicators (AdLine/Trin) work only with composites calculated inside AmiBroker. If you are using the Quotes Plus database for example you should use QP2's own symbols for advances and declines. !NY-A, !NY-D, !NY-AV, !NY-DV The formula for NYSE Trin using the QP2 database is: Armslndex = ( F o r e i g n ( " ! N Y - A " , " C " ) / F o r e i g n ( " ! NY-D", ( F o r e i g n ( " ! N Y - A V " , " C " ) / F o r e i g n ( " ! N Y - D V " , " C " ) ); P l o t ( Armslndex, " T r i n " , colorRed ) ;
"C")
)
/
Unclssues - Unchanged issues Syntax: Unclssues() Returns: ARRAY
Function: Returns the number of unchanged issues for a given market (the one that the current stock belongs to) Example: Unclssues()
1צu
Introduction to AmiBroker UncVolume - Unchanged issues volume Syntax: UncVolume() Returns: ARRAY
Function: Returns the volume of unchanged issues for a given market (the one that the current stock belongs to) Example: UncVolume() INDICATORS
AccDist - Accumulation/distribution Syntax: AccDist() Returns: ARRAY
Function: Calculates the Accumulation/ Distribution indicator. Example: AccDist()
ADX - Average directional movement index Syntax: ADX( period = 14 ) Returns: ARRAY
Function: Calculates the Average Directional Index indicator Example: ADX(), ADX(20)
AFL - AmiBroker Formula Language ATR - Average true range Syntax: ATR( period ) Returns: ARRAY
Function: Calculates the Average True Range indicator Example: ATR(7)
BBandBot - Bollinger band - bottom Syntax: BBandBot( ARRAY, periods = 15, width = 2 ) Returns: ARRAY
Function: Calculates the bottom Bollinger Band of ARRAY. Example: BBandBot( Close, 10, 2 )
BBandTop - Bollinger band - top Syntax: BBandTop( ARRAY, periods = 15, width = 2 ) Returns: ARRAY
Function: Calculates the top Bollinger Band of ARRAY. Example: BBandTop( Close, 10, 2 )
305
1צu
Introduction to AmiBroker CCI - Commodity channel index Syntax: C C I ( p e r i o d s = 14 )
CCIa( ARRAY, p e r i o d s = 14 ) Returns: ARRAY
Function: Calculates the Commodity Channel Index (using periods averaging range ). Second version (CCIa) accepts an input array, so CCI can be applied to an array different than close. Example: CCI( 14 ), CCIa( High, 14 );
Chaikin - Chaikin oscillator Syntax: Chaikin( fast = 9, slow = 14 ) Returns: ARRAY
Function: Calculates the Chaikin Oscillator with averaging parameters: fast, slow Example: Chaikin (9, 14);
GetCursorMouseButtons - Get current state of mouse buttons Syntax: GetCursorMouseButtons() Returns: NUMBER
Function: This function returns mouse button state at the time when chart formula is executed.
AFL - AmiBroker Formula Language
307
Example: i f ( GetCursorMouseButtons() & 1 {
)
p r i n t f ( " l e f t mouse b u t t o n i s p r e s s e d down" }
);
For more information, read the AmiBroker User's Guide.
GetCursorXPosition - Get current X position of mouse pointer Syntax: GetCursorXPosition( mode = 0 ) Returns: NUMBER ( d a t e t i m e )
Function: Retrieves the current mouse pointer X co-ordinate (i.e. datetime of bar under the mouse pointer). Example: T o o l T i p = "X=" + D a t e T i m e T o S t r ( G e t C u r s o r X P o s i t i o n ( ) "nY=" + G e t C u r s o r Y P o s i t i o n ( ) ;
) +
GetCursorYPosition - Get current Y position of mouse pointer Syntax: GetCu rsorYPosition() Returns: NUMBER
Function: Retrieves the current mouse pointer Y co-ordinate (i.e. value in dollars or other Y-axis unit). Example: T o o l T i p = "X=" + D a t e T i m e T o S t r ( G e t C u r s o r X P o s i t i o n ( ) "nY=" + G e t C u r s o r Y P o s i t i o n ( ) ;
) +
1צu
Introduction to AmiBroker MACD - Moving average convergence/divergence Syntax: MACD( fast = 12, slow = 26) Returns: ARRAY
Function: Calculates the MACD indicator using fast and slow averaging periods. Example: The formula "MACD()" returns the value of the MACD indicator (i.e., the red line). The formula "SIGNAL()" returns the value of the MACD's signal line (i.e., the blue line).
MDI - Minus directional movement indicator (-DI) Syntax: MDI( period = 14 ) Returns: ARRAY
Function: Calculates the Minus Directional Movement Indicator (-DI line) Example: MDI()
MFI - Money flow index Syntax: MFI( periods = 14 ) Returns: ARRAY
Function: Calculates the Money Flow Index with period range Example: MDI( 16)
AFL - AmiBroker Formula Language
309
NVI - Negative volume index Syntax: NVI() Returns: ARRAY
Function: Calculates the Negative Volume Index. Example: NVI()
OBV - On balance volume Syntax: OBV() Returns: ARRAY
Function: Calculates the On Balance Volume indicator. Example: OBV()
OscP - Price oscillator Syntax: OscP( fast, slow ) Returns: ARRAY
Function: Calculates the price oscillator based on exponential moving averages Example: OscP(9, 18)
1
צu
Introduction to AmiBroker
OscV - Volume oscillator Syntax: OscV( fast, slow) Returns: ARRAY
Function: Calculates the volume oscillator based on exponential moving averages Example: OscV( 9,18 )
PDI - Plus directional movement indicator Syntax: PDI( period = 14 ) Returns: ARRAY
Function: Calculates the Plus Directional Movement Indicator (-DI line) Example: PDI( 14)
PlotText - Write text on the chart Syntax: PlotText( "text", x, y, color, bkcolor = colorDefault) Returns: NOTHING
Function: This function writes text in specified co-ordinates. Where: x - is x-coordinate in bars (like in LineArray) y - is y-coordinate in dollars color is text color bkcolor is background color If bkcolor is not specified (or equal to colorDefault) text is written with transparent background, any other value causes solid back-
AFL - AmiBroker Formula Language
311
ground with specified background color. Example: P10t(C,"Price", colorBlack, styleLine Plot(MA(C,20),"MA20", colorRed ) ;
);
Buy=Cross( C, MA(C,20 ) ); S e l l ־Cross( MA( C, 20 ), C ); d i s t = 1.5*ATR(10); f o r ( i = 0; i < BarCount; i + + ) { i f ( B u y [ ! ] ) P l o t T e x t ( "Buy\n@" + C[ i ], i, L[ i ) - d i s t [ i ] , colorGreen ); i f ( S e l l [ i ] ) P l o t T e x t ( " S e l l \ n @ " + C[ i ], i, H[ i ] + d i s t [ i ] , colorRed, c o l o r Y e l l o w );
} PlotShapes( Buy * shapeUpArrow + S e l l * shapeDownArrow, I l f ( Buy, colorGreen, colorRed ) );
PVI - Positive volume index Syntax: PVI() Returns: ARRAY
Function: Calculates the Positive Volume Index. Example: PVI ()
RequestTimedRefresh - Forces periodical refresh of indicator pane Syntax: RequestTimedRefresh( interval, onlyvisible = True ) Returns: NOTHING
Function: The function causes the given indicator window to refresh automatically every interval seconds regardless of data source used or connection state. The interval parameter defines timeout in seconds between re-
1צu
Introduction to AmiBroker freshes. AmiBroker attempts to align refreshes to second boundary so if you call it RequestTimedRefresh( 5 ) you should get refreshes at 0, 5,10, 15, 20, 25, 30, 35, 40, 45, 50 and 55 second of the minute. Due to the way regular (low overhead) timers are implemented in Windows they have accuracy of +/-55ms provided the CPU is not very busy. Don't expect to get the first line of your code to execute exactly at .000 milliseconds. This varies depending on machine load, number of quotes, system time slice, and tens of other factors. Usually (on my testing machines) the first line of the code executes anywhere in the first 100 ms of the second, provided that other processes do not interfere. Windows is not a real-time operating system and it does not guarantee any fixed execution/reaction times. The only visible parameter set to True (default value) means that refreshes are triggered only for visible and not minimized windows. This applies also to the main AmiBroker window - when it is minimized charts are not refreshed by default. To force refreshes when a window is minimized you need to set this parameter to False. Note that this visibility applies mostly to the 'minimized' state or the situation when you move the chart outside the boundary of the physical screen so it is not visible (to an eye) but still open. It does not apply to chart windows that are placed on inactive sheets, as they do not really exist until they are shown (this way AmiBroker conserves memory and CPU) and as non-existing, chart windows can not be refreshed. Hint: to detect whenever a given refresh comes from timer or user action you can use the Status("redrawaction") function. It returns 0 for regular refresh (user action) and 1 for timer-refresh. Example: RequestTimedRefresh( 5); // automatically refresh this particular chart every 5 seconds
RMI - Relative Momentum Index Syntax: RMI( periods = 20, momentum = 5 ) Returns: ARRAY
AFL - AmiBroker Formula Language
313
Function: Calculates Altman's Relative Momentum Index (S&C Feb 1993) Example: RMI( 20, 5 )
ROC - Percentage rate of change Syntax: ROC(
ARRAY,
periods = 12, absmode = False )
Returns: ARRAY
Function: Calculates the periods rate-of-change of percentage.
ARRAY
expressed as
if absmode = False the value returned is ( array ־ref( array, -periods ) )/ref( array, -periods ) if absmode = True the value returned is ( array - ref( array, -periods ) )/abs( ref( array, -periods )) Example: The formula roc( Close, 14 ) returns the 14-period percent rate-of-change of the closing prices.
RSI - Relative strength index Syntax: RSI( periods = 14 ) RSIa( ARRAY, periods = 14 ) Returns: ARRAY
Function: Calculates the RSI indicator of the close using periods range The second version, RSIa, accepts an input array so RSI can be applied to other arrays than close. Example: RSI( 12 ) RSIa( High, 12);
1
צ
u
Introduction to AmiBroker
RWI - Random walk index Syntax: RWI( minperiods, maxperiods) Returns: ARRAY
Function: Calculates the Random Walk Index indicator as a difference between Random Walk Index from Highs (RWIHI() function) and Random Walk Index from Lows (RWILO() function. Example: RWI( 9, 40 );
RWIHi - Random walk index of highs Syntax: RWIHi( minperiods, maxperiods) Returns: ARRAY
Function: Calculates the Random Walk Index from Highs. Example: RWIHi( 9, 40 );
RWILo - Random walk index of lows Syntax: RWILo( minperiods, maxperiods ) Returns: ARRAY
Function: Calculates the Random Walk Index from Lows. Example: RWILo( 9, 40 );
AFL - AmiBroker Formula Language
315
SAR - Parabolic stop-and-reverse Syntax: SAR( accel = 0.02, max = 0.2 ) Returns: ARRAY
Function: Calculates the Parabolic SAR indicator. Acceleration is given by accel argument and maximum acceleration level is given by max argument. Example: SAR()
SetBarFillColor - Set bar/candlestick/cloud chart fill color Syntax: SetBarFillColor( colorarray) Returns: NOTHING
Function: SetBarFillColor( colorarray ) allows independent control of candlestick, bar, cloud, and area chart fill color SetBarFillColor must precede the Plot() function call it applies to. When applied to: •
•
styleCandle ־SetBarFillColor controls the color of the interior of the candle body. Shadows and outline are controlled by the color passed in Plot statement styleArea - SetBarFillColor controls the color of interior of histogram bars
•
styleBar - SetBarFillColor controls the color of the bar (H-L). Open and close ticks color is controlled by Plot statement
•
styleCloud - SetBarFillColor controls the color of interior of the cloud. Outline is controlled by the color passed in Plot statement
•
Other styles are not affected
Example: S e t B a r F i l l C o l o r ( I l f ( MACD()>Signal(), c o l o r Y e l l o w , c o l o r B l u e ) ); P l o t ( C, " P r i c e " , I l f ( C > 0, colorGreen, colorRed ), styleCandle );
1צu
Introduction to AmiBroker SetChartBkColor - Set background color of a chart Syntax: SetChartBkColor( color) Returns: NOTHING
Function: Sets chart background to user-specified color Example: SetChartBkColor( colorBlue);
SetChartBkGradientFill - Set background gradient color fill in indicators Syntax: SetChartBkGradientFill( topcolor, bottomcolor, titlebkcolor = default) Returns: NOTHING
Function: Enables background gradient color fill in indicators. Please note that this is independent of 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) • topcolor - specifies the top color of the gradient fill • •
bottomcolor - specifies the 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: SetChartBkGradientFill( ParamColor("BgTop", colorWhite), ParamColor("BgBottom", colorLightYellow));
AFL - AmiBroker Formula Language
317
Signal - MACD signal line Syntax: Signal( fast = 12, slow = 26, signal = 9 ) Returns: ARRAY
Function: Calculates the Signal line of MACD indicator. Example: Signal( 14, 28, 10 );
StochD ־Stochastic slow %D Syntax: StochD( periods = 14, Ksmooth=3, Dsmooth=3 ) Returns: ARRAY
Function: Calculates the %D line of Stochastic Oscillator (with internal slowing KSmooth, DSmooth). Example: The formula "stochd( 5 )" returns the value of a 5-period %D double smoothed by 3 periods
StochK - Stochastic slow %K Syntax: StochK( periods = 14, ksmooth=3 ) Returns: ARRAY
Function: Calculates the %K line of Stochastic Oscillator (with internal slowing KSmooth). Example: The formula "stochk( 5 ) ״returns the value of a 5-period %K slowed down 3 periods.
1צu
Introduction to AmiBroker Trix - Triple exponential smoothed price Syntax: Trix( periods = 9 ) Returns: ARRAY
Function: Calculates the TRIX indicator (with averaging range of periods). Example: Trix( 12 )
Ultimate - Ultimate oscillator Syntax: Ultimate( fast = 7, med = 14, slow = 28 ) Returns: ARRAY
Function: Calculates the Ultimate Oscillator indicator using the three cycle lengths supplied as parameters. Note that each of the three parameters must be greater than the preceding parameter. Example: The formula "ultimate( 7, 14, 21 )" returns the default Ultimate Oscillator.
AFL - AmiBroker Formula Language EXPLORATION
/
319
INDICATORS
AddColumn - Add numeric exploration column Syntax: AddColumn( array, name, format = 1.2, textColor = colorDefault, bkgndColor = colorDefault, width = -1 ) Returns: NOTHING
Function: Adds a new column to the exploration result list. The colu m n 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 to 6 characters.) The next two parameters modify the text and background colors, special format constants: • formatDateTime - produces date time formatted according to your system settings AddColumn( DateTime(),
•
"Date / Time", formatDateTime );
formatChar - allows output of single ASCII character codes: Example (produces signal file accepted by various other programs): Buy=Cross(MACD(),Signal()); S e l l = C r o s s ( S i g n a l ( ) , MACD()); F i l t e r = B u y OR S e l l ; SetOption("NoDefaultColumns", True ); AddColumn( DateTime(), " D a t e " , formatDateTime ); AddColumn( I l f ( Buy, 66, 83 ), " S i g n a l " , formatChar );
•
width parameter allows control of the pixel width of the column
1צu
Introduction to AmiBroker Example 1: Simple column showing close price addcolumn(
Close,
"Close p r i c e " ,
1.4
);
Example 2: Colorful output F i l t e r =1; AddColumn( C l o s e , " C l o s e " , 1 . 2 ) ; AddColumn( MACD(), "MACD", 1 . 4 , I I f ( MACD() > 0, c o l o r G r e e n , colorRed ) ); AddTextColumn( F u l l N a m e ( ) , " F u l l name", 77 , colorDefault, I l f ( C l o s e < 10, c o l o r L i g h t B l u e , c o l o r D e f a u l t
)
);
AddTextColumn - Add text exploration column 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. The next two parameters allow modification of text and background color. Width parameter allows control of pixel width of the column. Example: AddTextColumn( GroupID( 1 ), "The name of the group"); Please note that AddTextColumn takes a single string as a parameter, so you can only display text that does not vary on bar-by-bar basis.
EncodeColor - encodes color for indicator title Syntax: EncodeColor( colorlndex) Returns: STRING
AFL - AmiBroker Formula Language
321
Function: Converts color index to a string escape sequence that changes the color of text output in chart title. Color escape sequence uses cXX sequence where XX is a 2 digit number specifying color index. For example, c38 defines violet. There is a special sequence c־l that resets to the default axis color. Example: Title = "This is written in " + EncodeColor( colorViolet) + "violet color " + EncodeColor( colorGreen ) + "and this in green";
GetChartID - Get current chart ID Syntax: GetChartID() Returns: NUMBER
Function: Returns the chart ID of current indicator formula. Returns 0 if used in Automatic analysis. Example: Cross( graphO, Study( "RE", GetChartID()));
GetPriceStyle - Get current price chart style Syntax: GetPriceStyle () Returns: NUMBER
Function: Returns the price chart style value to be used in Plot statement. Returned value depends on selection in View > Price chart style menu. Example: Plot( C, "Close", ParamColor("Color", colorBlack ), styleNoTitle I ParamStyle("Style") I GetPriceStyle());
1צu
Introduction to AmiBroker LineArray - Generate trend-line array Syntax: LineArray( xO, yO, xl, yl, extend = 0, usebarindex = False ) Returns: ARRAY
Function: The LineArray function generates array equivalent to trend line drawn from point (xO, yO) to point (xl, yl). x coordinates are in bars (zero based), y coordinates are in dollars. Note: xO must be smaller than xl. Note־. The function accepts only numbers, therefore generates a single line. To produce multiple lines you have to call it multiple times with different coordinates. extend parameter controls automatic extension of the trend line. If extend is 1 then line is right extended. If extend is 2 then line is left extended. If extend is 3 then line is left and right extended usebarindex parameter controls if x coordinates are interpreted as current array indexes (from O..BarCount-l) (when usebarindex = False) or as absolute bar indexes (returned by Barlndex() function) when usebarindex = True. These two may differ if QuickAFL feature is turned on. Example:
yO=LastValue(Trough(L,5,2)); y1=LastValue(Trough(L,5,1)); xO=BarCount - 1 - L a s t V a l u e ( T r o u g h B a r s ( L , 5 , 2 ) ) ; x1=BarC0unt - 1 - L a s t V a l u e ( T r o u g h B a r s ( L , 5 , 1 ) ) ; Line = L i n e A r r a y ( xO, yO, x1, y1, 1 ); P10t(C, "C", c o l o r W h i t e , s t y l e C a n d l e ) ; P l o t ( L i n e , "Trend l i n e " , c o l o r B l u e ) ;
Param - Add user-definable numeric parameter Syntax: Param( "name", defaultval, min, max, step, sincr = 0 ) Returns: NUMBER
Function: Adds a new user-definable parameter, which will be accessible via the Parameters dialog :
AFL - AmiBroker Formula Language
323
right click over chart pane and select "Parameters" or press Ctrl+R allows change of chart parameters - changes are reflected immediately. "name" - defines parameter name that will be displayed in the parameters dialog defaultval - 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 - automatic section increment value (used by drag-drop interface to increase default values for parameters) Note: default/min/max/step parameters have to be constant numbers. This is because these values are cached and are not re-read during subsequent formula evaluations. Note that Parameters are independent for each chart pane and for Automatic Analysis window. In Automatic Analysis window parameters can be modified using "Parameters" button and they are independent from ones you use for any chart. To change the parameters for the indicator, please right-click over chart pane and select "Parameters" from the menu. Example: Sample code 1: t i c k e r = ParamStr( " T i c k e r " , "MSFT" ); sp = Param( "MA P e r i o d " , 12, 2, 100 ); P l o t F o r e i g n ( t i c k e r , "Chart o f " + t i c k e r , ParamColor( " P r i c e C o l o r " , c o l o r L i g h t Y e l l o w ) , styleCandle ); P l o t ( MA( F o r e i g n ( t i c k e r , "C" ), sp ), "MA(" + W r i t e V a l ( sp, 1 . 0 ) + " ) " , ParamColor( "MA C o l o r " , colorRed ) );
Sample code 2: sp = Param( "RSI P e r i o d " , 12, 2, 100 ); r = RSI( sp ) ; Plot( r, "RSI("+WriteVal(sp,1.0)+")", ParamC010r("RSI C o l o r " , colorRed ) ); Buy = Cross( r, 30 ); S e l l = Cross( 70, r ); PlotShapes( shapeUpArrow * Buy + shapeDownArrow * S e l l , I I f { Buy, c o l o r G r e e n , colorRed ) ) ;
1צu
Introduction to AmiBroker ParamColor - Add user user-definable color parameter Syntax: ParamColor( "name", defaultcolor) Returns: NUMBER
Function: Adds a new user-definable parameter, which will be accessible via Parameters dialog : Right-click over chart pane and select "Parameters" or press Ctrl+R to change chart parameters - changes are reflected immediately. "name" ־defines parameter name that will be displayed in the parameters dialog defaultcolor - defines default color value of the parameter colorCycle - accepted only by ParamColor function as default value, causes default color to cycle through red, blue, green, turquoise, gold, violet, bright green, dark yellow Example: Plot( RSI(), "RSI", ParamColor( "RSI Color", colorRed ));
ParamDate - Add user user-definable date parameter Syntax: ParamDate( "Name", "Default date״, format = 0 ); Returns: NUMBER STRING
Function: Adds a new user-definable date parameter, which will be accessible via Parameters dialog : right click over chart pane and select "Parameters" or press Ctrl+R to change chart parameters - changes are reflected immediately. "name" - defines parameter name that will be displayed in the parameters dialog "default date" - is a string holding date in any any format: YYYYMM-DD, MM/DD/YY, DD-MM-YY, etc.
AFL - AmiBroker Formula Language
325
format - defines return value format, allowable values are: 0 - return value is a NUMBER and holds DateNum. ie: 990503 for May 3, 1999, 1 - return value is a STRING formatted holding date according to your windows regional settings Default parameter has to be a constant, because these values are cached and are not re-read during subsequent formula evaluations. Example: s t a r t = ParamDate(
" S t a r t Date",
"2003-05-03" );
ParamField - Creates price field parameter Syntax: ParamField("name", field = 3 ) Returns: ARRAY
Function: Allows picking 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. Example:
p = ParamField("p"); Plot (p,"P", colorRed,styleLine);
1צu
Introduction to AmiBroker ParamList - Creates the parameter that consist of the list of choices Syntax: ParamList( "Name״, ״Values״, defaultval = 0 ) Returns: STRING
Function: Creates the parameter that consist of the list of choices (specified in "values" parameter ־I or comma separated), defaultval parameter defines ordinal position of the default string value specified in "values" parameter. Returned value is a STRING representing choosen item. Example: OrderType = ParamList("Order Type", "MKTILMTISTP" );
ParamStr - Add user user-definable string parameter Syntax: ParamStr( ״name״, ״default) ״ Returns: STRING
Function: Adds a new user-definable parameter, which will be accessible via Parameters dialog : right-click over chart pane and select "Parameters" or press Ctrl+R to change chart parameters - changes are reflected immediately. "name" - defines parameter name that will be displayed in the parameters dialog "default" - defines default value of the parameter Example: ticker = ParamStr( "Ticker", "MSFT" );
AFL - AmiBroker Formula Language
327
ParamStyle - Select styles applied to the plot Syntax: ParamStyle("name", defaultstyle = styleLine, mask = maskDefault) Returns: NUMBER
Function: Allows selection of the styles applied to plot. Parameters: name - parameter name defaultstyle - default value of style. Takes a combination of style constants mask - binary mask that defines which styles should be visible in the drop down list maskDefault - show thick, dashed, hidden, own scale styles (this is the 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 Example:
P = ParamField("Price f i e l d " , - 1 ) ; Periods = Param("Periods", 15, 2, 200, 1, 10 ); P l o t ( EMA( P, Periods ), _DEFAULT_NAME(), ParamColor( " C o l o r " , c o l o r C y c l e ) , ParamStyle("Style") );
1צu
Introduction to AmiBroker ParamTime - Add user user-definable time parameter Syntax: ParamTime( ״Name״, ״Default time״, format = 0 ); Returns: NUMBER STRING
Function: Adds a new user-definable time parameter, which will be accessible via Parameters dialog : right click over chart pane and select "Parameters" or press Ctrl+R to change chart parameters ־changes are reflected immediately "name" - defines parameter name that will be displayed in the parameters dialog "default time" - is a string holding time in any format: HH:MM:SS, HH:MM, etc. format - defines return value format, allowable values are: 0 - return value is a NUMBER and holds TimeNum. Ie: 133515 for 13:35:15 1 - return value is a STRING formatted holding time according to your windows regional settings Default parameter must be a constant. This is because these values are cached and are not re-read during subsequent formula evaluations. Example:
s t a r t = ParamTime(
" S t a r t Time",
"09:30"
ParamToggle - create Yes/No parameter Syntax: ParamToggle("name","values",defaultval=0) Returns: NUMBER
);
AFL - AmiBroker Formula Language
329
Function: Allows use of boolean (Yes/No) parameters, "name" - the name of the parameter "values" - parameter values (separated with I character, e.g. "No I Yes" - first string represents false value and second string represents true value) defaultval - default value of the parameter Example:
PlotTheGrids = ParamToggle("Plot g r i d s " , " N o | Y e s " , 0 ) ; i f (PlotTheGrids ==1) { PlotGrid(0); PlotGrid(-100); PlotGrid(100); PlotGrid(-200); PlotGrid(200); }
ParamTrigger - Creates a trigger (button) in the parameter dialog Syntax: ParamTrigger( "Name״, "Button text") Returns: NUMBER
Function: Creates trigger (button) in the Parameter dialog. If you place ParamTrigger in the indicator code it will create a "button" in Parameter dialog that can be pressed. Normally ParamTrigger will return zero (0), but when the button in the param window is pressed, it will refresh the chart and ParamTrigger will return 1 (one) for this single execution (further refreshes will return zero, until the button is pressed again) Example:
t r i g g e r = ParamTrigger("Place O r d e r " , " C l i c k here t o place o r d e r " ) ; i f ( trigger ) { // your one-shot code here }
1צu
Introduction to AmiBroker Plot - Plot indicator graph Syntax: Plot( array, name, color/barcolor, style = styleLine, minvalue = {empty}, maxvalue = (empty), XShift = 0 ) Returns: NUMBER
Function: Plots the graph using array data. Parameters: array - data array to be plotted name - defines graph name used for displaying values in a title bar. color - defines plot color that could be static (if third argument is a number) or dynamic (when third argument is an array). Color indexes are related to the current palette (see Preferences/Color) style is a combination of one or more of following values: •
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 - do not display values of this plot in the chart title
AFL - AmiBroker Formula Language • •
331
styleCloud - cloud style (area between high and low arrays) - to be used with PlotOHLC function styleClipMinMax - clip (do not paint) area between min and max levels ־note this style is incompatible with printers and WMF (metafiles).
minvalue and maxvalue - (used by styleOwnScale plots ONLY) define plot minimum and maximum values (lower and upper boundary for Y axis) XShift - allows to visually shift the chart past the last bar. Example: // Example 20-bar Moving average s h i f t e d 10 bars / / i n t o the f u t u r e past t h e l a s t b a r : Plot(Close,"Close",colorBlack,styleCandle); Plot(MA(C10se,20), " S h i f t e d MA", colorRed, s t y l e L i n e , N u l l , N u l l , 1 0 ) ; / / Note t h a t s h i f t occurs d u r i n g p l o t t i n g // and does not a f f e c t the source a r r a y
PlotGrid - Plot horizontal grid line Syntax: PlotGrid( level, color = colorDefault) Returns: NOTHING
Function: Plots horizontal grid line using built-in dotted style at given level and color. Example: PlotGrid( 25, colorRed ); Instead of number you can also use expression but it must be a numeric expression, not an array. Use LastValue to convert:
your_expression = . . . P l o t G r i d ( LastValue( your_expression )
);
1
צ
u
Introduction to AmiBroker
PlotOHLC - Plot custom OHLC chart Syntax: PlotOHLC( open, high, low, close, name, color/barcolor, style = styleCandle I styleOwnScale, minvalue = {empty}, max value = {empty[, XShift = 0 ) Returns: NUMBER
Function: Plots the price chart using custom open, high, low, close arrays supplied as parameters. Fifth argument name defines graph name used for displaying values in a title bar. Graph color could be static (if sixth argument is a number) or dynamic (when sixth argument is an array). Color indexes are related to the current palette (see Preferences/Color) style defines chart plot style (see Plot() function for possible values) minvalue and maxvalue - (used by styleOwnScale plots only) define plot minimum and maximum values (lower and upper boundary for Y axis) XShift - Visually shifts the chart into future (blank) bars. Example: PlotOHLC( l.TOpen, 1.1* High, 1.1* Low, 1.1* Close, "Price chart shifted 10% up", colorRed, styleCandle );
PlotShapes - Plots arrows and other shapes Syntax: PlotShapes( shape, color, layer = 0, yposition = graphO, offset = -12 ); Returns: NOTHING
Function: Plots arrows and other shapes on any chart pane. •
shape defines type of the symbol. When shape is 0 (zero) nothing is plotted. Values other than zero cause plotting various pre-defined shapes. Odd values plot the shape below the indicator, even values plot the shape above the indicator.
•
color defines color of shape
AFL - AmiBroker Formula Language
333
•
layer defines layer number on which shapes are plotted
•
yposition defines Y-position where shapes are plotted (by default they are plotted 'around' graphO (first indicator) line)
•
offset - (or distance) parameter (by default -12 ), Offset is expressed in screen pixels. Negative offsets shift symbols down, positive offsets shift symbols up. To place the shape exactly at yposition, specify 0 as offset
•
Constants for shapes: shapeNone, shapeUpArrow, shapeDownArrow, shapeHollowUpArrow, shapeHollowDownArrow, shapeSmallUpTriangle, shapeSmallDownTriangle, shapeHollowSmallUpTriangle, shapeHollowSmallDownTriangle, shapeUpTriangle, shapeDownTriangle, shapeHollowUpTriangle, shapeHollowDownTriangle, shapeSmallSquare, shapeHollowSmallSquare, shapeSquare, shapeHollowSquare, shapeSmallCircle, shapeHollowSmallCircle, shapeCircle, shapeHollowCircle, shapeStar, shapeHollowStar, shapeDigitO, shapeDigitl, shapeDigit2, shapeDigit3, shapeDigit4, shapeDigit5, shapeDigit6, shapeDigit7, shapeDigit8, shapeDigit9, shapePositionAbove
Example 1: PlotShapes( I I F ( buy, s h a p e D i g i t 9 + shapePositionAbove, shapeNone ) , c o l o r G r e e n ) ;
Example 2: GraphO=MACD(); Graph1=Signal(); Buy=Cross(GraphO, Graph;)!־ S e l l = C r o s s ( G r a p h l , GraphO); PlotShapes( ( Buy OR S e l l ) * ( 1 + Cum( Buy OR S e l l ) % 52 ), I l f ( Buy, c o l o r G r e e n , colorRed ) , 5 ) ; GraphXSpace = 5;
1צu
Introduction to AmiBroker PlotVAPOverlay ־Plot Volume-At-Price overlay chart Syntax: PlotVAPOverlay( lines = 300, width = 5, color = colorGreen, vapstyle = 0); Returns: NOTHING
Function: Plots Volume-At-Price (VAP) overlay chart. There must be at least one regular Plot function in your formula for this to work, and there can be only one PlotVAPOverlay in one indicator •
vapstyle = 0 - left side, area fill, on top of all plots
•
vapstyle = 1 - right side, area fill, on top of all plots
•
vapstyle = 2 - left side, lines only, on top of all plots
•
vapstyle = 3 - right side, lines only, on top of all plots
•
vapstyle = 4 - left side, area fill, behind all plots
•
vapstyle = 5 - right side, area fill, behind all plots
•
vapstyle = 6- left side, lines only, behind all plots
•
vapstyle = 7 - right side, lines only, behind all plots
Example:
P l o t ( Close, " P r i c e " , c o l o r W h i t e , s t y l e C a n d l e ) ; PlotVAPOverlay( P a r a m ( " l i n e s " , 3 0 0 , 1 0 , 1 0 0 0 , 1 ) , Param("width",10,1,99,1), ParamColor("color", colorDarkBlue), Param("style",0,0,7,1) );
SelectedValue - Retrieves value of the array at currently selected date/time point Syntax: SelectedValue( ARRAY) Returns: NUMBER
Function: Retrieves array value at currently selected bar. The main purpose is for commentary and interpretation code.
AFL - AmiBroker Formula Language
335
Example: SelectedValue( close) SelectedValue(array) is a function that retrieves the 'selected element ׳of the array. Since the 'selection line' is available only for charts, SelectedValue gives the value of array at the bar that is currently selected in chart by vertical line. This is how it works in indicators, interpretation, and chart commentary, because they are relative to the selected bar. In AA window 'selected element' means the last bar of the currently selected analysis range. It is the last available bar for "all quotes" and "last n quotes" range. It is the the bar corresponding to "End Date" when using "From-To" range. If you choose range: "all quotes" in AA, SelectedValue function is equivalent to array[BarCount -1]
SetChartOptions - Set/clear/overwrite defaults for chart pane options Syntax: SetChartOptions( Mode = 0, Flags = 0, gridFlags = chartGridMiddle, ymin = 0, ymax = 0 ) Returns: NOTHING
Function: Allows set/clear/overwrite/set defaults for chart pane options Mode ־specifies how options are set: •
0 - set only the default values for new chart. Defaults are applied only once when chart is inserted in a new pane, so later you can modify any option using Indicator Builder
•
1 - overwrite - the values specified in 2nd and 3rd argument overwrite any previously set values
•
2 - set flag - flags specified in 2nd and 3rd parameter are binary-ORed with the current values, so effectively these options are set while those remaining are unchanged
•
3 - reset flag - flags specified in 2nd and 3rd parameter are cleared while the others remain unchanged.
1צu
Introduction to AmiBroker Flags - allowable flags are: chartShowDates, chartLogarithmic, chartShowArrows, chartWrapTitle, chartHideQuoteMarker. chartHideQuoteMarker - hides the quote selector line on perpane basis, the same as Parameter dialog > Axes & Grid > Vert, quote marker: Show/Hide
gridFlags - (for internal AmiBroker use - do not use it in your own coding as this parameter will eventually be removed) allowable values are: chartGridDivlOO, chartGridPercent, chartGridDivlOOO, chartGridMargins chartGridMiddle, chartGridO, chartGrid30, chartGrid70, chartGridlO, chartGrid90, chartGrid50,chartGridl 00,chartGrid20,chartGrid80,chartGridl ymin, ymax - these parameters specify Y-axis minimum and maximum values for custom scaling. If you specify any values that meet the condition ymin < ymax, AmiBroker will turn OFF automatic scaling and use specified min/max values for Y scale. The Mode argument controls when these settings are applied (0 - only when new chart is created, 1 - always), when modes 2 and 3 are used ־scaling is not changed. Example 1: / / t o mark "Show a r r o w s " by d e f a u l t In a new c h a r t use S e t C h a r t O p t i o n s ( 0, ChartShowArrows );
Example 2: SetChartOptions(2, chartWrapTitle ); T i t l e = " t h i s i s a t e s t o f a u t o m a t i c wrapping o f t i t l e t e x t t h a t i s t o o l o n g t o f i t i n s i n g l e l i n e , f o r t h a t reason t h i s sample f o r m u l a uses v e r y l o n g t e x t . I hope you are e n j o y i n g the sample";
AFL - AmiBroker Formula Language
337
SetSortColumns - Sets the columns which will be used for sorting in AA window Syntax: SetSortColumns( coll, col2, ....) Returns: NOTHING
Function: Sets the columns which will be used for sorting, coll, col2, ... collO. Column numbers are one-based. Positive number means sort ascending, negative number means sort descending. Upto 10 columns can be specified for multiple-column sort. Each subsequent call to SetSortColumns overwrites previous one. Examples: // s o r t by 5th column in ascending order SetSortColumns( 5 ) // s o r t by 3rd column in descending order SetSortColumns( -3 ) // s o r t by 1st column in ascending o r d e r // and then by Second column in descending o r d e r // (multiple-column s o r t ) . SetSortColumns( 1, -2 ):
Writelf - Commentary conditional text output Syntax: Writelf( EXPRESSION, "TRUE TEXT״, ״FALSE TEXT) ״ Returns: STRING
Function: 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. Writelf in fact does not "write" anything. The name is misleading but it is left for easy translation of MS formulas to AmiBroker. Writelf issimilar to "TextllF". It returns string value depending on condition. Example: Writelf( C>MA(C,200), "The close is above the 200-period moving average." "The close is below the 200-period moving average." );
1צu
Introduction to AmiBroker WriteVal - Write number or value of the array Syntax: WriteVal( WriteVal(
format = 1.3, separator=True) format = 1.3, separator=True )
NUMBER, ARRAY,
Returns: STRING
Function: It is used to display the numeric value of NUMBER or ARRAY. The second parameter - format - allows you to control output formatting (decimal places and leading spaces). The integer part of the number controls minimum number of characters used to display the number (if you specify high number the output will be space-padded). The fractional part defines how many decimal places to display, for example 1.0 - will give you a number without fractional part at all, and 1.2 ־will display two digits past the decimal point There is also a special format constant formatDateTime that allows to print date/time returned by DateTime() function formatted according to Windows regional settings. Third parameter separator (true by default) controls if thousand separator is added or not. Thousands separator is definable in Tools > Preferences > Misc. WriteVal always returns *one* value of the array (not an array of values). In almost all cases this is LastValue of the array but in indicators it is "selected value" - the one that is selected by the vertical line. NumToStr is a synonym for WriteVal function and NumToStr is preferred in new coding. Examples: // Simple use (no custom f o r m a t ) W r i t e V a l ( StochK(39) - StochK(12)
);
/ / D i s p l a y r a t e o f change w i t h 2 decimal d i g i t s // and % appended to the end W r i t e V a l ( ROC( Close, 20 ), 1.2 ) + "%"; // Display date/time according to regional s e t t i n g s W r i t e V a l ( DateTime(), formatDateTime ) ;
AFL - AmiBroker Formula Language
339
_DEFAULT_NAME - Retrieve default name of the plot Syntax: _DEFAULT_NAME() Returns: STRING
Function: This function returns the default name of plot in the dragdrop section. The default name consists of section name and comma separated list of values of numeric parameters defined in given section. Example: _SECTION_BEGIN("MA1"); P = ParamField("Price f i e l d " ) ; Periods = Param("Periods", 15, 2, 200, 1, 10 ); P l o t ( MA( P, Periods ), _DEFAULT_NAME(), ParamColor( " C o l o r " , c o l o r C y c l e ) , ParamStyle("Style") ); _SECTI0N_END();
_DEFAULT_NAME will evaluate to "MAI (Close,! 5)" string.
_N - No text output Syntax: _N( string) Returns: NOTHING
Function: Inhibits printing string to the commentary output window Example:
_N( t i c k e r = name() ); / / thanks t o _ N f u n c t i o n t i c k e r symbol i s not p r i n t e d
1צu
Introduction to AmiBroker P A R A M V A L U E S - Retrieve param values string Syntax: _PARAM_VALUES0 Returns: STRING
Function: _PARAM_VALUES retrieves the values of the parameters defined in current drag-drop section. It works the same as _DEFAULT_NAME except that no section name is included (so only the list of parameter values is returned). Example: _SECTI0N_BEGIN("MACD"); r1 = Param( "Fast a v g " , 12, 2, 200, 1 ); r2 = Param( "Slow a v g " , 26, 2, 200, 1 ); r3 = Param( " S i g n a l a v g " , 9, 2, 200, 1 ); P l o t ( ml = MACD(r1, r2) ,
StrFormat(_SECTION_NAME()+"(%g,%g)", r1, r 2 ) ,
ParamColor("MACD c o l o r " , colorRed ) , ParamStyle("MACD s t y l e " ) ) ; P l o t ( si = S i g n a l ( r 1 , r 2 , r 3 ) , " S i g n a l " + _PARAM_VALUES(), ParamColor("Signal c o l o r " , c o l o r B l u e ) , ParamStyle("Signal s t y l e " ) ); P l o t ( m l - s i , "MACD H i s t o g r a m " , ParamColor("Histogram c o l o r " , c o l o r B l a c k ) , s t y l e N o T i t l e \ ParamStyle("Histogram s t y l e " , styleHistogram | styleNoLabel, maskHistogram ) ); _SECTION_END();
SECTIONJBEGIN - Section begin marker Syntax: _SECTION_BEGIN( "section name) ״ Returns: NOTHING
Function: Marks beginning of the drag-drop section. "section name" must be a constant, literal string, enclosed in double quotation marks. You must not use a variable here. Example: See _PARAM_VALUES() entry.
AFL - AmiBroker Formula Language
341
S E C T I O N E N D - Section end marker Syntax: _SECTION_END() Returns: NOTHING
Function: Marks end of drag-drop section Example: See _PARAM_VALUES() entry.
SECTION NAME - Retrieve current section name Syntax: _SECTION_NAME() Returns: STRING
Function: The function that gives the name of the drag-drop section (given in previous _SECTION_BEGIN call). Example: See _PARAM_VALUES() entry.
1צu
Introduction to AmiBroker DATE/TIME
Barlndex - Get zero-based bar number Syntax: Barlndex() Returns: ARRAY
Function: Returns a zero-based bar number - the same as Cum(l)-1 but it is much faster than Cum(l) when used in Indicators When QuickAFL is ON, the Barlndex() may not be equal to array item index. Actual array item corresponding to bar index can be found this way: bi = B a r l n d e x ( ) ; a r r a y i t e m = SelectedValue( bi ) - b i [ 0 ]; "Close at s e l e c t e d b a r : " + Close[ a r r a y i t e m ];
Example: ThisIsLastBar = Barlndex() == LastValue( Barlndex()); This statement compares each element of an array, Barlndex(), to a number, LastValue(BarIndex()), and produces array as a result. The array, ThisIsLastBar, will have 0 in every element except the one where Barlndex() does equal LastValue(BarIndex()), which will have a value of 1.
BeginValue - Value of the array at the beginning of the range Syntax: BeginValue( ARRAY) Returns: NUMBER
AFL - AmiBroker Formula Language
343
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. 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. Examples: / / Simple commentary: W r i t e V a l ( BeginValue( DateTime() ) , formatDateTime ) ; W r i t e V a l ( EndValue( DateTime() ) , formatDateTime ) ; "Percentage change of c l o s e is " + W r i t e V a l ( 100 * (EndValue( Close ) - BeginValue( Close )) / B e g i n V a l u e ( Close ) ) + "%";
// Get t h e number of bars in t h e range and / / c a l c u l a t e some s t a t s f o r t h a t range: P e r i o d = EndValue( B a r l n d e x ( ) ) - BeginValue( B a r l n d e x ( ) StandardDeviationlnTheRange = EndValue( StDev( C l o s e , P e r i o d ) );
);
Date - Date Syntax: Date() Returns: STRING
Function: It is used to display the selected date in commentary / interpretation window Example: Title =Date()+" ״+Name()+ ״Close״+WriteVal(C);
Introduction to AmiBroker 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 + d a y so 2001-12-31 becomes 1011231 and 1995-12-31 becomes 951231 Example: D a t e O f I n t e r e s t = (DateNum()==1080820); // August 20, 2008 Plot(DateOfInterest,"DI",colorRed,styleLine);
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 formatted according to your system settings. Examples: // Simple d a t e / t i m e column AddColumn( DateTime(), "Date / Time", formatDateTime ); / / Produces s i g n a l f i l e accepted b y v a r i o u s o t h e r programs Buy=Cross(MACD(),Signal()); S e l l = C r o s s ( S i g n a l ( ) , MACD()); F i l t e r = B u y OR S e l l ; SetOption("NoDefaultColumns", True ); AddColumn( DateTime(), " D a t e " , formatDateTime ); AddColumn( I l f ( Buy, 66, 83 ), " S i g n a l " , formatChar );
AFL - AmiBroker Formula Language
345
DateTimeConvert - Date/time format conversion Syntax: DateTimeConvert( format, date, time = N u l l ) Returns: NUMBER ARRAY
Function: The function allows conversion from DateTime format to DateNum and TimeNum and vice versa. format parameter controls the direction of conversion: • format = 0 - converts DateTime format to DateNum format. Example: mydatenum = DateTimeConvert( 0, DateTime()); // - this returns DateNum • format = 1 - converts DateTime format to TimeNum format. Example: mytimenum = DateTimeConvert( 1, DateTime()); // - returns timenum •
format = 2 - converts from DateNum and optionally TimeNum to DateTime format. Example: mydatetime = DateTimeConvert( 2, DateNum(), TimeNum());
•
format = 3 - converts DateTime format to Seconds (00..59). Example: myseconds = DateTimeConvert( 3, DateTime());
•
format = 4 - converts DateTime format to Minutes(00..59). Example: myminute = DateTimeConvert( 4, DateTime());
•
format = 5 - converts DateTime format to Hours (00..23). Example: myhour = DateTimeConvert( 5, DateTime());
Example:
mydatenum = DateTimeConvert( mytimenum = DateTimeConvert( mydatetime = DateTimeConvert( mydatetime = DateTimeConvert(
0, 1, 2, 2,
DateTime() DateTime() DateNum(), DateNum()
) ; / / r e t u r n s DateNum ) ; / / r e t u r n s timenum TimeNum() ); );
1צu
Introduction to AmiBroker Day - day of month Syntax:: Day() Returns: ARRAY
Function: Returns the array with days (1-31) Example:
w r i t e i f ( day() < 3, "Beginning of t h e month", "The r e s t of the month" );
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 s e l l = dayofweek() == 5; // s e l l 0 חFriday
AFL - AmiBroker Formula Language
347
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 Y e a r " ) ;
EndValue - Value of the array at the end of the selected range Syntax: EndValue(
ARRAY)
Returns: NUMBER
Function: This function gives the single value (number) of the ARRAY at the end of the selected range. If no range is marked then the value at the last bar is returned. To select the range you have to double click in the chart at the beginning of the range and then double click in the chart at the end of the range. Then > < markers will appear above date axis. Examples: // Simple commentary: W r i t e V a l ( BeginValue( DateTime() ), formatDateTime ); W r i t e V a l ( EndValue( DateTime() ), formatDateTime ); "Precentage change of c l o s e is " + W r i t e V a l ( 100 * (EndValue( Close ) - BeginValue( Close ) ) / B e g יי מ. inValue( Close ) ) + "יי%"; // Get the number of bars in t h e range and / / c a l c u l a t e some s t a t s f o r t h a t range: Period = EndValue( B a r l n d e x ( ) ) - BeginValue( B a r l n d e x ( ) StandardDeviationlnTheRange = EndValue( StDev( Close, Period ) );
);
1צu
Introduction to AmiBroker GetPlaybackDateTime - Get bar replay position date/time Syntax: GetPlaybackDateTime() Returns: NUMBER
Function: The function returns bar replay playback position in datetime format, or zero if bar replay is not active Example: / / new f u n c t i o n t o r e t r i e v e playback p o s i t i o n d a t e / t i m e / / r e t u r n s zero if bar r e p l a y is NOT a c t i v e pt = GetPlaybackDateTime(); i f ( Pt ) { T i t l e = "Playback t i m e :
" + DateTimeToStr( pt );
}
else { T i t l e = "Bar Replay not a c t i v e " ;
}
Hour - Get current bar's hour Syntax: Hour() Returns: ARRAY
Function: Retrieves the current bar's hour Example: Hour()*10000 + Minute() * 100 + Second()
AFL - AmiBroker Formula Language
349
Interval - Get bar interval (in seconds) Syntax: Interval( format = 0 ) Returns: NUMBER
Function: Interval() function returns the bar interval. Possible formats: format = 0 - returns bar interval in seconds format = 1 - as above plus TICK bar intervals are returned with negative sign so Interval() function applied to 10 tick chart will return -10 format = 2 - returns STRING with name of interval such as "weekly/monthly/daily/hourly/15-minute/5-tick" Time intervals in seconds: •
tick bars = 0
•
5 sec bars = 5
•
1 min bars = 60 (inMinute constant)
•
hourly bars = 3600
•
daily bars = 86400 (inDaily constant)
•
weekly bars = 432001 (inWeekly constant)
•
monthly bars = 2160001 (inMonthly constant)
Example: "Interval in seconds " + WriteVal( Interval());
Minute - Get current bar's minute Syntax: Minute() Returns: ARRAY
Function: Retrieves the current bar's minute Example: Hour()*10000 + Minute() * 100 + Second()
1צu
Introduction to AmiBroker Month - month Syntax: Month() Returns: ARRAY
Function: Returns the current bar's month Example: buy = ( month() == 1 ) and day < 3; // buy in January
Now - Gets current system date/time Syntax: Now( format = 0 ) Returns: STRING NUMBER Function: Returns the current date / time in numerous formats: •
format = 0 - returns string containing current date/time formatted according to system settings
•
format = 1 - returns string containing current date only formatted according to system settings
•
format = 2 - returns string containing current time only formatted according to system settings
•
format = 3 - returns DATENUM number with current date
•
format = 4 - returns TIMENUM number with current time
•
format = 5 - returns DATETIME number with current date/ time
•
format = 6 - returns current DAY (1..31)
•
format = 7 - returns current MONTH (1..12)
•
format = 8 - returns current YEAR (four digit)
•
format = 9 - returns current DAY OF WEEK (1..7, where l=Sunday, 2=Monday, and so on)
•
format = 10 - returns current DAY OF YEAR (1..366)
Example: AddTextColumn( Now(), "Current time");
AFL - AmiBroker Formula Language
351
Second - Get current bar's second Syntax: Second() Returns: ARRAY
Function: Retrieves the current bar's second Example: Hour()*10000 + Minute() * 100 + Second()
TimeNum - Get current bar time Syntax: TimeNum() Returns: ARRAY
Function: Returns the current bar's time coded as follows: 10000 * hour + 100 * minute + second, so 12:37:15 becomes 123715 Example: TimeNum()
Year - Year Syntax: Year() Returns: ARRAY
Function: Returns the current bar's years (full four digits 1900-....) Example: WriteVal( year());
1צu
Introduction to AmiBroker T i m e Frame functions
TimeFrameCompress - Compress single array to given time frame Syntax: TimeFrameCompress( array, interval, mode = compressLast) Returns: ARRAY
Function: The TimeFrameCompress function compresses single array to given interval using given compression mode available modes: • compressLast - last (close) value of the array within interval • compressOpen - open 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
To expand the compressed array you should use the TimeFrameExpand function.
The TimeFrameCompress function is provided for completeness and it can be used when you want to compress single array without affecting built-in OHLCV arrays. If you call TimeFrameCompress it does not affect results of other functions (opposite to TimeFrameSet). Example: wc = TimeFrameCompress( Close, inWeekly ); / * now the time frame i s s t i l l unchanged (say d a i l y ) and our MA w i l l operate on d a i l y data */ dailyma = MA( C, 14 ); /* but if we c a l l MA on compressed a r r a y , i t w i l l g i v e M A from o t h e r t i m e frame * / weeklyma = MA( wc, 14 ); / / note t h a t argument i s time-compressed a r r a y P l o t ( d a i l y m a , "DailyMA", colorRed ) ; weeklyma = TimeFrameExpand( weeklyma, inWeekly ); / / expand f o r d i s p l a y P l o t ( weeklyma, "WeeklyMA", c o l o r B l u e );
AFL - AmiBroker Formula Language
353
TimeFrameExpand - Expand time frame compressed array Syntax: TimeFrameExpand( array, interval, mode = expandLast) Returns: ARRAY
Function: The TimeFrameExpand function expands time-compressed array from interval time frame to base time frame (interval parameter must match the value used in TimeFrameCompress or TimeFrameSet) The TimeFrameExpand is used to decompress array variables that were created in different time frame. Decompressing is required to properly display the array created in different time frame. 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. 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)).
Caveat: expandFirst used on price different than open may look into the future. For example if you create a weekly high series, expanding it to daily interval using expandFirst will enable you to know on Monday what will be the high for entire week.
1צu
Introduction to AmiBroker Example: wc = TimeFrameCompress( Close, inWeekly ); /* now t h e time frame is s t i l l unchanged (say d a i l y ) and our MA w i l l operate o n d a i l y data * / dailyma = MA( C, 14 ); /* but if we c a l l MA on compressed a r r a y , it w i l l g i v e MA from o t h e r t i m e frame * / weeklyma = MA( wc, 14 ); // note t h a t argument is time-compressed a r r a y Plot( dailyma,
"DailyMA", colorRed ) ;
weeklyma = TimeFrameExpand( weeklyma, inWeekly ); display P l o t ( weeklyma,
// expand f o r
"WeeklyMA", c o l o r B l u e );
TimeFrameGetPrice - Retrieve O, H, L, C, V values from other time frame Syntax: TimeFrameGetPrice( pricefield, interval, shift = 0, mode = expandFirst) Returns: ARRAY
Function: The TimeFrameGetPrice - retrieves OHLCV fields from other time frames. This works immediately without need to call TimeFrameSet at all. • •
•
pricefield ־is one of the following: "O", "H", "L" "C", "V", "I״ (open interest). interval is bar interval in seconds. You can use pre-defined interval constants: inlMinute, in5Minute, inl5Minute, inHourly, inDaily, inWeekly, inMonthly. Or integer multiples like (3*inlMinute) for 3 minute bars 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).
AFL - AmiBroker Formula Language
355
mode - one of 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)).
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. Example: // Example 1. get p r e v i o u s week Open p r i c e TimeFrameGetPrice( " 0 " , i n W e e k l y , -1 ) // Example 2. get weekly Close p r i c e 3 weeks ago TimeFrameGetPrice( " C " , inWeekly, -3 ) // Example 3. get weekly High p r i c e 2 weeks ago TimeFrameGetPrice( " H " , inWeekly, -2 ) // Example 4. get t h i s week Open p r i c e . TimeFrameGetPrice( " 0 " , inWeekly, 0 ) // Example 5. get p r e v i o u s Day High // when w o r k i n g on i n t r a d a y d a t a TimeFrameGetPrice( " H " , i n D a i l y , -1 )
1צu
Introduction to AmiBroker TimeFrameMode - Switch time frame compression mode Syntax: TimeFrameMode( m o d e ) Returns: NOTHING
Function: Switches time frame functions to different operating modes. Where mode is one of 0,1, or 2. • TimeFrameMode( 0); - switches time frame functions to time-based operation (the default) • TimeFrameMode( 1 ); - switches time frame functions to N-tick operation (positive values passed to TimeFrameSet are treated now as N-tick) •
TimeFrameMode( 2); - switches time frame functions to N-volume bar operation (positive values passed to TimeFrameSet are treated now as N-volume bars)
•
TimeFrameMode( 3); - switches time frame functions to N-Range bar operation (positive values passed to TimeFrameSet are treated now as N-range bars)
Note: N-volume bars are very different from time-based bars (compression of data to N-volume bar may actually deliver more output bars - for example if one tick is 1000 shares and you have specified 100V bars then single tick will be expanded to ten 100V bars - ten times original size) TimeFrame functions are protected against array overrun and will not decompress beyond original array size (you will get an "Error 47. N-volume bar compressed data longer than base time frame"). Also switching main time frame to some weird N-volume bar value will result in limiting the output to maximum twice original data size(without error message). You should keep that in mind and avoid using too small N-volume bar intervals that could lead to such condition. Also due to the nature of N-volume bars only the TimeFrameSet() function will yield correct N-volume bar values, TimeFrameGetPrice() may give
AFL - AmiBroker Formula Language
357
slightly distorted results. It is also possible to use n-volume bars in TimeFrame functions without calling TimeFrameMode() - it is then necessary to specify n-volume bars as a negative number offset by -1000000 (minus one million): TimeFrameSet( -1000000 - 2000 ); Example: TimeFrameMode( 2 ); TimeFrameSet( 50000 ); / / . . . d o something .. . TimeFrameRestore();
// 50'000 share b a r s . .
TimeFrameRestore - Restores price arrays to original time frame Syntax: TimeFrameRestore() Returns: NOTHING
Function: The TimeFrameRestore function restores price arrays replaced by TimeFrameSet. Note that only OHLC, V, OI and Avg built-in variables are restored to original time frame when you call TimeFrameRestore(). All other variables created when being in the different time frame remain compressed. To de-compress them to original interval you have to use TimeFrameExpand.
358
Introduction to AmiBroker
Example:
TimeFrameSet( in5Minute ); // s w i t c h to 5 minute frame /* MA now operates on 5 minute d a t a , ma5_13 holds time-compressed 13 bar MA of 5min bars */ ma5_13 = MA( C, 13 ); TimeFrameRestore(); / / r e s t o r e time frame t o o r i g i n a l TimeFrameSet( i n H o u r l y ); // s w i t c h now to h o u r l y mah_9 = EMA( C, 9 ); // 9 bar moving average from h o u r l y data TimeFrameRestore(); / / r e s t o r e time frame t o o r i g i n a l P l o t ( Close, " P r i c e " , c o l o r W h i t e , s t y l e C a n d l e ) ; // p l o t expanded average P l o t ( TimeFrameExpand( ma5_13, i n S M i n u t e ) , "13 bar moving average from 5 min b a r s " , colorRed ); P l o t ( TimeFrameExpand( mah_9, i n H o u r l y ) , "9 bar moving average from h o u r l y b a r s " , colorRed );
TimeFrameSet - switch price arrays to a different time frame Syntax: TimeFrameSet( interval) Returns: NOTHING
Function: The TimeFrameSet function replaces the current price/ volume arrays, open, high, low, close, volume, openint, and avg, with time-compressed bars of the specified interval. Once you switch to a different time frame, all calculations and built-in indicators operate on newly selected time frame. To get back to the original interval, call the TimeFrameRestore() function. Before calling TimeFrameSet again in the same formula with a different interval, you have to restore the original time frame first using TimeFrameRestore. interval defines time frame interval in seconds. So 60 means 1-minute. For the convenience the following interval constants are pre-defined: •
inl Minute = 60
•
in5Minute = 5 * 60
•
inl5Minute = 15 * 60
•
inHourly = 3600
•
inDaily = 24 * 3600
•
inWeekly = 5 * 24 * 3600 + 1 = 432001
•
inMonthly = 25*24* 3600 + 1 = 2160001
AFL - AmiBroker Formula Language
359
To get other intervals you can use a multiple of pre-defined intervals, for example: ( 3 * inlMinute ) gives 3 minute bars. Or you can use 3 * inDaily for 3-day bars. You can also use negative values for N-tick charts: -5 gives a 5-tick chart. Note that N-tick compression works correct only if you have 1-tick base time interval selected in database settings. You can also use TimeFrameSet to create N-volume bars as well as Range bars. See TimeFrameMode() function for more details. Very Important: •
inWeekly constant is now 432001 ( 5*inDaily + 1 ) - in previous version it was 432000
•
inMonthly constant is now 2160001 ( 25*inDaily + 1 ) - in previous version it was 2160000
•
It is changed because now N-day custom intervals are supported and they will interfere with weekly/monthly.
Note that 5*inDaily is now different than inWeekly. 5*inDaily ereates 5-day bars that do not necessarily cover Monday-Friday while inWeekly always creates bars that begin on Monday and end on Friday. Also 25*inDaily creates 25-day bars that do not represent a full month, while inMonthly always begins with first day of the month and ends at the last day of the month 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 a good idea to always call TimeFrameRestore when you are done processing in other time frames. When the time frame is switched to other than the original interval the results of all functions called since TimeFrameSet are time-compressed too. If you want to display them in the original time frame you need to 'expand' them as described later. Variables created and assigned before call to TimeFrameSet() remain in the time frame they were created. This behavior allows mixing unlimited different time frames in a single formula.
360
Introduction to AmiBroker
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. Example: TimeFrameSet( i n 5 M i n u t e ); // s w i t c h to 5 minute frame /* MA now o p e r a t e s on 5 minute d a t a , ma5_13 holds time-compressed 13 bar MA of 5min bars */ ma5_13 = MA( C, 13 ); TimeFrameRestore(); / / r e s t o r e t i m e frame t o o r i g i n a l TimeFrameSet( i n H o u r l y ) ; / / s w i t c h now t o h o u r l y mah_9 = EMA( C, 9 ); // 9 bar moving average from h o u r l y data TimeFrameRestore(); / / r e s t o r e t i m e frame t o o r i g i n a l P l o t ( Close, " P r i c e " , colorWhite, styleCandle ) ; / / p l o t expanded average P l o t ( TimeFrameExpand( ma5_13, i n S M i n u t e ) , "13 bar moving average from 5 min b a r s " , colorRed ); P l o t ( TimeFrameExpand( mah_9, i n H o u r l y ) , "9 bar moving average from h o u r l y b a r s " , colorRed );
AFL - AmiBroker Formula Language INFORMATION
/
361
CATEGORIES
CategoryAddSymbol - Adds a symbol to a category Syntax: CategoryAddSymbol( symbol, category, number ) Returns: NOTHING
Function: The CategoryAddSymbol function adds the symbol to the 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
•
categorylndustry
•
categoryWatchlist
•
categoryFavorite
•
categorylndex
number is a market/group/industry/sector/watchlist number: •
0..255 for categoryMarket, categoryGroup, categorylndustry
•
0..63 for categorySector
•
no limit for categoryWatchlist.
•
ignored for categoryFavorite, categorylndex
Example: // the code adds symbols w i t h l a s t day volume > 100000 / / t o the w a t c h l i s t number 1 i f ( L a s t V a l u e ( V ) > 100000 ) {
}
CategoryAddSymbol(
"", categoryWatchlist,
1
);
362
Introduction to AmiBroker
CategoryFind - Search for category by name Syntax: CategoryFind( "name", category) Returns: NUMBER
Function: Allows a search for category by name. It takes category name and kind as parameters and returns INDEX (ordinal number). For example it allows finding the index of a watchlist by searching for its name. The index (wlnumber in the example below) can be used later in functions that need the index (like CategoryGetSymbols). Example: wlnumber = CategoryFind("MyWatchList 1 " , c a t e g o r y W a t c h l i s t ); mysymbols = CategoryGetSymbols(categoryWatchlist, wlnumber );
CategoryGetName - Get the n a m e of a category Syntax: CategoryGetName( category, number) Returns: STRING
Function: The CategoryGetName function retrieves the name of category. category is one of the following: •
categoryMarket
•
categoryGroup
•
categorySector
•
categorylndustry
•
categoryWatchlist
•
categoryFavorite
•
categorylndex
AFL - AmiBroker Formula Language
363
number is a market/group/industry/sector/watchlist number: •
0..255 for categoryMarket, categoryGroup, categorylndustry
•
0..63 for categorySector
•
no limit for categoryWatchlist.
•
ignored for categoryFavorite, categorylndex
Example: CategoryGetName( categoryWatchlist, 1 );
CategoryGetSymbols - Retrieves comma-separated list of symbols belonging to given category Syntax: CategoryGetSymbols( category, index ) Returns: STRING
Function: Retrieves comma-separated list of symbols belonging to given category Supported categories: •
categoryMarket
•
categoryGroup
•
categorySector
•
categorylndustry
•
categoryWatchlist
•
categoryFavorite
•
categorylndex
index is a market/group/industry/sector/watchlist number: •
0..255 for categoryMarket, categoryGroup, categorylndustry
•
0..63 for categorySector
•
no limit for categoryWatchlist.
•
ignored for categoryFavorite, categorylndex
Use StrExtract function to extract individual symbols from the list.
364
Introduction to AmiBroker
Example:
/ * n o t e : i f given w a t c h l i s t c o n t a i n s l o t s o f symbols ** performance may be poor ** AVOID SUCH CODES IN REAL-TIME MODE ! */
f u n c t i o n CreateAverageForWatchList( {
listnum )
/ / r e t r i v e comma-separated l i s t o f symbols i n w a t c h l i s t l i s t = CategoryGetSymbols( c a t e g o r y W a t c h l i s t , l i s t n u m ) ; Average = 0; f o r ( i = 0; {
// j u s t in case t h e r e are no w a t c h l i s t members ( sym = S t r E x t r a c t ( l i s t , i ) )
!= " " ; i++ )
f = Foreign( sym, "C" ); i f ( i == 0 ) Average = f; e l s e Average = Average + f;
} }
r e t u r n Average / i;
// d i v i d e by number of components
P l o t ( CreateAverageForWatchList( 1 );
), "Avg of WL 1 " , colorGreen
CategoryRemoveSymbol - Remove a symbol from a category Syntax: CategoryRemoveSymbol( symbol, category, number ) Returns: NOTHING
Function: Removes the symbol from given category. Note that for markets, groups, industries 'removing ׳means moving from the given category to a category with number zero, since the symbol is always assigned 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
•
categorylndustry
AFL - AmiBroker Formula Language •
categoryWatchlist
•
categoryFavorite
•
categorylndex
365
number is a market/group/industry/sector/watchlist number: •
0..255 for categoryMarket, categoryGroup, categorylndustry
•
0..63 for categorySector
•
no limit for categoryWatchlist.
•
ignored for categoryFavorite, categorylndex
Example: // the code removes the symbols w i t h l a s t day volume < 1000 // from the w a t c h l i s t number 1 i f ( LastValue( V ) < 1000 ) {
}
CategoryRemoveSymbol( " " , c a t e g o r y W a t c h l i s t ,
1
);
FullName - Full name of the symbol Syntax: FullName() Returns: STRING
Function: The function returns the symbol's full name, which is definable by the user in Symbol > Information window. Example: printf( FullName());
366
Introduction to AmiBroker
GetCategorySymbols - Retrieves a comma-separated list of symbols belonging to a given category Syntax: GetCategorySymbols( category, index) Returns: STRING
Function: This function is obsolete. The same process is available under the new name CategoryGetSymbols. The old name is left only for backward compatibility. Please use the new name in all new codes.
GetDatabaseName - Retrieves folder name of current database Syntax: GetDatabaseName() Returns: STRING
Function: Retrieves the n a m e of the database - the last part (folder) of the database path Example: d b n a m e = GetDataBaseName();
GetFnData - Get fundamental data Syntax: GetFnData("field") Returns: NUMBER
Function: GetFnData allows accessing fundamental data from Information window (View > Information). "field" parameter can be one of the following: •
"EPS"
•
"EPSEstCurrentYear"
AFL - AmiBroker Formula Language •
"EPSEstNextYear"
•
"EPSEstNextQuarter״
•
"PEGRatio״
•
"SharesFloat"
•
"SharesOut"
•
"DividendPayDate"
•
"ExDividendDate"
•
"BookValuePerShare"
•
"DividendPerShare״
•
"ProfitMargin"
•
"OperatingMargin"
•
"OneYearTargetPrice"
•
"ReturnOnAssets"
•
"ReturnOnEquity"
•
"QtrlyRevenueGrowth"
•
"GrossProfitPerShare"
•
"SalesPerShare"
•
"EBITDAPerShare"
•
"QtrlyEarningsGrowth"
•
"InsiderHoldPercent"
•
"InstitutionHoldPercent"
•
"SharesShort"
•
"SharesShortPrevMonth"
•
"ForwardDividendPerShare"
•
״ForwardEPS״
•
"OperatingCashFlow"
•
"LeveredFreeCashFlow"
•
"Beta"
•
"LastSplitRatio"
•
"LastSplitDate"
367
Example: AddColumn( Close / GetFnData( "EPS" ) , " C u r r e n t P/E r a t i o " ); AddColumn( Close / GetFnData( "EPSEstNextYear" ) , " E s t . Next Year P/E r a t i o " ); Filter = Status("lastbarinrange");
368
Introduction to AmiBroker
GroupID - Get group ID/name Syntax: groupid( mode = 0 ) Returns: NUMBER STRING
Function: Retrieves the current stock group ID/name. •
When mode = 0 (the default value ) this function returns numerical group ID (consecutive group number)
•
When mode = 1 this function returns name of the group.
Example: F i l t e r = GroupID() == 7 OR GroupID() == 9; AddTextColumn( GroupID( 1 ), "Group name" );
IndustrylD - Get industry ID / name Syntax: IndustrylD( mode = 0 ) Returns: NUMBER STRING
Function: Retrieves the current stock industry ID/name. •
W h e n mode = 0 (the default value ) this function returns the numerical industry ID (consecutive industry number)
•
When mode = 1 this function returns the name of the industry.
Example: F i l t e r = I n d u s t r y l D ( ) == 7 OR I n d u s t r y l D ( ) == 9; AddTextColumn( I n d u s t r y l D ( 1 ), " I n d u s t r y name" );
AFL - AmiBroker Formula Language
369
InWatchList - Watchlist membership test (by ordinal number) Syntax: InWatchList( listno) Returns: NUMBER
Function: Checks if the stock belongs to a watchlist number listno. If yes - the function returns 1 otherwise 0. Example: Filter= InWatchList( 3 ) OR InWatchList( 5 );
InWatchListName - Watchlist membership test (by name) Syntax: InWatchList( "name) ״ Returns: NUMBER
Function: Checks if the stock belongs to a watchlist number "listname". If yes - the function returns 1 otherwise 0. Example: Filter= InWatchListName( "My Hotlist" ) OR InWatchList( "My Second Hotlist" );
IsContinuous - Checks 'continuous quotations' flag state Syntax: IsContinuous() Returns: NUMBER
Function: Returns 1 if current symbol has 'continuous quotations' flag turned on in Symbol > Information window. Returns zero otherwise. Example: ic = IsContinuous();
370
Introduction to AmiBroker
IsFavorite - Check if current symbol belongs to favorites Syntax: IsFavorite() Returns: NUMBER
Function: The IsFavorite function returns True (1) if current symbol belongs to favorites, returns False (0) otherwise. Example: if( {
IsFavorite()
)
p r i n t f ( Name() + " belongs to f a v o r i t e s " );
}
Islndex - check if current symbol is an index Syntax: Islndex() Returns: NUMBER
Function: The Islndex function returns True (1) if current symbol is an index, returns False (0) otherwise. Example: if( {
}
Islndex()
)
p r i n t f ( Name() + " is an i n d e x " );
MarketID - Market ID / name Syntax: MarketID( mode = 0 ) Returns: NUMBER STRING
AFL - AmiBroker Formula Language 388 Function: Retrieves current stock market ID/name. •
When mode = 0 (the default value ) this function returns numerical marketID (consecutive market number)
•
When mode = 1 this function returns name of the market.
Example: F i l t e r = MarketID() == 7 OR MarketID() == 9; AddTextColumn( MarketID( 1 ), "Market name" );
Name - Ticker symbol Syntax: Name() Returns: STRING
Function: It is used to display the stock short name (ticker) Example: Name()
SectorlD - Get sector ID / name Syntax: SectorlD( mode = 0 ) Returns: NUMBER STRING
Function: Retrieves current stock sector ID/name. •
When mode = 0 (the default value ) this function returns nu merical sector ID (consecutive sector number)
•
When mode = 1 this function returns name of the sector.
Example: F i l t e r = S e c t o r l D ( ) == 7 OR S e c t o r l D ( ) == 9; AddTextColumn( S e c t o r l D ( 1 ), "Sector name" );
372
Introduction to AmiBroker
REFERENCING O T H E R S Y M B O L D A T A
Foreign - Access foreign security data Syntax: Foreign( TICKER, DATAFIELD, fixup = 1) Returns: ARRAY
Function: Allows reference to other (than the current) tickers in the AFL formulas. TICKER is a string that holds the symbol of the stock. DATAFIELD defines which array is referenced. Allowable data fields: "open״, "close״, "high", "low", "volume", "interest". The last parameter - fixup - accepts following values 0 - the holes are not fixed 1 - default value - missing data bar OHLC fields are all filled using previous bar Close and volume is set to zero. Note: you can use Foreign/RelStrength without specifying last parameter: Foreign( "ticker", "field" ), RelStrength( "ticker" ) - then the holes will be fixed. 2 - causes filling the holes in the data with previous O, H, L, C, V values Unless you know what you are doing you should use the default value of fixup parameter (Fixup=l). If you do not use fixup=l, data holes will have the value of Null that you would need to handle by yourself. Foreign function synchronizes the data file you are referencing with the currently selected symbol. Synchronization makes sure that each bar of foreign data matches exactly with each bar of currently selected symbol. So if DateNum() function returns 990503 for given bar then Close array represents the close of currently selected symbol at May
AFL - AmiBroker Formula Language
373
3,1999 and Foreign(״SYMBOL״, "C") represents close of foreign symbol at May 3,1999 too. This is absolutely necessary because otherwise you won't be able to do any meaningful operations involving both selected symbol and foreign symbol. This is also needed for the display so when you mark the quote with a vertical line it will always match the date displayed regardless if you use Foreign or not. Please note that if you have data holes in the currently selected symbol, then in order to synchronize bars, the Foreign function will remove bars that exist in Foreign symbol but do not exist in currently selected symbol. Examples: / / P l o t t i n g spread between c u r r e n t l y // s e l e c t e d symbol and another one GraphO = Close - F o r e i g n ( "MSFT", " C l o s e " )
;
// EXAMPLE 2: / / B u i l t - i n r e l a t i v e performance c h a r t _N( T i c k e r L i s t = P a r a m S t r ( " T i c k e r s " , ""DJI,MSFT,GE") ); NumBars = 20; fvb = S t a t u s ( " f i r s t v i s i b l e b a r " ) ; P l o t ( 100 * ( C - C[ f v b ] ) / C[ f v b ], Name(), c o l o r B l u e ); f o r ( i = 0; ( symbol = S t r E x t r a c t ( T i c k e r L i s t , i ) ) != " " ; i + +
{)
fc = F o r e i g n ( symbol,
"C"
if( {
)
! isNull( fc[ 0 ] Plot(
}
}
);
)
100 * ( fc - f c [ f v b ] )/ f c [ f v b ], symbol, c o l o r L i g h t O r a n g e + ( ( 2 * i ) % 15 ), styleLine );
PlotGrid( 0, colorYellow ); _N( T i t l e = "{{NAME}} ־R e l a t i v e Performance [ % ] : {{VALUES}}" );
374
Introduction to AmiBroker
GetBaselndex - Retrieves symbol of relative strength base index Syntax: GetBaselndex() Returns: STRING
Function: Retrieves the base relative-strength index for given security as defined in Symbol > Categories. Example: AddTextColumn( GetBaselndex(), "Base index" );
PlotForeign - Plot foreign security data Syntax: PlotForeign( tickersymbol, name, color/bar color, style = styleCandle I styleOwnScale, minvalue = {empty[, maxvalue = {empty}, XShift = 0 ) Returns: NUMBER
Function: Plots the foreign-symbol price chart (symbol is defined by tickersymbol parameter). Second argument name defines graph n a m e 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) minvalue and maxvalue - (used by styleOwnScale plots ONLY) define plot m i n i m u m and m a x i m u m values (lower and upper b o u n d a r y for Y axis) XShift - allows visually shifting the chart into future (blank) bars. Example: PlotForeign( "ADJI", "Dow Jones", colorRed );
AFL - AmiBroker Formula Language
375
RelStrength - Comparative relative strength Syntax: RelStrength( "tickername", fixup = 1) Returns: ARRAY
Function: Calculates relative strength of currently selected security compared to "tickername" security. When you give an empty string as the argument, a standard relative strength base security taken from Stock > Categories will be used. The last parameter - fixup - with the default value of 1 ־causes filling the holes in the data with previous values. If fixup is 0 - the holes are not fixed. Note: you can still use Foreign/RelStrength in the old way: Foreign( "ticker״, "field" ), RelStrength( "ticker" ) then the holes will be fixed. Example: RelStrength( " A DJI" )
RestorePriceArrays - Restore price arrays to original symbol Syntax: RestorePriceArrays( tradeprices = False ) Returns: NOTHING
Function: The RestorePriceArrays restores original price and volume arrays after the call to SetForeign. tradeprices parameter has to match the one used in SetForeign() function. When tradeprices argument is set to TRUE, then not only OHLC, V, OI, Avg arrays are restored, but BuyPrice, SellPrice, ShortPrice, CoverPrice, PointValue, TickSize, RoundLotSize, MarginDeposit variables are too.
376
Introduction to AmiBroker
Example: / / Example 1 : P l o t t h e i n d i c a t o r using f o r e i g n s e c u r i t y data SetForeign("MSFT"); P l o t ( U l t i m a t e ( ) , " U l t i m a t e from MSFT", colorRed ); RestorePriceArrays(); // Example 2: Use SetForeign w i t h E q u i t y f u n c t i o n SetForeign("MSFT", True, True ); Buy = Cross( MACD(), S i g n a l ( ) ) ; S e l l = Cross( S i g n a l ( ) , MACD()); e = E q u i t y ( ) ; // b a c k t e s t on MSFT R e s t o r e P r i c e A r r a y s ( True ); // <- should match parameter used i n SetForeign
SetForeign - Replace current price arrays with those of foreign security Syntax: SetForeign( ticker, fixup = True, tradeprices = False ) Returns: NUMBER
Function: The SetForeign function replaces current price/volume arrays with those of foreign security, returns True (1) if ticker exists, False (0) otherwise. If ticker does not exist (and function returns false) price arrays are not changed at all. fixup parameter controls whether data holes are filled with previous bar data or not. If fixup is False then data holes are filled with Null value. For detailed discussion on fixup parameter please check Foreign function. tradeprices parameter controls whether trade price arrays should be replaced too. If it is set to TRUE, then not only OHLC, V, OI, Avg arrays are set to foreign symbol values, but also BuyPrice, SellPrice, ShortPrice, CoverPrice, PointValue, TickSize, RoundLotSize, MarginDeposit variables are set to correspond to foreign security. This allows Equity() to work well with SetForeign.
AFL - AmiBroker Formula Language
377
The single SetForeign( "ticker" ) call is equivalent to the following sequence: C = Foreign( "ticker", "C" ); 0 = Foreign( "ticker", "O" ); H = Foreign( "ticker", "H" ); L = Foreign( "ticker", "L" ); V = Foreign( "ticker", "V" ); 01 = Foreign( "ticker", "I" ); Avg = ( C + H + L)/3; but 6x faster. (SetForeign takes about the same time as single foreign). To restore original prices call RestorePriceArrays() Examples: / / Example 1 : P l o t t h e i n d i c a t o r u s i n g f o r e i g n s e c u r i t y d a t a SetForeign("MSFT"); P l o t ( U l t i m a t e ( ) , " U l t i m a t e from MSFT", colorRed ) ; RestorePriceArrays(); / / Example 2 : Use S e t F o r e i g n w i t h E q u i t y f u n c t i o n SetForeign("MSFT", T r u e , True ) ; Buy = Cross( MACD(), S i g n a l ( ) ) ; S e l l = Cross( S i g n a l ( ) , MACD()); e = E q u i t y ( ) ; // b a c k t e s t on MSFT R e s t o r e P r i c e A r r a y s ( True ) ; // <- should match parameter used in S e t F o r e i g n
378
Introduction to AmiBroker
FILE I N P U T / O U T P U T FUNCTIONS
fclose - Close a file Syntax: fclose( filehandle) Returns: NOTHING
Function: Closes a file. The filehandle (NUMBER) should be the handle returned by fopen function. Example: f h = fopen( i f ( fh ) {
"myfile.txt",
fputs( "Testing", fh fclose( fh );
"w");
);
}
fdelete - Deletes a file Syntax: fdelete( "filename" ) Returns: NUMBER
Function: This function deletes a file. "filename" is a path to the file name (relative or full path). If just file name without path is specified then AmiBroker directory is used, returns TRUE if file successfully deleted, FALSE otherwise Example: fdelete( "test.csv" )
AFL - AmiBroker Formula Language
379
feof - Test for end-of-file Syntax feof( filehandle ) Returns: NUMBER
Function: The feof function returns a nonzero value after the first read operation that attempts to read past the end of the file. It returns 0 if the current position is not end of file. There is no error return value. filehandle is a file handle returned by fopen function. Example: // The f o l l o w i n g code (commentary) reads / / a l l l i n e s from the e x t e r n a l f i l e and / / d i s p l a y s i t i n commentary window f h = fopen( i f ( fh ) { while( {
}
}
"quotes.csv",
"r");
! f e o f ( fh ) )
p r i n t f ( fgets( fh )
);
else {
}
printf("ERROR: f i l e can not be found (does not e x i s t ) " ) ;
380
Introduction to AmiBroker
fgets - get a string from a file Syntax: fgets( filehandle ) Returns: STRING
Function: The fgets function reads a string from the input file (defined by filehandle a r g u m e n t ) and returns the string as a result. fgets reads characters from the current file position to and including the first newline character, or to the end of the file whichever comes first. The newline character, if read, is included in the returned string.
The filehandle argument is a number returned by fopen function. The file has to be opened with "x" flag (for reading). Example: // The f o l l o w i n g code (commentary) reads / / a l l l i n e s from the e x t e r n a l f i l e and / / d i s p l a y s i t i n commentary window f h = fopen( i f ( fh ) { while( {
}
}
"quotes.csv",
"r");
! f e o f ( fh ) )
p r i n t f ( fgets( fh )
);
else {
}
printf("ERROR: f i l e can not be found (does not e x i s t ) " ) ;
AFL - AmiBroker Formula Language
381
fgetstatus - Retrieves file status/properties Syntax: fgetstatus( filename, what, format = 0 ) Returns: NUMBER STRING
Function: The function that retrieves file properties/status. Returns NUMBER or STRING depending on format parameter. If file does not exist it returns Null. Parameters: •
filename - the name of the file (with or without full path) to query
•
what ־specifies what file property to retrieve, allowable values 0 - the date/time the file was created 1 - the date/time the file was last modified 2 - the date/time the file was last accessed for reading 3 - the file size in bytes 4 - attribute byte of the file
•
format - specifies return format of date/time values (format specifications are the same as in Now() function): allowed values: 0 - returns string containing date/time formatted according to system settings 1 - returns string containing date only formatted according to system settings 2 - returns string containing time only formatted according to system settings 3 - returns DATENUM number with date 4 - returns TIMENUM number with time 5 - returns DATETIME number with date/time
382
Introduction to AmiBroker 6 - returns date DAY (1..31) 7 - returns date MONTH (1..12) 8 - returns date YEAR (four digit) 9 ־returns date DAY OF WEEK (1..7, where l = S u n d a y 2 = ׳M o n day, and so on) 10 - returns date DAY OF YEAR (1..366)
Note that Windows supports only 2 second resolution of file date/ time stamps. Example: / / get m o d i f i c a t i o n date s t r i n g o f p o r t f o l i o . a f l f i l e fgetstatus("formulasWEquity\\portfolio.afl",1,0);
fmkdir - Creates (makes) a directory Syntax: fmkdir( "dirname" ) Returns: NUMBER
Function: Creates (makes) a directory. "dirname" specifies the path of the directory to be created. This function creates only one directory at a time. If you want to create a nested directory tree, you have to call it multiple times. For example to create C:\MyDirectory\MySubDirectory folder you have to call it twice: fmkdir( fmkdir(
"C:WMyDirectory" ); "C:\\MyDirectory\\MySubDirectory"
);
It is safe to call fmkdir even if directory already exists - there will be no change to file system. Returns TRUE if directory successfully created, FALSE otherwise Example: fmkdir( "C:\\TestResults" );
AFL - AmiBroker Formula Language
383
fopen - Open a file Syntax: fopen( filename, m o d e ) Returns: NUMBER
Function: Opens file, returns filehandle (NUMBER). File handle is non-zero if the file opened successfully, zero on failure. Parameters: •
filename - STRING - contains the path to the file name. Note that single backslash in path must be written in AFL as a double backslash
•
mode - STRING - access mode can be "r" - for reading, "w" for writing, "a" for appending (and all other regular C-runtime library modes)
Example: f h = fopen( i f ( fh ) {
}
fputs(
"myfile.txt",
"Testing",
"w");
fh );
else { printf("Error
}
opening
file");
384
Introduction to AmiBroker
fputs - Write a string to a file Syntax: fputs( string, filehandle) Returns: NOTHING
Function: Writes (puts) the string to the file. The filehandle must be a number returned by fopen function used to open the file. The file has to be open for writing or appending ("w" or "a") for this fputs to work. Example: // The f o l l o w i n g code e x p o r t s quotes / / o f c u r r e n t stock t o q u o t e s . c s v / / comma separated f i l e
// fh = fopen( i f ( fh ) { fputs(
"quotes.csv",
"w");
"Date,Open,High,Low,Close,V01ume\n",
fh
);
y = Year(); m = Month(); d = Day(); f o r ( i = 0; i < BarCount; i++ ) { ds = StrFormat("%02.Of-%02.Of-%02.Of,", y[ i ] , m[ i ] , d[ i ] ) ; f p u t s ( ds, f h ) ;
}
qs = S t r F o r m a t ( " % . 4 f , % . 4 f , % . 4 f , % . 4 f , % . 0 f \ n " , 0[ i ] , H[ i ] , L[ i ] , C[ i ] , V[ i ] f p u t s ( qs, f h ) ;
fclose( fh
}
);
);
AFL - AmiBroker Formula Language
385
frmdir - Removes a directory Syntax: frmdir("dirname") Returns: NUMBER
Function: This function removes a directory "dirname" specifies the path of the directory to be removed. This function removes only one directory at a time. So if you want to remove a nested directory tree you have to call it multiple times, for example: f r m d i r ( "C: W M y D i r e c t o r y W M y S u b D i r e c t o r y " subdir f i r s t frmdir( "C:WMyDirectory" );
);
/ / d e l e t e nested
The directory must be empty before removing it otherwise it will not be possible to remove it. Returns TRUE if directory successfully removed, FALSE otherwise Example: frmdir ( ״C:\\01dTest;)״
386
Introduction to AmiBroker
STRING M A N I P U L A T I O N
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. Useful for creation of exploration that displays single letters for signals instead of numbers. Example: Buy = C r o s s ( M A C D ( ) , S i g n a l ( ) ) ; S e l l = Cross(Signal(),MACD()); F i l t e r = Buy OR S e l l ; AddColumn( I I f ( Buy, A s c ( " B " ) , A s c ( " S " ) ) ,
);
" S i g n a l " , formatChar
DateTimeToStr - Convert datetime to string 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: T001Tip="X="+DateTimeT0Str(GetCursorXPosition()) +"nY="+GetCursorYPosition();
AFL - AmiBroker Formula Language
387
NumToStr - Convert number to string Syntax: NumToStr( NumToStr(
format = 1.3, separator=True) format = 1.3, separator=True )
NUMBER, ARRAY,
Returns: STRING
Function: It is used to convert numeric value of NUMBER or ARRAY to string. The second parameter - format - allows you to control the output formatting (decimal places and leading spaces). The integer part of the number controls the m i n i m u m number of characters used to display the number (if you specify high number the output will be space-padded). The fractional part defines how many decimal places to display, for example 1.0 - will give you a number without fractional part at all, and 1.2 - will give two digits past the decimal point. There is also a special format constant formatDateTime that allow conversion of date/time returned by DateTime() function formatted according to Windows regional settings. Third parameter - separator (true by default) - controls whether the thousand separator is added or not. Thousands separator is definable in Tools > Preferences > Misc. Note: NumToStr is a synonym for WriteVal function, and is the preferred function. Examples: // Simple use (no custom f o r m a t ) NumToStr( StochK(39) - StochK(12)
);
/ / D i s p l a y r a t e o f change w i t h 2 decimal d i g i t s // and % appended to the end NumToStr( ROC( Close, 20 ), 1.2 ) + "%"; // Display date/time according to regional s e t t i n g s NumToStr( DateTime(), formatDateTime );
388
Introduction to AmiBroker
printf - Print formatted output to the output window Syntax: printf( formatstr,...) Returns: NOTHING
Function: The printf function formats and prints a series of characters and values to the output window, which can be either the commentary or the interpretation window. If arguments follow the format string, the format string must contain specifications that determine the output format for the arguments. printf and StrFormat behave identically except that printf writes output to the window, while StrFormat does not write anything to output window but returns resulting string instead. For numbers always use %f, %e, or %g formatting; %d or %x will not work because there are no integers in AFL. As of now only numbers and arrays can be printed. For arrays, 'selected value ׳is printed. Read more about various % format specifiers on Microsoft site: http://msdn2.microsoft.com/en-us/library/56e442dc(VS.80).aspx Example: f o r ( i = 0; i < 10; i + + ) {
}
printf(
"Hello world,
l i n e %gn",
i );
AFL - AmiBroker Formula Language
389
StrExtract - Extracts given item (substring) from comma-separated string Syntax: StrExtract( list, item ) Returns: STRING
Function: Extracts given item (substring) from comma-separated list of items, item is a zero-based index of the item in the list. If no substring at given index is found then an empty string is returned ()״״. Useful to retrieve symbols from the list obtained via GetCategorySymbols function. Example: StrExtract(
"MSFT,AAPL,AMD,INTC", 2 ) w i l l r e t u r n AMD
StrExtract(
"MSFT,AAPL,AMD,INTC", 0 ) w i l l r e t u r n MSFT
StrExtract( string ""
"MSFT,AAPL,AMD,INTC", 200 ) w i l l r e t u r n empty
StrFind - Find substring in a string Syntax: StrFind( string, substring ) Returns: NUMBER
Function: The StrFind function finds the first occurrence of substring in string. Returns 0 if not found, otherwise returns character index (onebased) of first occurrence.
390
Introduction to AmiBroker
Example: i f ( S t r F i n d ( Name(), { pnintf(
״
.L"
"The " + Name()
)
) + " has
.L s u f f i x " ) ;
}
else { printf(
"The " + Name() + " does not have
.L s u f f i x " ) ;
} StrFormat - Write formatted output to the string Syntax: StrFormat( formatstr, ...) Returns: STRING
Function: The StrFormat function formats and returns a series of characters and values in the result string. If arguments follow the format string, the format string must contain specifications that determine the output format for the arguments. StrFormat and printf behave identically except that printf writes output to the window, while StrFormat does not write anything to output w i n d o w but returns resulting string instead. StrFormat function is useful in conjunction with fputs function that allows writing a string to a file. For numbers always use %f, %e, or %g formatting; %d or %x will not work because there are no integers in AFL. As of now only numbers and arrays can be used. For arrays, 'selected value' is used. Example: f h = f o p e n ( " T e s t . c s v " , "w" ) ; f o r ( i = 0 ; f h && i < 10; i + + ) { t e x t = StrFormat( fputs( text, fh );
} fclose(
fh
);
"Hello world,
l i n e %g\n",
i
);
AFL - AmiBroker Formula Language
391
StrLeft - Extracts the leftmost part Syntax: StrLeft( STRING, count) Returns: STRING
Function: Extracts the first (that is, leftmost) count characters from STRING and returns a copy of the extracted substring. If count exceeds the string length, then the entire string is extracted. Example: newstring = StrLeft( string, 4 );
StrLen - string length Syntax: StrLen( STRING) Returns: NUMBER
Function: Calculates the length of the string Example: This function could be used for (for example) filtering out only 3 letter stock codes: Buy = something A N D StrLen( name()) ==3;
StrMid - Extracts part of the string Syntax: StrMid( STRING, start, count) Returns: STRING
Function: Extracts a substring of length count characters from STRING, starting at position start (zero-based). The function returns a copy of the extracted substring. Example: newstring = StrMid( string, 1, 2 );
392
Introduction to AmiBroker
StrReplace - String replace Syntax: StrReplace( srcstring, oldsubstring, newsubstring ) Returns: STRING
Function: Given an original string srcstring, replace all occurrences of oldsubstring with newsubstring. The string may grow or shrink as a result of the replacement, that is oldsubstring and newsubstring do not have to be equal in length. The function performs case-sensitive matches. Example: / / t h e e x p r e s s i o n below w i l l / / r e s u l t i n s t r i n g i n which ' r e d ' i s replaced w i t h S t r R e p l a c e ( " T h i s f o x i s r e d " , " r e d " , "brown" ) ;
'brown'
StrRight - Extracts the rightmost part of the string Syntax: StrRight( STRING, count) Returns: STRING
Function: Extracts the last (that is, rightmost) count characters from STRING and returns a copy of the extracted substring. If count exceeds the string length, then the entire string is extracted. Example: newstring = StrRight( string, 4 );
StrToDateTime - Convert string to datetime Syntax־. StrToDateTime( "string) ״ Returns: NUMBER
Function: Converts a string representing date/time value to the corresponding DateTime number. The resulting string can later be compared to output of DateTime() function, for example. Example: Buy = DateTime() == StrToDateTime("2005-Mar-05");
AFL - AmiBroker Formula Language StrToLower - Convert to lowercase Syntax: StrToLower( "string" ) Returns: STRING
Function: This function converts input string to all lower case. Example: Title = StrToLower( "MiXeD CaSe;) ״
StrToNum ־Convert string to number Syntax: StrToNum( string) Returns: NUMBER
Function: Converts string to number. Example: L i s t = "123,456,789"; f o r ( 1 = 0 ; ( Item = S t r E x t r a c t ( L i s t , i ) {
}
p r i n t f ( "%gn", StrToNum( Item )
)
! = " " ; i++ )
);
StrToUpper - Convert to uppercase Syntax: StrToUpper( "string) ״ Returns: STRING
Function: This function converts input string to all upper case. Example: Title = StrToUpper( "MiXeD CaSe;) ״
393
394
Introduction to AmiBroker
T R A D I N G SYSTEM T O O L B O X
Alertlf - Trigger alerts Syntax: Alertlf( BOOLEAN_EXPRESSION, command, text, type = 0, flags = 1+2+4+8, lookback = 1 ); Returns: NOTHING
Function: Triggers alert action if BOOLEAN_EXPRESSION is true. BOOLEAN_EXPRESSION is the expression that if it evaluates to True (non zero value) triggers the alert. If it evaluates to False (zero value) no alert is triggered. Only lookback most recent bars are considered. 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. 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 the-path-to-the-file-or-URL. Launches an external application or file or URL specified after EXEC command are attached after file n a m e and text is attached at the end EXEC command uses ShellExecute function and allows not only EXE files but URLs too. 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
AFL - AmiBroker Formula Language
395
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 the name "other" Flags control behavior 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. lookback parameter controls how m a n y recent bars are checked Example: Buy = Cross( MACD(), S i g n a l ( ) ); S e l l = Cross( S i g n a l ( ) , MACD() ); Short = S e l l ; Cover = Buy; A l e r t I F ( Buy, "EMAIL", "A sample a l e r t on " + F u l l N a m e ( ) , 1 ); A l e r t I F ( S e l l , "SOUND C : \ \ W i n d o w s \ \ M e d i a \ \ D i n g . w a v " , "Audio a l e r t " , 2 ); A l e r t I F ( S h o r t , "EXEC C a l c . e x e " , "Launching e x t e r n a l a p p l i c a t i o n " , 3 ); A l e r t I F ( Cover, " " , "Simple t e x t a l e r t " , 4 ) ;
396
Introduction to AmiBroker
ApplyStop - Apply built-in stop Syntax: ApplyStop( type, mode, amount, exitatstop, volatile = False, ReEntryDelay = 0) Returns: NOTHING
Function: Controls the built-in stops from the formula level. This allows optimization of stops. Parameters: type: 0 = stopTypeLoss - m a x i m u m 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 at regular trade price (if you are trading on the close it means that only the close price will be checked for exits and exit will be done at the close price)
AFL - AmiBroker Formula Language
397
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 behavior) or if it can vary during the trade (Volatile = TRUE) (allows single line Chandelier exit implementation) ReEntryDelay: how many bars to wait until entering the same stock is allowed. 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
398
Introduction to AmiBroker
Scenario 3: You trade on next day Open and want to exit by stop on Open price when previous day's H-L range hits stop Correct settings: ExitAtStop = 2 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 Notes: 1. If you are trading at the Close with zero delays be sure to unmark "Activate Stops Immediately" in Settings.
AFL - AmiBroker Formula Language
399
2. For visual conformation of ApplyStop function, add the following lines below your ApplyStop formula in Indicator Builder: Equity(•!);
// THIS EVALUATES STOPS
Plot(Sell==4,"ApplyStop Sell",colorRed,1|styleOwnScale); Plot(Cover==4,"ApplyStop Cover",colorGreen,1|styleOwnScale);
3. If two or more different stops are triggered on the same bar then they are evaluated in this fixed order: Fixed Ruin stop (losing 99.96% of the starting capital) Max. loss stop Profit target stop Trailing stop N-bar stop 4. 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 2 - max. loss 3 - profit target 4 - trailing 5 - n-bar stop 6 - ruin stop 5. 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 the 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 the "Has priority" box in AA Settings window.
400
Introduction to AmiBroker
6. ApplyStop function is designed to be used to simulate stop orders placed at the exchange or simulated by the brokerage. These explain how stops operate for Interactive Brokers: http://www.interactivebrokers.com/en/trading/orders/stop.php7ib_ entity=uk http://www.interactivebrokers.com/en/trading/orders/trailingStops. php?ib_entity=uk
Example: / * max l o s s s t o p o p t i m i z a t i o n * / ApplyStop(stopTypeLoss, stopModePercent, O p t i m i z e ( "max. l o s s s t o p l e v e l " , 10, 2, 30, 1 True ) ; /* s i n g l e - l i n e implementation of Chandelier e x i t */ A p p l y S t o p ( s t o p T y p e T r a i l i n g , stopModePoint, 3*ATR(14), True ) ; / * N-bar s t o p * / A p p l y S t o p ( stopTypeNBar,
stopModeBars, 5 );
),
True,
AFL - AmiBroker Formula Language
401
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 )
Cross - Crossover check 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))
402
Introduction to AmiBroker
EnableRotationalTrading - Turns on rotational-trading mode of the backtester This function is now marked as obsolete. Use SetBacktestMode( backtestRotational) in new formulas. But the information is still relevant. Unless you specifically want to implement fund-switching/rotational trading system you should not use this mode. Rotational trading is a limited subset of AmiBroker's general portfolio testing. Syntax: EnableRotationalTrading() Returns: NOTHING
Function: When placed on the top of system formula it turns on the rotational-trading (aka. fund-switching) mode of the backtester. Rotational trading is a popular method for trading mutual funds. It is also k n o w n as fund-switching or scoring&ranking. Its basic premise is to rotate among symbols all the time so only the top N issues ranked according to some user-definable score are held. The number of positions open depend on "Max. open positions" setting and available f u n d s and position size. Once a position is entered, it remains in place until the security's rank drops below WorstRankHeld (can be set via SetOption("WorstRankHeld", 5 )). Regular buy/sell/short/cover signals are not used at all. The rotational trading mode uses "buy price" and "buy delay" from the Settings I Trade page as trade price and delay for both entries and exits (long and short). To enter this mode you have to call EnableRotationalTrading() function at the very beginning of your formula. Use of buy/sell/ short/cover variables is not allowed. Only PositionScore variable will be used to rank securities and trade top N securities.. A simple rotational trading formula (stocks with high RSI are best candidates for shorting while stocks with low RSI are best candidates for long positions):
AFL - AmiBroker Formula Language
403
EnableRotationalTrading(); SetOption("WorstRankHeld",5); P o s i t i o n S i z e = - 2 5 ; / / i n v e s t 25% o f e q u i t y i n s i n g l e s e c u r i t y P o s i t i o n S c o r e = 50 - R S I ( ) ;
The score (PositionScore) for all securities is calculated first. Then all scores are sorted according to absolute value of PositionScore. Then top N are chosen to be traded. N depends on available f u n d s and "max. open positions" setting. Backtester successively enters the trades starting from highest ranked security until the number of positions open reaches "max. open positions" or there are no more f u n d s available. The score has the following meaning: higher positive score means better candidate for entering long trade lower negative score means better candidate for entering short trade the score of zero means no trade (exit the trade if there is already an open position on a given symbol) the score equal to scoreNoRotate constant means that already open trades should be kept and no new trades entered the score equal to scoreExitAll constant causes the rotational mode backtester to exit all positions regardless of HoldMinBars. Note that this is a global flag and it is enough to set it for just any single symbol to exit all currently open positions, no matter on which symbol you use scoreExitAll (it may be even on symbol that is not currently held). By setting PositionScore to scoreExitAll you exit all positions immediately regardless of HoldMinBars setting Exits are generated automatically when security's rank drops below "worst rank held". There is no real control over when exits happen except for setting low score to force exits. You can also set the score on any (at least one) security to the value of scoreNoRotate to prevent rotation (so already open positions are kept). But this is global and does not give you individual control.
404
Introduction to AmiBroker
Equity - Calculate single-symbol equity line This function is left here for backward compatibility. Equity() function uses so called "old" single-security backtester that offers only a subset of features of new backtester. To retrieve the value of portfolio-level equity generated by the new backtester use Foreign(" EQUITY״, "C"). Syntax: Equity( Flags = 0, RangeType = -1, From = 0, To = 0 ) Returns: ARRAY
Function: Returns single-security Equity line based on buy/sell/short/ cover rules, buy/sell/short/coverprice arrays, all apply stops, and all other backtester settings. Flags - defines the behavior of Equity function Flags: 0 : (default) Just calculates the equity array. 1 : works as 0, but additionally updates buy/sell/short/cover arrays so all redundant signals are removed exactly as it is done internally by the backtester plus all exits by stops are applied so it is now possible to visualize ApplyStop() stops. 2 : (advanced) works as 1 but updated signals are not moved back to their original positions if buy/sell/short/cover delays set in preferences are non-zero. Note: this value of flag is documented but in 99% of cases should not be used in your formula. Other values are reserved for the future. RangeType - defines quotations range being used: -1 : (default) use range set in the Automatic analysis window 0 : all quotes 1 : n last quotes (n defined by 'From' parameter) 2 : n last days (n defined by 'From' parameter) 3 : From/To dates
AFL - AmiBroker Formula Language
405
From : defines start date (datenum) (when RangeType == 3) or "n" parameter (when RangeType == 1 or 2) To: defines end date (datenum) (when RangeType == 3) otherwise ignored datenum defines date the same way as DateNum() function as YYYMMDD where YYY is (year - 1900), MM is month, DD is day December 31st, 1999 has a datenum of 991231. May 21st, 2001 has a datenum of 1010521 All these parameters are evaluated at the time of the call of Equity function. Complete equity array is generated at once. Changes to buy/sell/short/cover rules made after the call have no effect. Equity function can be called multiple times in single formula. Example: Buy Sell e = Plot Plot
= Cross (C, MA(C,5)); // Your buy r u l e = Cross (MA(C,5),C); // Your S e l l r u l e ; Equity(); (C, "C", c o l o r B l a c k , s t y l e C a n d l e ) ; (e, " E q u i t y " , colorGreen, s t y l e L i n e | styleOwnScale);
ExRem - Remove excess signals Syntax: ExRem( ARRAY1, ARRAY2 ) Returns: ARRAY
Function: Removes excess signals returns 1 on the first occurrence of "true" signal in Arrayl then returns 0 until Array2 is true even if there are "true" signals in Arrayl Example: Buy = ExRem( Buy, S e l l ); S e l l = ExRem( S e l l , Buy );
406
Introduction to AmiBroker
ExRemSpan - Remove excess signals spanning given number of bars Syntax: ExRemSpan( ARRAY1, n u m b a r s ) Returns: ARRAY Function: Removes excess signals that span numbars bars since initial signal. (In other words first non-zero bar passes through, then all subsequent non-zero bars are ignored (zero is returned) until numbars bars have passed since initial signal. From then on a new signal may pass through) This function makes easy writing exits after a fixed number of bars, for example if you want to always sell 5 bars after the buy you should now use a combination of ExRemSpan and Ref(). It will work even if initial buy array has lots of redundant signals. Example: Buy = 1; Buy = ExRemSpan( Buy, 5 ); S e l l = Ref( Buy, -5 );
Flip - Creates State signals from Impulse signals Syntax: Flip( ARRAY1, ARRAY2) Returns: ARRAY
Function: Works as a flip/flop device or "latch" returns 1 from the first occurrence of "true" signal in Arrayl until a "true" occurs in Array2 which resets the state back to zero until next "true" is detected in Arrayl. Example: Buy = Cross(C,MA(C,5)); S e l l = Cross (MA(C,5),C); // Comment out the next two l i n e s / / t o see the e f f e c t o f F l i p . Buy = F l i p ( B u y , S e l l ) ;
AFL - AmiBroker Formula Language Sell = Flip(Sell,Buy); Plot(Buy,"Buy",colorGneen,styleLine); P10t(Sell, "Sell", colorRed,styleLine);
GetBacktesterObject - Get access to the backtester object Syntax: GetBacktesterObject() Returns: OBJECT
Function: This function is used in custom backtester procedures to get access to the backtester object. Note that GetBacktester method should only be called when Status("action") returns actionPortfolio. For more details please read Custom Backtester documentation Example: i f ( Status("action")== actionPortfolio {
)
/ / r e t r i e v e the i n t e r f a c e t o p o r t f o l i o b a c k t e s t e r bo = G e t B a c k t e s t e r O b j e c t ( ) ; / / . . . h e r e i s your custom b a c k t e s t f o r m u l a .
}
407
408
Introduction to AmiBroker
GetOption - Gets the value of option in automatic analysis settings Syntax: GetOption("fieldname") Returns: NUMBER
Function: Gets the value of various options in automatic analysis settings. field - is a string that defines the option to read. There are following options available: •
"NoDefaultColumns" - if set to True - exploration does not have default Ticker and Date/Time columns
•
"InitialEquity"
•
"AllowSameBarExit"
•
"ActivateStopsImmediately"
•
"AllowPositionShrinking"
•
"FuturesMode"
•
"InterestRate"
•
"MaxOpenPositions" - m a x i m u m number of simultaneously open positions (trades) in portfolio backtest/optimization
•
"WorstRankHeld" - the worst rank of symbol to be held in rotational trading mode (see EnableRotationalTrading for more details)
•
"MinShares" - the m i n i m u m number of shares required to open the position in the backtester/optimizer. If you don't have enough f u n d s to purchase that many, trade will NOT be entered
•
"MinPosValue" - (4.70.3 and above) the m i n i m u m dollar amount required to open the position in the backtester/optimizer. If you don't have enough f u n d s trade will NOT be entered
•
"PriceBoundChecking" - if set to False - disables checking and adjusting buyprice/sellprice/coverprice/shortprice arrays to current symbol High-Low range.
AFL - AmiBroker Formula Language
409
•
CommissionMode 0 - use portfolio manager commission table 1 - percent of trade 2 - $ per trade 3 - $ per share/contract
•
CommissionAmount - amount of commission in modes 1..3
•
AccountMargin - (in old versions it was 'MarginRequirement') - account margin requirement (as in settings), 100 = no margin
•
ReverseSignalForcesExit - reverse entry signal forces exit of existing trade (default = True )
•
UsePrevBarEquityForPosSizing - Affects how percent of current equity position sizing is performed. False (default value) means: use current (intraday) equity to perform position sizing, True means: use previous bar closing equity to perform position sizing
Example: InitialEquity = GetOption("InitialEquity");
GetTradinglnterface - retrieves OLE automation object to automatic trading interface Syntax: GetTradinglnterface() Returns: OBJECT
Function: Retrieves the OLE (Object Linking and Embedding) automation object to automatic trading interface. "Name" is the interface name. You have to have the trading interface installed separately to make it work, otherwise you will get the error message attempting to use this function. Trading interface for Interactive Brokers is available from download section: http://www. amibroker.com/download.html
410
Introduction to AmiBroker
Hold - Hold the alert signal Syntax: Hold( EXPRESSION, p e r i o d s ) Returns: ARRAY
Function: Holds a "true" result of EXPRESSION for the specified number of periods. This true result is held true over the number of periods specified even if a "false" result is generated. Example: Hold( Cross(RSI(14)/70),5)
I l f - Immediate IF function Syntax: Ilf( EXPRESSION, TRUE_PART, FALSE_PART ) Returns: ARRAY
Function: "Immediate־IF" ־a conditional function that returns the value of the second parameter (TRUE_PART) if the conditional expression defined by the first parameter (EXPRESSION) is true; otherwise, the value of third parameter is returned (FALSE_ PART). IIF is a function - so the result of evaluation is returned by that function and should be assigned to some variable. Ilf 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. A common error assumes that Ilf is a flow control statement. It is not. Ilf is a function. This is the correct way to use Ilf: result = Ilf( condition, 7, 9 ); And this is a common, but incorrect way: Ilf( condition, result = 7, result = 9);
AFL - AmiBroker Formula Language
411
Example: The formula result = Ilf( MACD()
LastValue - Last value of the array Syntax: LastValue(ARRAY, lastmode = True ) Returns: NUMBER
Function: Returns the last calculated value of the specified ARRAY. The result of this function can be used in place of a constant (NUMBER) in any function argument. If ARRAY is undefined (e.g., only 100-days loaded and you request the last value of a 200-day moving average) then the lastvalue function returns zero. Warning: since this function fills an entire data array with the last value of another array, it allows a formula to look into the future. lastmode parameter (affects only commentary/interpretation): True - the last value is always returned False - then in commentary the 'selected' value is returned
412
Introduction to AmiBroker
Optimize - Define optimization variable Syntax: Optimize( "description", default, m i n , max, step ) Returns: NUMBER Function: Defines the optimization process parameters. With normal backtesting, scanning, exploration, and commentary modes the optimize function returns default value, so the above function call returns default. In optimization mode the 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 the 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; step is an interval used for increasing the value from min to max. Example: variable = Optimize("my optimization var", 9, 2, 20, 1 ); Notes: 1. You can refresh your Equity chart after each Optimization step and observe (like a slide show) how the linearity of your Equity curve is affected by adding these two lines to the very end of your code: AB = C r e a t e O b j e c t ( " B r o k e r . A p p l i c a t i o n " ) ; AB.RefreshAll();
Important note: Do not use in commentary, interpretation, or indicator builder because it will cause a loop. 2. Here it is a function that combines Param() and Optimize(): f u n c t i o n ParamOptimize( pname, d e f a u l t v a l , minv, maxv, step ) { r e t u r n O p t i m i z e ( pname, Param( pname, d e f a u l t v a l , minv, maxv, minv, maxv, s t e p );
}
step ),
AFL - AmiBroker Formula Language
413
Ref - Reference past/future values of the array Syntax: Ref( ARRAY, period ) Returns: ARRAY
Function: References a previous or subsequent element in an ARRAY A positive period references "n" periods in the future; a negative period references "n" periods ago. Example: The formula "ref( CLOSE, -14 )" returns the closing price 14 periods ago. Thus, you could write the 14-day price rate-ofchange (expressed in points) as "C - ref( C, -14 )." The formula "ref( C, 12 ) ״returns the closing price 12 periods ahead (this means looking up the future)
SetBacktestMode - Sets working mode of the backtester Syntax: SetBacktestMode( mode ) Returns: NOTHING
Function: Sets the working mode of the backtester. A 'mode' parameter is one of the following backtest modes: Supported backtest modes: •
backtestRegular - regular, signal-based backtest, redundant signals are removed.
•
backtestRegularRaw - signal-based backtest, redundant (raw) signals are not removed, only one position per symbol allowed
•
backtestRegularRawMulti - signal-based backtest, redundant (raw) signals are not removed, 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 exits all open positions on a given symbol, Scale-In/Out works on all open positions of given a symbol at once.
•
backtestRotational - rotational trading system.
414
Introduction to AmiBroker
Examples: SetBacktestMode( SetBacktestMode( SetBacktestMode(
backtestRegular ) ; backtestRegularRaw ); backtestRegularRawMulti
);
/ / r o t a t i o n a l t r a d i n g mode. // The e q u i v a l e n t of E n a b l e R o t a t i o n a l T r a d i n g ( ) SetBacktestMode( b a c k t e s t R o t a t i o n a l ) ;
SetCustomBacktestProc - Define custom backtest procedure formula file Syntax: SetCustomBacktestProc( filename, enable = True ) Returns: NOTHING
Function: This function allows changing custom backtest procedure file from AFL formula level. To learn more about the custom backtester please read: •
Portfolio Backtester Interface Reference Guide in the AmiBroker User's Guide.
•
An excellent article in the AmiBroker User's Knowledge Base: http://www.amibroker.org/userkb/2008/03/16/amibroker-custom-bncktester-in terface-2/
This description of the custom backtester comes from Wayne, GP, author of the article in User's Knowledge Base. From version 4.67.0, AmiBroker provides a custom backtester interface to allow customizing the operation of the backtester's second phase which processes the trading signals. This allows a range of special situations to be achieved that aren't natively supported by the backtester. AmiBroker tends to refer to this as the Advanced Portfolio Backtester Interface, but it is widely referred to as the Custom Backtester Interface. Due to the object model used by the backtester interface, a higher level of programming knowledge is required than for simple AFL or looping. This document starts by discussing that model, so is
AFL - AmiBroker Formula Language
415
aimed at AFL programmers who are already proficient and comfortable with basic AFL use, array indexing, and looping. Parameters filename parameter instructs backtester to use external formula file as custom backtest procedure, if empty - it means use current formula enable = True (default) - enables custom backtesting procedure (the same as SetOption("UseCustomBacktestProc", True ); enable = False - disables custom proc Example: SetCustomBacktestProc( "Formulas\MyCustomBacktest.afl", True);
SetFormulaName - Set the name of the formula Syntax: SetFormulaName( string ) Retruns: NOTHING
Function: Sets the name of the formula that is displayed in the backtest result explorer. Example: SetFormulaName("My Holy Grail System");
416
Introduction to AmiBroker
SetOption - Sets options in automatic analysis settings Syntax: SetOption( field, v a l u e ) Returns: NOTHING
Function: Sets various options in automatic analysis settings. Also affects Equity() function results. field - is a string that defines which option to change. There are the following options available: •
"NoDefaultColumns" ־if set to True - exploration does not have default Ticker and Date/Time columns
•
"InitialEquity"
•
"AllowSameBarExit"
•
"ActivateStopsImmediately"
•
"AllowPositionShrinking"
•
״FuturesMode״
•
"InterestRate"
•
"MaxOpenPositions" - maximum number of simultaneously open positions (trades) in portfolio backtest/optimization
•
"WorstRankHeld" - the worst rank of symbol to be held in rotational trading mode (see EnableRotationalTrading for more details)
•
"MinShares" ־the m i n i m u m number of shares required to open the position in the backtester/optimizer. If you don't have enough f u n d s to purchase that many, trade will not be entered
•
"MinPosValue" - the m i n i m u m dollar amount required to open the position in the backtester/optimizer. If you don't have enough f u n d s trade will not be entered
•
"PriceBoundChecking" - if set to False - disables checking and adjusting buyprice/sellprice/coverprice/shortprice arrays to current symbol High-Low range.
•
CommissionMode 0 - use portfolio manager commission table 1 - percent of trade 2 - $ per trade 3 - $ per share/contract
AFL - AmiBroker Formula Language
417
CommissionAmount - amount of commission in modes 1..3 AccountMargin (in old versios it was 'MarginRequirement') ־account margin requirement (as in settings), 100 = no margin ReverseSignalForcesExit - reverse entry signal forces exit of existing trade (default = True ) UsePrevBarEquityForPosSizing ־Affects how percent of current equity position sizing is performed. False (default value) means: use current (intraday) equity to perform position sizing, True means: use previous bar closing equity to perform position sizing PortfolioReportMode - sets backtester report mode: 0 - trade list 1 - detailed log 2 - summary 3 - no output (custom only) UseCustomBacktestProc - True/False - allows turning on/off custom backtest procedure EveryBarNullCheck - allows turning on checking for Nulls in arithmetic operations on every bar in the array (by default it is off - i.e. AmiBroker checks for nulls that appear in the beginning of the array and in the end of the array and once non-null value is detected it assumes no further holes (nulls) in the middle). Turning "EveryBarNullCheck" to True allows extending these checks to each and every bar. Note however that turning it on gives huge performance penalty (arithmetic operations are performed even 4x slower when this option is on, so don't use it unless you really have to). HoldMinBars - Number - if set to value > 0 - it disables exit during user-specified number of bars even if signals/stops are generated during that period EarlyExitBars - Number if set to value > 0 - causes that special early exit (redemption) fee is charged if trade is exited during this period EarlyExitFee - defines the % (percent) value of early exit fee HoldMinDays - Number - if set to value > 0 - it disables exit during user-specified number of calendar days (not bars) even if signals/stops are generated during that period
418
Introduction to AmiBroker
•
EarlyExitDays ־Number if set to value > 0 - causes that special early exit (redemption) fee to be charged if trade is exited during the period specified in calendar days (not bars).
•
DisableRuinStop - if set to TRUE, built-in ruin stop is disabled.
•
Generate report - allows to suppress/force generation of backtest report. Allowable values: 0,1, or 2. By default backtest reports are generated only for portfolio backtests and for individual backtests if individual reporting is turned on in the settings. Reports are disabled for optimization. Now with the SetOption() function you can either suppress report generation for backtests or enable report generation during certain optimization steps, all from code level. SetOption("GenerateReport", 0 ); // suppress generation of report SetOption("GenerateReport", 1 ); // force generation of full report SetOption("GenerateReport", 2 ); // only one-line report is generated (in results.rlst file) viewable as single line in Report Explorer
Warning: If you change the option on *per-symbol* basis the composite results (%profit for example) will be distorted since calculations assume that the options are constant for all symbols in one backtest run. 'HoldMinBars', 'EarlyExit..." options are an exception from this rule (i.e. can be safely set on per-symbol basis) Examples: S e t O p t i o n ( " I n i t i a l E q u i t y " , 5000 ) ; SetOption("AllowPositionShrinking", S e t O p t i o n ( " M a x O p e n P o s i t i o n s " , 5 ); PositionSize = -100/5; SetPositionSize - set trade size
True
);
AFL - AmiBroker Formula Language
419
SetPositionSize - Set trade size Syntax: SetPositionSize( size, method ) Returns: ARRAY
Function: This function allows control of trade (position) size in four different ways, depending on 'method' parameter. • size (ARRAY) defines desired trade size •
method (ARRAY) defines how 'size' is interpreted spsValue (=1) - dollar value of size spsPercentOfEquity (=2) - size expressed as percent of portfolio-level equity (size must be from ..100 (for regular accounts) or .1000 for margin accounts) spsShares (=4) - size expressed in shares/contracts (size must be > 0 ) spsPercentOfPosition (=3) - size expressed as percent of currently open position (for scaling in and scaling out only) spsNoChange (=0) - don't change previously set size for given bar
Examples: / / T o l i q u i d a t e 50% o f p o s i t i o n S e t P o s i t i o n S i z e ( 50, s p s P e r c e n t O f P o s i t i o n * ( Buy == s i g S c a l e Out ) ) ;
Special value spsNoChange (=0) means don't change previously set size for given bar. This allows writing constructs like: S e t P o s i t i o n S i z e ( 100, spsShares ); // 100 shares by d e f a u l t / / f o r s c a l e - o u t use 50% o f c u r r e n t p o s i t i o n s i z e S e t P o s i t i o n S i z e ( 50, I I f ( B u y = = s i g S c a l e 0 u t , s p s P e r c e n t O f P o s i t i o n , spsNoChange));
420
Introduction to AmiBroker
SetTradeDelays - Control trade delays applied by the backtester Syntax: SetTradeDelays( buydelay, selldelay, shortdelay, coverdelay ) Returns: NOTHING Function: Sets trade delays applied by the backtester. This function allows you to override trade delays from the "Settings" page. Example: SetTradeDelays( 1,
1, 1 )
ValueWhen - Get value of the array when some condition was met Syntax: ValueWhen ( EXPRESSION, ARRAY, n = 1) Returns: ARRAY
Function: Returns the value of the ARRAY when the EXPRESSION was true on the n -th most recent occurrence. Note: this function also allows 0 and negative values for n, which enables referencing the future Example: dd = ValueWhen( Cross( C l o s e , MA(C10se,5)),MACD(),1 p r i n t f ( " d d = " + NumToStr(dd));
);
AFL - AmiBroker Formula Language
421
LOW-LEVEL GRAPHICS
These functions control low-level graphics. To learn more about lowlevel graphic functions please read the tutorial, "Using low-level graphics" in the AmiBroker User's Guide. This introduction to low-level graphics is taken from that tutorial. Completely new low-level graphic AFL interface allows complete flexibility in creating any kind of user-defined display. The interface closely mimics Windows GDI API, with the same names for most functions for easier use for GDI-experienced programmers. The only differences are: 1. compared to Windows GDI all functions are prefixed with 'Gfx' 2. pen/brush/font creation/selection is simplified to make it easier to use and you don't need to care about deletion of GDI objects 3. three overlay modes are available so you can mix low-level graphics with regular Plot() statements (mode = 0 (default) - overlay low-level graphic on top of charts, mode = 1 - overlay charts on top of low-level graphic, mode =2 draw only low-level graphic (no regular charts/grid/titles/etc)) All functions use pixels as co-ordinates (when used on screen). For printouts and metafiles pixels are mapped to logical units to match the higher resolution of printers. Use Status("pxwidth") and Status("pxheight") to find pixel dimensions of the drawing surface. The available low-level gfx functions are described on the pages that follow.
422
Introduction to AmiBroker
GfxArc - Draw an arc Syntax: GfxArc( xl, yl, x2, y2, x3, y3, x4, y4 ) Returns: NOTHING
Function: Draws an elliptical arc. The arc drawn by using the function is a segment of the ellipse defined by the specified bounding rectangle. The actual starting point of the arc is the point at which a ray drawn from the center of the bounding rectangle through the specified starting point intersects the ellipse. The actual ending point of the arc is the point at which a ray drawn from the center of the bounding rectangle through the specified ending point intersects the ellipse. The arc is drawn in a counterclockwise direction. Parameters • xl - x-coordinate of the upper left corner of the bounding rectangle •
yl - y-coordinate of the upper left corner of the bounding rectangle
•
x2 - x-coordinate of the lower right corner of the bounding rectangle
•
y2 - y-coordinate of the lower right corner of the bounding rectangle
•
x3 - x-coordinate of the arc's starting point.
•
y3 - y-coordinate of the arc's starting point.
•
x4 - x-coordinate of the arc's ending point.
•
y4 - y-coordinate of the arc's ending point.
Example: GfxSelectPen( colorRed ); GfxArc(100,0,200,100,150,0,200,50);
AFL - AmiBroker Formula Language
423
GfxChord - Draw a chord Syntax: GfxChord( xl, yl, x2, y2, x3, y3, x4, y4 ) Returns: NOTHING
Function: Draws a chord (a closed figure bounded by the intersection of an ellipse and a line segment). The (xl, yl) and (x2, y2) parameters specify the upper-left and lower-right corners, respectively, of a rectangle bounding the ellipse that is part of the chord. The (x3, y3) and (x4, y4) parameters specify the endpoints of a line that intersects the ellipse. The chord is drawn by using the selected pen and filled by using the selected brush. Parameters •
xl - x-coordinate of the upper left corner of the bounding rectangle
•
yl - y־coordinate of the upper left corner of the bounding rectangle x2 - x-coordinate of the lower right corner of the bounding rectangle
• •
y2 - y-coordinate of the lower right corner of the bounding rectangle
•
x3 - x-coordinate of the chord's starting point.
•
y3 - y-coordinate of the chord's starting point.
•
x4 - x-coordinate of the chord's ending point.
•
y4 - y-coordinate of the chord's ending point.
Example: GfxSelectPen( colorRed ); GfxSelectSolidBrush( colorBlue ); GfxChord(100,0,200,100,150,0,200,50);
424
Introduction to AmiBroker
GfxCircle - Draw a circle Syntax: GfxCircle( x, y, radius ) Returns: NOTHING
Function: Draws a circle. The center of the circle is given by x and y parameters. The circle is drawn with the current pen, and its interior is filled with the current brush. Parameters •
x - x-coordinate of the center of the circle
•
y - y-coordinate of the the center of the circle
•
radius ־radius of the circle
This function is essentially the same as GfxEllipse( x ־radius, y - radius, x + radius, y + radius ); Example: GfxCircle(
100,
100, 5 0 ) ;
GfxDrawText - Draw a text (clipped to rectangle) Syntax: GfxDrawText( "text", left, top, right, bottom, format = 0 ) Returns: NOTHING
Function: Formats and draws text in the given rectangle. It formats text by expanding tabs into appropriate spaces, aligning text to the left, right, or center of the given rectangle, and breaking text into lines that fit within the given rectangle. The type of formatting is specified by format argument. When format is not specified the text is aligned to the top/left corner. Parameters: •
"text" - string to be drawn
•
left - x-coordinate of upper left corner of the clipping rectangle
•
top - y-coordinate of upper left corner of the clipping rectangle
•
right - x-coordinate of lower right corner of the clipping rectangle
AFL - AmiBroker Formula Language
425
•
bottom - y-coordinate of lower right corner of the clipping rectangle
•
format - specifies the method of formatting the text. It can be any combination of the following values (combine using the bitwise OR operator): • DT_BOTTOM = 8 - Specifies bottom-justified text. This value must be combined with DT_S1NGLELINE. DTCENTER = 1 - Centers text horizontally. • DT_END_ELLIPSIS = 32768 or DT_PATH_ELLIPSIS = 16384 - Replaces part of the given string with ellipses, if necessary, so that the result fits in the specified rectangle. You can specify DT_END_ELLIPSIS to replace characters at the end of the string, or DT_PATH_ELLIPSIS to replace characters in the middle of the string. If the string contains backslash (\) characters, DT_PATH_ELLIPSIS preserves as much as possible of the text after the last backslash. • DT_EXPANDTABS = 64 ־Expands tab characters. The default number of characters per tab is eight. • DT_LEFT = 0 - Aligns text flush-left. D T N O C L I P = 256 - Draws without clipping. DrawText is somewhat faster when DT_NOCLIP is used. • DT NOPREFIX = 2048 - Turns off processing of prefix characters. Normally, DrawText interprets the ampersand (&) mnemonic-prefix character as a directive to underscore the character that follows, and the two-ampersand (&&) mnemonic-prefix characters as a directive to print a single ampersand. By specifying DT_NOPREFIX, this processing is turned off. • DT_RIGHT = 2 - Aligns text flush-right. DT_SINGLELINE = 32 - Specifies single line only. Carriage returns and linefeeds do not break the line. DT_TOP = 0 - Specifies top-justified text (single line only). DT VCENTER = 4- Specifies vertically centered text (single line only). • DT_WORDBREAK = 16 - Specifies word-breaking. Lines are automatically broken between words if a word would extend past the edge of the rectangle specified by lpRect. A carriage return-linefeed sequence will also break the line.
426
Introduction to AmiBroker
Note: DT_ constants come from Windows API and are provided here for reference only. They are not defined in AmiBroker therefore you should use numerical values instead. EXAMPLE / / f o r m a t t e d t e x t o u t p u t sample v i a l o w - l e v e l g f x f u n c t i o n s C e l l H e i g h t = 20; C e l l W i d t h = 100; G f x S e l e c t F o n t ( "Tahoma",
CellHeight/2
function PrintlnCell( string, {
);
row, Col )
GfxDrawText( s t r i n g , Col * C e l l W i d t h , row * C e l l H e i g h t , (Col + 1 ) * C e l l W i d t h , (row + 1 ) * CCeel l H l Heei g i ghht t, , 00 ); } PrintlnCell( PrintlnCell( PrintlnCell( PrintlnCell( PrintlnCell(
"Open", 0, 0 ); " H i g h " , 0, 1 ); "Low", 0, 2 ); " C l o s e " , 0, 3 ); "Volume", 0, 4 );
GfxSelectPen( c o l o r B l u e ) ; f o r ( i = 1; i < 10 && i < BarCount; i + + ) { PrintlnCell( PrintlnCell( PrintlnCell( PrintlnCell( PrintlnCell( GfxMoveTo( 0, GfxLineTo( 5 }
StrFormat( "%g" StrFormat( "%g" StrFormat( "%g" StrFormat( "%g " StrFormat( "%g" i * CellHeight * CellWidth, i
0[ i ] ). i. H[ i ] ). i! L[ i I ) > i ־ C[ i ] ) > i ־ V[ i ] ). i> ); * CellHeight
GfxMoveTo( 0, i * C e l l H e i g h t ); GfxLineTo( 5 * C e l l W i d t h , i * C e l l H e i g h t
0 1 2 3 4
); ); ); ); );
); );
f o r ( Col = 1; Col < 6; C01++ ) { GfxMoveTo( Col * C e l l W i d t h , 0 ) ; GfxLineTo( Col * C e l l W i d t h , 10 * C e l l H e i g h t ); }
AFL - AmiBroker Formula Language
427
GfxEllipse - Draw an ellipse Syntax: GfxEllipse( xl, yl, x2, y2 ) Returns: NOTHING
Function: Draws an ellipse. The center of the ellipse is the center of the bounding rectangle specified by xl, yl, x2, and y2. The ellipse is drawn with the current pen, and its interior is filled with the current brush. Parameters • •
xl - x-coordinate of the upper left corner of the bounding rectangle yl - y-coordinate of the upper left corner of the bounding rectangle
•
x2 - x-coordinate of the lower right corner of the bounding rectangle
•
y2 - y-coordinate of the lower right corner of the bounding rectangle
Example: GfxEllipse( 10, 10, 200,100 );
428
Introduction to AmiBroker
GfxGradientRect - Draw a rectangle with gradient fill Syntax: GfxGradientRect( xl, yl, x2, y2, fromcolor, tocolor ) Returns: NOTHING
Function: Draws a rectangle. The interior of the rectangle is filled using gradient color. Parameters •
xl - x-coordinate of the upper left corner of the rectangle
•
yl - y-coordinate of the upper left corner of the rectangle
•
x2 - x-coordinate of the lower right corner of the rectangle
•
y2 - y-coordinate of the lower right corner of the rectangle
•
fromcolor - the 'upper' color of the gradient fill
•
tocolor - the 'lower' color of the gradient fill
The rectangle extends up to, but does not include, the right and bottom coordinates. This means that the height of the rectangle is y2 - yl and the width of the rectangle is x2 - xl. Both the width and the height of a rectangle must be greater than 2 and less than 32767. Example: GfxGradientRect( 10, 10, 100, 100, colorWhite, colorGrey50 );
GfxLineTo - Draw a line to a specified point Syntax: GfxLineTo( x, y) Returns: NOTHING
Function: Draws a line from the current position up to, but not including, the point specified by x and y. The line is drawn with the selected pen. The current position is set to x,y.
AFL - AmiBroker Formula Language
429
Parameters •
x - Specifies the x-coordinate of the end point of the line.
•
y - Specifies the y-coordinate of the end point of the line.
Example: GfxMoveTo( 0, 0 ); G f x L i n e T o ( 100, 100 );
GfxMoveTo - Move graphic cursor to new position Syntax: GfxMoveTo( x, y) Returns: NOTHING
Function: Moves the current position to the point specified by x and y. Parameters • x - Specifies the x-coordinate of the new position. •
y - Specifies the y-coordinate of the new position.
Example: GfxMoveTo( 10, 20 );
430
Introduction to AmiBroker
GfxPie - Draw a pie Syntax: GfxPie( xl, yl, x2, y2, x3, y3, x4, y4 ) Returns: NOTHING
Function: Draws a pie-shaped wedge by drawing an elliptical arc whose center and two endpoints are joined by lines. The center of the arc is the center of the bounding rectangle specified by xl, yl, x2, and y2. The starting and ending points of the arc are specified by x3, y3, x4, and y4. The arc is drawn with the selected pen, moving in a counterclockwise direction. Two additional lines are drawn from each endpoint to the arc's center. The pie-shaped area is filled with the current brush. If x3 equals x4 and y3 equals y4, the result is an ellipse with a single line from the center of the ellipse to the point (x3, y3) or (x4, y4). Parameters •
xl - x-coordinate of the upper left corner of the bounding rectangle
•
yl - y-coordinate of the upper left corner of the bounding rectangle x2 - x-coordinate of the lower right corner of the bounding rectangle
• •
y2 - y-coordinate of the lower right corner of the bounding rectangle
•
x3 - x-coordinate of the arc's starting point. This point does not have to lie exactly on the arc.
•
y3 - y-coordinate of the arc's starting point. This point does not have to lie exactly on the arc. x4 - x-coordinate of the arc's ending point. This point does not have to lie exactly on the arc.
• •
y4 - y-coordinate of the arc's ending point. This point does not have to lie exactly on the arc.
Example: GfxSelectPen( colorRed ); GfxSelectSolidBrush( colorBlue ); GfxPie(100,0,200,100,150,0,200,50);
AFL - AmiBroker Formula Language
431
GfxPolygon - Draw a polygon Syntax: GfxPolygon( xl, yl, x2, y2, ...) Returns: NOTHING
Function: Draws a polygon consisting of two or more points (vertices) connected by lines, using the current pen. The system closes the polygon automatically, if necessary, by drawing a line from the last vertex to the first. This function takes a variable number of arguments and accepts up to 12 points (24 arguments = 12 co-ordinate pairs). The number of arguments must be even as each pair represents (x,y) co-ordinates of the vertex. The polygon is filled with the current brush and the outline is painted with the current pen. Parameters: •
xl - x co-ordinate of first point
•
yl - y co-ordinate of first point
•
x2 - x co-ordinate of second point
•
y2 - y co-ordinate of second point
•
xl2 - x co-ordinate of 12th point
•
yl2 - y co-ordinate of 12th point
Example: GfxSelectPen( colonGreen, 2 ); GfxSelectSolidBrush( colorYellow ); GfxPolygon(250,200,200,200,250,0,200,50);
432
Introduction to AmiBroker
GfxPolyline - Draw a polyline Syntax: GfxPolyline( xl, yl, x2, y2, ...) Returns: NOTHING
Function: Draws a set of line segments connecting the points specified by arguments (xl,yl), (x2,y2), ... The lines are drawn from the first point through subsequent points using the current pen. Unlike the GfxLineTo function, the GfxPolyline function neither uses nor updates the current position. This function takes a variable number of arguments and accepts up to 12 points (24 arguments = 12 co-ordinate pairs). The number of arguments must be even as each pair represents (x,y) co-ordinates of the point. Parameters: •
xl - x co-ordinate of first point
•
yl - y co-ordinate of first point
•
x2 - x co-ordinate of second point
•
y2 - y co-ordinate of second point
•
•
xl2 - x co-ordinate of 12th point
•
yl2 - y co-ordinate of 12th point
Example: GfxSelectPen( c o l o r G r e e n , 2 ); GfxPolyline(250,200,200,200,250,0,200,50);
AFL - AmiBroker Formula Language
433
GfxRectangle - Draw a rectangle Syntax: GfxRectangle( xl, yl, x2, y2 ) Returns: NOTHING
Function: Draws a rectangle using the current pen. The interior of the rectangle is filled using the current brush. Parameters •
xl - x-coordinate of the upper left corner of the rectangle
•
yl - y-coordinate of the upper left corner of the rectangle
•
x2 - x-coordinate of the lower right corner of the rectangle
•
y2 - y-coordinate of the lower right corner of the rectangle
The rectangle extends up to, but does not include, the right and bottom coordinates. This means that the height of the rectangle is y2 - yl and the width of the rectangle is x2 - xl. Both the width and the height of a rectangle must be greater than 2 and less than 32767. Example: GfxRectangle( 10, 10, 30, 30 )
434
Introduction to AmiBroker
GfxRoundRect - Draw a rectangle with rounded corners Syntax: GfxRoundRect( xl, yl, x2, y2, x3, y3 ) Returns: NOTHING
Function: Draws a rectangle with rounded corners using the current pen. The interior of the rectangle is filled using the current brush. Parameters •
xl - x-coordinate of the upper left corner of the rectangle
•
yl - y-coordinate of the upper left corner of the rectangle
•
x2 - x-coordinate of the lower right corner of the rectangle
•
y2 - y-coordinate of the lower right corner of the rectangle
•
x3 - the width of the ellipse used to draw the rounded corners
•
y3 - the height of the ellipse used to draw the rounded corners
The rectangle extends up to, but does not include, the right and bottom coordinates. This means that the height of the rectangle is y2 - yl and the width of the rectangle is x2 - xl. Both the width and the height of a rectangle must be greater than 2 and less than 32767. Example: GfxRoundRect( 10,10, 100,100, 15,15 );
AFL - AmiBroker Formula Language
435
GfxSelectFont - Create / select graphic font Syntax: GfxSelectFont( "facename", pointsize, weight = fontNormal, italic = False, underline = False, orientation = 0 ) Returns: NOTHING
Function: Initializes a font with the specified characteristics. Then selects that font as current for subsequent drawing operations. Parameters: •
"facename" - specifies the typeface name of the font
• •
pointsize - specifies point size of the font (fractional numbers are allowed), for example 11.5 gives 11.5 point font. weight - specifies the font weight (in inked pixels per 1000). Typical values are: 300 - light, 400 - normal, 700 - bold, 800 - ultrabold
•
italic - specifies whether the font is italic
•
underline - specifies whether the font is underlined
•
orientation - specifies the angle (in 0.1-degree units) between the baseline of a character and the x-axis. The angle is measured counterclockwise from the x-axis.
Example: G f x S e l e c t F o n t ( " T a h o m a " , 20, 700 ) ; GfxSetBkMode(1); GfxSetTextColor(colorBrown); GfxTextOut("Testing graphic c a p a b i l i t e s " ,
20,
28
);
436
Introduction to AmiBroker
GfxSelectPen - Create / select graphic pen Syntax: GfxSelectPen( color, width = 1, penstyle = penSolid ) Returns: NOTHING
Function: GfxSelectPen initializes (if not already initialized) a pen with the specified style, width, and color. Then selects the pen as current for subsequent drawing operations. Parameters: •
color - specifies color for the pen
•
penstyle - specifies the style for the pen. Solid=0, Dash=l, Dot=2, Null=5 (invisible pen). Lines of width > 1 can only use solid style. For a list of other possible values, see the Microsoft docs on CreatePen Windows API function.
•
width - specifies the width of the pen. If this value is 0, the width in device units is always 1 pixel, regardless of the mapping mode (this is useful for drawing hairline lines on printer outputs).
More info on pens in Windows GDI: http://msdn2.microsoft.com/enus/library/ms535467 Example: GfxSelectPen( c o l o r G r e e n , 2 ); GfxSelectSolidBrush( colorYellow ); GfxPolygon(250,200,200,200,250,0,200,50);
AFL - AmiBroker Formula Language
437
GfxSelectSolidBrush ־Create / select graphic brush Syntax: GfxSelectSolidBrush( color) Returns: NOTHING
Function: GfxSelectSolidBrush initializes a brush with a specified solid color. Then selects the brush as current for subsequent drawing operations. Parameters: •
color - specifies color for the brush
Example: G f x S e l e c t P e r i ( c o l o r G r e e n , 2 ); GfxSelectSolidBrush( colorYellow ); GfxPolygon(250,200,200,200,250,0,200,50);
GfxSetBkColor - Set graphic background color Syntax: GfxSetBkColor( color) Returns: NOTHING
Function: Sets the current background color to the specified color. If the background mode is OPAQUE (see GfxSetBkMode), the system uses the background color to fill the gaps in styled lines, the gaps between hatched lines in brushes, and the background in character cells. Parameters: •
color - specifies the new background color
Example: GfxSetBkColor( ColorRGB( 10, 20, 30 ));
438
Introduction to AmiBroker
GfxSetBkMode - Set graphic background mode Syntax: GfxSetBkMode( bkmode ) Returns: NOTHING
Function: Sets the background mode. The background mode defines whether the system removes existing background colors on the drawing surface before drawing text, hatched brushes, or any pen style that is not a solid line. Parameters: • bkmode - Specifies the mode to be set. This parameter can be either of the following values: OPAQUE = 2 - Background is filled with the current background color before the text, hatched brush, or pen is drawn. This is the default background mode. TRANSPARENT = 1 - Background is not changed before drawing Example: GfxSetBkMode( 1 ); // set transparent mode
AFL - AmiBroker Formula Language
439
GfxSetOverlayMode - Set low4evel graphic overlay mode Syntax: GfxSetOverlayMode( mode = 0 ) Returns: NOTHING
Function: Sets overlay mode for low-level graphics. Parameters: •
mode - desired overlay mode. Possible values are: 0 - (default) low-level graphic is overlaid on top of charts 1 - charts are overlaid on top of low-level graphics 2 - only low-level graphics are displayed (no charts, no grids, etc)
Example: GfxSetOverlayMode( 2 ); // don't display charts nor grids
GfxSetPixel - Set pixel at specified position to specified color Syntax: GfxSetPixel( x, y, color ) Returns: NOTHING
Function: Sets the pixel at the specified x, y coordinates to the specified color. The point must be in the visible part drawing surface (otherwise it won't be painted). Parameters • x - Specifies the x-coordinate of the point. • y - Specifies the y-coordinate of the point. • color - specifies the color to be used to paint the point Example: GfxSetPixel( 20, 20 );
440
Introduction to AmiBroker
GfxSetTextAlign - Set text alignment Syntax: GfxSetTextAlign( align) Returns: NOTHING
Function: Sets the text-alignment flags. The GfxTextOut function uses these flags when positioning a string of text on a display or device. The flags specify the relationship between a specific point and a rectangle that bounds the text. The coordinates of this point are passed as parameters to the TextOut member function. The rectangle that bounds the text is formed by the adjacent character cells in the text string. Parameters: •
align - combination (binary-OR) of one or more the following flags: X-direction alignment: TA_CENTER = 6 - Aligns the point with the horizontal center of the bounding rectangle. TA_LEFT = 0 - Aligns the point with the left side of the bounding rectangle. This is the default setting. TAJRIGHT = 2 - Aligns the point with the right side of the bounding rectangle. Y-direction alignment TAJBASELINE = 24 - Aligns the point with the base line of the chosen font. TA_BOTTOM = 8 - Aligns the point with the bottom of the bounding rectangle. TA_TOP = 0 - Aligns the point with the top of the bounding rectangle. This is the default setting, flags that determine whether the current position is updated when text is written: TA_NOUPDATECP = 0 - Does not update the current position after each call to a text-output function. This is the default setting. TA_UPDATECP = 1 ־Updates the current x-position after each call to a text-output function. The new position is at the right side of the bounding rectangle for the text. When
AFL - AmiBroker Formula Language
441
this flag is set, the coordinates specified in calls to the GfxTextOut member function are ignored Note: TA_ constants come from Windows API, they are given for reference only. They are not predefined in AmiBroker, so you need to use numerical values. Example: GfxSetTextAlign( 6 I 24 ); // center and baseline alignment
GfxSetTextColor - Set graphic text color Syntax: GfxSetTextColor( color) Returns: NOTHING
Function: Sets the text color to the specified color. AmiBroker will use this text color when writing text to this window using GfxTextOut or GfxDrawText. The background color for a character is specified by the GfxSetBkColor and GfxSetBkMode member functions. Parameters: •
color - Specifies the color of the text
Example: GfxSetTextColor( colorRed ); G f x S e t T e x t C o l o r ( ColorRGB( 100,
200,
100 )
);
442
Introduction to AmiBroker
GfxTextOut - Writes text at the specified location Syntax: GfxTextOut( ״text" x, y ) Returns: NOTHING
Function: Writes a character string at the specified location using the currently selected font. Parameters: •
"text" - Specifies the character string to be drawn
•
x ־Specifies the x-coordinate of the starting point of the text
•
y - Specifies the y-coordinate of the starting point of the text
Character origins are at the upper-left corner of the character cell. By default, the current position is not used or updated by the function. The font used can be set using GfxSelectFont() function. Text color can be set using GfxSetTextColor() function. If a formula needs to update the current position when it calls GfxTextOut, the formula can call the GfxSetTextAlign function with flags set to 1 (TAJJPDATECP Windows flag). When this flag is set, GfxTextOut function ignores the x and y parameters on subsequent calls to GfxTextOut, using the current position instead. The output of this function is not clipped. If you want clip text to user-defined rectangle, use GfxDrawText() function instead. Example: G f x S e l e c t F o n t ( " T i m e s New Roman", 16, 700, True ); G f x T e x t O u t ( " P e r c e n t of s h a r e s h e l d b y : " , 10 , 10 );
AFL - AmiBroker Formula Language MISCELLANEOUS
443
FUNCTIONS
#include - Preprocessor include command Syntax: #include Returns: NOTHING
Function: Includes external AFL files into your formula. Notes: • include statement needs a single backslashes in the path (this is different than normal AFL string parsing). • Using #include command may slow down formula execution even considering the fact that AmiBroker tries to include only once and cache pre-processed text. •
No error message is given if #include fails and this code is experimental.
•
Nesting #include commands is supported.
•
By default, files *included are cached by AmiBroker. To turn off caching use #pragma nocache before any !include statements.
•
include accepts alternative way of specifying file names to include: #include (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 is much shorter to write includes and you can move include folder now without changing all AFL codes using !includes.
444
Introduction to AmiBroker For example, if you have set the standard include path to "C:\ AFL\MyIncludes" and write in your formula: #include then AmiBroker will look for the C:\AFL\MyIncludes\common.afl file.
•
include reports file(s) not found in regular error message box.
Example: #include "C:\Program Files\AmiBroker\AFL\common.afl"
#include_once - Preprocessor include (once) command 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 a 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"
#pragma - Sets AFL pre-processor option Syntax: #pragma optionname Returns: NOTHING
Function: Sets various AFL pre-processor options. Pre-processor is a
AFL - AmiBroker Formula Language
445
part of AFL engine that processes formulas before they are executed. Currently the only task of the pre-processor is to include external files via #include command. Currently the only option available via #pragma is nocache. #pragma nocache causes #included files to not be 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 one single space. Disabling caching may slow down execution of the formula, espedaily in indicators. Example: #pragma nocache #include " m y f i l e . a f l "
ClipboardGet - Retrieves current contents of Windows clipboard Syntax: ClipboardGet() Returns: STRING
Function: Retrieves the current contents of Windows clipboard Example: "Contents of the Windows clipboard" + ClipboardGet();
446
Introduction to AmiBroker
ClipboardSet - Copies the text to the Windows clipboard Syntax: ClipboardSet( ״Text;) ״ Returns: NUMBER
Function: Copies the "text" to the Windows clipboard. Returns True (1) on success and 0 on failure Example: / / t h i s can b e used t o p u t d y n a m i c a l l y - c o n s t r u c t e d t e x t s i n t o // clipboard C l i p b o a r d S e t ( "The p r i c e of " + F u l l N a m e ( ) + " is " + Close );
ColorHSB - Specify color using Hue-Saturation-Brightness Syntax: ColorHSB( hue, saturation, brightness ) Returns: NUMBER
Function: The function allows specification of color out of 16 million color (24 bit) palette using Hue, Saturation and Brightness parameters. The return value is a number that can be used in Plot, PlotOHLC, PlotForeign, AddColumn, AddTextColumn functions to specify chart or column color. 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 360 degrees hue in HSV color wheel. When you modify hue from 0 to 255 you will see consecutive rain-
AFL - AmiBroker Formula Language
447
bow 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 Examples: / / 3 - d m u l t i c o l o r m u l t i p l e moving average c l o u d c h a r t s i d e = 1; i n c r e m e n t = P a r a m ( " I n c r e m e n t " , 2 , 1, 10, 1 ); f o r ( i = 10; i < 80; i = i + i n c r e m e n t ) { up = MA( C, i ) ; down = MA( C, i + i n c r e m e n t ); i f ( ParamToggle("3D e f f e c t ? " , " N o | Y e s " ) ) s i d e = I I f ( u p < = d o w n AND Ref( up<=down, 1
),
1, 0 . 6 );
PlotOHLC( u p , u p , d o w n , d o w n , " M A " + i , ColorHSB( 3 * ( i 1 0 ) ־, P a r a m ( " S a t u r a t i o n " , 128, 0 , 255 ) , s i d e * P a r a m ( " B r i g h t n e s s " , 255, 0, 255 ) ), s t y l e C l o u d | styleNoLabel ); }
//Color-parade exploration Filter=1; f o r ( i = 0; i < 256; i = i + 16 ) AddColumn( C , " C " , 1 . 2 , c o l o r D e f a u l t , ColorHSB( ( B a r l n d e x ( ) + i ) % 256, 2 5 5 - i , 255 )
);
ColorRGB - specify color using Red-Green-Blue components Syntax: ColorRGB( red, green, blue ) Returns: NUMBER
Function: The function specifies color out of 16 million color (24 bit) palette using Red, Green, Blue components. The return value is a number that can be used in Plot, PlotOHLC, PlotForeign, AddColumn, AddTextColumn functions to specify chart or column color.
448
Introduction to AmiBroker
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: P l o t ( MA(C,10), P l o t ( MA(C,20), P l o t ( MA(C,30),
" L i g h t Red", ColorRGB( 255, 128, 128 ) ); " L i g h t G r e e n " , ColorRGB( 128, 255, 128 ) ); " L i g h t B l u e " , ColorRGB( 128, 128, 255 ) );
CreateObject - create COM object 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 every time the formula is executed (the object is released automatically at the end of the formula - no explicit freeing is necessary) Example: myobj = C r e a t e O b j e c t ( " M y O w n A c t i v e X . C l a s s l " ) ; m y o b j . M e t h o d ( 1, 2, C l o s e ); // c a l l t h e method of myobj COM obj ect
CreateStaticObject - create static COM object Syntax: CreateStaticObject() Returns: OBJECT
AFL - AmiBroker Formula Language
449
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 later 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 = C r e a t e S t a t i c O b j e c t ( " M y O w n A c t i v e X . C l a s s l " ) ; m y o b j . M e t h o d ( 1 , 2 , C l o s e ) ; / / c a l l t h e method o f myobj object
COM
EnableScript - Enable scripting engine Syntax: EnableScript( "enginename" ) Returns: NOTHING
Function: Enables AFL scripting host, enginename specifies which scripting language will be used. Allowable values: "jscript", "vbscript". Example: EnableScript( " j s c r i p t " ); EnableScript("vbscript");
EnableTextOutput - Enables/disables text output in the Chart Commentary window Syntax: EnableTextOutput( enable) Returns: NOTHING
Function: Enable or disable text output in the guru chart commentary window
450
Introduction to AmiBroker
Example: EnableTextOutput(False); v a r i a b l e = " t e x t " ; / / t h i s w o n ' t b e w r i t t e n t o commentary w i n dow EnableTextOutput(True);
GetExtraData - Get extra data from external data source Syntax: GetExtraData() Returns: NUMBER ARRAY STRING
Function: Retrieves data-source specific data. Currently only Quotes Plus and TC2000 plug-isn support this function. The list of fields available via QP2 plug-in: •
"AnnDividend״
•
"Shares"
•
"SharesFloat"
•
"IssueType" (string)
•
"SharesOut"
•
"SharesShort"
•
"TTMsales"
•
"Beta"
•
"TTMEps"
•
"HiPERange"
•
"LoPERange"
•
"PEG"
•
"InstHolds"
•
"LTDebtToEq"
•
"CashFlowPerShare"
•
"ROE"
•
"TTMSales"
•
"YrlEPSGrowth"
AFL - AmiBroker Formula Language
451
•
"Yr5EPSGrowth"
•
"YrlProjEPSGrowth"
•
" Yr2Proj EPSGrowth"
•
"Yr3to5ProjEPSGrowth"
•
"BookValuePerShare"
•
"Briefing( ״string)
•
"QRS" (array)
•
"HasOptions"
•
"EPSRank" (array)
•
"Sales" (array)
•
"EPS" (array)
• •
"LastMainDate" - (number) date of last update of given symbol in YYYYMMDD format "Exchange" ( ־string) - exchange code
•
"ExchangeSub" - (string) exchange sub-code
•
"Flags" - (string)
•
"MarginFlag" - (string)
•
"CUSIP ״- (string)
•
"SIC" - (string)
•
"IssueStatus" - (string) - with default settings all symbols should have issue status = 0 other possible values: 0 = actively trading; 1, P = trading on a when issued basis, 5, 6, 7, A, B, C, D, E, M = not trading 4, N = new symbol, G, K, X, R, Z = changes to symbol, cusip, name, etc.
The list of fields available via TC2000 plug-in: •
"BOP" - balance of power indicator
•
"MoneyStream" - money stream indicator
Example: G e t E x t r a D a t a ( " b r i e f i n g " ) ; / * g i v e s b r i e f i n g t e x t (STRING) graphO = G e t E x t r a D a t a ( " Q R S " ) ; / * g i v e s Quotes Plus r e l a t i v e s t r e n g t h (ARRAY) * /
*/
452
Introduction to AmiBroker
GetPerformanceCounter - Retrieves the current value of the high-resolution performance counter Syntax: GetPerformanceCounter( bReset = False ) Returns: NUMBER
Function: GetPerformanceCounter retrieves the current value of the high-resolution performance counter. Returned value is in milliseconds. Resolution is up to 0.001 ms (1 microsecond). The value of high-resolution counter represents number of milliseconds from either system start (boot) or from the last counter reset. To reset the counter you need to call GetPerformanceCounter function with bReset parameter set to True. Note that resetting counters inside one formula does not affect counters in other formulas. Since returned values are very large (time in milliseconds since system start is usually quite large), for precise measurements of a single function or small function block execution times it is strongly recommended to reset counter at the beginning of the block so floating point resolution (7 digits) does not affect the precision of measurement. GetPerformanceCounter function can also be used in trading system automation to measure time in milliseconds between various events . Subtract values returned by GetPerformanceCounter() during two different events. Caveat: this function relies on Windows API QueryPerformanceCounter function and CPU RTDSC instruction and it may yield inaccurate results if you have a multiple-core processor and AMD's "Cool and Quiet" enabled in BIOS or other CPU clock stepping technologies enabled. If this applies to you, you may check Microsoft hotfix to this problem at: http://support.microsoft.com/?id=896256
AFL - AmiBroker Formula Language Examples: // EXAMPLE 1 // The code shows t h a t 1000 i t e r a t i o n s of s i n ( ) c a l c u l a t i o n / / t a k e s about 1.7 m i l l i s e c o n d s . / / Note t h a t c a l l t o the GetPerformanceCounter() // has overhead of about 0.015 ms (15 microseconds) G e t P e r f o r m a n c e C o u n t e r ( T r u e ) ; / / r e s e t c o u n t e r t o zero f o r ( i = 0; i < 1000; i + + ) { k = sin(
i );
} elapsed=GetPerformanceCounter(); "Time [ms] = " + e l a p s e d ; // EXAMPLE 2 / / GetPerformanceCounter f u n c t i o n // may a l s o be used to r e p o r t t i m e s i n c e system s t a r t . elapsed=GetPerformanceCounter(); S t r F o r m a t ( " T i m e s i n c e system s t a r t %.0f days, %.0f h o u r s , %.0f m i n u t e s , %.0f seconds, %.0f m i l l i s e c o n d s " , floor(elapsed/(24*60*60*1000)), f l o o r ( e l a p s e d / ( 6 0 * 6 0 * 1 0 0 0 ) ) % 24, f l o o r ( e l a p s e d / ( 6 0 * 1 0 0 0 ) ) % 60, f l o o r ( elapsed/1000 ) % 60, elapsed % 1000 );
453
454
Introduction to AmiBroker
GetRTData - Retrieves the real-time data fields Syntax: GetRTData("fieldname") Returns: NUMBER
Function: Retrieves the last (the most recent) value of the following fields reported by streaming real-time data source: •
"Ask" - current best ask price
•
"AskSize " - current ask size
•
"Bid" - current best bid price
•
"BidSize " - current bid size
•
"52WeekHigh" - 52 week high value
•
"52WeekHighDate" - 52 week high date (in datenum format)
•
"52WeekLow" - 52 week low value
•
"52WeekLowDate" - 52 week low date (in datenum format)
•
"Change" - change since yesterdays close
•
"Dividend" - last dividend value
•
"DivYield" - dividend yield
•
"EPS" - earnings per share
•
"High" - current day's high price
•
"Low" - current day's low price
•
"Open" - current day's open price
•
"Last" - last trade price
•
"Openlnt" - current open interest
•
"Prev" - previous day close
•
"TotalVolume" - total today's volume
•
"TradeVolume" - last trade volume
•
"ChangeDate" - datenum (YYYMMDD) of last data change
•
"ChangeTime" - timenum (HHMMSS) of last data change
•
"UpdateDate" - datenum (YYYMMDD) of last data update
•
"UpdateTime" - timenum (HHMMSS) of last data update
•
"Shares" - total number of shares
AFL - AmiBroker Formula Language
455
Notes: 1. This function is available only in the Professional edition. Calling it using the Standard edition will give you NULL values for all fields. 2. Works only if data source uses real-time data source (plugin). 3. Availability of data depends on underlying data source - check the real-time quote window to see if the given field is available. 4. Function result represents the current value at the time of the call or formula execution. They will be refreshed depending on chart or commentary refresh interval (which can be set in preferences). Built-in real-time quote window is refreshed much more often (at least 10 times per second).
Example: "Bid "Ask "Last "Vol
= " ++G GeettR RTTD Daattaa((" B i d " ) ; = "+GetRTData("Ask"); "+GetRTData("Ask"); = "+GetRTData("Last"); = "+GetRTData("TradeVolume");
"EPS = "+GetRTData("EPS"); "52week h i g h = "+GetRTData("52weekhigh");
456
Introduction to AmiBroker
GetRTDataForeign - Retrieves the real-time data fields (for specified symbol) Syntax: GetRTDataForeign( "fieldname" , "symbol" ) Returns: NUMBER
Function: This function is similar to GetRTData but allows specification of symbol other than currently selected. And it is much faster than SetForeign / GetRTData combo. The function retrieves the last (the most recent) value of the following fields reported by streaming real-time data source for the specified symbol: • "Ask" - current best ask price • "AskSize " - current ask size •
"Bid" - current best bid price
•
"BidSize " - current bid size
•
"52WeekHigh" - 52 week high value
•
"52WeekHighDate" - 52 week high date (in datenum format)
•
"52WeekLow" - 52 week low value
•
"52WeekLowDate" - 52 week low date (in datenum format)
•
"Change" - change since yesterdays close
•
"Dividend" - last dividend value
•
"DivYield" - dividend yield
•
"EPS" - earnings per share
•
"High" - current day's high price
•
"Low" - current day's low price
•
"Open" - current day's open price
•
"Last" - last trade price
•
"Openlnt" - current open interest
•
"Prev" - previous day close
•
"TotalVolume" - total today's volume
•
"TradeVolume" - last trade volume
•
"ChangeDate" - datenum (YYYMMDD) of last data change
AFL - AmiBroker Formula Language •
"ChangeTime" - timenum (HHMMSS) of last data change
•
"UpdateDate ״- datenum (YYYMMDD) of last data update
•
"UpdateTime ״- timenum (HHMMSS) of last data update
•
"Shares" - total number of shares
457
Notes: 1. This function is available only in the Professional edition. Calling it using Standard edition will give you NULL values for all fields. 2. Works only if data source uses real-time data source (plugin). 3. Availability of data depends on the underlying data source - check the real-time quote window to see if the given field is available . 4. Function result represents the current value at the time of the call or formula execution. And they will be refreshed depending on chart or commentary refresh interval (settable in preferences). Built-in real-time quote window is refreshed much more often (at least 10 times per second) Example: "Bid = "Ask = "Last = "Vol = "EPS = "52week
"+GetRTDataForeign("Bid"); "+GetRTData("Ask"); "+GetRTData("Last"); "+GetRTData("TradeV01ume"); "+GetRTDataForeign("EPS", "AAPL"); high = "+GetRTDataForeign("52weekhigh",
"MSFT");
458
Introduction to AmiBroker
GetScriptObject - Get access to script COM object Syntax: GetScriptObject() Returns: OBJECT Function: Retrieves AFL host's script object. This allows calling of functions defined in JScript/VBScript directly from AFL. Example: EnableScript("j script") <%
f u n c t i o n MyAdd(x, { return }
y)
x+y;
%>
script = GetScriptObject(); / / c a l l the f u n c t i o n defined i n J S c r i p t W r i t e V a l ( s c r i p t . M y A d d ( 7, 9 ) );
IsEmpty - Empty value check Syntax: IsEmpty( ARRAY) Returns: ARRAY
Function: Returns 1 (or 'true') when given point in array is )empty! Note: {empty} value is used internally by AFL to mark bars when the value is not available - for example for the first 20 bars the value of 20-day simple moving average is not available ({empty}) IsNull is a synonym for IsEmpty. It is preferable to use IsNull in new formulas, because of naming consistency with Null constant. Example: movagv = MA( C l o s e , 30 ); W r i t e l F ( I s E m p t y ( movavg ) , W r i t e V a l ( movavg ) );
"Moving average not a v a i l a b l e y e t " ,
AFL - AmiBroker Formula Language
459
IsFinite - Check if value is finite Syntax: IsFinite( x ) Returns: NUMBER ARRAY
Function: Returns 1 (TRUE) if its argument x is finite, that is, if -INF < x < +INF. It returns 0 (FALSE) if the argument is infinite or a NaN. x can be a number or an array Example: IsFinite( 1/0);
IsNan - Checks for NaN (not a number) Syntax: IsNan( x) Returns: NUMBER ARRAY
Function: Returns {empty} if the argument x is a NaN; if the argument is a number, it returns 0 (FALSE). A NaN is generated when the resuit of a floating-point operation cannot be represented in Institute of Electrical and Electronics Engineers (IEEE) format. Example: IsNan( 0/0);
460
Introduction to AmiBroker
IsNull - Check for Null (empty) value Syntax: IsNull( x) Returns: NUMBER ARRAY
Function: This function is a synonym of IsEmpty(). Gives True if value is equal to Null (empty) value. Example: MAvg = MA( C l o s e , 30 ); f o r (i=25; i<=35; i++) { //printf(NumToStr(MAvg[i])); p r i n t f ( W r i t e l f ( I s N u l l ( MAvg[i] ) , "Moving average NOT a v a i l a b l e y e t " , WriteVal( MAvg[i]) ) + " \ n " ) ;
}
IsTrue - True value (non-empty and non-zero) check Syntax: IsTrue( ARRAY) Returns: ARRAY
Function: Returns 1 (TRUE) when the given point is not {empty} and not zero. Example: dd = I s T r u e ( 4 > 2 ) ; p r i n t f ( NumToStr(dd)
);
AFL - AmiBroker Formula Language
461
NoteGet - Retrieves the text of the note Syntax: NoteGet( "Symbol) ״ Returns: STRING
Function: Retrieves note linked to "symbol". If symbol is "" (empty string) then current symbol is used. Example: "You have entered the following text in the notepad" + NoteGet("");
NoteSet - sets text of the note Syntax: NoteSet( "Symbol״, "Text..;) ״ Returns: NUMBER
Function: 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 be allowed to save your manually entered text. Returns True (1) on success, 0 on failure. Example: NoteSet("AMD", "Jun 15, 2004: AMD will deliver its first multi-core processors next year");
462
Introduction to AmiBroker
NZ - Null (Null/Nan/Infinity) to zero Syntax: Nz( x, valueifnull = 0 ) Returns: NUMBER ARRAY
Function: Converts Null/Nan/Infinity values to zero (or user defined value) x can be a number or an array. You can use the Nz function to return zero, or another specified value, when argument x is Null or Nan or Infinite. For example, you can use this function to convert a Null (empty) value to another value and prevent it from propagating through an expression. If the optional valueifnull argument is included, then the Nz function will return the value specified by that argument if the x argument is Null (or Nan or Infinity). Example: You can use the Nz function as an alternative to the Ilf function. Instead of: vanTemp = I l f (
IsFinite(
(H-L)/
You can write: varTemp = Nz(
(H-L)/(C-L)
);
),
(H-L)/(C-L),
0 );
AFL - AmiBroker Formula Language
463
PopupWindow ־display pop-up window Syntax: PopupWindow( bodytext, captiontext, timeout = 5, left = -1, top = -1 ); Returns: NOTHING
Function: The function creates and displays pop-up window with specified bodytext, captiontext. Parameters: •
bodytext - the string containing the text of the window body
•
caption - the string containing the text of the window caption
• •
timeout - auto-close time in seconds (default 5 seconds) left - top-left corner X co-ordinate (default = -1 -means autocenter)
•
top - top-left corner Y co-ordinate (default = -1 - means autocenter)
Example: i f ( P a r a m T r i g g e r ( " D i s p l a y Popup Window", {
"Press here"
PopupWindow("Current t i m e i s : " + N o w ( ) , " A l e r t " , 640*mtRandom(), 4 8 0 * m t R a n d o m ( ) ) ;
}
) 2,
)
464
Introduction to AmiBroker
Prefs - Retrieve preferences settings Syntax: Prefs( index) Returns: NUMBER STRING
Function: Retrieves preferences setting. Allowed index values are: •
0: FatLineChart;
•
1: MarkQuotations;
•
2: ChartVolumeType;
•
3: ShortTimeMA;
•
4: STMARange;
•
5: MidTimeMA;
•
6: MTMARange;
•
7: BollingerBands;
•
8: Pref.BBFactor;
•
9: ROC;
•
10: RSI;
•
11,12,13: MACD;
•
14: StochSlow;
•
15, 16,17: Ultimate;
•
18: VolumeType;
•
19-22: /* reserved amiga only */
•
23: AutoArrange;
•
24: LogChartScale;
•
25: MaxChartQuot;
•
26: TRIX;
•
27: LongTimeMA;
•
28: LTMARange;
•
29: VolMARange;
•
30: RelativeStrengthBase (string);
•
31: LimitSave;
•
32: LimitSaveRange;
•
33: CCI;
AFL - AmiBroker Formula Language •
34: CCIAvg;
•
35: Tooltips;
•
36: MFI;
•
37, 38: Chaikin;
•
39: DataPath (string)
•
40: DataTooltips;
•
41: LoadAllWhenSelect;
•
42: PartialLoad;
•
43: PartialLoadQty;
•
44, 45: TRIN;
•
46: STMAType;
•
47: MTMAType;
•
48: LTMAType;
•
49: ADX;
•
50, 51: ParabolicSAR;
•
52: EnableMainChartSAR;
•
53: DefaultPriceStyle;
•
54: StockTreeMode;
•
55: TickerListMode;
Example: dd = MACD( P r e f s ( 11 ), P r e f s ( 12 ) ); p r i n t f ( NumT0Str(Prefs(11)) + NumT0Str(Prefs(12)) + NumToStr(dd) );
465
466
Introduction to AmiBroker
Say - Speaks provided text Syntax Say("text") RETURNS: NOTHING
Function: Say() function speaks user-specified text (you may need to install Microsoft Speech API. The voice settings are in Windows Control Panel) Example: //
s i m p l e example
S a y ( " T e s t i n g t e x t t o speech e n g i n e " ) ; / / h e l p f u l helper functions f u n c t i o n SayOnce( t e x t ) { i f ( StaticVarGetText("lastsaidtext") { Say(
text
!= text
)
);
StaticVarSetText("lastsaidtext", text ); }
}
f u n c t i o n SayNotTooOften( t e x t , M i n p e r i o d {
)
elapsed=GetPerformanceCounter()/1000; L a s t e l a p s e d = Nz( S t a t i c V a r G e t ( " l a s t s a y t i m e " )
);
i f ( elapsed - L a s t e l a p s e d > M i n p e r i o d ) { StaticVarSet("lastsaytime",
}
}
Say(
text
elapsed
);
);
S a y 0 n c e ( " T e s t i n g "+Name() ); SayNotTooOften( "Say not more o f t e n than every 60 seconds",
60 );
AFL - AmiBroker Formula Language
467
SetBarsRequired - Set number of previous and future bars needed for script/DLL to properly execute Syntax: SetBarsRequired( backwardref = -1, forwardref = -1 ) Returns: NOTHING
Function: Set the number of previous and future bars needed for script/DLL to properly execute. If your formula is pure AFL you don't need to use this function at all, as AmiBroker automatically calculates the number of bars required for all its built-in functions. But if you are using script or a DLL you may need to use this function to make sure that your indicators are properly calculated in QuickAFL mode. Specifying -1 means no change. For example if you are using the script that calculates 100 bar moving average you may need to call SetBarsRequired( 100, 0 ); at the very beginning of your formula. Please note that in most cases it is not necessary (even if you are using script or DLL) because AmiBroker always provides at least 30 past data bars more than needed. Example: SetBarsRequired( 100000, 100000 ) // require all past and all future bars
StaticVarGet - Gets the value of static variable Syntax: StaticVarGet( "varname" ) Returns: NUMBER STRING
Function: Gets the value of static variable. Static variable - the variable has static duration (it is allocated when the program begins and deallocated when the program ends) and initializes it to Null unless another value is specified. Static variables allow sharing values between various formulas. Only NUMBER and STRING static variables are supported now (not ARRAYS).
468
Introduction to AmiBroker
StaticVarGetText - Gets the value of static variable as a string Syntax: StaticVarGetText( "varname" ) Returns: STRING
Function: Gets the value of static variable as a string. The only difference between StaticVarGet is that this function always returns a string. So if a given static variable does not exist it returns an empty string "" instead of Null. Numbers are also converted to string. Static variable - the variable has static duration (it is allocated when the program begins and deallocated when the program ends) and initializes it to Null unless another value is specified. Static variables allow sharing values between various formulas. Only NUMBER and STRING static variables are supported now (not ARRAYS). Example: myvar = S t a t i c V a r G e t T e x t ( " M y V a r i a b l e " ) ; i f ( myvar {
== ""
printf("Not
)
Set");
}
else { p r i n t f ( " V a r i a b l e Set:
" + myvar);
}
StaticVarRemove - remove static variable Syntax: StaticVarRemove( "variablename" ) Returns: NOTHING
Function: This function removes static variable and releases associated memory.
AFL - AmiBroker Formula Language
469
StaticVarSet - sets the value of static variable Syntax: StaticVarSet( "varname", value) Returns: NUMBER
Function: Sets the value of static variable. Returns 1 on success, 0 on failure. Static variable - the variable has static duration (it is allocated when the program begins and deallocated when the program ends) and initializes it to Null unless another value is specified. Static variables allow sharing values between various formulas. Only NUMBER and STRING static variables are supported now (not ARRAYS).
StaticVarSetText - Sets the value of static string variable. Syntax: StaticVarSetText( "varname״, "value" ) Returns: NUMBER
Function: Sets the value of static string variable. Returns 1 on success, 0 on failure. Static variable - the variable has static duration (it is allocated when the program begins and deallocated when the program ends) and initializes it to Null unless another value is specified. Static variables allow sharing values between various formulas. Only NUMBER and STRING static variables are supported now (not ARRAYS). Example: dd = StaticVarSetText( "varname","value" printf ( NumToStr(dd) ) ;
);
470
Introduction to AmiBroker
Status - Get run-time AFL status information Syntax: Status( "statuscode) ״ Returns: ARRAY
Function: Returns run-time status of the analysis engine. Supported status codes: • "stocknum" - gives you the ordinal number of currently analysed symbol •
"action" - gives information in what context given formula is run: 1 - Indicator, 2 - Commentary, 3 - Scan, 4 - Exploration, 5 - Backtest / Optimize
•
"rangefromdate", "rangetodate" - return current auto-analysis From-To range as DateNums
•
"rangefromtime", "rangetotime" - return current auto-analysis From-To range as DateNums "barinrange" - returns 1 when current bar is within current auto-analysis From-To range
• •
"barvisible" - (custom indicators only) returns 1 when current bar is visible in current view
•
"firstbarinrange" and "lastbarinrange". They return 1 (or True) on the first/last bar of analysis range.
•
"buydelay", "selldelay", "shortdelay", "coverdelay" - return delays set in the Settings window "firstbarintest" and "lastbarintest" - similar to "firstbarinrange" and "lastbarinrange" but they return the settings of last Backtest / Optimization and intermediate scans/ explorations do not affect them
•
•
"firstvisiblebar", "lastvisiblebar", "firstvisiblebarindex", "lastvisiblebarindex" - return bar number or bar index of first/ last visible bar. Available in indicator mode only.
•
"redrawaction" - returns 0 (zero) for regular refreshes, and 1 for refreshes triggered via RequestTimedRefresh().
•
"pxwidth" - returns pixel width of chart window pane (indicators only, low-level gfx)
AFL - AmiBroker Formula Language
471
•
"pxheight" - returns pixel height of chart window pane (indicators only, low-level gfx) (AmiBroker 4.94 or higher)
•
"axisminy" - retrieves the minimum (bottom) value of Y axis (indicators only, low-level gfx)
•
"axismaxy" - retrieves the maximum (top) value of Y axis (indicators only, low-level gfx)
•
"pxchartleft" - returns x-coordinate of top-left corner of chart area
•
"pxcharttop" - returns y-coordinate of top-left corner of chart area
•
"pxchartright" - returns x-coordinate of bottom-right corner of chart area
•
"pxchartbottom" - returns y-coordinate of bottom-right corner of chart area
•
"pxchartwidth" - returns width chart area (right-left)
•
"pxchartheight" - returns width chart area (bottom-top)
Examples: // Example 1: i f ( S t a t u s ( " r e d r a w a c t i o n " ) ==1 {
)
_TRACE("nTIMED REFRESH"+Now()); } RequestTimedRefresh(1); / / Example 2 ( l o w - l e v e l g r a p h i c o v e r l a y + p i x e l c o - o r d i n a t e conversion): _SECTION_BEGIN("GfxOverlaySampleNew"); function GetVisibleBarCount() { lvb = S t a t u s ( " l a s t v i s i b l e b a r " ) ; fvb = S t a t u s ( " f i r s t v i s i b l e b a r " ) ; r e t u r n Min( Lvb - f v b , BarCount - f v b );
} f u n c t i o n GfxConvertBarToPixelX( {
bar )
lvb = Status("lastvisiblebar"); fvb = S t a t u s ( " f i r s t v i s i b l e b a r " ) ; pxchartleft = Status("pxchartleft"); pxchartwidth = Status("pxchartwidth"); r e t u r n p x c h a r t l e f t + bar
}
* p x c h a r t w i d t h / ( Lvb - f v b + 1
);
472
Introduction to AmiBroker f u n c t i o n G f x C o n v e r t V a l u e T o P i x e l Y ( Value ) { l o c a l Miny,
Maxy,
pxchartbottom,
pxchartheight;
Miny = S t a t u s ( " a x i s m i n y " ) ; Maxy = S t a t u s ( " a x i s m a x y " ) ; pxchartbottom = Status("pxchartbottom"); pxchartheight = Status("pxchartheight"); r e t u r n pxchartbottom - f l o o r ( 0.5 + ( Value - Miny ) * p x c h a r t h e i g h t / ( Maxy - Miny ) );
} P10t(C,
"Price",
colorBlack,
styleHistogram );
GfxSetOverlayMode(O); G f x S e l e c t S o l i d B r u s h ( colorRed GfxSelectPen( colorRed ) ;
);
AllVisibleBars = GetVisibleBarCount(); fvb = S t a t u s ( " f i r s t v i s i b l e b a r " ) ; f o r ( i = 0; i < A l l V i s i b l e B a r s ; i + + ) { x = G f x C o n v e r t B a r T o P i x e l X ( i ); y = G f x C o n v e r t V a l u e T o P i x e l Y ( C[ i + f v b ] G f x R e c t a n g l e ( x - 1 , y - 1 , x + 2, y+1
);
);
} / / S e t C h a r t B k G r a d i e n t F i l l ( ColorRGB(200,200,200), ColorRGB( 255,255,255) ); _SECTION_END();
Study - Reference hand-drawn study Syntax: Study( STUDYID, CHARTID = 1 ) Returns: ARRAY
Function: Generates an array equivalent to a trendline study drawn by the user - allows detecting trendline breakouts from AFL. STUDYID is a two-character identifier of the study. Identifiers are: "UP ״- uptrend, ״DN ״- downtrend, "SU ״- support, ״RE ״- resistance, ״ST" - stop loss, however you can use any identifiers (there are no limitations except that AmiBroker accepts only 2 letter codes).
AFL - AmiBroker Formula Language
473
CHARTID - identifies the chart pane where the study was drawn - you can find out what the chart ID is for a given chart by looking in Parameters dialog, Axes & Grid, Miscellaneous: Chart ID or using GetChartID() AFL function. More information about this function is included in the Tutorial: Using Studies in AFL formulas
Example: / / t h i s example p l o t s f i l l e d a r e a between / / s u p p o r t (SU) and r e s i s t a n c e (RE) l i n e s P10t(C, " P r i c e " , c o l o r B l a c k , s t y l e C a n d l e ) ; su = S t u d y ( " S U " , G e t C h a r t I D ( ) ); re = Study("RE", GetChartID() ); PlotOHLC( r e , re, su, su, " " , c o l o r Y e l l o w , s t y l e C l o u d
);
VarGet - Gets the value of dynamic variable Syntax: VarGet( "varname" ) Returns: ARRAY NUMBER
Function: Gets the value of dynamic variable. Returns the NUMBER or ARRAY depending on the type of underlying variable. Dynamic variables are variables that are named dynamically, typically by creating a variable name from a static part and a variable part. The following example dynamically constructs the variable name from a variable prefix and a static suffix. Example: // F i r s t r u n t h e example a t VarSet // f o r ( i = 1; i < 10; i + + ) { Plot( }
VarGet(
"C"+i
),
"C"+i,
colorRed
);
474
Introduction to AmiBroker
VarGetText - gets the text value of dynamic variable Syntax: VarGetText( "varname" ) Returns: STRING
Function: Gets the text (string) value of dynamic variable. Similar to VarGet but always returns string values (if the underlying variable has different type it is converted to string) Allows, for example, appending text variable no matter if it is defined earlier or not as shown in the example below. Dynamic variables are variables that are named dynamically, typically by creating a variable name from a static part and a variable part. The following example dynamically constructs the variable name from a variable prefix and a static suffix. Example: T i t l e = VarGetText("Title") + "something"; / / above w i l l work c o r r e c t l y r e g a r d l e s s o f whenever // t i t l e was d e f i n e d e a r l i e r o r not
VarSet - sets the value of dynamic variable Syntax: VarSet( "varname", value) Returns: NUMBER
Function: Sets the value of dynamic variable. Returns 1 on success, 0 on failure. Dynamic variables are variables that are named dynamically, typically by creating a variable name from a static part and a variable part. The following example dynamically constructs the variable name from a variable prefix and a static suffix. Example: for( {
i = 1;
VarSet( }
i < 10;
"C"+i,
i++ )
Ref( C ,
-i )
);
AFL - AmiBroker Formula Language // c r e a t e s v a r i a b l e s C1, 0 2 , C3, C4 / / e q u a l t o Ref( C , - 1 ) , R e f ( C , - 2 ) , // Ref( C, 10 ) r e s p e c t i v e l y
475
C10 ...,
VarSetText - sets dynamic variable of string type Syntax: VarSetText( "varna me״, ״valuetext) ״ Returns: STRING
Function: Sets the text (string) value of dynamic variable. Similar to VarSet but allows assigning a string (text) instead of a number or an array. Dynamic variables are variables that are named dynamically, typically by creating a variable name from a static part and a variable part.
Version - Get version info Syntax: Version(minrequired = 0) Returns: NUMBER
Function: Returns the AmiBroker version number as a float ( 3.90 for example ). Additionally when you specify Version( 4.0 ) AmiBroker will issue an error message when running the formula on AB earlier than 4.0 :) Example: Version( 3.90);
476
Introduction to AmiBroker
TRACE - Print text to system debug viewer Syntax: _TRACE("string") Returns: NOTHING
Function: Write debug messages from AFL code to system debug viewer, (it calls internally OutputDebugString Win API function). To view debug messages you have to run DebugView freeware program from http://www.sysinternals.com/Utilities/DebugView.html Example: _TRACE("This i s _TRACE("This i s _TRACE("This i s
a test"); s e l e c t e d v a l u e o f c l o s e : " + Close ) ; f i r s t element o f c l o s e a r r a y : " + C l o s e [
0 ]
);
Chapter 9
Analysis
477
478
Introduction to AmiBroker
The Analysis pull-down menu gives access to the major tools for writing, testing, and validating trading systems; and for monitoring them for trading signals. Analysis Quick Review...
!
m A
Automatic Analysis,., Commentary.,, Eormula Editor... AFL Code Wizard
QUICK REVIEW
The Quick Review gives quick access to lists of daily price quotations and period-over-period price changes. L Quick Review Review V P
; Quotes (alphabetically)
Date;
|
Price AA AAPL ABT AEP AES AIG ALL AMGN AVP
32.13 169 53 57 43 39.04 15.26 21 49 45.13 62 85 42.83 39.68 65.56 31.14 67 76 fin n i
AXP BA BAC BAX RHI
- I
8/29/2008
% Oi (18% -2.4% -2.2% -21% -1.5% -0.1% -1.0% -1.9% -1 6% -1.8% -1.2% -0.9% -1.1% A"/.
High
Low
32 50 173.50 5882 40.03 15.65 21.67 45 76 6416 43.72
32 01 169 04 57 43 39.04 15 23 21 00 45.02 62 83 42.74
40.14 66 43 31 48 68 86 fit fi9
39.39 6510 30.72 67 74 7a fifi
־i Show
Volume 5762.200 21.405.300 3,975.800 1,541.600 2.633,600 26,197,800 3.482,900 6.727.400 2.344,300 9.396,000 3,912,900 40.831,700 2,403.800 1 ?no cnn
The Date menu opens a calendar tool that lets you select the report date - the date you want as the base date of the report. L Quick Review Review
type
Monthly returns 8/29/2008
•
immediately
Sun Man T u e W e d Thu
Fn
TGT
CI
AVP TvVX IP MS HD UNH CMCSA MRK Wr׳ COV EMC MFP
Sat 2honge
Ticker 11
12
13
14
15
17
18
19
20
21
2;
24
25
26
Todoy 24 33 27.53
19.18
32.41 5080 49.58 14.03 ?R_?5
27
28 E I
9/5/2008 2712 30.45 21 18 3567 55 49 54 07 15 28
16.0754 1196% 14 DO*/. 12.35% 12.33% 11 8 6 % 11.47%
10 61%
10 43% 10.06% 9.23% 9.06% 8 91%
Analysis
479
Clicking the Filter button opens the Filter settings dialog. This allows you to specify the group of symbols that will be processed. There are two tabs, Include and Exclude, and they have the same controls. Using the pull-down menus for any of the categories, you can include whatever you want the report to show, then exclude whatever portion of those included that you do not want. This example shows including the watchlist containing the members of the S&P 100 index. Filter settings Include
!
Exclude
Market: Group: Sector: Industry:
::
׳י
t ן
י
1
Watch list:
1spioo
Favourites:
•
Indexes:
ם
m
_ 1c
f
c
» 1־
The Review type menu lets you select what type of report it will calculate. . Quick Review type:
Quotes (alphabetically)
Q u o t e s (alphabetically) Daily returns Weekly returns 71 Show Monthly returns - יimmediately Quarterly returns Yearly returns Ticker Price/Earnings comparision AA Price/Book value comparision AAPL 169 53 -2.4% 173.50 ABT 57.43 -22% 58.82 AEP 39.04 -2.1% 40 03 AES 15.26 -1 5% 15.65 AiG 21.49 -0.1% 21.67 ALL 45.13 -1 0% 45.76 AMGN 6285 -1 9% 64.16 AVP ־1 6% 42.83 43.72 AXP 38.68 -1 8% 4014 BA 65.56 -1 2% 66 43 31 14 BAC -09% 31 48 BAX 67.76 -11% 68 88 RHI fin 1ח HI R?
169 04 57.43 39 04 15.23 21.00 45 02 62.83 42 74 39.39 6510 30 72 67 74 7Q OR
21,405,300 3.975.800 1.541,600 2.633,600 26.197,800 3,482,900 6.727,400 2,344,300 9.396.000 3.912,900 40,831.700 2,403,800 ל9RQ Cfin
.'..,:.י
Quotes (Alphabetically) lists the closing price, day-over-day price change, high, low, and volume. The first image in this section, page 252, shows the Quotes report for stocks in the S&P 100. The next options are: •
Daily returns
•
Weekly returns
•
Monthly returns
480
Introduction to AmiBroker
•
Quarterly returns
•
Yearly returns
These are all calculations of price change from one period ago to the report date. The report shows the price at the period earlier, the current price, and the percentage change. It is sorted into descending order by percentage change, but you can sort on any column by clicking the colu m n header. Here is an example of a monthly report: it
C BR
Quick Review
1 Reviewtype
1 Monthly returns
I Dele:
! 8/29/2008
P
ן—ן ןShow 1 '—'immediately Ticker TGT a AVP TW< IP MS HD UNH CMCSA MRK Wr" COV EMC MFQ
_
I
C Filter.
J
L_
P r e v price
Price
% Change
45.68 36.43 37.57 14.57 24.08 36.50 24.33 27.53 19.16 32.41 50 80 4958 14.03 9K 9C
53.02 41 88 4263 16.37 27.05 40.83 27.12 30.45 21 18 3567 55.49 5407 15.28 ?n 3K
16 07% 14 96% 14.00% 12.35% 12.33% 11 86% 11 47% 10.61% 10.43% 10.06% 9.23% 906% 8.91% n nnv
Show
1 I
Close
~
| -f
a
//A
Clicking the Show button starts the calculations that produce the report. Checking the Show Immediately box lets the results display as soon as they are calculated, rather than waiting until the entire report is complete before displaying results. Getting results for the final two report type options: •
Price/Earnings comparison
•
Price/Book value comparison
requires that your database has entries for earnings and book value.
Analysis
481
AUTOMATIC ANALYSIS
As you worked through the Examples in Chapter 3, you saw some of the features and tools of Automatic Analysis. This chapter adds more detail. MAIN WINDOW
When you select Automatic Analysis from the Analysis menu, this window opens. . A u t o m a t i c Analysis - T r a d i n g S y s t e m l . a f l :C\Program
F1les\Am1Broker\Forrnulas\lntro800k\Tred1ngSystern1 ofl
Apply to 0
O
Range
( • ) current symbol
Del
|
0 n last days ®from
Run every:
• W a i t for backfill (RT only) •
i 1/ 1/2000
v
j 1/ 1/2009
Ki
T.
*—1 Net Profit
Explore j
| Beport -
|
I
; ] יij
EguiV
J Parameters
Sync chart on select
Results
Scon
1 Sack Test
: Q n lost quotations
f
O u s e liter •
1
O o" quotations
" symbols
:' j
File
|»]
Settings.
J
j
|
* Net % Profit
j
Qptlmize
Close ש
Exposure %
CAR
RAR
Max Trad,
Max Trad...
Max. S y s .
Max. S:
<1 rows) Profit - 46929.10 (46.934/ ״CAR - 4.54%, MaxSysDD - -46060.03 (-39.27%). CAR/MDD - 0.12. t winners • 26 ש
Begin by examining some of the controls on this window, then go into detail behind the buttons. Formula file Left to right in the Formula file area, there are three items: •
a display of the path of the file that is currently selected or active.
•
a Pick button that lets you navigate to and select a file to become the active file. an Edit button that opens the Formula Editor so that you can modify the selected file.
•
482
Introduction to AmiBroker ix
CD m
Automatic Analysis - TradingSysteml .afl
| I Formula file
ו
:C:\Program F1les\AmiBrokeAFormulas\lntroBook\TradingSysteml .afl
! [ Pick j [ Edit
L O a l l symbols © current symbol
[
O ® ״quotations ,
.
,
יQ n last quotations
>&L,
Scan
J [
:
Explore
1 Back Test j " ־״I 1 Optimize
ר
Apply To The Apply To area gives you three choices of what the analysis will be applied to: •
all symbols - use all the symbols in the database.
•
current symbol ־use only the single symbol that is active or selected.
•
use filter - clicking the Define button opens the Filter settings dialog and lets you select a group of symbols based on their membership in categories. See the image of the Filter settings dialog on page 479. Formula file __ :C:\P10grarn Files\ArniBroker\F0rrnula.s\lr1troBo( Apply to
Range
0 a l l symbols
Qallc
(3) current symbol
—......
O u s e filter
[ Deiine .
f l R u n every:
j
__
5min
Ola Onlo
(Sjfron
• W a i t for backfill (RT only) חSync chart on select
Range The Range area gives you four choices for the date range that the analysis will be applied to: •
all quotations - uses all the data in the database.
•
n last quotations - enter the number of quotations you want to use in the n= field.
•
n last days - enter the number of days you want to use in the n= field.
•
from / to - you can either type the date directly, or use the menu to open a calendar. Select the starting date and ending date.
Analysis
483
Miscellaneous Checking the Run every box, and filling in the number of minutes, requests that the analysis be repeated periodically on the schedule you want. This is useful if you are receiving real-time data or intra-day snapshots and want the results of the analysis refreshed. Checking the Wait for backfill box, which is only meaningful if you are receiving real-time data, requests that the analysis not begin until the data is up-to-date and data for any historical period you have defined has been received. ( # ) current s y m b o l O u s e filter
I
Define...
r ~ | Run e v e r y :
!
]
5m1n |
• Wait for backfill ( R T only) 1 1 S y n c chart o n s e l e c t
Checking the Sync chart on select box is meaningful only after having run an analysis on multiple issues. Click on any of the rows in the Results window and the symbol in that row will be loaded and become the selected issue. All the charts will be redrawn using the newly loaded symbol. F 1 Run e v e r y :
I
5mm
• W o n for backfill (RT only) 0 S y n c chart on s e l e c t Results Net Profit
A : I j ; V
AA AA... ABT AEP AES AIG ALL A..
AVP AXP I BA > BAC , BAX
•61,027. 637,028. -430 94 69,025.43 90.776.51 -59.718 . 84.021.31 -41,585... -11,182.. -43.610... 90,338 70 -51.346... 12.472 30
Net % Profit
Exposi
TOT
637.03 -0.43 69.03 90.78 -59.72 8102 -41.59 -11.18 -43.61 9034 -51.35 12.47
484
Introduction to AmiBroker
SETTINGS B U T T O N
Clicking the Settings button on the main AA window opens the Backtester settings dialog. It has six tabs. Each will be discussed. General tab Backtester settings General j T r a d e s ! Stops Report 1! Portfolio ii Walk-Forward: General settings UDi f~1 Allow position size shrinking
Initial equity: Long
Positions:
| Daily
Periodicity:
w
I1 !
0 R e v e r s e entry signal forces exit
Min. s h a r e s : q!
Min. p o s . value: חFutures
r~l Activate s t o p s immediately (when turned on. stops are c h e c k e d AFTER current b a r signals)
0 Allow s a m e bar exit (single bar trade) • Use
mode
• P a d a n d align all d a t a to reference symbol:
QuickAFL i'DJI
(turning this on m a y slightly c h a n g e indicators if you h a v e d a t a holes) Defaults (zero m e a n s allow fractional i of s h a r e s )
Round lot size:
(zero m e a n s no minimum c h a n g e ) Commissions & rates | (S) commission table I
I
Q percent
Annual interest rate Account margin:
j Q)% per trade O $ p e r share/contract
1
(100 m e a n s no margin account)
Help
Initial equity ־Enter the starting balance for the trading account. Positions - The menu gives three choices. Select whichever is meaningful for your trading system. • Long •
Short
•
Long and Short
Periodicity - The menu gives choices consistent with your database. If you have an end-of-day database, you will only see choices of daily and longer. If you have an intraday database, you will see shorter time periods. Periodicity: Min. s h a r e s : Min. p o s . value: O Futures m o d e
| Daily Yearly Quarterly ! Monthly Weekly
F | ־P a d a n d align a Day/Night Hourly (turning this on may 15 Minute 5 Minute Defaults 1 Minute 3-minute Round lot size: 7-minute 10-minute Tick size: 12-minute 20-minute Commissions & rate•
Analysis
485
Min Shares - The minimum number of shares required to open a position. If your account does not have enough cash to purchase this many shares, it will pass on the trade. Min pos value - The minimum dollar amount required to open a position. If your account does not at least this much cash, it will pass on the trade. Futures mode - Check this box to have the trade accounting done using margin deposit and point value. Pad and align all data to reference symbol - This is off by default. When checked, it will be turned on. When on, the quotes of all symbols are padded and aligned to the reference symbol. Padding and aligning insures that there will be data for exactly the same dates and times in both series. The symbol being tested will have data removed for periods when the reference symbol has no data, and will have data added (previous value copied) for periods when it has no data but the reference symbol does. Enter the ticker for the reference symbol in the box. Allow position size shrinking - When checked, allows position size to shrink so that a partial position can be taken if cash is insufficient for a full position. Activate stops immediately - When you trade on open and want to have built-in stops activated on the same bar, check this box. When you trade on close and want built-in stops to be activated from the next bar, uncheck this box. Reverse entry signal forces exit - Check this box to turn on, uncheck to turn off. When on, a signal to entry a short position forces an exit to a long position being held, and vice versa. When off, an entry to a short position does not force the exit of a long position - the long position waits for its own exit signal. Allow same bar exit - Check this box to turn on, uncheck to turn off. When on, the exit from a trade can occur on the same bar as the entry. When off, the earliest exit is the next bar. Use QuickAFL - When checked, use QuickAFL. QuickAFL examines the visible charts and recomputes indicators using only as much data as necessary to redraw the visible portion or recompute the selected range.
486
Introduction to AmiBroker
Round lot size - The minimum number of shares, or contracts, that can be purchased. For mutual funds, where it is possible to purchase fractional shares, enter 0. Tick size - The smallest change in the price that can be recorded. A setting made on this screen is a global setting and will apply to all symbols. You can enter a value for each symbol, which will override the global setting, using Symbol > Information. Commissions & rates - Can be set from a table, or you can enter a number to be used as a percentage, a cost per trade, or a cost per share. Annual interest rate - The rate you earn on f u n d s that are in cash and not invested in a position. Account margin - This setting is for your entire account. It is not related to margin for futures. It is the percentage of the f u n d s in your trading account that comes from your cash. 100 means all of your account comes from your own money. 50 means that 50 percent of your account comes from your own money and you are borrowing the other 50 percent. Trades tab Backtester settings General | Trades
Stops |i Report ; Portfolio
Walk-Forward j
Long t r a d e s Buy price:
Sell price:
Buy d e l a y :
Sell d e l a y :
Short t r a d e s S h o r t price:
C o v e r price:
Short delay:
Cover delay:
j Close
Help
Buy Price - The menu gives you a choice of Close, Open, High, Low, or Average. This price will be used if your trading system issues a market order. That is, if it only signals Buy or Sell without specifying the
Analysis
487
BuyPrice or SellPrice. You can use an AFL statement (BuyPrice = xxx) to override settings made on this screen. Sell Price, Short Price, and Cover Price are the same. Buy Delay - The number of bars between the generation of the signal and the execution of the trade. If you are using daily bars, computing signals in the evening, and trading the next day, use a value of 1. If you are watching the market intra-day, get a signal near the close, and make the trade on that same bar, use a value of 0. You can use an AFL statement (SetTradeDelays) to override settings made on this screen. Stops tab
Maximum Loss Stop - You have a choice of: •
Disabled - No maximum loss stop is active.
•
Percent - Enter a maximum loss stop as a percentage of the entry price. Enter the percentage number in the field.
•
Point - Enter a maximum loss stop as a fixed number of points. Enter the number of points in the field.
The Exit at menu gives you three choices. Maximum loss stop ®disabled O percent O point
| Exit at trade price only (0) Exit intraday at stop (1) [Exit next bar at trade price (2)
488
Introduction to AmiBroker
•
Exit at trade price only - Use the price set on the Trades tab. If you have set your sell to be at the close, the stop will be executed at the close, at the closing price.
•
Exit intraday at stop - Use the price computed by the AFL code. Exit next bar at trade price - Use the price set on the Trades tab, and exit on the next bar.
•
Re-entry delay - Number of bars to wait before taking a new position in this same issue. Profit target and Trailing stop are controlled in the same way. N-bar stop - You have a choice of: •
Disabled - No N-bar stop in place.
•
bars - Enter the number of bars in the field. An exit will be made after this number of bars.
Has priority - When checked, the N-bar stop has priority over other exits that are signalled for the same bar. When unchecked, other stops are considered first, such as a profit target hit on the same bar as the N-bar exit stop. Report tab
Analysis
489
Result list shows - give you a choice of: •
Trade list - Report a listing with a row for every trade made.
•
Detailed log - Report a listing with a row for every bar, including information about scores and positions.
•
Summary - Report a listing with one entry per backtest.
Risk free rates - Interest rates used when computing Sharpe ratio and Ulcer Performance Index. Distribution charts spacing - Controls the spacing between bars on some of the charts. MAE/MFE distribution charts - Only available with Professional Edition of AmiBroker. When checked, produce the Maximum Adverse Excursion and Maximum Favorable Excursion distribution charts. Generate detailed reports for each symbol in individual backtest When checked, generate a full report for each symbol. This will increase the time of the run and increase the disk space used. Include trade list in the report - Check to turn on, which is the default. When turned on, generates a trade list with every backtest. Warn before time consuming operations - Check to turn on, which is the default. When turned on, pop-up a dialog box asking for confirmation to continue when a long run has been requested. Old Backtester - Provides access to a previous version of the backtester. At the introductory level, you probably do not need the old backtester.
490
Introduction to AmiBroker
Portfolio tab
Max open positions - Maximum simultaneous open positions. This can also be set by AFL code (SetOption("MaxOpenPositions", number )), which overrides the value entered on the Portfolio tab. Add artificial future bars - Add empty bars onto which you can plot indicators. Useful for plotting the value of stops and profit targets to be used the next day. Limit trade size as percentage of entry bar volume - Set a limit so that your trade does not dominate the trading or try to take impossible positions. Disable trade size limit when bar size is zero ־Useful when trading mutual f u n d s and indices that have no volume information. Use previous bar equity for position sizing - When unchecked, which is the default, all f u n d s are immediately available, so use intra-day equity when taking new positions. Enable custom backtest procedure - Allows you to specify a procedure to use as the fitness function. This topic is beyond the introductory level, and is thoroughly described in Quantitative Trading Systems.
Analysis
491
Walk-Forward tab Backtester settings General: Trades
S t o p s :! R e p o r t
Portfolio : W a l k - F o r w a r d
( • ) E a s y m o d e (EOD)
O E a s y m o d e (intraday)
Start
vj
1/ 1/2000 • Anchored
End
O Advanced mode
[ 1/ 1/2001
Last:
[ 1 / 1/2008
Step:
[T
» * [ • U s e t o d a y year(s)
v
End Last:
f י
Mi
׳se today
Step: Optimization t a r g e t Mode IS OOS IS OOS
Ulcer Pert Index Start
End
1/1/2000 1/1/2001 1/1/2001 1/1/2002
1/1/2001 1/1/2002 1/1/2002 1/1/2003
Help
You have a choice of: •
Easy mode (EOD) - End-of-Day easy mode - AmiBroker handling the coordination of dates so in-sample and out-of-sample periods align properly.
•
Easy Mode (Intraday) - Intraday easy mode - AmiBroker handling the coordination of dates so in-sample and out-of-sample periods align properly.
•
Advanced Mode - You have complete control over the length of the in-sample period, the length of the out-of-sample period, and the alignment of the two.
This description is for the Easy mode EOD. Start - The first date for the first in-sample period. End - The last date for the first in-sample period. Last - The last date for the last full in-sample period. Step - The length of the out-of-sample period. Anchored - When checked, the beginning of every in-sample period is the date of the first day of the first in-sample period. With each successive step, the length of the in-sample period grows longer. When unchecked, the in-sample periods are all the same number of days long,
492
Introduction to AmiBroker
and the starting dates move forward in time by the length given for Step. Use today - When checked, do not accept a date for Last. Instead, continue the in-sample and out-of-sample periods using all the data available. Optimization target - The menu gives a list of the built-in metrics that can be used as fitness functions. Developers who want to reward equity growth while penalizing drawdown might want to try one of the metrics that have that characteristic: •
RAR/MDD
•
CAR/MDD
•
RRR (Risk-Reward Ratio)
•
Ulcer Performance Index
•
K-Ratio
msig&smm
*י
% of Winners Avg % Profit/Loss Avg Bars Held Avg Profit/Loss CAR CAR/MDD Exposure % K-Ratio L. Avg % Loss L Avg. Bars Held L Avg. Loss L. Tot. Loss Mac. S y s % Drawdown Max. S y s Drawdown Max. T r a d e % Drawdown Max. T r a d e Drawdown Net % Profit Net Profit No. Payoff Ratio Profit Factor RAR RAR/MDD R e c o v e r y Factor RRR S h a r p e Ratio Standard Error Ulcer Index W. Avg % Profit W Avg. Bars Held W Avg. Profit W. Tot. Profit
V
Advanced developers can: • •
Use advanced mode to completely control the walk forward stepping. Write their own fitness function and instruct the backtester to use it.
Analysis
493
EXPLORE B U T T O N
The previous sections - Main Window and Settings Button - explained how to set up for Automatic Analysis (AA) runs. When you click the Explore Button on the main AA window, you start an AA run. The exploration runs an AFL program that searches for conditions that you specify, then produces a report. Every program that will be run as an exploration has a Filter statement in it. In order for a result to appear in the report, that result must pass the filter. For example, you might want a report showing which members of the S&P 100 have both today's price and today's volume greater than their 10 day averages. Follow these steps: 1.
Use the Formula Editor to write the AFL code and save it in a file named ExploreRisingPriceAndVolume.afl. / / ExploreRisingPriceAndVolume.afl // // An AFL program to run as an Exploration. // Use with a category such as a watchlist. // // Produce a report listing every member of the // group that has both today's price and today's // volume above the 10 day averages. // PriceRising = C > MA( C, 10 ); VolumeRising = V > MA( V, 10 ); Filter = PriceRising AND VolumeRising; AddColumn( AddColumn( AddColumn( AddColumn(
C, MA( V, MA(
"C", 1.2 ); C, 10 ), "MA(C,10)", 1.2 ); ״V " , 1.0 ); V, 10 ), "MA(V,10)", 1.0 );
494
Introduction to AmiBroker
L. [C:\ProgramFiles\AmiBroker\FormulasVCustom\ExploreRising... El 16
Edit
D d • ט
lools S
*
%B
«>־
ty
ExplorsRIsingPrii
• J > ׳E1 -
!-
//
ExploreRisingPriceAndVolume.afi
// //
An A F L p r o g r a m to run as an E x p l o r a t i o n . Use w i t h a c a t e g o r y such as a w a t c h l i s t .
I/ // //
P r o d u c e a r e p o r t l i s t i n g e v e r y m e m b e r of the g r o u p t h a t has b o t h t o d a y ' s p r i c e and t o d a y ' s v o l u m e a b o v e the 10 d a y averages.
// //
//
j
Help
P r i c e R i s i n g = C > M A ( C, 10 ); V o l u m e R i s i n g = V > M A ( V, 10 ); Filter• = P r i c e R i s i n g A H D AddColumn( AddColumn( AddColumn( AddColumn(
VolumeRising;
C " ׳C", 1.2 ); M A ( C, 10 ), ״M A ( C , 1 0 ) 1 . 2 ;) ׳ ״ V, "V", 1.0 ); MA ( V, 10 ), r ׳M A ( V , 1 0 ) 1 . 0 ,;) ״
Ready
2. In Automatic Analysis, click Pick, navigate to the file you just ereated, and select it. 3. Click Use filter, click Define, select the category you want to use. 4. Click n last days, set n to 1. 5. Click Explore. The list of issues in your category meeting the criteria in your AFL appear in the results window. it Automatic Analysis ־ExploreRisingPriceAndVolume.afl i C:\Program FilesVAmiBrokeAFormulas\Custom\ExploreRisingPriceAndVolume.afl Range
Apply to |
O all symbols
; O all quotations
!
O current symbol
-
:j O n 'ast quotations [
Def
(S}n last days Ofrom:
f~]Run every:
־
[ 1/ 1/2000
to;
• Wait for backfill (RT only)
| Back Test n
[ 1 / 1/2009
חSync chart on select Results TickBr AEP BNI CAT a DIS HON MER MMM MO MRK NSC : RF ' T TWX vz WMT WY XOM
Date/Time 8/29/2008 8/29/2008 8/29/2008 8/29/2008 8/29/2008 8/29/2008 8/29/2008 8/29/2008 8/29/2008 8/29/2008 8/29/2008 8/29/2008 8/29/2008 8/29/2008 8/29/2008 8/29/2008 8/29/2008 8/29/2008
!Number of rows: 18
C
M4(C.10)
V
MA(V.10)
39 01 10710 70.73 11 88 32.35 50.17 28 35 71 60 21 03 35.67 73.53 9.27 31.99 16 37 3512 69.07 5519 80.01
3893 102.13 6919 41.81 31.97 19.33 25 20 71.39 20.94 35.12 7055 8.51 31 11 1588 31.72 56.91 52.93 79.13
1.511.600 3.923.100 1.905,200 1.817.000 9.062.700 3.383.500 62.341.000 3.410.000 10.670.500 11,569.000 3,995,900 12,843.500 31,327.100 22,653.800 10,087,900 12,853,700 2,051.500 22,060,300
1,166,750 2.935.090 1,709,930 1,773,300 8.700.510 3,263,150 29.311,630 3.125.810 6.706.910 10,166.590 2,655,150 12,105,270 20,130,890 19.047,040 9,909.870 12.485,160 2.029.360 21.747,960
(
Optimize
:-[
Analysis
495
The elements of AFL code that are unique to explorations are: •
The Filter statement.
•
The AddColumn statements.
The Filter statement has the form: Filter = any expression that evaluates to True or False;
If you want an entry in the report for every symbol in the watchlist, use this: Filter = 1;
The AddColumn statement has the form: AddColumn (Array, "Name", format);
Where Array is the value to be reported, "Name" is the heading for the column, and format is the format of the output. Format is a pair of digits with a decimal point between them, such as 1.4. The first digit is the number of spaces to use. 6.4 guarantees 6 spaces for the number, even if it only requires 2. The second digit is the number of decimal places to display. 6.4 displays the result to 4 decimal places.
496
Introduction to AmiBroker
BACKTEST
BUTTON
The Backtest Button begins execution of a backtest. That is, a test of the profitability of the buy and sell rules defined in an AFL program as it is applied to historical data. The AFL code that buys and sells is a trading system. The backtest button has a pull-down menu that gives three choices: •
Portfolio Backtest ־Apply the backtest program to a group of issues, all of which are candidates to be held. The backtester calculates the buy and sell signals for each individual issue in the group. Then it goes through the signals in order by time. Whenever there is a buy signal and there is cash available to take the trade, a position is taken. If there is not enough cash, the trade is passed. Whenever there is a sell signal, the position is sold and the cash made available for another purchase. The equity curve (running account balance) and report are produced for the portfolio as a whole.
•
Individual Backtest - As above, apply the backtest to a group of issues, all of which are candidates to be held. The backtester calculates the buy and sell signals for each individual in the group. Then, differing from the portfolio method, it assumes each of the issues is the only candidate to be held, and calculates a report for each of the issues individually.
•
Old Backtester - Runs an earlier version of the backtester. For more information, see the AmiBroker User's Guide, Old Backtester Report.
The same AFL code can be run as a portfolio backtest and an individual backtest. I N O R D E R T O R U N A B A C K T E S T O N A P O R T F O L I O , you must click use filter and define a group. Then click Backtest (portfolio backtest is the default) or use the menu and choose portfolio backtest.
click current symbol and click backtest. The result will be titled . If you want the result to list the ticker symbol, use the menu and choose individual backtest. I N ORDER TO R U N A BACKTEST ON A SINGLE ISSUE,
Analysis
497
IN ORDER TO RUN A BACKTEST ON SEVERAL ISSUES IN O N E PASS, TREATING
filter, use the menu and choose individual backtest. There will be a result for every symbol in the group, but no portfolio result.
T H E M A S I N D I V I D U A L S R A T H E R T H A N A S A P O R T F O L I O , CLICK U S E
In processing the AFL file, the backtester performs the calculations and assignment statements. The key component is the set of buy and sell (and, perhaps, short and cover) signals. The format of a buy statement is: Buy = whatever condition you want to signal taking a new position;
And of a sell statement: Sell = whatever condition you want to signal exiting that position;
When the calculations that make up the condition to buy evaluate to True, or 1, that constitutes a buy signal. When the calculations that make up the condition to sell evaluate to True, or 1, that constitutes a sell signal. A very simple trading system, often used as an example because of its simplicity, not because of its profitability, is a moving average crossover. Look at the code from Example 6B, Chapter 3. // // // // // // // // //
Example6B.af1 A trading system based on the crossover of two moving averages. Buy when the faster moving average crosses up through the slower moving average. Sell when the faster moving average crosses down through the slower moving average.
FastMALength = 5; SlowMALength = 20;
//Guess that 5 is a good value //Guess that 20 is a good value
FastMA = MA( C, FastMALength ); SlowMA = MA( C, SlowMALength ); Buy = Cross( FastMA, SlowMA ); Sell = Cross( SlowMA, FastMA );
498
Introduction to AmiBroker
When ever the right-hand side of the Buy = statement evaluates to be True, that is a buy signal. The Cross function returns a value of true on every bar where the first argument is higher than the second argument on this bar, but the first argument was lower than the second argument on the previous bar. That is - where the first argument crossed up through the second argument. Example 6, Chapter 3, demonstrates a trading system based on a moving average crossover. Review that example now. In order to test the profitability of a trading system when it is applied to a portfolio, the system must have some way of controlling the number of positions held at any one time. It must also be able to allocate funds to each new position. There are AFL statements that do that. The statement: SetOption ("MaxOpenPositions", 3);
tells the backtester that there can be a maximum of 3 open positions. If 3 positions are being held and a buy signal comes from a symbol not being held, it is ignored and that trade is passed. If fewer than 3 positions are being held and there are sufficient f u n d s to take a new position, a position will be taken in the symbol that generated that buy signal. Having the possibility of holding 3 positions implies that there is funding for 3 "tracks". The statement: PositionSize = -100 / 3;
tells the backtester that each new position is funded by one third of the account equity. As the equity grows, more money is available for purchases in each of the three tracks - they share the f u n d s equally. You might want a way to test the effect of allowing a differing number of maximum positions. These statements are equivalent to the ones above, but give the flexibility of changing the maximum number easily. PosQty = 3; // There can be 3 open positions SetOption("MaxOpenPositions", PosQty ); PositionSize = -100/PosQty; // invest 100% of portfolio // equity divided by PosQty
Analysis
499
Put these statements at the beginning of the code from Example 6B, and save it under a new file name, say BacktestExample.afl. // // // // // // // // //
BacktestExample.afl A trading system based on the crossover of two moving averages. Buy when the faster moving average crosses up through the slower moving average. Sell when the faster moving average crosses down through the slower moving average.
PosQty = 3; // There can be 3 open positions SetOption( "MaxOpenPositions", PosQty ); PositionSize = -100 / PosQty; // invest 100% of // portfolio equity divided by PosQty FastMA = MA( C, 5 ); SlowMA = MA( C, 20 ); Buy = Cross( FastMA, SlowMA ); Sell = Cross( SlowMA, FastMA j; Plot( C, "C", colorBlack, styleCandle ); e = Equity(); Plot( e, "equity", colorGreen, styleLine | styleOwnScale );
When you have the program changed and are in the Formula Editor, click the Analysis icon (the "!" in the toolbar). This causes the file being edited to becomes the active or selected file and Automatic Analysis opens. Click use filter, then Define, and select a watchlist with 5 or more symbols in it. The 9 S&P sector exchange traded f u n d s make a good watchlist for testing. The 9 symbols are: XLB, XLE, XLF, XLI, XLK, XLP, XLU, XLV, XLY. Set the range to 1/1/2000 to 1/1/2007.
500
Introduction to AmiBroker
Click Backtest. The Results area will show the results of running the system as a portfolio. lx Automatic Analysis - BacktestExample afl Formula file j C:\Program F1lesVVniBrakeAFormulas\Custom\BacktestExampleafl
i
O
al
O
symbols
®usefilter
1
[ Back Test =״
ו
j 1/ 1/2000"
׳י
O n last d a y s
I
(*)from:
iRun e v e i y
[
-] |
Optimize
Report.
;| ]יי
FHe
Eaurty
j ' ] ![
[
O W a i t t o t b e c k H (RT only)
1
Q S y n c chart o n select
Parameters
I
,
״J
Q
Settings..
J
Close
|
₪
Results Ticker
Edit
Explore
quotations
! 0> n last quotations
O current symbol :
| I Pick ||
Range
Apply to
Net Profit
Net % Profit
Exposure %
CAR
RAR
1,677 70
1 63
53 60
0 24
0 45
Max Trad -4,206 06
Max. Trad. -10 95
Max. Sys . -32 203 30
(1 rows) Profit • 1677 70 (1 68%). CAR • 0.24%, MoxSysDD - -32203 30 (-30.43%). CAR/MDD - 0 01 I winners - 58 (34
The results are poor, but perhaps they can be improved later. Click the Report button. The Report will open. Expand it and look at the statistics on the first tab. Look at the trades on the Trades tab. Note that there are several positions held at a given time - between 0 and 3. Click the Equity button and scroll back and forth. Blue areas are positions, green are cash. You can see when there were 0, 1, 2, and 3 positions held. A VP -
!׳־
= 96,992
:town - -8,839 40
fltNMKP 80,000
-
Aug ז ^ ז
H
C
v ,Dec 12006 *Feb Tviir 0 5
Use the pull-down menu at the right side of the Backtest button and select Individual Backtest. The Results area will show the results - one line for each of the members of the watchlist.
Analysis
501
L Automatic Analysis - BacktestExample.afl C:\Prograrn FilesVVniBroker\Formulas\Custom\BacktestExarnple afl Apply 10
Pick
Range
( J o l l symbols
Explore
: O o" quotations
O current symbol
.
O
n
l®st quotations
® u s e filter
1 Pet
O
ח
l®st d a y s
{*)from:
1 I Run evety: •
Wait tor backfill (RT only)
•
Sync chart on select
|[־iiT
( BadiTest I
1/ 1/2000 1/ 1/2007
B־po-t
-j [ H|
[
Eauiy
|
Parameters
Qptimiie
| - J [_ Settings... J [
I
Close
₪
Results T
"j
File
Net Profit
Net % Profit
Exposure %
XLB -10.502.. XLE 1.805.36 XLF -5,88797 XLI 3.46586 XLK -3,270.98 XLP -1,078.63 XLU 19,885.24 XLV -156.65 XLY 2.581.62
-10 50 1.81 -589 3.47 -3.27 -1.88 19 69 -0.16 2.58
1890 18.83 19 41 17.58 16 89 1B.40 19.13 17.42 18.18
CAR
RAR
-1,57 -8 33 0.26 1.36 -0.86 - 4 4 5 0.49 2.78 -0 47 -2.81 -0.15 -0.84 2.63 13.73 -0.02 -0.13 0.37 2.01
Max. Trad -3.899 50 -3.199.54 -4.142.74 -2.873.25 -4,749.19 -3.508.68 -3.977.94 -3.09446 -3,853.18
Max. Trod -10 B8 -8.99 -11 67 -7 97 -14.34 -9.90 -10.31 -9.06 -981
Max Sys 17:220.76 -18.034.90 -13,067.36 -11.520.05 -17,448.37 -9.210.56 -5.647.15 -13.001.43 -9.934.97
;(9 rows) Profit - 2581.62 (2 58%). CAR • 0 37%. MoxSysDO - -9934.97 (-9.39%). CAR/MDD - 0.04. # winners - 23 (38.33'
If you click the Equity button (portfolio equity is the default), the portfolio equity chart shows that there is either one position or none. This is because the last backtest was not a portfolio test, so there is no portfolio result to display. Instead, the equity for one of the individual issues is displayed using the portfolio equity format of blue and green columns. Use the pull-down menu to the right of the Equity button and select Individual Equity. A new pane will open and plot the equity of the symbol in the row that has been selected, this time in individual equity format. Click another row and get the equity curve for that symbol. The solid red part is the equity from the trading system; the blue line is the equity from buy-and-hold. XLU - Equity = 123,411 13, Buy&Hold = 133.793 34
136.000 IEEEB 132.000 128,000
502
Introduction to AmiBroker
CONTEXT
MENU
After an Automatic Analysis r u n where there are results in the results window, right-click anywhere in the window to bring up the AA Context menu. There are two rather different types of processing on the context menu: 1. Show arrows resulting from trades taken on a single security - the top three. 2. Send symbols resulting from runs taken over a group of securities to watchlists - the next four. L. Automatic Analysis - BacktestExample.afl ןC:\Program Files\AmiBroker\Formulas\Custom\BacktestExample.afl Apply to
Range
O a f l symbols
O
O current symbol
.
® u s e filter
[
6111
°et
|
j 1/ 1/2000
J
! 1/ 1/2007
• Wait for backfill (RT only) i
I
i O חlast days j ®from:
riRunevety:
II HI Beport״. -וו Eauity -וו P a r a m e t e r s 11 Scan
quotations
O חlast quotations
»
i S y n c chart on select
Back T e s t
Explore Optimize File Settings...
T
XLF XU XLK XLP XLU XLV XLY
Net Profit -10.502.. -5,887.97 3.465.86 -3,270.98 -1.078.63 19.885 24 -156 65 2.581 62
Net % Profit
Exposure %
CAR
RAR
-10.50
18.90
-1.57"
-8.33
Max Trad. :
1
Close
Results
XLB
| j*]
Max- Sys
₪ Max S;׳
3.B99.50
Show arrows for all raw signals
17.22076-11 67 -7.97 -14 34 -990 -10.31 -9.06 -9.61
Show arrows for actual trades Show current trade arrows Add all results to watch list... Add selected results to watch list... Replace watch list with the results...
-13,087 36 -11.52005 -17148 37 -9.210.56 -5,647.15 -13.001.43 -9.934.97
Replace watch list with selected results., clear results list Select All Copy (9 rows) Profit • 2581.62 ( 2 . 5 8 ^
Ctrl+A Ctrl+C .עדו,.).^׳
MDD - 0 04. *winners - 23 (38.33
We'll demonstrate in two examples. Running a trading system on a single security will get us to the first set of three options. To get things set up, follow these steps: F I R S T EXAMPLE.
1. From the Analysis menu, select Automatic Analysis. Click Pick and select Example6B again. 2. Click Edit, which will open the Formula Editor and display the AFL code of the system. Add these three lines to the bottom of the program: Plot( C, "C", colorBlack, styleCandle ); Plot( FastMA, "FastMA", colorRed, styleLine ); Plot( SlowMA, "SlowMA", colorBlue, styleLine );
503
Analysis Save the program as Example6X.afl. L [C:\Program Files\AmiBroker\Formula5\Custom\Ex:ample6X.a... File ט // // // // // // // // //
Edit
!001s
!_:OjX
Help
#
m
^
׳
E«ample6x
>׳־;־::׳
! - _
ExampleSX.afl A t r a d i n g system based on the c r o s s o v e r of t w o m o v i n g averages. B u y w h e n the faster m o v i n g average c r o s s e s up t h r o u g h t h e slower m o v i n g average. Sell w h e n t h e faster m o v i n g a v e r a g e c r o s s e s d o w n t h r o u g h the slower moving average.
F a s t M A L e n g t h = 5; S l o w M A L e n g t h = 20; F a s t M A = M A ( C, S l o w M A = M A ( C,
/ / G u e s s 5 is a good v a l u e / / G u e s s 20 is a good v a l u e B
F a s t M A L e n g t h ); S l o w M A L e n g t h );
B u y = C r o s s ( F a s t M A , S l o w M A ); Sell = C r o s s ( SlowMA, F a s t M A ); Plot( C, "C", colorBlack, s t y l e C a n d l e ); Plot( F a s t M A , "FastMA", c o l o r R e d , s t y l e L i n e ); Plot( SlowMA, "SlowMA", c o l o r B l u e , s t y l e L i n e );
Send to automatic analysis window
Ln 22, Col 48
3. Click the Verify Syntax icon to test for typing errors. 4. Using the Apply icon, drop down its menu and use the Insert option. A new pane will open with the price in a candlestick chart, a 20 period simple moving average, and a 5 period simple moving average. 5. Right-click the pane with the new chart, bringing up the Chart Pane Context menu. Set the options to show the date axis and to show trading arrows. Click OK to leave the context menu. (Review Chart Pane Context Menu if necessary.)
6.
Set some parameters for Automatic Analysis. Use just the current symbol. Set the date range for a year or two. Positions to Long. Periodicity to Daily. Buy and Sell on the Close with Delay 0. Reporting show a Trade List.
504 7.
Introduction to AmiBroker Click Backtest. The Results window will show results.
EBB
t Automatic Analysis - Example6X.afl I C:\Prograrn Files\AmiBroker\Formulas\Q1stom\Example6X.afl A p p l y to
Range
O "סs y m b o l s :
! O ® ייquotations
@ current s y m b o l O u s e filter
: O חlast quotations [
on
Db1
18st
days
»ח
(*)from: 1/2006 /ן ן
•
Run e v e ry
•
W a i t for backfill ( R T only)
1/ 1/2008
Q S y n c cfcart or! s e l e c t Results Ticker XLU XLU XLU XLU XLU XLU XLU XLU XLU XLU XLU XLU XLU
Trade Long Long Long Long Long Long Long Long Lang Long Long Long Long
Date
Price
Ex d a t e
1/9/2006 2/22/2006 1/21/2006 6/1/2006 7/3/2006 9/29/2006 11/13/20. 1/29/2007 3/15/2007 7/3/2007 8/10/2007 8/23/2007 9/F./2007
31.98 32.47 31.54 32.15 32.65 33.99 359 36.37 38 74
1/31/2006 3/8/2006 5/17/2006 6/21/2006 9/11/2006 11/9/2006 12/22/20... 3/5/2007 5/25/2007 7/26/2007 8/15/2007 8/28/2007 10/19/20
40.15 3901 39.37 39 3
Ex, P . .
%...
Profit : % Profit
3 2 1 5 0.53% 531*58 31.6 -2 68... -2,693... 30,64 -2.22... -2,171 31.72 -1.34... -1.279.. 34.23 4 84% 4.567.58 35.64 4.85% 4,80362 36.57 1.87% 1.936.43 37.57 3.30% 3.487.31 41.1 6.09% 6.851.25 38.7 -3.61... -4.183... 38.03 -2.51... -2,804. 38 -3 48 . -3.787... 39 74 1.12% 1.176.22
0.53% -2.68% -222% -1.34% 4.B4% 4,65% 1.87% 3.30% 6.09% -3.61% -2.51% -3.48% 112%
Shares 3,1 26 95 3,096.14 3.102.03 2.975.63 2,890.87 2,911 28 2,890 2 2,906.09 2.818.33 2.885.01 2.862 08 2.76467 2.673.22 >
O
:(15 rows) Profit - 7972.97 (7.97%). CAR • 3 93״/.. M a x S y s O O - -16426 65 (-13.61 •/.), CAR/MDD • 0 29. * w i n n e r s - 8 (53.:
8.
Right-click the Results window to bring up the context menu. : Ticker
Trade
Date
Price
Ex d a t e
1 XLU ^
Long
1/9/2006
1196
1/31/2006
XLU XLU XLU XLU XLU XLU XLU XLU XLU I XLU i XLU
Long Long Long Long Long Long Long Long Long Long Long
1/21/2006 6/1/2006 7/3/2006 9/29/2006 11/13/20. 1/29/2007 3/15/2007 7/3/2007 6/10/2007 8/23/2007 9/6/2007
31 51 5/1 32.15 6/2 32.65 9/1 33.93 11/ 35 9 12/i 36.37 3 36 71 5 10.15 7/2!
ft
3901 39.37 39 3
8/1 8/2 10/11'
Ex P 32 15
% 0 53%
Profit
% Profit
Shares
531 58
053%
3.126 95
S h o w a r r o w s far all raw signals S h o w a r r o w s for actual trades S h o w current trade a r r o w s
>
ונו
Add all results to watch list... Add selected results to watch list. Replace watch list with the results... Replace watch list with selected results... c l e a r results list
1(15 rows) Profit - 7972,97 (7 97%), CAR - 3 93%. t,
Since this run was made on a single symbol, the top three options are meaningful. Show arrows for all raw signals - Sometimes there are signals that do not result in trades. This option shows all signals. Show arrows for actual trades - Shows those signals that became trades. Show current trade arrows ־Each row of the results represents one trade. Select one trade. This option scrolls the chart and shows the arrows for that one trade.
Analysis
505
This chart shows arrows for actual trades. (The arrows drawn for the first option result in the same chart, because there are no extraneous signals.) XLU - C = 43.43. FastMA = 43 41. SlowMA = 43 DO
Options four through seven come after running the system using a group of stocks. Follow these steps (1 through 5 are the same as the previous example): 1. From the Analysis menu, select Automatic Analysis. Click Pick and select Example6X. S E C O N D EXAMPLE.
2. Click Edit, which will open the Formula Editor and display the AFL code of the system. 3. Click the Verify Syntax icon to test for typing errors. 4. Using the Apply icon, drop down its menu and use the Insert option. A new pane will open with the price in a candlestick chart, a 25 period simple moving average, and a 5 period simple moving average. 5. Right-click the pane with the new chart, bringing up the Chart Pane Context menu. Set the options to show the date axis and to show trading arrows. Click OK to leave the context menu. (Review Chart Pane Context Menu if necessary.) 6. Set some parameters for Automatic Analysis. Use filter and select a watchlist of your choosing. Set the date range for a year or two. Positions to Long. Periodicity to Daily. Buy and Sell on the Close with Delay 0. Reporting show Summary.
506
Introduction to AmiBroker
7. On BackTest's drop-down menu, select individual backtest. You will see a progress bar as the system is applied to each symbol in the watchlist. L. Automatic Analysis - Example6X.afl | C:\Program Fi le s\AmiB ro ke r\F0 rrnu I a.s\Cu sto m\Exarn p I e 6X . afI Apply to
: Range
O all symbols
| 0 all quotations :
: CZ) current symbol ®usefilter
[
Del
Explore
Onlastquotations O
n
![־־IdiT
] | Pick
Optimize
last d a y s
! ® f r o m : 1/ 2/ן
5min j
•
Run every:
•
Wait for backfill (RT only)
:'
Portfolio Backtest (default)
1/ 1/2008
Old (v4.4) Backtester
F I S y n c chart o n select
The Results window will show results. Sort the results as you wish by clicking a column header. L. Automatic Analysis - Example6X.afl C:\Prograrr1 Files\,AmiBroker\Formulas\Custom\Exarnple6X.afl Apply to
Range
I Q a l l ׳symbols
! O
a|
;
j: O
n
Q current symbol [Dei
® u s e filter
[
l quotations l a s t quotations
: O חlast d a y s ® ןfrom:
F l Run every:
I 1/ 1/2006
-
1/ 1/2006
• Wait for backfill (RT only)
י
f ~ | S y n c chart on select
Scon
|
Explore
|
-j j
Qptimize
-1
File
-|
|
Back T e s t
[
Bepott
|
[ _ EauiV
h| |
Settings..
|
Close
|
Parameters
₪
Results Net Profit
Net X Profit
XLE 40.476 71 XLI 18,32810 XLK 15.691 29 XLU 7,972.97 XLV 5.394 98 XLP 4.23470 XLB -979.31 XLY -7,353.38 XLF -16.656..
40 48 18.33 15 69 797 5.39 4.23 -0.98 -7 35 -16.66
T...
|
Exposure %
F
\
63.15 18 61 29 46 64 34 8 8 2 13 70 66 33 7 5 9 11 45 64.34 3,93 610 56.37 2 67 474 64.34 2.10 3.27 6 6 7 3 -0.49 - 0 7 4 61 75 -3.76 -5 09 58.57 - 8 7 4 -14..
< (9 rows) Profit - -7353.38 (-7 35%). CAR
CAR
Max. Trad.. -10,509 69 -6,630,20 -7,998.31 -7,068 28 -4,442 05 -3.501 67 -8,385.66 -5,670.04 -8,093 23
Max Trad -7 87 -576 -6 62 -5.95 -407 -3.25 -7 84 -508 -B 85
Max. S y s .
Max S!
-14,045 61 -10,786,27 -8,951 01 -16,426 65 -11.096 97 -9.270.71 -13.19714 -19.058 63 -18,174 95 >
3.76%-
־. MaxSysDD • -19058.63 (-17 06%). CAR/MDD - -0.22. *winners « 3 (1 ־.
Analysis
507
Each row represents the result of running this system on an individual symbol. Select several rows by holding the C O N T R O L key while left-clicking the rows you want. Right-click the Results window to bring up the context menu. L Automatic Analysis - Example6X.afl Formula file j C:\Program Files\AmiBroke1\Formulas\Custom\Example6X.afl
.
Apply to
Range
O all symbols
O
O current symbol
1
quotations
O " '®St quotations
usefilter
I °al®
c:
0 n last d a y s ®from:
ח:Run every
Scan
||
| Back Test
|
1
Bepott
-1 1
1/ 1/2006 1/ 1/2008
Waitforbackfill (RTonly) •
|
Eflurty
:||־י
[ Parameters
• Sync chart on select
Explore
| ייj
Optimize File Settings...
] j
|
Close
Results
ש Net Profit
Net % Profit
18.328 18
IB 33
i XLU 7.972.97 I XLV 5.394 98 : XLP 4.234.70 I XLB -979 31 ! XLY -7.353.38 I XLF -16.656
7.97 5 39 4.23 -0 98 -735 -16 66
Exposure %
CAR
F
Max. T r a d .
Max. Trad
Max. Sys ...
Show arrows for all raw signals
Max. S;
-10.786.27
Show arrows for actual trades Show current trade arrows
-16.426.65 -11.096.97 -9.270.71 -13,197.14 ו י ד ״tBSIET" -18,174.95
Add all results to watch list... Add selected results to watrh list... Replace watch list with the results.. Replace watch list with selected results Clear results list Select All
* :(9 rows) Profit - -7353 38 (-7.35%).
9.
Ctrl+A ctrl+c
Copy Mguyu.ll •
.״..., -0.22. *winners = 3 (!',
•
The four options marked are applicable: Add all results to watchlist ־Adds all the symbols in the results list to the watchlist. Duplicates will be removed. Add selected results to watchlist - Adds the symbols in the rows you have selected to the watchlist. Replace watchlist with the results - Makes the watchlist empty, then adds all the symbols in the results list. Replace watchlist with selected results - Makes the watchlist empty, then adds the symbols in the rows you have selected to the watchlist.
TW^jronmiEfc
508
Introduction to AmiBroker
FILE B U T T O N
The file button has a pull-down menu that gives two choices. Export - Export the contents of the Results window to a file in a directory of your choice. The format of the saved file can be either .csv, which can be opened in a spreadsheet for further analysis, or .html, which can be printed, e-mailed, or imported back into the results window.
File Export... Import...
•
Import - Import a file in .html format that was previously exported. The import works best if the file being imported was created by AmiBroker using the Export command.
If the File button is clicked without pulling down the menu, the default operation is Export. EQUITY
BUTTON
The equity button has a pull-down menu that gives two choices. Eguity
•
j»
Portfolio Equity Individual Equity
Portfolio Equity ־Opens a new pane and displays the equity for the most recent run using the portfolio format. . Drawdown = -490.05
IP - Portfolio
־mm׳ 10,000
Final Equity
0,000
BBS®•'0 4.000
• •
2,000 g
Drawdown Blue Securities Held
•
Green Cash Held
Individual Equity - Opens a new pane and displays the equity for the most recent run using the current symbol as the price series tested. Changing the current symbol, either by clicking a row in the results window or by selecting a new symbol, changes the equity plot to reflect testing that symbol.
509
Analysis
[The plot style in the image shown has been changed so that the trading system equity is a line for better printing. On the default plot it is a solid area.] MSFT- Equity = 121,599.96, Buy&Hold = 104,113 69
160.00• 15D.000 140 ,ODD 13D .000
110.0••
E3CE I I II!
90.000 60,000
Buy and Hold
Trading System
REPORT B U T T O N
ן
Report
The report button has a pull-down menu that gives
u
t W O
View last report (default)
C h 0 i C e S .
Report Explorer
•
View last report - Opens the report for the most recent backtest. The report is in .html format, with one html page per tab of the report. Reports are saved in the directory C:\Program Files\AmiBroker\Reports. They stay there until you remove them. i
BacktestExample
File
View
mmmm
,3
׳y
HJJJ
Backtest Report ־HtmlView
ן
Help
m
f
Statistics | Charts I Trades I Formula I Settinqs i Symbols Statistics Al trades
Long t r a d e s
Short trades
Initial capital
100000.00
100000.00
100000 00
Ending capital
124305.08
124305.08
100000.00
24305.08
24305.08
24.31 %
24.31 %
0.00 0.00 % 0.00%
Net Profit Net Profit % Exposure % Net Risk Adjusted Return % Annual Return % Risk Adjusted Return % AN t r a d e s
16.00 %
16.00 %
151.90 %
151.90 %
N/A
3.16%
3.16%
0.00 %
19.75 %
19.75 %
N/A
0 (0.00 %)
195
195(100.00%)
Avg. Profit/Loss
124.64
124.64
N/A
Avg. Profit/Loss %
0.36%
0.36 %
N/A
5.38
5.38
123 (63.08 %)
123 (63.08 %}
107642.59
107642.59
Avg. Bars Held Winners Total Profit
N/A
0 (0.00 %} 0.00
Avg. Profit
875.14
875.14
N/A
Avg. Profit %
2.47%
2.47%
N/A
3.93
3.93
N/A
13
13
0
3503.46
3503.46
0.00
2
2
Avg. Bars Held Max. Consecutive Largest win * bars in largest win
;1 If:
510
Introduction to AmiBroker
•
Report Explorer - Opens the Report Explorer (which runs as a separate program), and loads a summary line for each report in the Reports directory. You can sort the list by clicking on the header of any column.
: 1 - '• ' 11 Report Explorer ־results.rlst
1 File Edit
View
I a? Q ft* X ש ; # 1 2 3 4 5 6 7 8 9 <
i Name
f
| Created
Figure_l... Figure_l... Figure_l... Figure_l... Figure_l... Figure_l... Figure_l... Figure_l... Figure_l...
H R I
Help
2008-07- ., 2008-07- .. 2008-07- .. 2008-07- .. 2008-07 ־.. 2008-07- ,. 2008-07- .. 2008-07- ... 2008-07 ־...
j Type] Syrnbol(s) I I I I I I I I I
AAPL ADBE ADSK AKAM ALTR AMAT AMGN AMLN AMZN
j Date Range ( N e t Profit 3/7/2007.... 3/7/2007.... 3/7/2007.... 3/7/2007.... 3/7/2007.... 3/7/2007.,.. 3/7/2007..,. 3/7/2007.... 3/7/2007...,
62081.51 20786.43 -20539.02 ־3571.92 -2043.00 ־26653.81 ־17611.46 3168.36 4340.33
| Net % Pr... | Exposure % ii CAR 62.08 20.79 ־20.54 ־3.57 -2,04 -26.65 -17.61 3.17 4.34
48.27 48.27 48.27 48.27 48.27 48.27 48.27 48.27 48.27
42,37 14.81 -15.48 -2.63 -1.50 -20.29 -13.21 2.31 3.16
J
RAR
87.78 30.69 -32.07 ־5.44 ־3.10 -42.03 ־27.37 4.78 6.54
J Max. Tra... 1 Ma ^ -14724.35 -6535.99 ־13568.66 ־20048.27 -18011.15 ־7128,82 ־9569,76 -11322.32 -17981,61
-7( -5.: -16 -18 -15 -7,( -9.: -10 >
Ready
If you have previously turned on the feature that generates detailed reports (on Automatic Analysis > Settings > Report, click Generate detailed reports for each symbol in individual backtest), clicking one of the rows in the report listing will open the detailed report. The menus for the Report Explorer give a method for selecting and deleting unneeded reports. Use the Edit menu. Either select and delete individual rows. Or select all and then delete.
11־
Analysis
55ו
OPTIMIZE BUTTON
I
Optimize
jי
Portfolio Optimization (default) Walk-Forward Optimization View 3D optimization graph Old (v4.4) Optimizer
To O P T I M I Z E is T O M A K E A N O R G A N I Z E D S E A R C H for the set of values for the parameters of a trading system that maximize the objective function you are using to compare alternative systems. There is one statement that must be added to a trading system to allow it to be optimized. var
=
Optimize ( "name" , def , min , max , step );
var is a variable in your AFL program. name is a string literal that will be used as a label when reporting. def is the default value given to var whenever the program is evaluated in a mode other than optimize. min is the minimum value of the range you wish to search. max is the maximum value of the range you wish to search. S t e p is the increment by which the value is increased for each optimization. For example, MALength = Optimize ( "MALength", 5, 1, 21, 2 );
The variable named MALength will be given values of 1, 3, 5, ... 21 in successive optimization passes. Example 8, Chapter 3, ran an optimization. Review that example now. Portfolio Optimization If you click the Optimize button without pulling down the menu to make other choices, you are asking for a portfolio optimization. Review the section on the backtest button and note that it, too, defaults to a portfolio test.
512
Introduction to AmiBroker
If you have checked use filter, clicked define, and selected a watchlist or some other list of symbols, the backtest and the optimization are carried out on that group as a portfolio. If the watchlist you have selected contains a single symbol, or if you checked use current, then your portfolio is a single issue, and the backtest or optimization is carried out on the single issue. Optimization Basics An optimization is simply a series of backtest runs, each run made with a different set of values for the parameters. If you were patient enough, you could type each variable in your program individually and make the same series of backtests. The advantage of having the optimization done by AmiBroker is that the details are handled by the program, and the results are displayed in the Results window for your evaluation. After the alternative runs have been made (whether you used the optimizer or hand-entered the values), you must decide which set of values to use; and that is a decision you must make for yourself. Your level of comfort with the system that emerges from your design and testing will reflect the method you used to choose the best alternative. The period of time, and the data associated with that period, that is processed as each of the backtest or optimization runs is made is called the in-sample data. When searching for the best set of values for the parameters, the in-sample data is being searched. The in-sample results will be good — they are always good — we do not stop working with the system until they are good. The real test is see whether those results are due to a good model that correctly identified the signal portion of the data, the patterns, rather than the noise. To make that test, change the dates to a period that follows the in-sample data and that has not been used to select the parameter values. That new data and time period is called the out-of-sample data. If the results obtained by running the system on the out-of-sample data are good, then there is a possibility that the system can, indeed, identify patterns that precede profitable trading opportunities. But please be careful. It is too easy to run an optimization (on in-sample data), pick the best values, r u n the system on the out-of-sample data, notice that an adjustment to the system would make the out-of-sample results much better, change the code for the system, and rerun the system. Every time that is done, the data that was previously out-of-sample
Analysis
513
has become increasingly in-sample. Eventually the results from both the in-sample and out-of-sample runs will be good; but that success is partially due to expanding the in-sample data set. A new, fresh, out-ofsample set of data is now required. Objective Functions AmiBroker has 20-some built-in metrics that are automatically computed and reported for each run. If the ranking produced by one of these metrics agrees with your own ranking, then you can use that metric as your objective function (also called a fitness function). If you want a custom function, you can write the AFL that describes it, tell AmiBroker to compute a score using that function for each run, and rank the results by that function. There are examples of doing that in the AmiBroker User's Guide and in Quantitative Trading Systems Most trading system development platforms do not provide the power and flexibility in creation and use of custom objective functions that AmiBroker does. In fact, most have a default objective function of net profit, and most have no way to specify any other. Unfortunately, net profit is a poor choice for an objective function. Net profit is one of the metrics that tends to perform well in-sample, but poorly out-of-sample. That is, most trading systems can be adjusted until they produce high net profit results on the in-sample data, but profit for the out-of-sample data is often poor. Better choices of metrics are those that reward equity growth while penalizing drawdown. AmiBroker has several of those as built-in metrics. They include: •
RAR/MDD - Risk adjusted Annual Return / Maximum DrawDown.
•
CAR/MDD - Compound Annual Return / Maximum DrawDown.
•
K-ratio - a metric developed by Lars Kestner.
•
RRR - Risk - Reward Ratio.
•
Ulcer Performance Index.
514
Introduction to AmiBroker
Exhaustive versus Non-Exhaustive Optimizing If you do nothing special, when you code your optimize functions and then click the optimize button, AmiBroker will use every combination of parameter values you have given - an exhaustive search. If one variable goes from 2 to 100 in steps of 2, that is 50 values; if another goes from 1 to 20 in steps of 1, that is 20 values. An exhaustive optimization would run a backtest for each of the 1000 (20 times 50) alternatives. After the 1000 runs, AmiBroker will sort them into descending order according to the metric you chose and display the results. Since every possible combination has been evaluated, the best one is at the top of the list. AmiBroker has two alternative methods of carrying out the search that will probably find the best alternative, and will do it in much less time because it does not search the entire space. The search space, as the universe of all possible combinations of parameter values is called, will have some regions where the objective function values are high, and other regions where they are low. There are some optimization methods that focus their search efforts on those areas that are more promising and skip lightly over the less promising areas. These are called nonexhaustive search methods. The two implemented in AmiBroker are: •
CMAE (Covariance Matrix Adaptation Evolutionary Strategy)
•
"Tribes" - an adaptive, parameter-less version of PSO (Particle Swarm Optimization) non-exhaustive optimizer.
Appendix C, Resources, has URLs to references for both these methods. The absolute best score of all the alternatives, and the set of values for the parameters that are associated with it, is called the global maximum. It is the best solution. An exhaustive search will find the global maximum. Other regions will have scores higher than the surrounding areas, but will not be the absolute highest. They are called local maximums. Non-exhaustive search methods sometimes find local maximums, but not the global maximum; although usually they do find the global maximum. There are advantages to using the non-exhaustive methods. •
One is that they are quicker to converge — quicker to find the region that contains the maximum. If your optimization has only a few thousand alternatives to consider, you may not
Analysis
5 ו5
notice the difference. If it has 100,000 or more, a run that would take hours or days to complete, you will definitely notice the difference. •
Another is that the algorithm used to evaluate the objective function can be clever and can take into account the surrounding points. One of the goals is to pick a set of values that score well, but that also are stable and robust. A robust area of a search space has good scores not only at the maximum, but also in the surrounding area.
To use either of these non-exhaustive methods, place a statement at the start of your program: OptimizerSetEngine("cmae"); OptimizerSetEngine("trib")
According to the literature, the cmae technique is superior. 3D Visualization If your program has exactly two variables being optimized, you can see what the response surface looks like. The response surface is the plot of the objective function in the vertical direction versus the two variables in the two horizontal directions. After running an optimization (either exhaustive or non-exhaustive), pull down the menu at the right of the optimize button and click view 3D optimization graph. The controls allow you to rotate and tilt the graph, and to raise and lower the water level. For all trading systems, the model (the AFL code) is the static representation of the underlying market it is modeling. When the model and the market are in synchronization, as they always are for the in-sample period, the objective score for the best parameter values will be high. When the underlying market shifts, as it will in the out-of-sample period, the optimal point will shift as well. A slight shift in the market has the same effect as moving the optimal peak slightly. If the new position has a lower objective score, the system will be less profitable, or unprofitable. So the best solution to the optimization is to find a region of the parameter space that not only scores well, but is robust — in the 3D view, an area that has a high score and is the top of a broad, flat, plateau.
516
Introduction to AmiBroker
3D graphics by AmiBroker
If you look at the 3D visualization and find that the best region is at one of the borders, expand the range being searched and run again — the best region may get even better in the area not tested in the first runs. Some Optimizing Tricks •
Thanks to Herman van den Bergen for contributing this technique to the AmiBroker library. You can Optimize parameters with custom number series by using the numbers generated by the Optimize() function as an index to access numbers in a custom array. Here is an example using a custom array FB[] of Fibonacci numbers: FB[0] = 0.0; FB[ 1 ] = 23.6; FB[2] = 38.2; FB[3] = 50.0; FB[4] = 61.8; FB[5] = 100; FB[6] = 161.8; FB[7] = 261.8; FB[8] = 423.6; FBindex = Optimize("FBindex",0,0,8,1);
FibNum = FB[FBindex]; ... place your Code using FibNum here ...
Analysis
•
517
Thanks to Tomasz Janeczko for this one. You can refresh your equity chart after each optimization step, and observe how the linearity of your equity curve is affected, by adding these two lines to the very end of your code: AB = C r e a t e O b j e c t ( " B r o k e r . A p p l i c a t i o n " ) ; AB.RefreshAll();
Important note: Do not use in commentary, interpretation, or indicator builder because it will cause loop. •
And thanks to Tomasz again for this. Some asked for a function that combines Param() and Optimize(). Here it is: function ParamOptimize( pname, defaultval, minv, maxv, step ) { return Optimize( pname, Param( pname, defaultval, minv, maxv, step ), minv, maxv, step ); }
518
Introduction to AmiBroker
Walk Forward To start a walk forward run, pull down the menu next to the Optimize button and select Walk-Forward Optimization. Example 9, Chapter 3, ran a walk forward. Review that example now. Background and Justification While there is nothing special about the optimization process - it is just an organized way to look at a lot of alternatives - there is something very special about the walk forward process. The walk forward process is the best tool available to you for trading system validation. While you are developing your trading system, you have access to all the data. Using your best efforts, you try to develop your system using in-sample data and test it using out-of-sample data. But what will happen when you start actually trading the system? The walk forward process can give you an idea of what might happen. In the development phase, you used the in-sample data and ran optimizations to search for patterns, then tested on out-of-sample data. The walk forward process automates this for you and provides several important things: •
It automates the process of optimizing over a set of in-sample data.
•
It automates selection of the best set of values.
•
It automates testing over the out-of-sample data.
•
For each walk forward step, it gives you a look at what happens when your system goes from in-sample to out-of-sample.
•
It gives you an idea of how long your system remains in synchronization with the market it is modeling.
•
It provides a set of out-of-sample results that you can use as a baseline to compare the actual results of your own trading.
The walk forward process is the culmination of the steps of: •
Choose your own objective function.
•
Optimize in-sample.
•
Test out-of-sample.
Note that in the walk forward process, the best set of values for the parameters is chosen, and the out-of-sample results are calculated using those values. At this point, you do not choose which set to use; you
Analysis
519
have already incorporated the criteria that are important to you into your objective function. For a deeper discussion of objective functions, see Quantitative Trading Systems. Mechanics of Walk Forward By the time you get to the walk forward stage, you have a trading system you like and you know what tradables it models well. You are looking for three things: •
How long is the in-sample period?
•
How long is the out-of-sample period?
•
What is the out-of-sample performance?
The underlying market is changing as the fundamentals upon which it is based change. These could be interest rates, the strength of the currency, the phase of the economic cycle, the profitability of the sector and of the specific company, and so forth. Your model is able to identify the important characteristics and identify profitable trading opportunities, but the model and the market drift from being in synchronization to out. The length of the in-sample period must be shorter than the period of synchronization. Your system sets its parameter values in the in-sample period and trades in the out-of-sample period. So, your system must sync-up during the in-sample period, then trade for as long as the synchronization remains strong. Open Automatic Analysis, click the Settings button, and the WalkForward tab. 1. Click Easy mode (EOD). Decide when to begin your walk forward. Of course, you must have data from the starting date to the present. But you may decide not to use all of your historical data. By using your judgement, or by running some tests, decide whether the oldest data you have has the same characteristics as the more recent data. For example, the characteristics of the entire equities market changed after October 1987, so you may not want to use data earlier than 1988. If your preferred markets ran up sharply in the late 1990s and fell off dramatically in the early 2000s, you may want to include that data, or you may want to exclude it. 2. Set your starting date in the Start box. 3. Leave Anchored unchecked.
520
Introduction to AmiBroker
Each model and market combination has a unique relationship. There is no way to tell in advance what the optimum length of the in-sample period is. You must run tests to determine it. By the time you are running the walk forward tests, you should have a very good idea of what length in-sample period to use. 4. Set that length as your in-sample length on the walk forward tab. That is, set the End date so that the length of time between Start and End is the length of your in-sample period. 5. Decide what date you want as the last day of the last in-sample period. (You may want to withhold some data from the walk-forward process, just as you withheld some data from the backtesting runs you made earlier.) Enter that date in the Last field. Alternatively, check Use today. Your system will remain profitable as long as the model and the market remain in sync during the out-of-sample period. The length you set as the step sets both the re-optimization period and the out-of-sample length. By running tests, you can determine how long, typically, the system remains profitable in the out-of-sample period. That is the Iongest you can wait between re-optimizations. 6. Set the length you want to use for your out-of-sample and re-optimization in the Step field, and use the pull-down menu to select the time increment. Backtester settings
Analysis
521
The dates that will be used for each in-sample r u n and each out-of sample run will be computed and entered into the table. Scroll up and down and review these dates. Be certain they reflect what you want. 7. Select your optimization target from the pull-down list. You should already have selected an objective function and been using it all along during your system development and backtesting. RRR is a good choice. 8. Click OK. This exits the Walk Forward setup dialog. Each of the walk forward runs is evaluated as it takes place. After an in-sample optimization, the best set of parameter values is chosen and a single test run is made using those values and that specific in-sample period. The equity curve for that in-sample run is calculated. Next, a single test run is made, using those same values, for the out-of-sample period that immediately follows. The equity curve for that out-of-sampie run is calculated. There are two reports you can watch as the walk forward runs take place. The first is the set of in-sample and out-of-sample summaries. These are produced automatically and displayed on a separate tab in the main chart window. Mode
Begin
End
No.
N e t Profit N e t % Profit Exposure %
IS
1/1/2000
1/1/2001
168
29717.14
OOS
1/1/2001
1/1/2002
1
IS
1/1/2001
1/1/2002
24
OOS
1/1/2002
1/1/2003
1
IS
1/1/2002
1/1/2003
21
OOS
1/1/2003
1/1/2004
1
4774.69
CAR 30.09
RAR Max. T r a d e
29.72
71.10
־3414.31
-3.41
64.19
־3.43
-5.35
36514.88
36.51
51.61
36.75
71.21
-5164.02
-5.16
68.65
־5.19
-7.S6
10505.40
10.51
64.00
10.57
16.51
4.77
61.45
4.80
7.81
42.32
The second is the concatenation of the in-sample equity curves and outof-sample equity curves. These are displayed in a pane of the main chart window. But you must first insert the indicator that will display
522
Introduction to AmiBroker
them. Using the charts tabbed menu, expand the equity category, rightclick IS and OOS Equity, then left-click Insert. Symbols j Layouts [ Layers
Charts
h LJ Averages 6 Q Bands שCJ Basic Charts שD Custom S-G3 Equity f Individual
m f P^fffgg^?
;
/ Portfolio Insert Linked
C J Include Si! LJ Indicators ₪ C1 IntroBook
Overlay
SsrCJ NAAIM Atlanta m CJ QTS Book
Analysis Edit
m 03 QTS Book Code & - £ 3 Systems / /
Rename
Example ExampleRotatiot
Delete New Refresh
As the walk forward progresses, you can click on the main chart tab and watch the equity curves develop. This example illustrates a classic example of a system that does well in-sample, but poorly out-of-sample. It has learned the noise, but not the signal. QQQQ - Dalty 9/6/2006 In-Sample Equity = 749,596 66, Out-Of-Sample Equity = 119,193 76 10
in-sample equity
600,000
500,000 400,000 300,000
^^^ycv^
out-of-sample equity ^ rי
" ^ V j
Ml2002""ll2003mm2004l"m2005l|״l|2006
200,000
Q
The in-sample results are (almost) always better than the out-of-sampie results. Good trading systems have out-of-sample results that rise steadily in all the out-of-sample periods, like the one shown here. QQQQ - Daily 9/8/2008 In-Sample Equity = 972,866 31. Out-Of-Sample Equity = 312,212.09 966,666
in-sample equity
606,600
766,600 860,000
500,000
...........out-of-sample •׳ M III IMI2000IIMI120011'Tli 2002
2003
-^י
equity
400,000 I B S i o 200.000
!"200811
100,000
Analysis
523
Back on the Automatic Analysis screen: 1. Select your trading system. 2. Define your watchlist. 3. Pull down the menu next to the Optimize button, click WalkForward Optimization. L Automatic Analysis - ZScoreBuyWeaknessTradingSystem.afl Formula file H C:\Program Files\AmiBrokeAFormulas\Custom\ZScoreBuyWeaknessTradingSystem.afl Range •! O oil quotations O חlast quotations Q n last d a y s ®from: • Wait for backfill (RT only)
1/ 1/2001
׳י
1/ 1/2009
v
View 3D optimization graph
P I Sync chart o n select
Old (v4.4) Optimizer
Results No. 1
T Net Profit
N e t ' / . Profit
Exposure %
CAR
RAR
<19169
419
34 86
613
1758
<
Wax Trad. -6.10584
Max. Trad -6.52
Max. Sys
T
Max S;
-16.123.17
>
N u m b e r of rows: 1
Look at the equity curves and the in-sample and out-of-sample summaries. If they look good, your system is ready for trading.
524
Introduction to AmiBroker
COMMENTARY AND INTERPRETATION You can write commentary that will appear in the Commentary window or the Interpretation window. The commentary is specific to the active symbol, the active pane, and the selected bar. The explanation for Commentary is first, then Interpretation. COMMENTARY
Using the Analysis menu, select Commentary. The commentary window has two tabs - Commentary and Formula. Use the Formula tab to enter the AFL code you want to use, and the Commentary tab to display the output. Analysis j Quick Review... J I Automatic Analysis. &
Commontary...
*
Formula Editor... 1 ^
.
AFL Code Wizard
;
Guru Chart C o m m e n t a r y - hb comm.afl Commentary
f. 1j
Apply
] |
Load
"A d o w n d a y |; ) ״
| |
Save
|
|
Close
Guru Chart Commentary - hb comm.afl Commentary
נ
Ln 3. Col 49
"The c l o s i n g p r i c e is: " + WriteVal(C); W r i t e l f (C>Ref (C,-1) , "An up day״,
[
(—1IDif3
Formula
1
L ״Q !X
Formula
M 3-
49
j T h e closing price is: 125.480 A down d a y
|
Apply
| [
Load
| [
Save
|
j
Close
j
1 1
Analysis
525
A commentary formula consists of two elements: static text and dynamic content. STATIC T E X T
Static text elements are enclosed in quotes and terminated with a semicolon. The text is displayed in the commentary window exactly as it is written. Each statement will be placed on a new line. Including the two characters "\n" will force a line break in the output whenever that is necessary (and it will be necessary in Interpretation). A simple example of static text is: "The closing price is: "; DYNAMIC CONTENT
Two AFL functions are useful for creating dynamic content: WriteValQ (or its equivalent function, NumToStr), and Writelf(). WriteVal Syntax: WriteVal(NUMBER); WriteVal(ARRAY);
Returns: STRING
Description: WriteVal does not really write anything; it converts either a number or an array to a string and returns the string value. WriteVal can only be used within a commentary. Any expression that evaluates to a number or numeric array can be uses as an argument to WriteVal. For example: WriteVal(C10se - Ref(Close,-1));
WriteVal always returns *one* value of the array (not an array of values). In almost all cases this is LastValue of the array but in indicators it is "selected value" ־the one that is selected by the vertical line.
526
Introduction to AmiBroker
Writelf - Conditional Output Syntax WriteIf(Expression, "True Text", "False Text"); Returns STRING
Description The Writelf function is very similar to the Ilf function. An expression is evaluated. If the result is True, then whatever is in the True Text string is returned. If the result is False, then whetever is in the False Text string is returned. For example: Writelf(C>Ref(C,-1), "An up day", "A down day"); C O N C A T E N A T I O N means join together by appending one to the other. The concatenation operator is "+". To join two strings together, put the "+" between them. Any expression that evaluates to a string can be concatenated into the output by using the "+" operator. For example:
"The closing price is: " + WriteVal(Close);
The calculation and nesting can be as complex as you wish. For example: Indicatorl = ...; Indicator2 = ...; Indicator3 = ...; "The indicator status today is " + Writelf(Indicator1>3, "Very Bullish", Writelf(Indicator2>12, "Bullish", Writelf(Indicator3<0, "Bearish", "Neutral" ))); USE
Commentary code is written by typing it into the Formula tab of the Commentary window; no editor is needed. The Save button opens a Save As dialog and you can save the commentary just as you would save any other AFL program. If you have already written a commentary, clicking the Load button opens a dialog box so you can locate and load the program you want to use. Click the Apply button to r u n the code. Click the Results tab to see the commentary that applies to the bar that is selected.
Analysis
527
INTERPRETATION
To convert the code you have written for the commentary window so that it appears in the interpretation window, enclose every string that is being written so that it becomes an argument to a Printf function. Syntax printf(formatstr); Returns Nothing Description Printf sends the string portion of formatstr, formatted according to the format portion of formatstr, to the output. In this case, the output is the interpretation window. The code must be appended to the AFL code of the system or function that is displayed in a pane. In order to see the output, make the pane active. The commentary output will appear in the interpretation window. As bars are selected, the output will be interpreted for each bar. In the image that follows: A. Add the commentary code to the AFL for a trading system that has a plot statement. B. Use the Apply Indicator icon to open a new pane and plot the indicator. C. Click in the pane that has the commentary code attached to it. D. Read the commentary in the Interpretation window.
528
Introduction to AmiBroker
If you click a bar, you will see the interpretation for that bar. If you click a different pane, you will see the commentary associated with that pane. PERFORMANCE T I P
To get the best performance, enclose the commands that compute the values used only by the commentary, and the statements that produce the output, in a set of braces and precede them by a conditional test. For example: If(Status("action")==actionCommentary) { // computations needed only for the commentary // WriteVal, Writelf, and Printlf statements }
This section of code will only be executed if the commentary will be visible if produced, thus saving execution time.
Chapter 10
Write It Yourself
529
530
Introduction to AmiBroker
The previous chapters have shown examples of functions, indicators, and trading systems. This chapter explains in more detail how you go about writing your own. The examples in this chapter all assume that the data is end-of-day and comes from the exchange. Forex and afterhours trading are not considered. The data bars are daily bars and have at least a closing price, perhaps open, high, and low. It can be stocks, mutual funds, exchange traded funds, or commodities - the techniques apply to all and we will not distinguish. BEFORE YOU START CODING
A few questions need answers before you start. When will you be collecting the data, running your trading system, and issuing your signals? When will you place your orders? When will the orders be executed? The answers will help you specify the BuyPrice and Trade Delay. TRADING NEXT DAY OPEN ( N D O )
Assume you have a day job and you are doing your data collection in the evening, running your trading systems in the evening, generating signals from the values of the most recent bar, placing orders in the evening, and anticipating execution at the opening price the next trading day. You must specify Trade Delay of 1. Your signals come today, your trades happen tomorrow - one day later. If you plan to issue Market On Open orders, you must specify your BuyPrice as Open. Note: If you are trading mutual f u n d s and the only price point and trading opportunity tomorrow is the close, then you must specify you BuyPrice as Close. There are two methods of telling AmiBroker about those choices.
Write It Yourself
531
The first is using Analysis > Automatic Analysis > Settings > Trades, and filling in the BuyPrice and BuyDelay. Entering your preferences there sets them as defaults. See page 486. The second is in your AFL code. L [C:\Program FHes\AmiBrokertFormulas\CustomXExampleTradi.. Eile
Edit
loote
m
Help D C f H ' • • i . R i B « ־ י: » : ExampleTrading " J ! > ׳- 3
//
ExampleTradingSystem.afl
Set // ״the T r a d e D e l a y s and B u y P r i c e i t for trading Next D a y O p e n (MDO). SetTradeDelays(1,1,1,1) ; B u y P r i c e = Open; ;SellPrice = O p e n
These lines go at the top of your code. The SetTradeDelays procedure has four numbers. They represent the trade delay for the Buy, Sell, Short, and Cover, respectively. The BuyPrice = Open; line tells AmiBroker that you want market orders executed at the open. In AmiBroker, a market order is any order that does not explicitly state a price and a condition. Buy = Cross(C,MA(C,5)); issues a market order, since no price or other condition is specified. TRADING SAME D A Y CLOSE
If you have an accurate and profitable short term trading system - one that holds only a few days - you will probably find that the price change between the close of the bar that generates your signal and the open on the next bar is in the same direction as your signal. That overnight move is often the most profitable portion of the holding period. In order to capture it, you must be able to anticipate the price that will give you a signal before the close of trading, then execute your trade and take your position on the close. Your TradeDelay is 0, and your BuyPrice is Close. There are several ways to anticipate the signal. •
Use real-time quotes, either snapshot or streaming, to estimate the closing price just before the closing time.
•
Use the formula for the code that generates your signal to precalculate what price would trigger your signal. Either enter that as a Limit On Close order, or be ready to place the order
532
Introduction to AmiBroker yourself.
•
Use a root-finding algorithm to precalculate the price necessary for any condition, whether you have the formula or not. For example, you can precalculate the price at which a moving average will cross through a 2 ATR band, and have your order ready when that condition happens. This procedure is explained in detail in Quantitative Trading Systems.
Whatever your trading delays and buy price are, if you use AFL statements to set them, the values given in the AFL override the values set in Settings. PORTFOLIO CONSIDERATIONS
You may be planning a system that trades only one thing - perhaps a broad market index. In that case, the number of positions you hold will always be either zero or one. And you need to make no special arrangements for portfolio management. You may also be planning to write several trading systems, each for a single tradable, and manage the position allocation outside AmiBroker. Again, you need no special portfolio code. You may be planing a trading system that keeps track of a universe of potential holdings - say the Fidelity Select Funds, or the S&P Sector ETFs. Your system monitors each of them every day. Whenever there is a buy signal, you want AmiBroker to take a position, but only if there is room in your holdings. In this case you do need special arrangements to handle the portfolio. There are no settings that let you manage a portfolio - this can only be done in AFL code. Expanding on the previous example, add these lines at the top of your code. File
Edit
Dtfji //
tools S
>
Help e
"י
•
E־.ampleTr.jdmq' V •_J ־
! -
ExampleTradingSystem.a£l
/, ׳׳Set the T r a d e D e l a y s and B u y P r i c e // foe t r a d i n g N e x t Day O p e n {NDO). SetTr a d e D e l a y s ( 1 , 1 , 1 , 1 ) ; B u y P r l c e = Open; S e l l P r i o e — Open; // 3et Maximvari O p e n P o s i t i o n s // and f u n d i n g a l g o r i t h m M a x P o s i t i o n s = 3; S e t O p t i o n ( " M a x O p e n P o s i t i o n a " , M a x P o s i t i o n s ); SetPositionSize( 10• / MaxPositions, spsPercentOfEguity);
A• \
Write It Yourself
533
MaxPositions = 3;
MaxPositions is not a reserved variable. It is one of your variables, and it is used so that you can easily change its value, or optimize it. SetOption("MaxOpenPositions", MaxPositions );
SetOption, using the "MaxOpenPositions" option and MaxPositions identifier, tells AmiBroker than the maximum number of open positions is found in the variable MaxPositions. SetPositionSize( 100 / MaxPositions, spsPercentOfEquity);
[The older method producing the same result is: PositionSize = -100 / MaxPositions; ] SetPositionSize tells AmiBroker how to allocate funds. If the second argument is spsPercentOfEquity, treat whatever number the first argument is as a percentage. Allocate that percentage of the equity to each new position taken. With MaxPositions having a value of 3, each new position gets 33.33% of the equity. If the second argument is spsValue, then that number of dollars will be used. If there is not enough in cash to make the full purchase, AmiBroker checks the Setting to see whether Allow Position Size Shrinking has been checked. If it has been checked, then all the remaining cash will be used to take the new position. As you progress, there are additional statements you will want to use to be certain that AmiBroker manages the system as you want it to. For now, let's move on. ENTER A LONG POSITION - BUY
The AFL statement that tells AmiBroker to issue a Buy signal is: Buy = something;
Buy is a reserved variable. It is an array and it has values for every day. Those days when your system does not generate a Buy signal, the value for that day is False, or 0. Those days when your system does generate a Buy signal, the value for that day is True, or 1. Whether the value is a 0 or a 1, False or True, depends on the result of evaluating the right hand side - the something.
534
Introduction to AmiBroker
Whenever there is a Buy Signal and no position is held, there will be a purchase. If there is already a position, the signal will be ignored. Recall that every statement of this type has an expression on the right hand side and a variable on the left hand side separated by the "=" sign. The "=" sign is the assignment operator. Processing the statement requires two steps: evaluating the right hand side so that it returns a unique result of the same type as the variable on the left hand side; then assigning that value to (or storing that value in) the variable. Since Buy needs to be assigned the value of True, or 1, whenever the system generates a Buy signal, the right hand side is usually an expression that is either True or False, 1 or 0. Some simple examples: Buy = DayOfWeek() == 2;
DayOfWeek is a built-in function that evaluates what day of the week the current bar is. It returns a value of 0 for Sunday, 1 for Monday, 2 for Tuesday, and so forth. The "==" is a comparison operator that checks what is on its left and what is on its right and returned a value of either True, the two are the same, or False, the two are different. If the bar being evaluated is Tuesday, DayOfWeek() returns 2, and the "==" operator returns True - the two are the same. So the value of True, or 1, for the right hand side is assigned to, or stored in, Buy. AmiBroker sees that Buy is True and issues a Buy signal. If you are running a backtest, a new position is taken. If you are running a scan, the report tells you that there is a new Buy signal at the close of today's bar. Buy = Cross ( C, MA(C,5) );
Cross is a built-in function that returns a value of True when the first argument, C, has a greater value after this bar than the second variable, MA(C,5); and the first variable had a lower value than the second variable after the previous bar. Said differently, Cross returns True when the first variable crosses up through the second variable. The two being compared do not
Write It Yourself
535
need to be variables; constants and expressions are also acceptable. The first variable is the current bar's close. The second variable is the current bar's 5 day simple moving average. If the close was below the 5 day moving average yesterday and is above it today, then Cross returns a True. The evaluation of the right hand side is complete and the True is assigned to Buy. A Buy Signal is generated. This is called an impulse signal. It is True for one bar, then False. After a few bars it may be True again, but only for one bar. •
Setup = C > MA(C,5); StochSignal = Cross(StochD(),30); Buy = Setup AND StochSignal;
This represents a setup and a trigger. The first line is the setup. The right hand side evaluates to True on every bar where the close is above its 5 day simple moving average. That will be one day or several days in a row. This type of signal is called a state signal. The second line evaluates to True on those bars when the StochD indicator crosses up though the 30 line. The Buy Signal is generated when both are True - the And operator evaluates to True when both its right hand side and its left hand side are true. EXIT A LONG POSITION - SELL
Sell works the same as Buy. Sell = whatever;
Whenever the right hand side evaluates to True, a Sell signal is generated. If there is a position, it will be sold. If there is no position, the signal will be ignored. Some simple examples: •
Sell = DayOfWeek() == 5;
Sell on Friday.
536 •
Introduction to AmiBroker Sell = Cross ( MA(C,5),C );
Cross is True when the first argument, MA(C,5), has a greater value after this bar than the second variable, C,; and the first variable had a lower value after the previous bar. That is, when MA(C,5) rose through C — or when C fell through MA(C,5). E X I T A LONG POSITION VIA STOP
There are several ways to exit a long position: •
A Sell signal, as was just described.
•
A timed exit, or n-bar stop.
•
A profit target, or profit stop.
•
A trailing stop.
•
A maximum loss stop.
AmiBroker has built-in stops. Review the sections of this book and the AmiBroker User's Guide for descriptions of stops. A Timed Exit For trading systems that hold only a short period - perhaps a few days - the timed exit may be valuable. This stop exits after 5 days. ApplyStop( stopTypeNBar, stopModeBars, 5 );
A Profit Target Also for systems that hold only a short period, exit when the trade has a profit. This stop exits when it can book a 5 percent profit. ApplyStop( stopTypeProfit, stopModePercent, 5 );
A Trailing Stop Trailing stops work well for positions that are held a longer time. They follow along behind a rising price - rising when the price goes up, but never declining. If the price declines enough to cross through the stop price, the position is sold. This stop, called a chandelier stop, trails at 3 times the Average True Range below the price. ApplyStop(stopTypeTrailing, stopModePoint, 3*ATR(14), True, True );
537
Write It Yourself A Maximum Loss Stop
The maximum loss stop is the last resort. Well designed systems seldom have positions exited because the price hit a maximum loss stop. This is a 15 percent maximum loss stop. ApplyStop( stopTypeLoss, stopModePercent, 15 );
W R I T E LOOPING C O D E
Often, you can do everything you want to with the functions built-in to AmiBroker. Occasionally, you need to examine the data bar-by-bar. A very simple example will be used to illustrate looping — the calculation of a 5 day simple moving average of the closing price for every bar of data. The AmiBroker code is easy: MABuiltln = MA(C,5);
To explain the looping code, a diagram will help. You will see a small box for every day of data. There is an arrow pointing to an arbitrary index position labeled i. Index i is the day having its average computed, i starts at 0, the first bar, and goes up through BarCount-1, the last bar. There is also an arrow pointing to a group of 5 bars that will be used to compute the 5 day moving average. A separate index, j, will be used to move through these 5 bars.
Close
14 3 2 01 ו
-t 0
12
3
4
5
MyOwnAvg
6 • • •
i
•••
BarCount-1
538
Introduction to AmiBroker
The AFL code to compute a 5-day simple moving average of the Close, and store that average in MyOwnAvg, is: for ( i = 0; i < 4; i++ ) { MyOwnAvg[i] = C[i];
} for ( i = 4; i < BarCount; i++ ) { Summer = 0; for ( j = 0; j <= 4; j++ ) { Summer = Summer + C[i-j];
} MyOwnAvgti] = Summer / 5;
The first for loop handles the first part of the series where there is not enough data to compute a 5 day average. MyOwnAvg is set to the same value as Close for those 4 cells. The second for loop starts at the 5th cell, the one whose index is 4 (array index numbers start at 0). And it goes up to and includes BarCount-1, the end of the series. The variable i is the index of the cell being worked on at any given time. To compute the 5 day simple moving average, the values of the current cell and the previous 4 cells are added together, then that sum is divided by 5. The third for loop does that. Note that the j variable used to add up the 5 values counts backwards; that makes the coding easier. Good programming practices strongly discourage use of specific numbers, such as 4 and 5, in programs. And it would be impractical to have to write a new program for every different moving average length. Here is the same code written using a variable for the length of the moving average: MALen = 5; for ( i = 0; i < MALen; i++ ) { My0wnAvg2[i] = C[i];
}
Write It Yourself
539
for ( i = MALen - 1; i < BarCount; i++ ) { Summer = 0; for ( j = 0; j < MALen; j++ ) { Summer = Summer + C[i-j];
} My0wnAvg2[i] = Summer / MALen; }
W R I T E A C U S T O M FUNCTION
AmiBroker has hundreds of built-in functions. But eventually you will come across an indicator or a function that you want to use that is not built-in. The code that follows implements the simple moving average again, this time as a function. // MyOwnAvgFunction.af1
II
function MACustom ( Price, Length ) { for ( i = 0; i < Length; i++ ) { Result[i] = Price[i];
} for ( i = Length - 1; i < BarCount; i++ ) { Summer = 0; for ( j = 0; j < Length; j++ ) { Summer = Summer + P r i c e [ i ־j ] ;
} Resultfi] = Summer / Length;
} return Result;
} BuiltlnAvg = MA( C, 5 ); MyOwnAvg = MACustom( C, 5 ); Plot( C, "C", colorBlack, styleCandle ); Plot( MyOwnAvg, "MyOwnAvg", colorRed, styleLine ); Plot( BuiltlnAvg, "BuiltlnAvg", colorBlue, styleLine );
540
Introduction to AmiBroker
Variable Length Parameter The MyOwnAvgFunction has two parameters - Price and Length. Price is an array, perhaps of closing prices, perhaps of some other indicator. It is expected that there will be variation among the values in that array. Length is constant throughout the calculation of the average. The next example illustrates that the length can be an array, and its elements variable. There must be some way of determining what values to put in the array. The ADX indicator is sometimes used to indicate the strength of a trend. High values of ADX correspond with long cycle periods, low values of ADX with short periods. This example uses the value of the ADX indicator as the length of the moving average. Readers will want to experiment with using other indicators of period or cycle length. // MyOwnAvgVariableFunction.af1 // function MACustomVariable ( Price, Length ) { Ignore = int( LastValue( Highest( Length ) ) ); for ( i = 0; i < Ignore; i++ ) { Result[i] = Priceji];
} for ( i = Ignore; i < BarCount; i++ ) { ThisLength = int( 0.5 * Length[i] ); Summer = 0; for ( j = 0; j < ThisLength; j++ ) { Summer = Summer + Price[i-j];
} Result[i] = Summer / ThisLength;
}
return Result;
} ADXVal = ADX( 14 ); //Plot(ADXVal,"ADXVal",colorBlue,styleLine|styleOwnScale); BuiltlnAvg = MA( C, 10 ); MyOwnAvg = MACustomVariable( C, ADXVal ); Plot( C, "C", colorBlack, styleCandle ); Plot( MyOwnAvg, "MyOwnAvg", colorRed, styleLine ); Plot( BuiltlnAvg, "BuiltlnAvg", colorBlue, styleLine );
Write It Yourself
541
This line computes how many elements at the beginning of the series should be ignored. There are more sophisticated ways to compute that, but the point is that it must be considered. Ignore = int( LastValue( Highest( Length ) ) );
Instead of Length being constant throughout, it varies. The value needed is in the cell with the same index number as the series being averaged. This line extracts the value of the variable length and makes it an integer, so it can be used as an index into the arrays. The 0.5 factor is a fudge factor. Since there is so much delay in the ADX indicator, its value is cut in half to make it more responsive. ThisLength = int( 0.5 * Length[i] );
Note how the built-in average stays about the same distance from the closing prices, but the custom average with the variable lengths tightens up when the direction is changing, and lags behind when there is a trend.
542
Introduction to AmiBroker
A Trend Following Trading System TrendFollowing.af1 Using end of day data, generating signals in the evening, placing trades for execution the next day on the open. Takes only long positions. Holds up to 3 positions. Moving average crossover to enter, moving average crossover to exit, chandelier trailing stop. Variables are set up for optimization and walk forward testing. Try this using a watchlist of the nine S&P sector exchange traded funds. This is just an example. Do Not trade this system. Do you own research. OptimizerSetEngine( "cmae" ); SetTradeDelays( 1, 1, 1, 1 ); BuyPrice = Open; SellPrice = Open; PosQty = Optimize( "PosQty", 2, 1 , 3 , 1 ); SetOption ( "maxopenpositions", PosQty ); SetPositionSize( 100 / PosQty, spsPercentOfEquity ); MALI = Optimize( "MALI", 50, 1, 51, 2 ); MAL2 = Optimize( "MAL2", 30, 2, 52, 2 ); MA1 = MA( C, MALI ); MA2 = MA( C, MAL2 ); Buy = Cross( MA1, MA2 ); Sell = Cross ( MA2, MA1 ); ATRMult = Optimize( "ATRMult", 3.75, 1, 5, 0.25 ); ApplyStop( stopTypeTrailing, stopModePoint, ATRMult * ATR( 14 ), True, True );
Write It Yourself
543
A Mean Reversion Trading System // MeanRevension.af1 // // // //
Using end of day data, generating signals just before the close, placing trades for execution the same day at the close.
// Takes only long positions. // Holds up to 3 positions. // Moving average crossover to enter, // moving average crossover to exit, // chandelier trailing stop. // Variables are set up for optimization // and walk forward testing. // Try this using a watchlist of the nine // S&P sector exchange traded funds. // This is just an example. // Do Not trade this system. // Do you own research. function zscore( price, Lookback ) { zs = ( price - MA( price, Lookback ) ) / StDev( price, Lookback ); return zs;
} OptimizerSetEngine( "cmae" ); SetTradeDelays( 0, 0, 0, 0 ); BuyPrice = Close; SellPrice = Close; PosQty = Optimize( "PosQty", 1, 1, 3, 1 ); SetOption ( "maxopenpositions", PosQty ); SetPositionSize( 100 / PosQty, spsPercentOfEquity ); ZSLength = Optimize( "ZSLength", 34, 4, 50 , 1 ); zs = zscore( C, ZSLength ); BuyLevel = Optimize( "BuyLevel", -2.0, -4.0, 0.0, 0.25 ); Buy = Cross( BuyLevel, zs ); Sell = Cross( zs, 0 ); HoldDays = Optimize( "HoldDays", 9, 1, 10, 1 ); ApplyStop( stopTypeNBar, stopModeBars, HoldDays ); ProfitPercent = Optimize( "ProfitPercent", 3, 0.5, 5, 0.25 ); ApplyStop ( stopTypeProfit, stopModePercent, ProfitPercent );
544
Introduction to AmiBroker
Feedback
We hope this book has been useful to you.
We will appreciate your feedback regarding it.
If you feel that: •
There are topics that have been particularly helpful.
•
Topics that seem to be confusing.
•
Topics that are missing or inadequately covered.
Or you just want to make a comment about something related to the book, please send an e-mail to us at: [email protected]
We cannot guarantee a personal response, but your comments will help make the next edition of this book, and our other books, better.
Thank you.
Appendix A
Glossary
accumulation
Buying is dominant over selling.
active An element of a graphical display that has the focus, or has been selected, usually by clicking on it. alpha The rate of return of an asset, relative to the market. The intercept of the regression line describing the relative rates of return of the asset and the market. argument In computer science terms, a procedure has formal parameters that describe the process being programmed, and actual arguments that are used to evaluate the procedure for a specific case. Most people are rather informal about the distinction between parameters and arguments. When the distinction is unimportant, either term may be used. array In computer science, an array is a data structure consisting of a group of elements that are accessed by indexing. In most programming languages each element has the same data type and the array occupies a contiguous area of storage. Some programming languages, includ545
546
Introduction to AmiBroker
ing AmiBroker's AFL, support array programming which generalizes operations and functions to work transparently over arrays as they do with scalars, instead of requiring looping over array members. asset sold.
A resource having economic value. A resource that is bought or
atr - average true range A measure of volatility. Computed by taking the difference between the true high (the maximum of yesterday's close and today's high) and the true low (the minimum of yesterday's close and today's low). These daily figures are averaged over some period, say 14 days. bad tick
An erroneous tick that does not represent a trade.
backtest Testing the profitability of a trading strategy on prior periods of time. bar A consolidation of all ticks received over a given period of time into a single graphic element with values for the open, high, low, and closing values during that period. beta The volatility of an asset, relative to the market. The slope of the regression line describing the relative rates of return of the asset and the market. breakout A trade at a price higher than the highest high over a given period, or lower than the lowest low over a given period. capital asset pricing model In finance, the Capital Asset Pricing Model (CAPM) is used to determine a theoretically appropriate required rate of return of an asset given that asset's non-diversifiable (systemic or market) risk. close
The price of the final tick or transaction in a bar.
commodity tract.
A basic economic good that is traded as a futures con-
constant expiration A method of computing the prices of a synthetic futures contract based on an average of all active contracts. continuous contract A synthetic futures contract constructed by splicing together individual contracts as they roll over. contract A single unit of a commodity or future, such as 42000 galIons of crude oil, traded on one of the futures exchanges.
Glossary
547
correlation A statistical measurement of the similarity of two data series, measured over a selected period of time. curve-fit The term applied to a model that fits the data points too well, probably modeling the noise rather than the signal, and unlikely to represent the general patterns in the data. database In AmiBroker, a directory holding the historical price data for the symbols in that database, and information about the charts associated with it. A layout defines how the database is used. data mining Searching data series for patterns. Sometimes a derisive term implying a search for correlated data without regard for probable underlying association. data plug-in A utility program that coordinates external database with AmiBroker. Each data vendor's data plug-in is unique to that vendor's database. day trading Buying and selling within a single trading day based on signals taken from analysis of intraday data. degrees of freedom A statistical measurement based on the relationship between the number of independent observations in a data series and the number of parameters that are estimated using that data. The number of data points minus the number of estimates is called the residual degrees of freedom. The lower the residual degrees of freedom, the less likely that the model has learned a general pattern. delayed real-time Real-time data that has been delayed, usually by about 20 minutes, before being broadcast. diffusion index An index formed by comparing the number or total amount of increases with the number or total amount of decreases over a group of tradable issues. displacement A term describing the shifting of an indicator or a graph either forward or backward in time, often to reduce the effect of the lag of the indicator. distribution
Selling is dominant over buying.
Donchian A trading system method that buys on a breakout to new highs and sells on a breakout to new lows. Based on work done by Richard Donchian in the 1970s and 80s.
548
Introduction to AmiBroker
Drag and Drop A Windows technique for moving or copying from one location to another. Left-click the material to be copied (say, an indicator) and hold the left mouse button down, drag to the location (say, a pane of a chart window), drop the material (release the left mouse button). drawdown The peak to trough decline in the value of a position or an account, usually measured as a percentage. efficient The central point of several theories of market prices and movements. Proponents of the strong form of efficiency believe that all information, whether public or private, is represented in the price of the asset at all times, and that there is no profit to be made by analyzing prices, earnings, estimates, or anything else. Quantitative analysis and technical analysis are based on the belief that the markets are sufficiently inefficient that analysis of price patterns will lead to profitable trades. end-of-day Data reported after the market has closed, and representing one day's activity. End-of-day data for stocks and futures is usually reported as a set of four data points, the opening trade, the high, the low, and the closing trade. Mutual fund data is usually only the closing price. equity curve The value of the trading account over time, often presented as a graph. evolutionary operation A search technique that fixes the values of all variables except one, and searches for the best model by varying that one. Then repeats for all other variables, and continues to cycle through until an optimum solution has been found. This method works well in industrial processes, but not for financial data. exchange The organization responsible for regulating the trading of stocks, futures, or options. exhaustive search data point.
A search technique that examines every possible
expectancy The average amount or percentage won or lost on an average trade by a trading system. The expectancy must be positive for a system to be profitable. expiration The time at which an individual futures contract or option ceases to exist.
Glossary
549
exploration The AmiBroker term for the analysis of a group of issues, resulting in a report listing information about each item. The report can contain anything that AmiBroker has access to or can compute, including indicators and buy and sell signals. exposure The percentage of time a given trading system is in a position. Whenever it is not exposed, the system has no position and is flat. external database A database maintained by a data vendor, such as Quotes Plus or Norgate Premium Data. Cannot be modified by Quote Editor. fast market Market conditions characterized by heavy trading, market imbalances, and high volatility. first notice The date when holders of futures contracts are notified that the specific contract they hold will be expiring shortly, and they need to either exit their position or prepare for delivery of the commodity that contract represents. fitness function
Objective function.
focus An element of a graphical display that is active, or has been selected, usually by clicking on it. fold A method used to develop out-of-sample periods from a set of data. The data is divided into several periods, each in turn reserved as out-of-sample data while the remaining data is in-sample. This method is not appropriate for modeling financial trading systems. forex Short for Foreign Exchange. Trading of currencies, usually as pairs with a transaction being the purchase of one currency and the simultaneous sale of the other. friction
The costs of trading - primarily slippage and commission.
front month expiration.
The futures contract that is most active and closest to
function In AmiBroker, a method of encapsulating a calculation into a single segment of code that can be called using its name. An example is the square root function. future A tradable asset that represents the future delivery of some physical commodity or financial asset.
Introduction to AmiBroker
550
future leak A future leak occurs when a trading system looks ahead to data that will not be available in real-time to make its buy and sell decisions. global When used with respect to layout — means a layout that can be used with more than one database. When used with respect to variables and functions — means variables that are defined outside the function and can be referenced inside the function. See local. high
The highest price traded for the period defined.
historical data The data series comprised of the historical records of all the individual reports for trades for an asset. holding period sell.
The amount of time a position is held from buy to
impulse signal A signal that fires (is set to True) once when an event occurs. For example Cross(C,MA(C,5)) is True (1) on the bar where the C is higher than its moving average but was not higher the previous bar; False (0), all other times. Compare with state signal. indicator A representation of some characteristic of a tradable issue. Indicators are often mathematical in nature, such as a moving average, and are displayed graphically. The states or values of indicators are key components of trading systems. in-sample During the model development process, data is divided into two sections. The in-sample data is used to develop the model, the out-of-sample data is used to verify that the model has detected patterns in the data that are predictable and profitable. intraday When referring to data bars, data that is shorter than a full day. When referring to trading, trades that are made during the trading day rather than at the open or close of trading. jackknife
Same as fold.
K-ratio A metric used to measure the goodness or fitness of a trading system developed by Lars Kestner. K-ratio is essentially the slope of the equity line divided by the standard error of the equity line. lag The amount of time or number of bars that an indicator is behind the series it has been applied to. For example, a 21 day simple moving average has a lag of 11 days - half the moving average period.
Glossary
55 ו
layout The top level of the AmiBroker structure. Layouts are associated with databases. Layouts contain windows, which contain sheets, which contain panes, which contain charts and formulas. leverage The relationship between the value of the asset being traded and the amount of money the trader has put up for that trade. Unless margin is used, stock trades are unleveraged. Futures trades are usually leveraged. limit-if-touched order An order placed with a broker that becomes a limit order when a trade occurs at the price specified. limit-on-close order An order placed with a broker that becomes a market-on-close order if the closing price is within the limit specified. limit-on-open order An order placed with a broker that becomes a market-on-open order if the opening price is within the limit specified. limit order An order that is placed with a broker to buy at a price below the lowest offer, or to sell at a price above the highest bid. linear scale Equal distances on the graph represent equal increments. Compare with logarithmic. local When used with respect to layout, means a layout that can be used with only one database. When used with respect to variables and functions, means variables that are defined inside the function and cannot be referenced outside the function. See global. logarithmic equal distances on the graph represent equal percentage changes. Compare with linear. long low
A long position has purchased the asset, but not yet sold it. The lowest price traded for the period defined.
market When referring to orders to buy or sell, a market order is executed at the current offer or bid. When referring to tradable assets in general, the market is the broad category to which the tradable belongs. market order An order placed with a broker to buy or sell at the current offer or bid price. market-if־touched order An order placed with a broker that becomes a market order when a trade occurs at the price specified.
552
Introduction to AmiBroker
market-on־close order the closing price.
An order placed with a broker to buy or sell at
market-on-open order the opening price.
An order placed with a broker to buy or sell at
mean
The arithmetic average.
mean reversion A trading system method based on an expectation that prices return to a mean level. Mean reversion systems buy weakness and sell strength. metric A measure. The term is often used when discussing the fitness of a trading system. model The idea or method that becomes the computer code portion of a trading system. Monte Carlo A technique used in system validation that makes repeated selections from random data to test the stability and sensitivity of trading systems. native database The database that AmiBroker maintains. Can be modified by Quote Editor. object linking and embedding (OLE) A technique in Microsoft's Component Object Model that allows one program to delegate part of a task to another program, then re-import the results. objective function A single-valued measurement of the fitness of a trading system. Optimization techniques are guided by maximizing the value of the objective function. one-cancels-all order A set of orders placed with a broker. When any one of the orders is executed, all of the others are canceled. ohlc The four data points associated with a bar of data - open, high, low, and close. open
The first price traded for the period specified.
open interest ist.
For futures contracts, the number of contracts that ex-
optimal f A position sizing technique based on methods developed by Ralph Vince that computs the optimal number of contracts to hold for any given trade in order to maximize future account equity.
Glossary
553
optimization The organized search of alternative values of variables in a trading system. outlier A legitimate data point that is outside the normal range of data points. out-of-sample During the model development process, data is divided into two sections. The in-sample data is used to develop the model, the out-of-sample data is used to verify that the model has detected patterns in the data that are predictable and profitable. parameter In computer science terms, a procedure has formal parameters that describe the process being programmed, and actual arguments that are used to evaluate the procedure for a specific case. Most people are rather informal about the distinction between parameters and arguments. When the distinction is unimportant, either term may be used. pattern system A trading system based on the assumption that recognizable price patterns precede opportunities to make profitable trades. perpetual contract
The same as continuous contract.
pessimistic return ratio A metric designed by Ralph Vince that attempts to estimate the out-of-sample performance of a trading systems by adjusting statistics measured from in-sample performance. phantom signal A phenomenon of walk-forward testing (or trading systems that have future leaks) where a signal or position changes without warning. real-time When referring to price quotations, data that is reported and broadcast as soon after the transactions take place as is possible. regression A modeling technique that computes the best fit of a line or curve to the data. rollover Rollover takes place when one futures contract expires, or drops off significantly in volume, and the next in time sequence becomes the front month. scalar
A variable that takes only a single value. Compare with array.
scan In AmiBroker, running a program that checks the group of tickers for signals.
554
Introduction to AmiBroker
seasonality system A trading system based on the premise that prices move up or down at predictable times of the day month, year, or other time period. selected An element of a graphical display that has the focus, or has been made active, usually by clicking on it. sensitivity A technique used in modeling to test the ability of the model to detect general patterns. Values of parameters are changed by small amounts to see if the fitness values remain at or near optimum. Sharpe ratio A measure of performance based on the ratio of the return of the portfolio to the standard deviation of the return. The return is adjusted to be the excess return minus a risk-free rate, such as short term treasury bills. short A short position has sold the asset, and will need to purchase it back later to close out the trade. signals A trading system analyzes the data according to its rules and issues buy and sell signals. snapshot data Snapshot data is real-time, or delayed real-time, data that is checked periodically intraday, but does not contribute toward building a real-time intraday database. Sortino ratio A measure of market risk similar to the Sharpe ratio, but using only the downside volatility in the denominator rather than the standard deviation. standard deviation A statistical measure of the variability or volatility of a set of data. The square root of the variance. standard error A statistical measure of variability somewhat similar to the standard deviation, but based on repeated measurements. The standard error can be thought of as the standard deviation of the means of repeated samples. state signal A signal that remains set to True as long as the condition tested remains True. For example: C>MA(C,5) will be True (1) on every bar where the close is above its moving average. Compare with impulse signal. stationary The statistical concept that the characteristics of the data being modeling change very little over time. Financial time series are notoriously non-stationary.
Glossary
555
stop and reverse A trading method where the exit from a long trade signals the entry to a short trade, and the exit from a short trade signals the entry to a long trade. The system is always in a position. stop order An order placed with a broker to buy or sell at the market when a trade occurs at the price specified. stop limit order An order placed with a broker to trade, but only at a limit price, when the market trades at the price specified. survivor bias Optimistic bias introduced into tests of historical data due to the fact that failed organizations drop out of existence and are no longer in the database. symbol space Just as the range of values for any variable being optimized can be thought of as a numeric space, the range of tickers available for testing can be thought of as the ticker space or symbol space. synchronization Agreement between a profitable trading model, written in AFL, and the data the model processes. When the two are in sync, the system remains profitable. system A trading system, in the context of this book, is a combination of a model and one or more data streams. tick The report of a single transaction. Also, the minimum upward or downward movement in the price of a security. toolbar A narrow panel in a graphical user interface where buttons and icons can be placed. tooltip A window that pops up displaying information about the data at the cursor's location. tradable Any asset that can be bought and sold, and modeled as a component of a trading system. trading frequency The number of times per day, month, or year that a trading system issues buy or sell signals. trading range Every market can be characterized as being in either trending mode, where prices predominantly move in one direction, or a trading range mode, where prices return to the recent average. trailing stop For a long position, the trailing stop rises as the price and the trade's profit rises, but never drops back when the price falls.
Introduction to AmiBroker
556
If the price drops to the level of the trailing stop, a market order to exit the position is issued. trend Every market can be characterized as being in either a trending mode, where prices predominantly move in one direction, or a trading range mode, where prices return to the recent average. trend following A trading system method that recognizes that the market is in a trending mode and takes a position in the direction of that trend. Trend following systems buy strength and sell weakness. Treynor ratio A risk adjusted measure of return for a trading system similar to the Sharpe ratio, but using beta as the measure of volatility instead of standard deviation. true high
The maximum of today's high and yesterday's close,
true low
The minimum of today's low and yesterday's close,
true range
True high minus true low.
ulcer index A metric that uses the depth and length of drawdowns as a measure of the performance of a trading system. validation Validation is the process of applying statistical tests to data from the out-of-sample trading to estimate the likelihood that a trading system will be profitable in the future. VAMI Value Added Monthly Index - a measure of portfolio performance based on monthly changes in the portfolio equity. variance A statistical measure of variability or volatility of a set of data. The sum of the squared deviations of the individual data points from their mean. volume riod.
The number of shares or contracts traded over a given pe-
walk forward The technique of repeatedly optimizing over an insample period, testing over an out-of-sample period, and moving both periods forward in time. The concatenated results from the out-of-sampie periods are used to estimate the likelihood of future profitability. watchlist A list of symbols that you create and store in one of the watchlists in the symbols tree. Use the watchlist to restrict the group of symbols that are processed in automatic analysis.
Appendix B
Industries and Sectors
557
558 Industry
Introduction to AmiBroker Industry Code
Advertising Aerospace & Defense Air Courier Airline Apparel/Accessories Appliance & Tool Audio & Video Equipment Auto & Truck Manufacturers Auto & Truck Parts Beverages (Alcoholic) Beverages (Non-Alcoholic) Biotechnology & Drugs Broadcasting & Cable TV Business Services Casinos & Gaming Chemical Manufacturing Chemicals - Plastics & Rubber Coal Communications Equipment Communications Services Computer Hardware Computer Networks Computer Peripherals Computer Services Computer Storage Devices Conglomerates Constr. - Supplies & Fixtures Constr. & Agric. Machinery Construction - Raw Materials Construction Services Consumer Financial Services Containers & Packaging Crops Electric Utilities Electronic Instruments & Controls Fabricated Plastic & Rubber Fish/Livestock
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
Sector
Sector Code
Services Capital Goods Transportation Transportation Consumer Cyclical Consumer Cyclical Consumer Cyclical Consumer Cyclical Consumer Cyclical Consumer/Non-Cyclical Consumer/Non-Cyclical Healthcare Services Services Services Basic Materials Basic Materials Energy Technology Services Technology Technology Technology Technology Technology Conglomerates Capital Goods Capital Goods Capital Goods Capital Goods Financial Basic Materials Consumer/Non-Cyclical Utilities Technology Basic Materials Consumer/Non-Cyclical
8 1 10 10 3 3 3 3 3 4 4 7 8 8 8 0 0 5 9 8 9 9 9 9 9 2 1 1 1 1 6 0 4 11 9 0 4
Industries and Sectors Food Processing Footwear Forestry & Wood Products Furniture & Fixtures Gold & Silver Healthcare Facilities Hotels & Motels Insurance (Accident & Health) Insurance (Life) Insurance (Miscellaneous) Insurance (Prop. & Casualty) Investment Services Iron & Steel Jewelry & Silverware Major Drugs Medical Equipment & Supplies Metal Mining Misc. Capital Goods Misc. Fabricated Products Misc. Financial Services Misc. Transportation Mobile Homes & RVs Money Center Banks Motion Pictures Natural Gas Utilities Non-Metallic Mining Office Equipment Office Supplies Oil & Gas - Integrated Oil & Gas Operations Oil Well Services & Equipment Paper & Paper Products Personal & Household Prods. Personal Services Photography Printing & Publishing Printing Services Railroads Real Estate Operations Recreational Activities
37 38 39 40 41 42 43 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
Consumer/Non-Cyclical Consumer Cyclical Basic Materials Consumer Cyclical Basic Materials Healthcare Services Financial Financial Financial Financial Financial Basic Materials Consumer Cyclical Healthcare Healthcare Basic Materials Capital Goods Basic Materials Financial Transportation Capital Goods Financial Services Utilities Basic Materials Technology Consumer/Non-Cyclical Energy Energy Energy Basic Materials Consumer/Non-Cyclical Services Consumer Cyclical Services Services Transportation Services Services
559 4 3 0 3 0 7 8 6 6 6 6 6 0 3 7 7 0 1 0 6 10 1 6 8 11 0 9 4 5 5 5 0 4 8 3 8 8 10 8 8
560
Introduction to AmiBroker
Recreational Products Regional Banks Rental & Leasing Restaurants Retail (Apparel) Retail (Catalog & Mail Order) Retail (Department & Discount) Retail (Drugs) Retail (Grocery) Retail (Home Improvement) Retail (Specialty) Retail (Technology) S&Ls/Savings Banks Schools Scientific & Technical Instr. Security Systems & Services Semiconductors Software & Programming Textiles - Non Apparel Tires Tobacco Trucking Waste Management Services Water Transportation Water Utilities
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
Consumer Cyclical Financial Services Services Services Services Services Services Services Services Services Services Financial Services Technology Services Technology Technology Consumer Cyclical Consumer Cyclical Consumer/Non-Cyclical Transportation Services Transportation Utilities
3 6 8 8 8 8 8 8 8 8 8 8 6 8 9 8 9 9 3 3 4 10 8 10 11
Appendix C
Resources
561
562
Introduction to AmiBroker
AMIBROKER DIRECTORY STRUCTURE
C:\Program Files AmiBroker ADK AmiQuote ASX-PremiumData Data DataAsDistributed Formats Formulas Averages Bands Basic Charts Custom Drag-Drop Equity Include Indicators Intro Book Systems Intraday IQ Realtime Layouts Notes Plugins QP End of Day QP Realtime Reports Scripts
Application Dev Kit (C++) AmiQuote Program Database Norgate EOD Database Yahoo EOD Database Yahoo EOD For ASCII Import AFL code Built-in Built-in Built-in Your code Built-in Built-in Built-in Built-in Code for this book Built-in Database AN Intraday Database DTN IQ Real-time Layout definitions Notes you write Built-in Database Quotes Plus EOD Database Quotes Plus Real-time Reports from AA Scripts to run
Template WEB SITES
AmiBroker Home page: http://www.amibroker.com AmiBroker Knowledge Base (provided by AmiBroker): http://www.amibroker.com/kb/ AmiBroker Newsletter archives: http://www.amibroker.com/newsletter/ AmiBroker On-line User's Guide: http://www.amibroker.com/gnide/ AmiBroker On-line Video Tutorials (one example of many): http://w1vw.amibroker.com/video/uicustomize.html AmiBroker Order page: http://www.amibroker.com/order.html AmiBroker Support page: http://www.amibroker.com/support.html AmiBroker User's Knowledge Base (provided by user community) http://www.amibroker.org/userkb/
AddToComposite document: http://www.amibroker.org/3rdparty/IntroToAtc.pdf AN Futures: http://www.anfutures.com/ AStyle.dll: http://www. amibroker. com/bin/astyle. dll Blue Owl Press (publisher of this book): http:Hwww.blueowlpress.com Custom Backtest Procedure document: http://www. am ibroker. org/userkb/2008/03/16/ amibroker-custom-backtester-interface-2/ DebugView: http://www.sysinternals.com/utilities/debugview.html
563
564
Introduction to AmiBroker
DTN IQ Feed: http://www. iqfeed. net Format specifiers for printf statement: http://msdn2. microsoft. con/en-us/library/56e442dc(VS. 80). aspx Graphics pens, from Microsoft: http://msdn2.microsoft.com/en-us/library/ms535467 HSB color space: http://en.wikipedia.org/wiki/HSB_color_space Interactive Broker's stop operation: http://www.interactivebrokers.com/en/trading/orders/ stop.php?ib_entity=uk http://www.interactivebrokers.com/en/trading/orders/ trailingstops.php?ib_entity=uk Interactive Broker's Trading Interface: http://www.amibroker.com/download.html Introduction to AmiBroker Resource Links: http://www.introductiontoamibroker.com/resources Norgate Premium Data: http://www.premiumdata.net Norgate Premium Data - AmiBroker plug-in: http://www.premiumdata.net/support/amibroker.php Optimization using the Covariance Matrix Adaptation Evolutionary Strategy (CMA-ES): http://www.bionik.tu-berlin.de/user/niko/cmaesintro.html http://www.bionik.tu-berlin.de/user/niko/cec2005.html Optimization using the "Tribes" method of Particle Swarm Optimization (PSO): http://www.particleswarm.info/Tribes_2006_Cooren.pdf Quantitative Trading Systems: http://www.quantitativetradingsystems.com Quotes Plus: http://www.qp2.com/joomla/index.php
Template RGB color space: http://en.wikipedia.org/wiki/RGB_color_model Russell Investments, home of Russell 1000 and Russell 2000: http://www.rnssell.com Windows API QueryPerformanceCounter information: http://support, microsoft. com/?id=896256 Yahoo AmiBroker Forum: http://finance.groups.yahoo.com/group/amibroker Yahoo Financial site: http://finance.yahoo.com/
INDUSTRIES.JS SCRIPT PROGRAM /*
** * * AmiBroker/Win32 scripting Example ** ** ** ** ** **
File: Industries.js Created: Tomasz Janeczko, November 26th, 2000 Last updated: Tomasz Janeczko, December 17th, 2000 Purpose: Import industy assignments Language: JavaScript (Windows Scripting Host)
** The data is stored in lines with following format ** * * ,, */
WScript.Echo( "Script Started" ); /* change this line according to your data file name */ ImportStocks("r1OOOfullname.txt"); WScript.Echo( "Finished" ); function ImportStocks( filename ) { var var var var var
fso, f, r; ForReading = 1; AmiBroker; fields; stock;
565
Introduction to AmiBroker
566
/* Create AmiBroker app object */ AmiBroker = new ActiveXObject( "Broker.Application" ); /* ... and file system object */ fso = new ActiveXObject( "Scripting.FileSystemObject" ); ASCII file */ filename, ForReading); f/* = open fso.OpenTextFile( i = 1; /* read the file line by line */ while ( !f.AtEndOfStream ) { r =
f.ReadLine();
/* split the lines using comma as a separator */ fields = r.split(","); try { I* add a ticker - this is safe operation, in case that ticker already exists, AmiBroker returns existing one */ stock = AmiBroker.Stocks.Add( fields[ 0 ] ); stock.FullName = fields[ 1 ]; stock.IndustrylD = parselnt( fields[ 2 ] );
}
catch( e ) { WScript.echo( "There is a problem in line no." + i + ".\nThe line looks as follows:\n'" + r + "'\nlt will be skipped and next lines will be processed as normal" ); i++; /* refresh ticker list and windows */ AmiBroker.RefreshAll();
}
Appendix D
Schematic Diagram
567
568
Introduction to AmiBroker
Thanks to Robert Grigg, a colleague from Australia, who campaigns tireless — spreading the word about the importance of using proper trading system design and testing techniques. Robert has graciously permitted use of his AmiBroker Schematic diagram. The schematic illustrates the relationships among and between the major components of AmiBroker. Although it is labeled unofficial, Tomasz Janeczko has complemented its accuracy.
An AmiBroker Schematic
(not official) What components are in AmiBroker?
OL• &
w*a
g«n»ratlon
icriprti
Editor
Low
Opt m l u t i >n
-•vol a apM• >
txr
Rfporflng SharU
fusion B>׳l O M M M
jcsv)
plor»1 on Scan:
f. •nagi
hn
E ackta* tor
zx:
hH
<
Imports
|
r0foert@cfok«. c o m ^ u Copp&xt
&
Qrys&at &b9 tW RylM
2008
Index
569
570
Introduction to AmiBroker
#include - preprocessor include, 443 #include_once - preprocessor include, 444 #pragma - set preprocessor options, 444 = ( a s s i g n m e n t operator), 253 == ( e q u a l i t y test), 2 5 3 _ D E F A U L T _ N A M E - r e t r i e v e d e f a u l t n a m e of plot, 339 _ N - n o text o u t p u t , 339 P A R A M V A L U E S - r e t r i e v e p a r a m v a l u e s string, 340 S E C T I O N B E G I N - s e c t i o n b e g i n marker, 340 _ S E C T I O N _ E N D - s e c t i o n e n d marker, 341 _ S E C T I O N _ N A M E - retrieve c u r r e n t s e c t i o n n a m e , 341 _TRACE - print text to s y s t e m d e b u g v i e w e r , 476 3 D v i s u a l i z a t i o n , 515
ABI - a b s o l u t e b r e a d t h i n d e x , 205 a b s - a b s o l u t e v a l u e , 275 A b s o l u t e b r e a d t h i n d e x , 205 A c c D i s t - a c c u m u l a t i o n d i s t r i b u t i o n , 206, 304 account manager, 9 account margin, 486 a c c u m u l a t i o n d i s t r i b u t i o n , 206 a c c u m u l a t i o n s w i n g , 207 a c o s - a r c c o s i n e f u n c t i o n , 275 activate s t o p s i m m e d i a t e l y , 4 8 5 active p a n e , 117 a d d all r e s u l t s to w a t c h l i s t , 5 0 2 a d d artificial f u t u r e bars, 490 add selected results to watchlist, 502 A d d C o l u m n - a d d n u m e r i c e x p l o r a t i o n c o l u m n , 319, 495 A d d T e x t C o l u m n - add text e x p l o r a t i o n c o l u m n , 320 AddToComposite, 300 A D L i n e - a d v a n c e d e c l i n e , 206, 301 A D P r i c e - W i l l i a m s a d v a n c e d e c l i n e , 206 A D R a t i o - a d v a n c e d e c l i n e ratio, 206 A D X - d i r e c t i o n a l m o v e m e n t , 207, 3 0 4 advance decline line, 206 ratio, 206 W i l l i a m s , 206 a d v a n c e d m o d e , 491 A d v l s s u e s - a d v a n c i n g i s s u e s , 301 A d v V o l u m e - a d v a n c i n g i s s u e s v o l u m e , 302 A F L ( A m i B r o k e r F o r m u l a L a n g u a g e ) , 241-476 editor see formula editor overview, 6 A F L c o d e w i z a r d , 146
Index AFL f u n c t i o n reference, 150 AFL library, 150 alerts, 7 , 1 7 2 Alertlf - trigger alert, 394-395 a l l o w p o s i t i o n s i z e s h r i n k i n g , 485 a l l o w s a m e bar exit, 485 A l m o s t E q u a l - r o u n d i n g error i n s e n s i t i v e c o m p a r i s o n , 276 A l t m a n , Roger, 215, 312 A M A - a d a p t i v e m o v i n g average, 285 A M A 2 - a d a p t i v e m o v i n g average, 285 A m i Q u o t e , 15 AN Futures, 41 a n c h o r e d , 491, 519 a n n u a l interest rate, 486 analysis, 477-528 a n a l y s i s p u l l - d o w n m e n u , 114,146 A n d r e w s pitchfork, 158 A p p e l , Gerald, 212 apply indicator, 245 icon, 85 apply to, 4 8 2 A p p l y S t o p - a p p l y built-in stop, 3 9 6 - 4 0 0 a r g u m e n t s , 259 call by n a m e , 259 call by reference, 259 call by value, 259 A r m s , Richard, 220 A r m s i n d e x , 220 array p r o c e s s i n g , 242, 249-251 s u b s c r i p t operator, 256 A s c - get ASCII c o d e of character, 386 ASCII data, 23 import, 2 3 - 3 0 ASI - a c c u m u l a t i o n s w i n g , 207 asin - a r c s i n e f u n c t i o n , 277 astyle.dll, 244 atan - a r c t a n g e n t f u n c t i o n , 277 a t a n 2 - a c r t a n g e n t of y/x, 2 7 7 ATR - a v e r a g e true range, 208, 3 0 5 a u t o - h i d i n g m e n u s , 160 a u t o m a t e d trading, 8 a u t o m a t i c a n a l y s i s , 73-104, 146, 481-523 c o n t e x t m e n u , 502-507 a u t o - u p d a t e q u o t e s , 147 average adaptive, 285 d i s p l a c e d , 195 d o u b l e e x p o n e n t i a l , 196, 286 e x p o n e n t i a l , 196, 287 s i m p l e m o v i n g , 195, 287 triple e x p o n e n t i a l , 196, 288 w e i g h t e d , 198, 288 Wilders, 197, 288
571
572
Introduction to AmiBroker
a v e r a g e true range, 208 a x e s a n d grids, 125
backtest, 78-102, 245 button, 496-501 i n d i v i d u a l , 496-501 portfolio, 87-90, 496-501 backtesting, 7 B a r C o u n t , 250, 256 B a r l n d e x - g e t z e r o - b a s e d bar n u m b e r , 3 4 2 bar interval, 119 bar replay, 147 BarsSince, 401 BBandBot - Bollinger band bottom, 305 B B a n d T o p - B o l l i n g e r b a n d top, 305 b e f o r e y o u start c o d i n g , 530 B e g i n V a l u e - v a l u e at b e g i n n i n g of range, 3 4 2 beta, 208 block, 256 block d i a g r a m , 110-111 Bollinger b a n d s , 198 John, 198 b r e a d t h thrust, 209 built-in f u n c t i o n s , 256 b u y a n d s e l l a r r o w s , 82-84 b u y delay, 4 8 7 b u y price, 486
c a l c u l a t e c o m p o s i t e s , 145 capital a s s e t p r i c i n g m o d e l , 230 c a s c a d e w i n d o w s , 149 category, 22, 1 4 5 , 1 6 5 , 1 7 7 a s s i g n m e n t , 168 g r o u p , 177 i n d u s t r y , 177 market, 177 m e m b e r s h i p , 177 sector, 177 w a t c h l i s t , 178-189 C a t e g o r y A d d S y m b o l , 361 C a t e g o r y F i n d , 362 C a t e g o r y G e t N a m e , 362 C a t e g o r y G e t S y m b o l s , 363, 366 C a t e g o r y R e m o v e S y m b o l , 364 CCI - c o m m o d i t y c h a n n e l i n d e x , 210, 306 ceil - c e i l i n g v a l u e , 278 Chaikin Marc, 210, 2 2 2
Index oscillator, 210, 306 volatility, 2 2 2 chart analysis, 230 chart area, 114 chart colors, 124 c o n t e x t m e n u , 122-130 default, 117 e x a m p l e 1, 57-60 n e w , 131 pane, 122 p e r i o d s , 124 properties, 129-130 sheets, 115 structure, 107-111 title, 115 c h a r t i n g , 5, 230 charts tabbed m e n u , 65,114, 190 charts (formulas), 190-225 adjust scale, 194 a n a l y s i s , 169 c h a n g e p a r a m e t e r s , 193 delete, 191 drag a n d drop, 191 insert, 1 6 8 , 1 9 0 insert l i n k e d , 168,191 overlay, 169,192-193 charts, v i e w , 137 c l e a n u p database, 148 C l i p b o a r d G e t - retrieve c o n t e n t s of W i n d o w s c l i p b o a r d , 4 4 5 C l i p b o a r d S e t - c o p i e s text to W i n d o w s c l i p b o a r d , 4 4 6 C M A E o p t i m i z a t i o n , 514 c o d e c h e c k & profile, 245 ColorHSB - s p e c i f y color, 446 ColorRGB - s p e c i f y color, 4 4 7 colors, chart, 124 c o m m e n t a r y , 146,171, 524-528 c o m m e n t s , 252 c o m m i s s i o n s and rates, 486 c o m m o d i t y c h a n n e l i n d e x , 210 c o m p o u n d statement, 256 c o n d i t i o n a l if, 256 configurability, 8 Correlation, 289 c o s - c o s i n e f u n c t i o n , 278 c o s h - h y p e r b o l i c c o s i n e f u n c t i o n , 279 cover delay, 487 cover price, 486 CreateObject - create C O M object, 4 4 8 CreateStaticObject - create static C O M object, 4 4 8 Cross, c r o s s o v e r check, 401 crosshair, 135
573
574
Introduction to AmiBroker
CSI data, 31 C u m - c u m u l a t i v e s u m , 286 custom, 203 cycles, 158
d a i l y v i e w icon, 5 9 d a i l y v o l u m e , 211 data b a s e s , 5 a d d s y m b o l s , 21 block d i a g r a m , 14 c l e a n u p , 148 c o n f i g u r a t i o n , 33, 42, 49 d e f a u l t (DATA), 13 e n d - o f - d a y , 14, 31-40 e x t e r n a l , 14 free, 15 intraday, 41-54 native, 14 n e w , 131 o p e n , 132 plug-in, 14 p u r i f y , 147 real-time, 41-54 save, 132 s e t t i n g s , 132 updates, 22 data f e e d s , 4 data date format, 23 d e l a y e d real-time, 4 3 D T N IQ, 4 8 - 5 2 e n d - o f - d a y , 31-40 fields, 28 free, 15, 23, 41 historical, 25 import, 23 m s n , 15, 2 3 N o r g a t e P r e m i u m Data, 3 5 - 4 0 Q u o t e s Plus, 31-35, 4 4 - 4 7 real-time, 4 4 - 5 4 research, 25 s u b s c r i p t i o n , 31 tick, 5 3 - 5 4 y a h o o , 15, 23 date format, 2 3 function, 343 m e n u , 478 d a t e / t i m e axis, 115, 118, 125 D a t e N u m - date number, 344 DateTime - e n c o d e d date time, 344
Index D a t e T i m e C o n v e r t , 345 DateTimeToStr - c o n v e r t d a t e t i m e to string, 386 D a y - d a y of the m o n t h , 346 D a y O f W e e k , 346 DayOfYear, 347 Declssues - declining issues, 302 D e c V o l u m e - d e c l i n i n g i s s u e s v o l u m e , 302 default chart, 117 delete indicator, 191 q u o t a t i o n , 134 s e s s i o n , 134 d e l i s t e d securities, 35 delivery, 9 D E M A - d o u b l e e x p o n e n t i a l m o v i n g average, 196, 286 d e t a i l e d log, 489 d e t r e n d e d price oscillator, 211 d i r e c t i o n a l m o v e m e n t , 207 disable trade s i z e limit, 490 discussion forum, 20 d i s p l a c e d m o v i n g average, 195 d i s p l a y n e w price series, 116 D i s p M A - d i s p l a c e d m o v i n g average, 195 d o u b l e e x p o n e n t i a l m o v i n g average, 196 D P O - d e t r e n d e d price oscillator, 211 drag a n d drop, 191 d r a w toolbar, 114 drop-down menus see pull-down menus D T N IQ Feed, 48-52 DVI - d a i l y v o l u m e , 211 d y n a m i c market, 235
e a s e of m o v e m e n t , 211 e a s y alerts, 174 e a s y m o d e EOD, 491 e a s y m o d e intraday, 491 edit p u l l - d o w n m e n u , 114, 134 efficient m a r k e t h y p o t h e s i s , 230 E M A - e x p o n e n t i a l m o v i n g average, 196, 287 e n a b l e c u s t o m backtest p r o c e d u r e , 490 EnableRotationalTrading, 402-403, 414 EnableScript - e n a b l e s c r i p t i n g e n g i n e , 449 EnableTextOutput - e n a b l e text o u t p u t to c o m m e n t a r y w i n d o w , 449 EncodeColor, 320 EndValue - v a l u e at e n d of range, 347 EOM - e a s e of m o v e m e n t , 211 equity button, 508-509 curve, 78, 85-86, 203 function, 404
575
576
Introduction to AmiBroker
IS a n d O O S , 204 p o r t f o l i o , 89-90, 204 e x a m p l e 1 - chart a stock, 57-60 e x a m p l e 2 - a p p l y a t r e n d l i n e , 61-64 e x a m p l e 3 - plot a m o v i n g average, 6 5 - 6 8 e x a m p l e 4 - m a k e a w a t c h l i s t , 69-71 e x a m p l e 5 - r u n an e x p l o r a t i o n , 72-77 e x a m p l e 6 - r u n a s i n g l e s t o c k backtest, 78-86 e x a m p l e 7 - r u n a p o r t f o l i o backtest, 87-90 e x a m p l e 8 - o p t i m i z e a t r a d i n g s y s t e m , 91-97 e x a m p l e 9 - p e r f o r m w a l k f o r w a r d v a l i d a t i o n , 98-102 e x a m p l e 10 - s c a n for b u y a n d sell s i g n a l s , 103 exitatstop, 396 e x p - e x p o n e n t i a l f u n c t i o n , 279 e x p l o r e button, 4 9 3 - 4 9 5 e x p o n e n t i a l m o v i n g average, 196 e x p l o r a t i o n , 7, 72-77, 245, 4 9 3 - 4 9 5 export, 508 expression, 253 ExRem - remove excess signals, 405 E x R e m S p a n - r e m o v e e x c e s s s i g n a l s s p a n n i n g g i v e n n u m b e r o f bars, 406
f c l o s e - c l o s e a file, 378 f d e l e t e - d e l e t e a file, 378 feedback, 544 feof - t e s t s for e n d of file, 379 FFT - fast Fourier t r a n s f o r m , 294 f g e t s - g e t a s t r i n g f r o m a file, 380 f g e t s t a t u s - retrieve file status, 381 Fibonacci toolbar, 114 file button, 508 file p u l l - d o w n m e n u , 114 filter s e t t i n g s , 76, 479 filter s t a t e m e n t , 493, 495 find (symbol), 143 fitness function, 94 flags, 269-270 Flip - create state s i g n a l s f r o m i m p u l s e s i g n a l s , 406 f l o o r - floor v a l u e , 279 f l o w control, 261 break, 262 c o n t i n u e , 262 do ... w h i l e , 261, 263-264 for, 261, 264 if ... else, 261, 265-266 s w i t c h , 261, 266-267 w h i l e , 261,268 f m k d i r - m a k e a directory, 382 f o p e n - o p e n a file, 3 8 3 f o r e i g n , 200 f u n c t i o n , 372-373
Index f o r m a t D a t e T i m e , 319 formatChar, 319 f o r m u l a file, 481 format p u l l - d o w n menu, 114,131,141 format toolbar, 114 f o r m u l a editor, 72, 78, 127,146, 242, 243-248 Fosback, N o r m a n , 205, 213, 215 f p u t s - w r i t e a s t r i n g to a file, 3 8 4 frac - fractional part, 280 f r m d i r - r e m o v e a directory, 385 F u l l N a m e - f u l l n a m e of s y m b o l , 365 f u n d a m e n t a l a n a l y s i s , 230 f u t u r e leak, 245 f u t u r e s m o d e , 485
G a p D o w n , 296 G a p U p , 296 g e n e r a l tab, 4 8 4 - 4 8 6 g e n e r a t e d e t a i l e d r e p o r t s for e a c h s y m b o l , 489 GetBacktesterObject, 407 G e t B a s e l n d e x - retrieve s y m b o l for relative s t r e n g t h base, 374 G e t C a t e g o r y S y m b o l s , 366 G e t C u r s o r M o u s e B u t t o n s ־get c u r r e n t state of m o u s e buttons, 306 G e t C u r s o r X P o s i t i o n - g e t c u r r e n t X p o s i t i o n of m o u s e pointer, 3 0 7 G e t C u r s o r Y P o s i t i o n - get current Y p o s i t i o n of m o u s e pointer, 307 GetChartID, 321 G e t D a t a b a s e N a m e , 366 GetExtraData - get data f r o m e x t e r n a l data s o u r c e , 450-451 G e t F n D a t a - g e t f u n d a m e n t a l data, 366-367 G e t O p t i o n - retrieve a u t o m a t i c a n a l y s i s s e t t i n g s , 408 G e t P e r f o r m a n c e C o u n t e r - retrieve v a l u e of counter, 452-453 G e t P l a y b a c k D a t e T i m e - g e t bar replay p o s i t i o n , 3 4 8 GetPriceStyle - g e t current chart price style, 321 GetRTData - retrieve real-time data fields, 4 5 4 - 4 5 5 G e t R T D a t a F o r e i g n - retrieve r e a l - t i m e data fields, 4 5 6 - 4 5 7 GetScriptObject - a c c e s s to script C O M object, 4 5 8 g e t t i n g started, 1 G e t T r a d i n g l n t e r f a c e - retrieve a u t o m a t i c t r a d i n g interface, 4 0 9 G f x A r c - d r a w an arc, 4 2 2 G f x C h o r d - d r a w a chord, 4 2 3 GfxCircle - d r a w a circle, 424 G f x D r a w T e x t - d r a w a text, 4 2 4 - 4 2 6 G f x E l l i p s e - d r a w an ellipse, 4 2 7 G f x G r a d i e n t R e c t - d r a w a r e c t a n g l e w i t h g r a d i e n t fill, 428 GfxLineTo - d r a w a l i n e to a point, 4 2 8 G f x M o v e T o - m o v e cursor, 429 G f x P i e - d r a w a pie, 430 G f x P o l y g o n - d r a w a p o l y g o n , 431 G f x P o l y l i n e - d r a w a p o l y l i n e , 432 G f x R e c t a n g l e - d r a w a rectangle, 4 3 3 G f x R o u n d R e c t - d r a w a r e c t a n g l e w i t h r o u n d corners, 4 3 4 G f x S e l e c t F o n t - select g r a p h i c font, 435
577
578
Introduction to AmiBroker
G f x S e l e c t P e n - s e l e c t g r a p h i c p e n , 436 GfxSelectSolidBrush - select graphic brush, 437 G f x S e t B k C o l o r - s e t b a c k g r o u n d color, 4 3 7 G f x S e t B k M o d e - set b a c k g r o u n d m o d e , 438 G f x S e t O v e r l a y M o d e - set o v e r l a y m o d e , 439 G f x S e t P i x e l - s e t pixel to s p e c i f i e d color, 439 G f x S e t T e x t A l i g n - s e t text a l i g n m e n t , 4 4 0 G f x S e t T e x t C o l o r - s e t text color, 441 G f x T e x t O u t - w r i t e text, 4 4 2 global, 259 g l o b a l m a x i m u m , 514-515 G r o u p I D - g e t g r o u p n a m e , 368 Granville, Joe, 214 grid, 126 g u a r a n t e e s , 239
head and shoulders, 230 help p u l l - d o w n menu, 114,150 Herrick John, 212 payoff i n d e x , 212 H H V - h i g h e s t h i g h v a l u e , 271 H H V B a r s - b a r s s i n c e h i g h e s t h i g h , 271 H i g h e s t - highest value, 272 H i g h e s t B a r s - b a r s s i n c e h i g h e s t v a l u e , 272 H i g h e s t S i n c e - h i g h e s t v a l u e s i n c e c o n d i t i o n met, 272 H i g h e s t S i n c e B a r s - b a r s s i n c e h i g h e s t v a l u e s i n c e c o n d i t i o n met, 273 history, 136 H o l d - h o l d an alert s i g n a l , 410 H o u r - c u r r e n t bar's hour, 348 HPI - H e r r i c k payoff i n d e x , 212
if (flow control), 256 IIF - c o n d i t i o n a l if, 256, 410 import a n a l y s i s , 508 ASCII, 132 data, 23 M e t a s t o c k , 132 w i z a r d , 132 i n d i v i d u a l backtest, 496 i n d i v i d u a l equity, 508 i n - s a m p l e , 97, 98-102, 234, 236, 491, 512, 518-523 i n c l u d e , 204 i n c l u d e trade list in report, 489 identifiers, 252 i n d e x , 249 indicators, 190-224 adjust scale, 194 a v e r a g e s , 195
Index c h a n g e p a r a m e t e r s , 193 d r a g a n d drop, 190 insert, 190 insert l i n k e d , 191 overlay, 192 indicator p a n e , 115 industries.js, 20 i n d u s t r y g r o u p , 19 I n d u s t r y l D - get i n d u s t r y n a m e , 368 initial equity, 484 insert chart (formula), 168, 190, 245 insert l i n k e d , 1 6 8 , 1 9 0 insert p u l l - d o w n m e n u , 114,139 Inside - i n s i d e day, 296 installation, 11 int - i n t e g e r part, 280 i n t e g e r s - n o n e in AFL, 388 internet, fair u s e , 44 internet integration, 9 interpretation, 524-528 interpretation t a b b e d m e n u , 114, 171 interpretation, v i e w , 137 Interval - get bar interval, 349 interval link, 128 InWatchList - w a t c h l i s t m e m b e r s h i p test by n u m b e r , 369 I n W a t c h L i s t N a m e - w a t c h l i s t m e m b e r s h i p test by n a m e , 369 IS a n d OOS, 204 I s C o n t i n u o u s - c h e c k s c o n t i n u o u s q u o t a t i o n flag, 369 I s E m p t y - e m p t y v a l u e check, 458 IsFavorite - c h e c k s m e m b e r s h i p in favorites, 370 IsFinite - c h e c k if v a l u e is finite, 459 I s l n d e x - c h e c k s m e m b e r s h i p in i n d i c e s , 370 I s N a N - c h e c k for n o t - a - n u m b e r , 459 IsNull - c h e c k for null, 460 IsTrue - c h e c k for True, 4 6 0
jscript, 20
K-ratio, 235 Keltner, b a n d s , 199 Chester, 199
Lambert, D o n a l d , 210 Lane, George, 219 LastValue - last v a l u e of array, 411 layers t a b b e d m e n u , 114,163 layers add, 164
579
580
Introduction to AmiBroker
daily, 163 d e f a u l t , 163 h i d e , 164 intraday, 163 lock, 164 m o n t h l y , 163 unlock, v i e w , 137 visibility, 163 w e e k l y , 163 layout, 107-111 l a y o u t s t a b b e d m e n u , 114, 162 l a y o u t s , v i e w , 136 l i m i t trade s i z e a s p e r c e n t a g e o f e n t r y bar v o l u m e , 490 l i n e a r r e g r e s s i o n , 197, 289-290 L i n e A r r a y - g e n e r a t e t r e n d - l i n e array. 322 L i n e a r R e g - linear r e g r e s s i o n e n d p o i n t , 289 L i n R e g l n t e r c e p t - i n t e r c e p t of l i n e a r r e g r e s s i o n line, 290 L i n R e g S l o p e - l i n e a r r e g r e s s i o n slope, 290 LLV - l o w e s t l o w v a l u e , 273 LLVBars - b a r s s i n c e l o w e s t low, 273 local, 259 local m a x i m u m , 514-515 l o g - n a t u r a l l o g a r i t h m , 280 loglO - d e c i m a l l o g a r i t h m , 281 l o o p i n g c o d e , 250-251, 256, 258-268, 537-541 L o w e s t - l o w e s t v a l u e , 274 L o w e s t B a r s - b a r s s i n c e l o w e s t , 274 L o w e s t S i n c e - l o w e s t v a l u e s i n c e c o n d i t i o n m e t , 274 L o w e s t S i n c e B a r s - b a r s s i n c e l o w e s t v a l u e s i n c e c o n d i t i o n m e t , 275
MA - s i m p l e m o v i n g average, 195, 287 M A C D - m o v i n g a v e r a g e c o n v e r g e n c e d i v e r g e n c e , 212, 308, 317 t r a d i n g s y s t e m , 224 M A E / MFE d i s t r i b u t i o n charts, 489 m a r k e t facilitation i n d e x , 212 M a r k e t I D - m a r k e t n a m e , 370 m a s s i n d e x , 213 M a x - m a x i m u m v a l u e , 281 m a x o p e n p o s i t i o n s , 490, 498 m a x i m u m l o s s stop, 4 8 7 M D I - m i n u s d i r e c t i o n a l m o v e m e n t indicator, 308 m e a n r e v e r s i o n , 97,102, 5 4 3 mechanical system, 234 m e d i a n - m i d d l e e l e m e n t , 291 m e r g e , 142 m e t r i c s , 235 MFI - m o n e y flow i n d e x , 213, 3 0 8 M i n - m i n i m u m v a l u e , 281 m i n p o s v a l u e , 485 m i n s h a r e s , 485
Index M i n u t e - current bar's m i n u t e , 349 m o m e n t u m , 213 m o n e y f l o w i n d e x , 213 m o n i t o r results, 239 M o n t h - current bar's m o n t h , 350 m o v i n g average a d a p t i v e , 285 d i s p l a c e d , 195 d o u b l e e x p o n e n t i a l , 286 e x a m p l e 3, 6 5 - 6 8 e x p o n e n t i a l , 196, 287 simple, 195, 287 triple, 196, 288 w e i g h t e d , 198, 288 Wilders, 197, 288 m o v i n g a v e r a g e c o n v e r g e n c e d i v e r g e n c e , 212 m s n data, 15, 23 m t R a n d o m - M e r s e n e t w i s t e r r a n d o m n u m b e r generator, 291 m t R a n d o m A - M e r s e n e t w i s t e r r a n d o m n u m b e r g e n e r a t o r (arrays), 292 m u l t i - w i n d o w layout, 108-111
n־bar stop, 488, 536, 5 4 3 N a m e - ticker s y m b o l , 371 n e g a t i v e v o l u m e indicator, 213 n e x t d a y o p e n , 530-531,542 noise, 236 N o r g a t e P r e m i u m Data, 31, 3 5 - 4 0 N o t e G e t - retrieve text of note, 461 n o t e p a d tabbed m e n u , 114,170 N o t e S e t - s e t text of note, 461 N o w - current s y s t e m date / time, 350 NumToStr, 338, 387 N V I - n e g a t i v e v o l u m e indicator, 213, 309 NZ - null to zero, 462
objective f u n c t i o n , 94, 234, 513, 518 OBV - on b a l a n c e v o l u m e , 214, 309 old backtester, 489 on b a l a n c e v o l u m e , 214 o p e n interest, 200 operator, 253 arithmetic, 254 array subscript, 256 a s s i g n m e n t , 253 c o m p a r i s o n , 253 c o m p o u n d , 254 logical, 254 p r e c e d e n c e , 255 o p t i m i z a t i o n graph, 515 o p t i m i z a t i o n target, 492
581
582
Introduction to AmiBroker
o p t i m i z e , 91-102, 237, 245, 412, 511-517 ordering, 9 o r g a n i z e a s s i g n m e n t s , 145 O s c P - price oscillator, 214, 309 OscV, v o l u m e oscillator, 214, 310 o u t - o f - s a m p l e , 96, 98-102, 234, 236, 238, 491, 512, 518-523 Outside, 297 overlay, 169 overview, 3
p a d a n d a l i g n , 485 pane active, 117 a d d n e w , 121 close, 1 2 1 , 1 3 6 c o n t e x t m e n u , 122 a x e s a n d grid, 124 colors, 124 p a r a m e t e r s , 122 p e r i o d s , 124 price field, 124 m a x i m i z e , 136 m o v e , 136 reorder, 121 resize, 61,118, 136 restore, 136 parabolic s t o p a n d reverse, 218, 315 Param - a d d u s e r - d e f i n a b l e n u m e r i c p a r a m e t e r , 322-323 P a r a m C o l o r - a d d u s e r - d e f i n a b l e p a r a m e t e r color, 324 P a r a m D a t e - a d d u s e r - d e f i n a b l e d a t e p a r a m e t e r , 324 parameters c h a r t context, 122-126 f o r m a l , 259 P a r a m F i e l d - c r e a t e s price field p a r a m e t e r , 325 P a r a m L i s t - creates p a r a m e t e r of list of c h o i c e s , 326 ParamStr - a d d u s e r - d e f i n a b l e s t r i n g p a r a m e t e r , 326 P a r a m S t y l e - s e l e c t s s t y l e s a p p l i e d to plot, 327 P a r a m T i m e - a d d u s e r - d e f i n a b l e t i m e p a r a m e t e r , 328 P a r a m T o g g l e - create y e s / n o p a r a m e t e r , 328 ParamTrigger - c r e a t e s a trigger in p a r a m e t e r d i a l o g , 329 p a r e n t h e s e s , 255 particle s w a r m o p t i m i z a t i o n (PSO), 514 PDI - p l u s d i r e c t i o n a l m o v e m e n t indicator, 310 Peak, 297 PeakBars - bars s i n c e p e a k , 298 p e r c e n t b a n d s , 199 percentile, 292 performance, 5 p e r i o d i c i t y , 119, 4 8 4 p e r i o d s , chart, 124 Plot - plot i n d i c a t o r graph, 330-331 PlotForeign, 374
Index PlotGrid - plot h o r i z o n t a l grid line, 331 P l o t O H L C - plot c u s t o m O H L C chart, 332 P l o t S h a p e s - plot a r r o w s a n d o t h e r s h a p e s , 332-333 PlotText - w r i t e text on chart, 310 PlotVAPOverlay - plot v o l u m e - a t - p r i c e chart, 3 3 4 plug-in, 147 data, 14 PopupWindow - display pop-up window, 463 portfolio backtest, 87-90, 496 c o n s i d e r a t i o n s , 532-533 equity, 89-90, 204, 508 o p t i m i z a t i o n , 511 p o r t f o l i o tab, 490 p o s i t i o n in range, 219 p o s i t i o n score, 225 p o s i t i o n size, 498 p o s i t i o n s , 484 p o s i t i v e v o l u m e i n d e x , 215 Prec - adjust n u m b e r of d e c i m a l places, 2 8 2 Prefs - retrieve p r e f e r e n c e settings, 4 6 4 - 4 6 5 P r e m i u m Data, 31, 3 5 - 4 0 prettify s e l e c t i o n , 244 price axis, 115,117 price / data tooltip, 115 price chart, 115 price field, chart, 125 price (formula), 200 price oscillator, 214 price series, d i s p l a y n e w , 116 price v o l u m e trend, 215 pricing, 9 printf - print f o r m a t t e d o u t p u t to t h e o u t p u t w i n d o w , 388, 390 p r o c e d u r a l p r o g r a m m i n g l a n g u a g e , 242 p r o c e d u r e s , 258 p r o f e s s i o n a l e d i t i o n , 4, 12 profile, 245 profit target, 488, 536, 5 4 3 properties, 129 p s y c h o l o g y of trading, 234 p u l l - d o w n m e n u , 130 analysis, 114,146 edit, 114,134 file, 114,131 format, 114,141 help, 114,150 insert, 114,139 tools, 114,147 v i e w , 114,135 symbol, 114,116,142 w i n d o w , 114, 149 p u n c t u a t o r , 253 PVI - p o s i t i v e v o l u m e i n d e x , 215, 311 P V T - price v o l u m e trend, 215
583
584
Introduction to AmiBroker
q q u a n t i t a t i v e a n a l y s i s , 231 Q u i c k A F L , 342, 467 q u i c k r e v i e w , 146, 4 7 8 - 4 8 0 quotation d e l e t e , 134 q u o t e editor, 143 q u o t e s , a u t o - u p d a t e , 147 Q u o t e s Plus, 31-35, 4 4 - 4 7
R a n d o m - r a n d o m n u m b e r , 293 range automatic analysis, 482 mark, 120 rate of c h a n g e , 216 read me, 150 r e a l - t i m e q u o t e , v i e w , 137 r e a l - t i m e q u o t e w i n d o w , 52, 1 4 5 , 1 7 3 r e c u r s i o n , 261 r e - d o c k a b l e m e n u s , 160 r e e n t r y d e l a y , 396, 488 Ref - r e f e r e n c e p a s t or f u t u r e data, 413 r e g r e s s i o n , 157 relative m o m e n t u m , 215 relative p e r f o r m a n c e , 201 relative s t r e n g t h , 216 relative s t r e n g t h i n d e x , 216 R e l S t r e n g t h - c o m p a r a t i v e relative s t r e n g t h , 375 replace w a t c h l i s t w i t h s e l e c t e d results, 5 0 2 replace w a t c h l i s t w i t h t h e results, 502 report, 80-81 report button, 509-510 report explorer, 510 report tab, 88, 4 8 8 - 4 8 9 R e q u e s t T i m e d R e f r e s h - f o r c e s p e r i o d i c r e f r e s h of indicator pane, 311 r e s e r v e d variables, 257 resize pane, 61,118 RestorPriceArrays, 375 r e s u l t s w i n d o w , 88-89, 94-95 sort, 95 return, 260 r e v e r s e e n t r y s i g n a l f o r c e s exit, 485 risk f r e e rates, 489 risk / y i e l d m a p , 136 risk-reward ratio, 235 RMI - relative m o m e n t u m , 215, 312 R O C - rate of c h a n g e , 216, 313 rotational trading, 225 r o u n d - r o u n d n u m b e r to n e a r e s t integer, 282 r o u n d lot size, 486
Index RRR - risk-reward ratio, 235 RS - relative s t r e n g t h , 216 RSI - relative s t r e n g t h i n d e x , 215, 216, 313 RSIa - relative s t r e n g t h i n d e x , 217 rule-based s y s t e m , 235 run every, 4 8 3 Russell, 16 RWI - r a n d o m w a l k i n d e x , 217, 314
s a m e d a y close, 531-532, 5 4 3 SAR - parabolic s t o p a n d reverse, 218, 315 Say - s p e a k s text, 466 scalar, 251 scan, 7,103, 245 scope, 258-260 scripting, 8, 20 scroll bar, 59, 115, 118 S e c o n d - current bar's s e c o n d , 351 S e c t o r l D - get sector n a m e , 371 S e l e c t e d V a l u e - v a l u e of array at c u r r e n t l y s e l e c t e d d a t e / t i m e , 3 3 4 sell delay, 487 sell price, 486 s e n d to a u t o - a n a l y s i s , 245 S e t B a c k t e s t M o d e , 402-403, 413 SetBarFillColor, 315 S e t B a r s R e q u i r e d - set bars n e e d e d for script, 4 6 7 SetChartBkColor - set b a c k g r o u n d color, 316 SetChartBkGradientFill - set b a c k g r o u n d g r a d i e n t color, 316 S e t C h a r t O p t i o n s - set/clear d e f a u l t s for c h a r t p a n e o p t i o n s , 3 3 5 - 3 3 6 S e t C u s t o m B a c k t e s t P r o c - d e f i n e c u s t o m b a c k t e s t p r o c e d u r e , 414 SetForeign - replace c u r r e n t price w i t h f o r e i g n security, 376-377 S e t F o r m u l a N a m e , 415 S e t O p t i o n s - s e t s s e t t i n g s for a u t o m a t i c a n a l y s i s , 416-418 S e t P o s i t i o n S i z e - set trade size, 419 S e t S o r t C o l u m n s - set c o l u m n s for s o r t i n g i n A A w i n d o w , 337 SetTradeDelays, 420 short delay, 487 short price, 486 s h o w a r r o w s for actual trades, 5 0 2 s h o w a r r o w s for all raw s i g n a l s , 5 0 2 s h o w current trade a r r o w s , 5 0 2 signal, 236 s i m p l e m o v i n g average, 195 s l i d i n g m e n u s , 160 s i g n - r e t u r n s s i g n of n u m b e r , 282 Signal - M A C D s i g n a l line, 317 sin - s i n e f u n c t i o n , 283 s i n h - h y p e r b o l i c s i n e f u n c t i o n , 283 s n a p to price, 141 sort results, 95, 480
585
586
Introduction to AmiBroker
split, 142 sqrt - s q u a r e root, 283 S t a n d a r d & Poor's, 20 sector ETFs, 499-501 s t a n d a r d e d i t i o n , 4, 12 s t a n d a r d toolbar, 114,151 statement, 253 static m o d e l , 235 StaticVarGet - g e t v a l u e of static variable, 4 6 7 StaticVarGetText - g e t v a l u e of static v a r i a b l e as text, 468 S t a t i c V a r R e m o v e - r e m o v e static variable, 4 6 8 StaticVarSet - set v a l u e of static variable, 469 StaticVarSetText - s e t v a l u e of static v a r i a b l e as text, 469 S t a t u s - g e t A F L r u n - t i m e status, 4 7 0 - 4 7 2 s t a t u s bar, 114 StdErr - s t a n d a r d error, 293 S t D e v - s t a n d a r d d e v i a t i o n , 293 Stochastic, %D, 220, 317 %K, 219, 317 m o m e n t u m , 220 s t o p s tab, 487-488 StrExtract - extract s u b s t r i n g f r o m c o m m a - s e p a r a t e d string, 389 StrFind - f i n d s u b s t r i n g in string, 389 StrFormat - w r i t e f o r m a t t e d o u t p u t to s t r i n g , 390 s t r i n g literal, 2 5 3 StrLeft - e x t r a c t s l e f t m o s t part of string, 391 StrLen - s t r i n g l e n g t h , 391 StrMid - e x t r a c t s part of string, 391 StrReplace - s t r i n g replace, 392 StrRight - e x t r a c t s r i g h t m o s t part of s t r i n g , 392 StrToDateTime - c o n v e r t s t r i n g to d a t e t i m e , 392 StrToLower - c o n v e r t to l o w e r c a s e , 393 S t r T o N u m - c o n v e r t s t r i n g to n u m b e r , 393 StrToUpper - c o n v e r t to u p p e r c a s e , 393 study A n d r e w s pitchfork, 158 arrow, 157 c y c l e s , 158 Fibonacci, 158 function, 472 G a n n , 158 h o r i z o n t a l , 157 m o d i f y , 155 parallel, 157 ray, 157 r e g r e s s i o n , 157 t r e n d line, 157 triangle, 158 vertical, 157 z i g - z a g , 157 S u m - s u m data o v e r s p e c i f i e d n u m b e r of bars, 287
Index s u m m a r y , A A , 489 support, 9, 230 s u r v i v o r bias, 35 s y m b o l link, 128 symbol delete, 142 n e w , 142 s y m b o l p u l l - d o w n m e n u , 114, 116, 142 s y m b o l s t a b b e d m e n u , 58, 114,116, 165 s y m b o l s , v i e w , 136 s y n c chart o n select, 4 8 3 s y n c h r o n i z a t i o n , 98, 235 s y s t e m s directory, 224 systems, trading M A C D , 224 rotational, 225
tabbed m e n u s a u t o - h i d i n g , 160 charts, 114, 168 re-dockable, 160 interpretation, 114,171 layers, 114, 163 layouts, 114,162 n o t e p a d , 114,170 s l i d i n g , 160 s y m b o l s , 114,116 tan - t a n g e n t f u n c t i o n , 284 t a n h - h y p e r b o l i c t a n g e n t f u n c t i o n , 284 T E M A - triple e x p o n e n t i a l m o v i n g average, 196, 288 template, 128 term, 253 tick data, 53-54 tick size, 486 ticker toolbar, 114, 116 tile w i n d o w s , 149 t i m e & sales, v i e w , 137,174-176 t i m e s e r i e s forecast, 197 t i m e d exit, 536, 5 4 3 T i m e F r a m e C o m p r e s s , 352 T i m e F r a m e E x p a n d , 353 TimeFrameGetPrice, 354-355 T i m e F r a m e M o d e , 356 TimeFrameRestore, 357 TimeFrameSet, 358-360 T i m e N u m - current bar's time, 351 tip of the day, 150 tokens, 252 toolbars add or r e m o v e buttons, 152
587
588
Introduction to AmiBroker
a d d icons, 159 d o c k i n g , 154 draw, 1 1 4 , 1 5 4 Fibonacci, 114, 154 format, 1 1 4 , 1 5 4 s t a n d a r d , 114, 151 ticker, 114,152 tools, 1 1 4 , 1 5 2 view, 114,137,153 tools p u l l - d o w n menu, 114,147 t o o l s toolbar, 114 tooltip, 62 trade delay, 530-532, 542-543 trade list, 489 trades tab, 4 8 6 - 4 8 7 traders i n d e x , 220 trailing stop, 488 trading arrows, 82-84,126 trading system development 1. d e f i n e t h e o b j e c t i v e f u n c t i o n , 234-235 2. d e c i d e w h a t to trade a n d h o w to trade it, 235 3. d e s i g n the t r a d i n g s y s t e m , 235-236 4. d e t e r m i n e the l e n g t h of t h e i n - s a m p l e p e r i o d , 236 5. d e t e r m i n e t h e l e n g t h of t h e o u t - o f - s a m p l e p e r i o d , 236 6. d e c i d e w h a t to o p t i m i z e , 237 7. p e r f o r m w a l k f o r w a r d r u n s , 237-238 8. e v a l u a t e the o u t - o f - s a m p l e results, 238 9. trade t h e s y s t e m , 239 10. m o n i t o r t h e results, 239 t r a d i n g s y s t e m d e v e l o p m e n t p l a t f o r m , 231 trading s y s t e m s M A C D , 224 m e a n reversion, 543 rotational, 225 trend following, 542 t r e n d f o l l o w i n g , 97, 5 4 2 t r e n d line, 61, 157, 2 3 0 trial v e r s i o n , 11, 13 tribes o p t i m i z a t i o n , 514 T R I N - traders i n d e x , 220, 3 0 3 triple e x p o n e n t i a l , 221 triple e x p o n e n t i a l m o v i n g average, 196 TRIX - triple e x p o n e n t i a l , 221, 318 T r o u g h , 298 T r o u g h B a r s - bars s i n c e t r o u g h , 299 TSF - t i m e s e r i e s forecast, 197, 294
ulcer p e r f o r m a n c e i n d e x , 235 u l t i m a t e oscillator, 222, 318 U n c l s s u e s - u n c h a n g e d issues, 303
Index UncVolume ־unchanged issues volume, 304 u s e quick AFL, 485 u s e p r e v i o u s bar e q u i t y for p o s i t i o n s i z i n g , 4 9 0 u s e today, 492 u s e r - d e f i n e d f u n c t i o n s , 258 user's g u i d e , 150
validation, 98-102, 234 v a l u e axis, 115, 117 V a l u e W h e n - g e t v a l u e o f array w h e n s o m e c o n d i t i o n w a s true, 420 VarGet - g e t v a l u e of d y n a m i c variable, 4 7 3 VarGetText - g e t text v a l u e of d y n a m i c variable, 474 variable l e n g t h parameter, 540-541 variables, 257 r e s e r v e d , 257 VarSet - set v a l u e of d y n a m i c variable, 474 VarSetText - set text v a l u e of d y n a m i c variable, 475 v e r i f y s y n t a x , 245, 5 0 3 Version - get A m i B r o k e r v e r s i o n info, 475 v i e w last report, 509 v i e w p u l l - d o w n m e n u , 114, 135 alert o u t p u t , 137 charts, 137 interpretation, 137 layers, 137 layouts, 136 n o t e p a d , 137 r e a l t i m e quote, 137 s y m b o l i n f o r m a t i o n , 137 s y m b o l s , 136 t i m e a n d sales, 137 toolbars, 137 v i e w toolbar, 114 v i s u a l i z a t i o n , 515 volatility Chaikin, 222 Wilder, 223 v o l u m e , 201 v o l u m e at price, 202 v o l u m e oscillator, 214, 2 2 3
w a i t for backfill, 4 8 3 w a l k forward, 98-102, 237, 518-523 w a l k f o r w a r d tab, 491-492 w a r n b e f o r e t i m e c o n s u m i n g o p e r a t i o n s , 489 watchlist, 144,178-189 add s y m b o l , 167, 181 a d d w a t c h l i s t , 180 a u t o m a t i c a n a l y s i s , 184
589
590
Introduction to AmiBroker
delete, 167, 183 e x a m p l e , 69-71 e x p o r t , 167,187 h i d e e m p t y , 167, 184 i m p o r t , 167,186 local / global, 179 n e w , 167 r e m o v e s y m b o l , 167,183 r e m o v e w a t c h l i s t , 180 r e n a m e , 187 sort tickers, 182 w e b l i n k s , 150 w e e k l y v i e w icon, 5 8 w e i g h t e d m o v i n g average, 198 w h i t e s p a c e , 252 Wilder m o v i n g average, 197, 288 volatility, 2 2 3 W e l l e s , 197, 207, 2 2 3 Williams %R, 2 2 3 a d v a n c e d e c l i n e , 206 Bill, 212 Larry, 206, 222, 2 2 3 w i n d o w p u l l - d o w n m e n u , 114, 149 windows, 4,11 c a s c a d e , 149 tile, 149 W M A - w e i g h t e d m o v i n g average, 198, 288 Writelf - c o n d i t i o n a l text for c o m m e n t a r y , 337, 526 WriteVal - w r i t e a n u m b e r , 338, 387, 525 www.amibroker.com, 2
XShift, 332
y a h o o data, 15, 23, 25 y a h o o f o r u m , 150 Year - c u r r e n t bar's year, 351
Z i g - z i g - z a g indicator, 299 z i g - z a g , 224 z o o m , 119 z o o m i n icon, 5 9 z o o m o u t icon, 5 9 Z w e i g , M a r t i n , 209
If you enjoyed this book and would like to order additional copies for yourself, your friends, or your colleagues, please visit us on the web at www.introductiontoamibroker.com and order directly from the publisher. You may also be interested in Quantitative Trading Systems, a book that discusses the design, testing, and validation of trading systems. Learn more about it at www.quantitativetradingsystems.com and order directly from the publisher. Howard Bandy is the author of both books, and both are published by Blue Owl Press, www.blueowlpress.com.
Introduction to
AmiBroksr Advanced Technical Analysis Software for Charting and Trading System Development
Howard B. Bandy
GmmiM^MM
Sydtemd
Practical Methods For Design, Testing, and Validation Howard B. Bandy