ChatGPT is utterly amazing and scary at the same time

Yes it is possible, but even with syntax check, AI generated code might be completely wrong on all other levels. With current state of the art GPTs they still don't have any kind of actual understanding what they write. Hallucinations are still very common.

AI is great tool in the hand of experienced human that adds missing understanding element. So programmers can use AI assistants easily as they spot logical errors quickly.

4 Likes

Dr. Tomasz,
I would like to know what could be achieved if a person like you, using the content in this Community, in the User Manual, in the Knowledge Base and in other similar places, decided to create an AI for AmiBroker/AFL.
I would pay to have such a tool as a teacher 24/7/365, no doubt about it.

Such thing exits already Better way to get to information - #7 by Tomasz but due to limitations of LLM (hallucinations) it requires human approval/moderation. The LLMs are simply too unreliable, even if they are provided with right context.

I know that within these 6 favorite bookmarks are the answers to all my doubts but...it is not easy to find them!

However, I will not give up :sweat_smile:.

None of these work any better than ChatGPT. In fact they can be illegal because using our copyrighted content (Users' guide, AFL reference) without our permission is violation of our intellectual property rights.

1 Like

Ok, I understand.
I saw that my post asking if a specialized AFL GPT I found worked well has been deleted, I understand that you deleted it because of this. Sorry I didn't notice!!
I'm still trying to create a GPT to help me with AFL. I'm trying to learn about Prompts to see if I can create something useful.
Can Prompts be shared here?

I already explained, no amount of prompting would change the fact that GPTs don't understand a thing. It is just "text generator". Not something that actually understands anything. The amount of hallucination is ridiculous. This GPT even if asked the most simple thing hallucinates like hell. It comes up with function names that don't exist. Without knowledgeable human checking what this thing writes, the code generated can't be trusted. GPTs can be fun when you ask them to write a POEM because in poetry you don't have rules. GPTs are good at TEXT tasks like translation (that was original purpose of Transformers) and summarization, writing a novel maybe. Programming is another story. Programming requires not only fluency in language syntax, but also understanding how some abstract concepts work.

ChatGPT is simply stupid. Ask him "Write MA crossover in AFL" and it will even write correct code:

but then say "But Moving Average function in AFL is NOT "MA" and this is what this stupido says:

It does NOT KNOW anything. Prompts can steer it to utter nonsense.

If you say that you are an elephant it would agree and continue with nonsense.

3 Likes

I understand Dr. Tomasz, thank you for your explanations. I understand that it may or may not be useful and that you have to be very careful with hallucinations.
But it will be possible with some very well-made prompts that it can become better, right?
That is, instead of "tricking" him as in the MA example, giving him correct data and also correcting him when he makes mistakes.
Well, it is a hope for newbies like me to learn AFL, there is no doubt about that. Although we will see if we lose hope or not. :sweat_smile:

Yes, you can provide it with correct information. Problem is that GPTs don't know what is true what is not. They lack meta-knowledge or any knowledge at all. They don't know what they know and they don't know what they don't know.
GPTs are statistically based text generators. They produce "nicely sounding text" that statistically likely could be produced by human in response to given question. It is a play of law of large numbers. If there are lots of examples in the training set that closely resemble your question you are likely to get something that is statistically correct.

5 Likes

ChatGPT now allows uploading custom documents. It is great way to get fact-based answers from AmiBroker Users' Guide:

Simply use (+) button in ChatGPT to upload UsersGuide.pdf (available for download from AmiBroker - Technical Analysis Software. Charting, Portfolio Backtesting, Scanning of stocks, futures, mutual funds, forex (currencies). Alerts. Free quotes.)

This way ChatGPT will look for the information in the AmiBroker users guide greatly enhancing accuracy of the answers.

19 Likes

Just a heads up. Over the last few days, I was playing with the Google Gemini Pro 2.5 Experimental model that was just released about 2 weeks ago. It is available basically for free from Google's AI Studio.

And I have one thing to say: It is much, much better than OpenAI's offerings. Try it for yourself, you will be surprised.

10 Likes

Thanks to Gemini 2.5 Pro ability to handle 1 million input tokens, I fed it with entire AmiBroker Users's guide (about 900K tokens when converted to markdown format) and told it to produce "condensed" knowledge document of about 50K words, it came up with this:

AmiBroker Core Knowledge Base (Based on User's Guide 6.9x)

Product Overview

AmiBroker 6.9x is a comprehensive technical analysis program featuring advanced charting, back-testing, scanning, and optimization capabilities.

Editions:

  • Standard Edition: End-of-day (EOD) and basic intraday (1-, 5-, 15-min, hourly, custom minute) charting/backtesting/scanning. Limited real-time features (10 symbols streaming, 1 Time & Sales). 32-bit only. Up to 2 analysis threads.
  • Professional Edition: Includes all Standard features plus:
    • Tick charts/backtesting/scanning (requires specific RT feeds like eSignal, IB, DDE).
    • 1-second, 5-second, 15-second bar charts/backtesting/scanning.
    • Unlimited real-time quote display symbols.
    • Unlimited Time and Sales windows.
    • GetRTData / GetRTDataForeign AFL functions.
    • Wait for backfill in Analysis.
    • Max Adverse/Favourable Excursion charts in Portfolio backtest reports.
    • 64-bit version available (requires 64-bit OS and compatible plugins).
    • Multi-threading Analysis window (up to 32 threads, limited by CPU cores & symbols).
    • QuickGFX rendering engine (experimental, performance boost).

System Requirements:

  • Minimum: Pentium 450 MHz, 1GB RAM, 20 MB disk space, 256 color 800x600 display.
  • Recommended: 1GHz+ multi-core CPU, 4GB+ RAM.
  • Supported OS: Windows 7 (SP1+IE11+TLS1.2+KB3004394), Windows 8, Windows 10, Windows 11 (32-bit and 64-bit versions where applicable). Older OS (XP, Vista, 9x) NOT supported by current versions.
  • 64-bit AmiBroker requires a 64-bit Windows OS and 64-bit compatible data plugins. 32-bit AmiBroker runs on both 32-bit and 64-bit Windows.

Installation:

  • Use the setup program from amibroker.com.
  • Default installation: C:\Program Files\AmiBroker.
  • Restart if prompted.
  • Start via Start Menu.

Getting Help:

  • Press F1 for context-sensitive help.
  • Read the Tutorial section first.
  • Check the Troubleshooting guide.
  • Use the Search tab in the help file.
  • AmiBroker website (amibroker.com): searchable, Tips newsletter, Support area, FAQ, AFL Library, Members area.
  • AmiBroker Forum (forum.amibroker.com): user community, searchable archives.

Core Concepts

Database Structure:

  • An AmiBroker database is a directory (folder) containing data files.
  • Default database: data subfolder in the AmiBroker installation directory.
  • Data files (quotes, symbol info, studies) are stored in subdirectories named 0-9, a-z, _.
  • broker.workspace file: stores category names, composite info.
  • broker.master file: stores symbol table for quick loading.
  • Users generally should not manually modify files within the database directory.

External Data Sources:

  • AmiBroker can read data directly from external sources via Data Plugins (e.g., eSignal, IQFeed, IB, Metastock, TC2000, Quotes Plus, etc.).
  • Setup via File -> Database Settings. Choose the plugin from "Data source".
  • Local Data Storage:
    • Enabled: Caches data retrieved from the plugin into AmiBroker's local database files for faster access. Required for most RT feeds.
    • Disabled: Reads directly from the external source each time (can be slower).
  • When using a plugin, AmiBroker still uses its own database directory to store information not present in the external source (studies, categories, etc.).
  • Do NOT import ASCII/AmiQuote data for symbols already managed by a plugin unless you understand the implications (potential overwrites or data corruption). Exception: importing data for symbols not present in the RT database marks them as "Use only local database".

Categories:

  • Used to organize symbols (Markets, Groups, Sectors, Industries, Watch Lists, Favorites, Indexes, GICS, ICB).
  • Viewed in the Symbols tab of the Workspace window.
  • A single symbol can belong to multiple categories simultaneously.
  • Mutually Exclusive: Groups, Markets, Sectors/Industries, GICS, ICB (symbol belongs to only one of each type).
  • Free Membership: Watch Lists, Favorites, Indexes (symbol can belong to none, one, or many).
  • Managed via Symbol -> Categories window or Symbol -> Organize Assignments.
  • Sector/Industry definitions are stored in broker.workspace. Templates broker.sectors and broker.industries are used when creating new databases.
  • GICS (Global Industry Classification Standard) and ICB (Industry Classification Benchmark) are hierarchical classification systems supported via specific category types and codes (defined in GICS.txt/ICB.txt).
  • ASCII importer supports importing category assignments ($SECTORNAME, $INDUSTRYNAME, $GICS, $ICB commands).
  • Tools -> Update US symbol list and categories automatically sets up US stock lists and industry assignments (overwrites existing structure).

Watch Lists:

  • User-definable lists of symbols.
  • Managed via Symbol -> Watch List menu or right-click context menus.
  • Unlimited number of watch lists.
  • Stored as .TLS files in the Watchlists subfolder within the database directory.
  • Order of symbols is preserved when adding from sorted lists (like AA results).
  • Can be imported/exported from/to .TLS, .LST, .TXT, .CSV files.
  • Can be populated directly from Automatic Analysis results.

Layers:

  • Used to organize hand-drawn studies on charts.
  • Managed in the Layers tab of the Workspace window.
  • Layers can be shown/hidden individually.
  • Built-in layers (Default, Intraday, Daily, Weekly, Monthly) can be locked to automatically show/hide based on chart interval.
  • User can create custom layers.
  • Studies are drawn on the currently selected layer.

User Interface

Main Window:

  • Toolbar: Quick access to common functions.
  • Workspace Window: Contains tabs for Symbols, Layouts, Layers, Charts (Formulas).
  • Chart Area: Displays price and indicator charts in panes.
  • MDI Tabs (optional): Switch between open document windows (Charts, Analysis, Web Research, Account Manager).

Customization (Tools -> Customize):

  • Toolbars/Menus: Add, remove, rearrange buttons and menu items. Define custom tools.
  • Keyboard Shortcuts: Define custom key bindings for commands.
  • Appearance: Select UI themes (Basic, Nature, Gray, Black, etc.). Control MDI tab visibility.
  • Web Pages: Define custom URLs for the Web Research window.

Chart Window:

  • Multiple panes possible per window.
  • Panes show price charts or indicators based on AFL formulas.
  • X-axis (time), Y-axis (price/value).
  • Scroll bar for time navigation.
  • Chart Sheets (Tabs at bottom): Up to 60 sets of indicators per window, saved as templates (.chart).
  • Right-click context menu: Access Parameters, Edit Formula, Close Pane, Template options, etc.
  • Scrolling: Use scroll bar, mouse wheel.
  • Zooming: Use View menu, toolbar buttons (Zoom In/Out/All/Normal/Range), Ctrl+Mouse Wheel.
  • Y-Axis: Drag to move scale, Shift+Drag to shrink/expand, Double-click to reset.
  • Interval: Change via View menu, toolbar buttons (i, h, d, w, m, q, y), or custom interval combo box.
  • Quote Selection: Click chart (or Ctrl+Click if configured) to show vertical line and data values for that bar. Use Left/Right arrow keys to move selection.
  • Range Selection: Double-click start, double-click end (or F12 / Shift+F12 with selection line active). Used for Zoom->Range and AFL BeginValue/EndValue.
  • Drawing Tools: Trend lines, rays, channels, Fibonacci tools, Gann tools, shapes, text boxes available from Insert menu or Draw toolbars. Objects are selectable, movable, resizable, deletable (DEL key). Properties via Alt+Enter or right-click->Properties.
  • Symbol/Interval Linking: Use 'S' and 'I' buttons near scrollbar to link multiple chart windows by symbol and/or interval using color codes.
  • Symbol Lock: Padlock button prevents symbol changes in a specific chart.
  • Floating Windows: Detach chart windows to move to separate monitors (Window -> Floating).
  • Chart Themes: Pre-defined color/style schemes selectable in Preferences -> Axes & Grid.

Workspace Window Tabs:

  • Symbols: Search box, category tree, symbol list. Click headers to sort. Drag headers to reorder columns.
  • Layouts: Save/load multi-window arrangements (window positions, sizes, symbols, intervals, chart sheets per window). Local (per-database) and Global layouts.
  • Layers: Manage visibility and properties of drawing layers.
  • Charts (Formulas): Tree view of AFL formulas in the Formulas directory. Double-click or use context menu (Insert/Overlay) to apply to charts.

Other Key Windows:

  • Parameters Window (Ctrl+R): Modify indicator parameters defined by Param* functions in AFL. Adjust axes, grid, show/hide trading arrows.
  • Data Window (Window -> Data Window): Shows OHLCV, indicator values for the bar under the mouse cursor.
  • Formula Editor (Analysis -> Formula Editor): Edit AFL code with syntax highlighting, auto-complete, parameter info, error reporting, code folding, debugging features.
  • Web Research (File -> New -> Web Research): Embedded browser to view web pages related to the selected symbol. User-definable URLs with symbol placeholders ({t}, {s}, {S}, {a}, {i}, {t0} etc.). Sync options control automatic updates when symbol changes. New Chromium/Edge engine available in v6.90 (64-bit only, requires WebView2 runtime).
  • Account Manager (File -> New -> Account): Track trades, equity, commissions manually. Enter transactions chronologically. Save/load accounts (.acx files).
  • Symbol Information (Symbol -> Information): View/edit symbol details, name, alias, categories, fundamental data fields, currency, margin/point value, round lot/tick size.
  • Notepad (Window -> Notepad): Store free-form text notes per symbol. Accessible via NoteGet/NoteSet AFL functions.
  • Quote Editor (Symbol -> Quote Editor): Manually add, edit, delete individual quote bars.
  • Symbol Finder (F3): Quickly find symbols by ticker or name.
  • Categories Window (Symbol -> Categories): Define names for markets, groups, sectors, industries. Assign base indexes and profile URLs per market. Re-arrange category order (v6.10+).
  • Assignment Organizer (Symbol -> Organize Assignments): Move multiple symbols between categories, delete multiple symbols.
  • Real Time Quote Window (Window -> Realtime Quote): Displays streaming real-time data fields for selected symbols (requires RT data source). Limited symbol count based on subscription/edition. Context menu for Time & Sales, Easy Alerts. Features Bid/Ask trend indicator (v5.90+).
  • Easy Alerts (Window -> Easy Alerts): Define simple price-based alerts without coding (RT mode only).
  • Time & Sales Window (Window -> Time & Sales): Shows every incoming trade, bid, ask tick with color coding. Includes short-term trade statistics. Unlimited windows in Pro edition.
  • Bar Replay (Tools -> Bar Replay): Play back historical data across all symbols at adjustable speed. Affects charts and analysis.
  • Analysis Window (Analysis -> Automatic Analysis or File -> New -> Analysis): Perform scans, explorations, backtests, optimizations. Load/Save analysis projects (.apx files). Define Apply To (All, Current, Filter) and Range (All, Recent bars/days, From-To). Buttons for Scan, Explore, Back Test, Optimize, Report, Equity, Settings, Filter. Multi-threaded execution in Pro edition.
  • Filter Settings: Define criteria (market, group, sector, industry, watchlist, favorites, index inclusion/exclusion) for Analysis window's "Filter" Apply To mode.
  • System Test Settings: Configure backtester parameters (initial equity, commissions, stops, trade delays, periodicity, portfolio settings, report options).
  • Commentary Window (Analysis -> Commentary): Display textual analysis generated by AFL formulas.
  • Log Window (Window -> Log): View AFL errors (compile-time and run-time) and _TRACE output.
  • Performance Monitor (Tools -> Performance Monitor): Shows memory usage and performance statistics.

Data Management & Feeds

Data Sources:

  • (local): Native AmiBroker format. Updated via ASCII import (Wizard, Importer, AmiQuote, scripts). Fastest performance.
  • Plugins: Connect to external EOD or Real-Time (RT) data sources.
    • EOD Plugins: Quotes Plus, TC2000/TCNet/TC2005, FastTrack, Metastock. Data read directly. Local caching recommended for TC2000.
    • RT Plugins (Pro Edition Recommended): eSignal, IQFeed, Interactive Brokers (IB TWS), QuoteTracker, Statica (WSE), DDE. Stream real-time data. Require local data storage enabled. Have specific setup procedures and symbol formats.

AmiQuote:

  • Companion downloader program.
  • Downloads EOD and delayed intraday data from free sources (Yahoo, MSN, Google Finance, etc.).
  • Supports many international exchanges (using Yahoo suffixes like .L, .AX, .PA).
  • Downloads Forex data.
  • Can download fundamental data (basic and extra) from Yahoo (US stocks).
  • Can run in automatic update mode (Tools -> Auto-update quotes) or manual mode.
  • Uses Ticker List files (.TLS).
  • Automatic import into AmiBroker database.

ASCII Importer:

  • Imports data from text files (.csv, .txt, etc.).
  • Flexible format definition using $ commands (e.g., $FORMAT, $SEPARATOR, $SKIPLINES, $DATE_YMD, $AUTOADD).
  • Can import OHLCV, OpenInt, Aux1/2, Ticker, FullName, Alias, Category assignments (MarketID, GroupID, IndustryID, SectorName, IndustryName, GICS, ICB), Fundamental data fields.
  • Format definitions stored in .format files in Formats subdirectory. import.types defines file types available in the import dialog.
  • Wizard (File -> Import Wizard) provides simplified interface for common formats.
  • Supports tick data import ($TICKMODE 1 - Warning: deletes existing quotes for the symbol first).
  • Supports microsecond timestamp resolution (HH:MM:SS.mmmuuu).

Metastock Importer:

  • One-time import from Metastock MASTER/EMASTER and F*.DAT files into AmiBroker native database.
  • Not recommended for continuous use; use the Metastock plugin instead for direct reading.

Real-Time Data Handling:

  • Requires RT plugin configured in File -> Database Settings.
  • Local Data Storage must be Enabled.
  • Base Time Interval determines the smallest bar resolution collected (Tick, seconds, 1-minute recommended for most).
  • Add symbols via Symbol -> New.
  • RealTime Quote window (Window -> Realtime Quote) shows streaming data.
  • Backfill feature downloads historical intraday data (availability varies by plugin/source). Can be automatic or manual (Plugin Status Menu -> Force Backfill).
  • Wait for backfill option in Analysis window ensures data is complete before scan/backtest runs (supported by eSignal, IQFeed).
  • Plugin status indicator (bottom right corner): Green (OK), Yellow (Wait), Red (Error), Purple (Shutdown). Right-click for context menu (Reconnect, Shutdown, Backfill options).

Fundamental Data:

  • 32+ fields available (EPS, P/E, Book Value, Shares Out, Dividend info, Margins, etc.).
  • View/Edit in Symbol -> Information window.
  • Download free US fundamental data via AmiQuote (Yahoo sources).
  • Access from AFL using GetFnData("fieldname").
  • Import via ASCII importer using specific field names in $FORMAT.
  • Access via OLE automation (Stock object properties).

AmiBroker Formula Language (AFL)

Core Concept: Array Processing:

  • AFL operates primarily on arrays (vectors) of data (like Open, High, Low, Close, Volume, OpenInt).
  • Operations (+, -, *, /, MA, RSI, etc.) are applied element-wise across entire arrays simultaneously, making execution very fast.
  • Formulas typically define rules or calculate indicators based on these array operations.
  • User-defined variables store intermediate or final array/scalar results.

Syntax Basics:

  • Statements end with a semicolon (;).
  • Case-insensitive identifiers (variable/function names).
  • Comments: // single line or /* multi-line */.
  • Whitespace (spaces, tabs, newlines) is mostly ignored except as token separators.
  • Built-in arrays: Open(O), High(H), Low(L), Close(C), Volume(V), OpenInt(OI), Avg ((H+L+C)/3).
  • String literals enclosed in double quotes (").

Operators:

  • Arithmetic: +, -, *, /, % (modulus), ^ (power).
  • Comparison: <, >, <=, >=, == (equality), != (inequality). Return 1 (true) or 0 (false).
  • Logical: AND, OR, NOT.
  • Bitwise: & (AND), | (OR).
  • Assignment: = (simple), +=, -=, *=, /=, %=, &=, |= (compound).
  • Subscript: [] (access array elements, e.g., Close[i]). BarCount gives number of bars (0 to BarCount-1).
  • Matrix Product: @.
  • Type Check: typeof(operand) returns string like "number", "array", "string", "function", "undefined".

Flow Control (v4.40+):

  • Operate on single values (scalars), typically within loops when processing arrays element-by-element.
  • if( condition ) statement1; [ else statement2; ]: Conditional execution. Use {} for compound statements.
  • for( init; condition; loop ) statement;: Looping construct.
  • while( condition ) statement;: Loop while condition is true.
  • do statement; while( condition );: Loop, condition checked after first execution.
  • switch( expression ) { case value1: statement; break; ... default: statement; }: Multi-way branching. break exits the switch.
  • break;: Exits the innermost for, while, do-while, or switch.
  • continue;: Skips rest of current loop iteration, proceeds to next.

User-Defined Functions/Procedures (v4.40+):

  • function FunctionName( param1, param2, ... ) { ... return value; }
  • procedure ProcedureName( param1, param2, ... ) { ... } (no return statement)
  • Encapsulate reusable code.
  • Parameters are passed by value (except Maps which are by reference).
  • Variable Scope:
    • Implicit: Global if first used outside a function, local if first used inside.
    • Explicit: local varname; or global varname; inside a function overrides default.
    • SetOption("RequireDeclarations", True); enforces explicit declaration.

Static Variables (v5.30+):

  • Retain value between formula executions. Allocated on first use, exist until AB closes or StaticVarRemove.
  • StaticVarSet("name", value, persistent = False, compressionMode = cmDefault): Stores scalar, array, or matrix. persistent=True saves/loads value between AB sessions. compressionMode controls array compression (v6.10+).
  • StaticVarGet("name", align = True): Retrieves value. align=True syncs array timestamps.
  • StaticVarSetText("name", "string", persistent = False) / StaticVarGetText("name"): For string values.
  • StaticVarRemove("name*"): Removes static variable(s) (wildcards supported).
  • StaticVarAdd("name", value, keepAll = True, persistent = False): Atomic addition, faster alternative to AddToComposite for creating composites (v6.10+).
  • StaticVarCompareExchange("name", exchange, comperand): Atomic compare-and-swap, useful for inter-thread synchronization (semaphores, critical sections) (v5.50+).
  • StaticVarCount(): Number of static variables in memory.
  • StaticVarInfo("name*", "field"): Get info ("list", "memory", "totalmemory", "count") (v5.60+).
  • Declared Static Variables (v6.30+): Requires #pragma enable_static_decl(prefix). Use static _myvar;. Faster access than StaticVar* functions.

Key Reserved Variables (for Backtesting/Analysis):

  • Buy, Sell, Short, Cover: Arrays holding 1/True for entry/exit signals.
  • BuyPrice, SellPrice, ShortPrice, CoverPrice: Arrays specifying execution prices (default taken from AA Settings). Adjusted to fit High-Low range if needed.
  • PositionSize: Controls trade size. Positive = dollar amount, Negative (-1 to -100) = % of portfolio equity. Can be an array for dynamic sizing.
  • PositionScore: Ranks entry signals when choices exceed limits/funds. Higher absolute value is preferred. Used exclusively in Rotational Trading mode.
  • RoundLotSize, TickSize, PointValue, MarginDeposit: Override per-symbol settings from Symbol->Information.
  • Filter: Exploration mode only. Rows where Filter == 1 are included in results.
  • Exclude: If Exclude == 1, symbol is skipped in AA modes.

Key Reserved Variables (for Indicators/Charts):

  • Title: Overrides the default chart title string. Can include color codes (EncodeColor).
  • GraphXSpace: Sets extra % space above/below plot.
  • GraphZOrder: Controls plotting order (obsolete, use Plot ZOrder parameter).
  • GraphLabelDecimals: Controls number of decimals in value labels (v5.90+).

Important Functions (Selection):

  • Plot(): Primary function to draw indicators (lines, histograms, candles, bars, clouds, etc.). Many style options.
  • PlotOHLC(): Plot custom OHLC charts.
  • PlotShapes(): Draw arrows or other shapes on the chart.
  • PlotForeign(): Plot data from another symbol on the current chart.
  • PlotGrid(): Draw horizontal grid lines efficiently.
  • PlotText() / PlotTextSetFont(): Draw text annotations at specific chart coordinates.
  • Param() / ParamColor() / ParamStr() / ParamStyle() / ParamToggle() / ParamDate() / ParamTime() / ParamList() / ParamField(): Create user-adjustable parameters accessible via the Parameters dialog (Ctrl+R).
  • Ref( array, periods ): Access past (-periods) or future (+periods) values of an array.
  • ValueWhen( condition, array, N=1 ): Get value of array when condition was true N-th time ago.
  • Highest(), Lowest(), HHV(), LLV(), HighestSince(), LowestSince(), HHVBars(), LLVBars(), HighestSinceBars(), LowestSinceBars(): Find high/low values and bars since they occurred over various periods/conditions.
  • MA(), EMA(), WMA(), DEMA(), TEMA(), Wilders(), AMA(), HMA(): Various moving average calculations.
  • StDev(), LinearReg(), LinRegSlope(), Correlation(), Median(), Percentile(), Kurtosis(), Skewness(): Statistical functions.
  • Cross( array1, array2 ): Returns 1 where array1 crosses above array2.
  • IIf( condition, truepart, falsepart ): Conditional value selection (element-wise on arrays). Evaluates BOTH parts. Use if/else for flow control.
  • Cum( array ): Cumulative sum.
  • Sum( array, periods ): Sum over periods lookback.
  • BarIndex(): Returns array of zero-based bar numbers.
  • DateTime(): Returns array of encoded date/time values. Use DateTimeToStr or DateTimeFormat to convert to string. Use DateTimeConvert for other conversions. DateTimeDiff to compare.
  • Day(), Month(), Year(), DayOfWeek(), DayOfYear(), Hour(), Minute(), Second(), MilliSec(), MicroSec(): Extract date/time components.
  • TimeFrameSet() / TimeFrameRestore() / TimeFrameCompress() / TimeFrameExpand() / TimeFrameGetPrice(): Functions for working with multiple time frames within a single formula. Not a replacement for chart/analysis periodicity settings.
  • Foreign( ticker, field, fixup=1 ): Access data array ("O", "H", "L", "C", "V", "I", "1", "2") from another symbol (ticker). fixup=1 fills holes with previous close.
  • SetForeign( ticker, fixup=True, tradeprices=False ) / RestorePriceArrays(): Temporarily replace built-in OHLCV arrays with those of another ticker. Faster than multiple Foreign calls.
  • Study( studyID, chartID=1 ): Reference hand-drawn studies by their ID (set in study properties).
  • AddToComposite( array, "~compositeticker", "field", flags ): Create composite indicators by summing/counting array values across symbols during a Scan.
  • printf() / StrFormat(): Formatted output to Log/Commentary window (printf) or to a string variable (StrFormat). Supports %g, %f, %e, %s.
  • StrExtract(), StrFind(), StrLeft(), StrRight(), StrMid(), StrLen(), StrReplace(), StrSort(), StrToLower(), StrToUpper(), StrToNum(), NumToStr(): String manipulation functions.
  • Gfx* functions: Low-level graphics for custom chart drawing (lines, shapes, text, images). Operate in pixel or bar/price coordinate modes (GfxSetCoordsMode). Control Z-order (GfxSetZOrder).
  • Gui* functions: Create and manage on-chart GUI controls (buttons, edits, sliders, etc.) (v6.30+).

Backtesting & Optimization

Process:

  1. Define trading rules using Buy, Sell, Short, Cover reserved variables in AFL.
  2. Optionally define execution prices (BuyPrice, etc.) and position sizing (PositionSize, SetPositionSize).
  3. Optionally define ranking score (PositionScore).
  4. Optionally set backtester options (SetOption, ApplyStop, SetBacktestMode, SetTradeDelays, etc.).
  5. Open the Analysis window (Analysis -> Automatic Analysis).
  6. Load the formula (Pick button).
  7. Select Apply To range (All symbols, Current, Filter).
  8. Select Range (All quotations, N recent bars/days, From-To dates).
  9. Adjust Settings (Initial Equity, Commissions, Stops, Periodicity, etc.).
  10. Click Back test button.
  11. View results list and click Report for detailed statistics.

Key Settings (Analysis -> Settings):

  • General: Initial Equity, Positions (Long/Short/Both), Futures Mode, Min Shares/Pos Value, Commissions (Table, %, $/Trade, $/Share), Interest Rate, Periodicity, Allow Position Shrinking, Activate Stops Immediately, Round Lot Size, Tick Size, Reverse Signal Forces Exit, Allow Same Bar Exit, Use QuickAFL.
  • Trades: Default Buy/Sell/Short/Cover prices (Open, Close, High, Low, Mid, etc.), Delays (0 = same bar, 1 = next bar, etc.).
  • Stops: Max Loss (%, Points), Profit Target (%, Points), Trailing (%, Points, % Risk), N-Bar. Option ExitAtStop controls if exit happens at stop level (intraday if H/L hits it) or at regular trade price on stop bar/next bar. Stops can be set via UI or ApplyStop() function.
  • Portfolio: Max Open Positions, Artificial Future Bar, Limit Trade Size (% of bar volume), Use Previous Bar Equity for Sizing, Custom Backtest Procedure settings.
  • Report: Result list format (Trade list, Detailed Log, Summary), Risk Free Rates, Include formula/settings/trade list in report, Generate detailed reports for individual backtests.
  • Walk-Forward: Configure In-Sample optimization periods and Out-Of-Sample test periods. Define Optimization Target metric. Start via Optimize button dropdown -> Walk Forward Optimization.
  • Monte Carlo: Enable simulation, set runs, choose method (trade list vs equity changes), configure position sizing for simulation, enable equity curve display. Results appear in "Monte Carlo" tab of backtest report.

Portfolio Backtesting (SetBacktestMode( backtestRegular ) or higher):

  • Tests strategy across multiple symbols simultaneously using a single shared portfolio equity.
  • Requires setting PositionSize to less than 100% (e.g., PositionSize = -25; for 25% of equity per trade).
  • SetOption("MaxOpenPositions", N); limits concurrent trades.
  • PositionScore variable ranks entry signals if candidates exceed limits/funds. Higher absolute score preferred.
  • Supports multiple currencies if configured in Preferences -> Currencies and Symbol->Information.
  • Supports scaling in/out (sigScaleIn, sigScaleOut).

Rotational Trading (SetBacktestMode( backtestRotational )):

  • Fund-switching style. Uses PositionScore exclusively for ranking.
  • Buys/Shorts top N ranked symbols (N based on MaxOpenPositions/funds).
  • Exits when rank drops below SetOption("WorstRankHeld", value).
  • Buy/Sell/Short/Cover variables are ignored.

Optimization:

  • Find optimal parameter values.
  • Use Optimize("Param Name", default, min, max, step) function in AFL for each parameter.
  • Click Optimize button in Analysis window.
  • Results show performance metrics for each parameter combination.
  • 3D Chart: Visualize results for 2-parameter optimizations (Optimize button dropdown -> 3D Optimization Chart). Helps identify robust parameter ranges vs curve-fit spikes.
  • Smart Optimization (Non-Exhaustive): For large parameter spaces. Use OptimizerSetEngine("spso" | "trib" | "cmae"). Faster than exhaustive but may find local optimum. Set options via OptimizerSetOption().
  • Multi-threaded Individual Optimize: Faster single-symbol optimization (Optimize dropdown -> Individual Optimize). Exhaustive only, no custom backtester (v5.70+).

Backtest Report:

  • Provides detailed performance statistics (Net Profit, Annual Return %, Max Drawdown %, CAR/MDD, RAR/MaxDD, Profit Factor, Payoff Ratio, Sharpe Ratio, Win %, Avg Trade, etc.).
  • Separate stats for All, Long, Short trades.
  • Hover over metric names for tooltips.
  • Color-coded values highlight good/bad performance (v5.60+).
  • Can include trade list.
  • Custom metrics can be added via Custom Backtester Interface.

AFL Tools

  • Formula Editor: Primary tool for writing/editing AFL code. Features syntax highlighting, auto-complete, parameter info, error checking, debugging.
  • Automatic Analysis: Main interface for running Scans, Explorations, Backtests, Optimizations.
  • Commentary Window: Displays textual output generated by AFL formulas (printf, WriteIf, WriteVal, NumToStr). Useful for custom interpretations.
  • AFL Code Wizard: Add-on for generating basic trading system code from English-like descriptions.

Troubleshooting & Performance

  • Troubleshooting Guide: Section in the manual covering common problems.
  • Crash Recovery: System attempts to save work on crashes. Automatic bug reporting option.
  • Performance Tuning:
    • Use native AFL functions over OLE/Scripting where possible.
    • Minimize Foreign/AddToComposite calls; use Static Variables for inter-symbol communication if feasible.
    • Limit data size processed, especially for complex formulas or multi-threading. Ensure data fits in RAM.
    • Use QuickAFL (enabled by default in AA settings) when testing partial ranges. Be aware SetBarsRequired(sbrAll) disables it.
    • Static Variables: Write only once per analysis run if possible (use if(Status("stocknum")==0)).
    • Avoid accessing UI elements or OLE objects from AFL code run within indicators or analysis threads, as it serializes execution and can cause deadlocks.
  • Performance Monitor (Tools -> Performance Monitor): Shows memory usage, cache stats, refresh times.
  • Multi-threading: Enabled by default in Pro edition charts and New Analysis. Utilizes multiple CPU cores. Performance depends on formula complexity, data size, and avoidance of shared resource contention (OLE, excessive Foreign/AddToComposite/StaticVar writes).

OLE Automation

  • Allows controlling AmiBroker from external scripts (JScript, VBScript, Python, etc.) or applications.
  • Main object: Broker.Application.
  • Provides access to Stocks collection, individual Stock objects (properties like Ticker, FullName, MarketID, fundamental data fields), Quotations collection (individual Quote objects with Date, O, H, L, C, V, OI), Documents collection, AnalysisDocs collection (for New Analysis window control), etc.
  • Caution: Avoid manipulating UI objects (Documents, Windows, AnalysisDoc) via OLE from within an AFL formula running in that UI context.

This distilled text covers the essential features, concepts, and usage patterns of AmiBroker.

15 Likes

Did you ask it for any suggestions (for next features) while enabled with "Grounding with Google Search" ?

I use LMNotebook with the manual. Instead of searching for a specific topic, I just type in a question and it guides me to the relevant sections while providing key information. Quite impressive and a real time saver!

2 Likes

OpenAI released GPT5 yesterday. My first impression is that it is overly verbose and not as great as OpenAI says. It hallucinates quite a lot. Definitely does not keep the promise of reduced hallucination.

Google’s Gemini Pro 2.5 Pro is still significantly better in my A/B testing in all areas.

Sorry OpenAI but it looks like stagnation.

7 Likes


source: SimpleBench

Gemini Pro ranks 1st indeed!
Still far from the human baseline which explains the hallucination :slight_smile:

Give it time :grin: but at least it has thinking of its own
I never expected that it will deduce that latest conversion was the issue..

Reply from model about why it is not living up to the hype..
If you want, I can explain why GPT-5 may feel weaker in some coding/conversion tasks even though it’s technically stronger — that’s something I’ve noticed in your Pine Script → AFL work. It’s a tuning side effect.

Do you want me to break that down?

I have to write this in the context of what Sam Altman says in their GPT5 announcement.

Sam Altman said in this video:

One of the top use cases of Chat GPT is health. People use it a lot you've all seen examples of people getting day-to-day care advisor sometimes even lifesaving diagnosis. GPT-5 is the best model ever for health. It empowers you to be more in control of your healthcare journey. We really prioritize improving this for GPT-5. It scores higher than the previous model and help bench and evaluation we created with 250 physicians

OpenAI might have bright mathematicians aboard, but sorry to say, someone lost his mind here. IMHO saying such things to public, advertising real use of ChatGPT for self-diagnosis is absurd, dangerous and plain stupid. Sorry Sam, you look like an idiot and charlatan here. I think regulators should step in here and forbid advertising GPT for health and OpenAI and Sam Altman personally should be held responsible not only for not protecting the system against giving absurd medical advice but openly advertising GPT for health.

I don't believe that they are unaware of numerous reports of truly toxic advice given by ChatGPT leading to tragic developments, including inducing psychosis:

https://www.wsj.com/tech/ai/i-feel-like-im-going-crazy-chatgpt-fuels-delusional-spirals-ae5a51fc

causing divorces:

delivering detailed and personalized plans for drug use, calorie-restricted diets or self-injury:

or giving really bad "health plan":

Note: this post was proudly written by human, not AI. (So sorry for grammar imperfections)

10 Likes

No doubt, it is irresponsible on Sam Altman's part, but the intellectual impoverishment of humanity is admirable.

10 Likes

Not very surprising given how much time youngsters spend on mindless scrolling of social media. But they are really the victims of dopamine system in their brains, the blame has to be put on those who offer this brainwashing "entertainment" that is specifically designed to abuse dopamine reward systems in humans.

6 Likes