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.
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.
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.
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:
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.
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.
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.
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).
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.
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).
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).
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.
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).
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).
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.
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.
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.
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.
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.
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).
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().
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.
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.
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!
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.
Give it time 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.
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:
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.