AmiBroker Change Log

CHANGES FOR VERSION 5.70.0 (as compared to 5.69.0)

• GDI: use of PS_ALTERNATE style in Windows 95/98 causes resource leak. Fixed.
• UI: Place Order dialog, it was problematic to enter fractional offsets for brackets. Fixed.
• " Recent database" menu randomly listed files instead of databases. Fixed. Note if you have custom toolbar with "Recent database" submenu added, you need to delete it and re-insert.

CHANGES FOR VERSION 5.69.0 (as compared to 5.68.1)

• Adding symbols via ASCII import caused change of selected symbols in charts. Fixed.
• OLE: AnalysisDoc.Run supports Individual Optimization now (Action == 5)
• Charts: when formula file can not be found the detailed information about the path referenced and current working directory is displayed instead of old "the formula can not be found - no chart to display"
• New Analysis: added Auto-repeat status icon in the right-hand corner of the Info bar (yellow 'play' arrow shows up when auto-repeat is active and scheduled for next run)
• AFL: Percentile() uses now new algorithm that has linear O(n) complexity instead of O(log(n)*n) so it is MUCH faster than the old one and close to Median() that uses quickselect (which is fastest)

By the way, to find average of upper and lower median for EVEN number of elements you can use
Percentile( array, range, 50 )

- it will execute approx 30% slower than Median, but Median only returns LOWER median for even 'range' parameter.

• ODBC plugin: now available in 64-bit
• AFL: since 5.63 round() function used 32-bit floorf which resulted in some differnces as compared to 5.60. Previous code version is restored now.
• DDE plugin: 64-bit version of DDE plugin was producing incorrect timestamps. Fixed.
• Default seed for Random() and mtRandom() was based on time(), which could be the same for threads created in the very same moment. Now the seed in multiple threads is guaranteed to be unique. This prevents repeated pseudo-random sequences in multiple threads created in the very same moment.
• IB plugin: added support for CFDs (security type=CFD, exchange=SMART) and commodities (security type = CMDTY, exchange = SMART)

Example symbology for CFD:
IBUS500-SMART-CFD-USD

Symbol-SMART-CFD-Currency

Example symbology for commodities:
XAUUSD-SMART-CMDTY

Symbol-SMART-CMDTY-Currency

• UI: Now there are separate MRU (most recently used) menus for files and databases (File->Recent Databases, File->Recent Files_)
• Removed / changed some mnemonics (key accelerators) in menus to avoid duplicates
• The default setting for Layers/"Auto-Select Layer" is changed to OFF.

You can use it for example to add full name as a custom metric to the trade list

SetCustomBacktestProc("");

/* Now custom-backtest procedure follows */
if( Status("action") == actionPortfolio )
{
bo = GetBacktesterObject();

bo.Backtest(1); // run default backtest procedure

// iterate through closed trades first
{
}

}

fast = Optimize("fast", 12, 5, 20, 1 );
slow = Optimize("slow", 26, 10, 25, 1 );
Sell=Cross(Signal(fast,slow),MACD(fast,slow));

• SPSO (standard particle swarm optimizer) plugin: now available in 64-bit
• Tribes plugin: now available in 64-bit
• DDE plugin: now available in 64-bit

CHANGES FOR VERSION 5.68.1 (as compared to 5.68.0)

• fixed crash in 64-bit version when usign StaticVarGenerateRanks on large arrays
• AFL: since 5.63 round() function used 32-bit floorf which resulted in some differnces as compared to 5.60. Previous code version is restored now.

CHANGES FOR VERSION 5.68.0 (as compared to 5.67.2)

• AFL: new function: Error("text") - allows to display user-defined error messages and stop execution of the formula. Good for 3rd party plugin implementors to display error messages

Example:
Error("Something went wrong");

Note that error number in case of user-defined error message is always 99.

• AFL: new function: StaticVarGetRankedSymbols( "outputprefix", "inputprefix", datetime )
• AFL: new function: StaticVarGenerateRanks function (flexible ranking function)

NOTE: This function is NOT intended to replace bakctester's built-in ranking via PositionScore. Just the opposite: whenever you can, you should use PositionScore as it is way way faster and less memory-consuming way to perform backtests with ranking. To learn more about how to use PositionScore see "Portfolio level backtesting" section of the tutorial. StaticVarGenerateRanks is intended to be used for tasks OTHER than backtesting such as explorations or indicators that may require ranking functionality.

WARNING: this function is computationally and memory intensive. It takes about 20ms per 15K bars and 7 symbols. Try to call it JUST ONCE per scan/exploration/backtest using if( Status("stocknum")==0) or better yet, use separate scan just once to pre-calculate ranks and use it later (like composite creation scan). If you fail to do so and call StaticVarGenerateRanks for every symbol performance would drop significantly as this function not only needs lots of time to compute but it also has to lock the access to shared memory used by static variables so other threads trying to access static variables would wait until this function completes.

StaticVarGenarateRanks( "outputprefix", "inputprefix", topranks, tiemode )

"inputprefix" is a prefix that defines names of static variables that will be used as input for ranking.
AmiBroker will search for all static variables that begin with that prefix and assume that remaining part of the variable name is a stock symbol. Say you want to rank stocks by ROC (rate of change). All you need to do is to store values into static variables.
Let us say that we will use static variable names like "ValuesToSortAPPL", "ValuesToSortMSFT", and so on.

To fill input static variables you can use this loop:

for( i = 0; ( sym = StrExtract( symlist, i ) ) != ""; i++ )
{
SetForeign(sym );
Value = ROC( C, 10 );
RestorePriceArrays();
StaticVarSet( "ValuesToSort" + sym, Value );
}

Now you are ready to perform sorting/ranking. There are two modes, normal ranking mode and Top/Bottom Rank mode.
Normal ranking mode is performed when toprank argument is set to zero.

StaticVarGenerateRanks( "rank", "ValuesToSort", 0, 1224 );

In this case StaticVarGenerateRanks call would generate set of static variables starting with prefix defined by 2nd argument
each variable holding the rank of particular symbol, so in this case
RankValuesToSortMSFT will hold ranking of MSFT
RankValuesToSortAAPL will hold ranking of AAPL
Note that in AmiBroker rank count start from ZERO.

Third argument (topranks) is zero in normal ranking mode
Fourth argument (tiemode) defines how ties are ranked. Supported modes are 1234 and 1224. In 1224 mode ties are numbered with equal rank.

Example code for normal ranking mode (everything done is done in one pass, can be used in indicator):

symlist = "C,CAT,DD,GE,IBM,INTC,MSFT";

// delete static variables
StaticVarRemove("ValuesToSort*");

// fill input static arrays
for( i = 0; ( sym = StrExtract( symlist, i ) ) != ""; i++ )
{
SetForeign(sym );
Value = ROC( C, 10 );
RestorePriceArrays();
StaticVarSet( "ValuesToSort" + sym, Value );
}

// perform ranking
StaticVarGenerateRanks( "rank", "ValuesToSort", 0, 1224 ); // normal rank mode

for( i = 0; ( sym = StrExtract( symlist, i ) ) != ""; i++ )
{
Plot( StaticVarGet( "RankValuesToSort" + sym ), sym, colorCustom10 + i );
}

Top/bottom ranking mode (that generates top/bottom ranking tables that hold indexes to top ranking values. When topranks > 0 top ranked values are used, when topranks < 0 then bottom ranked values are used. The values are stored in variables that have format of: OutputprefixInputprefixN where N is a number 1, 2, 3 representing top/bottom ranks. Let us assume that OutputPrefix parameter is "Top" and Inputprefix parameter is ROC. In such case variable TopROC1 would hold the index of top rated value. TopROC2 would hold second top rated value, and so on.
StaticVarGenerateRanks function uses rank numbering that starts from ONE. In top ranking mode StaticVarGenerateRanks will also prepare static variable that contains comma separated list of variable names that can be used to find out which index refers to which symbol. So if TopROC1 holds 1 you would lookup first substring in TopROCSymbols variable to find out what variable (symbol) ranked at the top. Additionally StaticVarGetRankedSymbols gives easy-to-use method to retrieve comma separated list of ranked symbols for particular datetime.

Example code for top ranking mode

symlist = "C,CAT,DD,GE,IBM,INTC,MSFT";

// delete static variables
StaticVarRemove("ValuesToSort*");

// fill input static arrays
for( i = 0; ( sym = StrExtract( symlist, i ) ) != ""; i++ )
{
SetForeign(sym );
Value = ROC( C, 10 );
RestorePriceArrays();
StaticVarSet( "ValuesToSort" + sym, Value );
}

// perform ranking
StaticVarGenerateRanks( "rank", "ValuesToSort", 0, 1224 ); // normal rank mode
StaticVarGenerateRanks( "top", "ValuesToSort", 3, 1224 ); // top-N mode
StaticVarGenerateRanks( "bot", "ValuesToSort", -3, 1224 ); // bottom-N mode
for( i = 0; ( sym = StrExtract( symlist, i ) ) != ""; i++ )
{
Plot( StaticVarGet( "RankValuesToSort" + sym ), sym, colorCustom10 + i );
}

sdt = SelectedValue( DateTime() );
Title = "{{NAME}} -{{DATE}} - {{VALUES}} TOP: " + StaticVarGetRankedSymbols( "top", "ValuesToSort", sdt ) +
" BOT: " + StaticVarGetRankedSymbols( "bot", "ValuesToSort", sdt ) ;

• New Analysis: when two Analysis windows were open and running Scan simultaneously with AddToComposite composites could get reset by scan running in second window. Fixed.
• Added millisecond support to ASCII importer. Supported time format with milliseconds is HH:MM:SS.mmm (where mmm is milliseconds 000..999)
• Unsettled sale proceeds were settled at the end of the day instead of the beginning of the next day. Fixed.
• The message 'trade not entered because of insufficient funds' is modified to mention that it also it may not be entered because of incorrect position size specified by the user

CHANGES FOR VERSION 5.67.2 (as compared to 5.67.0)

• Using more than 100 Plot() statements in one formula could cause memory corruption sometimes resulting in access violation. Fixed.
• File->New->Blank chart and then clicking "View" caused exception in 5.67.1. Fixed
• Low-level gfx playback engine resets colors to black pen / white background, so it does not get influenced by chart colors like labels.
• GfxSetOverlayMode( 2 ) sometimes produced incorrect output in 5.67.0. Fixed.

CHANGES FOR VERSION 5.67.0 (as compared to 5.66.0)

• New Analysis: Optimization continued even if there was error inside custom backtest procedure. Fixed.
• Charting: a new "Warning 902 can not plot a chart in logarithmic scale as a data set contains negative value(s)" message is displayed on attempt to use log scale with negative data and the chart is plotted in linear scale instead.
Also the user can add this to View toolbar using toolbar customization (click on arrow in the "View" toolbar, "Add or remove buttons" then "View" then "Logarithmic...")
• AFL: new function fdir( "wildcard", flags = 1 ) - returns comma separated directory list (like "DIR" command)
"wildcard" is a path with a wildcard pattern to match.
For example "C:\\*.*" will give you all files in C: drive, but "C:\\*.txt" will give you only files with .txt extension.
flags - controls what is returned the default is 1 - only files, 2 - only directories, 3 - both files and directories

Example:
printf("Only files:\n");
_N( list = fdir( "c:\\*.*", 1 ) );

for( i = 0; ( filename = StrExtract( List, i ) ) != ""; i++ )
{
printf( filename + "\r\n" );
}

printf("\n\nOnly directories:\n");
_N( list = fdir( "c:\\*.*", 2 ) );

for( i = 0; ( filename = StrExtract( List, i ) ) != ""; i++ )
{
printf( filename + "\r\n" );
}

printf("\n\nBoth files and directories:\n");
_N( list = fdir( "c:\\*.*", 3 ) );

for( i = 0; ( filename = StrExtract( List, i ) ) != ""; i++ )
{
printf( filename + "\r\n" );
}

• GfxSetOverlayMode( mode = 1 ) did not work with "alternate background fill". Fixed.
• Analysis Settings Load/Save buttons were positioned wrong in RTL (right-to-left) systems. Fixed.
• AFL: CategoryCreate( "name", category ) - adds new category (currently supports only adding watchlists)
newwl = CategoryCreate( "name", categoryWatchList ) - this will add (create new) watch list with "name" (if it does not exist) or will return existing "name" watch list

newwl will hold new watch list index.

Currently only creation of watch list is supported by this function.

• 64-bit: Fixed crash with backtest of more than 10 million bars
• 64-bit: Fixed 'squeeze' problem with charts at full zoom out when more than 10 million data bars were displayed
• OLE Stocks.Add and Stocks.Remove trigger resynchronization of selected indexes to avoid problems with "symbol locked" charts

CHANGES FOR VERSION 5.66.0 (as compared to 5.65.0)

• 32-bit and 64-bit versions now use different registry key to save list of DLLs so warning messages about non-certified 3rd party plugins are not displayed each time you switch between 32-bit and 64-bit app version anymore.
• Foreign("~~~EQUITY" ) within custom backtest proc in old AA returned zero (because of change in 5.65). Fixed.
• CBT: when low-level mode was used (no ProcessTradeSignals was called) ~~~Equity open interest field was not filled with number of open positions. Fixed.
• When user moved default Formula path somewhere else Report charts were not generated properly. Fixed.
• CBT: a new field "TransactionCosts" (equivalent to report's "total transaction costs") is now supported in the custom backtester Stats.GetValue method
• ASCII importer: added DELISTING_DATE to fields available in $FORMAT command. To import delisted symbols you may use file like this. Acceptable date formats are YYYY-MM-DD (ISO standard) and DD-MM-YYYY (automatically detected). Note that MM-DD-YYYY (US) is not detected because one can not automatically detect if 01-02-2003 means february 1st or january 2nd #$FORMAT NAME, DELISTING_DATE
$NOQUOTES 1$OVERWRITE 1
SYMBOL,"2012-07-0

• AFL: GetFnData returned invalid value for fields DividendPayDate and ExDividendDate when they were empty (not set) in the Information window. Fixed (now Null is returned)
• AFL: GetFnData now supports new field "DelistingDate"

dd = GetFnData("DelistingDate");
if( IsNull( dd ) )
printf("Security is active");
else
printf( "Delisted at" + dd + DateTimeToStr( dd ) );
• Information window: added "Delisting date" field.
Delisting Date is a last day when security was available for trading due to delisting. If the security is still active the field is empty.
• Information window: it was not possible to set/change Dividend Pay Date and Ex Dividend date from UI. Fixed.
• Preferences window: new tab "Candles & Bars" that controls detailed appearance of candlestick and traditional bar charts

Use up/down colors - when marked bar charts use candlestick up/down color defined in the Colors tab
End cap style - controls whenever bar charts are plotted so the endings of lines are rounded, square or flat.
The difference between square and flat is that square end will plot with "square" pen and with wide pens it will plot width/2 pixels above high and below low because of pen thickness (looks good but high/lows are not precisely marked).
" Flat" means that ends terminate at exact position (so high and lows are precise), but the open/close ticks may look weird when plotted at high/low ("staircase effect")

Open/Close tick % thickness - controls the thickness of line used to plot open/close ticks. It is expressed in % of main bar thickness (default is 100%)
Open/Close tick % length - controls the length of open/close ticks. It is expressed in % of candle width which is usually half the distance between bars (but not more than 30 pixels).

• The database save was triggered when opening documents using recent file list. Fixed.
• Parameter window: Right mouse button double click over parameter label resets selected parameter to the default value now
• AFL: PlotShapes() now has XShift parameter
• Custom metric optimization target (WF tab) is now matched case-insensitive (FC#2442)

CHANGES FOR VERSION 5.65.0 (as compared to 5.64.0)

• In-memory quotation cache can now be larger than 20K symbols. Now the maximum is 100K symbols (user definable in Tools->Preferences, "Data" tab). Caveat use extreme values ONLY if you have plenty of memory AND you are using 64-bit version
• New Analysis: Walk-forward result list colums had "alpha" type which resulted in alphabetic sort when user clicked on column. Fixed (numeric type is used now).
• QuickData did not work properly for not time-based intervals so it is now automatically turned off for charts using such intervals.
• Fixed crash @0048C19A/48C1C4 (click on result list after backtest to show arrows sometimes produced this).
• Trade profit calculation speeded up which results in upto 15% faster optimization with lots of trades
• New Analysis: In 5.64.x "stocknum" incorrectly started counting from 1 instead of 0 as in old versions. Fixed.
• Foreign/SetForeign/RelStrength of the same symbol as active does nothing (i.e. refers to already existing thread local data, instead of querying database)
• New Analysis: when SetSortColumns was used in 5.63 and above it could trigger redundant multiple sorts. Now it is fixed (sort only once)
• New Analysis: results are now sorted after Individual Optimization the same way as after portfolio Optimization

CHANGES FOR VERSION 5.64.0 (as compared to 5.63.0)

• New Analysis: Multi-threaded Individual Optimization (experimental). Upto NumberOfCores faster. Note: no CBT and only exhaustive mode is supported as of now

The new optimizer is called "Individual Optimize" in the New analysis window and you can access it here:

Note that old "Optimize" button runs OLD (i.e. 5.60) optimizer - for comparison purposes.

"Individual Optimize" will use all available processor cores to perform single-symbol optimization.
In "Current symbol" mode it will perform optimization on one symbol.
In "All symbols" and "Filter" modes it will process all symbols sequentially, i.e.
first complete optimization for first symbol, then optimization on second symbol, etc.

Limitations:
1. Custom backtester is not supported (yet)
2. Smart optimization engines are NOT supported - only EXHAUSTIVE optimization works.

For explanation of these limitations see http://www.amibroker.com/guide/h_multithreading.html

Eventually I may get rid of limitation (1) - when I change the CBT NOT to use OLE anymore.
But (2) is probably here to stay for long.

• Built-in constant are set up once and shared among all threads to save setup time (gives 10% speed up in execution of simple formulas)
• Built-in constants such as colorBlack are now read-only and any attempt to overwrite such constant value results in error 55.
• New Analysis, list view in scans, explorations and individual optimizations is refreshed less often to gain some speed.
• In case of individual backtest / individual optimization the backtester allocates much smaller price cache (just for 2 symbols) - takes less time.
• In 5.63 Bar Replay did not with "QuickData" enabled (it required View->Refresh All to start working). Fixed.
• Some actions (like import of past data, split, etc) did not trigger automatic chart refresh when QuickData was enabled. Fixed.

CHANGES FOR VERSION 5.63.0 (as compared to 5.62.0)

• QuickData for charts implemented. QuickData is a new feature that greatly decreases time required to prepare compressed/filtered data for real-time charts.
QuickData is turned ON by default. It can be turned off in Tools->Preferences, "AFL" tab. Do NOT turn it off however, unless you are having problems/issues.
QuickData minimizes number of required operations by analysing what has changed in the input data and re-doing compression only for changed portion. This results in significant real-time performance improvement especially on 1-minute databases having >200K bars and many charts open. With this option turned on and 6 charts open load factor can drop from above 100% to less than 1%. CPU usage drops by more than 7x (from 7% to less than 1%)
• Time&Sales now supports filtering out trades and bid/ask quotes below user-defined size
• Time&Sales allows to customize colors (separate color setting for trades occuring above/at ask, inside, at / below bid, etc). Right-click and use context menu to bring up "Colors..." dialog
• Time&Sales now supports "Wide list" mode in addition to existing "Narrow" mode. "Wide mode" has separate columns for bid / ask data. To switch - right click on the T&S window and choose "Wide" or "Narrow" from context menu
• OpenInterest field of ~~~EQUITY symbol now holds number of open positions on bar per bar basis
• GetFnData() supports now "Currency" and "WebID" fields
• AFL: some transcendental math functions (sqrt, sin,asin, cos, acos, tan, atan, ln, log10, etc) are 10-30% faster now.
• AmiQuote 3.05: fix to "It is illegal to call out while inside message filter" error that sometimes occurred when OLE server was busy during long imports
• ASCII importer: if import takes more than 5 seconds, Windows does not mark AmiBroker as "not responding" anymore
• Progress indicator (for ASCII import) in the status bar is larger and works better for large files
• AFL: SetSortColumns() can now be called more than once to support multiple rankings via AddRankColumn
• 64-bit version: Added 'highDPIaware' and "asInvoker' settings to application manifest in x64 version, to prevent file system virtualization and scaling on high-DPI screens
• Added X/Y constaints for drawing tools. When you hold down "Y" key, start and end Y co-ordinates are set to equal value (with trend line it gives horizontal line). When you hold down "X" key you get perfectly vertical line (X start/end set to equal value)
• When loading and saving quotation files, AmiBroker does not allocate extra memory buffer. This conserves RAM when handling large files.
• 64-bit version is able to load/save files larger than 2GB per symbol (more than 53 million data bars per symbol). Note that you would need to use huge amounts of RAM as using 50 million data bars requires 6GB of RAM or more for any decent performance.
WARNING: Files larger than 2GB can not be used with 32-bit version. You must use 64-bit version in order to be able to access files >2GB.
Also note that loading / saving file that has 2GB (2000MB) size on hard disk that has 100MB/second read/write speed takes over 20 seconds. Do not assume that the program hanged up only because Windows marks it as "not responding" when it is busy writing 2GB+ files. Windows would say the application is 'not responding' if it is busy reading/writing for more than 1 second.
To work with such huge files you should invest in some very fast SSD to cut down those times, with currently fastest SSD use SATA3 6GBps and this would give you theoretical maximum of 750MB per second. Still loading/saving 2GB from such high-performance drive would take 3+ seconds.
• When user re-arranged tabs in the "Log" window, "Clear" and other right-menu commands used wrong tab. Fixed.
• AFL: new function AddRankColumn - adds ranking column(s) according to current sort set by SetSortColumns
Filter = 1;

SetSortColumns(-4);
AddRankColumn(); // rank according to 4th column (descending)
SetSortColumns(-3);
AddRankColumn(); // rank according to 3rd column (ascending)

CHANGES FOR VERSION 5.62.0 (as compared to 5.61.0)

• AddSummaryRows now supports also flag = 32. This flag adds standard deviation row

Filter=1;
// add Total, Average, Min, Max, and Count and StdDev rows (1+2+4+8+16+32)=63 - with two decimal places summary rows are added at the top of the list
• AddSummaryRows treated NULLs as zeros in averages. Now it is fixed and NULLs are not included in calculations.
• Drawing tooltip "bars" count starts from 0 (when line is pure vertical) to match status bar X distance display. Status bar coords display is hidden once drawing is done to prevent user confusion.
• Snap to price now allows snapping to Closing and Opening price, to activate snap to close hold down "C" key, to activate snap to open hold down "O" key while drawing line / moving the mouse
• When "Play" button is pressed Bar replay dialog checks if Start Date is earlier than End date and displays error message if that is not the case.
• Ticker box is updated with new full name if it is changed from symbol information
• Per-symbol UserData fields are accessible now via GetFnData("UserData0")..GetFnData("UserData99"). This feature is for implementors of custom data plugins to allow them to expose custom data
for( i = 0; i < 100; i++ )
printf( "UserData%g %g\n", i, GetFnData("UserData"+i) );
• New Analysis: In 5.61.0 Walk Forward kept old "Current symbol" until Scan/Explore/Backtest was run. Fixed
• First line in "Parallel trendlines" tool is snapped to price (if the option is turned on) as normal trendline.
• eSignal: now plugin supports EOD history for more than 40 years back
• Charting: Copy-Paste Special allows to copy entire chart pane with various options

a) Entire chart pane (fully independent) - it creates a copy of chart pane, assigns new chart ID, creates duplicate of the formula file so parameters are independent and formula is private (not shared with source pane)

b) Entire chart pane (independent parameters, but shared formula), the same as (a) but does NOT create duplicate of the formula so it shares the very same formula file with the original pane

c) Entire chart pane (hard-wired, shared parameters, formula and drawings, same chartID) - a new pasted pane is directly hard-wired with pane being copied, so it shares the same CHART ID and every change made to it is made to the original (source) too.

• Backtest report now includes 'Total transaction costs' (sum of all commissions paid)
• Aux1/Aux2 fields now allow user-definable aggregation/compression mode (File->Database Settings->Intraday Settings). Available choices are last (default), first, highest, lowest, sum

CHANGES FOR VERSION 5.61.0 (as compared to 5.60.3)

• When using any drawing tool X and Y distance is shown in the status bar (FC #2380)
• When position can not be entered due to insufficient funds the Backtester in the "detailed mode" gives additional info such as: requested entry price, requested position size (and dollar value) and requested round lots (FC#2377)
• Time&Sales column layout persists between runs now (FC #2341)
• Running any #import command (including "Update US symbol list and categories") is preceeded by prompt for confirmation now
• Report Explorer now supports copying selected items to clipboard (Edit->Copy), Ctrl+C (FC#2288)
• Quote Editor: added "Go to selected" button that quickly scrolls to and selects the data bar marked on chart (FC#2342)
• New Analysis: parameters were not reset to default values when formula was loaded. Fixed. (#2353)
• New Analysis: "Add artificial future bar" option does not affect Exploration and Scan anymore (FC#2353)
• Max. chart rendering time of 1000 ms when multithreaded charts are turned ON can be overriden now by registry setting. See FC#2330 for details.
• Increased width of symbol combo boxes in Symbol->Merge dialog to prevent truncation of ticker names
• Floating window caption is now synchronized even if it is not active (FC#2376)
• eSignal: new version allows to select whenever EOD bars should report Settlement price or regular close
• Change PlotShapes does NOT use "shape0", "shape1" variables anymore to prevent clashing with user-defined variables (#104931)
• ASCII importer now supports $WEBID command and WEBID field in the$FORMAT command to allow importing web ID (FC#2362)
• ASCII importer now supports $ISINDEX,$ISFAVORITE commands, and ISINDEX and ISFAVORITE fields in the $FORMAT command (FC#2310) • Apply To: Filter dialog takes less time to show up CHANGES FOR VERSION 5.60.3 (as compared to 5.60.2) • When custom backtest formula was defined in separate file then report "Formula" tab shown CBT formula instead of actual system formula. Fixed. • New Analysis, when Apply to was set to "Current" then changing current symbol during optimization affected results. Fixed • New Analysis, database's time shift was applied twice in "Show current trade arrows" mode. Fixed. • Custom backtest procedure was not called when number of trades was equal zero (no trades at all). This prevented creation of custom metrics in such case. Now CBT code is called anyway. • 3D optimization chart was corrupted when optimization included custom metrics. Fixed. • Corrections and updates to Users' Guide CHANGES FOR VERSION 5.60.2 (as compared to 5.60.1) • Setup: GICS.txt file had 50102010 category incorrectly entered (without new line). Fixed. • Setup: Formats\aqgi.format file added • Scale in/out column could have thousand separator added in incorrect place. Fixed. • New Analysis: when there was no selected formula filey a number of empty items were added to the combo box. Fixed. • New Analysis: Walk-forward summary report name and from date was not reset in second and subsequent runs in the same Analysis window. Fixed. • New Analysis: if symbol did not have any quotes at all, "wait for backfill" did not wait. Fixed. • New Analysis: Exploration - a little speed up by decreased number of string reallocations in CAnalysisExploreJob::Run • Inactive Web research window did not sync with selected symbol when "sync always" was turned on. Fixed. MG #113 • Filter dialog background change did not look nice on Windows XP and earlier. Turned this off in pre-Vista OSes. • eSignal: in "EOD" mode when started outside trading session a last bar could be duplicate of previous day bar. Fixed • eSignal: 64-bit plugin now correctly downloads daily (EOD) history (so mixed mode works fine too). • eSignal plugin: added support for extended intraday (to enable it use Configure: "Use extended intraday history data request") • Due to Windows "feature" dotted lines with width of 1 were printed as solid lines on a printer. Workaround (forcing width to 0) for printer implemented. • Default black chart theme is only set when no preferences file is found. If broker.prefs exists but it is stored in pre-5.52 version then white scheme is applied by default. • Charts: when loading multiple chart layout the invisible/obscured windows were not always scrolled to the end (most recent quote). Fixed. • Auto-hidden Analysis windows sometimes did not repaint properly. Fixed. • Sharpe ratio now uses floating point trade length/qty ratio instead of integer to prevent rounding. • AFL: Now OLE strings passed by reference (VT_BSTR|VT_BYREF) are accepted too. CHANGES FOR VERSION 5.60.1 (as compared to 5.60.0) • New Analysis: when OoS test was turned OFF in advanced Walk Forward mode, it would crash at the end attempting to create summary out of non-existing out-of-sample tests. Fixed. • New Analysis: Walk-forward combined OoS equity is just concatenation of OoS steps and no scaling is applied anymore. This it little faster and prevents some boundary/roundoff conditions. • Inactive tab text color is now fixed RGB (#656565) instead of querying system COLOR_GRAYTEXT as it is too light on XP. If you want inactive tab text to be completely black, then create registry key HKEY_CURRENT_USER\Software\TJP\Broker\Settings\InactiveTabTextColor with DWORD value of 0 (zero) Instead of black (0) you may use any other RGB value of course [HKEY_CURRENT_USER\Software\TJP\Broker\Settings] " InactiveTabTextColor"=dword:00000000 • In 5.58 and above Study() only worked in indicators, and always referred to current chart ID. It did not work in Analysis. Fixed. • ASCII import: ASCII characters above code 127 are not trimmed from the end of strings anymore. CHANGES FOR VERSION 5.60.0 (as compared to 5.59.0) • Upgrade information: keys issued before 2011-04-13 are expired with 5.60 • UI: removed unused options from Prefs/Miscelleneous page • UI: In 5.59 ticker box was not in sync with currently selected symbol on loading single-chart layout. Fixed • UI: importing custom icon image using Tools->Customize, button RMB -> Edit Image -> Import image caused change of current working directory. Now CWD is saved and restored after customization. • UI: Floating panes use themed frames now • UI: Filter settings dialog is resizable now (and static fields use proper background color) • UI: Crash could occur if the user customized Tools menu by moving "Update US stock list..." item from the very last position in the menu elsewhere. Fixed. • UI: cosmetic color changes (chart sheet tabs) • On attempt to close Analysis window that is currently running scan/exploration/backtest an appropriate error message is displayed. • New Analysis: the message "No symbols matched apply to / filtering criteria" shows up in the message bar instead of dialog, so one does not need to click OK • New Analysis: Specifying ReEntryDelay > 0 in ApplyStop rotational and raw modes caused incorrect results in second and subsequent backtests (MG#79). Fixed. • New Analysis: In 5.59 3D optimization chart - wrong 2nd axis legend was wrong (duplicate of 1st axis). Fixed. • New Analysis: In 5.58 and 5.59 smart optimizer engine was not finalized properly when user pressed "Cancel" during optimize run. Fixed. • New Analysis: error message bar text is now trimmed to 110 characters to ensure there is a place for the "Details" button • In colorCycle sequence colorRed is replaced with colorLightOrange for better visibility when displayed with red candles • In 5.58 View->Intraday->Tick turned incorrect "0-tick" interval which resulted in effective 1-second compression. Fixed. • colorDefault is now user- definable in the preferences (Colors tab) and selectable from Parameters window and associated with chart theme • Charts: Print Preview and printout had incorrect colors due to the fact that SetDCPenColor/SetDCBrushColor APIs do not work with metafiles/printers. Fixed. • Charts: In 5.59 chart could stop refreshing when it had odd number of Plot() calls combined with a couple of PlotForeign() calls and total number of items to display in tooltip/data window exceeded 20. Fixed. • Changed default Price all in one volume to color to ColorBlend( ColorRGB( 128, 128, 192 ), GetChartBkColor(), 0.5 )), • Changed default colors for charts to "Black" scheme and outline mode to "One color for entire handle and hollow up candle body" • Changed default chart layout for clean installation • Changed default appearance to VS2010 / pane tabs on bottom • Changed Bollinger band filled default color to ColorBlend( Color, GetChartBkColor(), 0.8 ) • changed all price formulas shipped in setup to use colorDefault instead of colorBlack • Blank chart panes now use defined chart background color instead of white • Background of built-in dark grey theme made slightly lighter than black • ASCII import: sector names beginning with "Sector" and industry names beginning with "Industry" were not imported properly. Fixed. • aqh.format, aqd.format, aqg.format changed - removed$VOLFACTOR 0.01 previously used so volume is reported in shares not in hundreds of shares
• ApplyStop( stopTypeNBar, ... ) in backtestRegularRaw / backtestRegularRawMulti/Rotational - N-bar stop exited 1 bar later than in regular mode. Fixed.
• AFL: when array was passed as "amount" argument to DateTimeAdd, the results could be incorrect. Fixed.
• AFL: SetChartOptions did not write chart flags in 5.5x. Fixed
• AFL: GetFnData() now supports "Country" field

CHANGES FOR VERSION 5.59.0 (as compared to 5.58.0)

• New Analysis: loading previously stored APX files into 5.58 resulted in ICB filter being set (instead of cleared). Fixed.
• New Analysis: 3D optimization chart can also be displayed from single-parameter optimization now, without need to add dummy Optimize()
• IB data plugin: CMDTY historical requests use MIDPRICE instead of TRADES
• IB data plugin: Max. number of symbols increased to 1000
• UI: Tools->Preferences/Charting: added setting to show (or hide) the bar number in the crosshair's X label, by default the bar number is NOT shown now (previously it was ON by default)
• UI: Tools->Preferences/Charting removed setting for "'New look' charts" - now 'New look' is used always
• UI: For PlotOHLC and Plot with styleCandle/styleBar tooltip and data window display OHLC data in this order (instead COHL in previous versions)
• UI: Data window now displays values for all panes at once (you can turn the display of single pane back using right click menu option)
• ASCII importer: added $COUNTRY command and COUNTRY field to$FORMAT command
• AFL: in ROC, RSI, RSIa, TRIX, CCI, MFI, MA, EMA, Hold, BBandBottom, BBandTop, PDI, MDI, ADX, ATR, Correlation, Wilders functions 'range' parameter is now checked for > 0 and error is displayed when it is negative
• Interval-locked layers did not work correctly for N-tick/volume/range intervals. Fixed.

CHANGES FOR VERSION 5.58.0 (as compared to 5.57.1)

• DB: Automatic setup and update of stock symbol listing, together with sectors, industries, markets and groups (Tools->Update US symbol list and categories). This is implemented using new #import command and new ASCII importer commands (see below for the details)
• UI: custom tools menu - added special internal command #import that allows to import ASCII files from local disk or even from remote (web) sources. In the Tools->Customize, "Tools" page, you can now define custom tool that uses new #import command
Command: #import
Initial dir: path to format definition file
• UI: custom tools menu - when an error occurs during launching of external command appropriate error message is displayed (instead of nothing like in old versions)
• DB: The support for Industry Classification Benchmark (ICB) category system added (See icb.txt file for definitions)
• OLE: Stock object has new property (string): ICB (read/write)
• ASCII importer: support for importing sector/industry scheme and assignments by name (new SECTORNAME and INDUSTRYNAME fields in $FORMAT command) • ASCII importer: new command$CLEARSECTORS 1 to wipe existing sector / industry structure.
• ASCII importer: new $SORTSECTORS command to sort existing sector/industry structure.$SORTSECTORS 1 - sort case sensitive, without touching sector/industry == 0 (undefined sector/undefined industry)
$SORTSECTORS 2 - sort case sensitive, all defined sectors/industries$SORTSECTORS 3 - sort case insensitive, without touching sector/industry == 0 (undefined sector/undefined industry)
$SORTSECTORS 4 - sort case insensitive, all defined sectors/industries • ASCII importer: crash could occur if required numeric arguments for some commands were missing. Fixed. • ASCII importer: added support for ICB import: ICB field added to$FORMAT command and added $ICB command For example ICB assignments for NYSE can be imported from this site: http://www.nyse.com/indexes/nyaindex.csv (to import use this format def)$FORMAT FullName, Ticker, Skip, ICB, Skip, Skip, Skip, Skip
$SKIPLINES 2$SEPARATOR ,
$CONT 1$GROUP 255
$AUTOADD 1$NOQUOTES 1

• ASCII importer: numeric field data may be enclosed in double quotation marks and still properly interpreted as numbers now.
• AFL: SetChartOptions did not allow to overwrite miny/maxy in 5.51-5.57. Fixed.
• AFL: CategoryGetSymbols, CategoryGetName, CategorySetName, CategoryAddSymbol, CategoryRemoveSymbol, CategoryFind updated to support categoryICB (new constant = 8)
• AFL: added InIcb() and IcbID() functions
• AFL: Added Status("lastbartimeleftrt") - it works like "lastbartimeleft" but uses the most recent RT stream update time instead of Now(). Also added Status("lastrtupdate") - time of last RT stream update
Depends on RT plugin to deliver correct DateUpdate / TimeUpdate data.
If plugin or date source sends incorrect datetimestamps or does not send DateUpdate/TimeUpdate correctly this function will not operate properly.
Note that most data sources send weird (not current) datetime stamps on weekends. Also IQFeed plugin sends DateUpdate/TimeUpdate only inside regular trading hours
• UI: Interval combo box was not updated after changing preferences / intraday / custom interval settings. Fixed.
• Analysis: when optimization is stopped, Optimize() returned NON-default value when Status("action")==actionPortfolio in subsequent backtest. Fixed

CHANGES FOR VERSION 5.57.1 (as compared to 5.57.0)

• When real-time quotes were streaming interval combo refreshed too often making it hard to enter new interval in 5.57.0. Fixed.
• Entering custom interval in the combo did not always work correctly for floating windows in 5.57.0. Fixed.

CHANGES FOR VERSION 5.57.0 (as compared to 5.56.0)

• Charts/UI: now there is a new chart interval combo box that allows to either select predefined interval OR simply type ANY interval you want without the need to define it in the preferences
Supported interval codes are:
Y - yearly, Q - quarterly, M - monthly, W - weekly, D - daily, N - day/night,
h - hourly, m -minute (note lowercase m), s - second, T - tick, R - range, V.

D, h, m, s, T, R, V intervals can be preceded by a number. So if you type 15m it means 15 minute chart,
if you type 13T it means 13 tick chart, if you type 200R it means 200R (range) chart.
If you type just a number (x) without the following letter it will treat it as x-minute chart.

Note that while AmiBroker is trying to keep layout files backward compatible, attempt to load the layout that uses 'new' interval that is not present in defined set into *old* (pre-5.57) version will result in this extra interval being replaced by simply daily chart.

• Tools->Auto update quotes is now native command (not a 'custom tool' as it was)
This change was caused by the fact that custom tools menu is stored in HKEY_CURRENT_USER registry key that is shared between 32-bit and 64-bit version.
That caused that if both 32-bit and 64-bit versions were installed an unmatching bitness version of AmiQuote could be launched and that in turn
caused problems because in Windows OS 64-bit automation first calls 64-bit server and only in absense of it tries 32-bit. So if both versions were installed
only one was updated properly (the last one installed) using "Auto-update" command.
Having this command native ensures that proper bitness version is launched so 32-bit and 64-bit versions of AmiBroker can be updated with appropriate corresponding versions of AmiQuote.
• Default "X grid spacing" changed to 50 (from original 60) pixels
• 12 hour X grid spacing replaced by 6 hour

CHANGES FOR VERSION 5.56.0 (as compared to 5.55.1)

• New Analysis: A new walk-forward summary report that covers all out-of-sample steps
There were significant changes to walk forward testing made to allow summary out-of-sample report.
The most important change is that each subsequent out-of-sample test uses initial equity equal to previous step ending equity.
(Previously it used constant initial equity).
This change is required for proper calculation of all statistics/metrics throughout all sections of out-of-sample test.

Summary report shows the note that built-in metrics correctly represent all out-of-sample steps
but summary custom metrics are composed using user-definable method:
1 first step value, 2 last step value, 3 sum, 4 average, 5 minimum, 6 maximum.

By default summary report shows last step value of custom metrics UNLESS user specifies different combining method in

bool AddCustomMetric( string Title, variant Value, [optional] variant LongOnlyValue, [optional] variant ShortOnlyValue , [optional] variant DecPlaces = 2, [optional] variant CombineMethod = 2 )

This method adds custom metric to the backtest report, backtest "summary" and optimization result list. Title is a name of the metric to be displayed in the report, Value is the value of the metric, optional arguments LongOnlyValue, ShortOnlyValue allow to provide values for additional long/short-only columns in the backtest report. Last argument DecPlaces controls how many decimal places should be used to display the value.

Supported CombineMethod values are:
1 first step value, - summary report will show the value of custom metric from very first out-of-sample step
2 last step value (default), - summary report will show the value of custom metric from the last out-of-sample step
3 sum, - summary report will show the sum of the values of custom metric from all out of sample steps
4 average, - summary report will show the average of the values of custom metric from all out of sample steps
5 minimum, - summary report will show the smallest value of custom metric from all out of sample steps
6 maximum.- summary report will show the largest value of custom metric from all out of sample steps

Note that certain metrics calculation methods are complex and for example averaging them would not lead to mathematically correct representation of all out of sample test.
Summaries of all built-in metrics are mathematically correct out-of-the-box (i.e. they are *not* averages, but properly calculated metrics using method that is appropriate for given value). This contrasts with custom metrics, because they are user-definable and it is up to the user to select 'combining' method, and still it may happen that none of the available methods is appropriate.
For that reason the report includes the note that explains what user-definable method was used to combine custom metrics.

• New Analysis: walk forward procedure now produces detailed reports for every out-of-sample step
• Enhanced backtest report: color-coding 'good' and 'bad' values in backtest report
Some of the metrics in the backtest report are color-coded.
Blue means "neutral", Green means "good", Red means "bad"
Metrics that are not colorized are always black
This color coding is of course arbitrary and should be used as guideance only.
Treat 'red' as a warning flag and advice to check the value in detail.

As of now the following metrics are colorized:
Net Profit, Net Profit % - bad < 0, good > 0
Annual Profit %, bad < 0, neutral betwen 0 and 10, good > 10
RAR % bad < 0, good > (10 / Exposure)
Avg. Profit/Loss all trades (Expectancy ) - bad < 0, good > 0 Avg Profit/Loss % all trades (Expectancy %) - bad < 0, good > 0 Max. system % drawdown - bad: dd worse than -30%, neutral: dd between -30 and -10%, good - -10% to 0% CAR/MaxDD, RAR/MaxDD - bad < 1, neutral between 1 and 2, good > 2 Recovery factor - bad < 1, neutral between 1 and 2, good > 2 Payoff ratio - bad < 1, neutral between 1 and 2, good > 2 • Report: a note added to tooltips for Sharpe ratio and UPI metrics telling where user can change risk-free rates for those metrics • Report Explorer 1.0.2 - added alternate row background color • Removed "00:00:00" time in the "date from" in the backtest report / settings page • Param window: clicking on category that had exactly same name as parameter resulted in changing parameter value. Fixed. • Analysis: all custom metrics were treated as numbers (for example got formatted with thousand separator). Now AmiBroker custom metrics of string type are treated as strings and do not get any extra formatting for the display. • Added recommendation to activate multithreading to the performance warning tooltip when multithreading is currently turned OFF. CHANGES FOR VERSION 5.55.1 (as compared to 5.54.0) • Random characters could appear in list view clipboard copy in 5.55.0. Fixed (5.55.1). • _SECTION_BEGIN/_SECTION_END/_PARAM_VALUES appeared twice in auto-complete listbox. Fixed. • SetOption("PortfolioReportMode", x ) changed exploration columns too. Fixed. (bmg#92) • AFL: new function GetAsyncKeyState( vkey ) GetAsyncKeyState is 100% equivalent of Windows API function of the same name. See: http://msdn.microsoft.com/en-us/library/windows/desktop/ms646293(v=vs.85).aspx The function queries current state of keyboard keys (at the time of the call). vkey is virtual key code to query (see table below). The function returns 0 if key is NOT pressed and value < 0 ( less than zero) when key is currently pressed. Example: Plot( C, "Close", colorRed ); vk_Shift = 16; if( GetAsyncKeyState( vk_Shift ) < 0 ) Title = "Shift is pressed";  Virtual Key codes: vk_BackSpace = 8; vk_Tab = 9; vk_Return = 13; vk_Shift = 16; vk_Control = 17; vk_Alt = 18; vk_Pause = 19; vk_CapsLock = 20; vk_Escape = 27; vk_Space = 32; vk_PageUp = 33; vk_PageDown = 34; vk_End = 35; vk_Home = 36; vk_Left = 37; vk_Up = 38; vk_Right = 39; vk_Down = 40; vk_PrintScreen = 44; vk_Insert = 45; vk_Delete = 46; /* NOTE: vk_0..vk_9 vk_A.. vk_Z match regular ASCII codes for digits and A-Z letters */ vk_0 = 48; vk_1 = 49; vk_2 = 50; vk_3 = 51; vk_4 = 52; vk_5 = 53; vk_6 = 54; vk_7 = 55; vk_8 = 56; vk_9 = 57; vk_A = 65; vk_B = 66; vk_C = 67; vk_D = 68; vk_E = 69; vk_F = 70; vk_G = 71; vk_H = 72; vk_I = 73; vk_J = 74; vk_K = 75; vk_L = 76; vk_M = 77; vk_N = 78; vk_O = 79; vk_P = 80; vk_Q = 81; vk_R = 82; vk_S = 83; vk_T = 84; vk_U = 85; vk_V = 86; vk_W = 87; vk_X = 88; vk_Y = 89; vk_Z = 90; vk_LWin = 91; vk_RWin = 92; vk_Apps = 93; /* numerical key pad */ vk_NumPad0 = 96; vk_NumPad1 = 97; vk_NumPad2 = 98; vk_NumPad3 = 99; vk_NumPad4 = 100; vk_NumPad5 = 101; vk_NumPad6 = 102; vk_NumPad7 = 103; vk_NumPad8 = 104; vk_NumPad9 = 105; vk_Multiply = 106; vk_Add = 107; vk_Subtract = 109; vk_Decimal = 110; vk_Divide = 111; /* function keys */ vk_F1 = 112; vk_F2 = 113; vk_F3 = 114; vk_F4 = 115; vk_F5 = 116; vk_F6 = 117; vk_F7 = 118; vk_F8 = 119; vk_F9 = 120; vk_F10 = 121; vk_F11 = 122; vk_F12 = 123; vk_F13 = 124; vk_F14 = 125; vk_F15 = 126; vk_F16 = 127; vk_NumLock = 144; vk_ScrollLock = 145; vk_LShift = 160; vk_RShift = 161; vk_LControl = 162; vk_RControl = 163; vk_LAlt = 164; vk_RAlt = 165; vk_SemiColon = 186; vk_Equals = 187; vk_Comma = 188; vk_UnderScore = 189; vk_Period = 190; vk_Slash = 191; vk_BackSlash = 220; vk_RightBrace = 221; vk_LeftBrace = 219; vk_Apostrophe = 222; • AFL: Status() function supports new fields "lastbarend", "lastbartimeleft", "timeshift" Status("lastbarend") returns DateTime of the end of last bar. For example 5 -minute bar at 9:00 will have end time of 9:04:59 (works for time-based bars only) Status("timeshift") returns database timeshift expressed in seconds Status("lastbartimeleft") returns number of seconds to the completion of current last bar. Works for time-based bars only. Note that for proper operation this requires database timeshift to be set properly (so dates displayed on chart match your local computer time zone). • List view clipboard copy now uses regional settings decimal separator. You can turn it off and revert to "always dot" decimal separator by creating registry key HKEY_CURRENT_USER\TJP\Broker\Settings DWORD value "UseLocaleForClipboard" = 0 • Charting: added left- and right extend option to the rectagle drawing tool • List view date column sort was incorrect when regional settings time format was set to: H:mm:ss. Fixed. • When multithreading in charts was turned OFF, drawing tools did not work properly in 5.53-5.54. Fixed. • XYChartAddPoint does not generate error anymore when Null values are passed as X, Y co-ords. Instead it silently ignores such points (they are not plotted) and XYChartAddPoint returns FALSE (0) • AFL: new function StaticVarInfo( "varname", "field" ) StaticVarInfo( "varname", "field") - provides information about static variables " varname" - is a variable name. It can be also a wildcard template such as "myvariable*" and then it means that AmiBroker will search for all variables beginning with " myvariable". * character matches any string, ? matches any single character Supported "field" values are: " list" - returns the list of static variables " memory" - returns memory usage in bytes (not including memory used for variable name itself) " totalmemory" - returns memory usage in bytes (including memory used for variable name) Example: StaticVarSet("my_array1", Close ); StaticVarSet("my_array2", Close ); StaticVarSet("my_scalar", 12 ); StaticVarSetText("my_text", "Text123456" ); "All variables in memory: " + StaticVarInfo( "*", "list" ); " Total static var memory: " + StaticVarInfo( "*", "totalmemory"); " Only my_ variables: " + StaticVarInfo( "my_*", "list" ); " Memory 2 arrays (bytes): " + StaticVarInfo( "my_array*", "memory" ); " Memory scalar (bytes): " + StaticVarInfo( "my_scalar", "memory" ); " Memory text (bytes): " + StaticVarInfo( "my_text", "memory" ); CHANGES FOR VERSION 5.54.0 (as compared to 5.53.1) • New Analysis: "Sync chart on select" did not respect linked charts and symbol lock. Fixed. • AFL: new function XYChartSetAxis( "chartname", "x-axis name", "y-axis name" ) • AFL: new function XYChartAddPoint( "chartname", "text", x, y, color ) • New Analysis: Implemented XY (scatter) charts in Explorations Example: // XY chart coding example // This formula generates 2 X-Y scatter charts that display relationship between // final trade profit and MFE and MAE Buy = Cross( MACD(), Signal()); Sell = Cross( Signal(), MACD() ); Short = False; Cover = False; Eq = Equity( 1 ); // single-security equity this evaluates stops (if you use them) and removes extra signals Entry = Buy OR Short; EqAtEntry = ValueWhen( Entry, Eq ); Profit = 100 * ( Eq - EqAtEntry ) / EqAtEntry; // percent profit // MAE and MFE below use CLOSING equity, MAE and MFE in the report use high/low price MAE = 100 * ( LowestSince( Entry, Eq ) - EqAtEntry ) / EqAtEntry; // percent MAE MFE = 100 * ( HighestSince( Entry, Eq ) - EqAtEntry ) / EqAtEntry; // percent MAE bi = BarIndex(); Len = bi - ValueWhen( Entry, bi ); EntryPrice = ValueWhen( Entry, BuyPrice ); // if you prefer MAE/MFE using high/low price // uncomment the lines below (long only Version) MAE = 100 * ( LowestSince( Entry, Low ) - EntryPrice ) / EntryPrice ; // percent MAE using low MFE = 100 * ( HighestSince( Entry, High ) - EntryPrice ) / EntryPrice ; // percent MAE using high Exit = Sell OR Cover; dt = DateTime(); Clr = ColorHSB( Status("stocknum"), 255, 255 ); for( bar = 0; bar < BarCount; bar++ ) { if( Exit[ bar ] ) { // item text consists of two parts // first part (before \t) is a item name displayed immediatelly on XY chart // second part (after \t) is a tooltip hint text that is displayed in the tooltip // when you hover on given item // here we will only use hint text HintText = "\t" + Name()+"@"+ DateTimeToStr( dt[ bar ] ); XYChartAddPoint( "Profit vs MAE", HintText, MAE[ bar ], Profit[ bar ],Clr ); XYChartAddPoint( "Profit vs MFE", HintText, MFE[ bar ], Profit[ bar ], Clr ); XYChartAddPoint( "Profit vs trade length", HintText, Len[ bar ], Profit[ bar ], Clr ); } } XYChartSetAxis( "Profit vs MAE", "[MAE]", "[Profit]" ); XYChartSetAxis( "Profit vs MFE", "[MFE]", "[Profit]" ); XYChartSetAxis( "Profit vs trade length", "[Length]", "[Profit]" ); Filter = Exit; AddColumn( Eq, "Equity" ); AddColumn( Profit, "Profit" ); AddColumn( MAE, "MAE" ); AddColumn( MFE, "MFE" ); AddColumn( Len, "trade length" ); • {{INTERVAL}} gave incorrect (unstable) results in custom n-tick/n-range/n-volume charts when used with multithreading. Fixed. • Interval(2) returned incorrect (unstable) results in custom n-tick/n-range/n-volume charts when used with multithreading. Fixed. • Preferences: Currency page was not working properly. Fixed. • Status bar look matches now appearance settings (esp. visible in VS2012 style) • Parameter window now allows to select combined styles (like styleHidden) as well as their components styleNoRescale+styleNoDraw independently • User setting for minimum pixel spacing in X grid (Tools->Preferences, "Axes / Grids") - it is recommended to keep it at default value (60 pixels), for denser grid use less spacing (minimum 30 pixels), for wider grid use more x spacing (maximum 120 pixels) • Sometimes panes did not refresh to final size when chart sheets are switched (for example - one tab has only one pane second tab has two panes). Fixed. CHANGES FOR VERSION 5.53.1 (as compared to 5.53.0) • Trend lines and other drawing tools sometimes were blinking or disappeared in 5.53.0. Fixed • Plots with styleDashed mixed with plots using other styles could cause continuous growth of rendering time in 5.52/5.53. Fixed. CHANGES FOR VERSION 5.53.0 (as compared to 5.52.0) • Triangle drawing tool now supports filled interiors • Vertical selector line was flicerking with RT update when more than one chart window was open. Fixed • SetChartGradientFill renamed to SetGradientFill • SetGradientFill now has 2 more arguments: baseline and baselinecolor. Allows reverse gradient chart (such as underwater equity) and 3 color gradients top->baseline->bottom • Added 2-year and 5-year x grid spacing • Gradient chart sometimes disappeared when null values were in the data set and chart was zoomed out to the maximum. Fixed. • GUI: Preferences dialog adjustments (moved "bold" checkbox in color page, removed obsolete "show vertical line" boxes in charting page, moved candlestick outline color settings from charting to color page ) • styleClipMinMax interferred with styleGradient in 5.52.0. Fixed (both styles can now be used independently as well as combined together) CHANGES FOR VERSION 5.52.0 (as compared to 5.51.2) • Chart themes implemented, featuring new look, new grid settings, new background gradient fills, predefined themes for more details see: http://www.amibroker.com/guide/h_themes.html • Charts: X-axis algorithm rewritten (now it is clearer and prevents overcrowded/unreadable X labels) • Charts: added native gradient area charts. Gradient chart is obtained using styleGradient. Upper gradient color is specified by color parameter in Plot() function, bottom gradient color is either background color or can be defined using SetChartGradientFill function. styleGradient can be combined with styleLine Example SetChartGradientFill( colorLightOrange, colorPaleGreen ); Plot( C, "Close", ColorBlend( colorPaleGreen, colorBlack ), styleGradient | styleLine, Null, Null, 0, -1 ); • Charts: Plot/PlotForeign/PlotOHLC now adds extra parameter "width" that controls the width of the line. Positive values specify PIXEL width, negative values specify width in percent of current bar width. So for example -20 will give you dynamic width that is 20% of bar width. Example:  Plot( C, "Close", colorBlack, styleBar, Null, Null, 0, 1, -20 /* line width as percent of bar */ );  • Eliminated build-up of rendering times caused by growing of MFC temporary GDI object maps in non-UI threads. Now rendering engine uses direct WINAPI calls without MFC • View->Filtering menu was disabled in 5.51.x. Fixed • Data window was not working in 5.51.x. Fixed • " Show middle lines" = "NO" causes date axis to be moved down outside visible area. Fixed. • Selector line was not working correctly in 5.51. Fixed. • Bold dotted trendline did not work in 5.51 BETA. Fixed • AFL: LinearReg/LinRegSlope/LinRegIntercept/TSF/StdError display proper error message when user passes negative (wrong) parameter • Study tooltip information now includes also number of bars between start and end of the trendline • New Analysis: saving last column layout works better • Account manager: Edit->Undo menu was missing. Fixed. • GetFnData() now supports retrieving "Address" field too • On Win98 and above drawing engine uses DC_PEN/DC_BRUSH for speed • Optimize() reduced possibility of IEEE floating point accumulation errors with steps < 1 (such as 0.01) • PlotShapes() does not plot multiple times in same x/y pos anymore - it results in faster rendering when shapes overlap (large zoom outs) CHANGES FOR VERSION 5.51.2 (as compared to 5.51.1) • PlotShapes() rendering was slower in 5.51 than in 5.50. Fixed. • Interpretation was blank with new rendering engine. Fixed. • Charts: Quick AFL was disabled in new rendering engine causing slowdowns with > 100K bars. Fixed CHANGES FOR VERSION 5.51.1 (as compared to 5.51.0) • fix for low-level Gfx* functions causing crash when multithreaded GDI was enabled CHANGES FOR VERSION 5.51.0 (as compared to 5.50.5) • Charts: Multithreaded GDI implemented for super-smooth UI response and preventing GDI-intensive charts from detoriating entire UI responsiveness • Maximum rendering time limit increased to 1000ms (1sec) when multithreaded charts + GDI are enabled (allowing 2 times more complex plots without Warning 901) • 64-bit only: eSignal plugin - first BETA version of 64-bit eSignal plugin (3.0.0) CHANGES FOR VERSION 5.50.5 (as compared to 5.50.4) • Newly created chart template did not save current tab when it was not switched before saving. Fixed. • Notepad window is refreshed when it is brought back from invisible tab • AFL Code Wizard: sometimes 64-bit version of AFL wizard could hang on clicking "AND/OR" rule. Fixed (AFL Wizard 1.0.2) • Charts: Invisible Symbol-linked charts may not be properly refreshed when changing symbol (happens only when not using streaming RT source). Fixed. • OLE: AnalysisDoc.Run now supports mode =3 (individual backtest) • AFL: Equity()/Status()/GetOption used on chart referred to OLD AA settings instead of last run analysis (whenever it is old AA or new). Now uses last run analysis settings . • AFL: SetFormulaName did not work in New Analysis. Fixed. CHANGES FOR VERSION 5.50.4 (as compared to 5.50.3) • New Analysis: "Show arrows for actual trades" sometimes used date range from old AA. Fixed • New Analysis: Individual backtest - custom metrics columns would not appear if very first symbol under test does not generate ANY trades. Fixed. • UI: when you float a maximized MDI window it becomes little smaller so it does not overlap MDI tabs. • Print/Print Preview: circle/arc/rectangle objects outside current view are properly clipped on printouts • New Analysis: When user cancelled optimization in the middle and ran backtest afterwards then this single follow up backtest could be incorrect and required another run to produce correct result again. Fixed. • When timeshift != 0 then duplicate range markers could appear at day boundary. Fixed. • Small rounding issue in ray drawing fixed • When multiple chart panes were using SetForeign on rare occassions foreign call could fail (return other symbol data) Fixed. CHANGES FOR VERSION 5.50.3 (as compared to 5.50.2) • New Analysis: proper symbol list refresh is triggered when composites are created or user calls SetOption("RefreshWhenCompleted, True ); • When settlement delay was set to zero, then interest rate setting was ignored (5.46-5.50.2). Fixed. • New Analysis: Individual backtest: setting different report mode took place only after second run / second symbol. Fixed. • Formulas: styleNoLabel is now default for all "Band" formulas (Bollinger/Keltner/Percent) • Formulas: faster version of Portfolio Equity formula • Formulas: Ichimoku cloud added • TC2K/TC2KFunds plugins updated to check Wow6432Node registry key on 64-bit installations (should avoid TC2k detection issue on 64-bit Windows) • PlotVAPOverlay did not draw the very last level line. Fixed. Also done some cosmetic tweaks. • New Analysis: Walk forward tab table did not display custom metrics. Fixed. • Ticker bar prevents from adding empty '' symbol names • Blank chart can be closed using flyout minitoolbar now • When database is empty or chart does not have properly selected symbol the information note is displayed in the chart window (instead of blank chart) • Fixed crash @7C8097FF when trying to drag drop indicator on chart when database is empty CHANGES FOR VERSION 5.50.2 (as compared to 5.50.1) • New Analysis: If current formula is open in the formula editor it is auto-saved prior to running any Analysis (as old AA did) • New Analysis: on Backtest/Optimization current formula is saved in @LastBacktestFormula registry key so it can be referenced by Individual Equity formula • New Analysis and Old AA: HoldMinBars > 0 can now be used together with AllowSameBarExit=True Settings: 'Stops' tab: N Bar stop has priority check box state was not saved. Fixed • New Analysis: on attempt to load analysis project file that contains formula path that does not exist or is not writable AmiBroker will create the formula in the "Formulas\Imported" folder instead of not creating it at all • New Analysis: WinXP-only - RMB click column descend/ascend menus were not working due to Windows XP bug. Fixed. • New Analysis: when formula is picked from the folder that is inside current working directory, then relative path is used and stored in project instead of absolute path previously used • New Analysis: SeparateLongShortRank required proper MaxLongPos and MaxShortPos definitions in order to work. Now if they are missing defaults are applied as in old AA. • Plugins: IQFeed: added "You can't close plugin window" on attempt to close working IQFeed window. • UI: Chart tree, Layout tree in "Explorer" theme • UI: Category list now features new icons and decreased indentation • UI: Owner-draw listviews now fully implement ellipsis item truncation mechanism, but using ExtTextOut only which is 6 times faster than DrawText that Windows uses • UI: Floating non-chart windows (account/web browser/analysis) are not closed when switching layouts. • Plugins: IQFeed plugin uses new faster IQFeed API, downloads less and uses way more efficient method to backfill 1/5/15-second base time intervals CHANGES FOR VERSION 5.50.1 (as compared to 5.50.0) • New Analysis: Individual Backtest implemented. Note that it runs with approx same speed as old AA as Individual Backtest is single threaded for reasons explained in the User's manual http://www.amibroker.com/guide/h_multithreading.html • New Analysis: toolbar icons for parameters and settings changed to avoid confusion with the icon for preferences • UI: Symbol List uses Windows 7/Vista style • New Analysis: Toolbar customization is now saved • MRU (most recently used) file menu moved to submenu and MRU list increased to 10 items • Charts: fixed small alignment problem on Y axis when using fixed (nonproportional) font • New Analysis: backtester object now has EquityArray property that returns entire equity array (not just current value). Please note that values are filled during backtest and only after backtest is complete, all values are valid. If you call it in the middle, it will contain only "upto given point" data. Avoid abusing this function and it is costly in terms of RAM/CPU.e). You may use bo.EquityArray instead of Foreign("~~~Equity", "C" ) in custom backtester code. It accesses local copy of equity in New Analysis (unlike Foreign that accesses global symbol) • New Analysis: AddToComposite with atcDeleteValues | atcEnableInPortfolio did not delete previous values. Fixed • New Analysis: "Interval" menu item in the auto-repeat group renamed to "AR interval" because some users interpreted it wrong (as periodicity) • New Analysis: OLE interface implemented Description in the http://www.amibroker.com/guide/objects.html Example The following JScript example a) opens analysis project from C:\Analysis1.apx file b) starts backtest (asynchronously) c) waits for completion d) exports results e) closes analysis document AB = new ActiveXObject( "Broker.Application" ); try { NewA = AB.AnalysisDocs.Open( "c:\\analysis1.apx" ); // opens given analysis project file if ( NewA ) { NewA.Run( 2 ); // starts analysis (asynchronous - returns immediatelly // (0-scan, 1- exploration, 2- portfolio backtest, 4- optimization, 6-walk forward) while ( NewA.IsBusy ) WScript.Sleep( 500 ); // wait for completion NewA.Export( "test.html" ); // exporing results WScript.echo( "ended" ); NewA.Close(); // closing analysis window } } catch ( exc ) { WScript.echo( "Exception: " + exc.message ); } • Charts: more tweaks for Y axis algorithm for readability. Now in Tools->Preferences, "Charting" the user may select different grid stepping: Instead of default 1, 2, 5, 10 grid stepping, user may select to use 2.5 step instead of 2 (Use 2.5 step in Y axis) • GetFnData() supports new field "Alias" - return Alias field without need to use OLE • GetOption supports new fields: ApplyTo and Filter*, eliminates the need to use OLE for that purpose New fields: -"ApplyTo" - returns Analysis "Apply To" setting 0 - all symbols, 1 - current symbol, 2 - filter - "FilterIncludeIndex", "FilterIncludeFavorite", "FilterIncludeMarket", "FilterIncludeGroup", "FilterIncludeSector", "FilterIncludeIndustry", "FilterIncludeWatchlist" - return "Include" filter settings -1 - means NOT selected (not included), >= 0 index of included category - "FilterExcludeIndex", "FilterExcludeFavorite", "FilterExcludeMarket", "FilterExcludeGroup", "FilterExcludeSector", "FilterExcludeIndustry", "FilterExcludeWatchlist" - return "Exclude" filter settings -1 - means NOT selected (not excluded), >= 0 index of excluded category • Fix for FPU inaccurracies in range bars implemented CHANGES FOR VERSION 5.50.0 (as compared to 5.49.2) • New Analysis: "Save" creates now a Analysis project (.apx) file that includes all settings and formula needed in single file. The file itself is in human readable XML format. When such file is loaded on somebodys' else computer it will recreate original formula if one is not present. It will warn if there is a name conflict and let you decide to keep existing formula or overwrite. • UI: File open dialog now has "All supported files" option in the "Files of type" • UI: PopupWindow is now resizable (see size gripper in the lower-right corner) • AFL: PopupWindow function has additional parameters to control width/height and flag that controls whenever popup window captures input focus PopupWindow( "bodytext","captiontext", timeout = 5, left = -1, top = -1, width = -1, height = -1, captureFocus = True ); width = width in pixels, -1 - use default width height = height in pixels, -1 - use default height captureFocus - decides whenever popup window captures input focus or not Example: popup window that does not change input focus: PopupWindow("test", "caption", 30, -1, -1, -1, -1, False); • New Analysis: ApplyStops applied in non-regular modes are passed to 2nd phase properly now. • New Analysis: "Show current trade arrows" fixed. • New Analysis: View->Filtering menu options were not available when New Analysis was active. Fixed. • New Analysis: Standard Edition has a limit of max 2 threads per Analysis window instance. • UI: Log window clicking on error displayed AFL Editor and marked Line+1, Col+1 char position instead of proper place. Fixed • New Analysis: Errors are now displayed in a modern message bar instead of dialog box • UI: holding down Ctrl and Q keys simultaneously while AmiBroker is starting resets all menus/command bars to defaults • New Analysis: scroll bar properly works when "Walk forward" tab is active • New Analysis: Walk forward tab content can be now copied using Edit->Copy / Ctrl+C • New Analysis: when "wait for backfill" was turned on and external data source was very slow to repond (like IQFeed during backfill) subsequent calls to Status('stocknum') could give non-unique numbers. Fixed. • New Analysis: Copy to clipboard includes headers now • New Analysis: Column customization/state persistence implemented • Charts: New Y axis grid algorithm for clearer display on condensed charts • AFL: CategoryGetSymbols supports new categoryAll (all symbols in the database) and new Mode parameter CategoryGetSymbols( category, number, mode = 0 ); Mode parameter decides what field is retrived: 0 (default value) - ticker symbol 1 - full name Example: to get all symbols existing in the database simply call CategoryGetSymbols( categoryAll, 0 ); to get full names of all symbols use: CategoryGetSymbols( categoryAll, 0, 1 ); • AFL: Added Warning 503. Using OLE / CreateObject / CreateStaticObject is not multi-threading friendly. See Users' Guide ""Efficient use of multithreading"" for more details. • AFL: Added ThreadSleep( milliseconds ) function. It suspends current thread for specified number of milliseconds (maximum is 100 ms). Works only from NON-UI threads. When called from UI thread the function does NOTHING and returns immediatelly. Please do NOT abuse this function. Using it may negatively impact performance. • AFL: Added StaticVarCompareExchange function. Provides atomic interlocked compare/exchange functionality Parameters " varname" Specifies the name of the destination static variable. Static variable if exists must be scalar numeric type. If static variable is not initialized, the function assumes that it has value of zero. exchange Specifies the exchange value. Scalar numeric. Comperand Specifies the value to compare to the destination static variable. Scalar numeric. Return Values The return value is the initial value of the destination static variable. If variable did not exist, it returns zero. The StaticVarCompareExchange function performs an atomic comparison of the "varname" static variable value with the Comperand value. If the static variable value is equal to the Comperand value, the Exchange value is stored in the static variable. Otherwise, no operation is performed. The function StaticVarCompareExchange provides a simple mechanism for synchronizing access to static variables that are shared by multiple threads. The following examples show how to implement semaphore and critical section in AFL using StaticVarCompareExchange function:  // EXAMPLE 1 : Simple semaphore (no waiting) if( StaticVarCompareExchange( "semaphore", 1, 0 ) == 0 ) // obtain semaphore { // protected section here // Here you have exclusive access (no other threads that check for semaphore will enter simultaneously) ///////////////////////// StaticVarSet("semaphore", 0 ); // reset semaphore } else { _TRACE("Can not obtain semaphore"); } /////////////// // EXAMPLE 2 HOW TO IMPLEMENT CRITICAL SECTION IN AFL /////////////// function _TryEnterCS( secname ) { global _cursec; _cursec= ""; // try obtaining semaphore for 1000 ms for( i = 0; i < 1000; i++ ) if( StaticVarCompareExchange( secname, 1, 0 ) == 0 ) { _cursec = secname; break; } else ThreadSleep( 1 ); //sleep one millisecond return _cursec != ""; } // call it ONLY when _TryEnterCS returned TRUE ! function _LeaveCS() { global _cursec; if( _cursec != "" ) { StaticVarSet( _cursec, 0 ); _cursec = ""; } } function TimeConsumingWork() { // WARNING: the Percentile is CPU hungry as it involves lots of sorting, the loop below may take > 1 second to complete for( i = 0; i< 10; i++ ) Percentile( C, 100, 10 ); } //_TRACE("Without CS Begin " + GetChartID() ); //TimeConsumingWork(); // some time consuming calculation //_TRACE("Without CS End" + GetChartID() ); // Example usage (critical section) if( _TryEnterCS( "mysemaphore" ) ) { // you are inside critical section now _TRACE("Begin CS " + GetChartID() ); TimeConsumingWork(); // some time consuming calculation _TRACE("End CS " + GetChartID() ); _LeaveCS(); } else { _TRACE("Unable to enter CS"); } CHANGES FOR VERSION 5.49.2 (as compared to 5.49.1) • New Analysis: added Optimize->3D Optimization chart menu • New Analysis: buttons for Portfolio Equity/Individual Equity charts added • New Analysis: Info Bar added (that duplicates some of the info that normally appears on the Info Tab). It can be turned on using Settings->Info Bar • New Analysis: Report generation is now OFF by default when running optimization/walk forward as in old AA. This gives about 0.9 sec gain per step. • New Analysis: Single-symbol optimization made faster by caching already compressed quote array on subsequent steps • New Analysis: the check for Status("StockNum") was sensitive to blanks between parenthesis, function name and string parameter. Now it is made insensitive to blanks. • New Analysis: when "Range" was "n last bars" or "n last days", Status("rangefromdate") gave date of preceding bar. Fixed. • UI: "Performance" tooltip title was not always updated on time. Fixed. • UI: "Wait for plugin" window displays progress bar with "marquee" style instead of circle of dots CHANGES FOR VERSION 5.49.1 (as compared to 5.49.0) • New Analysis: Testing on unaligned data sometimes took longer than expected because of the work necessary to bring signals in order. Now a smart method avoids most of the memory transfers and can give 10x speedup on backtesting very long unaligned intraday data. • New Analysis: "Backtest started", "Exploration started" text in the info tab appeared twice per run (instead of once). Fixed • New Analysis: Backtest report did not include formula code. Fixed. • New Analysis: Fixed crash that could occur when running analysis with Range set to "N recent bars" and N was exceeding number of quotes. • New Analysis: Float/Normal/Close popup menu RMB menu was active everywhere in floating window instead of only caption area. Fixed. • New Analysis: Implement single-thread start when Status("StockNum") is detected in the code. Other threads are started when first symbol processing is completed. • New Analysis: Send to Analysis did not update formula combo box properly in certain scenarios: when formula X was selected, then formula Y, then formula X again. Fixed. • Old AA: status bar displays true timing for fair comparisons between old AA and new Analysis. Watching progress bar numbers was misleading as it closed before all processing was truly complete, so it looked like old AA completed sooner than it really did • UI: menu item for Old Automatic Analysis restored as apparently some users got lost. Also attempt to run old Automatic analysis displays an information about new Analysis window CHANGES FOR VERSION 5.49.0 (as compared to 5.48.0) • New Analysis: when floating pane is made normal from/to dates were reset to today. Fixed. • New Analysis: when Apply To: Filter is defined so NO symbol matches the criteria, appropriate message is displayed when trying to run Analysis and action is terminated instead of displaying progress bar forever • New Analysis: when analysis window is "floating" double click/show arrows/sync affects active MDI chart just like old AA did, as opposed to last one (when analysis is not floating) • New Analysis: Optimization parameter setup stage uses now not more than 100 bars. This reduces setup time. • New Analysis: implemented import / export, File menu now has Import HTML and Export HTML/CSV commands • New Analysis: Implemented "Wait for backfill" option. This slows down analysis sequence so AmiBroker waits for external RT data source to deliver backfill data When "wait for backfill" option is turned on, AmiBroker checks if data for given symbol are complete, if not, it sends request to external source to backfill the data and waits 1 second. After one second, it checks again, it data are complete, if not, it waits another 1 second, and so on. Once data are complete given symbol is used for formula execution. • New Analysis: Custom backtester uses "last backtest settings" when calling GetStatus() instead of old AA settings • New Analysis: auto-repeat interval edit field did not allow to enter values if moved to main toolbar via customization. Fixed. • Formula Editor Analysis toolbar button now operates on New Analysis window • Default for timestamping of intraday compression changed to "Show START time of interval" • Charts: AFL error message color is now definable in Tools->Preferences, "Color" tab • Charts: Tooltips automatically display also OHL prices (in addition to close) when Plot style is set to candlestick, bar or when PlotOHLC was used • UI: Adjusted item Y offset for owner drawn listviews for consitent look with old layout of system listviews in Windows XP and earlier OSes • UI: Account, Analysis and Web research windows don't use client edge/border anymore - gives slicker / less crowded look • UI: when focus is switched to floating document window, the application menu is switched to proper context • UI: When File->Close was used on floating pane, document was closed but docking pane was not. Fixed. • UI: The toolbar button and menu option to launch old Automatic Analysis window are now hidden (can be brought back by using Tools->Customize), old AA can also be launched from new Analysis via Analysis->Old Analysis menu • UI: New menu options and toolbar button to launch new analysis window • UI: Moved all menu items controlling visibility of docking windows to "Window" menu • UI: floating state of windows can now be turned on/off using right-click menu over tab / floating window caption • UI: File->Save (when currently selected window is a chart) command now saves Chart template. To save database use "Save database" instead. • UI: Defaults for data window are changed, so extra OHL display is turned off by default as currently PlotOHLC displays all 4 prices in the tooltip and data window already • UI: Data window scroll bars are hidden and do not flicker when updating • UI: "Save All" toolbar button removed, "Save database" button added to replace it • Web Research: turned on "silent" mode - should prevent error message boxes displayed by IE engine. • QuoteEngine: Range bars algorithm improved significantly • Quote array uses 20480 bytes (512 quotes) allocation chunk size (exactly 5x4KB page) for better alignment with Windows virtual memory pages CHANGES FOR VERSION 5.48.0 (as compared to 5.47.0) • New Analysis: custom metrics columns were invisible in backtest/optimizations. Fixed. (#91031) • New Analysis: backtest did not display proper column names when Report mode was different than trade list. Fixed. Also added support for changing report mode via SetOption(). • New Analysis: Auto-repeat Scan/Explore implemented (aka. "Run every" in old AA) (use drop down menu next to "Settings" button) • New Analysis: Showing arrows by double click implemented • New Analysis: Sync chart on select option implemented (use drop down menu next to "Settings" button) • Fixed window activation issue after RMB click in chart window when non-chart floating windows are active • New Analysis: Cancelling walk-forward did not restore date range and settings and didn't reset internal step counter. Fixed. • New Analysis: Formula path disappeared when window was made floating. Fixed. • New Analysis: in 5.47 non-exhaustive optimizers sometimes stopped after first step in walk-forward. Fixed. • Charting: scroll bar zoom function remains active even at extreme zoom in levels • New Analysis: Fixed problem with opt steps warning dialog appearing sometimes in the out-of-sample tests in walk forward sequence • New Analysis: Signal heaps are separated now, allowing to run concurrent backtest/optimizations in many analysis windows • New Analysis: removed unnecessary refreshes of symbol list during optimizations that caused slowdowns when user had large database • New Analysis: The size of control fields is properly adjusted with regards to DPI • New Analysis: Status("StockNum") was always zero in 5.47 and earlier. Now it is set properly. Caveat: be careful when you run codes that use Status("StockNum")==0 for special processing in multithreading mode. Other threads with "StockNum" = 1, 2, 3,... will run simultaneously! If you store static variables in step 0 these variables may be empty if you access them from other parallel running threads. • Fixed Error 53 message that was giving an error when proper \" (quotation mark espace sequence) was used CHANGES FOR VERSION 5.47.0 (as compared to 5.46.0) • New Analysis: last used ApplyTo/Range/From/to dates/filters and other settings are saved when Analysis window is closed • Fix to "slow response" problems some users reported when switching symbols • Fibonacci retracement- modifying Z-order affected only control trendline, not all lines as it should. Fixed. • New Analysis: implemented Walk-Forward testing (use drop arrow next to Optimization button) • AFL engine: new error 53: incorrect \ espace sequence. Error is issued when user forgets that single slash must be written as \\ • Default title for new analysis window is "AnalysisX" (instead of "Unnamed") where X is consecutive number 1, 2.. • attempt to use Say() on computer without sound card or without driver installed does not result in throwing exception/crash report, but it is rather silently ignored CHANGES FOR VERSION 5.46.0 (as compared to 5.45.0) • New Analysis: Exhaustive multi-threaded optimization implemented • New Analysis: Smart (non-exhaustive) multi-threaded optimization implemented in a way compatible with existing optimizer plugins Note however that due to the fact that most non-exhaustive optimization plugins are not re-entrant, AmiBroker prevents from running more than one non-exhaustive multi-threaded optimization at a time. You can however, run many exhaustive optimizations in parallel, as they don't require external plugins. • Slight modification to the way how compressed bar charts are drawn (so bars with H==L are better visible) CHANGES FOR VERSION 5.45.0 (as compared to 5.44.1) • 64-bit version compiled with new version of C runtime (Microsoft security update) • Fixed date/time column sorting in virtual list views when regional date format was different than yyyy-MM-dd • AFL: ClipboardSet() returns True (1) when clipboard has been successfully set. Sometimes clipboard is locked by another applications and then write can fail (ClipboardSet() will return zero/False then) • New Analysis: Changed alignment of Date/Time column to left in backtest result list. • Most AFL engine setup moved to worker threads. Result - smaller UI thread load in MT charts (better scalability) and much faster (upto 2x) explorations/scans in New Analysis window • New Analysis: added "Info" tab that provides some summary information about analysis (number of rows, timings, backtest summary) - contents can be copied using Ctrl+C / Edit->Copy NOTE: End users should only look at "Completed in... sec" line that shows actual run time of the analysis (scan/exploration/backtest). The times shown in "timings" row are for Amibroker.com internal use. In development/testing they help us tweak the performance of various parts of analysis engine. The detailed timings do not sum up to actual run time. No further infomation is available at the moment. The "timings" row is subject to change/removal in the future versions. If you have problems/questions with the performance of new Analysis window please copy (Ctrl+C) the contents of Info tab and send to support. • New Analysis: first-phase backtest signal processing and ranking moved to non-UI threads, enabling better parallelism, results in better backtest performance (upto 2x in with trivial codes) CHANGES FOR VERSION 5.44.0 (as compared to 5.43.1) • New Analysis: fixed AddToComposite() • New Analysis: Interval() function was working incorrectly in new analysis window. Fixed. • New Analysis: Backtest ~~~EQUITY symbol did not have "use only local database" set in 5.43.1. Fixed. • New Analysis: Backtest performance improved by removing some unnecessary list view refreshes (now it should never be slower than old AA even with simplest formulas) CHANGES FOR VERSION 5.43.1 (as compared to 5.43.0) • When range different than "All quotes" was selected, backtest in new Analysis window could produce incorrect results in 5.43.0. Fixed. CHANGES FOR VERSION 5.43.0 (as compared to 5.42.0) • New Analysis Window: multi-threaded Backtest feature implemented (experimental) Note that only first phase of backtest is multithreaded (each symbol in separate thread). 2nd phase (custom backtest) is executed in main thread as there is only one symbol to work on (i.e. equity) and it needs to talk with OLE which is single threaded and GUI. • Load/Unload buttons removed from Plugins dialog. This was developer-only feature and it was abused by ordinary people who were unloading plugins that were actually in -use (such as data plugins when being connected to given data source) • ListViews: the last line (partially shown) in RT quote window was not easily selectable. Fixed • New Analysis window: Implemented Parameters dialog • AFL: GetCursorMouseButtons() sometimes missed clicks when multithreading was on and formula took ages to execute. Now it is now 100% reliable. • Auto-selection of proper layer based on selected viewing interval NOTE: This feature can be turned off by click with RIGHT mouse button over layers window and UNCHECKING "Auto-select layer" • IRA accounts support - implemented Settlement delay in backtester, via SetOption("SettlementDelay", x ) "SettlementDelay" option describes the number of days (not bars) it takes for sale proceeds to settle and be available for opening new positions. SetOption("SettlementDelay", 3 ); // this will cause that proceeds from sale are only available for trading on 3rd day after sale For detailed tracking " Detailed log" report option now shows available and unsettled funds for T+1, T+2 and so on Note: when using this option it is recommended to use backtestRegularRaw instead of backtestRegular, otherwise some trades may not be entered because funds are not settled immediately and you need to be able to enter not on first but subsequent buy signals and that is exactly what backtestRegularRaw offers. Note2: old backtester (Equity() function) ignores settlement delay • Zoom in/out toolbar buttons zoom in finer steps (+/-10%) • Analysis ListView, RMB menu new option: "Add Rank column" - adds a column with ordinal rankings based on current sort or just row number column when list is not sorted • New feature: Adding new chart/research/account/analysis via (+) tab • New Analysis window: Implemented SetSortColumns • New Analysis window: Implemented AddSummaryRows CHANGES FOR VERSION 5.42.0 (as compared to 5.41.0) • Implemented right click menu in new Analysis windows (Add symbols to watchlist/Show arrows functionality) • Zoom in/out toolbar buttons now have auto-repeat feature • In 5.41.0 Ctrl+C from list view copied text without tabs (column separators). Fixed • In 5.41.0 did not refresh progress dialog optimization status list. Fixed. (owner draw list view initial size is retrieved in PreSubclass now) • In 5.41.0 did not display Time&Sales in reverse order (newest on top). Fixed. CHANGES FOR VERSION 5.41.0 (as compared to 5.40.3) • New Analysis window (File->New->Analysis) - featuring multithreaded Scan and Exploration Performance note: to fully benefit from multithreading it is best to use AmiBroker local NATIVE database (not external) as it is the only database that can deliver data quickly enough. Tests show that on AmiBroker native databases scans and explorations are 100% scalable to multiple cores - i.e. for example would run upto 8 times faster on 8 CPU/core machine. IMPORTANT: This window is work-in-progress. Multithreaded Backtest and Optimization features will be added later. • AFL: AddColumn - added mini bar charts to explorations Exploration now features ability to create mini bar charts in individual cells. AddColumn has new parameter 'barchart' AddColumn( ARRAY, "Caption", format = 1.2, fgcolor = colorDefault, bkcolor = colorDefault, width = -1, barchart = null ) 'barchart' parameter accepts values from 0...100 represening percentage width of bar chart displayed in a cell the in-cell bar chart is drawn with bkcolor (background color). Example usage: Filter=1; AddColumn( Close, "Close" ); rank = PercentRank( Close, 100 ); Color = ColorHSB( rank * 64/100, 255, 255 ); AddColumn( rank, "100-day percent rank", 1.2, colorDefault, Color, -1, rank ); Note that although this example uses same value for numeric display and chart bar width, it does NOT need to be the same, i.e. numerical value of the cell is independent from bar chart. • Totally rewritten listview with very efficient owner draw code speeds up list view scrolling/resizing/repainting more than 10 times. Native system ListView control is terribly slow on Windows XP/Vista/7 (surprisingly it was many times faster in Win9x!) • AFL: Percentile() does a param check for range > 0 now • Mini-chart in RT Quote window - Mini chart shows where LAST price is within LOW-HIGH range. • Errors and warnings are now displayed in red color in the indicator pane • During actual GDI chart rendering AmiBroker measures time and if it exceeds 500ms timeout it stops rendering with Warning 901. This check is required because GDI rendering occurs in GUI thread and if GUI thread does not process messages for half second Windows will think that application is "not responding". This prevents making application stuck with some overly complex, possibly incorrect formulas that call hundreds of Plot()s • Warning 502: Calling Plot()/PlotOHLC over 500 times is displayed in indicator in runtime to prevent abuse • All list views, pressing Ctrl and NumPad'+' automatically adjusts column widths to content • if data are missing in the in-memory cache, Foreign() calls from non-GUI threads use synchronous retrieval method for reliability. This provides reliable results in AA but may slow down the multi-threaded operations if cache size is too small and user uses more Foreign() calls than in-memory cache size. IMPORTANT: For optimum performance in-memory cache setting (Tools->Preferences->Data) should be GREATER than number of Foreign() calls in any single formula used. Values lower than that cause lots of disk activity and serialization of all Foreign calls that means that additional threads must wait for data retrieval to complete. • Old and new Analysis window: outputting millions of rows to listview is much faster now • All list views - Ctrl+A (Select All) made much faster CHANGES FOR VERSION 5.40.3 (as compared to 5.40.2) • GfxTextOut produced too large text on paper / printout. Fixed. • GicsID returns empty string when GICS is not defined for symbol • PlotText: y==Null check added to skip calls that don't produce any output CHANGES FOR VERSION 5.40.2 (as compared to 5.40.0) • 64-bit version: MS VC++2005 compiler default floating point code generation option switched back to fp:precise because fp:fast produced incorrect code • Print preview and Edit->Image->Copy respect Price chart style setting • Notepad window: pressing Ctrl+C/V/X and ESC key afterwards closed AmiBroker without warning. Fixed. • Quick review: Volume is printed without using scientific notation upto 9 billion • SaveNewChartsInfo is called in SaveWorkspaceInfo() to ensure that broker.newcharts is in sync with saved layout, Broker.cpp line 927 • Exception dialog "Exit program" exits program forcefully now. This prevents situation when program could not be closed and sometimes corrupted data on exit. • Selection line is handled properly again in Print preview/Edit->Image->Copy • AA / Scan outputting lots (10K+) of signals made much faster • Memory consumption during AA / Explorations reduced significantly, also multi-column explorations are much faster (10x) • 64-bit version: AB x64 reverted to "Daily" setting when re-entering AA Settings dialog if user previously selected weekly/monthly/quarterly/yearly. Fixed CHANGES FOR VERSION 5.40.0 (as compared to 5.39.0) • Fixed crash occuring when drawing object was not deselected prior to switching symbol • Added extra thread safety measure for Foreign() so it handles situation when other thread is deleting symbol while it is being accessed via Foreign() • New version (1.3) of 3D chart viewer (O3G) fixes problem with Edit->Copy image function on Vista/Windows 7 with desktop composition turned ON • Multithreading does not revert to "ON" state on startup when user turned if OFF last time (it was so in 5.34-5.39 to force testing of MT) • Temporarily removed asInvoker manifest because it created problems with 3rd party programs/plugins that are not Windows 7 compatible (QP2, FastTrack) • AFL: PercentRank( array, range ) implemented array - input data range - lookback range Returns percent rank (0...100) of the current element of the array within all elements over the specified range. A value of 100 indicates that the current element of the array is the highest for the given lookback range, while a value of 0 indicates that the current value is the lowest for the given lookback range. It is equivalent (but 2x faster) to: function PercentRank2( Data, Periods) { Count = 0; for ( i = 1; i <= Periods ; i++ ) { Count += Data > Ref( Data, -i ); } return 100 * Count / Periods; } • AFL thread termination is safer and faster now (this also eliminates randomly occuring AFL syntax errors when swithing layouts) CHANGES FOR VERSION 5.39.0 (as compared to 5.38.0) • Lookup( array, datetime, mode = 0 ) enhanced to support mode = -2 and mode 2 mode now has following allowable values mode = 0 - find exact match, otherwise return Null mode = -1 - find exact match, otherwise return nearest predecesor (if datetime is past last bar it will return last bar value) mode = -2 - find exact match, otherwise return nearest predecessor EXCEPT the very last bar (if searched datetime is past last bar it will return Null) mode = 1 - find exact match, otherwise return nearest successor (if datetime is before first bar it will return first bar value) mode = 2 - find exact match, otherwise return nearest successor EXCEPT the very first bar (if searched datetime is before first bar it will return Null) • GetPriceStyle() caused chart flashing when different windows had different price style selected. Fixed. • Log output/error messages from AFL engine are now passed to main window asynchronously (via PostMessage) • Chart was not refreshed immediatelly when using drag-drop on single-pane charts with non-streaming DB. Fixed • Account manager: Transactions list: "Gross value" column calculation fix. • Bar Replay dialog has now new checkbox "Reset alert time" that resets last alert time for all symbols when you press Play button enabling AlertIf() to be triggered again from the start on each replay • Fixed problem with incorrect reading of previously saved layout/template when user decreased number of chart sheets in the preferences • "Show arrows for current trade" in AA did not work with 12 hour AM/PM time format. Fixed • Fixed Lookup() function handling of end-of-day-only records and mode=0 (exact match). • Quote Editor: "Use timeshift" checkbox position wasn't adjusted when resizing dialog. Fixed. • Quote Editor was not able to edit quotes after 12:00PM when 12 hour AM/PM time format was used. Fixed • In 5.31.x BETAs syntax error message was displayed without error number. Fixed. • Fixed problem of incorrect allocation of chart value cache when window width was below 16 pixels. CHANGES FOR VERSION 5.38.0 (as compared to 5.37.1) • Fixed structure packing in x64 version causing problems with display of parameter tooltips for 3rd party DLLs • WMA had trouble with null handling at the beginning. Fixed. • Improved CCI accuracy in x64 version (as compared to x86 version) • Added switch to turn reset chart zoom level when loading layout Tools->Preferences, "Charting" " Reset zoom to default when loading layout" - by turning this ON, zoom level gets reset to default number of bars as defined in preferences for any loaded layout, bringing old (pre-5.37) behaviour • AFL: FIR( array, coefficients, size ) implemented This function implements general-purpose Finite Impulse Response filter (FIR) http://en.wikipedia.org/wiki/Finite_impulse_response The output is convolution of input aray with coefficents table (impulse response table). The function performs automatic normalization of coefficient table if necessary (if its sum is not 1) INPUTS: array - input array to be smoothed coefficients - array of FIR coefficients size - number of coefficients ( filter_order + 1 ) It is functional (but 2+ times faster) equivalent of following AFL: function FIR_AFL( input, coeff, size ) { result = 0; sumcoeff = 0; for( i = 0; i < Min( size, BarCount ); i++ ) { sumcoeff += coeff[ i ]; result += coeff[ i ] * Ref( input, - size + i + 1 ); } return result/sumcoeff; } For example 5 bar weighted moving average can be written: coeff[ 0 ] = 1; coeff[ 1 ] = 2; coeff[ 2 ] = 3; coeff[ 3 ] = 4; coeff[ 4 ] = 5; FIR( Close, coeff, 5 ); Another example: ALMA which is FIR filter with shifted Gaussian coefficents can be implemented as follows: function ALMA_AFL( input, range, Offset, sigma ) { local m, im, s, Coeff; m = floor( Offset * (range - 1) ); s = range / sigma; for( i = 0; i < Min( range, BarCount ); i++ ) { im = i - m; Coeff[ i ] = exp( - ( im * im )/ ( 2 * s * s ) ); } return FIR( input, Coeff, range ); } • AFL: HMA (Hull Moving Average) HMA - Hull Moving average it is equivalent to this AFL: function HMA_AFL( input, Range ) { return WMA( 2 * WMA( input, int( Range / 2 ) ) - WMA( input, Range ), int( sqrt( Range ) ) ); } • AFL: new function: DateTimeAdd( datetime, amount, interval = inDaily ) The function adds specified amount of 'intervals' to input datetime array. Allows for example to calculate datetime 5 days back or 13 months into the future INPUT: datetime - scalar or array - the datetime value to add to (for example returned by Now(), DateTime() or StrToDateTime/_DT or ConvertDateTime functions) amount - number of 'intervals' to add (seconds/minutes/hours/days/etc - depending on interval parameter) interval - specifies unit you want to add, supported units are in1Second, in1Minute, inHourly, inDaily, inWeekly, inMonthly, inQuarterly, inYearly RETURNS: datetime (scalar or array) - returned type depends on input Example 1: x = Now( 5 ) ; printf("11 days from now " + DateTimeToStr( DateTimeAdd( x, 11, inDaily ) ) ; Example 2 (commentary): x = Now(5); " now is " + DateTimeToStr( x ); for( shift = -12; shift <= 12; shift++ ) { printf("%g seconds from now is " + DateTimeToStr( DateTimeAdd( x, shift, 1 ) ) + "\n", shift ); printf("%g minutes from now is " + DateTimeToStr( DateTimeAdd( x, shift, in1Minute ) ) + "\n", shift ); printf("%g hours from now is " + DateTimeToStr( DateTimeAdd( x, shift, inHourly ) ) + "\n", shift ); printf("%g days from now is " + DateTimeToStr( DateTimeAdd( x, shift, inDaily ) ) + "\n", shift ); printf("%g weeks from now is " + DateTimeToStr( DateTimeAdd( x, shift, inWeekly ) ) + "\n", shift ); printf("%g months from now is " + DateTimeToStr( DateTimeAdd( x, shift, inMonthly ) ) + "\n", shift ); printf("%g quarters from now is " + DateTimeToStr( DateTimeAdd( x, shift, inQuarterly ) ) + "\n", shift ); printf("%g years from now is " + DateTimeToStr( DateTimeAdd( x, shift, inYearly ) ) + "\n\n", shift ); } • AFL: new function: Lookup( array, datetime, mode = 0 ) The function searches for the bar with specified datetime and returns the value from the same position of the input array. If exact match can not be found it returns: Null - when mode is 0 (zero) - the default behaviour, closest predecesor bar value - when mode is -1 closest successor bar value - when mode is 1 Example: InputDate = "2011-04-05"; Title = "Close value at (or before) " + InputDate + " is " + Lookup( Close, _DT( InputDate ), -1 ); This function uses very fast binary search and it is many times faster than previous AFL-based methods such as FindValueAtDateTime() presented in the past. Any call to FindValueAtDateTime ( input, dt, value ) can be now replaced with Lookup( input, value ) (there is no need to pass dt- datetime). NOTE: This function does not affect QuickAFL required bars, therefore it will only search bars that are actually loaded in arrays. For indicators it may mean that it won't be able to find value if it is invisible, unless you use SetBarsRequired() function to ensure that more bars are loaded. • AFL: function _DT( "string" ) added - this is short alias for StrToDateTime() function • AFL: added FirstVisibleValue/LastVisibleValue functions // in charts / indicators /interpretation they return the values of array at first and last visible bars // in other (non-indicator) modes they return array elements with subscripts of 0 and BarCount -1 respectively // Note that these functions do not affect QuickAFL, so LastVisibleValue may be used instead of LastValue // These functions are intended to complement functionality already available via HighestVisibleValue and LowestVisibleValue x = C; Plot( x, "x", colorRed ); Plot( FirstVisibleValue( x ), "fvv", colorGreen ); Plot( LastVisibleValue( x ), "lvv", colorBlue ); • Cum( Null) was causing exception in AFL engine. Fixed • Print preview flickered when moving the mouse due to frequent refreshes when crosshair was enabled. Fixed. • Structured exception handler is set for every thread for better exception reporting CHANGES FOR VERSION 5.37.1 (as compared to 5.36.0) • EncodeColor did not accept colorDefault (-1) in 5.37.0. Fixed 5.37.1. • AFL Code Wizard 1.01: fixed incompatibility with Internet Explorer 9 • AFL: PlotText() internally detects if given x-coordinate is outside visible area, skips entire processing and returns zero (without plotting anything) for invisible bars. This saves execution time for inefficiently written formulas that did not check for visible bars by themselves. • Report charts now use Formula path as defined in preferences not hard-coded one so they work if user has moved his/her formula folder elsewhere • Fixed crash occuring sometimes on completly blank chart when user set number of blank (future) bars to zero (#75570) • Fixed crash when trying to use Overlay onto blank chart • AmiBroker is now marked as DPI-aware (this ensures crisp display by turning off Win7 DPI virtualization that scales and blurs image on high DPI (>=150dpi) displays) • AFL: added new message: 'Error 52. Invalid argument value. Argument must be positive (and not Null))'. The message is displayed when you pass incorrect value to a function (like Null as a range to Sum() ) • Layout files now include zoom factor so charts are loaded with most recently used zoom level • Updated version of UI library featuring new appearance themes and alpha-channel resize tracker CHANGES FOR VERSION 5.36.0 (as compared to 5.35.0) • AFL Editor more detailed code checks implemented - now displays *warnings* (for code parts that are syntactically correct but likely errorneous in practice) Example: Warning 501. Assigment within conditional. Did you mean == instead of = ? The warning will display if you use = (assignment operator) as a condition in if(), while(), do-while(), and for() statements and IIf() function The result of an = assignment statement is the value of the right-hand side of the = statement. You can use an assignment statement as a conditional test, but it is not recommended. It usually is the result of a typo where a == equality test was intended, as the following example shows: Example: if( x = 3 ) // x will be assigned with 3 then it is used as "true" value so condition is always met - AmiBroker will display warning 501. Assignment within conditional { // this if will ALWAYS be executed } Probably the user meant: if( x == 3 ) // x will be compared to 3 { // this is true conditional part } If you want to overcome warning 501 while still doing assigment within conditional perform a check like this: if( ( x = 3 ) == True ) // this NOT cause warning 501 { printf("test"); } • Temporary workaround for docking window crash when Internet Explorer 9 is installed and web research window resized • AFL: GicsID and InGICS added GicsID( mode ) returns STRING - gives information about current symbol GICS category mode = 0 - returns string containing GICS code alone (such as " 15103020") mode = 1 - returns string containing GICS category name (such as "Paper Packaging") mode = 2 - returns string containing both code and name (such as "15103020 Paper Packaging") InGics( "gics_code" ) - performs yes/no test if current symbol belongs to given GICS category for example if GICS set for the symbol is 15103020 InGics("15"), InGICS("1510"), InGics("151030") and InGics("15103020") will ALL return true but all others (like InGics("20")) will return false. Example usage: "GICS(0) = " + GicsID( 0 ); " GICS(1) = " + GicsID( 1 ); " GICS(2) = " + GicsID( 2 ); for( i = 10; i < 90; i+= 1 ) { gics_code = StrFormat("%02.0f", i ); printf("In Gics '"+ gics_code + "' = %g\n", InGics( gics_code ) ); } • In minimised windows RequestTimedRefresh with onlyvisible parameter set to False worked unreliably when multithreading was ON. Fixed. • AFL engine gives more detailed information about exceptions (including line numbers and file path) • Formula editor, indicators and commentary catch all exceptions, not only system exceptions • Fixed potential crash when param dialog is referring to non-existing view (NO_CHART_ID) • AFL: "Unknown exception" should now be reported with line numbers for easier identification of ofending function • AFL: for/while/do-while loops were not executed if syntax or runtime error occured before them and "stop parsing on first error" was turned off. Fixed CHANGES FOR VERSION 5.35.0 (as compared to 5.34.5) • AFL Editor: "firstvisiblebarindex" and "lastvisiblebarindex" are initialized with first and last data bar when using "Verify syntax" to avoid problems. Although these Status fields should only be used in indicators, it is quite common mistake among users to use them unconditionally • AFL: Sum() function displays Error 52. Invalid argument value when range argument is negative (instead of random crash) • Account manager: fixed OLE exception in date conversion occuring randomly due to uninitialized exit date when trade has been opened. • Indicator Maintenance Wizard now creates log (indmaint.log in AmiBroker directory) that reports all layout files read and eventual errors found. It also attempts to read corrupted layouts in a "safe" way so it does not crash • Parameter window: fixed handling of mixed section and section-less parameters • Quote Editor: fixed editing when timeshift was not zero plus added ability to turn on/off timeshift (so quotes can be edited in original exchange zone) • Fix: Click on items in param() window did not set focus ( fix @ line 1505 HotPropCtrl.cpp ) • AFL: Error 10. Subcript out of range message now gives information about exactly which array element was accessed • AFL: Added new error message "Error 51. Array subscript has Null value" • /STACK:2097152,16384 (2M/16K) option for x64 compilation - to allow deep nesting in AFL, also reduced stack usage by Execute() function • Removed (evil) IsBadReadPtr function • OLE: AB.RefreshAll( [optional] Flags = 1 ) - takes now new optional parameter Flags. Flags = 1 means refresh only charts (fast), Flags = 3 means refresh charts, dialogs, symbol list, chart list, etc (SLOW!) • OLE: AB.RefreshAll() changed for improved consistency (marks for refresh and it is refreshed every 1 second regardless of number of requests within one second) • //--Indicator-End-- special marker is now obsolete and does nothing (entire formula is executed). For conditional execution of interpretation code use conditional statement if with Status() function • Fix: switch( str_function_call_here ) did not work properly when expression was a function call returning string such as StrLeft(). Fixed • Fix: internal time conversion (flocaltime) made thread safe using TLS • AFL: Equity() now uses thread local storage for keeping stop state variables to prevent interference when multiple threads call Equity() • AFL: mtRandom(A) now uses thread local storage, so using non-null seed yields reproducible sequence even if multiple threads are calling mtRandom in parallel • Foreign() uses SendNotifyMessage instead of PostMessage if symbol data are not already cached to trigger loading quicker (solves support #78278) • Implemented cross-thread bidirectional communication mechanism that allows to call functions across threads in safe way. This allows among other things to make non-threading safe APIs (like Quotes Plus) to operate properly with multi-threading enabled. (Fixes GetExtraData crash with QP2 - FC#2072) • Prefs/Misc/"Show interpretation in tooltips" checkbox removed as this functionality has been removed in 5.32.0. Use Interpretation window instead (View->Interpretation) • OLE: AB.Import() - UI is automatically refreshed after import so there is no need to call RefreshAll() anymore. Also the refresh is "smart" it only updates symbol lists if any symbols were added CHANGES FOR VERSION 5.34.5 (as compared to 5.34.0) • Worked around Microsoft OS bug #248760 and #209467 - writing to metafiles from multiple threads causes lost object selections. This has caused display unstability for Gfx function-generated output. The only way to fix that was NOT to use metafiles at all. Gfx code was rewritten not to use Microsoft metafiles. As a result of custom implementation Gfx functions work now 3 times faster and are multi-threading safe. • GfxDrawText automatically falls back to much (4x) faster ExtTextOut when format is 0 or DT_NOCLIP and string does not contain any new line characters CHANGES FOR VERSION 5.34.0 (as compared to 5.33.0) • Fix: Gfx functions when run in multithreaded mode slowed down over time due to Micosoft MFC library GDI wrappers not being thread-safe. Fixed by replacing MFC calls with straight WINAPI calls. • Multi-threading charts are now ON by default and will be reset to ON on each restart. This change is temporary but added because some people forget to turn this on. • Fix: When Symbol Lock was ON, currently focused chart did not update its quote cache. Fixed • Fix: Status("redrawaction") was giving 0 result for timed refreshes in 5.31-5.33 while it should give 1. Fixed. • Fix: GDI leak found when using Gfx* functions in Automatic Analysis that resulted in resource exception after long use. Fixed • Fix: GDI leak found after Parameter windows "Reset all". Fixed • Fix: Black screen in Edit->Image->Copy as bitmap/Metafile/Export/Send e-mail. Fixed. Now uses separate instance of AFL engine not to interfere with execution running in the background. • Fix: AFL engine did not release memory buffer for pre-processed parts (#include). Fixed • AmiBroker now has requestedExecutionLevel set to "asInvoker" in its manifest file and that prevents Vista/Windows 7 folder virtualization. It also displays a warning message when it does not have write access to its working directory. CHANGES FOR VERSION 5.33.0 (as compared to 5.32.1) • OLE: Analysis object - added IsBusy property that allows OLE programs to check whenever AA is currently running asynchronous AA operation • In 5.32.1 only active window was refreshed automatically by streaming data - others required mouse click. Fixed. • In 5.32 formulas using Status("actionex") == actionIndicator caused blank pane when focused because actionex was NOT indicator. Compatibility shim implemented. • Fixed bad crash occuring when using AddToComposite with atcFlagsEnableInIndicator in multi-threaded mode • Fix: Interval linked charts did not update immediatelly and multi-window layouts required click to update after loading. Fixed. • Fix: Crash @501C30 when doing double right click on Data window • Dangling pointer to view (after its deletion) removed from timedrefresh map and parameter window. This prevents some crashes • Compat: In 5.32 when SetOption() was placed AFTER custom backtester procedure code in user formula - such options did not affect CBT results. Technically 5.32 was correct one and 5.30 incorrect (such options affected CBT results), but because probably too many user formulas are poorly written without taking attention on placement of SetOption() calls and that created false bug reports, an old compatible behaviour was restored till the time when error messages about wrong placement of SetOption() calls are implemented, so users become aware about their coding errors. • Bug recovery/report dialog now allows the user to type steps required to reproduce the crash and select how often given problem occurs • Attempts to run AA asynchronous operation (Backtest/Optimize/Scan/Explore) via OLE while another one is still running are detected and prevented (with error message "Automatic Analysis is Busy processing") • AFL thread termination routine checks for possible same-process COM call deadlock and pumps COM messages if necessary to complete thread gracefully CHANGES FOR VERSION 5.32.1 (as compared to 5.32.0) • Fix: when "stop parsing at first error" option was turned on "Reset all" button in parameters window caused params to disappear. Fixed • Fix: random crash @7792E25B (small alloc heap corruption) fixed • Fix: random crash @4BFFF7 (when accessing static variables from multiple threads at once). Fixed. • Fix: Eliminated multi-threaded race condition that randomly caused blank charts. CHANGES FOR VERSION 5.32.0 (as compared to 5.31.2) • Parameters work also without _SECTION_BEGIN/_SECTION_END, Parameters 'Reset All' operation improved • Interpretation does not use extra execution cycle anymore (text evaluation is done within normal indicator execution) • Formula Editor: Syntax check, Apply indicator, Insert work faster because it only uses 100 bars to perform syntax check instead of all bars • Formula Editor: Code check & profile uses not more than 100K bars • Fix: Timing display in the chart shows correctly AFL execution and redraw time when multi-threading is ON and does not flicker • Fix: Say() function works properly when multithreading is ON • Fix: Errors occuring in JScript/VBScript parts do not result in crash anymore • Data Window now allows to choose which of default data elements (OHLCV, OI, Aux1/2) to display - use Right click context menu • Data window display is immediate and does not require extra AFL execution • Data tooltip readout is immediate - does not use extra execution cycle anymore (implemented internal cache) • When there are no parameters for given indicator - empty brackets are not added anymore for display in tooltip/data window and as a return value of _DEFAULT_NAME(). CHANGES FOR VERSION 5.31.2 (as compared to 5.31.1) • Fixed: Problems with Gfx functions in 5.31.1 • Fixed: Parameters window was not refreshed properly after ResetAll in 5.31.1 • Fixed: Crash when switching layouts in 5.31.1 • Fixed: Crash @004C297D - Foreign returned wrong interval in 5.31.1 • Fixed: Crash @0040F91C / @0040FA2B (all references to ChartInfo removed from AFL engine) in 5.31.1 • Fixed: Automatic Analysis ignored changes done via SetOption and other runtime settings-related changes in 5.31.1 • Fixed: Changing chart display interval did not work immediatelly in 5.31.1 CHANGES FOR VERSION 5.31.1 (as compared to 5.31.0) • fixed crash @0040BACD (using Gfx... functions) when multi-threading was enabled • fixed crash @0041E27C (JScript/VBScript embedded code) when multi-threading was enabled • fixed crash @7686F05D and @004B83EC (load/create new database) when multi-threading was enabled CHANGES FOR VERSION 5.31.0 (as compared to 5.30.4) • Major change: AFL Engine rewritten completely to allow multi-threaded execution CAVEAT: this is very new code and may not be stable This change will lead to several improvements that will be added in future versions. First public release of multi-threaded AFL engine (5.31.0 BETA) features support for multi-threading in commentary and charts. By default multi-threaded execution in charts is disabled. To enable multi-threaded execution of charts, go to Tools->Preferences, "AFL" tab and check "Multi-threaded charts". Note that once you turn this option on, each chart PANE will execute in separate thread, so refreshes of each pane will become completely asynchronous, non-blocking. This has quite dramatic (positive) effect on perceived snappiness of user interface. However, there are also things you need to keep in mind. If your formulas rely on certain order of execution of panes, they may work incorrectly because generally all panes will be executing in parallel, and it depends on complexity of formula which one will finish earlier. Also a formula that is quick to execute may run several times while the other lenghty one is only finishing one run. This has also another side effect that Foreign and AddToComposite functions when they are used in chart formulas, will operate in asynchronous way (what you write with AddToComposite may not necesarily appear instantly if you read it back right after using Foreign()), therefore it is recommended to use static variables when you need synchronized access between threads. Since each thread uses approximatelly 1 MB of RAM for thread stack, the memory consumption when using multi-threading may be slightly larger. There are some things that do not work properly yet when "multi-threading charts" are turned on: • Performance meter / chart timing display do not show AFL execution times (the values reported are minimal). • Data tooltips / Data window are still executed in main GUI thread and this in theory can lead to problems (to improve stability it is recommended to turn off price data tooltips in Tools->Preferences->Miscellaneous) •HYBRID now allows importing OpenInterest, Aux1, Aux2 onto existing data without need to specify price
• New AFL function: PlaySound( "filename" )

The function plays back specified .WAV file

returns 1 on success, 0 on failure

Example:
PlaySound("c:\\windows\\media\\ding.wav");

• New AFL function: ShellExecute( "filename", "arguments", "workingdir", showcmd = 1 )

The function opens a file or runs executable.

It is equivalent of Windows API ShellExecute, with one difference, it always uses "open" verb.
This allows running executables, scripts, opening document files using their associated editors, etc.

If the function succeeds, it returns a value greater than 32. If the function fails, it returns an error value that indicates the cause of the failure.
For possible error codes, consult Microsoft documentation:
http://msdn.microsoft.com/en-us/library/bb762153(VS.85).aspx

Example:

• Multiple file open dialogs now use 1MB buffer (instead of 256K)
• OptimizerSetOption and OptimizerSetEngine are now no-ops for anything but backtest/optimization action

This prevents random problems when one used OptimizerSetOption or OptimizerSetEngine within indicator code.
• Value labels are drawn with a little offset from the Y axis. First Plot() label is drawn with an arrow pointing out exactly price level
• When main application window is in modal state (displaying File open dialog for example), RequestTimedRefresh is held
This fixes problem with file dialog changing current working directory while browsing for directory (FC #1670)
• When multiple MDI windows are open and one is maximized, the windows in back that are completely obscured by others and minimized windows are not redrawn during normal RT refresh

It is worth noting that if you use RequestTimedRefresh the chart will continue to be refreshed periodically even if obscured by other windows.
If you use RequestTimedRefresh with "onlyvisible" parameter set to False, the chart will be also refreshed if it is minimized

CHANGES FOR VERSION 5.30.3 (as compared to 5.30.1)

• Added GICS property to Stock OLE object
• Tools->Prefs->Data "In memory cache size" upper limit was sometimes calculated incorrectly on 64 bit Windows. Now upper limit is equal to physical RAM size even if > 4GB
• RequestTimedRefresh now supports sub-second (down to 0.1 sec) resolution, when enabled via registry setting (HKCU/Software/Broker/Settings/EnableHiresRTR, DWORD value = 1 )

CHANGES FOR VERSION 5.30.1 (as compared to 5.30.0)

• Show arrows for actual trades does not show arrows immediately. Fixed
• IB plugin: set Aux1/Aux2/OpenInt to zero
• Default redraw time (when no charts are displayed) is set to arbitrary 0.1 sec (instead of 1 sec used previously)
• Other minor fixes
• Performance warning tooltip is popped up automatically only once per run unless you exceed 1000% load
• Fixed access violation when refreshing "Charts" window under extreme load
• PluginNotification structure is now larger - has pCurrentSINew that is a pointer to new StockInfo structure, while pCurrentSI is reverted to StockInfoFormat4 to maintain compatibility with plugins that were no rewritten using new API

CHANGES FOR VERSION 5.30.0 (as compared to 5.29.6)

• When non-existing symbol is typed into "ticker" box, AmiBroker will first check if symbol with given Alias does not exist before proposing to add new symbol
• AmiBroker now ensures that during writing of data and config files no other process is reading or writing to them in order to prevent possible data corruption when running multiple simultaneous instances accesing same files. In case some other process is working with given file AB will retry to access given file within next 0.25 sec and repeat four times before failing
• Simple trading from the chart implemented (see "Place a buy/sell on chart" buttons in the toolbar and Insert menu) - requires installation of auto-trading interface
• Possible small database reading speed enhancements via use of FILE_FLAG_SEQUENTIAL_SCAN
• Parameters file (broker.params) was kept open all the time instead being closed right after reading/writing and that could cause problems. Fixed
• New status bar indicator showing performance measure: percentage load factor and more info in the tooltip
• Status bar information auto pop time set to 10 seconds to allow easier reading
• Filling symbol combo box is speeded up
• " Wait for plugin" shows up only when plugin takes more than 0.5 sec to initialize/release and uses simpler animation and does not use topmost style therefore does not cover IQFeed Connect dialog

CHANGES FOR VERSION 5.29.6 (as compared to 5.29.5)

• Race condition between UI threads eliminated (resulting in "wait for plugin" window not being closed sometimes)

CHANGES FOR VERSION 5.29.5 (as compared to 5.29.2)

• Sometimes when copying AA list to clipboard three dot (...) sequence appeared every 2048 characters of copied text and some characters could be missing. Fixed.
• GUI: chart context window items re-arranged - 'Close' menu item moved to the bottom and 'Properties' menu item moved to top (after Parameters)
• styleClipMinMax constant is now highlighted in AFL editor
• When different symbol were selected in active chart and in the Symbols pane (because of filtering) operations like adding/removing from watchlist got confused. Now AmiBroker asks the user what to do.
• NumToStr/WriteVal are polymorphic now (means better performance for scalar input arguments)
• Aux1/Aux2 reserved variables are highligted now in AFL editor
• PREV/NEXT sibling keyboard shortcut functionality restored
• Added "wait for plugin" window when switching external plugin-driven databases because sometimes plugin may take long time to shutdown/initialize
• New symbol bar: inability to select first symbol after new search when previously displayed was one symbol, current symbol is re-selected automatically when search string changes. In-place symbol editing disabled.
• Under some circumstances when broker.master was deleted/corrupted/inaccessible AmiBroker could hang loading database. Fixed.
• Cum() function does NOT use all bars any more by default.
In the past versions Cum() functions effectively turned OFF QuickAFL feature by requesting all bars to be processed.
Since Cum() function was popular it caused that many legacy formulas that used it were not benefiting from QuickAFL.
To enable QuickAFL with such formulas now Cum() function does NOT affect required bars count (previously it forced all bars).

This change may lead to different results when comparing with old versions. If you are interested in getting old behaviour and use all bars just add:

SetBarsRequired( sbrAll )

• BarIndex() now returns values always starting from zero (even if QuickAFL is turned on).
This change is required because Cum() now does not require all bars and formulas mixing Cum(1) and BarIndex would work improperly otherwise.
• Due to operating system changes in Vista and Windows 7, structured exceptions like address violations were not handled properly by exception handler and caused immediate program exit. Fixed.
• Status() function new fields
Status can now retrieve "quickaflfirstdatabar" and "quickafllastdatabar".
This feature is for internal use only.
These are bar indexes of actual underlying compressed quotation array that make up AFL's array[ 0 ] and array[ BarCount - 1]
• Crash report now properly lists Windows Vista (OS 6.0) and Windows 7 (OS 6.1)
• Crash recovery window now sends bug reports directly over http (WWW) protocol instead of relying on clients' MAPI email program as on Windows 7 e-mail program is no longer installed by default.

Improved crash recovery should also be able to catch exceptions in more (all?) cases.
New direct send in future will offer immediate resolution to problem once given exception is identified and entered into database.
Privacy:
Direct bug reporting allows to send bug report to amibroker.com on user request (click on "Send report" button).
It works over regular http (www) port 80, and sends only the information displayed explicitely on screen
(i.e. AmiBroker version, OS version, crash information, database info (number of symbols) and machine info (memory figures)).
No other information is sent. The user has option to send anonymously (without providing e-mail address). Although e-mail
address is optional, it is recommended to provide one if user wants to receive e-mail response to the error report.

CHANGES FOR VERSION 5.29.2 (as compared to 5.29.0)

• Some issues with datestamps (including wrong montly compression) were introduced by change to EOD markers done 5.29.0. Reverted/fixed.
• New symbol window is properly filled with categories even if not initally visible
• New symbol window category/list panes can be resized now
• GetPlaybackDateTime did not return zero when playback was not active in 5.27-5.29. Fixed.
• When plugins used InfoSite.AddStock (old one) more than once per symbol certain category assignments could be improperly set in 5.27..5.29.0. Fixed.
• Added fopen()/fclose() tracking and error message (Error 51) when user forgot to close files. On such error files are automatically closed by AB

CHANGES FOR VERSION 5.29.0 (as compared to 5.28.1)

• ASCII importer: added GICS support

Now you can import GICS symbol-code assignments using ASCII importer.
$FORMAT command now supports GICS code and there is$GICS command for single-symbol files.

For example if your file looks as follows:
(format is symbol, full name, gics sub industry code)
AAN,AARON'S INC,25504060

Then to import it usign AmiBroker's import wizard use the following
$FORMAT Ticker,FullName,GICS$OVERWRITE 1SEPARATOR ,
$CONT 1$GROUP 255
$AUTOADD 1$NOQUOTES 1

• Fixed loading of old AA settings so Chart dimensions are initialized with (500,300) instead of zero
• Trade.EntryDateTime, Trade.ExitDateTime were reporting values incompatible with DateTimeToStr in 5.27/5.28. Fixed
• Fixed assertion in Import Wizard (refering to non-existing combo box)
• A blank chart timing is now set to arbitrary value of 10ms
• All numeric edit fields in AmiBroker now display numbers in regular (non-scientific) notation upto 10^15 and max available precision (7 significant digits in case of single-precision IEEE)
• ASCII importer: removed 2^31 cap on volume field and removed some (int) conversions that were left from old days
• Implemented protection against re-entrant WM_PAINT messages sent by Vista and Win7 during COM calls
• New symbol list is repainted immediately after some changes now.
• Quote Editor in 5.28 editing EOD records caused creation of duplicates. Fixed.
• When converting from old database format, Aux1/2 fields are initialized with zero instead of some random values.
• When focus was inside new symbol window, accelerator keys did not work in 5.28. Fixed

CHANGES FOR VERSION 5.28.1 (as compared to 5.28.0)

• Re-based DLLs included to increase contiguous virtual memory space
• " Index" category was showing nothing in a new symbol window. Fixed.
• Quote Editor - multiple quote deletion was not possible in 5.27/5.28.0, only first selected item was deleted. Fixed
• Right-click beyond last symbol in the symbol list in a new symbol window caused crash in 5.28. Fixed.
• Changed the way in DateTime() values are coded to support legacy formulas that are not using currently recommended comparision method via DateTimeDiff()
• OLE: ZoomToRange() method works for floating windows

GetDateTimeArray returns a pointer to internal date time array. Array of DATE_TIME_INT elements.

The SiteInterface structure now looks as follows (struct size = 40 on 32-bit platforms, 76 on 64-bit platforms)

struct SiteInterface
{
int nStructSize;
int (*GetArraySize) (void);
float * (*GetStockArray)( int nType );
AmiVar (*GetVariable) ( const char *pszName );
void (*SetVariable) ( const char *pszName, AmiVar newValue );
AmiVar (*CallFunction) ( const char *pszName, int nNumArgs, AmiVar *ArgsTable );
AmiVar (*AllocArrayResult) (void);
void * (*Alloc) (size_t nSize);
void (*Free) (void *pMemory);
DATE_TIME_INT* (*GetDateTimeArray) (void);
};

• In 5.27/5.28 DateTimeConvert function returned incorrect datenum. Fixed
• New symbol list supports selection via typing few first letters (like symbol combo)
• When saved Automatic Analysis settings contained some garbage data in MaxLongPos/MaxShortPos parameters the backtester could exit with "Not enough memory" error. Fixed

CHANGES FOR VERSION 5.28.0 (as compared to 5.27.3)

• GICS is now available as Filter category (in Automatic Analysis, Quick Review and DB Purify)
• Completely redesigned Symbol window (View->Symbol)
New symbol window now features:
a) separate category/filter view
b) full text search with category filtering
full text search works in two modes:
- simple substring search (enter the text into "<search>" edit and
it will find all symbols that contain search phrase in either symbol or full name (anywhere, not just at the beginning)
- wildcard search (if you enter the search phrase with either * or ? wildcards
AmiBroker will perform wildcard search. For example ??? will return only 3-character symbols, and *-A0-FX - will return all forex symbols on eSignal database. Please note that search feature operates on symbols PRESENT in the AmiBroker database, it will not find symbols that do not exist in the AmiBroker database yet but are generally accessible after importing/adding them.
c) sorting by symbol or by full name
d) GICS support
e) hierachical filtering (if you select sector from category view it will show symbols
belonging to all industries within given symbol)
f) multiple selection of symbols (hold down CTRL key while selecting, or SHIFT to select groups)
allowing watchlist/favorite operation on multiple symbols at once
g) super-fast operation (all filtering/search/display takes less than 0.01 sec with 10000 symbols)
• Quote Editor Aux1 field was overwritten with value of Aux2 field. Fixed
• Quote Editor column layout/width is saved between sessions (again)
• N-second custom intervals can now be defined in Tools->Preferences->Intraday
• GICS categorisation
AmiBroker now reads GICS.txt file from its installation folder.
It contains GICS categories listed one by one in order of GICS code in the following format
GICS;Name;Description<CRLF>

GICS is numeric code from 2 digits upto 8 digits
Name is GICS category name
Description is GICS category description
These fields must be separated by semicolon
< CRLF> means carriage return/line feed characters (means "new line" - just press ENTER/RETURN key if you are editing with text editor)

There must be only one category per line in GICS.txt file

The default GICS.txt file is supplied already.

• Added support for GICS to AFL

There is a new constant : categoryGICS that works
in conjunction with category functions like
CategoryGetSymbols
CategoryGetName
CategorySetName
CategoryRemoveSymbol
CategoryFind

Note that these functions take index parameter, but the meaning of index parameter is different for GICS category - the index for categoryGICS is actually GICS code. Such as 10 for energy sector or 351010 for "Health Care Equipment & supplies" industry.
The codes are fixed even if new classifications are added at some point in the future. This means that you won't need to change AFL codes even if new classifications are added. But it is important to understand that these codes work in hierarchical way. So
GetCategorySymbols( categoryGICS, 10 ) will return all symbols belonging to energy sector, including those in 10101010 - Oil & Gas Drilling sector as well as 10102050 - Coal & Consumable Fuels; for example.
See
http://en.wikipedia.org/wiki/Global_Industry_Classification_Standard
for more details on GICS system

NOTE: current databases DO NOT have GICS codes assigned to symbols.
As far as I know PremiumData http://www.premiumdata.net/ is planning to release AmiBroker-compatible database with GICS support.

CHANGES FOR VERSION 5.27.3 (as compared to 5.27.2)

• HighestSince/LowestSince ignored very first bar [0] in the array. Fixed
• Stock object date fields can be set to "empty" by assigning zero.
• Aux1,Aux2 added to Import Wizard comboboxes
• View->Data window is now present in Customization dialog
• Weekly chart was not displayed if settings were to show first date of week and first date was before 1970. Fixed.
• Added DateTimeDiff( arg1, arg2 ) AFL function that returns difference in seconds between two date time arguments
It is important to understand that DateTime is not a simple number but rather bitset and two datetime values can only
be reliably compared for equlity or inequality using == or != operators. Any other comparisions (less than/greater then)
using normal operators > < can lead to wrong results, therefore to compare two datetime numbers you should use
DateTimeDiff( arg1, arg2 ) which will return positive values if arg1 > arg2 and negative values if arg1 < arg2.
• Symbol->Quote Editor now uses fully virtual mode - it does not require extra memory and shows up immediatelly and works fast regardles of number of quotes per symbol and is auto-refreshed every 5 sec
• eSignal plugin does not fill AuxData with random data (they are initialized with zero now)
• Fixed DateTimeToStr and StrToDateTime
• Fixed crash when saving symbols that had name() longer than 32 characters

CHANGES FOR VERSION 5.27.2 (as compared to 5.27.1)

• Fixed 16-character name problem in Metastock plugin
• Fixed monthly compression problem present in 5.27.1
• Fixed problem when OLE automation was used to modify symbol properties on OLD format databases without saving them first in new format
• Aux1 and Aux2 are new built-in AFL price arrays
• Fixed Text tool bug (Vertical text instead of horizontal in 5.27.1)
• 'Avg' field compression with TimeFrameSet fixed.
• Added AUX1 and AUX2 to ASCII importer field definitions
• Auxilliary data fields writable by AddToComposite field "1" (aux1), and field "2" (aux2)
• Quotations object added new method: long RetrieveEx(long Count, VARIANT* Date, VARIANT* Open, VARIANT* High, VARIANT* Low, VARIANT* Close, VARIANT* Volume, VARIANT* OpenInt, VARIANT* Aux1, VARIANT* Aux2);
• Aux1/Aux2 available as properties of Quotation object (OLE interface)

CHANGES FOR VERSION 5.27.1 (as compared to 5.27.0)

• Fixed incorrect year when importing intraday data using ASCII importer
• Fixed intraday filtering issue that occurred for auto-converted databases
• Market ID was not properly set in 5.27.0 alpha

CHANGES FOR VERSION 5.27.0 (as compared to 5.26.5)

• changed core data structures to support the following

• 64 bit date/time field with date range of 4095 years and resolution down to microseconds
• floating point volume and open interest fields
• two new auxilliary data fields per bar (internally, not yet exposed)
• 100 new user-defined fundamental data fields (internally, not yet exposed)
• support for GICS (internally, not yet exposed)
• upto 48 character length in Symbol/Alias/WebID fields
• Updated plugins for eSignal, IQFeed, Interactive Brokers, Quotes Plus, Metastock to support floating point volume/open int and 64 bit date/time
• Metastock plugin now reads long symbol description
• Symbol lock fixed (does not interfere with Interval linking)
• Added simple "BackupAB.exe" to backup entire AmiBroker folder after installation to prevent data in old format.

CHANGES FOR VERSION 5.26.5 (as compared to 5.26.0)

• Symbol lock on per-chart window basis (available via padlock button next to chart sheet tabs and chart context menu)
• User interface dialogs now use MS Shell Dlg 2 (Tahoma) font on Windows 2000, XP, Vista and Windows 7
• several minor fixes for 64 bit version

CHANGES FOR VERSION 5.26.0 (as compared to 5.25.0)

• Implemented user-definable report charts

Now it is possible for the user to create any number of charts that will be automatically generated and included in the backtest report.

To add user-defined chart to the report, simply save your chart formula under "Report Charts" folder.

That's all.

Any formula present in the "Report Charts" folder will be executed after completion of the backtest using ~~~EQUITY as selected symbol.

The beta ships with 3 sample charts:
a) portfolio equity
b) underwater equity (drawdown)
c) profit table

The charts are displayed in alphabetical order (using file name as a chart name).

• Built-in price arrays (OHLC, V, OI, Avg) are protected against assigning the value of wrong type (non-array)

CHANGES FOR VERSION 5.25.0 (as compared to 5.24.0)

• StaticVarGet() now has additional parameter - align

StaticVarGet("varname", align = True );

second parameter - 'align' - booleand True/False, default: True
- decides whenever AmiBroker performs timestamp synchronization/alignment or not.

The default value is True and it means that values stored in static variables
are retrieved and aligned to currently selected symbol data/timestamp
on each bar basis so data for corresponding date/time stamps match.
This is recommended setting and this is the way it worked in previous versions.

When align is switched to False - it means that AmiBroker does not perform
any checks nor any alignment and will fill the array with consecutive values
stored in static array regardless of their timestamps.
If there are less bars in the static array than in the current arrays, the last
value of static array will be propagated till BarCount - 1.

It is advised NOT to use align=False, unless you know exactly what you are doing
and you are aware that date/time stamps have no meaning in particular variable
or in case when date/time stamps are are aligned using your own method.

Note that speed difference between align 'on' and 'off' is usually negligible
because alignment algorithm is very fast and has similar complexity as plain
memory copy.

• AFL: HighestVisibleValue( array ), LowestVisibleValue( array )

Two new functions that calculate single value (not array) representing
highest and lowest values of given array within VISIBLE range (on chart).
Should be applied only in indicators as only indicators have concept of "visible" bars.
The function will return Null value if no visible bars are present.

They are equivalent to the following coding:
function HighestVisibleValueEquivalent( array ) {  bv = Status("barvisible");  Hh = -1e8;  for( i = 0; i < BarCount; i++ )  {   if( bv[ i ] AND array[ i ] > Hh ) Hh = array[ i ];  }  return hh; } function LowestVisibleValueEquivalent( array ) {  bv = Status("barvisible");  ll = 1e8;  for( i = 0; i < BarCount; i++ )  {   if( bv[ i ] AND array[ i ] < ll ) ll = array[ i ];  }  return ll; }

As you can see the AFL equivalent is simple, but native functions
are faster.

• When user picks a drawing tool, AmiBroker offers switching to default layer (0) if current layer is not visible
• StaticVarRemove("varname") now supports wildcards in the variable name

"varname" parameter can be either exact variable name or wildcard match string.
The '*' matches any number of characters, including zero characters. The '?' matches exactly
one character.

Example 1:

StaticVarRemove("MyVariables*");
// this will remove all static variables beginning with MyVariables prefix.

Example 2:

StaticVarSet("DifferentName", 1 ); printf( "Total static variables = %g\n\n", StaticVarCount() ); for( i = 1; i <= 5; i++ )   for( j = 1; j <= 5; j++ )    {      VarName = "Test_X=" + i + "_Y=" + j;      printf("Setting variable " + VarName + "\n" );      StaticVarSet( Varname, 1 );    } printf( "Total static variables = %g\n\n", StaticVarCount() ); printf( "Now wildcard remove *X=1*\n" ); StaticVarRemove( "*X=1*" ); printf( "Total static variables = %g\n\n", StaticVarCount() ); printf( "Now wildcard remove Test*\n" ); StaticVarRemove( "Test*" ); printf( "Total static variables = %g\n\n", StaticVarCount() ); printf("Removing 'differenname' variable\n"); StaticVarRemove("DifferentName" ); printf( "Total static variables = %g\n\n", StaticVarCount() );
• StaticVarCount function added - returns the total number of static variables in memory

• Study() function now allows to specify which Y scale to use (Study( studyid, chartid, scale = -1))

Study( studyid, chartid = 1, scale = -1 )

scale parameter specifies which scale should be used
scale = -1 : automatic (default value) - either linear or logarithmic depending on actual chart setting, chart is specified by chartID
scale = 0 : linear scale
scale = 1 : logarithmic scale

• data and optimizer plugins are loaded later (saves upto 15MB of RAM)
• Fixed GetChartBkColor function
• " show trading arrows" feature optimized for significantly lower CPU usage
• hi-density (>2x more data bars than pixels) variable color styleHistogram charts are plotted with correct colors
• less reallocations in real-time mode, 10% performance improvement and less fragmentation
• arrays for storing dynamic stop levels are only allocated/filled when needed (saves about 10% of AFL setup time)

function PlotGradientArea( array, caption, ColorTop, ColorBottom ) {  bkclr = GetChartBkColor();  HH = HighestVisibleValue( array );  if( NOT IsNull( hh ) ) SetChartBkGradientFill( ColorTop, ColorBottom, bkclr, Null, HH );  Plot( array, Caption, ColorBlend( ColorBottom, colorBlack ) );  PlotOHLC( HH, HH, array, HH, "", bkclr, styleNoLabel | styleNoTitle | styleCloud, Null, Null, 0, -10 ); } _SECTION_BEGIN("Price"); SetChartOptions(0,chartShowArrows|chartShowDates); _N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) )); PlotGradientArea( C, "Close", ParamColor("Top", colorLightOrange), ParamColor("Bottom", colorPaleGreen ) ); _SECTION_END(); 

CHANGES FOR VERSION 5.24.0 (as compared to 5.23.0)

• typeof() incorrectly returned compile-time type instead of run-time type. Fixed.
• Static array variables implemented

StaticVarSet( name, value ) and
StaticVarGet( name )
AFL functions now accept arrays in addition to numbers (scalars).

Static arrays can be even 100 faster than AddToComposite/Foreign, however these two are not strictly equivalent.
There are following limitations / differences of static arrays as compared to Foreign/AddToComposite:
a) static array variables store only as many bars as there are currently in use by given chart
(so they do not affect QuickAFL in any way). This is different that AddToComposite that forces usage and store of all bars.
b) static array variables work best if you read them using the same interval as they were written to. I.e when you create static array variables using 5-minute chart, for best results read them in some other 5-minute chart. Reading in different intervals is possible, but subject to limitations
of timestamping (see below)
c) when you read static variable in a different interval that it was originally stored,
static variables perform padding/synchronization and time compression/decompression automatically in a similar way as foreign,
however Foreign compresses data always from base-time interval, while static variables operate on previously stored interval,
hence result may differ. For example, if previously stored data was in daily interval, and you read such static variable in intraday
chart, you will see essentially flat lines for each day, representing static data from daily interval.
d) static array variables do not work well for non-time based intervals (tick/n-volume/n-tick) because timestamps in those intervals
may not be unique (i.e. several bars may have same time stamp), so time synchronization is not reliable.
e) static array variables are little slower than normal AFL variables, so for best performance, use read-once, write-once paradigm, using
temporary normal variable for any processing during formula execution, like this:
// start of the formula:
temp = StaticVarGet("mystaticarray" );

// now perform all necessary calculations using temp variable

temp = Nz(temp) + C/2;
...

// at the end of the formula store to static
StaticVarSet("mystaticarray", temp );

CHANGES FOR VERSION 5.23.0 (as compared to 5.22.0)

• Font used by progress window, string input, tip of the day, search file is now "MS Shell Dlg" (the same as elsewhere in AB) that means that is CoolType friendly (TTF)

• AFL: SetOption("ExtraColumnsLocation", col) - this new option allows the user to change the location of custom columns added during backtest/optimization

"extra" columns mean:
a) any custom metrics added using custom backtester
b) any optimization parameters defined using Optimize() function

If both custom metrics and optimization parameters are present then
custom metrics appear first then optimization parameters

This function is provided to allow the user to change the default "at the end" location of custom columns/optimization parameters.
For example

SetOption("ExtraColumnsLocation", 1 );

will cause that custom metrics and opt params will be subsequently added starting from column 1 (as opposed to last column default)

Note that this setting changes "visual" order of columns, not really in-memory order or export order, so
exported data files or copy/paste format do not change.

• Implemented hiding columns in all list views (right click over list view HEADER to bring "Setup Columns" dialog)

• Storing column state (widths/ordering/visibility) in automatic analysis implemented
The widths, ordering and visibility of all built-in columns in automatic-analysis is stored between runs.
This works for each operation mode (i.e. scan/backtest/optimization) separately, so column setup
for scan does not affect stored column order for backtest, as well as state of columns for optimization does not
affect backtest, etc.
Note also that state of exploration mode is not stored, due to its complete user-configurability from AFL level.

• Data Window implemented (available from View->Data Window menu)

(if you can not see this menu, you would need to reset the menu using Tools->Customize, select "Menu Bar" and then press "Reset" button).

If you prefer to use Data Window over data tooltips, you can turn off data tooltips using Tools->Preferences, "Miscellaneous" tab, UNCHECK "Price data tooltips" box.

• Home key was working incorrectly when more than one pane was used in the chart. Fixed

• Implemented simple performance monitor Tools->Performance Monitor
Showing some memory and usage statistics:
- number of symbols in the database
- number of symbols cached in RAM
- quotation data memory usage
- current symbol memory usage
- total chart refresh time
- real-time data stream update frequency

The contents of the window is updated automatically every 3 seconds

This tool is intended to be used now for two purposes:
a) tweaking cache settings for best RAM usage (for example optimizations will run faster if all quotation data can be kept in RAM)
b) monitoring real-time performance

More uses will probably come in the future.

• Time&Sales window now shows some "recent statistics" regarding trading

Time&Sales window now shows some "recent statistics" regarding trading namely:
- ask minus bid difference expressed in number of trades and shares

A little background:
Ask minus bid: the positive numbers represent more transactions occuring on ASK side than on BID side.
This in theory may mean more buying than selling, but in practice things are largely dependent
on security traded. Esp. dark liquidity pools do not show in order books and
may report trades to the tape several seconds later thus invalidating relationship between

IMPORTANT:
These are temporary, short-term stats - they cover ONLY trades displayed in the T&S window since opening of the window OR
resetting stats.

You can reset statistics using right click menu : "Reset Stats"

CHANGES FOR VERSION 5.22.0 (as compared to 5.21.0)

• added ability to extend blank chart area by pressing END key multiple times (each time 10 blank bars are added) and restoring preferences value by subsequent pressing of HOME key.
• added option to always require variable declarations (using local/global) on formula-by-formula basis:
SetOption("RequireDeclarations", True );
global test1;
test1 = 5; // OK variable declared
test2 = 3; // error: assignment without declaration

The typeof operator is used in the following way:
typeof (operand)
The typeof operator returns a string indicating the type of the *unevaluated* operand. operand is the string, variable, function identifier, or object for which the type is to be returned.
When supplying identifier, it should be provided alone, without arithmetic operators, without extra arguments and without braces.
If you want to check the type of value returned by the function, you must first assign the return value to a variable and then use
typeof( variable ).
Possible return values are:
" undefined" - identifier is not defined
" number" - operand represents a number (scalar)
" array" - operand represents an array
" string" - operand represents a string
" function" - operand is a built-in function identifier
" user function" - operand is a user-defined function
" object" - operand represents COM object
" member" - operand represents member function or property of COM object
" handle" - operand represents Windows handle
" unknown" - type of operand is unknown (should not happen)typeof operator allows among other things to detect undefined variables in the following way
if( typeof( somevar ) == "undefined" )
{
/// when somevar is undefined the code here will execute
}
The following sample COMMENTARY code shows the output of
typeof in some common situations
x = MACD();
y = LastValue( x );
function testfun() { return 1; };
printf( typeof( test ) + "\n" ); // the undefined variable
printf( typeof( 1 ) + "\n"); // literal number
printf( typeof( "checking" ) + "\n"); // literal string
printf( typeof( x ) + "\n"); // array variable
printf( typeof( y ) + "\n"); // scalar variable
printf( typeof( MACD ) + "\n"); // function identifier
printf( typeof( testfun ) + "\n" ); // user function identifier

• GetSignalQty member function of Backtester object returned zero. Fixed now
• In the Plot() function Xshift parameter was used as z-order in 5.21 beta. Fixed now.
• Plot, PlotOHLC and PlotForeign() are no longer limited to -5..+5 zorder range. You can use any zorder value now.

Note that if you use zorder outside default range -5..+5, you may see performance degradation for big positive and big negative z-order values.
Approximate performance penalty is 10 milliseconds for 100 z-orders (or 1ms for 10 z-orders)

• SetChartOptions now adds ability to programmatically extend blank space on chart-by-chart basis

SetChartOptions( Mode = 0, Flags = 0, gridFlags = chartGridMiddle, ymin = 0, ymax = 0, blankbars = 0 )
New, 6th parameter "blankbars" defines the minimum number of blank bars for given chart. The default value of zero means no change
(use preferences setting).
if specified value is less than value set in preferences, it is ignored, so you can not decrease the blank bars below value set in preferences.
if many panes within same chart use this function, then the largest specified blankbars will be used
Note that you can still extend blank space further using END key.
Special feature - if "blankbars" is negative then extra blank bars added are equal to absolute value of blankbars parameter plus chart gets scrolled to rightmost position.
Caveat: forcing custom blankbars via SetChartOptions effectivelly disables HOME key scroll to begin operation.

• the feature to extend blank area via mouse wheel and > button is removed, due to complaints received

CHANGES FOR VERSION 5.21.0 (as compared to 5.20.0)

• All drawing tools now can define Z-order (from -5 to +5).

Z-order.
Imagine that you could see the drawing objects arranged on the chart page like puzzle pieces on a table. Some objects may appear to be placed one on top of another, and others may be overlapping.
This third dimension of chart page is known as "Z order." If the X axis relates to width and the Y axis to height, then the Z order relates to depth. Although Z order cannot be seen directly, just as can you position objects along X and Y (horizontal and vertical) axes, you can also position them in the Z order.
Every object on the page has its Z order, positioned in back to front order, so that objects at the front will take precedence over objects behind.
Z order gives you the ability to superimpose objects one on top of another.
You can change Z-order parameter using Properties dialog
as well as using Format->Z-Order->Bring Forward / Send Backward menus
(and default keystrokes Shift+Page Up, Shift+Page Down)
Negative values mean BEHIND axis/grid, positive mean above grid.
• Blank area past last available quote can be now enlarged on the fly by simply using > arrow in the scroll bar or using mouse wheel (just roll the wheel past the last bar) (FC #430,#1516, #1500, #1239, #982, #808, #561 )
• CBT: Backtester.GetSignalQty( bar, type ) method implemented (FC#1671)

Backtester object
GetSignalQty( bar, type ) method
- retrieves the number of signals occuring on given bar
type = 0 - both entry and exit signals
type = 1 - only entry signals
type = 2 - only exit signals
Note that AmiBroker to conserve memory keeps track only of 2 * MaxNumberOfPositions entry signals on any single bar,
however it keeps track of ALL exit signals (because they consume much less space and at the time of signal collection
it is not known which positions are already open, so all exits must be tracked to prevent missing an exit)
• E-mail alerts can now be sent through different port than 25 (see Tools->Preferences->Alerts) (FC#1641)
• Early warning of indicator space running out. At application exit the message is displayed when less than 10% indicator space is left, plus an offer to run Indicator Maintenance (FC#1667)
• new AFL functions ColorBlend

ColorBlend( colorFrom, colorTo, factor = 0.5 )
- the function blends (mixes) colorFrom with colorTo with 'factor' proportion using the following algorithm
RGB = ( 1 - factor ) * RGB(colorFrom) + factor * RGB(colorTo );
So factor = 0 means use colorFrom only, factor = 1 means use colorTo only. All in-between values
mean create mix of colors. The lower the factor value means more colorFrom.
This function makes it easy to lighten or darken colors like this:
function ColorLighten( color )
{
return ColorBlend( color, colorWhite, 0.5 );
}
function ColorDarken( color )
{
return ColorBlend( color, colorBlack, 0.5 );
}
• Plot, PlotForeign and PlotOHLC now have new parameter zorder which defines the Z-axis position of given plot. (FC#257)

zorder can be set from -5 to 5.
The default is zero.
Zorder = 0 means also where the "grid" is located.
So if you want to plot BEHIND the grid you need to specify negative zorder parameter.
Smaller values mean draw first (i.e. BEHIND others), higher values mean draw later (ON TOP of others).
Plots are drawn in the following order:
• zorder parameter takes precedence over the order of calling Plot() functions, so if z-order is set, it determines plotting order.
See http://www.amibroker.com/gifs/zorder.gif
• If multiple plots use the same z-order parameter they are plotted in reverse call order (ones that appear last in the code are plotted first). This rule can be changed by already existing switch graphzorder = 1 which, when specified, reverses this behaviour (so plots are drawn in call order).
Please note the above applies to each zorder "layer" separately (so within same zorder "layer" reverse call rule applies)
This may sound complicated but is required for backward compatibility.
Example:
Bollinger bands with "cloud" fill behind price (zorder = -1)
P = ParamField("Price field",-1); Periods = Param("Periods", 15, 2, 100, 1 ); Width = Param("Width", 2, 0, 10, 0.05 ); Color = ParamColor("Color", colorLightGrey ); Style = ParamStyle("Style") | styleNoRescale;; Plot( bbt = BBandTop( P, Periods, Width ), "BBTop" + _PARAM_VALUES(), Color, Style ); Plot( bbb = BBandBot( P, Periods, Width ), "BBBot" + _PARAM_VALUES(), Color, Style ); PlotOHLC( bbt, bbt, bbb, bbb, "", ColorBlend( Color, colorWhite, 0.9 ), styleCloud, Null, Null, Null, -1 );
• Rectangle and Ellipse drawing tool now are by default SOLID, with default fill color being a blend between background and selected drawing color, they are use ZOrder = -1 (behind regular plots) by default
• Support for SSL (secure connection) e-mail alerts added, so now you can use your GMail accounts. (FC#83)
Steps:
3. Configure (Tools->Preferences->Alerts) with SSL enabled as shown in this picture:
• X-Y co-ordinate labels on axes implemented. Can be controlled using View->X-Y labels menu. (FC#1621, FC#732)

CHANGES FOR VERSION 5.20.0 (as compared to 5.19.0)

• AFL: new function StrCount( "string", "substring" )

Function returns integer which is number of times substring was found in string. It is case sensitive.

The function can be used for example to count the number of commas in comma-separated list

tickers = "AAPL,MSFT,INTC";

numtickers = 1 + StrCount( tickers, "," );

• AFL: StrExtract( "string", item ) now accepts negative item values allowing to address items counting from the END of the list

tickers = "AAPL,MSFT,INTC";

"The last item is " + StrExtract( tickers, -1 );

printf("listing from the end of the list:\n");

for( item = -1; ( sym = StrExtract( tickers, item ) ) != ""; item-- )
{
printf( sym + "\n" );
}

• minor fixes

CHANGES FOR VERSION 5.19.0 (as compared to 5.18.0)

• Internal log window deletes all items if "!CLEAR!" text is outputted (FC 1552)
Example:
_TRACE("!CLEAR!"); // this clears the internal log window.
_TRACE("First line after clear");
• SetOption("RefreshWhenCompleted", True) added. This performs View->Refresh All once AFTER AA operation is completed

Under normal circumstances it is not needed to use that because AmiBroker refreshes ticker tree if necessary,
for example if use AddToComposite. It may be useful if you however use OLE automation inside AA and you don't want to trigger too many refreshes using RefreshAll().
This only works in Automatic Analysis, when used in indicator code it has no effect.
• Sometimes AddSummaryRows was not working when AB.RefreshAll() was used in the formula. Fixed now. (FC1550)

• Date time calendar disappeared when streaming update arrived. Fixed now. (FC 1572)
• Equity ticker symbols (~~~EQUITY, BESTEQUITY, ISEQUITY, OSEQUITY) marked with special flag so they are not used (skipped) in backtest
• Fib Timezones tool now displays lines 144 and 233 too. (FC20)
• math functions (sin,cos,log, ...) added to profiler reporting (array versions only)
• RT quote and log window tab sheet drag-drop marker is visible again
• Y-axis scale labels do not overlap even if chart is very compressed

CHANGES FOR VERSION 5.18.0 (as compared to 5.17.1)

• AFL: CategorySetName() function

CategorySetName( name, category, number )

Function sets the name of category (group,market, watch list, industry)

Arguments;
name - a new name for the category (in case of watch lists it has to be unique)
category - type of category, one of the following: categoryMarket, categoryGroup, categorySector, categoryIndustry, categoryWatchlist
number - the number (index) of the category 0.255 for market, group industry, 0..32 for sectors, 0...unlimited for watch lists
Please note that the function will also create watch list of given index if one does not exist.

• Added protection against trying to use 3d graph on non-exhaust optimization
• ParamToggle default value not shown after "Reset all" in AA [#52129]. Fixed
• added <= 0 check for log10 calls to protect from FPU exceptions when using log chart scale
• Added error message that prevents from running "Current symbol" backtest on IS/OOS/Best equity special tickers
• Added symbol validity check in backtest "Apply To: Current symbol"
• In detailed log mode the backtester now reports reason why trade is not entered
• Line studies were not visible on Yearly and Qtrly charts. Fixed
• Progress window does not steal focus from active window (prevents some random crashes when "run every" is used)
• When "run every" is used progress window is displayed minimized when AA is minimized

CHANGES FOR VERSION 5.17.1 (as compared to 5.17.0)

• In 5.17.0 "Current symbol" selection in AA always used first symbol in the database. Fixed.

CHANGES FOR VERSION 5.17.0 (as compared to 5.16.0)

• Log Window implemented

Log window (View->Log) allows to view:
edit-time errors displayed during formula check
run-time errors that occur when formula is running (not edited)
_trace command output within AmiBroker (without using 3rd party debug view)

To perform tasks such clearing the output, copying, changing settings use right - mouse click over the log window list.
Double click on the error line brings up the editor, so you can fix the error easily.

While "edit-time" error list is cleared automatically each time you check the syntax in the editor, the run-time error list is NOT cleared, so all errors remain listed, even if they are fixed already, unless you manually clear the list.

Note that _TRACE output is by default directed to outside debugger (like DebugView), in order to enable internal display you need to switch appropriate option in the Tools->Preferences->AFL You can choose to display internally / externally or in both places.
Internal _trace has much lower performance penalty (order of magnitude) than external, but that is achieved by the fact that
internal log window is refreshed only when application is not busy. It is appropriate for some uses, but you may prefer more immediate
refresh offered by DebugView.

• Zooming via Scroll bar improved. Now it works with wider range of zoom factors and also does not disable scoll bar when all quotes are visible. As accessibility feature, you can temporarily DISABLE zoom via scroll bar by pressing and holding down CTRL key.
• Added extra protection against going out of drawing array bounds in GetNextDrawing
• when broker.master file was loaded, some symbol temporary data were read from non-zeroed memory, fixed now
• fixed display glitch that occurred on some bars when logarithmic scale was used and chart was drawn using compression (2x more bars than pixels)
• When application is closed in Minimized state, the x,y co-ords of main window are not stored
• styleHistogram chart when drawn in compressed mode could fail to display some negative spikes (below base level) in 5.16. Fixed.
• inQuarterly and inYearly higlighted in AFL editor now
• SetBarFillColor could not make candle with same body and outline color. Fixed now.
• Fixed handling Null in styleArea chart (Null was ignored in 5.16)
• 32bit AmiBroker is now compiled with LARGEADDRESSAWARE flag, that allows it to use 3GB on 32 bit Windows versions that have /3GB boot flag enabled and 4GB on 64 bit Win
• First sorted column is drawn with darker color now (as in Windows explorer)
• Layouts are displayed in alphabetical order now (previously they were sorted only if files were stored on NTFS partition)
• When from-to range of backtest was small, AB sometimes allocated too large cache for portfolio backtest than necessary. Now it is fixed and should provide speed up for short range backtests.

CHANGES FOR VERSION 5.16.0 (as compared to 5.15.0)

• If in-memory cache was too small, it could happen that Walk-Forward kept old equity values in ~~~BESTEQUITY. Fixed now.
• AFL: Faster LR. Added constant-period version of linear regression calc - reduces complexitiy from O(N^2) to O(N)

Constant-period LinearReg, LinRegSlope, LinRegIntercept, TSF and StdErr functions execute now order(s) of magnitude faster.
• AFL: new GetChartBkColor function

Returns RGB color value of chart background. Sample code:

SetChartBkColor( ParamColor("Color", ColorRGB( 255, 255, 255 ) ) );

rgb = GetChartBkColor();

red = ( rgb & 255 );
green = floor( (rgb/256) & 255 );
blue = floor( rgb/(256*256) );

Title="R="+ red + " G=" + green + " B=" + blue;

• Candlestick style switches back to bar chart when number of bars displayed is twice the number of screen pixels
• eSignal plugin 1.9.0 (fixes to problem with RT update of certain foreign future markets such as NSF)
• IBController 1.2.0
• following TWS API changes ignoreRth and rthOnly flags are removed and replaced with single flag: outsideRTH
• IBc now allows to define which error codes should be ignored using File->Error code ignore list
• upgraded to use latest TWS API 9.41 (tested with latest TWS 885.7, requires at least 879)
• Improved speed of Day(), Month(), Year(), DaysSince1900(), DayOfWeek(), DayOfYear() functions on intraday data (upto 20x faster)
• Improved speed of DayOfWeek(), DayOfYear(), DaysSince1900() on EOD data (upto 2x faster)
• Optimized chart drawing for large number of bars, upto 10x faster when more than 70000 bars are visible on screen

The drawing algorithm switches to optimized drawing mode when just one line draw per horizontal pixel is performed if there are 2x or more bars than screen pixels.
• Say() function has now ability to queue speak requests

Say( "Text", purge = True );

when purge is set to True (the default) - any call to Say() purges all previous speak requests (queued or in-progress) and speaks
specified text immediatelly.

when purge is set to False - speak request is queued and will be spoken right after previous requests are done.

Also now Say() function returns the NUMERIC value that indicates how many speak requests are pending
0 - ERROR - speech engine not installed or not working properly
1 - currently requested text is spoken now (queue was empty)
2 or more - queue was not empty and previous request(s) will be completed prior to speaking currently specified text

CHANGES FOR VERSION 5.15.0 (as compared to 5.14.0)

• SetForeign called multiple times with "tradeprices" parameter set to True freed memory only partially. Now fixed.
• Equity() function does not cause exception when running backtest with QuickAFL enabled
• Equity() function does not require all past bars anymore when used in AA
• OptimizerSetEngine("") in some circumstances selected random plugin. Fixed now.
• When user has aborted optimization during in-sample step, the previously used opt params were not freed. Fixed.
• Implemented command line parameter that allows to specify the database to load at startup. /database "the path to the database here"
• In some places C-runtime mktime() was used leading to problems with dates prior to 1970. Fixed now.
• During custom backtester phase the ~~~EQUITY ticker is protected from flushing out of cache (it could only happen if using OLE to access quotes inside CB proc)
• Now ~~~BESTEQUITY, ~~~ISEQUITY, ~~~OSEQUITY are not flushed out from the cache during WF even if cache is small (ensures no missing parts in IS/OOS chart)
• Single-symbol optimization now also uses QuickAFL (when enabled). Requirements for the first symbol are calculated in setup phase. To get "most safe" requirement estimation, the setup phase uses maximum values of opt params.

CHANGES FOR VERSION 5.14.0 (as compared to 5.13.0)

• added support for Quarterly and Yearly intervals in all parts of the program
• new menu items under View interval
• new AFL constants inQuarterly, inYearly
• Yearly and Quarterly charts compression
• updated TimeFrame functions
• Changes to drawing made in v5.13 caused improper drawing lines located PAST the last available quote (trendlines and pitchforks) when timestamping method was "START TIME of interval". This is fixed now.

• Fixed AddSummaryRows so 'onlycols' parameter default (zero) is applied properly

• Implemeted "Select all" via Ctrl-A keyboard shortcut for all list (result list in AA for example)

• Mouse cursor shape (moving/sizing) reflects the selected study priority when more than one study exists under mouse position

• new multiple Volume At Price charts at user-defined points via new PlotVolumeOverlayA function

PlotVAPOverlayA( segments, lines = 300, width = 80, color = colorLightGrey, vapstyle = 4);

segmens - is an array which holds 0 and 1 (False/True) values, where 1 indicates starting/ending point of each VAP segment

AmiBroker will draw as many segments as there are '1' in the array. Note that minimum segment length is 2, so if entire array is filled with 1-s only,
it won't draw anything. In other words, there must be zeros (at least one) between 1's.

Simplest example:

Plot(C, "Close", colorBlack, styleCandle ); segments = IIf( Interval() < inDaily, Day(), Month() ); // draw daily or monthly VAP segments depending on display interval segments = segments != Ref( segments , -1 ); PlotVAPOverlayA( segments );

More complex example:
_SECTION_BEGIN("Price"); SetChartOptions(0,chartShowArrows|chartShowDates); _N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) )); Plot( C, "Close", ParamColor("Color", colorBlack ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); _SECTION_END(); _SECTION_BEGIN("VAP"); segments = IIf( Interval() < inDaily, Day(), Month() ); segments = segments != Ref( segments , -1 ); PlotVAPOverlayA( segments , Param("Lines", 300, 100, 1000, 1 ), Param("Width", 80, 1, 100, 1 ), ParamColor("Color", colorGold ), ParamToggle("Side", "Left|Right" ) | 2 * ParamToggle("Style", "Fill|Lines", 0) | 4*ParamToggle("Z-order", "On top|Behind", 1 ) ); Plot(segments, "", colorLightGrey, styleHistogram | styleOwnScale ); _SECTION_END();

• QuickAFL can now be used in Automatic Analysis (Settings: General: "Use QuickAFL" - check this box) - this can speed up explorations, scans and backtests by factor of 2+ if range is less than "all quotations"

More on QuickAFL feature here: http://www.amibroker.com/kb/2008/07/03/quickafl/

• Range Bars compression now uses TickSize as "1R step". TickSize defined in the Symbol Information, if its value is zero, then 1R would be equivalent to 0.01 movement (for backward compat)

• selecting date in multiple linked charts is now faster because redraw is not made when selected line in higher compressed interval remains in place

• selector line in linked charts works OK now, regardless of selected time compression timestamping method

• SetBarsRequired accepts now values -2 in special meaning: reference ALL bars

So
SetBarsRequired( -2, -2 ); // require ALL past and future bars - this turns OFF quickAFL

(Note that in pre 5.14 versions, such combination does NOTHING, and with those versions one needed
to write SetBarsRequired( 1000000, 1000000 ) to achieve the same effect)

For readability sbrNoChange (-1) and sbrAll (-2) constants were added so you can write:

SetBarsRequired( sbrAll, sbrAll );

• Sometimes progress bar did not show the name of optimization engine used. Now it is fixed

• Status("ActionEx") provides more codes than Status("action") to detect special executions states

Status("ActionEx") provides more detailed information about action that triggered AFL execution. Note that 5 first codes are the same as Status("action") but scope is limited to 'core'
meaning (see notes below).
Possible values
1 - actionIndicator - when indicator is being repainted
2 - actionCommentary (NOTE: commentary only, not interpretaion nor tooltip)
3 - actionScan - when AA Scan is performed
4 - actionExplore - when AA exploration is performed
5 - actionBacktest (NOTE backtest only, no optimization)
8-9 - reserved for future use
10 - actionExAAShowArrows - when AA "Show arrows" command is used
11 - actionExAAParameters - when AA "Parameters" dialog is displayed/updated
12 - actionExEditVerifyFormula - when AFL editor verifies syntax
13 - actionExOptimizeSetup - when Optimize() parameters are read (to setup optimization engine)
14 - actionExOptimizeBacktest - when Backtest is performed as a part of optimization process
15- actionExOptimizePortfolio - when portfolio-backtest phase (CUSTOM backtester) is performed as a part of optimization process
16 - actionExTooltip - when tooltip for given chart is being displayed/updated
17 - actionExInterpret - when the Interpretation window is being updated
18 - actionExInit - when AA needs to initialize QuickAFL bars required information and/or formula contains functions changing general AA options

NOTE: for backward compatiblity with all formulas you have written already, the codes for Status("action") did NOT change .

• Streaming chart update could stall if trend line handle was clicked in attempt to resize and released in the very same position (without moving the mouse). Now it is fixed.

• TimeFrameMode() now supports mode == 4 - which expresses RANGE bars in TickSize units (as opposed to mode 3 that uses dollars for backward compatiblity)

• when display chart timing option is turned on and RT stream is active the application STATUS BAR now displays TOTAL time for all charts, it should be BELOW 1 second for RT trading

CHANGES FOR VERSION 5.13.0 (as compared to 5.12.2)

• Main app window maximize state on 2nd monitor is saved OK now.
• Trendlines drawn in smaller interval (such as 1-minute), was moved one bar in higher interval (such as 5 minute) if compressed intraday timestamps ware set to START time of interval or FIRST tick
• The left-hand handle moved to the next bar when it was off-screen and right-hand handle was adjusted by the user. Now it is fixed. (FC#890)
• When drawing is clicked without moving the mouse, the co-ordinates stay untouched ( snap is not activated until you move the mouse)

AddSummaryRows( flags, format = 0, onlycols = 0, ...)

the flags parameter can be combination of the following

format - defines the numeric formating in WriteVal style so 1.2 for example means 2 decimal digits.
If default value of zero is used (or parameter not specified) the default formatting of "maximum precision"
is used - upto 15 digits are printed

onlycols - defines for which columns you want to display summary row values.
Note that if you do not specify any columns - ALL will be printed.

If you are using onlycols, you can define upto 10 columns, columns, like
in SetSortColumns are numbered starting from 1. For example:

AddSummaryRows( 1, 1.2, 3, 5, 7, 9 );

Display sum for columns: 3, 5, 7, and 9.

Generally you should call this funciton only once, using combination of flags desired.
But it is possible to call AddSummaryRows multiple times and the result will be "accumulation" (i.e. bitwise OR)
in case of "flag" parameter. format and onlycols are always overwritten by last call.

Example:

Filter=1;
AddSummaryRows( 31, 1.2 ); // add Total, Average, Min, Max, and Count rows (1+2+4+8+16)=31 - with two decimal places
summary rows are added at the top of the list

• Handles from selected study line are respected (i.e when study is already selected, and multiple studies exists under "click" point, the selection does not change) (FC#726)
• Magnet mode can be asynchronously (temporarily) toggled by holding SHIFT key while drawing. Toggle means that if you are in magnet mode and hold down shift it will turn it off and vice versa
• Magnet mode implemented for horizontal price levels and working correctly now (stay horizontal) (FC#728)
• During optimization Progress bar shows engine ID, opt. target, best value, step and best combination of parameters found upto "now". These figures are refreshed every second.
• Optimization (in non-WF mode) results are sorted by optimization target column (too)
• New optimization engine added: CMAE (Covariance Matrix Adaptation Evolutionary Strategy) optimizer plug-in

CMA-ES (Covariance Matrix Adaptation Evolutionary Strategy) is state-of-the-art non-exhaustive optimizer.
For scientific background see:
http://www.bionik.tu-berlin.de/user/niko/cmaesintro.html
According to scientific benchmarks outperforms nine other, most popular evolutionary strategies (like PSO, Genetic and Differential evolution).
http://www.bionik.tu-berlin.de/user/niko/cec2005.html

The CMAE.DLL plugin implements "Global" variant of search with several restarts with increasing population size
CMAE.DLL comes with FULL SOURCE CODE (inside "ADK" folder)

By default number of runs (or restarts) is set to 5.
It is advised to leave the default number of restarts.
You may vary it using OptimizerSetOption("Runs", N ) call, where N should be in range 1..10.
Specifying more than 10 runs is not recommended, although possible.
Note that each run uses TWICE the size of population of previous run so it grows exponentially.
Therefore with 10 runs you end up with population 2^10 greater (1024 times) than the first run.

There is another parameter "MaxEval". The default value is ZERO which means that plugin will automatically calculate MaxEval required. It is advised to NOT to define MaxEval by yourself as default works fine.

The algorithm is smart enough to minimize the number of evaluations required and it converges VERY fast to solution point, so usually it finds solutions way faster than other strategies.

It is normal that the plugin will skip some evaluations steps, if it detects that solution was found, therefore you should not be surprised that optimization progress bar may move very fast at some points. The plugin also has ability to increase number of steps over initially estimated value if it is needed to find the solution. Due to its adaptive nature, the "estimated time left" and/or "number of steps" displayed by the progress dialog is only "best guess at the time" and may vary during optimization course.

To use CMA-ES optimizer, you just need to add one line to your code:

OptimizerSetEngine("cmae");

This will run the optimization with default settings which are fine for most cases.

It should be noted, as it is the case with many continouos-space search algorithms, that decreasing "step" parameter in Optimize() funciton calls does not significantly affect optimization times. The only thing that matters is the problem "dimension", i.e. the number of different parameters (number of optimize function calls). The number of "steps" per parameter can be set without affecting the optimization time, so use the finest resolution you want. In theory the algorithm should be able to find solution in at most 900*(N+3)*(N+3) backtests where "N" is the dimension. In practice it converges a LOT faster. For example the solution in 3 (N=3) dimensional parameter space (say 100*100*100 = 1 million exhaustive steps) can be found in as few as 500-900 CMA-ES steps.

Tribes is adaptive, parameter-less version of PSO (particle swarm optimization) non-exhaustive optimizer.
For scientific background see:
http://www.particleswarm.info/Tribes_2006_Cooren.pdf

In theory it should perform better than regular PSO, because it can automatically adjust the swarm sizes and algorithm strategy to the problem being solved.

Practice shows that its performance is quite similar to PSO.

To find solutions significantly faster I can recommend CMA-ES (Covariance Matrix Adaptation Evolutionary Strategy) algorithm instead.

The Tribes.DLL plugin implements "Tribes-D" (i.e. dimensionless) variant. Based on http://clerc.maurice.free.fr/pso/Tribes/TRIBES-D.zip by Maurice Clerc. Original source codes used with permission from the author

Tribes.DLL comes with FULL SOURCE CODE (inside "ADK" folder)

Supported parameters:
" MaxEval" - maximum number of evaluations (backtests) per run (default = 1000).
OptimizerSetOption("MaxEval", 1000 );
You should increase the number of evaluations with increasing number of dimensions (number of optimization params).
The default 1000 is good for 2 or maximum 3 dimensions.

"Runs" - number of runs (restarts). (default = 5 )
You can leave the number of runs at default value of 5.

By default number of runs (or restarts) is set to 5.

To use Tribes optimizer, you just need to add one line to your code:

OptimizerSetEngine("trib");

OptimizerSetOption("MaxEval", 5000 ); // 5000 evaluations max

CHANGES FOR VERSION 5.12.2 (as compared to 5.12.0)

• In 5.12.0 BETA the walk-forward test was stopping after first in-sample cycle. Now it is fixed.
• AddSummaryRows total did not include the very first item. Fixed.

CHANGES FOR VERSION 5.12.0 (as compared to 5.11.1)

• ADK: A new interface for external optimization engines, see optimizer.html
• Added two example non-exhaustive optimizers: Standard Particle Swarm Optimizer (spso), and Monte Carlo (random pick) optimizer( moca)

Note that BOTH optimizers are provided for demonstration purposes.
Particularly Monte Carlo optimizer is meant as a "the most trivial and simple" or even "dumb" example of optimizer DLL coding.
It works by randomly picking parameter combinations without ANY additional logic. The results are thus random
and most probably sub-optimum.

On the other hand Standard Particle Swarm Optimizer is based on SPSO2007 code that is supposed to produce
good results provided that correct parameters (i.e. Runs, MaxEval) are provided for particular problem.
Picking correct options for the PSO optimizer can be tricky therefore results may significantly vary from case to case.

The source codes for both optimizers are OPEN and provided as illustration how to implement optimizer engines using
" simple" and "advanced" methods as described in optimizers.html file. You can find full source codes inside "ADK" subfolder.

In the future, I will provide more robust non-exhaustive optimizers using various methods.

Example code for Standard Particle Swarm Optimizer:
(finding optimum value in 1000 tests within search space of 10000 combinations)

OptimizerSetEngine("spso");
OptimizerSetOption("Runs", 1 );
OptimizerSetOption("MaxEval", 1000 );

sl = Optimize("s", 26, 1, 100, 1 );
fa = Optimize("f", 12, 1, 100, 1 );

Buy = Cross( MACD( fa, sl ), 0 );
Sell = Cross( 0, MACD( fa, sl ) );

Example Code for Monte Carlo optimizer:
(finding sub-optimum value in 1000 test within search space of 10000 combinations)

OptimizerSetEngine("moca");
OptimizerSetOption("NumSteps", 1000 );

sl = Optimize("s", 26, 1, 100, 1 );
fa = Optimize("f", 12, 1, 100, 1 );

Buy = Cross( MACD( fa, sl ), 0 );
Sell = Cross( 0, MACD( fa, sl ) );

• Increased limit of optimization parameters to 100
• AFL: new OptimizerSetOption("name", value ) function

The function set additional parameters for external optimization engine. The parameters are engine-dependent.
For example SPSO optimizer supports "Runs" (number of runs) and "MaxEval" (maximum evaluations (tests)per single run) parameters. Monte Carlo optimizer supports "NumSteps" (number of steps) parameter.
• AFL: new OptimizerSetEngine("name") function

The function selects external optimization engine defined by name. For demonstration two engines are provided: Standard Particle Swarm Optimizer ("spso") and Monte Carlo (random pick) optimizer ("moca")

Example:
OptimizerSetEngine("moca");
• ADK: new example C++ source codes: PSOSample, MOCASample

the flag parameter can be combination of the following

You can call AddSummaryRows multiple times and the result will be "accumulation" (i.e. bitwise OR)

Example:

Filter=1;
AddSummaryRows( 31 ); // add Total, Average, Min, Max, and Count rows (1+2+4+8+16)=31

summary rows are added at the top of the list

CHANGES FOR VERSION 5.11.1 (as compared to 5.11.0)

• Fixed problem with Walk Forward picking sometimes not the best parameter when thousand separator was used and metric values were greater than 1000

CHANGES FOR VERSION 5.11.0 (as compared to 5.10.1)

• Backtester: Implemented SeparateLongShortRank

To enable separate long/short ranking use:
SetOption("SeparateLongShortRank", True );

When separate long/short ranking is enabled, the backtester maintains TWO separate "top-ranked" signal lists, one
for long signals and one for short signals. This ensures that long and short candidates are independently even if position score
is not symetrical (for example when long candidates have very high positive scores while short candidates have only fractional negative scores).
That contrasts with the default mode where only absolute value of position score matters, therefore one side (long/short) may completely dominate ranking if score values are asymetrical.

When SeparateLongShortRank is enabled, in the second phase of backtest, two separate ranking lists are interleaved to form final signal list by
first taking top ranked long, then top ranked short, then 2nd top ranked long, then 2nd top ranked short, then 3rd top ranked long
and 3rd top ranked short, and so on... (as long as signals exist in BOTH long/short lists, if there is no more signals of given kind, then
remaining signals from either long or short lists are appended)

For example:

As you can see Short signals get interleaved between Long signals even though their absolute values of scores are smaller than corresponding scores of long signals. Also there were only 2 short signals for that particular bar so, the rest of the list shows long signals in order of position score

Although this feature can be used independently, it is intended to be used in combination with MaxOpenLong and MaxOpenShort options.

• Backtester: MaxOpenLong/MaxOpenShort implemented

MaxOpenLong - limits the number of LONG positions that can be open simultaneously
MaxOpenShort - limits the number of SHORT positions that can be open simultaneously

Example:
SetOption("MaxOpenPositions", 15 );
SetOption("MaxOpenLong", 11 );
SetOption("MaxOpenShort", 7 );

The value of ZERO (default) means NO LIMIT. If both MaxOpenLong and MaxOpenShort are set to zero (
or not defined at all) the backtester works old way - there is only global limit active (MaxOpenPositions) regardless of type of trade.

Note that these limits are independent from global limit (MaxOpenPositions).
This means that MaxOpenLong + MaxOpenShort may or may not be equal to MaxOpenPositions.

If MaxOpenLong + MaxOpenShort is greater than MaxOpenPositions
then total number of positions allowed will not exceed MaxOpenPositions, and individual long/short limits will apply too.
For example if your system MaxOpenLong is set to 7 and maxOpenShort is set to 7 and MaxOpenPositions is set to 10
and your system generated 20 signals: 9 long (highest ranked) and 11 short, it will open 7 long and 3 shorts.

If MaxOpenLong + MaxOpenShort is smaller than MaxOpenPositions (but greater than zero), the system won't be able to
open more than (MaxOpenLong+MaxOpenShort).

Please also note that MaxOpenLong and MaxOpenShort only cap the number of open positions of given type (long/short).
They do NOT affect the way ranking is made. I.e. by default ranking is performed using ABSOLUTE value of positionscore.

If your position score is NOT symetrical, this may mean that you are not getting desired top-ranked signals from one side.
Therefore, to fully utilise MaxOpenLong and MaxOpenShort in rotational balanced ("market neutral") long/short systems
it is desired to perform SEPARATE ranking for long signals and short signals.
To enable separate long/short ranking use:
SetOption("SeparateLongShortRank", True );

• Added ability to running Walk forward test from OLE, using Optimize(3)

Analysis.Optimize( mode )
when mode == 3 it runs walk forward test

AB = new ActiveXObject("Broker.Application");
AA = AB.Analysis;
AA.Optimize(3);

• AFL: DaysSince1900() function

It returns the number of days that passed since January 1st, 1900, counting from 1. January 1, 1900 is serial number 1, and January 1, 2008 is serial number 39448 because it is 39,448 days after January 1, 1900. Technically is equal to Windows OLEDATE and Excel's DATEVALUE function.

The function can be used for calculations that involve calendar days as opposed to trading days and replaces previously proposed AFL solution
http://www.amibroker.com/kb/2007/03/15/calendar-day-index/

Now RefDays can be implemeted as follows:

 SetBarsRequired( 365, 0 ); function RefDays( Array, Days ) {   td = DaysSince1900();   result = Null;   if( Days < 0 )   {      for( i = BarCount -1; i >= -Days; i = i - 1 )      {        backday = td[ i ] + Days; // Days is negative        for( j = -Days/2; j < i; j++ )        {           if( td[ i - j ] <= backday )            {              result[ i ] = Array[ i - j ];              break;            }        }      }   }   return result; } Plot( C, "C", colorRed ); Plot( Ref( C, -252 ), "Close 252 bars back", colorBlue ); Plot( RefDays( C, -365 ), "Close 365 days back", colorGreen ); 

CHANGES FOR VERSION 5.10.2 (as compared to 5.10.1)

• Fixed problem with Walk Forward picking sometimes not the best parameter when thousand separator was used and metric values were greater than 1000

CHANGES FOR VERSION 5.10.1 (as compared to 5.10.0)

• Fixed crash @004AB5A1 (when sector ID was invalid > 64)
• Fixed bug AFL editor Undo @004B2324
• Fixed bug @004662AD (crash when doing Code Check and Profile while AA running in background)

CHANGES FOR VERSION 5.10.0 (as compared to 5.09.0)

• Small improvement in axis font positioning - based on TEXTMETRIC
• Removed 1-pixel rendering overlap in multi-colored chart titles when ClearType was enabled
• Hi-Res (256x256) alpha Vista icon
• Quote array now uses HeapRealloc instead of HeapAlloc/HeapFree combination
• Fixed rare crash @433F58
• Fixed account manager updating cash after exiting short trade
• Web Browser window does not flicker anymore when resizing

CHANGES FOR VERSION 5.09.0 (as compared to 5.08.0)

• MDI Tab order is now saved in the layout
• Added interface to BugslayerUtil.dll for optional call stack / symbol dump report in crash recovery window
Now in the bottom of the crash report there is a detailed call stack and CPU register state. This should allow quicker/easier fixes of any crashes
• New fields in Status() function: pxchart*

Status("pxchartleft") - returns x-coordinate of top-left corner of chart area
Status("pxcharttop") - returns y-coordinate of top-left corner of chart area
Status("pxchartright") - returns x-coordinate of bottom-right corner of chart area
Status("pxchartbottom") - returns y-coordinate of bottom-right corner of chart area
Status("pxchartwidth") - returns width chart area (right-left)
Status("pxchartheight") - returns width chart area (bottom-top)
Chart co-ordinates are useful because they automatically take into account selected axis font size, whenever date axis is on or off
and other settings (New Look chart style)
All co-ordinates are in screen pixels. Note that top, left coordinates may not be zero as chart rectangle is smaller than underlying window because there is an extra space (padding) around chart.

// Test code:
Title = StrFormat("left=%g, top=%g, right=%g, bottom=%g, width=%g, height=%g", left=Status("pxchartleft"), top=Status("pxcharttop"), right=Status("pxchartright"), bottom=Status("pxchartbottom"), Status("pxchartwidth"), Status("pxchartheight") ); GfxSetOverlayMode(1); GfxRectangle(Left,top, right, bottom);

============ Overlay sample ================
_SECTION_BEGIN("GfxOverlaySampleNew"); function GetVisibleBarCount() {  lvb = Status("lastvisiblebar");  fvb = Status("firstvisiblebar");  return Min( Lvb - fvb, BarCount - fvb ); } function GfxConvertBarToPixelX( bar ) {  lvb = Status("lastvisiblebar");  fvb = Status("firstvisiblebar");  pxchartleft = Status("pxchartleft");  pxchartwidth = Status("pxchartwidth");  return pxchartleft + bar  * pxchartwidth / ( Lvb - fvb + 1 ); } function GfxConvertValueToPixelY( Value ) {  local Miny, Maxy, pxchartbottom, pxchartheight;  Miny = Status("axisminy");  Maxy = Status("axismaxy");  pxchartbottom = Status("pxchartbottom");  pxchartheight = Status("pxchartheight");  return pxchartbottom - floor( 0.5 + ( Value - Miny ) * pxchartheight/ ( Maxy - Miny ) ); } Plot(C, "Price", colorBlack, styleHistogram ); GfxSetOverlayMode(0); GfxSelectSolidBrush( colorRed ); GfxSelectPen( colorRed ); AllVisibleBars = GetVisibleBarCount(); fvb = Status("firstvisiblebar"); for( i = 0; i < AllVisibleBars ; i++ ) {    x = GfxConvertBarToPixelX( i );    y = GfxConvertValueToPixelY( C[ i + fvb ] );   GfxRectangle( x-1, y-1, x + 2, y+1 ); } //SetChartBkGradientFill( ColorRGB(200,200,200), ColorRGB( 255,255,255) ); _SECTION_END();

• OLE: Name property is now writable, allowing switchin currently selected symbol for the document

Example (JScript):
AB = new ActiveXObject("Broker.Application");
AB.ActiveDocument.Name = "MSFT"; // change the symbol for current document to "MSFT"

CHANGES FOR VERSION 5.08.0 (as compared to 5.07.0)

• Walk-Forward: "Easy" mode divided into two submodes: EOD and Intraday
Easy EOD mode assumes that you are using EOD data for walk-forward.
Easy Intraday mode assumes that you are using Intraday data for walk-forward
The difference is that in EOD mode the END date of previous period and START date of next period are the same - thus avoiding gap
between periods. Intraday mode set START date of the next period as NEXT DAY after END of previous period. That guarantees
that boundary day is not counted twice when testing on intraday data.
• SetOption("GenerateReport", value )
New option added to SetOption call
" GenerateReport" - 0/1/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 supress 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
• Total chart redraw time is calculated properly if multiple documents and charts are open that results in smoother performance and no update lockup
• When custom color palette is changed, any old RGB color that is not present in changed palette is matched to closest "standard" color
• Bugfix: when crosshair was enabled and moved OUTSIDE chart windows, then CPU usage was high. Now it is fixed
• Walk-Forward: when starting date is the last day of the month and step is n-month then it is treated as special case
AmiBroker now detects that start day is the last day of the month and moves the window to the last day of NEXT month, even if it is shorter.
That addresses the problem when one starts with January 31 and wants to step by one month - > since there is NO February 31, previous version
moved to March 3rd. Now it detects that it is last day of the month and moves to Feb 28 (or 29). Then in next step it will move to March 31.

CHANGES FOR VERSION 5.07.0 (as compared to 5.06.0)

• a bugfix in 5.06 affected Foreign() function so it did not load the data on very first access - now fixed. This fixes also huge drawdown numbers that occurred on open positions at the end of trade list if cache size was small
• AFL: SetChartOptions has now 2 more parameters that allow to set custom scaling
SetChartOptions( Mode = 0, Flags = 0, gridFlags = chartGridMiddle, ymin = 0, ymax = 0 )
new ymin, ymax 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. Note that 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.
• bugfix: in 5.06.0 deleting the very first symbol raised exception, now it is fixed
• bugfix: rarely when trade profits gone to absurd levels (for example if user switched off price checking and used zero as entry price), AmiBroker would crash when generating profit distribution chart, now it is fixed
• Crosshair moves way faster and flicker is practically eliminated
• Crosshair state is global now and saved between sessions
• Crosshair works now in floating windows and in inactive windows too
• IS, OOS, BEST equity tickers are now put into group 253 and market 253 (composites)

CHANGES FOR VERSION 5.06.0 (as compared to 5.05.1)

• Walk Forward: now you can select "trading days" instead of calendar days as step unit. Currently it is using simplified method: Mon-Fri as a trading days
• Walk Forward settings: fixed lockup (due to infinite loop) when step was set to zero, also added other checks for invalid entries
• RT Quote window: now symbols can be re-arranged by drag-and-drop (simply click on the symbol, hold and drag to re-arrange order)
• RT Quote window: faster refreshes and multi-step color fading
• RT Quote window: added ability to type-in multiple symbols directly (instead of selecting one by one or via existing watch list)
• RT Quote window: added ability to insert EMPTY line (to separate symbol groups)
• Preferences / Currencies: now you can define upto 20 currencies for multiple-currency backtesting
• New FindSignal function in Backtester object (custom backtester procedure) allowing fast lookups for signals matching given symbol
bo = GetBacktesterObject();
bo.FindSignal( bar, symbol, type )

where
bar is a bar number
symbol is ticker symbol
type represents type of signal to find: 0 - both entries and exits, 1 - only entries, 2 - only exits

The function finds for first matching signal that has fPrice != -1 (different than -1). If 0 is used as type, and entry and exit is on the same bar then entry signal will be returned. Note: fPrice = -1 is a special marker meaning that given signal should be ignored.

• Internal symbol pointers stay the same when new symbols are added or deleted. This addresses exceptions when using AddToComposite during backtests among other things
This fixes: FC#1101, exceptions when using AddToComposite inside CBT and exceptions occuring sometimes with COM when adding / removing symbols
• Floating panes are now "sticky" that makes it easier to arrange the workspace
• Charts: ability to hide vertical quote marker
The control over vertical quote marker is given now via
Parameter dialog -> Axes & Grid -> Vert. quote marker: Show/Hide

And programmatically via SetChartOptions function:
SetChartOptions( 2, chartHideQuoteMarker );

• Bugfix: when "pad and align" was used in AA and reference symbol did not have all trading days, the data used for very first symbol in the watch list under test could have been unaligned for the very first AA run, subsequent runs were OK)
• Alert Output column sizes / layout are now preserved between sessions
• Added two new backtest modes: backtestRegularRaw2 and backtestRegularRaw2Multi that do not remove excess EXIT signals
The common thing between Raw and Raw2 modes is that they both do NOT remove excess ENTRY signals.
The difference is that Raw modes remove excess EXIT signals, while Raw2 do NOT.
In Raw2 modes all exit signals (even redundant ones) are passed
to second phase of backtest just in case that you want implement strategy that skips first exit. Lets suppose that you want to exit on some condition from first phase but only in certain hours or after certain numbers of bars in trade or only when portfolio equity condition is met. Now you can do that in raw2 modes.
Note that Raw2 modes can get significantly slower when you are using custom backtester code that iterates thru signals as there can be zillions of exit signals in the lists even for symbols that never generated any entry signals, therefore it is advised to use it only when absolutely necessary. Raw2 modes are also the most memory consuming.

Note also that if you run the system WITHOUT custom backtest procedure there should be no difference between Raw and Raw2 modes (other than speed & memory usage) as first matching exit signal is what is used by default.

• 3D chart viewer: process priority is now set to IDLE
• 3D chart viewer: animation is now smoother (upto 100fps vs 25fps)

CHANGES FOR VERSION 5.05.1 (as compared to 5.05.0)

• Walk Forward AA Settings: added error message when start date > end date
• Walk Forward AA Settings: added "preview" list - showing all IS and OOS segments with dates

CHANGES FOR VERSION 5.05.0 (as compared to 5.04.2)

• Walk Forward: "Easy" mode in the settings implemented - it sets "out-of-sample" parameters automatically based on in-sample settings
• GetCursorMouseButtons new flag = 8 - means that current chart just received mouse click

///////////////////////////////////////////////// // Low-level graphic + Interactive GUI control sample // This example shows: //  1. how to draw "buttons" //  2. how to handle mouse clicks //  3. how to implement event call-backs /////////////////////////////////////////////////// Version( 5.04 ); // requires 5.04 or higher //////////////////////////////////////////////////// // Part 1: DRAWING TABLE OF BUTTONS ////////////////////////////////////////////////// GfxSetOverlayMode( 2 ); // formatted text output sample via low-level gfx functions CellHeight = 20; CellWidth = 100; GfxSelectFont( "Tahoma", CellHeight/2 ); GfxSetBkMode( 1 ); function PrintInCell( string, row, Col ) { GfxDrawText( string, Col * CellWidth, row * CellHeight, (Col + 1 ) * CellWidth, (row + 1 ) * CellHeight, 0 ); } GfxSelectPen( colorBlue ); for( i = 0; i < 10 && i < BarCount; i++ ) { for( k = 0; k < 5; k++ ) {    PrintInCell( "Button " + i + "," + k, i, k ); } GfxMoveTo( 0, i * CellHeight ); GfxLineTo( 5 * CellWidth, i * CellHeight ); } GfxMoveTo( 0, i * CellHeight ); GfxLineTo( 5 * CellWidth, i * CellHeight ); for( Col = 1; Col < 6; Col++ ) { GfxMoveTo( Col * CellWidth, 0); GfxLineTo( Col * CellWidth, 10 * CellHeight ); } ///////////////////////////////////////////////////////// // Part 2: MOUSE BUTTON CALL BACKS ////////////////////////////////////////////////////////// Title=""; function DrawButton( px, py, Clr1, Clr2, text ) {      Col = floor( px / CellWidth );      Row = floor( py / CellHeight );        GfxGradientRect( Col * CellWidth, row * CellHeight, (Col + 1 ) * CellWidth, (row + 1 ) * CellHeight,                    Clr1, Clr2 );      PrintInCell( text + " " + row + "," + Col, row, Col ); } function OnLMouseButton(x, y, px, py) {    _TRACE("LButton x = " + DateTimeToStr( x ) + " y = " + y );    DrawButton( px, py, ColorHSB( 50, 255, 255 ), ColorHSB( 90, 255, 255 ), "just clicked" ); } function OnRMouseButton(x, y, px, py) {    _TRACE("RButton x = " + DateTimeToStr( x ) + " y = " + y ); } function OnMMouseButton(x, y, px, py) {    _TRACE("MButton x = " + DateTimeToStr( x ) + " y = " + y ); } function OnHoverMouse(x, y, px, py) {    _TRACE("LButton x = " + DateTimeToStr( x ) + " y = " + y );      DrawButton( px, py, ColorRGB( 230, 230, 230 ), ColorRGB( 255, 255, 255 ), "mouse over" ); } function OnLButtonIsDown(x, y, px, py) {    _TRACE("LButton x = " + DateTimeToStr( x ) + " y = " + y );      DrawButton( px, py, ColorHSB( 190, 255, 255 ), ColorHSB( 210, 255, 255 ), "down" ); } ///////////////////////////////////////////////////////// // Part 3: GENERAL PURPOSE EVENT HANDLER (reusable! - may be put into "include" file) //////////////////////////////////////////////////////// function EventHandler() { local b, x, y, px, py; b = GetCursorMouseButtons(); // retrieve co-ordinates in date/value units x = GetCursorXPosition(0); y = GetCursorYPosition(0); // retrieve co-ordinates in pixel units px = GetCursorXPosition(1); py = GetCursorYPosition(1); if( b & 8 ) // flag = 8 is set when window just received mouse click {    // not-null means clicked in THIS (current) window    if( b & 1 ) OnLMouseButton( x, y, px, py );    if( b & 2 ) OnRMouseButton( x, y, px, py );    if( b & 4 ) OnMMouseButton( x, y, px, py ); } else {   if( b == 0 ) OnHoverMouse( x, y, px, py ); // no button pressed   if( b == 1 ) OnLButtonIsDown( x, y, px, py ); // button pressed } } EventHandler(); RequestTimedRefresh( 1 ); 
• GetCursorXPosition/GetCursorYPosition return non-null values when mouse is over the current chart regardless if it was clicked or not
• BUGFIX: trend line sometimes moved to the right edge when drawing/moving them while two charts were opened in different periods
• Selector line is not drawn (does not blink) when GfxOverlayMode is set to 2
• Walk Forward document can now be closed and/or hidden during WF (it is not re-opened constantly)

CHANGES FOR VERSION 5.04.2 (as compared to 5.04.1)

• New log scale (5.04.1) was not working nicely for small dynamic range charts - chart looked compressed. Fixed now.
• Chart Periodicity on MDI tab is now updated when switching
• Trendlines work fine with thick and dotted styles again (broken in 5.04)
• AFL: GetCursorXPosition/GetCursorYPosition functions changed
1. The functions now by default return NULL (empty value) if mouse is OUTSIDE the current window

2. New "mode" parameter controls what values are returned

GetCursorXPosition( mode = 0 )
GetCursorYPosition( mode = 0 )

mode = -1 - (old compatibility mode) - x - value gives X-coordinate in DateTime format. y - value gives PRICE. Values are reported no matter where is the mouse (i.e. may refer to window different than current if mouse is outside current window).
mode = 0 - (default) x - value gives X-coordinate in DateTime format. y - value gives PRICE. Returns NULL if mouse is outside current window
mode = 1 - x, y - are mouse coordinates expressed in screen PIXELS. Returns NULL if mouse is outside current window

CHANGES FOR VERSION 5.04.1 (as compared to 5.04.0)

• WF: Settings "Optimization target" combo box shows all built-in fields now
• WF: now combined in-sample and out-sample equities are available by ~~~ISEQUITY and ~~~OSEQUITY composite tickers
(consecutive periods of IS and OOS are concatenated and scaled to maintain continuity of equity line - this approach assumes that you generally speaking are compounding profits)
To display IS and OOS equity you may use for example this:
PlotForeign("~~~ISEQUITY","In-Sample Equity", colorRed, styleLine); PlotForeign("~~~OSEQUITY","Out-Of-Sample Equity", colorGreen, styleLine); Title = "{{NAME}} - {{INTERVAL}} {{DATE}} {{VALUES}}";
• WF: in-sample best uses "first best" result consistenly instead of quicksort (that did not prevent original order)
• WF: the output window is re-open when user closes it during Walk Forward optimization
• Log chart scaling enhanced to handle nicely extreme dynamic range

CHANGES FOR VERSION 5.04.0 (as compared to 5.03.0)

• AFL Formula Editor: Copy-paste does not "eat" last character
• AFL Formula Editor: Edit->Prettify Selection function added
• Calling Activate() method of Window object does not maximize MDI window any more
• Print Preview works fine now with floating windows
• Walk-Forward Optimization implemented (v1)

CHANGES FOR VERSION 5.03.0 (as compared to 5.02.2)

• Fixed: Pane/Template options do not work on floating window
• New linking settings are now saved in layouts and restored properly
• Fixed: Layouts with old-style linked charts are now automatically converted into new scheme when loading layout

CHANGES FOR VERSION 5.02.2 (as compared to 5.02.1)

• fixed problem with c-like multi-line comments /* */ that appeared in 5.02.1 beta

CHANGES FOR VERSION 5.02.1 (as compared to 5.01.1)

• Implemented Unlimited nesting of #include and #include_once
• True multi-monitor support. Chart windows can now be floated (outside main application frame) and moved to different monitors
• Implemented new way of symbol-linking of charts (the button next to scrollbar allows to choose linked group (1-9))
• Fixed crash when attempting to backtest on empty watch list (bug introduced in 5.01)
• AFL: SetBarFillColor( colorarray ) allows to independently control candlestick, bar, cloud, and area chart fill color
• OLE: when Broker.Application reference count drops to zero and AB was not running prior to CreateObject() then the AB is closed
• Implemented workaround to Windows XP list view drawing bug (MS KB813791)
• Floating pane title is synchronized now (5.02.0 fix)

CHANGES FOR VERSION 5.01.1 (as compared to 5.01.0)

• toolbar customizations are now stored in Broker.exe-CommandBars51 (number increased) to isolate new betas and old versions

CHANGES FOR VERSION 5.01.0 (as compared to 5.00.0)

• Tweaks in backtester for improved performance
Portfolio backtester on average 2x faster for both multiple and single-security tests (some trivial, frequently trading systems may observe upto 5x speedup on multiple securities during long analysis periods). Note that AFL engine speed has NOT changed as compared to 5.00. Speed increase comes from backtester tweaks alone, so the longer AFL code is the less speed-up you will see, because backtester processing would account for smaller part of overall execution time.
• Tweaks in quote handling for improved performance
• Code profiler - shows code analysis with detailed per-function timing report. Available from AFL Editor: Tools->Code Check & Profile menu

CHANGES FOR VERSION 5.00.1 (as compared to 5.00.0)

• Minor corrections to documentation
• Small changes for compatiblity with 64 bit version
• Version number bumped and release marked as official

CHANGES FOR VERSION 5.00.0 (as compared to 4.99.0)

• Database Purify: Date column type in set correctly now so clicking on column sorts by date instead of by alpha (FC#1130)
• Elapsed/estimated time is updated constantly when running long optimizations (FC#1107)
• Extra characters in the title occuring when using dynamic color with Null values in Plot() statements. Fixed. (FC#1129)
• Fixed saving of new commission table (FC#1122)
• In some cases slider did not allow to reach the upper margin of Param() when step was decimal fraction like 0.1 due to floating point rounding. Now it addressed. (FC#1155)
• Price Chart Style is now saved in a layout/template (FC#1039)
• When Find/Replace dialog is still open while Formula Editor is closed it does not cause exception anymore

CHANGES FOR VERSION 4.99.0 (as compared to 4.98.0)

• A warning added when closing the last chart window
• Fixed possible stack overflow when using ASCII importer for files without extension but with . (dot) in a path (directory) name
• TimeFrameMode(3) (range mode) was not functional in 4.98, now it is fixed
• Fixed calculation of profit of leveraged instruments denominated in non-base currency when dynamic fx rate was used
• Private heap allocator implemented for quotes and for trading signals
This should resolve problem of getting "out of memory" problem that could occur during very long optimizations due to poor handling of virtual memory in Windows.

CHANGES FOR VERSION 4.98.0 (as compared to 4.97.0)

• N-tick intervals from View->Intraday menu are enabled again in tick databases (were disabled in 4.97 only)

• AFL: Status() function: 2 new fields added

" axisminy" - retrieves the minimum (bottom) value of Y axis (indicators only)
" axismaxy" - retrieves the maximum (top) value of Y axis (indicators only)

Example 1:

Title = "Axis Min Y = " + Status("axisminy") + "Axis Max Y = " + Status("axismaxy"); 

Example 2:

SetChartOptions( 3, 0, ChartGridMiddle ); axismin = Status("axisminy"); axismax = Status("axismaxy"); Plot( C, "Price", colorBlack, styleBar ); // draw exactly 5 grid lines for( i = 0; i < 5; i++ ) {   y = axismin + i * (axismax - axismin)/4;   PlotGrid( y, colorRed ); } 
• HTML export / import now store extra information about the kind of file exported so when you export optimization result and re-import it later you will be able to use optimization graph (FC#: 1029)

• HTML import: sometimes when importing large files duplicate rows appeared at the end - now it is fixed (FC#1024)

• Fixed formatting of numeric values above 100000 after HTML import when comma used as thousands separator (FC#: 1029)

• Added protection against using file-system reserved characters (*?#:|></"\) in watch list names

• Implemented 5-tier commission schedule table in backtester (AA->Settings: Commission table : DEFINE...) (FC#270)

• Account Manager: commission was not subtracted from equity when scaling-in position that was open in previous amibroker run, now it is fixed

• Fixed problem with "Use only local database for this symbol" being set to "yes" during loading of the database with absent broker.master file

CHANGES FOR VERSION 4.97.0 (as compared to 4.96.0)

• Range Bar compression implemented now (FC#: 210, 1041,897,284)

Range Bars are price-driven bars, with each bar having a required minimum high-low range. Source data are consolidated into one bar until the range requirement is reached, then a new bar is started. It works best with tick data that have only one price per data point. You can use it with other base time intervals as well, but please note that if single source bar H-L range exceedes desired range, the output will be single bar that has range higher than requested. In other words source bars exceeding desired range won't be splitted into several range bars. For example if you use 1 minute bars and there is $3 dollar movement and you have selected$1 range bars it won't be splitted into 3 bars. Instead you will get single bar with original $3 range.This is so because AB has no idea what happened *inside* the bar. Prices could move first downwards and later upwards or opposite or zigzaging several times or making any other pattern inside bar and this information is not available from source bar that only has OHLC prices. Note that range bar compression is not standarised. Some other softwares may attempt to split to several artificial bars when range is exceeded, but we belive it is wrong since it is based on assumptions about price action inside bar that may and usually are wrong. Range bars can now be selected as custom compression from Tools->Preferences->IntradayRange bars are also available via TimeFrameMode() function TimeFrameMode( 3 ); // turn on range bars TimeFrameSet( 1.5 ); // set compression to 1.5$ range bar

• Mersene Twister MT19937 random number generator added
Two new AFL functions:

mtRandom( seed = Null ) - returns single random number (scalar) in the range [0,1)
mtRandomA( seed = Null ) - returns array of random numbers in the range of [0,1)

seed is random generator seed value. If you don't specify one, the random number generator
is automatically initialized with current time as a seed that guarantees unique sequence

Both functions use Mersene Twister mt19973ar-cok algorithm.
(Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura.)

Mersene Twister is vastly superior to C-runtime pseudo-random generator
available via Random() function.

It has a period of 219973 = approx 2.9*106012 For more information visit:
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html

M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-Dimensionally Equidistributed Uniform Pseudo-Random Number Generator", ACM Transactions on Modeling and Computer Simulation, Vol. 8, No. 1, January 1998, pp 3--30.

• AFL: PopupWindow() function added (FC#: 840)
SYNTAX:
PopupWindow( bodytext, captiontext, timeout = 5, left = -1, top = -1 );

bodytext - the string containing the text of the window body
caption - the string containing the text of window caption
timeout - auto-close time in seconds (default 5 seconds)
left - top-left corner X co-ordinate (default = -1 -means auto-center)
top - top-left corner Y co-ordinate (default = -1 - means auto-center)

Example code:
 if( ParamTrigger("Display Popup Window", "Press here" ) ) {     PopupWindow("Current time is: " + Now(),"Alert", 2, 640*mtRandom(), 480*mtRandom()); } 

• ASCII Importer: $TIMESHIFT option added (FC# 1094) Added ability to time-shift data at the time of the import.$TIMESHIFT shift_in_hours

For example:

$TIMESHIFT 2 will import with date/time stamps shifted 2 hours forward$TIMESHIFT -11.5

will import with date/time stamps shifted 11 and half hour backward

Please note that only INTRADAY data (with TIME component provided) are shifted. EOD data (without time field) are unaffected.]

• AFL: GetPlaybackDateTime() (FC#: 837)
 pt = GetPlaybackDateTime(); // new function to retrieve playback position date/time, //returns zero if bar replay is NOT active if( pt ) {   Title = "Playback time: " + DateTimeToStr( pt ); } else {   Title = "Bar Replay not active"; } 
It returns zero if bar replay is not active.

• Fixed lockup when bar replay was attempted on base time interval = tick

• Fixed passing IDispatch parameters to OLE/COM method calls

• Fixed error message typo in SetCustomBacktestProc (FC: 1085) "exit" vs "exist"

• 3D optimization chart viewer: added 4x4 Full Screen Anti-Aliasing for beautifully smooth 3D charts and improved readability
4x4 Full-Screen Anti-Aliasing (FSAA) feature is available only on graphic cards that support this in hardware (all NVidia GeForce cards, and most recent graphic cards that have 3D acceleration). It is not available for low-end graphic cards sometimes found in the cheapest notebooks.
If FSAA is not supported by the hardware View->Anti-aliasing menu item will be disabled (grayed).
If FSAA is supported in hardware then it will be turned on by default.
Note that animation speed with FSAA turned on may be lower on slower graphic cards. If speed is not acceptable you can turn off anti aliasing by unchecking View->Anti-aliasing menu (or turning off "A" button in the toolbar) of 3D chart viewer (O3G.exe).

CHANGES FOR VERSION 4.96.0 (as compared to 4.95.0)

• HTML Import to AA result list implemented (FC#579)
Note that this feature is intended to import only HTML files exported by AmiBroker. The HTML parser used is specifically written for this particular purpose and expects certain layout of HTML file. HTML files saved by other programs can not be imported. Use Automatic Analysis -> File -> Import to access this feature.

• Two new backtester modes that do not remove redundant signals (FC#: 105)
• RAW MODE: signal-based backtest, redundant (raw) signals are NOT removed, only one position per symbol allowed:
• RAW MODE WITH MULTIPLE POSITIONS - 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 exit all open positions on given symbol, Scale-In/Out work on all open positions of given symbol at once.

• AFL: new function SetBacktestMode( mode )
Sets working mode of the backtester:
 // default, as in 4.90, regular, signal-based backtest, redundant signals are removed SetBacktestMode( backtestRegular ); // signal-based backtest, redundant (raw) signals are NOT removed, only one position per symbol allowed SetBacktestMode( backtestRegularRaw ); // 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 exit all open positions on given symbol, Scale-In/Out work on all open positions of given symbol at once. SetBacktestMode( backtestRegularRawMulti ); // rotational trading mode - equivalent of EnableRotationalTrading() call SetBacktestMode( backtestRotational ); 
• AA window: custom draw buttons (with arrows) are redrawn on killfocus event to prevent flickering

• Fix: when symbol is deleted from database it is removed from all new watchlists as well

• Attempt to assign value to the element of the array named the same as the function inside the function declaration produces error 33 now instead of crash (FC#: 1011)

• Clicking RMB->Watchlist->Remove inside watch list node was removing symbol from all watch lists. Now it is fixed.

• Fixed cell text truncation that could happen randomly when using HTML export

• Position of compound drawings (retracements/cycles) is updated correctly now when "Properties" dialog was choosen from without selecting the drawing via LMB click

• Stops were reset to default values (from settings) when custom backtest routine was stored in separate file (not embedded or included in the formula). Now it is fixed

CHANGES FOR VERSION 4.95.0 (as compared to 4.94.0)

• Added support for AFL Code Wizard (Analysis->AFL Code Wizard menu and toolbar button)

AFL Code Wizard is a new add-on for AmiBroker. It allows creation of trading system formulas without ANY programming experience. It is available for purchase for $49 one-time fee. Further upgrades are free. AmiBroker comes with trial version that has all functionality *including* export of auto-generated AFL formula to AmiBroker. The only missing feature in trial version of AFL COde wizardis saving the project in .awz format. To run it select Analysis->AFL Code Wizard menu. AFL Code Wizard instructional video can be found at: http://www.amibroker.com/video/amiwiz/AFLWiz1.html • Symbol Tree->Right click->Watch List->Type In works from any node now (FC#991) • Filter window supports more than 256 watchlists (FC#1006) • Aliases are properly recognized when adding symbols to new watchlists CHANGES FOR VERSION 4.94.0 (as compared to 4.93.0) CHANGES FOR VERSION 4.93.0 (as compared to 4.92.0) • Fixed exception that maight occur when copying to clipboard very long lines from AA result list • CategoryGetName() now returns empty string for non-existing categories instead of some uninitialized (random) string • Fixed exception when trying to apply commentary on blank chart pane • AFL editor fix: right Alt + z does not trigger 'undo' anymore (allows to enter Polish z (z-dot-above) letter) • Fixed exception occuring when Symbol Information was edited at the same time while first auto-analysis was run • Fixed bar replay not functioning when viewing interval was the same as base time interval and set to less than 5 minute, mixed mode was off, and no afterhours/weekend filtering was enabled (FC#: 899) • Fix: defined FXRate for the very first symbol in the database is used correctly now (FC#: 975) • When LoadFormula() method of Analysis object is called parameters are reset now (FC#: 958) • Ability to export Chart in "portable" format so you can distribute chart templates to others and they will be restored together with all linked formulas (FC#: 96) This feature is available from RIGHT CLICK on chartTemplate->Save...Template->Load... menus. In addition to old local template format a new one is added with .chart extensionthat keeps not only window sizes and formula references (paths) but also formulas themselves,so all you need to do is to save your chart into one file (Chart Template, Complete *.chart)and copy that file onto different computer and chart will be recreated with all formulas linked to it. To Save chart into new format do the following: 1. Click with RIGHT MOUSE button over the chart and select Template->Save... 2. In the file dialog, "Files of type" combo select "Chart Template, Complete (*.chart)" 3. Type the file name and click Save. To load previously saved complete chart do the following: 1. Click with RIGHT MOUSE button over the chart and select Template->Load... 2. In the file dialog, select previously saved *.chart file and press "Open" Note: The procedure AmiBroker does internally is as follows: When you save the chart into new format it saves XML file with: a) names of all sheets, panes, their sizes, locations and other settings b) paths to all formulas used by all panes c) the text of formulas themselves When you load the chart in new format AmiBroker: a) sets up the sheets/panes according to information stored in the file b) for each formula stored in the file it checks if the same formula exists already on target computer: - if it does not exist - it will create one - if it exists and the contents is identical to the formula stored in .chart file it will do nothing - if it exists and the contents is different then it will create NEW formula filewith _imported.afl suffix (so old file is not touched) and will reference the pane to the _imported.afl formula instead. IMPORTANT NOTE: if you use any #include files AmiBroker will store the contentsof include files as well inside chart file and will attempt to recreate them on target machine.Please note that in case of includes it will check if it exists and if it is different.If both conditions are met (different file exists already) it will ask to replace or not.If you choose to replace - it will replace and make backup of existing one with .bak extensionIf you are using any files in "standard include files and include them using <> braces, AmiBroker will restore files in target machine standard include folder as well evenif the standard include folder path is different on the source machine). Note also - that this functionality is a bit experimental and pretty complex internally. There may be some bugs even though it was tested on number of different setups. Feedback is welcome. It is intended to be used to port charts between different computers. For storing layouts/templates on local computer you should rather use old formats as they consume much less space (they store only references,not the formulas themselves). One may however use new format for archiving purposes as itkeeps formulas and all references in one file that is very convenient for backups. CHANGES FOR VERSION 4.92.0 (as compared to 4.91.1) • Watch list tooltips now show WL ordinal number (index), name and symbol count • new menu item "WatchLists->Hide Empty watchlists" allows to show/hide empty watchlists Note that when you add new watch list AmiBroker will automatically unhide empty watch lists so you can see newly added list. • AFL: Category* functions work fine now with more than 256 watch lists • AFL: new function: CategoryFind() allows to search for category by name SYNTAX: CategoryFind( "name", category ) RETURNS: number FUNCTION: It allows to search for category by name. It takes category name and kind as parameters and returnsINDEX (ordinal number). For example it allows to find watch list index by name: wlnumber = CategoryFind("MyWatch List 1", categoryWatchlist ); mysymbols = CategoryGetSymbols(categoryWatchlist, wlnumber ); The index (in the above example watch list number) can be later used in functions thatneed the index (like CategoryGetSymbols). • AFL: new function: InWatchListName() allows to reference watch list by name It is equivalent to InWatchList function except that it takes watch list name as parameter instead of the index. SYNTAX InWatchListName( "listname" ) RETURNS NUMBER FUNCTION Checks if the stock belongs to a watch list having name of listname. If yes - the function returns 1 otherwise 0. EXAMPLE Filter= InWatchListName( "mywatchlist" ) OR InWatchListName( "mysecondwatchlist" ); Note that this function is a bit slower than InWatchList() function. • Fixed Watch List Export - now exports from selected watch lists (not only from watch list number zero) If you select only one watch list to export then original symbol order is preserved, multiple watch list export uses alphabetical order to prevent duplicates. • Fixed Watch List Sorting - now sorts selected watch list (not only watch list number zero) CHANGES FOR VERSION 4.91.1 (as compared to 4.91.0) • fixed symbol tree refresh after Watchlist->Import CHANGES FOR VERSION 4.91.0 (as compared to 4.90.5) • AA: new options in the context menu "Replace watch list with the results/selected results" This new option empties the watch list before adding results. The order of symbols in the result list is preserved in the watch list. • Watchlists: context (right click) menu - now there is no WL selection dialog displayed If you select the watch list from symbol tree and click with RIGHT mouse button to bring up watch list menu the selected watch list is used automatically and watchlist selector dialog is not displayed. • Watchlists: redesign - now there is no limit on number of watch lists you can use a) watch lists are now stored as text files inside "Watchlists" folder inside database. The folder contains of any number of .TLS files with watch lists themselves and index.txt that defines the order of watch lists. You can add your own .tls file (one symbol per line) and AmiBroker will update index.txt automatically (adding any new watch lists at the end)The .TLS files can also be open in AmiQuote. b) watch lists remember the order in which symbols were added, so for example if you sort AA result list in some order and then you"add symbols to watch list" the order will be kept in the watch list. c) you can now Add/Delete watch lists using Symbol->Watch List-> menu or from watch list context menuNote that if you have done any customization to the menu, you may need to go to Tools->Customize, select "Menu Bar" and press "Reset" button for this new menu items to appear. d) you can now alphabetically sort the symbols in the watch list e) all watch lists are shown in the symbol tree now, even if they are empty. f) for backward compatibility OLE automation WatchListBits/WatchListBits2 properties of Stock object continue to work for first 64 watch lists (bit states are transparently emulated) g) Watch lists created in 4.91 are not visible for older versions • When changing selected symbol, the tree is not traversed to the bottom (root). Instead only current branch is checked and if symbol is selected only if it is present under this branch (This prevents unnecessary unfolding of "All" and other branches) • AFL Editor: AUTOWORDSELECTION turned off • AFL: switch/case statement added (completed: 2007-03-31) (ext.ID: 580). More information: http://www.amibroker.com/guide/v50/keyword/switch.html Example: for( n = 0; n < 10; n++ ) { printf("Current n = %f\n", n ); switch(n) { case 0: printf("The number is zero.\n"); break; case 3: case 5: case 7: printf("n is a prime number\n"); break; case 2: printf("n is a prime number\n"); case 4: case 6: case 8: printf("n is an even number\n"); break; case 1: case 9: printf("n is a perfect square\n"); break; default: printf("Only single-digit numbers are allowed\n"); break; }  • AFL: break/continue statements added (supported inside for/while/do-while/switch statements). More information: http://www.amibroker.com/guide/v50/keyword/break.html http://www.amibroker.com/guide/v50/keyword/continue.html Example: for(i = 1; i < 1000; i *= 2 ) { if( i > 50 ) break; printf("%f\n", i ); } • AFL: new C-like assignment operators +=, -=, *=, /=, %=, &=, |= New operators are shortcuts for some common operations. x += y; is equivalent to x = x + y; x -= y; is equivalent to x = x - y; x *= y; is equivalent to x = x * y; x /= y; is equivalent to x = x / y; x %= y; is equivalent to x = x % y; x &= y; is equivalent to x = x & y; // bitwise and x |= y; is equivalent to x = x | y; // bitwise or • Enanced display in Real Time Quote window (dual-step change coloring - when field changes it is highlighted with bright yellow for 0.25 second then color changes to pale yellow and after a while to default (white) background)) CHANGES FOR VERSION 4.90.4 (as compared to 4.90.3) • PointValue is now automatically set to 1 if FuturesMode is NOT enabled for given backtest (pre-4.90 behaviour) • Fixed crash @040ecde occuring when user incorrectly specifed NULL as a plot color (this is user error but anyway should not crash) (FC#: 848) • Fixed problem with data tips non displaying under some rare circumstances(FC#: 844) • Fixed problem with loading layout that referenced non-existing symbol • Max Title len increased to 9K characters (FC#: 534) • Changes made to color/Thickness/Style of LOCKED studies is saved now even if position did not change (FC#: 846) • Ticker bar now only needs pressing ESC once to lose focus (FC#: 842) CHANGES FOR VERSION 4.90.3 (as compared to 4.90.2) • Fixed GIF export from OLE level when bitdepth was not specified (FC#816) • Notepad DEL key deletes one character now, not two (FC#817) • MDITab titles are refreshed properly after loading the layout (FC#811) • Layouts switching is faster CHANGES FOR VERSION 4.90.2 (as compared to 4.90.1) • new account manager: fixed partial scaling out calcs • OLE automation server registration checks registry access rights correctly on Windows Vista now (this prevents "Failed to update registry. Try using REGEDIT" message on Vista) • Setup program now registers OLE servers by itself using elevated rights on Vista (programs run with ordinary rights do not have access to OLE registration on Vista) • AddToComposite: the combination of atcEnableInIndicator + atcDeleteValues now invalidates cached foreign data (FC#: 809) CHANGES FOR VERSION 4.90.1 (as compared to 4.90.0) • Fixed exception @00435766 (displaying Interpretation for blank window) • Fixed exception @0044F999 (right click on title bar area on blank chart to delete non existing section) CHANGES FOR VERSION 4.90.0 (as compared to 4.89.0) • Fixed problem with information window length constraint being set wrong sometimes. (for example TickSize in View->Information was limited to 4 digits after entering Currency field) • Bar Replay current position static is now updated when changing start date • Fixed problem RTQ window stopped updating the symbol when it was listed twice in different tabs and removed from one (FC#: 439) • Fixed data tooltip display when xshift != 0 (FC#: 465) • Fixed vertical grid Z-order when graphgridzorder = 1 (FC#: 377) • Added "Use as default" box to Horizonal Line properties dialog - when checked, current drawing "show value" selection is stored as a default for all newly created horizontal lines (FC#: 389) • Added File->New->Pane (creates blank pane) • Added File->New->Blank chart (creates blank chart - you can drag-drop formulas on it) • Window->New Linked window menu has been replaced by File->New->Linked Chart • #30339 the limit of drawings per symbol has been increased from 5000 to 65000 [And contrary to previous (faulty) behaviour when limit is reached, you don't lose your previous drawings. Now you just can't save more than 65000 drawings per one symbol.] • Renamed Tools->Auto-update quotes (US & Canada) to Auto-update quotes (AmiQuote only) - new installations only • Removed Tools->Export to CSV - new installations only • Clipboard copy/paste now works OK on "Symbol ticker" combo (in the toolbar) • Warning message when deleting symbols changed to "Are you sure to delete current symbol from the DATABASE !" • Added open interest as a predefined formula • Account manager: 5-tier commission table added • Duplicate shortcut Alt+d for Edit / Define removed. Define now uses 'f' shortcut (FC#: 219) • BarReplay is now paused temporarily when user is drawing objects or printing • Thick dotted line is now plotted with geometic pen on Win2000/XP or higher (FC#: 720) • Fixed problem with passing HGDI handles when printing • Account manager cash calculation when scaling in fixed (FC#: 793) • Added styleNoRescale to Bollinger Bands in Price (all-in-one).afl • ASCII importer: volume is now NOT to adjusted when ADJCLOSE and CLOSE is used [To turn on adjusting (old, pre-4.90 behaviour) you need to add$SPLITADJVOL 1 to command to ASCII importer definition]

• FuturesMode setting set using SetOption #24503 works the same as in the settings dialog
[The difference was due to the fact that PointValue set in the Information window was not transfered to the formula when
Futures Mode was NOT set in the Settings dialog (further change by SetOption did not transfer it).
Now Point Value is transfered always.]

CHANGES FOR VERSION 4.89.0 (as compared to 4.88.0)

• AFL: Static variables are now case insensitive (FC#: 663)

• AFL: SetSortColumns() function (FC#: 607)
SetSortColumns( col1, col2, .... )

sets the columns which will be used for sorting.

col1, col2, ... col10 -Column numbers are ONE-based. Positive number means sort ASCENDING, negative number means sort DESCENDING. Upto 10 columns can be specified for multiple-column sort. Each subsequent call to SetSortColumns overwrites previous one.

Examples:

SetSortColumns( 5 ) - sort by 5th column in ascending order

SetSortColumns( -3 ) - sort by 3rd column in descending order

SetSortColumns( 1, -2 );
- sort by 1st column in ascending order and then by second column in descending order (multiple-column sort).

• Web Research: Synchronization with currently selected symbol has now three options:
Don't sync - does not synchronize with currently selected symbol
Sync active - synchronizes only when web research is active (or becomes active by clicking on it)
Sync always - synchronizes web page always, even if web research window is not active - warning: resource intensive

• New Account Manager added (completed: 2006-12-19)

Account manager provides ability to track your account portfolio. Account manager functionality provides superset of features offered by old portfolio manager, but still some things are left todo namely: multi-currency handling, more stats (backtest-like), multi-tiered commission schedules etc.

Short Instructions:

CREATE A NEW ACCOUNT:

Use File->New->Account menu to create new account

FUNDING AN ACCOUNT:

Before you do any trading, you have to fund your account. To do so press "FUNDING" button on the account manager toolbar, then select "Deposit" as operation type, enter the DATE when you have funded your account and enter the amount.
Note that funding date must PRECEDE any trading, as account manager won't allow you to trade prior to funding date. Initial deposit will show as "initial equity" in summary tab.

CHECK THE SETTINGS

It is good idea to go to "Summary tab" and setup commissions and trading mode. If this account is used for End-of-day trading you should set "EOD Mode" to YES, otherwise (if you trade intraday) you should set "EOD Mode" to NO. Depending on this setting Buy/Sell dialogs will allowyou to enter date and time of the trade or only date.

Commission schedule currently is only one-tier, in the future multiple-tier commission schedules will be possible.

Once you funded an account you can enter trades.To buy (enter long position or cover short position ) click on "BUY" button.

Then in the Buy dialog you need to select the symbol, the trade date/time. Once they are entered AmiBroker will display price of given symbol at the selected date/time (or preceding one if no exact match is found). It will also calculate maximum possible quantity taking price and available funds into account.

You can change the price and quantity manually.

All other values (net market valye, commission, market deposit, currency, fx rate) are calculated or retrieved automatically from Symbol->Information page. Once values are good, click OK to confirm transaction. If you made mistake, you can press UNDO (Edit->Undo) to revert last transaction.

Similar procedure is for selling (entering short positions or closing longs) with the exception that you should press "SELL" button instead.

All transactions that you made are listed in the "Transactions" sheet. All open positions are listed in "Open Positions" sheet. If you enter the trade for symbol that has position already open, AMiBroker will adjust "open positions" accordingly (perform scaling in/out). Once open position is closed it is removed from "open positions" list and moved to "Closed trades" sheet.

After each transaction, "Equity history" sheet is updated with current account equity value and also "Summary" page is updated with basic open/long/short trade stats.(More stats are to come).

IMPORTANT:

You have to remember that you must enter all transactions in chronological manner(oldest first, newest last), as account manager won't allow you to add trades out-of-order. If you make mistake, there is one-level undo that you can use to revert to state before last transaction. If you made more mistakes, the only option is to close account without saving and re-open original file.

To save edits made to account use File->Save (or File->Save As to save under new name). Note that account files are NOT encrypted now, and it is quite easy to read the file for everyone who has the access to it. So make sure not to leave your files on some public computer. Password protection/encryption is planned but NOT implemented yet.

OPENING PREVIOUSLY CREATED ACCOUNT:

To open account file, go to File->Open, in the File dialog,select "Account (*.acx)" from "Files of type" combo-box, and select the account file you want to load.

MULTIPLE ACCOUNTS:

You can create/open multiple accounts at once (just use File->New->Account, File->Open many times).

• Vertical selector line has now user-definable color / bold style and it is plotted behind all graphs so it does not affect readability
Use Tools->Preferences->Color to adjust selector line color and style

• Charts: by default extra 3% space is added on the top of chart compared to previous versions (4.88 or earlier)

• printf/strformat are now protected against buffer overrun (1024 bytes)

• Scroll-Bar Zoom feature implemented (dragging left or right edge of chart scrollbar resizes it allowing to zoom in/out from the scrollbar) (FC#619)
[To turn it OFF use
Tools->Preferences "Charting" tab:
UNCHECK "Enable Scroll Bar Zoom" box.]

• RequestTimedRefresh() was not always starting up correctly since 4.86 - fixed now.

• Range markers are now green (begin) and red (end) and are plotted with lines with small 'flag-like' rectangle at the end

• When user types non-existing symbol in ticker box, AmiBroker asks whenever it should be added or not
This allows very quick adding of new symbols directly from ticker box.
Just type symbol and press ENTER - if it does not exist - it will be added and backfilled if you use real time data source

• When adding/deleting symbols, charts displayed keep selected symbol

• Added ability to create composites (using AddToComposite) inside indicator code via new atcFlagEnableInIndicator flag (FC#: 191)

• AA window: now 'Sync chart' box is hidden when result list is maximized

• AFL: Implemented Say("text") function that speaks provided text (Windows XP, on lower-end Windows you need to install Microsoft Speech API, voice settings are in Windows Control Panel)
Example:

Say("Testing text to speech engine");

CHANGES FOR VERSION 4.88.0 (as compared to 4.87.1)

• Automatic Analysis window: Added "Sync chart on select" checkbox
when turned ON, selection of any line from result list automatically synchronizes (displays) relevant chart. Selection can be made not only by mouse but also by keyboard effectivelly allowing you to scroll through AA result list using key down button and charts will be switching automatically. Also when you press SPACE button, the arrows for selected trade/signal will appear (only after backtest / scan)

• AFL Lexer code optimizations
Removed strncmp() C runtime calls from lexer and replaced it with hand optimized code, gives on average 15% speed improvement on AFL execution on larger formulas. NB. multi-line comment handling is speeded up this way as much as 7 times.

• Bar Replay feature implemented (Tools->Bar Replay)
Bar Replay feature plays back data for ALL SYMBOLS at once. It means that data for all symbols will end at specified "playback position".This affects all formulas (no matter if they are used in charts or auto-analysis).

Controls description:

|<< - rewinds back to the beginning
< - one step back
[ ] - stop - turns bar replay OFF (chart are not affected by bar reply)
|| - pause - pauses current playback or enters pause mode that allows to manually drag the slider bar and affect chart display - in PAUSE mode data are internally modified so quotes past selected "playback" position are invisible to any part of AmiBroker ( charts / automatic analysis ), except quotation editor
> Play - playback bars history
> - one step forward
>> | - goes to end of selected range

Slider bar - allows to see the playback progress as well as MANUALLY move back and forward by dragging the slider thumb.

Start/End - controls provide start and end simulation dates. The playback works so that all data UPTO currently selected "Playback position" are visible. Data past this position are invisible. "Playback position" can change from user-defined "Start" to "End"dates. The small ^ buttons on the right side of Start / End date fields allow to set Start/End to currently selected date on the chart.

Step interval - defines interval of the step. Recommended setting is base interval of your database. So if you have 1-minute database, step interval should be 1 minute. If you have EOD database, step interval should be daily, however it is allowed to select higher step intervals. Note that chart viewing interval is independent from that. So you can playback 1 minute database and watch 15 minute bars (they will look like real - building last "ghost" bar as new data come in)

Speed parameter defines step frequency. It means how many steps will be played back within one second.Default is 1. Maximum is 5 minimum is 0.1. If you select 3 for example, AmiBroker will play one step every 0.333 sec giving total of 3 steps per second.

Skip afterhours - when turned on, playback skips hours outside regular trading hours as defined in File->Database Settings->Intraday Settings

Skip weekends - when turned on, playback skips Saturdays and Sundays

To ENTER PLAYBACK mode - press PLAY or PAUSE buttons - then data are truncated at current "playback position")To EXIT PLAYBACK mode - press STOP button or close Bar Replay dialog - the full data set will be restored.

Note that playback simulation is done internally and the database is kept untouched in fact (all data are still visible in Quote Editor), so there is no risk using Bar Reply.

• Added Insert->Select to Tools->Customize->Keyboard command list to allow customers to add keyboard accelerator to this action

• Fib. TIME extensions , "lock position" now works correcly. Also "bold" attribute can be now applied

CHANGES FOR VERSION 4.87.1 (as compared to 4.87.0)

• fixed symbol tree, right mouse click on the watch list causing exception

CHANGES FOR VERSION 4.87.0 (as compared to 4.86.0)

When this is turned ON, AmiBroker will query data plugin for fresh data when saving database. This ensures that all collected real time data is transferred to AmiBroker's own database.
Caveats:
1. if external data source uses automatic backfill - it may cause triggering backfills during saving 2. turning this feature ON may slightly increase CPU load
Recommendations:
Generally speaking all data sources with no backfill or slow backfill should turn ON this feature,others (with fast backfill covering long histories) should have this turned OFF.
IB plugin: recommended setting: ON
This feature is designed specifically with IB plugin in mind as it has very limited backfill capabilities and it is good to savedata so it does not need to be re-filled on next session.
eSignal plugin: recommended setting: OFF
Using eSignal with this feature turned on may cause excessive backfills and exceeding eSignal symbol limit
IQFeed plugin: recommended setting: OFF
DDE plugin: recommended setting: ON

• Fixed minor save on exit problem

1. File->New -> Default Chart replaces Window->New
2. File->New -> Web Browser - creates new web browser window tab
3. File->New -> Account - creates new account manager window (still in development, not available now) (Tools->Portfolio manager will soon become obsolete)
4. File->New -> Database - replaces File-> New database
5. File->Save / Save As.- allows to save current document (such as HTML page from the browser, or account information (in development))
6. File->Save All - saves ALL modified, open documents including all open formula files
7. File->Close - closes currently open document (chart, browser or account)

Removed View->Profile menu option as it is now replaced by superior File->New->Web Research

• Added Web Research window: multi-tab web browser with multiple built-in financial sites templatized shortcuts
This feature effectively replaces and extends previous View->Profile functionality that allowed to view single symbol profile web page. Now via File->New -> Web Research you can open multiple (unlimited) tabbed web browsers that allow to display unlimited(user configurable in Tools->Customize->Web Pages. In addition to that the browser now features regular "Address" bar that allows to type ANY URL address and use it as regular web browser.
" Open in New Window" option available from right click menu now opens new web browser inside tab.
" Sync" button when activated synchronizes web page with currently selected symbol, so you can browse for example profiles of different symbols by simply switching active symbol from the tree or combo box, without having to type complex URL addresses.

Configuration data are stored in webpages.cfg plain text file that holds any number of URL templates in the form of:

URLTemplate|Description

Description part is optional.URL template may use {t} marker that will be replaced in runtime with currently selected ticker. For more info see:http://www.amibroker.com/guide/h_profiles.html(note that old profile window is no longer available however, the URL template encoding remains the same)

• Added ability to turn off MDI tabs (Tools->Customize->Appearance "Show MDI tabs") - note however that it is not recommeded to turn them off since window navigation will be more difficult

• Added Symbol->Next Sibling / Symbol->Prev Sibling commands to Tools->Customize->Keyboard page (FC#.ID: 550)
This allows to navigate through symbols WITHIN selected category. On NEW installations it will default to Alt+Shift+Left arrow/Right arrow

• Fixed "Remove" button positioning in Organize assignments dialog

• Fixed combo box contents when "Indexes" are choosen in Assignment organizer

• Implemented File->Save All - which saves all open, MODIFIED documents/files, including AFL formulas
Note that because there is no editing functionality for HTML pages (Web Research window) they are never in modified state, so they never get saved using "Save All". To save HTML page you need to manually do Save on selected HTML doc.

• Pane Up/Pane Down function does not change the original height of panes moved

CHANGES FOR VERSION 4.86.0 (as compared to 4.85.0)

• Added 'every tick' RT chart refresh in Professional Edition to already existing 1-sec and up refresh intervals
To enable 'every tick' chart refresh in Professional Edition, go to Tools->Preferences, Intraday tab and enter ZERO (0) into "Intraday chart refresh interval" field. (note Standard Edition won't allow to do that).

Once you enter zero, AmiBroker will refresh all charts with every new trade arriving provided that the formulasyou use execute fast enough. If not, it will dynamically adjust refresh rate to maintain maximum possible refresh rate without consuming more than 50% of CPU (on average). So for example if your charts take 0.2 sec to execute AmiBrokerwill refresh them on average 2.5 times per second.

Note: built-in Windows Performance chart shows cumulated CPU consumption for all processes, to display PER-PROCESS CPU load use SysInternals free software http://www.sysinternals.com/Utilities/ProcessExplorer.html

• MDI tabs implemented

• AFL: Added GetPerformanceCounter( bReset = False ) function

SYNTAX: GetPerformanceCounter( bReset = False )

RETURNS: Number

GetPerformanceCounter retrieves the current value of the high-resolution performance counter. Returned value is in milliseconds. Resolution is upto 0.001 ms (1 microsecond).The value of high-resolution counter represents number of milliseconds from either system start (boot) or from last counter reset.To reset the counter you need to call GetPerformanceCounter function with bReset parameter set to True. Note that reseting 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 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. Example:

GetPerformanceCounter(True); // reset counter to zero for( i = 0; i < 1000; i++ ) {    k = sin( i ); } elapsed=GetPerformanceCounter(); "Time [ms] = "+elapsed;

The code above shows that 1000 iterations of sin() calculation takes about 1.7 milliseconds. Note that call to the GetPerformanceCounter() has overhead of about 0.015 ms (15 microseconds)

GetPerformanceCounter function may also be used to report time since system start:

elapsed=GetPerformanceCounter(); StrFormat("Time since system start %.0f days, %.0f hours, %.0f minutes, %.0f seconds, %.0f milliseconds ", floor(elapsed/(24*60*60*1000)), floor( elapsed/(60*60*1000) ) % 24, floor( elapsed/(60*1000) ) % 60, floor( elapsed/1000 ) % 60, elapsed % 1000 );

It can be also used in trading system automation to measure time in milliseconds between various events (just 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 to inaccurrate results if you have 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

• Fixed crash that sometimes occurred when chart using RequestTimedRefresh() was closed

• Added "Cancel" button to "Do you want to save database: Yes/No" dialog that appears on AB exit when database is modified

• Added registry key for controlling built-in exception handling.

If you are 3rd party developer working with Visual C++ debugger and wanting exceptions to be caught by Visual Studio debugger instead of AmiBroker's built-in crash recovery system contact AmiBroker support and we will provide instructions how to disable it.

• AFL: atan2( y, x ) implemented

atan2 returns the arctangent of y/x. If x is 0, atan returns 0. If both parameters of atan2 are 0, the function returns 0. While atan returns a value in the range –PI/2 to PI/2 radians; 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.

• AFL: FFT( array, size = 0 ) function implemented

FFT( array, len = 0 )

performs FFT (Fast Fourier Transform) on last 'len' bars of the array, if len is set to zero, then FFT is performed
on entire array. len parameter must be even.

Result:

function returns array which holds FFT bins for 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:
0th bin (result[0] and result[1]) represents DC component,
1st bin (result[1 ] and result[2]) represents real and imaginary parts of lowest frequency range
and so on upto result[ len - 2 ] and result[ len - 1 ]

remaining elements of the array are set to zero.

FFT bins are complex numbers and do not represent real amplitude and phase. To obtain amplitude and
phase from bins you need to convert inside the formula. The following code snipplet does that:

ffc = FFT(data,Len); for( i = 0; i < Len - 1; i = i + 2 ) {    amp[ i ] = amp[ i + 1 ] = sqrt(ffc[ i ]^ 2  +  ffc[ i + 1 ]^2);      phase[ i ] = phase[ i + 1 ] = atan2( ffc[ i + 1], ffc[ i ] ); }

IMPORTANT note: input array for FFT must NOT contain any Null values. Use Nz() function to convert Nulls to zeros
if you are not sure that input array is free from nulls.

Example formula:

SetBarsRequired(100000,100000); Len = Param("FFT Length", 1024, 64, 10000, 10 ); Len = Min( Len, BarCount ); x = BarIndex(); x1 = x - BarCount + Len; input = C; a = LastValue( LinRegIntercept( input, Len - 1 ) ); b = LastValue( LinRegSlope( input, Len - 1 ) ); Lr = a + b * x1; data = input - Lr;// de-trending ffc = FFT(data,Len); for( i = 0; i < Len - 1; i = i + 2 ) {    amp[ i ] = amp[ i + 1 ] = sqrt(ffc[ i ]^ 2  +  ffc[ i + 1 ]^2);      phase[ i ] = phase[ i + 1 ] = atan2( ffc[ i + 1], ffc[ i ] ); } auto = ParamToggle("Auto dominant cycle", "No|Yes", 1 ); sbar = Param( "Which FFT bin", 1, 0, 50 ); skipbin1 = ParamToggle("Skip 1st FFT bin", "No|Yes", 1 ); if( auto ) {    sbar = int( LastValue(ValueWhen( amp == LastValue(Highest( IIf( skipbin1 AND x < 4, 0 , amp ) )), x / 2 )) ); } fv = Status("firstvisiblebar"); thisbar = Ref( int(x/2) == sbar, -fv); Plot( Ref(amp,-fv), "amplitude (bin " + Ref( int(x/2), -fv ) +")", IIf( thisbar, colorRed, colorBlack ),styleArea); Plot( IIf( BarCount - BarIndex() < Len, data, Null ) , "de-trended input ("+Len+" bars)", colorOrange, styleLeftAxisScale ); Plot( cos( phase[ sbar * 2 ] + (sbar) * x1 * 2 * 3.1415926 / Len ), " dominant cycle "+ Len/(sbar) + "(" + sbar + " bin) bars", colorBlue, styleOwnScale ); GraphZOrder=1; GraphXSpace = 10; 

• Fixed: pre-defined color table in broker.prefs sometimes got corrupted

• Repainting of RT quote window is now flicker-free on Windows XP and higher

• Symbol->Organize assignments, added ability to remove multiple symbols at once from watch list, index and favourite categories

CHANGES FOR VERSION 4.85.0 (as compared to 4.84.0)

• AFL: Added DateTimeConvert function (FC#: 297)
DateTimeConvert( format, date, time = Null )

The function allows to convert from DateTime format to DateNum and TimeNum and vice versa.

format parameter controls the direction of conversion:

format = 0 - converts DateTime format to DateNum format, example

mydatenum = DateTimeConvert( 0, DateTime() );// - this returns DateNum

date argument should be in datetime formattime argument in this case should not be used

format = 1 - converts DateTime format to TimeNum format, example:

mytimenum = DateTimeConvert( 1, DateTime() ); // - returns timenum 

date argument should be in datetime formattime argument in this case should not be used

format = 2 - converts from DateNum and optionally TimeNum to DateTime format, example:

mydatetime = DateTimeConvert( 2, DateNum(), TimeNum() ); 

date argument should be in datenum formattime argument (optional) should be in timenum format. In case of EOD data you can skip time argument:

mydatetime = DateTimeConvert( 2, DateNum() );

• K-ratio is now reported with 4 decimal places (FC#: 357)

• Added 'left side' display option to horizontal line labels and fixed problem with label sometimes disappearing (completed: 2006-08-15) (FC#: 342)

• AFL: fgetstatus( filename, what, format = 0 )
Implemented

fgetstatus( filename, what, format = 0 )

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
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
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 1=Sunday, 2=Monday, 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 modification date string of portfolio.afl file fgetstatus("formulas\\Equity\\portfolio.afl",1,0);
• AFL: GetTradingInterface uses WaitForInputIdle now instead of fixed interval wait when launching IB interface

• Disabled snapping to pixel resolution after manual editing of drawings #32071

CHANGES FOR VERSION 4.84.0 (as compared to 4.83.1)

• Added GradientFillSlow code to support gradients on printers and metafiles which do not support them natively (completed: 2006-07-28)

• Added GraphGridZOrder variable to control when grid lines are plotted (completed: 2006-07-31) (ext.ID: 351)
When you specify
GraphGridZOrder = 1;
then grid lines are plotted on top of any charts

• AFL: new function RequestTimedRefresh( interval, onlyvisible = True ) (completed: 2006-08-06)

RequestTimedRefresh( interval, onlyvisible = True )

- causes given indicator window to refresh automatically every <interval> seconds regardless of data source used or connection state.

interval parameter defines timeout in seconds between refreshes. AmiBroker attempts to align refreshes to second boundaryso 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 how regular (low overhead) timers are implemented in Windows they have accurracy of +/-55ms providedthat CPU is not very busy. Don't expect to get 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 real-time operating system and it does not guarantee any fixed execution/reaction times.

onlyvisible parameter set to True (default value) means that refreshes are triggered only for visible and not minimised windows. This applies also to main AmiBroker window - when it is minimised charts are NOT refreshed by default. To force refreshes when window is minimised you need to set this parameter to False. Note that this visibility applies to mostly to 'minimised' state or the situation when you move chart outside the boundary of physical screen so it is not visible to an eye but still open. It does not apply to chart windows that are on 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, can not be refreshed.

Example:

RequestTimedRefresh( 5 ); // automatically refresh this particular chart every 5 seconds

Hint: to detect whenever given refresh comes from timer or user action you can use Status("redrawaction") function. It returns 0 for regular refresh (user action) and 1 for timer-refresh

• AFL: Status("redrawaction") added (completed: 2006-08-06)
Status function now supports new field: redrawaction

Status("redrawaction")

It returns 0 (zero) for regular refreshes, and 1 for refreshes triggered via RequestTimedRefresh(). Note that in the future more return values can be added.

Example:

if( Status("redrawaction") ==1 ) { _TRACE("\nTIMED REFRESH"+Now()); } RequestTimedRefresh(1); 
• CreateStaticObject() actually calls internal CreateStaticObject :-) - for some reason it was calling regular CreateObject() instead. (completed: 2006-07-27)

• Fixed problem with HoldMinDays sometimes allowing exit too soon (completed: 2006-07-29)

• Fixed: Custom metric sort problem in optimization result list (occurred in 4.83 only) (completed: 2006-07-29) (ext.ID: 345)

• Pane resizing algorithm changed so if you drag the divider between panes only neighbouring panes are resized (others remain unchanged)

• Real time quote parent window has WS_CLIPCHILDREN style in order to fix some minor redraw issue (completed: 2006-07-31)

CHANGES FOR VERSION 4.83.1 (as compared to 4.83.0)

• Fix to FC#302 caused problems with calling COM properties with parameters. This is now fixed.

CHANGES FOR VERSION 4.83.0 (as compared to 4.82.0)

• Added detection of multiple copies of plugins for the same data source (completed: 2006-07-26)
This (multiple copies of the plugins for same data source) was causing problems and lots of support issues because people were using old plugins even if they installed (newer) copy of the plugin. This was so becasue AB always used first one encountered in given directory and it usually was the oldest one. Now AB displays warning message that there are multiple copies of the same plugin and then they must be renamed or removed.

• Added HoldMinDays and EarlyExitDays options to SetOption() (completed: 2006-07-27)
In addition to already exitsing functionality of HoldMinBars / EarlyExitBars, new options to specify min hold/penalty period in CALENDAR DAYS (as opposed to bars).

SetOption("HoldMinDays", 30 ); // set minimum holding period to 30 calendar days SetOption("EarlyExitDays", 90 ); // set penalty period to 90 calendar days

Note that you can use one or another (not both at the same time) for one parameter, so you can specify minimum holding period in either days or bars (but not both at the same time). The same with EarlyExit period. You may however use different specifications (i.e. days/bars) for EarlyExit and HoldMin (they are independent from each other).

• Added scoreExitAll constant that causes rotational mode backtester to exit all positions regardless of HoldMinBars (completed: 2006-07-27)
Note that this is 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 immediatelly regardless of HoldMinBars setting.

Example:

PositionScore = ..your normal score.. // if market timing signal goes negative close all posiitons PositionScore = IIf( MarketTimingSignal < 0, scoreExitAll, PositionScore ); 

NOTE: This flag works ONLY in rotational trading mode (in regular mode it is easy to generate such global exit by ORing sell signal with global sell signal).

• CBT: Added ExitReason property to Trade object (completed: 2006-07-18) (FC#: 88)

• Chart Tree - RMB - Edit - now restores and focuses to already opened formula editor (if it is during editing) (completed: 2006-07-24) (FC#: 300)
Note that you can still open NEW instance of the editor with the very same file (for comparison and to see the original contents) by holding down SHIFT key when choosing "EDIT" menu.

• Eliminated extra unnecessary refreshes of commentary window when new symbol was picked from ticker selector (completed: 2006-07-24)

• Fixed calling parameter-less JScript functions from AFL level via GetScriptObject() (completed: 2006-07-19) (FC #: 302)

• Fixed: wrong estimated time in progress dialog when number of steps is greater than 2^32 (4294967296) (allocated to: 4.80.2) (completed: 2006-07-24)

Please note that this is independent from chart background color (background color fills entire pane, gradient fill is only for actual chart interior, so axes area is not affected by gradient fill)

SetChartBkGradientFill( topcolor, bottomcolor, titlebkcolor = default )

topcolor - specifies top color of the gradient fill
bottomcolor - specifies bottom color of the gradient fill
titlebkcolor - (optional) the background color of title text. If not specified then top color is automatically used for title background.

Example:

SetChartBkGradientFill( ParamColor("BgTop", colorWhite),ParamColor("BgBottom", colorLightYellow));

• Multiple tabs in RTQ window (completed: 2006-07-18) (FC#: 22)
RT quote window tabs behave the same as chart tabs: can be renamed with right mouse button and dragged from one place to another.
20 tabs are currently available.

• Non-numeric custom trade metrics are not formatted with thousands separators anymore (completed: 2006-07-21) (FC#: 314)

• now Tools->Preferences->Misc "Decimal places in RT quote window" allows to specify upto 6 decimal places. (completed: 2006-07-25)

• OLE: Fixed default property (Item) marker for Windows collection (completed: 2006-07-18)

• Progress dialog: now estimated time is displayed in years/days if it is large enough (completed: 2006-07-24)

CHANGES FOR VERSION 4.82.0 (as compared to 4.81.1)

• OLE: Quotations collection does not have _Item hidden property so it should fix problems with Delphi
• OLE: fixed Documents collection Item method returning always first document object regardless of parameter value
• OLE: Documents collection prepared to support multiple document types
• OLE Added Windows collection, Document property and Activate and Close methods to Window object (FC #272)

Windows collection has one method:

and two properties:

Count - returns the number of windows within given document

Item( i ) - returns the i-th window object

Window object has two new methods:

Activate() - makes window active (focused)
Close() - closes given window

and one new property:

Document - gives parent document object

EXAMPLE CODE (JScript):
outBuffer = ""; // global output string buffer

function output( string )
{
outBuffer = outBuffer + string + "\n";
}

AB = new ActiveXObject( "Broker.Application");

Docs = AB.Documents;
DocsQty = Docs.Count;

for( i = 0; i < DocsQty; i++ )
{
Doc = Docs( i );

output( "Document " + i + " name : " + Doc.Name );

Windows = Doc.Windows;
WinsQty = Windows.Count;

for( j = 0; j < WinsQty; j++ )
{
Win = Windows( j );

output( "  Window " + j + " Selected tab " + Win.SelectedTab );
}

}

WScript.echo( outBuffer );

WScript.echo( "Now will add one window" );
Doc = Docs( 0 );
Windows = Doc.Windows;

WScript.echo( "and close it" );

NewWindow.Close();

• New menu Symbol->Favorities and new item "Erase favourities" to empty the list of favourities (FC#: 280)
• Horizonal line value label added (use new Study properties -> Show Y Value checkbox available for horizonal lines) (FC# 271)
• Fixed crash when clicking on Watch List using RMB (problem occurred in 4.81 beta) (FC# 243)
• Fix: Status('lastvisiblebarindex") and Status("lastvisblebar") now return zero based index instead of one-based (FC# 265)
• Fix: removed spikes from styleCloud when plotted in non-continouous way (with nulls in the middle of the array) (FC# 283)
• Fix rounding problem in AA in futures mode when difference between entry and exit prices was very small and pointvalue large (added extra rounding to profit calculation) (FC# 135)
• Delete key now works in real time quote window (FC# 266)
• AddTextColumn produces now LEFT-justified output (FC# 291)

CHANGES FOR VERSION 4.81.1 (as compared to 4.81.0)

• fixed problem with some of the watch lists not showing up in 4.81.0

CHANGES FOR VERSION 4.81.0 (as compared to 4.80.2)

• Database structure changed to hold new fundamental data - quarterly EAT/EBT/Sales figures, Code and Nominal value have been replaced by new fields.

Despite these changes files are still backward and forward compatible - so it can be read by any other AB version, the only minor inconvenience is that if you load new file into old version (pre-4.81) of AmiBroker you will see weird numbers in old "Finances" dialog as well as in "Shares out." and "Book Value" fields.

• Implemented new View->Information property page featuring extra fundamental data fields

• OLE: added new fundamental data fields to Stock object

Stock object has now the following properties:

string Ticker;
Collection Quotations;
string FullName;
boolean Index;
boolean Favourite;
boolean Continuous;
long MarketID;
long GroupID;
float Beta;
float SharesOut;
float BookValuePerShare;
float SharesFloat;
string WebID;
string Alias;
boolean IsDirty;
long IndustryID;
long WatchListBits;
long DataSource;
long DataLocalMode;
float PointValue;
float MarginDeposit;
float RoundLotSize;
float TickSize;
long WatchListBits2;
string Currency;
string LastSplitFactor;
DATE LastSplitDate;
float DividendPerShare;
DATE DividendPayDate;
DATE ExDividendDate;
float PEGRatio;
float ProfitMargin;
float OperatingMargin;
float OneYearTargetPrice;
float ReturnOnAssets;
float ReturnOnEquity;
float QtrlyRevenueGrowth;
float GrossProfitPerShare;
float SalesPerShare;
float EBITDAPerShare;
float QtrlyEarningsGrowth;
float InsiderHoldPercent;
float InstitutionHoldPercent;
float SharesShort;
float SharesShortPrevMonth;
float ForwardDividendPerShare;
float ForwardEPS;
float EPS;
float EPSEstCurrentYear;
float EPSEstNextYear;
float EPSEstNextQuarter;
float OperatingCashFlow;
float LeveredFreeCashFlow;

• AFL: new function GetFnData() - allows accessing fundamental data

SYNTAX: GetFnData("field")
RETURNS: number

"field" can be one of the following:

"EPS"
"EPSEstCurrentYear"
"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"

• ASCII importer: added support for new fundamental data fields :

$FORMAT command now supports additional fields: DIV_PAY_DATE EX_DIV_DATE LAST_SPLIT_DATE LAST_SPLIT_RATIO EPS EPS_EST_CUR_YEAR EPS_EST_NEXT_YEAR EPS_EST_NEXT_QTR FORWARD_EPS PEG_RATIO BOOK_VALUE (requires SHARES_OUT to be specified as well) BOOK_VALUE_PER_SHARE EBITDA PRICE_TO_SALES (requires CLOSE to be specified as well) PRICE_TO_EARNINGS (requires CLOSE to be specified as well) PRICE_TO_BV (requires CLOSE to be specified as well) FORWARD_PE (requires CLOSE to be specified as well) REVENUE SHARES_SHORT DIVIDEND ONE_YEAR_TARGET MARKET_CAP (requires CLOSE to be specified as well - it is used to calculate shares outstanding) SHARES_FLOAT SHARES_OUT PROFIT_MARGIN OPERATING_MARGIN RETURN_ON_ASSETS RETURN_ON_EQUITY QTRLY_REVENUE_GROWTH GROSS_PROFIT QTRLY_EARNINGS_GROWTH INSIDER_HOLD_PERCENT INSTIT_HOLD_PERCENT SHARES_SHORT_PREV FORWARD_DIV OPERATING_CASH_FLOW FREE_CASH_FLOW BETA (see Formats\aqfe.format and Formats\aqfn.format files for example usage) • Removed Stock->Information and Stock->Finances dialogs (this functionality is replaced by View->Information - new dockable property window) • AFL: new function StrReplace( string, oldsubstring, newsubstring ) • Fixed crash occuring sometimes if "Symbol->Watch List->Type-in" symbol was longer than maximum allowable length (allocated to: 4.80.2) • Foreign() function changed. Now by default missing data bar OHL fields are filled using previous bar Close and volume is set to zero. It is possible to turn old behaviour (filling missing bar OHL fields using previous bar OHL fields and copying previous bar volume) if you use Fixup parameter set to 2. Foreign("MSFT","O", 2 ); // old-style (pre-4.81) fill • Scaling-in profit% calculations modified to use total cost instead of max. pos value • ships with AmiQuote 1.90 featuring automatic download and import of fundamental data from Yahoo Finance. See AmiQuote\ReadMe2.html for the details. CHANGES FOR VERSION 4.80.2 (as compared to 4.80.1) • Changed %profit calculation when scaling-in is used to use maximum number of shares ever held as a “base” of %profit calculation - this leads to “most conservative” % figures, compared to using just initial entry value. • Prec() function improved so it does not show rounding errors when working on integer CHANGES FOR VERSION 4.80.1 (as compared to 4.80.0) • fixed problem with Easy Alert window not accepting new alerts in some circumstances • included new IB plugin version 1.6.2 (FC issue #54) CHANGES FOR VERSION 4.80.1 (as compared to 4.80.0) • fixed problem with Easy Alert window not accepting new alerts in some circumstances • included new IB plugin version 1.6.2 (FC issue #54) CHANGES FOR VERSION 4.80.0 (as compared to 4.79.0) • Added extra information to "detailed log" to show commissions charged during scaling and both average and current exit price • Partial exit (scale-out) profits are included now in trade stats • Fix EOD missing Friday if "Filter weekedns" is turned ON and Daily compression uses Night / Day session settings (#28659) • AFL Editor: Added F1 handling of for/while/do-while/if-else • "SCAN" now displays prices using 4 decimal places • Fixed problem with progress bar locking active window instead of AA window when in run-every mode • Fixed: Layouts messed up with multiple instances running (ext.ID: 3) • "Margin requirement" in the AA settings renamed to "ACCOUNT margin" to clearly show that it is NOT futures margin • Eliminated resource leak in ExportImage OLE function • Fixed potential thread interlock in Indicator Maintenance wizard (should prevent hangup especially on multi-CPU/core machines) • Indicator tables are written to file (broker.newcharts) after each chart insert, before and after Ind. Maintenance just to prevent data loss if AB is not closed properly • Symbol->Watch List->Import refreshes entire symbol tree, not only watch list leaf • added few new formulas into Formulas\Indicators folder CHANGES FOR VERSION 4.79.0 (as compared to 4.78.1) • Added HoldMinBars feature that disables exit during user-specified number of bars even if signals/stops are generated during that period Please note that IF during HoldMinBars period ANY stop is generated it is ignored. Also this period is ignored when it comes to calculation of trailing stops (new highest highs and drops below trailing stops generated during HoldMinBars are ignored).This setting, similar to EarlyExitFee/EarlyExitBars is available on per-symbol basis (i.e. it can be set to different value for each symbol) Example: SetOption("HoldMinBars", 127 ); Buy=BarIndex()==0; Sell=1; // even if sell signals are generated each day, //they are ignored until bar 128 • additional checks added to ensure proper operation of individual equity chart AA window generates error if it can not write LastBacktestFormula to the registry AA complains with error message when individual equity formula does not contain #include @LastBacktestFormula statement that is required for proper operation (it includes the formula used in last backtest so Equity() function can process it) • AFL formula editor toolbar / menu is now customizable Asc() function for converting first character of the string to the ASCII code Asc( string, pos = 0 ) 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. Buy = Cross(MACD(),Signal()); Sell = Cross(Signal(),MACD()); Filter = Buy OR Sell; AddColumn( IIf( Buy, Asc("B"), Asc("S")), "Signal", formatChar ); • Changed EarlyExitFee functionality so it does NOT affect equity (and stats like drawdowns) if position is not liquidated during early bars • Chart sheet tabs improvements: added drag-drop moving, quick selection menu, home/end buttons • Fix: double click on Y axis does not turn <> range markers anymore (allocated to: 4.79.0) • Fix: Param slider, when step =2 and start is odd (for example 3 ) then subsequent values were even (they should be odd 3, 5, 7,...) now it is fixed • Fixed handling of mixed color encodings in AddColumn (pre-defined color constants did not work together with ColorRGB / ColorHSB, now it is fixed) Example of code that did not work correctly in 4.78.1 and earlier but now works fine.  Filter = 1; AddColumn(Close, "Close", 1.2, colorDefault, ColorRGB(255, 0, 0) ); // this works AddColumn(Close, "Close", 1.2, ColorRGB(0, 0, 255), ColorRGB(255, 0, 0)); // this works AddColumn(Close, "Close", 1.2, colorBlue, ColorRGB(255, 0, 0)); // this works in 4.79, but didn't in previous versions AddTextColumn(" ", " "); AddColumn(Close, "Close", 1.2, ColorRGB(255, 0, 0), colorDefault); // this works AddColumn(Close, "Close", 1.2, ColorRGB(255, 0, 0), ColorRGB(0, 0, 255) ); // this works AddColumn(Close, "Close", 1.2, ColorRGB(255, 0, 0), colorBlue); // this works in 4.79, but didn't in previous versions • Fractional increments on Y axis: added 1/320 increment (to use for example with ZT contract) and changed display method so integer part is separated from fractional part by ^ character • Implemented easy real-time alerts (allocated to: 4.79.0) "easy alerts" are available from RTquote window context menu. (Click on Real Time Quote window with RIGHT mouse button and select "Easy Alerts" option - then define alerts you want to generate using real time streaming quotes). If you add any alerts, please note that symbols used in alerts add up to total number of streaming symbols, so if you have 50 symbol limit on your data source and have 40 symbols in your real time quote window you will be able to setup alerts for only 10 extra symbols (if you use the same symbols as in real time quote window then it does not add up to the total count) • OLE: added ability to control sorting in AA window from OLE level Object: Analysis New method: SortByColumn( iColumn, bAscending, bMultiMode ) where iColumn - is zero-based column index to sort bybAscending - true/false decides the order we wantbMulti - if set to false - it means that we want to sort by single column or we define starting column for multi-column sortif set to true - it means that we are defining additional columns for multiple-column sort.So to sort by many columns you need to call SortByColumn once with bMulti set to false and then call SortByColumn for all remaining sort columns with bMulti set to true. Example (multiple column sort by column 1 and 2):  AB = new ActiveXObject("Broker.Application");AA = AB.Analysis; // sort by date/time column AA.SortByColumn( 1, False, False ); // add secondary sort column (see last argument = True) AA.SortByColumn( 2, False, True );  • OLE: added Application.Visible property AB = new ActiveXObject("Broker.Application"); AB.Visible = True; WScript.Sleep(1000); AB.Visible = False; WScript.Sleep(1000); AB.Visible = True; WScript.Sleep(1000); AB.Quit(); • OLE: when AmiBroker is created from OLE, it loads default layout now (previous versions did not • Scaling in/out fixes: added extra checks not to exceed available cash (scaling-in) and not to drop below zero shares (scaling out) • Time&sales now allows the user to disable display of bid/ask and/or trades By default both trades and bidl/ask quotes are shown, but now you can decide to turn off either one or both by clicking with RIGHT mouse button over Time&Sales window and checking/unchecking "Show Trades" and "Show Bid / Ask Quotes" menu items. • Tools: Preferences: Misc, renamed "Save on exit" to "Auto-save" and changed auto-save logic, so layouts are saved on each change When Auto-save: Layouts is turned ON, currently loaded layout is saved on change (i.e. when another layout is loaded, previously selected layout changes are saved first), the same with database load - if you load different database then recently used layout is stored automatically. IMPORTANT: changes are saved now to most recently loaded layout (not to 'default' one as it was before). So default layout is NOT affected by auto-save if you manually loaded different layout. CHANGES FOR VERSION 4.78.1 (as compared to 4.78.0) • atcFlagEnableInPortfolio now works fine with atcFlagCompositeGroup flag. Previously using atcFlagCompositeGroup (or atcFlagDefaults) prevented creation of composite in custom backtest procedure (even if atcFlagEnableInPortfolio was specified). atcFlagEnableInPorfolio worked only without it. Now it is fixed (works fine with or without atcFlagCompositeGroup) • AFLEditor: Edit->Replace fixed • HTMLExport: fixed crash occuring sometimes when lots of columns were used • HTMLExport: fix: colorDefault is not BLACK for background (bgcolor in <TD> tag is skipped) [(this also reduces file size) • HTMLExport: header row is in separate line (CR at the end) • backward compatiblity fix for ExportImage() function (when width and height are not provided then default - current window size - is used) (NOTE: this also fixes Edit->Image->Export ) CHANGES FOR VERSION 4.78.0 (as compared to 4.77.0) • AA: HTML export added that supports FULL COLOR output To export to HTML just click "EXPORT" button in AA window and select "HTML files" from "Files of type" combo box in file dialog. You can also use OLE interface Export method - if EXTENSION provided in the file name is .html then AmiBroker will output HTML file, otherwise it will output CSV (text) file. If you want colorful output in Excel, just EXPORT the file to HTML and load it into Excel (or drag-drop to excel). Please note that Excel color palette is limited (not all 16 million colors available in AmiBroker can be represented in Excel) Example colorful test exploration: Filter=1; for( i = 0; i < 256; i = i + 16 ) AddColumn( C, "C"+i, 1.2, colorDefault, ColorHSB( ( BarIndex() + i ) % 256, 255-i, 255 ) );  • List control code reviewed for better 64bit compatibility • List selection is maintained after sorting • Multiple column sort implemented in AA result list (and other list controls as well) To sort by more than one column: a) click the FIRST column then b) SHIFT-click second, third, fourth column ... and so on (upto 40 columns can be sorted at once) (to SHIFT-click means to click with left mouse button while having SHIFT key pressed down) c) to change the Asc/Desc order click on the same column again To restart sorting, release SHIFT key and click on column (it will become first). Subsequent columns (in the order you have clicked on them) are marked with 1, 2, 3, 4, 5, 6, 7, 8, 9 numbers (if you select more than 10 columns, then all columns above 10th will be marked with '...') • Backtester: added EarlyExitBars/EarlyExitFee functionality (not supported by old (v.4.4) backtester) Early exit (redemption) fee is charged when trade is exited during first N bars since entry. The fee is added to exit commission and you will see it in the commissions reported for example in detailed log. It is also reflected in the portfolio equity (so for first N bars since entry portfolio equity is lower by early exit fee). // these two new options can be set on per-symbol basis // how many bars (trading days) // an early exit (redemption) fee is applied SetOption("EarlyExitBars", 128 ); // early redemption fee (in percent) SetOption("EarlyExitFee", 2 ); (note 180 calendar days is 128 or 129 trading days) // how to set it up on per-symbol basis? // it is simple - use 'if' statement if( Name() == "SYMBOL1" ) { SetOption("EarlyExitBars", 128 ); SetOption("EarlyExitFee", 2 ); } if( Name() == "SYMBOL2" ) { SetOption("EarlyExitBars", 25 ); SetOption("EarlyExitFee", 1 ); }  • AA: "Scan every" feature has been renamed to "Run every" and allows automatic repeat of scan or exploration (new feaeture) it allows also shorter intervals Run every intervals can now be defined in MINUTES (default) or SECONDS. To enter run-every interval in seconds simply add "s" or "sec" at the end of interval value, for example: 10 sec - for run every 10 seconds 5 s - for run every 5 seconds 13 min - for run every 13 minutes 35 m - for run every 35 minutes 7 - for run every 7 minutes (if time unit is not specified then by default minutes are used) • OLE: ExportImage() now supports Width and Height parameters ExportImage function that now allows to specify width and height. So to export say 640x480 gif image you need to write: AB = new ActiveXObject("Broker.Application"); Win = AB.ActiveWindow; Win.ExportImage( "test.gif", 640, 480 ); and you will get perfect image with no jagginess or any scaling artifacts. And it works independently of your current window size and it does NOT affect your current window size. • fix: customColor1 can be selected again using color picker CHANGES FOR VERSION 4.77.0 (as compared to 4.76.0) • styleDashed now uses correct background color when it is modified using SetChartBkColor • AFL Editor: when there is nothing more to undo/redo beep sound is produced • AFL: OBV() and AccDist() now work correctly with TimeFrameSet (#26768) • AFL Editor: Edit->Replace implemented (Ctrl+H shortcut) • CBT: AddCustomMetric now has new parameter that controls number of decimal places used to display custom metric Trade.AddCustomMetric( "Name", value, [optional] decplaces = 2 ); Backtester.AddCustomMetric( "Name", Value, [optional] LongOnlyValue = Null, [optional] ShortOnlyValue = Null, [optional] decplaces = 2 ); where decplaces defines how many decimal places are used to display given metric in the report.If not specified it defaults to 2 decimal places. Example code: bo.AddCustomMetric( "Somestat", 100*kr, Null, Null, 4 ); // 5th parameter controls number of decimal places  • Tooltip "value" field now uses Prefs setting (Tools->Preferences->Misc: "Decimal places in chart titles/tools") + 1 digit decimal points • All Fibonbacci tools now use user-defined number of decimal places (Tools->Preferences->Misc: "Decimal places in chart titles/tools"). Note that this setting applies to NEWLY drawn or MODIFIED fibonacci retracements. Already existing ones won't be affected until you modify/move them. • Added new submenu under "Symbol": "Real Time Quote" with 3 new options: Add selected symbol / Add watch list / Remove all symbols IMPORTANT NOTE: to see new menu you need to go to Tools->Customize, select "MENU" bar and press "RESET" button • AFL: PlotText("Text", x, y, color, bkcolor = colorDefault ) New AFL function: PlotText( "text", x, y, color, bkcolor = colorDefault ) 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 background with specified background color Example: Plot(C,"Price", colorBlack, styleLine ); Plot(MA(C,20),"MA20", colorRed ); Buy=Cross( C, MA(C,20 ) ); Sell= Cross( MA( C, 20 ), C ); dist = 1.5*ATR(10); for( i = 0; i < BarCount; i++ ) { if( Buy[i] ) PlotText( "Buy\n@" + C[ i ], i, L[ i ]-dist[i], colorGreen ); if( Sell[i] ) PlotText( "Sell\n@" + C[ i ], i, H[ i ]+dist[i], colorRed, colorYellow ); } PlotShapes( Buy * shapeUpArrow + Sell * shapeDownArrow, IIf( Buy, colorGreen, colorRed ) ); • AFL: VarGetText New function VarGetText( "varname" ) the same as VarGet but always returns always string values (if underlying variable has different type it is converted to string) Allows for example appending to text variable no matter if it is defined earlier or not: Title = VarGetText("Title") + "something"; // this will work correctly regardless of whenever title was defined earlier or not] • VarSetText New function VarSetText( "varname", "value" ) the same as VarSet but operates on string values. • Auto-analysis backtest result summary modified (added row count and removed wordwrap) • Enlarged "Additional commands" field in ASCII Import Wizard • CBT: Fixed "Out of range" message generated by OLE wrappers when GetValue method of CBT Metrics object returned infinite value (for example as result of division by zero) • Fixed handling of CLICK - DRAW - CLICK drawing mode (#26994) during RT refresh • Fixed incorrect candle color occuring sometimes when candle body was only 1-pixel high • Fixed potential crash occuring sometimes when RTQ window was never shown but RT update arrived • Fixed problem with double arrows appearing on chart with ID == 1 • Fixed problem with selected date in Print/PrintPreview/Image copy • RTQ context menu "Delete symbol" renamed to "Remove symbol" • UI: simplification, Removed (default) from File->Database Settings Base Time interval Combo and "(default)" from local data storage and removed "IMPORTANT ..." static CHANGES FOR VERSION 4.76.0 (as compared to 4.75.2) • Renamed "Number of bars to load" to just "Number of bars" • Fixed problem with weird Time&sales background colors (bug introduced in 4.75.x) • Fixed 1.#INF in P/E colum (RT quote window) • Editor: fixed actionBacktest / actionExplore mix in auto-complete dropdown • Chart Y-axis can now be displayed as fractions (1/4, 1/8, 1/16, 1/32, 1/64, 1/128) - to switch this use Parameters -> GRID -> FORMAT • CBT: Trade object has now "Handle" property that can be passed to ExitTrade and ScaleTrade methods instead of symbol to allow control over exiting/scaling multiple positions of the same symbol  // This is sample formula that allows // to open multiple, separate positions on the same symbol // without averaging effect (i.e. each position on the same // symbol is completely independent). // // Sample code is provided for trading one symbol // Enter symbol you want to trade below Symbol = "MSFT"; Buy=Sell=Short=Cover=0; // real rules are defined inside custom backtest proc SetCustomBacktestProc(""); // enable custom backtest if( Status("action") == actionPortfolio ) { // actual backtest routine // (low-level) bo = GetBacktesterObject(); SetForeign( Symbol ); // make sure to calculate actual buy and buyprice arrays for symbol we need to backtest Buy = 1; // For testing purposes just enter new position every bar BuyPrice = Open; RestorePriceArrays(); // actual backtest loop bo.PreProcess(); for( i = 1; i < BarCount; i++ ) { // first update backtest stats and handle stops bo.UpdateStats( i, 0 ); bo.HandleStops( i ); bo.RawTextOutput("Bar " + i ); if( Buy[ i - 1 ] ) // if buy signal in previous bar { bo.EnterTrade( i, Symbol, True, BuyPrice[ i ], 500 /*$5000 into one trade */);        }           for( OpenPos = bo.GetFirstOpenPos(); OpenPos; OpenPos = bo.GetNextOpenPos() )        {            // exit positions if their age is > 5 bars and they are profitable          if( OpenPos.BarsInTrade > 5 AND OpenPos.GetProfit() > 0 )           {             // HERE IS A NEW PART !!!             // WE ARE PASSING HANDLE instead of ticker symbol             // THIS ENSURES PROPER OPERATION even if we have multiple positions of the same             // stock              bo.ExitTrade( i, OpenPos.Handle, OpenPos.GetPrice( i, "O" ) );            }        }        bo.RawTextOutput("Number of open positions: " + bo.GetOpenPosQty() );        bo.UpdateStats( i, 2 );    }           bo.PostProcess(); } 
• CBT: Small fix for low-level CBT backtest - internal current bar counter is set now via UpdateStats

• ASCII import wizard: Additional commands field accepts "ENTER" key alone (previously one needed CTRL+ENTER to create new line)

• ASCII importer limits the volume to 2147483647 so after convertion to 32bit integer it never becomes negative

• Added parameter list to backtest report (Settings page)

CHANGES FOR VERSION 4.75.2 (as compared to 4.75.1)

• when no data we available chart background is correct now (it was black instead of one choosen in prefs in 4.75.x)

• Added ability to disable fixed ruin stop

SetOption("DisableRuinStop", True);

to your formula the backtester will not use built in 99.96% loss stop (ruin) Note: it is recommended NOT to use it unless you really have to.

• added new option to SetOption:

SetOption("EveryBarNullCheck", True)

SetOption("EveryBarNullCheck", True)- allows to turn 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 arrayand 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 to extend these checks to each and every barwhich is the way 4.74.x and earlier versions worked.

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).

• Added small result summary after backtest in the status line

• Fixed problem with plotting xshifted charts occuring when formula referenced future bars

• logical (boolean) operators check for nulls on every bar and treat null as "false" to maintain backward compatibility with formulas written for previous versions

• Modified file dialog buffer size from 262144 (0x40000) bytes to 262143 (0x3FFFF) to workaround 16 bit (64KB) buffer limit of Windows 95/98/NT4 (yes surprisingly NT4 is limited to 64K buffer in file dialogs)

16-bit windows (95/98) and NT4 were treating 0x40000 as 0 (zero) because only lower 16 bits were interpreted. Thanks to move to 0x3FFFF it is now interpreted as 0xFFFF on 16 bit windows.

• Potential crash fixed when formula using AddToComposite atcEnableInBacktest is verified in the AFL editor

• Added XShift parameter to PlotOHLC and PlotForeign functions

• fixed re-mapping of built-in and custom colors in grid color picker

CHANGES FOR VERSION 4.75.1 (as compared to 4.75.0)

• ParamColor now accepts 24 bit colors without crashing

• Null values appearing at the end of data series (array) are handled appropriately (propagate through arithmetic operators)
This fixes problem that 4.75.0 had with "trendline" formulas that used Null values put into the array at the end of the data series.

• Most recently picked drawing tool color is preserved between runs

• EncodeColor was not handling all 24 bit color combinations correctly. Fixed now.

• Chart tree fix: Moving or renaming formula in charts tree now updates all paths in indicators that use this formula

CHANGES FOR VERSION 4.75.0 (as compared to 4.74.6)

• New chart style (styleCloud) to be used to create "cloud" chart as in Ichimoku charts. Also useful for indicator charts like MACD.

This style fills non-rectangular (free shaped) area between HIGH and LOW arrays provided
by PlotOHLC function. Open and Close arrays are not relevant for plotting however Close
is used as usual to display value label and title. So recommended use is to use "upper" bounding value
in Open and High arrays and "lower" bounding value in "Low" and "Close" arrays

Sample Ichimoku cloud:

SL = ( HHV( H, 26 ) + LLV( L, 26) )/2; TL = ( HHV( H, 9 ) + LLV( L, 9 ) )/2; DL = Ref( C, 25 ); Span1 = Ref( ( SL + TL )/2, -25 ); Span2 = Ref( (HHV( H, 52) + LLV(L, 52))/2, -25); Plot( C, "Price", colorBlack, styleCandle ); Plot( SL, "SL", colorRed, styleThick ); Plot( TL, "TL", colorGreen, styleThick ); PlotOHLC( 0, span1, span2, span2, "Cloud", colorLightOrange, styleCloud );

Simple MACD cloud:

m = MACD(); Plot( Signal(), "Signal", colorBlue, styleThick ); PlotOHLC( m,m,0,m, "MACD", IIf( m > 0, colorGreen, colorRed ), styleCloud );

Another MACD cloud (difference):

m = MACD(); s = Signal(); Plot( s, "Signal", colorBlue); Plot( m, "MACD", colorRed ); PlotOHLC( m,m,s,m, "MACD", IIf( m > s, colorLime, colorLightOrange), styleCloud );

• when File->Open database or MRU list is choosen then old database is saved first

• When default database is deleted, AB now asks for new default database folder, instead of re-creating it

• when database is deleted from the outside and user picks it via MRU list -then gets removed from MRU list and is not recreated anymore

• When AmiBroker is launched with incorrect "Start in" (working directory) then it automatically switches to "last good" path

" Last good" path is saved in the registry HKEY_CURRENT_USER\TJP\Broker\Defaults\LastGoodPath, during successful launch in correct directory (whenever working directory is correct or not it is determined by checking for presence of Broker.chm file (help file))

Using correct working directory is important because AmiBroker uses relative paths to most components.

• AFL: new function: StaticVarRemove()

StaticVarRemove("varname")
removes static variable and releases associated memory

• Start-up time decreased significantly by implementation of on-demand loading of formulas

(on slow, low-end machines loading time decreases from 10 seconds to just 0.5 second)

• printf/StrFormat/SelectedValue functions no longer affect number of extra future bars calculated by QuickAFL

• Minor plugin status change (as in IB backfill) does not cause sound (only tooltip is displayed)

• Increased the limit of files that can be selected using Windows file dialog
Now import wizard and ascii importer file dialogs use 256KB buffer for file names that on average should allow 20000 files to be selected at once.

• Further speed improvements by rewriting chart ID lookup routine (GetChartInfoByID)

• Chart title string is clipped so Y axis is never obscured

• Chart title can be automatically wrapped now
Use 'Parameters' window,
" Axes & Grid" tab,
Miscellaneous->Wrap title: YES

If you want to set it programmatically from the formula use
SetChartOptions( 2, chartWrapTitle );

• Auto-hide panes slide slightly faster

• All basic array arithmetic and logical operators inlined and hand optimized on assembly level for speed, gives upto 450% speed increase in basic array calculations

Example speed increases:

a) purely "theoretical" example
for( i = 0; i < 1000; i++ )  for( k = 0; k < 1000; k++ )    Sumh = H + L;

runs 4.8 times (+480%) faster (5 seconds in 4.75 compared to 24 seconds in 4.74 and older, Athlon64@2GHz)
2000 data bars.

This gives ( 2000 * 1000000 additions ) / 5 sec = 400 MEGAFLOPS (millions of floating point operations per second) AFL array-based AFL execution speed.

b) "real-world" examples:
" Projection Oscillator"
http://www.amibroker.com/library/detail.php?id=344
single security optimization runs 85% faster
(13 seconds (4.75) compared to 24 seconds (4.74 or older) )

" RSIS"
http://www.amibroker.com/library/detail.php?id=153
single-security optimization 5000 iterations runs 21% faster
(28 seconds (4.75) compared to 34 seconds (4.74 or older))

NOTE: Performance increase depends on complexity of the formula. Biggest gains can be observed for formula doing LOTS of mathematical calculations on arrays (using lots of +, -, *, /, ^, %, comparisions <, >, ==, !=, <=, >=, etc).

• AFL: new function: SetChartBkColor( color )
sets chart background to user-specified color

• Added chart timing display (you can turn it on via Tools->Preferences->Display chart timing)

when turned on, in the bottom of each chart the following information is displayed:
Total time X sec, AFL exec time Y sec (Z %), # extra bars back Q, fwd R

where
X - is total time in second spent during chart refresh ( this includes AFL execution and actual screen painting/drawing, grid / scale calculations, etc)
Y - is time spent in chart AFL execution only (without any actual screen painting, grid / scale calcs)
Z - is percentage of time that AFL execution takes compared to total time required for refresh
Q - is a number of previous bars (before first visible bar) that are needed to calculate the indicator (QuickAFL estimation)
R - is the number of future bars (after last visible bar) that are needed to calculate the indicator (QuickAFL estimation)

• Added asin/acos to the AFL function reference

• AFL: 24-bit (16 million) truecolor support for indicators and exploration output.

• new ColorRGB() and ColorHSB functions to access full 24 bit palette

ColorRGB( red, green, blue )

red, green, blue - represent color component values in range 0..255 each

http://en.wikipedia.org/wiki/RGB_color_model

ColorHSB( hue, saturation, brightness )

hue - represents gradation of color within the optical spectrum (as in rainbow)
saturation represents "vibrancy" of the color
brightness represents brightness.

Each parameter ranges from 0 to 255, where 0 represents 0% saturation/brightness
or 0 degree hue in HSV color wheel,
and 255 represents 100% saturation/brightness or 360degrees hue in HSV color wheel

When you modify hue from 0 to 255 you will see consecutive
rainbow colors starting from red, through yellow and green to blue and violet.

http://en.wikipedia.org/wiki/HSB_color_space

Example MA rainbow chart (bring up parameters dialog and play with it):

side = 1; increment = Param("Increment",2, 1, 10, 1 ); for( i = 10; i < 80; i = i + increment ) {     up = MA( C, i );     down = MA( C, i + increment );    if( ParamToggle("3D effect?", "No|Yes" ) )     side = IIf(up<=down AND Ref( up<=down, 1 ), 1, 0.6 );    PlotOHLC( up,up,down,down, "MA"+i, ColorHSB( 3*(i - 10),    Param("Saturation", 128, 0, 255 ),     side * Param("Brightness", 255, 0, 255 ) ), styleCloud | styleNoLabel ); }

///////

Filter=1; for( i = 0; i < 256; i = i + 16 )   AddColumn( C, "C", 1.2, colorDefault, ColorHSB( ( BarIndex() + i ) % 256, 255-i, 255 ) ); 

CHANGES FOR VERSION 4.74.6 (as compared to 4.74.5)

• Fixed problem with RTQuote failing to load symbol list during first show

• Fixed problem in AA-Apply To-Date that was introduced because of tab order change

CHANGES FOR VERSION 4.74.5 (as compared to 4.74.4)

• Toolbar theme was reset when entering Formula Editor, now it is fixed

• Quote Editor list now remembers columns size and order between runs

• Keyboard shortcut editor now allows using punctation characters like Ctrl+[, Ctrl+], - =, etc

• Automatic Analysis: Pick button now has shortcut on Alt+I to avoid conflict with Alt+P (Parameters), also fixed tab order

• Fixed ParamDate to return DateNum instead of YYYYMMDD (4 digit year)

CHANGES FOR VERSION 4.74.4 (as compared to 4.74.3)

• New "Appearance" tab in Tools->Customize, allowing to select menu/toolbar/docking pane themes and tab location

• Layout and Symbol trees are marked for refresh when database is changed and refreshed when user brings them up

• Fixed exception that occurred after customization when ticker bar was removed from all toolbars

• Fixed ticker bar losing focus when Shift/Insert/CapsLock/NumLock pressed

• Real-time Quote column order/size is remembered correctly again

CHANGES FOR VERSION 4.74.3 (as compared to 4.74.2)

• Fixed losing focus by ticker combobox when Shift, CapsLock, NumLock, Insert keys were pressed

CHANGES FOR VERSION 4.74.2 (as compared to 4.74.1)

• Ticker combo is now correctly refreshed on database change even if moved to other toolbar than default

• Previously when Reset was used on Ticker toolbar it became blank - now it is fixed, ticker combo is refilled after closing customization mode

• Edit field in Ticker combobox does not scroll horizontally now when edited text is too long

• Numeric keypad keys now work with File MRU menu (most recently used files)

• Global shortcuts continue to work when focus is inside ticker combo

• "Profile" button in View toolbar works correctly now

CHANGES FOR VERSION 4.74.1 (as compared to 4.74.0)

• Fixed incorrect message displayed in the progress window during some longer explorations

CHANGES FOR VERSION 4.74.0 (as compared to 4.73.0)

New UI features:
• Tear-Off Tabs
• Nested docking pane grouping
• WYSIWYG docking
• sliding auto-hide pinnable windows
• modern "Whidbey" look
• User-defined toolbars

For a little video presentation see: http://www.amibroker.com/video/uicustomize.htmlNote: toolbar and keyboard customizations made in old versions need to be re-done because they can not be imported by new system due to fundamental differences (I am sorry about that)]

• GroupID(), IndustryID(), SectorID, MarketID(), InWatchList(), IsIndex() and IsContinuous() functions are now affected by SetForeign

• Removed debug messages cluttering DebugView output (that appeared in 4.73)

• Changed the way drawing color picker is working: now it works like in Word (or other text editor) - keeps selected color even if drawing with different color is clicke

• Fixed false message "The note has been modified outside the notepad editor." occuring when file did not exist

• OLE: Changed Window.LoadTemplate to return FALSE when file can not be found

• OLE: Window.LoadTemplate now refreshes display so it is not necessary to use SelectedTab = 0

• Removed constant RT refreshes in interpretation window when text does not change

• ZoomToRange: last selected bar in range is visible after zooming now

CHANGES FOR VERSION 4.73.0 (as compared to 4.72.1)

• OLE: Window object, new method ZoomToRange( From, To )
ZoomToRange( From, To )
From and To parameters are of any type that can be converted to date(you can use string or OLE date for example).

Example code (JScript):

AB=new ActiveXObject("Broker.Application");
AW = AB.ActiveWindow;
if( AW.ZoomToRange( "2005-04-01", "2005-08-01" ) )
{
WScript.Echo("Zoom successfull" );
}

• Fixed: Chart got shrinked a bit with each overlaid plot, now the Y scale does not change (unless really needed)

• Fixed: XShift now works correctly with styleOwnScale and styleLeftScale

• Fixed: Volume chart overlaid on price chart in log scale (overlay) was compressed to flat line, now it is fixed (volume chart overlay uses linear scale always)
[#22262]

• AFL: Added AlmostEqual function (completed: 2005-09-16)

AlmostEqual( x, y, ulps = 5 )

this is a helper function for comparing floating point numbers.It returns True if x and y are equal or almost equal upto defined accurracy (ulps).It is recommended to use this function instead of equality check (==) as itleads to more reliable comparisons and less headache caused by IEEE floating pointacurracy issues.

Parameters:x, y - the numbers or arrays to be compared,Ulps stands for "units in last place" and represents maximum relative error of the comparison. Since 32 bit IEEE floating point numbers have accurracy of 7 significant digits, 1 unit in last place(ulp) represents relative error of 0.00001 %. The default value of ulps parameter is 5 which gives roughtly 0.00005% "comparison sensitivity".

Example code:

if( 1/3 == 0.3333333 )
{
printf("32-bit Floating point IEEE exact equality\n");
}

if( AlmostEqual( 1/3, 0.3333333 ) )
{
printf("Numbers are almost equal\n");
}

Thanks to Bruce Dawson for his fast routine.

• Optimize() function now checks if min < max, step > 0 and checks if parameter name is not empty

• Made Time&Sales case insensitive (when "case sensitive tickers" option is turned off")

• OBV/AccDist/Chaikin functions adjusted to be SetForeign-aware

• OLE: Application object new methods
BOOL SaveLayout( filename )

AB = new ActiveXObject("Broker.Application");

• OLE: Window object new property: SelectedTab

AB = new ActiveXObject("Broker.Application");
AW = AB.ActiveWindow;
tabindex = AW.SelectedTab; // read selected tab
AW.SelectedTab = 3; //switch to tab 3
AW.SelectedTab = tabindex; // restore originally selected tab

• Fixed: Exception was generated when GetRTDataForeign was called with non-existing ticker

• OLE: Window object new methods: LoadTemplate, SaveTemplate

AB = new ActiveXObject("Broker.Application");
AW = AB.ActiveWindow;
AW.SaveTemplate("Test.abt");

CHANGES FOR VERSION 4.72.1 (as compared to 4.72.0)

• fixed out-of-memory problem sometimes occuring during scan of large (>512MB) databases

CHANGES FOR VERSION 4.72.0 (as compared to 4.71.1)

• " Currency" field support in ASCII importer
$CURRENCY USD and field:$FORMAT Name,Currency$OVERWRITE 1$AUTOADD 1]

• Added "Additional commands" field in the Import wizard for typing any extra $- commands that are not available via checkboxes • Added parameter to AddColumn/AddTextColumn to control column width AddColumn( ARRAY, "Caption", format = 1.2, color = colorDefault, bgcolor = colorDefault, width = -1); AddTextColumn( "Text", "Caption", format = 1.2, color = colorDefault, bgcolor = colorDefault, width = -1 ); • AddToComposte new flag to work when Status("action")== actionPortfolio (completed: 2005-09-09) new flag is called atcEnableInPortfolio Example: if( Status("action" ) == actionPortfolio ) { ... Custom backtest mode here .... AddToComposite( some_array, "~COMPOSITE", "X", atcFlagEnableInPortfolio | atcFlagDefaults ); } • AFL added: tanh(), sinh(), cosh() functions Hyperbolic tangent, sine and cosine function • AFL functions: StrToUpper and StrToLower • Fixed: Tick ASCII import: last tick of previous import was deleted on subsequent import, now it is corrected • Function to detect mouse button state GetCursorMouseButtons() returns mouse button state at the time when chart formula is executed 0 - if no mouse button is pressed 1 - if left mouse button is pressed 2 - if right mouse button is pressed 4 - if middle mouse button is pressed plus combinations:3 - left + right5 - left + middle6 - right + middle 7 - left + right + middle] • GetRTDataForeign (retrieving values for other symbols) GetRTDataForeign( "field", "symbol") • Pane is not deleted if shrinked down to zero (prevents from accidential deletion of panes) • Plot function now has xshift parameter that allows to visually shift the chart past the last bar Example 20-bar Moving average shifted 10 bars into the future past the last bar: Plot(Close,"Close",colorBlack,styleCandle);Plot(MA(Close,20), "Shifted MA", colorRed, styleLine, Null, Null, 10 ); Note that shift occurs during plotting and does not affect source array • Removed data source selection from preferences because it caused user confusion way too often • Stock.Currency available via OLE • Title variable now supports new special token {{OHLCX}} which is replaced at runtime by string "Open ..., Hi .... Lo ... Close (...%)" showing current price This way it is possible to implement formula that will show OHLC prices with number of decimal places set in the preferences. Example: SetChartOptions(0,chartShowArrows|chartShowDates); _N(Title = "{{NAME}} - {{INTERVAL}} {{DATE}} {{OHLCX}} {{VALUES}}" ); Plot( C, "Close", ParamColor("Color", colorBlack ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); • user-definable number of decimal places in chart titles (completed: 2005-09-09) Number of decimal places displayed in default chart title is now user-definable inTools->Preferences->Miscellaneous"Decimal places in chart titles". Allowable values: -1 - dynamic mode (number of decimal places automatically adjusted) 0..6 - fixed number of decimal places • QuoteArray resizing now uses heuristic algorithm to minimize memory fragmentation and increase performance • atcFlagDeleteValues now highlighted properly in the AFL editor CHANGES FOR VERSION 4.71.1 (as compared to 4.71.0) • fixed compatibility problem with AmiQuote (due to changed order of OLE properties/method while AmiQuote was using old ones) • now ASCII importer in$TICKMODE does not delete quotes older than oldest (first) record in the imported file, so you can safely import tick data from subsequent files (older first, newest later)

CHANGES FOR VERSION 4.71.0 (as compared to 4.70.5)

• AFL: added GetCursorXPosition() and GetCursorYPosition() functions

Functions return current mouse cursor position.
Values returned are equal to those visible in the status bar, and these functions require status bar to be visible. Returned values represent cursor position at the formula execution time (or few milliseconds before it) and accurracy is subject to pixel resolution of the screen (first cursor position is read in screen pixels (integer) and then converted to actual value therefore for example when screen resolution is 1024x768 maximum obtainable resolution in X direction is 0.1% and in Y direction 0.13%), also X values are snap to datetime of nearest data bar.

It only makes sense to use these functions in indicator/interpretation code.

Using them in AA window may yield random values.GetCursorXPosition() function returns X position in DateTime format (the same as used by DateTime() function).You can convert it to string using DateTimeToStr() function.GetCursorYPosition() returns Y position (as displayed in Y axis of the chart).

Example:

ToolTip="X="+DateTimeToStr(GetCursorXPosition()) +"\nY="+GetCursorYPosition();

• AFL: added DateTimeToStr() and StrToDateTime() functions

These functions allow to convert string to datetime format and vice versa.

Example:

ToolTip="X="+DateTimeToStr(GetCursorXPosition()) +"\nY="+GetCursorYPosition();]

• Added ability to store charts as .GIF (in addition to PNG)

• ASCII importer maximum supported line length is increased to 2048 characters

• Fixed: .aflsafe files didn't get deleted automatically

• Added N-volume bars charts and timeframe support.

Custom N-volume bar intervals are definable (as usual) in Tools->Preferences->Intraday.

TimeFrame functions were also extended to support N-volume bars using new TimeFrameMode() function calling

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 nowas N-volme bars)

Example:

TimeFrameMode( 2 );
TimeFrameSet( 50000 ); // 50'000 share bars..
...do something ...
TimeFrameRestore();

Note: N-volume bars are somewhat weird (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 the only TimeFrameSet() function will yield correct N-volume bar values, TimeFrameGetPrice() may give 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 negative number offset by -1000000 (minus one million):

TimeFrameSet( -1000000 - 2000 );

// gives 2000V barsSimilarly formatted negative numbers will be reported by Interval() function when n-volume bars are selected.

• OLE: Save As PNG / GIF callable from automation

Example script:

AB = new ActiveXObject("Broker.Application");
AB.ActiveWindow.ExportImage("Test.png");

• Plugin is not called when GetExtraData is used for symbol that has "use only local database" flag turned on, and NULL is returned instead of an error

• Protected against changing application's current working directory by printing to file

• Toolbar does not get wrapped when main frame window is resized

• OLE: Analysis object has new method MoveWindow( x, y, width, height) that allows to control position and size of automatic analysis window

AB = new ActiveXObject("Broker.Application");
AB.Analysis.MoveWindow( 10, 10, 200, 200 );

It has some restrictions on size: specified size can not besmaller than 10x10 pixels and can not be bigger than entire screen dimensions.
Also when "No minimum size for resizing dialogs" box in UNCHECKED in Tools->Prefs->Misc it won't shink AA window below default size necessary to fully display all controls.

• ASCII importer: added ability to import tick data from text files

ASCII importer now allows tick data files to be imported.

Tick data files consist of several records having the same timestamp.This makes it impossible to use normal import mode which assumes different (unique) timestampsfor each data row (when same timestamp is found then new data overwrites old).

To turn on TICK mode you need to add manually

$TICKMODE 1 line to ASCII importer definition file.$TICKMODE is a special mode of importer that allows to import quotes that haveduplicate time stamps.

It makes two assumptions:
a) input data should come in the ascending time order (i.e. OLDER records first, LATEST records last)
b) input data should consist of entire tick history because importer will DELETE any existing quotes (to avoid creating multiple copies of the same ticks).

Once again: Turning on
$TICKMODE 1 will DELETE ANY QUOTES that already exist in the database and then will import all ticks from input data file. You have been warned. For example data files like this: MOL,0,20050606,162959,16400.0000,16400.0000,16400.0000,16400.0000,2MOL,0,20050606,162959,16400.0000,16400.0000,16400.0000,16400.0000,11MOL,0,20050606,162959,16400.0000,16400.0000,16400.0000,16400.0000,40 Can be imported using the following definition file:$FORMAT Ticker, Skip, Date_YMD, Time, Open, High, Low, Close, Volume
$SKIPLINES 1$SEPARATOR ,
$CONT 1$GROUP 255
$AUTOADD 1$DEBUG 1
$TICKMODE 1 Sometimes it happens that input files have invalid timestamps (seconds > 59). For example: MOL,0,20050606,162970,16400.0000,16400.0000,16400.0000,16400.0000,2 Please take a closer look at first line shown in this example it has time:16:29:70 (you see 70 seconds !) So I had to add a special flag to the importer that works around such data errors. It is called$ALLOW99SECONDS 1 and will convert all records with invalid seconds (i.e greater than 59)to 59s.
So record stamped 16:29:70 will be treated as 16:29:59

Now for tick mode to work with such incorrect records you would need to add two lines to ASCII importer definition:

$TICKMODE 1$ALLOW99SECONDS 1

CHANGES FOR VERSION 4.70.5 (as compared to 4.70.4)

• Fixed problem with Indicator Maintenance wizard not reading certain layouts correctly, thus deleting indicators that were in fact in use (allocated to: 4.70.5) (completed: 2005-05-08)
• Custom backtester: EnterTrade method uses RoundLotSize parameter from the AA settings if none is specified in function call and RoundLotSize field in Symbol->Information is set to zero (allocated to: 4.70.5) (completed: 2005-05-04)
• StaticVarSet - increased resolution to maximum supported by 32-bit IEEE (allocated to: 4.70.5) (completed: 2005-05-08)
• When trade size limit expressed as % of bar volume shrinks down the trade below "MinPosValue" then such trade is not entered (allocated to: 4.70.5) (completed: 2005-05-04)

CHANGES FOR VERSION 4.70.4 (as compared to 4.70.3)

• Closing editor window while AA operation is running does not result in crash if formula generates error (allocated to: 4.70.4) (completed: 2005-05-01)

• When margin requirement was set to 100 (no margin) then very small artifacts (0.0000000000001) were displayed as margin loan, this is now corrected (allocated to: 4.70.4) (completed: 2005-05-01)

• Added message "Formula execution halted because of an error - no chart to display" instead of "black pane" (allocated to: 4.70.4) (completed: 2005-04-30)

• AFL Editor: Fixed problem with errorneous horizontal scrolling when editing lines longer than 256 characters (allocated to: 4.70.4) (completed: 2005-04-19)

• Default layout is saved automatically when Tools->Indicator Wizard menu is selected (allocated to: 4.70.4) (completed: 2005-04-30)

• Fixed styleThick and styleLine small 'dash' artifact (allocated to: 4.70.4) (completed: 2005-04-30)

• Setup: Mixed mode EOD/Intraday is selected in demo eSignal database (allocated to: 4.70.4) (completed: 2005-04-30)

• Time-compressed N-minute bars are no longer reset on USA EST 00:00:00 when align to session times is turned on (allocated to: 4.70.4) (completed: 2005-04-21)

• Time-compression of bars: open interest is now correctly using "last" value (allocated to: 4.70.4) (completed: 2005-04-15)

• Tools->Indicator Wizard keeps old built-in indicator slots untouched

CHANGES FOR VERSION 4.70.3 (as compared to 4.70.1)

• Added "TIME" control to Text study properties (allocated to: 4.70.3) (completed: 2005-03-24)
• Assigning hyper-long strings to Title variable does not cause program termination anymore (allocated to: 4.70.3) (completed: 2005-03-18)
• Modified daily time compression and weekend filtering when daily bars are set to use day/night session start/end times (allocated to: 4.70.3) (completed: 2005-03-24)
[Now it works so that if day/night session is enabled then weekend begins with the start of Friday night session and ends with the beginning of Sunday night session]
• "Filter weekends" option added to View->Intraday menu, so now it is not necessary to go to File->Database Settings->Intraday settings to change it (allocated to: 4.70.3) (completed: 2005-03-24)
• "Override weekly/monthly bars use date of last trade" Preferences setting was affecting daily charts too. Now it is fixed (only weekly and monhtly charts are affected) (allocated to: 4.70.3) (completed: 2005-03-24)
• Exception when using a left open Param window after the indicator has been closed (allocated to: 4.70.3) (status: fixed) (completed: 2005-03-21)
[now if Param window is closed if corresponding indicator pane is closed]
• Fixed crash occuring sometimes when #included file was missing (allocated to: 4.70.3) (completed: 2005-03-21)
• Fixed crash occuring when run-time or syntax error occurred in the #included file that was longer than 16000 characters (allocated to: 4.70.3) (completed: 2005-03-24)
• Fixed GetCommission() method in Trade object not to ignore bInclExit parameter (allocated to: 4.70.3) (completed: 2005-03-24)
• Control over tooltip text from AFL formula level (allocated to: 4.70.3) (completed: 2005-03-24)
[available now via new reserved variable called TooltipTooltip = "My Tooltip text shows Close " + Close;note that X/Y coords are displayed in the tooltip anyway and that custom tooltip text length is limited to 1000 characters.]
• GetPositionValue() method of Trade object returned entry value instead of current value. Now it is fixed (i.e. CURRENT value is returned) (allocated to: 4.70.3) (completed: 2005-03-24)
• Implemented "Min. pos value" in addition to "Min. shares" (allocated to: 4.70.3) (completed: 2005-03-24)
[This sets global minimum on position (trade) size. Backtester will not open trades below this limit. Default value is zero (no minimum trade size).The setting is available via: AA, Settings: Min. Pos. Value field, and via SetOption("MinPosValue", ... )]
• Updated "READ ME" and some minor corrections in the User's Guide (allocated to: 4.70.3) (completed: 2005-03-24)
• "Max. trade drawdown" for short trades was incorrect, now fixed (allocated to: 4.70.3) (completed: 2005-03-24)

CHANGES FOR VERSION 4.70.1 (as compared to 4.70.0)

• Updated old parts of the User's Guide to present current status-quo.
• First trade exit price was sometime reported as -1#QNAN, this should be fixed now (allocated to: 4.70.1) (completed: 2005-03-16)
• "Delete indicator" in CONTEXT (chart) menu (allocated to: 4.70.1) (completed: 2005-03-10)
• Add ownStyle scaling factor so it is not necessary to use Highest(V) in volume chart (allocated to: 4.70.1) (completed: 2005-03-15)
• Added Help->AFL functions by name, Help->AFL functions by category, Help->AFL reference menu items to AFL editor (allocated to: 4.70.1) (completed: 2005-03-15)
• Adjusted formatting of param window min/max values so it does not use engineering notation (xEy) for numbers smaller than 1e8 (100 million) (allocated to: 4.70.1) (completed: 2005-03-12)
• BUG: Applying preferences resets price style to candlesticks even if something different is selected in View->Price chart style (allocated to: 4.70.1) (status: fixed) (completed: 2005-03-15)
• BUG: Choosing File->Print and then pressing "CANCEL" button blocked further RT refreshes, now fixed. Also now page count is set to 1 (avoid "Next page") (allocated to: 4.70.1) (status: fixed) (completed: 2005-03-15)
• BUG: GetPriceStyle() included styleDots even if currently selected style was candlestick or bar (allocated to: 4.70.1) (status: fixed) (completed: 2005-03-15)
• BUG: RT Quote, Context menu -> HIDE - does not shrink the panel (allocated to: 4.70.1) (status: fixed) (completed: 2005-03-15)
• Change default include directory to "Formulas\Include" (allocated to: 4.70.1) (completed: 2005-03-15)
• Display chart ID in Axes/Grid: Misc: part of parameters dialog and adjust description of Study() (allocated to: 4.70.1) (completed: 2005-03-12)
• Make IDR_BROKERTYPE and IDR_MAINFRAME menus the same (allocated to: 4.70.1) (completed: 2005-03-15)
• Modify registration checking to allow only licenses 4.20 and above (allocated to: 4.70.1) (completed: 2005-03-15)
• New version of IB plugin: 1.3.6 - max. number of streaming symbols increased to 100 (allocated to: 4.70.1) (completed: 2005-03-02)
• Pressing 'X' button in the main frame during Print preview closes print preview only instead of exiting application (allocated to: 4.70.1) (completed: 2005-03-15)
• Quotes for symbols beginning with non-US characters are not saved (should "land" in '_' folder but they don't) (allocated to: 4.70.1) (completed: 2005-03-12)
• Replaced IQFeed plugin with smaller (release) version (allocated to: 4.70.1) (completed: 2005-03-12)
• Symbol->Categories, "This group uses own intraday settings" checkbox and button are now repositioned correctly when dialog is resized (allocated to: 4.70.1) (completed: 2005-03-12)

CHANGES FOR VERSION 4.70.0 (as compared to 4.69.8)

• Rewriten all price formulas to use GetPriceStyle()
• _DEFAULT_NAME() uses indicator title if there is no _SECTION defined
• Changed default background color for the charts
• Removed obsolete color pickers from preferences
• when styleOwnScale is selected and min scale value is <= 0 then logarithmic scaling is turned off for this particular plot
• data plugin interface adjusted back to allow NULL RecentInfo pointer even if ticker is not null
• Removed all obsolete specialized drawing routines for old built-in charts
• Syntax highlighting: default text and number color changed from pink to violet (easier for the eyes)
• Hiding chart pane causes auto-arrange (if selected in preferences)
• Chart panes with date axis displayed take more space than panes without axis if auto-arrange selected
• fixed problem with handling scripting parts written in language that is new-line sensitive (VBScript)
• Changed "cyclic" colors in ParamColor
• fixed display of negative parameter values in Param dialog
• Fixed "scale shrinking" effect when no plot is drawn
• ParserCleanup is called when exception occurs inside interpretation
• if no GraphXSpace variable is defined then default 2% extra space is added
• support for TWS API 8.30 - add primaryExchange=Exchange = "SMART" (or "BEST")

CHANGES FOR VERSION 4.69.8 (as compared to 4.69.0)

• Added copying error message in AFL editor (Edit->Copy Error Message)
• New column in AA Trade List report: Scale In/Out - showing the number of scale-in and scale-out operations within given trade
• Added protection against re-opening the same formula in multiple editor windows via "Edit Formula"
• Price chart style switchable from the menu
• new AFL function:
GetPriceStyle() returns price chart style value to be used in Plot statement
Returned value depends on selection in View->Price chart style menu
• added View->Price chart style->Line with dots
• IB plugin auto-refresh configurable via File->Database Settings->Configure, "Force instant quote retrieval for all symbols"
• Fold/unfold directory in Chart tree causes inserting chart (fix double click handler)
• Fixed 1-tick interval handling when mixed eod/intraday data was enabled
• Fix toolbar display problem when manually sizing down the editor window to zero, closing and re-opening the editor
• Bar requirements were not recalculated after modifying formula since introduction of drag-drop. Fixed now.
• Added: You are about to save the file that is located in hidden drag-drop folder, do you want to move it to Custom folder so it is visible in the chart tree?" message
• Plot() function protected against specifying negative color
• Indicator exception handler calls now CleanupParser when exception occurred outside parser but still somewhere inside drawing routine so other indicators continue to work even if fatal exception occurred during drawing
• When a formula was drag-and-dropped from the Chart tree on to the AA window, the formula loaded, but all the parameters were not reset from the previous formula. Fixed now.
• ApplyStop changes: Fixed problem with trailing stop and exitatstop=2 in regular mode. Also better consistency of trailing stops between "Allow same day stop" mode set to true and false
• action* constants now highlighted by AFL editor
New SetPositionSize function:

SetPositionSize( size, method )
'size' and 'method' parameters are ARRAYS:
'method' can be one of:
spsValue (=1) - dollar value of size (as in previous versions)
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)

For example to liquidate 50% of position simply use

SetPositionSize( 50, spsPercentOfPosition * ( Buy == sigScaleOut ) );

spsNoChange (=0) - don't change previously set size for given bar (allows to write constructs like that):

SetPositionSize( 100, spsShares ); // 100 shares by default
SetPositionSize( 50, IIF( buy == sigScaleOut, spsPercentOfPosition, spsNoChange ) ); // for scale-out use 50% of current position size

New SetPositionSize function automatically encodes new methods of expressing position size into old "positionsize" variable as follows:
values below -2000 encode share count,
values between -2000 and -1000 encode % of current position
values between -1000 and 0 encode % of portfolio equity
values above 0 encode dollar value

Although it is possible to assign these values directly to old-style PositionSize variable, new code should use SetPositionSize function for clarity.

Example of code that exits 50% on first profit target, 50% on next profit target and everything at trailing stop:

Buy = Cross( MA( C, 10 ), MA( C, 50 ) ); Sell = 0; // the system will exit // 50% of position if FIRST PROFIT TARGET stop is hit // 50% of position is SECOND PROFIT TARGET stop is hit // 100% of position if TRAILING STOP is hit FirstProfitTarget = 10; // profit SecondProfitTarget = 20; // in percent TrailingStop = 10; // also in percent priceatbuy=0; highsincebuy = 0; exit = 0; for( i = 0; i < BarCount; i++ ) {    if( priceatbuy == 0 AND Buy[ i ] )     {        priceatbuy = BuyPrice[ i ];     }    if( priceatbuy > 0 )     {        highsincebuy = Max( High[ i ], highsincebuy );       if( exit == 0 AND           High[ i ] >= ( 1 + FirstProfitTarget * 0.01 ) * priceatbuy )        {          // first profit target hit - scale-out          exit = 1;          Buy[ i ] = sigScaleOut;        }       if( exit == 1 AND           High[ i ] >= ( 1 + SecondProfitTarget * 0.01 ) * priceatbuy )        {          // second profit target hit - exit          exit = 2;          SellPrice[ i ] = Max( Open[ i ], ( 1 + SecondProfitTarget * 0.01 ) * priceatbuy );        }       if( Low[ i ] <= ( 1 - TrailingStop * 0.01 ) * highsincebuy )        {          // trailing stop hit - exit          exit = 3;             SellPrice[ i ] = Min( Open[ i ], ( 1 - TrailingStop * 0.01 ) * highsincebuy );        }       if( exit >= 2 )        {          Buy[ i ] = 0;          Sell[ i ] = exit + 1; // mark appropriate exit code          exit = 0;          priceatbuy = 0; // reset price          highsincebuy = 0;        }     } } SetPositionSize( 50, spsPercentOfEquity ); SetPositionSize( 50, spsPercentOfPosition * ( Buy == sigScaleOut ) ); // scale out 50% of position 

• Change default value of "stop parsing at first error" pref switch to FALSE
• Context-sensitive help system (press F1, and help page relevant to current dialog / menu is brought up)

Note that help itself is from version 4.60, so some topics may be missing yet, but it will be all updated with official release 4.70 as it will come with a new Users Guide.
• Fixed bug: Drag-drop from one editor instance to another sometimes generated random characters in source editor
• Added "Error 46. Missing comma" error message to the error list

CHANGES FOR VERSION 4.69.0 (as compared to 4.68.2)

• Extended error information available now by pressing F1 key after highlighting error line
• "Syntax error" message improved
[Now the parser attempts to tell you what is the exact reason of the error, so it may tell you for example that:a) there is probably missing semicolon in the previous lineb) that it is expecting '{' at the beginning of function bodyc) that it expects ( after "if" , "for" and "while"etc, etc.]
• "Missing comma" error message added if there is no comma in variable declaration list or formal parameter list of the function
• Error line position calculated correctly even if using #include in the formula
• Word wrap feature removed (as it caused problems with reporting line number on syntax errors)
• Empty block statement allowed {}
• Edit button in AA window has now Alt-D shortut instead of Alt-E (no conflict with &Exploration)

CHANGES FOR VERSION 4.68.2 (as compared to 4.68.1)

• Improved syntax checking so it points to correct row/col even if case of block statements (completed: 2005-01-25)
[also with "bad arguments" error message arguments are now counted from 1 (instead of 0).]

• AFL editor now highlights with yellow color the line in which error occurred (Win XP, Win 2000 only) (completed: 2005-01-25)
[(there is a setting that allows to turn of this feature in Tools->Preferences->Editor "Highlight error line")]

• Error list in AFL editor (completed: 2005-01-25)
[All error messages are now displayed in the listbox beneath AFL editor. When you click on each error message, appropriate code line in the editor is localized.]

• Improved handing of "stop on first error" flag (completed: 2005-01-25)
[Previously only syntax errors were terminating parsing, now also run time errors terminate parsing on first error (when "stop on first error" flag is set)]

• Added protection against parser re-entry during formula execution (completed: 2005-01-25)
• ListTrades method of Backtester object now produces output only when "Trade List" mode is selected in the settings (completed: 2005-01-25)
[In previous versions (4.68.x) this method listed trades regardless of output mode selected causing misaligned output when "summary" mode was selected or optimization was run]

• Summary mode shows backtester metrics again (somehow it got broken in 4.68.1) (completed: 2005-01-25)

CHANGES FOR VERSION 4.68.1 (as compared to 4.68.0)

• When re-displaying resizable window its stored size and position is now adjusted to fit on screen, also maximized state is stored separately (category: UI - General) (status: fixed) (completed: 2005-01-23)
[(sometimes users moved windows outside desktop and had trouble getting them back)]
• The reminder message about "Show trade arrows" working in trade list mode is shown only once per session (category: UI - General) (status: changed) (completed: 2005-01-23)
• Allow custom metrics to work with 3D optimization charts (category: AFL - Backtester) (status: fixed) (completed: 2005-01-23)

CHANGES FOR VERSION 4.68.0 (as compared to 4.67.0)

• added: Default Custom backtest proc file path setting in the AA Settings -allows to define external formula that will be default user-defined backtester applied to all formulas that do not use its own procedure
• added: SetCustomBacktestProc function to allow changing custom backtest procedure file from formula level

SetCustomBacktestProc( "filename", enable = True )
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

This allows easier implementation of custom per-trade metrics. One can use Backtest( 1 ) to disable default listing of trades then iterate via position and trade list and then call ListTrades method. This is somewhat simpler then implementing entire backtest loop just to add few per-trade metrics.

• added: new field suppoted by SetOption(): PortfolioReportMode
1 - detailed log
2 - summary
3 - no output (custom only)
• Fixed crash occuring when trying to display error message about COM exception and COM
• Fixed "Reverse signal forces exit" handled incorrectly in 4.67.0
• changed: BarsInTrade in Trade object should start from 1, not from 2
BarsInTrade property of Trade object is now zero-based. Note however that the value of zero is available only when trade is just opened in "low-level" approach, so normally you would see numbers >= 1 (all other reporting in AB remains as it was, so enter today and exit tommorrow counts as 2-bar trade)
• fixed: click on "NEW" button in Formula editor should generate new file name in the toolbar
• fixed: Re-enable SAVE button when formula name changes
• added: Raw text output (allocated to: 4.68)
Backtester object features now RawTextOutput method that just outputs any string to the backtest result list at the time of the call. The user can output text formatted in multiple columns using \t (tab) character.

GetPrice( Bar, Field ) method of Trade object retrieves the values of the following fields:
O (Open)
H (High)
L (Low)
C (Close)
F (Fx currency rate)

NOTES:
1. GetPrice function is available only for OPEN POSITIONS, when called on closed trade returns Null value
2. Open interest field is not available GetPrice
3. Bar must be between 0..BarCount-1, otherwise exception will occur

CHANGES FOR VERSION 4.67.0 (as compared to 4.66.2)

• when copy-paste results from Exploration, color codes appeared in Excel as "square" characters. Now it is fixed.
• Automation interface change:
_Item (default property) with id of zero added to Stock.Quotations collection Old Item() property remains with id of 5. This should ensure backward-compatibility.
• removed FreeExtra function to avoid possible memory fragmentation caused by constant growing/shrinking memory when accessing data from RT sources when requested bar count was twice as much as retrieved.
• added error message when the plugin returns incorrect size of quote array
• removed requesting of quotes from RT data plugins during database save (this should address exceeding symbol count when saving large databases running with eSignal plugin)
• new method of Analysis OLE automation object:
Edit( [optional] ForceReload = False )

- displays AFL Editor window for currently loaded formula in AA window, optional ForceReload parameter (default=false) allows to force AFL edito to reload the formula from the file.

AB = new ActiveXObject("Broker.Application"); AA = AB.Analysis. AA.LoadFormula("myFormula.afl"); AA.Edit( 1 ); // force reload 
• new method of Analysis OLE automation object:
ShowWindow( nShowCmd ) - allows to show/minimize/maximize/restore AA window nShowCmd uses standard WinAPI values, few most popular:

SW_HIDE 0
SW_SHOWNORMAL 1
SW_SHOWMINIMIZED 2
SW_SHOWMAXIMIZED 3
SW_RESTORE 9
• Scaling-in and scaling-out (pyramiding) is now supported by the backtester.
Two special constants: sigScaleIn / sigScaleOut added to provide means to tell the backtester when you want to scale-in/out

All you have to do to implement pyraminding is to:
- Assign sigScaleIn to BUY/SHORT variable if you want to scale-in (increase size of) LONG/SHORT position
- Assign sigScaleOut to BUY/SHORT variable if you want to scale-out (decrease size of) LONG/SHORT position

Scaling size is defined by PositionSize variable which in case of scaling defines not absolute positionsize but dollar increase or decrease.

IMPORTANT: Please note that backtester treats trade that you scale-in/out as SINGLE trade (i.e. will show single row in trade list). The only difference versus plain trade is that it will calculate average entry price (and avg. entry fx rate) based on all partial entries and average exit price (and avg. exit fx rate) based on all parial exits and will show average prices in entry/exit price field. The commission is of course applied correctly to each (partial) entry/exit depending on partial buy/sell size.

If you want to see details about scaling you have to run backtest in "DETAIL LOG" mode as only then you will see how scaling-in /out works and how average prices are calculated.

Note also that scaling-in/-out and multiple-currency support is available only in portfolio backtester. Old backtester as well as Equity() function do NOT handle scaling-in/out nor multiple currencies (they simply ignore scaling commands).

Easy examples:

a) dollar-cost averaging (each month you buy stocks for fixed dollar amount)

FixedDollarAmount = 500; MonthBegin = Month() != Ref( Month(), -1 ); FirstPurchase = Cum( MonthBegin ) == 1; Buy = IIf( FirstPurchase, 1, // True (or 1) represents regular buy signal       IIf( MonthBegin, sigScaleIn, // each month increase position            0 ) ); // otherwise no signal Sell = 0; // we do not sell PositionSize = FixedDollarAmount;

b) dollar-cost averaging
(simplified formula because AB treats first sigScaleIn as buy anyway)

FixedDollarAmount = 500; MonthBegin = Month() != Ref( Month(), -1 ); FirstPurchase = Cum( MonthBegin ) == 1; Buy = IIf( MonthBegin, sigScaleIn, 0 ); // each month increase position Sell = 0; // we do not sell PositionSize = FixedDollarAmount;

c) increasing position when profit generated by trade without pyramiding
becomes greater than 5% and decreasing position when loss is greater than -5%

// percent equity change threshold when pyramiding is performed PyramidThreshold = 5; // regular trading rules (no pyramiding) Buy = Cross( MACD(), Signal() ); Sell = Cross( Signal(), MACD() ); e = Equity(1); // generate equity without pyramiding effect PcntProfit = 100 * ( e - ValueWhen( Buy, e ) )/ValueWhen( Buy, e ); InTrade = Flip( Buy, Sell ); // ExRem is used here to ensure that scaling-in/out occurs // only once since trade entry DoScaleIn = ExRem( InTrade AND PcntProfit > PyramidThreshold, Sell ); DoScaleOut = ExRem( InTrade AND PcntProfit < -PyramidThreshold, Sell ); // modify rules to handle pyramiding Buy = Buy + sigScaleIn * DoScaleIn + sigScaleOut * DoScaleOut; PositionSize = IIf( DoScaleOut, 500, 1000 ); // enter and scale-in size $1000, scale-out size:$500

• fixed appearent hang occuring on rare occassions when backtesting very large symbol set with trade size limit and round lot sizes enabled. Under such conditions the price cache that backtester uses could fill up due to the delayed release when limit of trade volume was hit and round lot size or min. shares setting did not allow to enter smaller trade.

• AFL editor changes:
• auto-saving of formula when user triggers analysis from AA window instead of AFL editor
• when analysis is triggered from AA window and editor window is open then any parsing error brings editor to the top
• AFL OLE support extended to allow SETTING OLE properties (previously only calling methods and getting properties was possible)

Now AFL supports setting/getting properties in usual (brace-less) way:

For example:

AB = CreateObject("Broker.Application"); Stock = AB.Stocks("MSFT"); Stock.FullName = "Microsoft"; // setting OLE property

• (for advanced users only, work in progress)
implemented new interface allowing to control 2nd phase of portfolio backtest

This allows multitude of applications including, but not limited to:

a) position sizing based on portfolio-level equity
b) implementing advanced rotational systems (you have now access to ranking arrays and can decide what trades to take after knowing which symbols scores best on bar-by-bar basis)
d) implementing custom formulas for slippage control
e) advanced scaling-in/-out based on portfolio equity and other run-time stats
f) advanded trading systems that use portfolio-level statistics evaluated on bar-by-bar basis to decide which trades to take

Full documentation on this new interface will be posted in a separate document.

Note: this interface is work-in-progress and any documentation is preliminary and subject to change
• logical operators between number and dispatch (OLE) objects are performed OK now. Also dispatch objects may be used in conditional expressions.

CHANGES FOR VERSION 4.66.2 (as compared to 4.66.1)

• Custom Tools menu re-enabled again (it was disabled in 4.66.0 and 4.66.1)

CHANGES FOR VERSION 4.66.1 (as compared to 4.66.0)

• fixed problem with duplicate chart sheets (which appeared in 4.66.0)

CHANGES FOR VERSION 4.66.0 (as compared to 4.65.2)

• Multiple-currency support in backtester.
Now backtester allows to backtest systems on securites denominated in different currencies. It includes ability to use historical (variable) currency rates. Currency rates are definable in "Currencies" page in the preferences. The currency in which given symbol is denominated in can be entered in Symbol->Information page
• "Currencies" page in Preferences - allows to define base currency and exchange rates (fixed or dynamic)
for different currencies. This allows to get correct backtest results when testing securities denominated in different currency than your base portfolio currency.
• (for advanced users only, beginners should leave it untouched)
ability to change AFL formula root folder. Tools->Preferences->AFL

This not only changes preferences setting but also moves all formula files from old location to new one and
re-links all charts to files in new location. If you specify new folder please make sure to create an empty one. Do NOT use root directories like 'C:\'
(Please use this feature with caution, as it may cause problems if you have more than one copy of AmiBroker installed in different directories, and upgrade scripts may not find your new formula folder automatically, thus formulas shipped with AB may not be updated on next installation *)
* - actually I will make installers aware of new folder location but this will only work if you have one installation or if multiple installations use the same formula folder.
• Custom indicator storage increased to 3000 slots
• Tools->Preferences->Data, new settings
"In-memory cache size max MegaBytes" -
now allows to limit the in-memory cache size to certain amount of megabytes (in addition to limiting number of symbols). The default value is 20% of physical RAM size (calculated by AB at first run)
• Indicator Maintenance Wizard (in Tools menu)
"Indicator Maintenance Wizard" scans all your hard drives for layout files, then reads them all and checks which indicators are in use, then presents you with a list of files that are not in-use and can be
deleted. Folders in drag-drop folder are automatically marked for deletion, the other can be marked manually. And with one click you can delete unused ones. The wizard can be run on whenever you need.
• new Interactive Brokers plugin (1.3.0) that collects data for all symbols in RT quote window and forces AB to retrieve collected data even if no chart is displayed for given symbol nor any scan is run
(note this feature requires not only new plugin but also AmiBroker 4.66.0 or higher)

CHANGES FOR VERSION 4.65.2 (as compared to 4.65.1)

• AFL Formula Editor: toolbar truncation problem solved
• AFL Formula Editor: new "Analysis" button with submenu allows launching AA Scan/Exploration/Backtest/Optimize directly from the editor. Subsequent clicks on "Analysis" button repeat last selected action.
• Automatic Analysis window redesigned:
• removed formula edit field - replaced by common editor that is accessible via "Edit" button,
• changing active formula via "Pick" button
• layout modifed - now more space for result list
• additional button ^ allows to extend result list to cover entire area of Auto-Analysis window.
• Now it is easy to have the same formula for indicator and AA. Just edit the formula and insert chart and use the very same formula in AA. Now when you modify the formula and save it - the changes will be immediatelly applied to both AA and IB.
• Analysis menu accessible from Formula tree allows to load any formula from tree directly to AA window.
AA window is also drag-drop target window so you can load the formula to it via drag-drop too.

CHANGES FOR VERSION 4.65.1 (as compared to 4.65.0)

• fixed unexpected exit of AmiBroker that happened when your formula had SetChartOptions() call and AFL Editor-> Verify or Insert chart was used
• added automatic saving of fail-safe copy before "Verify" in AFL editor. Fail-safe copy is saved with .aflsafe extension. The copy is automatically deleted if check was OK and no crash occurred. In case of crash you can load the backup file to AFL editor (change "Files of type" combo to "Fail-safe AFL backup" in the Open File dialog)

CHANGES FOR VERSION 4.65.0 (as compared to 4.64.3)

• AFL formula tree fold/unfold state restoring works with unlimited nesting levels
• files and entire folders can be now moved using drag & drop mechanism in AFL formula tree. To MOVE files/folders drag them with RIGHT MOUSE BUTTON, to overlay on indicators - drag them using LEFT mouse button
• unnecessary formula tree refreshes removed
• multiple-level UNDO in AFL editor
• multiple-level REDO in AFL editor
• other minor 'undo' feature improvements (entering new line character triggers undo)
• fixed crash when clicked AA->Parameters->Reset All
• Formula Editor has now "Formula name" field that allows to specify file name quickly and save it without need to open "Save As" dialog
Files are stored by default in Formulas\Custom folder
• Save As... toolbar icon replaced by Save drop down menu
• Save function now uses "formula name" field (no need to open file dialog)
• Scaling Min/Max properties now use plain edit fields (no sliders)
• Negative custom scale works again
• Numeric parameter editing enhanced:
- if you click on left-side part of the parameter value field then regular edit field is displayed
- if you click on right-side part of the parameter value field then slider control is displayed
- when "Step" argument in Param() function call is equal to zero, then slider is disabled and parameter is editable only via regular edit control
• Formula Editor now features "Apply indicator" button that works like old "Apply"
(i.e. checks syntax, saves and inserts ONCE) as well as "Insert indicator" (available from submenu) that allows to insert multiple chart panes linked to the same formula
• Formula Editor now has "Verify AFL" button that allows to verify syntax of your AFL
formula without saving
• Automatic Analysis -> Individual Equity and Portfolio Equity now link directly to
"Formulas\Equity\Individual.afl" and "Formulas\Equity\Portfolio.afl" files. If you want to have your own customized equity chart you can modify those files (remember that they will be overwritten by setup program). You can also have unlimited number of your own equity charts defined as custom indicators.
• Portfolio equity chart allows to turn on/off cash/drawdown/bars since last high/lin reg parts using Parameter dialog (by default they are all off)

CHANGES FOR VERSION 4.64.3 (as compared to 4.64.2)

• fixed broker.newcharts file saving routine (should solve 'black panes' problem that appeared in 4.64.0)

CHANGES FOR VERSION 4.64.2 (as compared to 4.64.1)

• during Layout/Template save, all currently used formulas are marked as 'used' so they do not get deleted if the user closes the pane using the same formula in some other layout. (Should solve 'black panes' problem that appeared in 4.64.0)
• when choosing "Delete" option from the formula tree AmiBroker displays the warning message that the formula may be in used in some indicators if the formula was 'linked' to some pane at least once.

CHANGES FOR VERSION 4.64.1 (as compared to 4.64.0)

• formula tree is refreshed after using "Save As..." function in Formula editor (to show any newly created files)
• "Parameters" menu option is turned on always

CHANGES FOR VERSION 4.64.0 (as compared to 4.63.1)

• QuickAFL is turned ON always
(it does not affect regular AFL code, only may affect some loops and/or plugins but a graceful period of almost 2 years was given to every user to get used to it and adjust the code if necessary, note: if particular formula needs all bars use SetBarsRequired function)
• Quick built-in charts is turned ON always
• Y-axis drag area is now thinner (to make de-selecting date easier)
• resizing dialogs remember not only size but also position
• time&sales windows remember size and positions separately for each symbol
• time&sales window now uses TimeShift setting from "Intraday Settings" screen
• max. trade drawdown stat figure is now also updated at exit price of the max. loss stop
• on startup all formulas (built-in and custom) that were stored in broker.charts / broker.bcharts files are now automatically converted to individual AFL files and stored under: Formulas\Old\Built-in
and Formulas\Old\Custom
• found and fixed few byte memory leak when using #include
• #include can now read from registry using @ character
#include @LastBacktestFormula
will include the formula that was used in last backtest run (useful for custom equity formulas)
• Workspace tab control now sizes down without displaying tab scroll bar
• all TimeFrame* AFL functions extended to work with N-tick bars too. N-tick intervals are specified by NEGATIVE numbers passed in 'interval' parameter.
So for example:
TimeFrameSet( -10 ); // switch to 10-tick interval
• Workspace -> Charts tree now supports file deletion, renaming, creation of new files and folders plus more via Right-mouse button (RMMB) menu. Options available from RMB menu:
• Insert - creates a copy of the selected file, insert _SECTIONS if necessary and inserts charts into new pane
• Insert Linked - just inserts chart into new pane - the pane links directly to selected formula (so if you have more than one pane using the same formula, modifying it will modify the chart in all panes linked to it)
• Overlay - overlays selected formula onto "active" pane. Active pane is the pane you have clicked on recently
• Edit - opens Formula Editor and loads selected file for editing
• Rename - allows to rename formula file
• Delete - deletes the formula (permanently !) - charts panes linked to it will become black
• New->Formula - creates new formula file
• New->Folder - creates new folder
• Refresh - refreshes directory/file tree
• Indicator builder removed and replaced by "Formula Editor"
• you can now control axis and grid settings from "Parameters" dialog
• "Main" chart, "Indicators" and "Other indicators" preference pages removed. Now all charts use new drag & drop system

CHANGES FOR VERSION 4.63.1 (as compared to 4.63.0)

• fixed one more multiple-monitor problem with color popup control
• Parameters dialog works again in Automatic-Analysis window
• new AFL function: ParamTrigger

ParamTrigger( "Name", "Button text")
- to be used in indicator builder - to create triggers (buttons).

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 button in the param window is pressed then 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:

trigger = ParamTrigger("Place Order", "Click here to place order"); if( trigger ) {   // your one-shot code here } 
• new AFL function: ParamList

ParamList( "Name", "Values", default = 0 )
- generates the parameter that consist of the list of choices (specified in "values" parameter - | or comma separated). default 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", "MKT|LMT|STP" );

CHANGES FOR VERSION 4.63.0 (as compared to 4.62.1)

• 6th parameter for the Param() - sincr - now has correct default value of zero.
• trading arrows are correctly aligned again - there was a problem introduced in 4.62.1 with arrows alignment
• fixed redraw problem of layers list
- retrieves OLE automation object to automatic trading interface. "Name" is the interface name. You have to have trading interface installed separately to make it work otherwise you will get the error message attempting to use this function. Trading interface for Interactive Brokers will be released separately.
• layer list item width is adjusted automatically now when sizing the workspace pane
• colour-popup is aware of multiple-monitor configurations now and opens up on correct monitor.
• 'Arrange' works properly now after 'pane maximize'
• added warning message when dropping files to AFL formula window.
• added realtime Time&Sales window (View->Time & Sales, or right click over real time quote window)
Standard Edition: only one time & sales window open
Professional Edition: no limits on simultaneously open Time & Sales windows
Note that Time & Sales window requires true tick-by-tick streaming data source (like eSignal) to operate properly. Certain feeds may not provide enough information to allow time&sales window operation. eSignal has been tested and it works fine, as for the others - there will be 'compatibility guide' published soon.
• added automatic marking on "show arrows" flag for old-style Price chart
• new AFL function (advanced users only)
SetChartOptions( Mode = 0, Flags = 0, gridFlags = chartGridMiddle )
allows to set/clear/overwrite/set defaults for chart pane options
• Mode - specifies how options are set:
• 0 - set only the DEFAULT values for new chart. Defaults are applied only once when chart is 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 remaining are unchanged
• 3 - reset flag - flags specified in 3nd and 3rd parameter are cleared while the others remain unchanged.
• Flags - allowable flags are:
chartShowDates, chartLogarithmic, chartShowArrow
• gridFlags - (for internal AmiBroker use - do not use it in your own coding as this parameter will be eventually removed) allowable values are: chartGridDiv100, chartGridPercent, chartGridDiv1000, chartGridMargins
chartGridMiddle, chartGrid0, chartGrid30, chartGrid70, chartGrid10, chartGrid90,
chartGrid50,chartGrid100,chartGrid20,chartGrid80,chartGrid1

Example:
to mark "Show arrows" by default in a new chart use
SetChartOptions( 0, chartShowArrows );

CHANGES FOR VERSION 4.62.1 (as compared to 4.62.0)

• new AFL function
ParamStyle("name", default = styleLine, mask = maskDefault ) - allows to select the styles applied to plot
• new constants:
styleHidden - a combination of styleNoDraw | styleNoRescale
styleDashed - dashed line
to be used with ParamStyle
maskDefault - show thick, dashed, hidden, own scale styles (this is default mask for ParamStyle)
maskAll - show all style flags
maskPrice - show thick, hidden, own scale, candle, bar
maskHistogram - show histogram, thick, hidden, own scale, area
• colorCycle - accepted only by ParamColor function as default value, causes that default color cycles through red, blue, green, turquoise, gold, violet, bright green, dark yellow
• added new setting in Preferences->Charting "Ask for parameters of newly inserted indicators"
(default = TRUE) ensures that AmiBroker displays parameter dialog when inserting or dropping new indicators
• removed obsolete "max number of custom indicators" setting
• Param() function accepts 6 parameters now
Param("name", defvalue, min = 0, max = 100, step = 1, sincr = 0 );
a new parameter sincr is defines the increase of default value when more than one section of the same kind is inserted (dropped) onto the chart
For example:
Periods = Param("Periods", 15, 2, 200, 1, 10 );
Plot( MA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ), ParamStyle("Style") );

now when more than one moving average is dropped onto the chart then subsequent moving averages default to 15, 25, 35, 45, ... and so on (starting value is 15, increase per new section is 10)

CHANGES FOR VERSION 4.62.0 (as compared to 4.61.0)

• implemented indicator drag and drop mechanism. See video tutorial: http://www.amibroker.net/video/dragdrop1.html
• new "Chart" tab in the workspace window (lists all AFL files and directories from "Formulas" subfolder)
• Automatic Analysis formula window is now drag&drop target too (you can drag formulas and AFL files onto it)
• new AFL special functions used to automatically create formulas from code snipplets dragged onto the the indicator pane.
_SECTION_BEGIN, _SECTION_END, _SECTION_NAME, _DEFAULT_NAME, _PARAM_VALUES
• new styleNoTitle causing that given Plot name and values are not included in the title bar of the indicator
• new ParamField function allowing to pick price field
• new ParamToggle function allowing for boolean (Yes/No) parameters
• In Tools->Preferences , Keyboard you can how define single key shortcut for maximizing and restoring chart pane via View : PaneToggle
• "Allow mixed EOD/intraday data" switch does not affect N-day bars anymore
• Parameters are not reset to default values when changing the formula- user-edited values are kept
• new parameters dialog allowing using sections (for example from drag&drop generated code)
• parameters dialog displays the items in the order as they appear in the formula
• fixed Y-axis scale shrinking problem occuring when styleOwnScale was used for all plots
• Insert->Standard Charts, Insert->Custom Indicators menu options removed (now everything is handled by drag & drop) (You can still insert old indicators from Indicator Builder dialog though)

CHANGES FOR VERSION 4.61.0 (as compared to 4.60.4)

• custom time interval support extended to N-day bars.

Now you can define N-day bars in Preferences (Intraday tab) as well as you can use N-day bars via TimeFrame functions. For example
TimeFrameSet( 3 * inDaily ); // switch to 3-day time frame

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 creates 5-day bars that DO NOT necesarily 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 necesarily represent full month, while inMonthly always begins with first day of the month and ends at the last day of the month

CAVEAT:
if your code uses hard-coded numbers like 432000 for weekly and 2160000 for monthly then you MUST change your code to use inWeekly constant and inMonthly constant instead.

• Study properties dialog has now new checkbox
"Lock position" - when checked study can not be moved or re-sized
• ExitAtStop has a new meaning for N-BAR stop type.
If ExitAtStop = 0 then N-bar stop has the lowest priority (so if for example profit target stop is hit on the same bar then profit target is evaluated first)
If ExitAtStop = 1 then N-bar stop has highest priority and it is evaluated before all other stops.
The same effect is obtained by checking "Has priority" box in AA Settings window.

• new maximizing/restoring chart pane functionality available via:
View->Pane->Maximize
View->Pane->Restore
as well as via right click menu.

Remember that you can assign your own keyboard shortcuts for that using Tools->Preferences->Keyboard
• New drawing tool: Arrow
- draws a line that ends with an arrow
• New drawing tool: zig-zag line
draws a series of connected trend lines (Hint: press ESC key to finish the series)
• new File functions in AFL:
• fdelete( "filename" ) - deletes file
"filename" is 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
• fmkdir( "dirname" ) - creates (makes) a directory
"dirname" specifies path of the directory to be created. Please note that this function creates only ONE directory at a time.
So if you want to create 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( "C:\\MyDirectory" ); fmkdir( "C:\\MyDirectory\\MySubDirectory" );

Note also that it is safe to call it even if directory already exists (then no change to file system is applied)
Returns TRUE if directory successfully created, FALSE otherwise
• frmdir( "dirname" ) - removes a directory
"dirname" specifies path of the directory to be removed. Please note that this function removes only ONE directory at a time.
So if you want to remove nested directory tree you have to call it multiple times, for example:

 fmkdir( "C:\\MyDirectory\\MySubDirectory" ); // delete nested subdir first fmkdir( "C:\\MyDirectory" );

Note that directory must be empty before removing it otherwise it will not be possible to remove it.
Returns TRUE if directory successfully removed, FALSE otherwise

CHANGES FOR VERSION 4.60.3 (as compared to 4.60.2)

• third point in 3-point drawing tools like triangle, pitchfork and fib extensions is now snapped precisely when snap-to-price is enabled
• user can override the maximum number of bars per symbol that AB allows

CHANGES FOR VERSION 4.60.2 (as compared to 4.60.1)

• october appears on date axis on weekly charts
• fixed small issue with returning global variables from functions (problem appeared in 4.60.1 only)
• zero level in performance grid is plotted with default grid color
• fixed adding separator characted when percent scale is used
• fixed problem with N/A results occuring when trade size limit by symbol volume was hit and round lot size was set to zero.
• Title variable templates: making Title statements easy.
Now you can embed special tokens in Title variable
that are replaced by appropriate values at run-time.
if you use {{VALUES}} inside Title string
it will be replaced by automatic-values generated by Plot function calls.
if you use {{NAME}} it will be replaced by ticker symbol.
if you use {{DATE}} it will be replaced by selected date
if you use {{INTERVAL}} it will be replaced by name of the interval
Example:
Title = "{{NAME}} - {{INTERVAL}} {{DATE}} - MyChart : {{VALUES}}";
• added information about the length of the cycle (in bars) when using
cycle drawing tool

CHANGES FOR VERSION 4.60.1 (as compared to 4.60.0)

• AA->Settings->Portfolio "Disable trade size limit if data bar has the volume of zero" (true by default). When it is turned ON and the entry bar volume is zero
the backtesterwill not apply the "limit trade size as % of entry bar volume"- this is to allow backtesting mutual funds that come with zero volume data When it is OFF and entry bar volume is zero then backtester will not allow to enter the trade on such bar.
• AA->Settings->Portfolio "Use Previous Bar Equity For Pos Sizing" and new field supported by SetOption/GetOption:
"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
• cosmetic issues:
- replaced "stock" with "symbol" in some strings
- fixed minor painting problem occuring with cycle study drawn on intraday charts
- using SelectedValue function does not grow future bar requirements anymore
• added StaticVarGetText to make using text static variables easier
http://www.amibroker.com/f?staticvargettext
• new built-in chart: Relative Performance - use right-click "Parameters" to change the ticker list.
• ATR uses more bars now when quickafl is on
• scoreNoRotate is now highlighted in AFL editor
• fixed problem with access violations occuring sometimes when calling the same function many times in single line and return statement in the form: return varname;
• Status function supports now
"firstvisiblebar", "lastvisiblebar", "firstvisiblebarindex", "lastvisiblebarindex"

CHANGES FOR VERSION 4.60.0 (as compared to 4.59.0)

• fixed problem with not displaying 3D charts when profit was >1000%
(comma used as a thousand separator was causing problems - now the separator is removed from the data file)
• O3G 3D graphing program improvements:
• optional flat orthogonal view
• translucent water level surface. You can move water level using PageUp/PageDown keys and/or toolbar buttons Thanks to Mark Feierstein for suggesting this.
• sizing and centering works much better now
• better font spacing/sizing
• you can now view the 3D chart of ANY statistic from optimization results just CLICK on the list column HEADER you wish to chart and then choose Report->3D graph and you will see the chart of selected metric.
• charting improvements
• when text tool is active, selecting other tool automatically accepts the text tool entry (no need for additional click on a chart to accept). (You can of course abandon edits by pressing ESC key)
• trend-line bug (affecting other drawing tools) eliminated. (sometime on multi-chart and multi-symbol setups the trendline randomly become almost horizontal, now it is fixed)
• new drawing tool: CYCLE study
- pick start and end points and AmiBroker will plot 30 equally-spaced cycles toward the past and 30 cycles towards the future
• new drawing tool: Fibonacci Extensions (Price)
- pick start and end point of the controlling trend line, then pick THIRD point where extension lines will start
• new drawing tool: Fibonacci Time Extensions
- pick start and end point and AmiBroker will plot time cycle lines that will represent fibonacci ratios multiplied by the number of bars between start and end point
• drawing three point objects (triangle, pitchfork, and Fib Extensions) simplified(now you can just click in three places - it is easier for the beginners than clicking, holding down and dragging as it worked previously. Old mode of operation works too)
• minor other fixes
- % sign appears again on grids using percent style

CHANGES FOR VERSION 4.59.0 (as compared to 4.58.0)

• added 3D, animated surface graph showing 2-parameter optimization results
(Automatic Analysis, Optimize button menu -> View 3D optimization graph

O3G - the 3D graphing program is pretty self-explaining.
Please note that you can move/rotate/animate the surface plot by mouse, keyboard and toolbar buttons.

Mouse controls:
- to Rotate - hold down LEFT mouse button and move in X/Y directions
- to Zoom-in, zoom-out - hold down RIGHT mouse button and move in X/Y directions
- to Move (translate) - hold down LEFT mouse button and CTRL key and move in X/Y directions
- to Animate - hold down LEFT mouse button, drag quickly and release button while dragging

Keyboard controls:
SPACE - animate (auto-rotate)
LEFT ARROW KEY - rotate vert. left
RIGHT ARROW KEY - rotate vert. right
UP ARROW KEY - rotate horiz. up
DOWN ARROW KEY - rotate horiz. down
NUMPAD + (PLUS) - Near (zoom in)
NUMPAD - (MINUS) - Far (zoom out)

You can also copy the image as bitmap using Edit->Copy image
• intraday bar's portfolio equity (IBPE) is calculated from current bar open price (IBPE is used only to calculate position size values when % of portfolio is specified and reported only in 'detail log' mode). end-of-bar equity (reported by equity chart) is calculated from close price (as it always was)
• status bar is automatically shown when Crosshair tool is turned on

CHANGES FOR VERSION 4.58.0 (as compared to 4.57.0)

• 9 new AFL functions:

NoteGet( "Symbol" );
- retrieves note linked to "symbol". If symbol is "" (empty string) then current symbol is used

NoteSet( "Symbol", "Text..." );
- sets text of the note linked to "symbol".
If symbol is "" (empty string) then current symbol is used.

If you overwrite note from AFL level that is opened at the same time in Notepad editor the editor will ask you (when you switch the focus to it) if it should reload new text or allow to save your manually entered text.

Example:
NoteSet("AMD", "Jun 15, 2004: AMD will deliver its first multi-core processors next year");

ClipboardSet( "Text" );
- copies the "text" to the Windows clipboard

ClipboardGet()
- retrieves current contents of Windows clipboard

// this can be used to put dynamically-constructed texts into // clipboard // ClipboardSet( "The price of " + FullName() + " is " + Close );

VarSet( "varname", value )
- sets the value of dynamic variable*

VarGet( "varname" )
- gets the value of dynamic variable*

StaticVarSet( "varname", value )
StaticVarSetText( "varname", "value" )
- sets the value of static variable**

StaticVarGet( "varname" )
- gets the value of static variable**

* Dynamic variables are variables that are named dynamically, typically by creating a variable name from a static part and a variable part. For example, the following example dynamically constructs the variable name from a variable prefix and a static suffix.

for( i = 1; i < 10; i++ ) { VarSet( "C"+i, Ref( C, -i ) ); } // creates variables C1, C2, C3, C4, ...., C10 equal to Ref( C, -1 ), Ref( C, -2 ),   ..., Ref( C, -10 ) // respectively

** Static variable - the variable has static duration (it is allocated when the program begins and deallocated when the program ends)
and initializes it to Null unless another value is specified. Static variables allow to share values between various formulas.
Only NUMBER and STRING static variables are supported now (not ARRAYS).
"Override: Weekly/monthly bars use day of last trade"
when checked (default) then weekly/monthly charts always use timestamp of the day of last trade within a week/month (may not be Friday or last day of the month) regardless of what is set in "Time stamp of compressed intraday bars shows" radio buttons
If you uncheck this box and "time stamp of compressed intraday bar" is set to END TIME of the interval, then weekly bars will be time-stamped with last day of the week (sunday) and monthly bars will be time-stamped with last day of the month regardless if trading has occured on that day or not.
• AddToComposite now by default deletes all previous data instead of setting existing fields to zero at the start of the scan.
The flag default flag 1 has now the name of atcFlagDeleteValues the old flag (now optional) atcFlagResetValues now has value of 32. Most formulas using ATC should not be affected by that change.
• AA: Settings: "Pad and align to reference symbol" is now available for all AA modes (not only portfolio backtest).
This allows for example to turn on aligning when running scans with AddToComposite and thus ensuring that data holes do not generate valleys in composites. This is useful to create intraday composites when data holes/misalignment is often. (when creating intraday composites it is now recommended to check alignining as well as changing "Time compressed bars use START (or END) time of interval" in Tools->Preferences->Intraday)

CHANGES FOR VERSION 4.57.0 (as compared to 4.56.1)

• profit distribution chart took a bit long when profits were extremely large - now it is fixed
• changed vertical line selection code to prevent line disappearing after RT update
• vertical line selection is now working fine in multiple linked windows displaying different time frames
• chart panes can be now moved up/down using View->Pane->Move Up/Down without need to re-insert everything to change the order
• fixed 'approx. X days' text in the "Database Settings" window that reported wrong values in versions 4.53..4.56
• when "show arrows" option is selected in AA window then correct interval is selected in the chart (it was not functioning properly for beta versions 4.53..4.56 and intraday data)
• added Notepad window (View->Notepad) that allows to store free-text notes about particular security. Just type any text and it will be automatically saved / read back as you browse through symbols. Notes are global and are saved in "Notes" subfolder as ordinary
text files.
• implemented browser-like history Back/Forward in menu View->History and in the toolbar,(keyboard shortcuts Back: Ctrl+Alt+LEFT, Forward: Ctrl+Alt+RIGHT, you can change it in Tools->Prefs->Keyboard) Please note that due to customization features of the toolbar on old installations the Back/Forward buttons will not appear unless added manually (click with RIGHT mouse button over standard toolbar, select "CUSTOMIZE" menu and add Back/Forward buttons.)

CHANGES FOR VERSION 4.56.1 (as compared to 4.56.0)

• fixed crash at address: 0x474f54
• fixed K-ratio calculation. Now follows exactly corrected Excel sheet from page 89 of "Quantitative Trading Strategies" by Lars Kestner (published 2003).
• because of many people not reading the comment regarding new "Limit trade size as % of entry bar volume" setting, implemented checking for volume = 0 in data files. If volume is equal to 0 in your data file then this trade size limit does not apply.

CHANGES FOR VERSION 4.56.0 (as compared to 4.55.1)

• fixed crash when RT quote window ticker list contained symbol that did not exist in the database
right-click over any toolbar and choose "CUSTOMIZE" menu to add/remove/arrange toolbar buttons. You can also press ALT key and move/arrange buttons within one toolbar without needing to open "customize" dialog
• eSignal plugin 1.7.1: fixed problem with zero data when the user selected not enough bars to load (mixed mode requires a bit more bars)

CHANGES FOR VERSION 4.55.1 (as compared to 4.55.0)

• implemented workaround to Windows XP status bar display problem causing plugin status indicator not 'disappearing' sometimes
• fixed problem with crash sometimes occuring when calling Import() OLE automation method
when AB was not running.
Versions 4.54-4.55 are localization-enabled and month names are localized too, localized strings have to be setup at the start of the program, but this was working correctly only if GUI was launched. When creating AB OLE object without GUI month name string were not
set-up correctly and this caused problems. (This fixes problems with CSI/UA export as well as AQ trying to import to non-existing instance of AB)
• fputs/fgets/fclose/feof file functions are now protected against using null file handle
(common coding error among AFL users)
• Parameter names are not truncated in the parameter list

CHANGES FOR VERSION 4.55.0 (as compared to 4.54.0)

• Median and Percentile calculations include current bar
• calling COM methods returning nothing (void) does not cause "type mismatch" message
• duplicate parameters are no longer produced when user specifies parameter names with trailing/leading spaces in Param()/ParamStr()/ParamColor()
• now it is safe to call AB.RefreshAll() from inside of AmiBroker because this method is protected against locking up / looping by not allowing consequent refresh if previous refresh occured in less than one second
• Parameters window now is resizable
• Parameters window now support date and time parameters.
Corresponding new AFL functions are:

ParamDate( "Name", "Default date", format = 0 );

where:
"Name" is a string holding parameter name
"Default date" is a string holding date in any any format:
YYYY-MM-DD
MM/DD/YY
DD-MM-YY
etc, etc.

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

ParamTime( "Name", "Default time", format = 0 );
where:
"Name" is a string holding parameter name
"Default time" is a string holding date in any of the following formats:
HH:MM:SS
HH:MM

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

Examples:
Title = WriteVal( ParamDate("ParamDateAsDateNum","2004-05-14"), 7.0 ); Title = ParamDate("ParamDateAsString","2004-05-17",1); 
• portfolio/individual backtester/optimizer, new setting in AA->Settings->Portfolio:
"Limit trade size as % of entry bar volume" (default = 10%)

This prevents from entering the trades greater than given percentage of entry bar's volume.
For example if backtesting daily data and today's volume for thinly traded stock is 177,000 shares, setting this to 10% will limit the maximum trade size to 17,700 shares (10% of total daily volume). This prevents from 'affecting the market'
by huge orders.

IMPORTANT NOTE:
Some instruments like MUTUAL FUNDS come without VOLUME data. To backtest such instruments please set this field to ZERO (0). This effectively turns OFF this feature. Otherwise you won't be able to enter any trade at all. Suggestions are welcome how to handle this problem automatically (maybe just detect if bar's volume is ZERO and then allow entering any size?)
• K-ratio calculation changed following the change made by its creator, Mr. Lars Kestner.

Quoting from the book "Quantitative Trading Strategies" from 2003 by Lars Kestner:

[ - - - ]
" The K-ratio is a unitless measure of performance that can be compared across markets and time periods. [ - - - ] Traders should
search for strategies yielding K-ratios greater than +0.50. Together, the Sharpe ratio and K-ratio are the most important
measures when evaluating trading strategy performance. Note: When I created the K-ratio in 1996, I thought I had created a
robust measure to evaluate performance. In mid-2000, trader Bob Fuchs brought a small error to my attention regarding the
scaling of the K-ratio. He was correct in his critique and I have corrected the error in this text. Publications prior to 2002 will
show a different formula for the K-ratio. The updated formula in this book is correct."

Mr Lars Kestner has corrected his formula based on this critique:

K-ratio = slope / ( sterr * per )

slope: Linear regression slope of equity line
sterr: Standard error of slope
per: Number of periods in the performance test

Special thanks to Jeremy Berkovits who brought that to my attention.

CHANGES FOR VERSION 4.54.0 (as compared to 4.53.1)

• "Allow mixed EOD/intraday data" mode added (controllable from File->Database Settings->Intraday, checkbox with the same name) it allows to work with database that has a mixture of intraday and EOD data in one data file. If this is turned on then in intraday modes EOD bars are removed on-the-fly and in daily mode EOD bars are displayed instead of time compressed intraday or if there is no EOD bar for corresponding day then intraday bars are compressed as usual.

This mode works in conjunction with new versions of plugins that allow mixed data. Mixed mode is now supported by MarketCast plugin (1.1 or higher)(Australia) and eSignal plugin (1.7.0 or higher) only.

Mixed mode allows intraday plus very long daily histories in one database.

Note that this is EXPERIMENTAL feature.

+ Real-Time quote window enhanced
Now only fields that are changed change the background to 'yellow' and if the value in given field increases then it is displayed in green if decreases then is displayed in red. This allows easy identification of movement.

+ all strings in the program moved to resources for easy localization

+ fixed problem with SetForeign()+FullName() returning symbol instead of full name of foreign security.

+ added new AFL function IsContinuous() to check if "continuous" flag is turned on in Symbol->Information window

+ OLE properties can be retrieved (DISPATCH_PROPERTYGET) directly from AFL now using parameterless function syntax. This allows reading values exposed by OLE automation directly from AFL code. Example:

AB = CreateObject("Broker.Application"); Stocks = AB.Stocks(); // get collection Stock = Stocks.Item( Name() ); // currently selected "FullName : " + Stock.FullName(); "Alias : " + Stock.Alias(); "Address : " + Stock.Address(); "Shares: " + Stock.Issue(); "Book value: " + Stock.BookValue(); "Market : " + Stock.MarketID(); "WebID : " + Stock.WebID();

You can check if OLE object is valid by calling IsNull() function, example:

AB = CreateObject("Broker.Application"); Stocks = AB.Stocks(); // get collection Stock = Stocks.Item( "INTC" ); if( IsNull( Stock ) ) {   printf("COM object invalid (Null) - symbol does not exist\n"); } else {   printf("COM object valid - you can access its methods\n"); }  

+ IsEmpty/IsNull and IsTrue functions operate with scalars and OLE dispatches without upsizing them to array

CHANGES FOR VERSION 4.53.1 (as compared to 4.53.0)

• addressed problem with broker.layers file. Now version 4.53.1 correctly reads broker.layers file saved with older versions however note that old versions are not compatible with new format.
• layer properties dialog provides more comfortable setting of layer visibility
• other minor fixes

CHANGES FOR VERSION 4.53.0 (as compared to 4.52.0)

• per-group intraday settings (filtering/daily compression) Use Symbol->Categories: "GROUP" -> Use own intraday settings, click
on "Intraday settings" button to define intraday settings specific to given group.
• intraday settings now allow to specify separate day (RTH) and night (ETH) sessions
• time filtering now allows to display:
a) 24 hours trading (no filtering)
b) day session only
c) night session only
d) day and night sessions only
• new intraday time compression mode: Day/Night - shows two bars (day and night) per day
• daily compression can be now based on
a) exchange time (available since 4.00)
b) local time (available since 4.50)
c) day/night session times definable by the user (new)
• when "activatestopsimmediately" is turned ON then cash from stopped out positions is NOT available to enter trades the same day
• Workspace tree supports in-place editing of market, group, sector, industry and watch list names. Single click on category name and just enter the name

CHANGES FOR VERSION 4.52.0 (as compared to 4.51.1)

• fixed problem with fixup=0 and handling multiple data holes in a row
• added new commands to ASCII format definitions:
$MINTICKERLEN <number> - defines minimum accepted length of the ticker symbol$MAXTICKERLEN <number> - defines maximum accepted length of the ticker symbol
For example ASX users may wish to use
$MAXTICKERLEN 3 to make sure that ASCII importer accepts only symbols that have no more than 3 characters (this excludes ASX options and warrants) • fixed problem with incorrect very first value of the array returned by variable-period version of HHV/LLV • fixed Procedure/function parameter overwrite issue when using built-in price arrays and variable overwrite issue • memory allocated for return value is marked for earlier freeing so calling user-defined functions inside loops should consume less memory • Interval() function enhanced. Now accepts format parameter: Interval( format = 0 ); possible values: 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" • vertical quote selection line in linked windows is now independent • changing "same day stops" via SetOption("ActivateStopsImmediately") in portfolio backtest mode has an effect now (previously reacted only on manual settings) • SetOption("CommissionMode", mode ) works now in portfolio mode too (previously worked in old backtest mode only) • SetOption("CommissionAmount", amount ) works now in portfolio mode too (previously worked in old backtest mode only) •$SEPARATOR command in ASCII importer definitions now allows to import files that have fields separated by more than one separator characters Separator string (array of characters) must be enclosed in quotation marks. If there is only one separator character (as in old versions) then quotation marks are needed.
For example files with joined date and time

$SEPARATOR ", "$FORMAT DATE_YMD,TIME,OPEN,HIGH,LOW,CLOSE

will be able to import file like this:
2004-02-04 12:30,3.41,3.44,3.40,3.42
(note date and time field are separated by space not by comma)
• Import wizard now supports new separators 'comma or space', 'semicolon or space' and 'tab or space'
• ASCII importer and Quote Editor properly
distinguish records with time specified as 00:00:00 from EOD records (without time)

CHANGES FOR VERSION 4.51.1 (as compared to 4.51.0)

• OLE interface methods numbering adjusted to maintain backward compatibility with previous versions and other programs referring to old OLE interface

CHANGES FOR VERSION 4.51.0 (as compared to 4.50.10)

• OLE automation interface changes:

Analysis.Backtest and Analysis.Optimize now support new "Type" parameter.
Type can be one of the following values:
0 : portfolio backtest/optimize
1 : individual backtest/optimize
2 : old backtest/optimize

For backward compatibility Type parameter is optional and defaults to 2
(old backtest/optimize)

Example code:

AB = new ActiveXObject("Broker.Application");
AB.Analysis.Backtest( 0 ); // perform portfolio backtest
AB.Analysis.Optimize( 0 ); // perform portfolio optimize

• OLE automation interface new object: "Commentary"

This object has 5 methods:
- BOOL SaveFormula( STRING pszFileName ) - saves the formula
- void Apply() - displays the commentary
- BOOL Save( STRING pszFileName ); - saves commentary output (result) to the file (use after call to Apply())
- void Close() - closes the commentary window

Commentary object is accessible from Broker.Application object via Commentary property:

Example code:

AB = new ActiveXObject("Broker.Application");
AB.Commentary.Apply();
AB.Commentary.Save("Test.txt");
AB.Commentary.SaveFormula("MACDTest.afl");
//AB.Commentary.Close();

• AFL function Now( format = 0 ) accepts new parameter values

Returns current date / time in numerous of formats:
// formats supported by old versions
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
// new formats available from version 4.51
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 1=Sunday, 2=Monday, and so on)
format = 10 - returns current DAY OF YEAR (1..366)

• Custom indicators:
If plot name is empty the value of such plot does not appear in the title
and does not appear in the data tool tip

Plot( C, "Price", colorWhite, styleCandle );
Plot( MA( C, 10 ), "", colorRed ); // NOTE that this plot name/value will NOT appear in the title
Plot( MA( C, 20 ), "MA20", colorGreen );

• SetOption( "field", value )
accepts new fields:
"CommissionMode" -
0 - use portfolio manager commission table
2 - $per trade 3 -$ per share/contract

"CommissionAmount" - amount of commission in modes 1..3

"MarginRequirement" - account margin requirement (as in settings), 100 = no margin

"ReverseSignalForcesExit" - reverse entry signal forces exit of existing trade (default = True )

• new AFL function: GetOption( "field" ) - retrieves the settings, accepted fields the same as in SetOption.

Example:

PositionSize = -100 / GetOption("MaxOpenPositions");

• new AFL function: GetRTData( "field" )
- retrieves the LAST (the most recent) value of the following fields
reported by streaming real time data source )
(Note 1: this function is available ONLY in PROFESSIONAL edition,
calling it using Standard edition will give you NULL values for all fields)
(Note 2: works only if data source uses real time data source (plugin) )
(Note 3: availablity of data depends on underlying data source
- check the real-time quote window to see if given field is available )
(Note 4: function result represents the current value at the time of the call
/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
way more often (at least 10 times per second) )

Supported fields:
"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
"OpenInt" - current open interest
"Prev" - previous day close
"TotalVolume" - total today's 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

Example:
"Bid = "+GetRTData("Bid");
"Last = "+GetRTData("Last");

"EPS = "+GetRTData("EPS");
"52week high = "+GetRTData("52weekhigh");

• Custom indicators:
Default names and graph values appear in the title
when using old-style graph0, graph1, graph2 statements in the custom indicators

CHANGES FOR VERSION 4.50.5 (as compared to 4.50.4)

• very minor fixes and cosmetics

CHANGES FOR VERSION 4.50.4 (as compared to 4.50.3)

• portfolio report now shows "N/A" instead of -1#INF and similar strange looking things that appeared when there were no trades (division by zero)
• removed the extra 'z' letter in fprintf formatting sequence (that caused crash on exit when saving params)
• correct column type (alpha) is set for the first column in individual backtest
• 'show current trade arrows' works OK after portfolio backtest
• when timeshift is not equal zero in intraday databases then DateNum(), Day(), Month(), Year(), DayOfWeek() and DayOfMonth() functions adjust date (day) when bar time is 'shifted' outside 0..24 hour range.
• rotational mode: all OHLC fields in artificial future bar are filled with close price of last bar for consistency with regular mode and to prevent problems with stops hit on artificial future bar in rotational mode.

CHANGES FOR VERSION 4.50.3 (as compared to 4.50.2)

• the formula names with dash '-' character are now properly displayed in the reports
• fixed problem with Equity/SetForeign (introduced in 4.50)
• MAE/MFE charts X-axis layout improved
• new report - trade list: profit, pos. size, cum. profit and profit/bar columns use fixed format with 2 decimal places now (no scientific format)
• EnableTextOutput() works again (thx. Greg)
• fixed rounding in Stock.NominalValue
• other minor fixes:
+ better CRC calculation method for #include
+ sellprice/coverprice are written back with updated prices for stops in case of Equity(1)
+ fixed menu-button owner draw painting code (thx. Herman)
+ progress window is displayed in single-stock optimization with new backtester too

CHANGES FOR VERSION 4.50.2 (as compared to 4.50.0)

• fixed problem with 'exit date' showing in fact 'entry date' in trade list (problem introduced in 4.50.0)
• fixed crash @0x482898

CHANGES FOR VERSION 4.50.0 (as compared to 4.49.0)

• old backtester uses now also "MinShares" Setting, so it will not enter trade with share position size lower than 'min. shares'. Due to this change. 'min. shares' setting has been moved from 'Portfolio' to 'General' setting page.
• changed handling of open positions in old backtester to match with portfolio backtester and equity plot:
- exit commissions are taken from open position profit (previously they were not taken)
- open positions are closed always at CLOSE price (previously were closed at trade price)
• LineArray( x0, y0, x1, y1, extend = 0, usebarindex = False )
- has new parameter (usebarindex) - False by default that switches allows to specify x parameters as bar Indexes (as returned by BarIndex() function).
• fixed problem with displaying exploration results having more than 100 columns
• portfolio backtests/optimizations should be 2x faster on average (* excluding scanning phase)
• layout of AA window changed. Now (new) PORFOLIO backtest and PORTFOLIO optimize modes are default and available from "Backtest" and "Optimize" buttons. Other modes are available from drop down menus added to "Backtest" and "Optimize" buttons. Portfolio report is no longer automatically displayed after portfolio backtest. Please click "Report" button to display it. The same applies to portfolio equity.
• layout of settings page changed. Old backtester settings moved to 'old' page.
• new "individual backtest" mode: allows to run new backtester separately on each symbol in the selected "apply to" group. (Replaces old backtester functionality in testing multiple stocks and provides new reports)
• settings and formula used are automatically saved after portfolio backtests
• new reports are now divided into separate pages: Statistics, Charts, Trades, Formula, Settings, Symbols
• each backtest report is now automatically stored "Reports" subfolder of AmiBroker directory. The results.rlst holds tab separated list of all backtests results while corresponding subdirectories hold reports of backtest. REMEMBER to delete old reports periodically (using Report Explorer), otherwise your hard disk would fill up!
• New add-on program (free) included: Report Explorer that allows to browse / sort / view / delete results of backtests.
Available from AA window Report -> Report Explorer.
• new AFL function:
SetFormulaName( string )
allows to programatically change the name of the formula that is displayed in the backtest result explorer
• fixed cases when GetChartID() used in AA did not return zero
• Window->Clone has been renamed to Window->New Linked to better describe its function
• other minor fixes

CHANGES FOR VERSION 4.49.0 (as compared to 4.48.2)

• new Percentile function

Percentile( array, period, rank )

rank is 0..100 - defines percentile rank in the array

Example:
Volume > Percentile( Volume, 100, 70 );

means: current day volume ranks within TOP 30% of volumes of last 100 bars (is above 70th percentile)

Volume < Percentile( Volume, 100, 30 );
means: current day volume ranks within BOTTOM 30% of volumes of last 100 bars (is below 30th percentile)

(performance note: the implementation of percentile function involves sorting that is relatively slow process even though that quicksort algorithm is used)
• new function

LineArray( x0, y0, x1, y1, extend = 0 )

generates array equivalent to trend line drawn from point x0, y0 to point x1, y1. x coordinates are in bars (zero based), y coordinates are in dollars Note: x0 must be SMALLER than x1. Note 2: the function accepts only numbers therefore
generates single line. To produce multiple lines you have to call it many times with different co-ordinates.
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

Example:
y0=LastValue(Trough(L,5,2)); y1=LastValue(Trough(L,5,1)); x0=BarCount - 1 - LastValue(TroughBars(L,5,2)); x1=BarCount - 1 - LastValue(TroughBars(L,5,1)); Line = LineArray( x0, y0, x1, y1, 1 ); Plot(C, "C", colorWhite, styleCandle); Plot( Line, "Trend line", colorBlue );
• new function sign( x )
(x can be number or array).
Returns 1 if x is positive, returns -1 if x is negative, and returns 0 if x is zero.
• ApplyStop : 'exitatstop' parameter extended:
ApplyStop( Type, Mode, Amount, ExitAtStop = 1, Volatile = False, ReentryDelay = 0 )

ExitAtStop = 0 - means check stops using only trade price and exit at regular trade price
(if you are trading on close it means that only close price will be checked for exits and exit will be done at close price)
ExitAtStop = 1 - check High-Low prices and exit intraday on price equal to stop level on the same bar when stop was triggered
ExitAtStop = 2 - check High-Low prices but exit NEXT BAR on regular trade price.

( first two modes 0 and 1 are the same as in old versions )

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

Scenario 2:
you trade on today's close and want to exit intraday on stop price
Correct settings:
ActivateStopsImmediately turned OFF
ExitAtStop = 1

Scenario 3:
you trade on next day OPEN and want to exit by stop on OPEN price when PREVIOUS day H-L range hits stop
Correct settings:
• (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

ExitAtStop = 2 (NEW)

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
• portfolio backtester: MAE/MFE are now updated with exit price in case when profit has been hit intraday and activate stops immediatelly was turned off.
• portfolio backtester: 'activate stops immediately'=TRUE and 'same bar exit'=FALSE combination works OK now
• 'auto-tile windows' feature now tiles windows only it two cases:
- when new window is open
- when RT quote window is shown/hidden
• in versions 4.48.0-4.48.2 cloned windows were sometimes saved in two or more copies, now it is fixed. This bug caused also crashes when switching layouts. Fixed.
• portfolio backtester now allows custom exit labeling as old backtester
• fixed range unmarking by double click in cloned windows
• all listviews now use alternate background colors for odd/even rows this feature can be turned off using Tools->Preferences->Miscellaneous "Use alternate row colors"

CHANGES FOR VERSION 4.48.2 (as compared to 4.48.1)

• once more changed slightly HTML copy routine and turned it off by default
• added a switch to Tools->Preferences->Editor that allows to turn "Copy as HTML" feature on, on those machines having no problems (like mine)

CHANGES FOR VERSION 4.48.1 (as compared to 4.48.0)

• Changed code that copies HTML format from AFL editor to clipboard. (this hopefully will address problems with pasting on some machines)
• MFE/MAE distribution charts are now available in Professional Edition only
• zooming is now independent in cloned windows

CHANGES FOR VERSION 4.48.0 (as compared to 4.47.0)

• window linking with different bar interval works now.
Just use Window->Clone menu ... this will create a clone of currently selected window. The difference from previous version is that you can now select different interval for this cloned window. Cloned windows are numbered. You can have infinite number of cloned windows and they are linked within group (change symbol in one window causes change in every linked window) but the viewing interval is independent.
• cloned windows are now properly saved in a layout. (note that format has changed slightly and you may get problems
trying to load into old version the layout saved with NEW version)
• portfolio backtester: added support for backtesting futures
• portfolio backtest report:
+ added MAE distribution chart (Pro version only)
+ added MFE distribution chart (Pro version only)
• ApplyStop / ExitAtStop=False feature in rotational mode works as in regular mode now (checks only trade price for stops, not H-L range. H-L is checked when ExitAtStop is True)
• AFL Editor - Edit->Copy puts "HTML Format" and "DwHt" (Dreamweaver HTML format) into clipboard in addition to TXT and RTF formats. This provides ability to paste nicely formatted codes directly into Outlook Express and Macromedia Dreamweaver

CHANGES FOR VERSION 4.47.0 (as compared to 4.46.3)

• in regular detailed log does not show more than 2 * MaxOpenPositions top ranked entry (buy/short) signals since anyway they won't ever be entered.
• Regular mode: "Max # of tracked signals" setting removed. Now _all_ exit signals are tracked.
• fixed offset in day numbers returned by DayOfWeek() function for dates prior to 1970
• added InterestEarning calculation to Portfolio backtest
• now single bar 'long side' and 'short side' exposure is calculated as value of long positions and short positions (respectively) divided by overall equity value. (previously it was divided by long equity / short equity value but it caused problems for systems that were constantly loosing on short side causing that short side dropped below zero)
• other minor fixes

CHANGES FOR VERSION 4.46.3 (as compared to 4.46.2)

• thousand separator is removed automatically in StrToNum to prevent problems with conversion of numbers > 1000 when thousand separator is enabled
• fixed issue with rotational mode, entering other symbols when trade on top ranked symbol has been stopped and re-entry delay > 0
• detailed log mode does not affect drawdown calculation (previously it could result in slightly bigger drawdowns reported in 'detailed log' mode due to the fact that exit bar close was included in drawdown calculations even when exiting on open.)
• still open trades are listed in HTML report too.
• trade list in HTML portfolio report can be turned OFF using Settings: "Report", Trade list: <no trade list> setting.
(this setting page will be cleaned up at some point when there will be one backtester only).

CHANGES FOR VERSION 4.46.2 (as compared to 4.46.1)

• AA settings, switch: "Add artificial future bar" - now artificial future bar is has incremented date, volume set to zero and all prices (OHLC) set to CLOSE price of last available data bar. (this is done to prevent the closed-out value of open positions)
• new AFL function:
Median( array, period ) - finds median (middle element) value over period elements
• now trade list in portfolio mode displays reason for exit (if trade has been closed by stop)
• trade list is now included in the report
• rotational mode: profit target stop was broken, now it is fixed

CHANGES FOR VERSION 4.46.1 (as compared to 4.46.0)

• scoreNoRotate now works again
• small fix in regarding month boundary handling in "Use local time for daily compression" mode.
• AA settings, new switch: "Add artificial future bar". When checked AmiBroker adds tommorrow's bar and this enables you to see tommorrow's (or next bar) trade recommendations when your system uses one bar delay. Artificial future bar is a copy of last available data bar but has of course incremented date and volume set to zero.
• two functions (where present in 4.46.0 but not documented)
IsFavourite() - returns 'true' if current symbol belongs to favorites
IsIndex() - returns 'true' if current symbol belongs to index category

CHANGES FOR VERSION 4.46.0 (as compared to 4.45.0)

• New AFL functions
• added NumToStr as synonum of WriteVal (as this function did not 'write' anything, just returned string)
• added StrToNum( string ) - converts string to numbe
• added StrFind( string, substring ) - finds first occurrence of substring in string. returns 0 if not found, otherwise returns character index (one-based) of first occurrence
• added StrFormat( formatstr, ... ) that performs sprintf-like formatting and returns string
• CategoryGetName( category, number) function - returns name of category (market/group/sector/industry/watchlist)
• CategoryGetSymbols( category, number ) added - synonym to GetCategorySymbols
• CategoryAddSymbol( symbol, category, number ); - adds the symbol to given category, note that for markets, groups, industries 'adding' means moving from one category to another, since the symbol is assigned always to one and only one market, group, industry and sector. This limitation does not apply to watchlists, favorites, and index categories. When symbol string is empty ("") then current symbol is used.
• CategoryRemoveSymbol( symbol, category, number ); - removes the symbol to given category, note that for markets, groups, industries 'removing' means moving from given category to category with number zero, since the symbol is assigned always to one and only one market, group, industry and sector. This limitation does not apply to watchlists, favorites, and index categories. When symbol string is empty ("") then current symbol is used.
• added new AFL functions for output/file handling (almost exactly like in C run-time):
• printf( formatstr, ... ) - output formatted text to the commentary/interpretation (note 1: for numbers always use %f, %e or %g formatting, %d or %x will not work because there are no integers in AFL, note 2: as of now only numbers and arrays can now be printed. For arrays 'selected value' is printed)
• fopen( filename, mode ) - opens file, returns filehandle . Mode can be "r" - for reading, "w" for writing, "a" for appending (and all other regular C-runtime library modes)
• fclose( filehandle ); - closes file
• fputs( string, filehandle ) - puts (writes) string to file
• fgets( filehandle ) - gets (reads) string from file (returns string)
• feof( filehandle ) - detects end-of-file marker ( gives True - if end of file reached )
• PositionScore table is now shifted according to buy trade delay in regular mode too. (it was shifted so in rotational mode already). Caveat: make sure to set long and short delays to the same values if you are trading both long and short sides, otherwise only long trades get correct ranks. Note 2: PositionSize is not and was never shifted with trade delays
to allow code for purchasing N stocks working with any delay, example PositionSize = 5 * BuyPrice
• added new option to File->Database Settings->Intraday settings "Use local time for daily compression".
All previous versions used exchange or data vendor time to do build daily bars (this means that regardless of your time shift settings daily bars looked the same because they used exchange or data source time (for example if you are using QuoteTracker it was US EST time) - this caused problems for Australian users using QuoteTracker as data source because QuoteTracker reported ASX quotes with US time that lead to invalid daily bars. Now if you check "Use local time for daily compression" AmiBroker will use your local time (according to 'time shift' setting) to build daily bars. Note that switching this on means that daily bars may look different when you change time zone (i.e. time shift setting)
• ASCII importer: support for importing unadjusted Yahoo data performing adjustment on the fly:
• new field ADJCLOSE - to read adj. close column from Yahoo. Works _only_ in conjunction with CLOSE field. When both CLOSE and ADJCLOSE are present in the ASCII format definition then importer calculates split factor by dividing ADJCLOSE/CLOSE. It then multiples OPEN, HIGH, LOW and CLOSE fields by this factor and divides VOLUME field by this factor. This effectively converts unadjusted prices to split adjusted prices. Split ratio gets locked once ADJCLOSE drops below 0.05.
• new command $ROUNDADJ decimaldigits - causes split-adjusted prices (see above) to be rounded to 'decimaldigits' precision. By default no rounding is done. • new command$RECALCSPLITS 1 - (off by default) causes that splits are recalculated by AmiBroker
by the algorithm that tries to construct correct adjusted price, based on inaccurate information provided by Yahoo.
Note that Yahoo provides only 2 decimal digits in adj. close field therefore the more adj. close approaches zero due to adjustements the error grows. The option $RECALCSPLITS 1 is intended to address this problem (at least partially). It works as follows: 1. for each bar ratio ADJCLOSE/CLOSE is calculated 2. if the ratio changes in two consecutive bars by more than 10% it means that split happened that bar. True split ratio is guessed by matching true fraction in the format of X/Y, where X and Y = 1..9, to the change in ratios. 3. Then true split ratio is used to adjust all past bars until new split is detected. • new command$RAWCLOSE2OI 1 - (off by default) - causes that OpenInterest field gets assigned CLOSE (raw close) field value multiplied by 100
• new aqh.format file included in "formats" subfolder using new ASCII importer commands to import and adjust prices from Yahoo. Compatible with existing AmiQuote versions.

CHANGES FOR VERSION 4.45.0 (as compared to 4.44.1)

• score of 999999 is no longer recognized. Use constant scoreNoRotate instead.
• UI simplification:
Rotational mode: separate settings for rotational mode trade price and delay and worst rank held have been removed.
Rotational mode now uses buy price and buy delay settings from "Trade" tab. You can also set delay from the code SetTradeDelays( 1, 1, 1, 1 ); will give you one bar delay. To set 'worst rank held' use SetOption function in your formula:
SetOption("WorstRankHeld", 5 );
• stops implemented in rotational trading mode (limitation: stops in rotational mode can only be static, they can not change
'stop amount' from symbol to symbol or from bar to bar like in regular mode)
• re-entry delay implemented for all kind of stops
• user interface added in the settings for n-bar stops
• ApplyStop function now takes 6 parameters:
ApplyStop( Type, Mode, Amount, ExitAtStop = True, Volatile = False, ReentryDelay = 0 )

CHANGES FOR VERSION 4.44.1 (as compared to 4.44.0)

• fixed problem with rotational mode, trading price: open

CHANGES FOR VERSION 4.44.0 (as compared to 4.43.2)

• fixed crash with 'detail mode' and large number of open positions/ranks used
• max. in-memory cache size can be set now to 20000 (please note that this large cache requires lots of RAM (more than 512MB))
• listview copy to clipboard feature now copies also column header names
• SetForeign( ticker, fixup = True, tradeprices = False) and
have new flag now: tradeprices (False by default) when tradeprices 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. Example: // your rules buy = ... sel = ... SetForeign("MSFT", True, True ); e = Equity(); // backtest on MSFT RestorePriceArrays( True ); // <- should match parameter used in SetForeign 
• Name(), FullName(), GetExtraData() work well with SetForeign() (i.e. give foreign name/data instead of currently selected)
• SetOption("PriceBoundChecking", False ); - disables checking and adjusting buyprice/sellprice/coverprice/shortprice arrays to current symbol High-Low range.
• % profit added to detailed log mode
• fixed bug in portfolio backtester occuring when 'allow same bar exit' was turned off and 'immediate stops' was turned on 2 buys and 2 sells occurred the in 2 bars in row
• Auto Analysis/Settings,setting modified "portfolio report mode: trade list/detailed log" moved to "report" tab
• Auto Analysis/Settings, rotational mode: added selection of trade price and trade delay to portfolio settings page
• Auto Analysis/Settings, portfolio backtester (both regular and rotational modes): added ability to pad and align all symbols to reference symbol. Note: by default this setting is OFF. Use responsibly. It may slow down backtest and introduce some slight changes to indicator values when your data has holes and holes are filled with previous bar data. The feature is intended to be used ONLY when your system uses general market timing (generates global signals based on data and/or indicators calculated using Foreign from 'reference' symbol). Note 2: if reference symbol does not exist, data won't be padded.
• Auto Analysis/Settings, report tab: added ability to define risk-free rates for Sharpe and Ulcer Performance Index calculations.
CHANGES FOR VERSION 4.43.2 (as compared to 4.43.0)
• backtester generates now error message when someone attempts to use buy/sell/short/cover signals in rotational mode
• column headings fixed in AA porfolio backtest report

CHANGES FOR VERSION 4.43.0 (as compared to 4.42.0)

• in regular backtest mode now it is possible to specify the score of the symbol (on bar-by-bar basis) via PositionScore variable. In this mode the score is used only at trade ENTRY to decide which securities should be traded in case when there are more simultaneous entry signals than max. allowable positions or available funds. AmiBroker will 'prefer' securities with higher absolute value of the score. If PositionScore is not used then it is assumed to be 1 for all securities. NOTE: regular mode must be used for all your backtesting except the cases when you want rotational-trading (fund switching). Only regular mode uses buy/sell/short/cover signals.
• rotational-trading mode must now be turned on by calling new EnableRotationalTrading() function at the top of your formula. AA / Settings / Portfolio:
1. Max. Traded renamed to more meaningfull "Max. Open Positions" - defines the maximum number of positions (trades) that can be open simultaneously (at any time)
2. Max. Ranked renamed to more meaningfull "Worst Rank Held" (rotational trading mode only) - must be equal or greater than max. open positions, if it is greater than Max. open positions then once a position is taken in a security it will not be exited until the ranking of that security drops below "Worst Rank Held"
• "Allow same day exit (single bar trade)" now affects Portfolio test too.
• SetOption() calls affect Portfolio backtest now added:
SetOption("MaxOpenPositions")
SetOption("WorstRankHeld")
SetOption("MinShares")
• fixed Avg Profit/Loss figures in "all trades" section of portfolio report
• added average PERCENT profit/loss figures
• internal accuracy of calculations of LinearReg, LinRegSlope, LinRegIntercept, StdErr, TSF raised from 32 bit floating point to 64 bit floating point
• fix: rotational trading mode does not enter position when score is 999999
• fixed column setup in AA
• other minor fixes
• as a temporary solution for people using Rx new version now uses HTMLView2.exe (that is shipped with the beta) to display the portfolio report.
CHANGES FOR VERSION 4.42.0 (as compared to 4.41.2)
• first (incomplete) early beta version of the portfolio backtester
• fixed plot of Null arrays using styleArea
• fixed display problem with % progress in single-stock optimization
• other minor fixes

CHANGES FOR VERSION 4.41.2 (as compared to 4.41.1)

• now Sum produces values for periods upto and including BarCount, so Sum( array, BarCount ) gives the value instead of Null
• fixed problem with saving parameters on exit when the user did not specify default value for string parameter using ParamStr("name", "")
• fixed 38-byte memory leak when returning values from user-defined functions
• real-time mode: after AFL syntax error commentary AFL editor is not refreshed until error is fixed and user presses 'apply'
• eSignal 1.6.0 plugin
(available separately from http://www.amibroker.com/bin/eSignal160.exe):
• much quicker backfills
• implemented force-reconnect feature in eSignal plugin
• fixed minor timing issue in eSignal plugin
• implemented workaround to invalid tick numbers sent sometimes by eSignal's data manager.
thanks to all users for reporting errors and helping ironing out outstanding issues.
CHANGES FOR VERSION 4.41.1 (as compared to 4.41.0)
• fixed chart refresh locking that happened when user was drawing some object and abandonend it by pressing ESC key.
• View->Refresh and View->Refresh All menus now reset internal chart refresh lock flag just in case.
• plugin status is refreshed more often
• maximum number of chart sheets increased to 60 (Caveat: when you increase the number of sheets you would not be able to use the layouts with OLDER versions of the software)
• TimeFrameSet() now affects result of Interval() AFL function. TimeFrameRestore() resets it back.
• Plot() makes copies of OHL arrays when styleCandle or styleBar is used so statements like
SetForeign("AAPL"); Plot( C, "Price", colorYellow, styleCandle ); SetForeign("MSFT"); Plot( C, "Price 2", colorBlue, styleCandle ); plot correctly. Previously one would need to use PlotOHLC() or PlotForeign()
• separate heap for syntax tree walker implemented, so larger AFL programs like PortfolioTrader should execute faster while retaining the speed improvement gained in 4.40.4 for small formulas.

CHANGES FOR VERSION 4.41.0 (as compared to 4.40.4)

• legacy 'stoch()' function removed. Use StochK and StochD instead.
• weekly / monthly charts are not affected by intraday compression settingsin preferences any more and always use last available day date for time stamp of time-compressed bar.
• Pref: Misc: auto-hide timeout field: added check for allowed values from 1...32
• TimeFrameSet( interval ) function implemented
- replaces current price/volume arrays: open, high, low, close, volume, openint, avg with time-compressed bars of specified interval once you switched to a different time frame all calculations and built-in indicators operate on selected time frame. To get back to original interval call TimeFrameRestore() funciton.
• TimeFrameRestore()
- restores price arrays replaced by SetTimeFrame. Note that only OHLC, V, OI and Avg built-in variables are restored to original time frame when you call TimeFrameRestore(). All other variables created when being in different time frame remain compressed. To de-compress them to original interval use TimeFrameExpand
• TimeFrameCompress( array, interval, mode = compressLast )
- compresses single array to given interval using given 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 values of the array within interval
• TimeFrameExpand( array, interval, mode = expandLast )
- expands time-compressed array from 'interval' time frame
('interval' must match the value used in TimeFrameCompress or TimeFrameSet)
Available modes:
• expandLast - the compressed value is expanded starting from last bar within given period (so for example weekly close/high/low is available on Friday's bar)
• expandFirst - the compressed value is expanded starting from first bar within given period
(so for example weekly open is available from Monday's bar)
• expandPoint - the resulting array gets not empty values only for the last bar within given period (all remaining bars are Null (empty))
Caveat: expandFirst used on price different than open may look into the future.
For example if you create weekly HIGH series, expanding it to daily interval using expandFirst will enable you to know on MONDAY what was the high for entire week.

graph0 = TimeFrameExpand( TimeFrameCompress( Close, inWeekly, compressLast ), inWeekly, expandLast ); graph1 = TimeFrameExpand( TimeFrameCompress( Open, inWeekly, compressOpen ), inWeekly, expandFirst ); 
• TimeFrameGetPrice( pricefield, interval, shift = 0, mode = expandFirst );
- references OHLCV fields from other time frames.
This works immediatelly without need to call TimeFrameSet

TimeFrameGetPrice( "O", inWeekly, -1 ) - gives you previous week OPEN price
TimeFrameGetPrice( "C", inWeekly, -3 ) - gives you weekly Close price 3 weeks ago
TimeFrameGetPrice( "H", inWeekly, -2 ) - gives you weekly High price 2 weeks ago
TimeFrameGetPrice( "O", inWeekly, 0 ) - gives you this week open price.
TimeFrameGetPrice( "H", inDaily, -1 ) - gives previous day high when working on intraday data
Price field is one of the following
"O", "H", "L", "C", "V", "I" (open interest)

Shift works as in Ref() function but it is applied to compressed time frame.
Note these functions work like these 3 nested functions
TimeFrameExpand( Ref( TimeFrameCompress( array, interval, compress(depending on field used) ), shift ), interval, expandFirst )
therefore if shift = 0 compressed data may look into the future ( weekly high can be known on monday ). If you want to write a trading system using this function please make sure to reference PAST data by using negative shift value.
The only difference is that TimeFrameGetPrice is 2x faster than nested Expand/Compress.
• new interval / timeframe constants:
in1Minute = 60
in5Minute = 5 * 60
in15Minute = 15 * 60
inHourly = 3600
inDaily = 24 * 3600
inWeekly = 5 * 24 * 3600
inMonthly = 25 * 24 * 3600
compressLast = 0
compressOpen = 1
compressHigh = 2
compressLow = 3
compressVolume = 4

expandLast = 0
expandFirst = 1
expandPoint = 2
• SetForeign( 'ticker' )
- replaces current price/volume arrays with those of foreign security, returns True if ticker exists, False otherwise.
If ticker does not exist (and function returns false) price arrays are not changed at all.
Equivalent to the following sequence:
C = Foreign( "ticker", "C" ); O = Foreign( "ticker", "O" ); H = Foreign( "ticker", "H" ); L = Foreign( "ticker", "L" ); V = Foreign( "ticker", "V" ); OI = 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();

EXAMPLE:
SetForeign( "MSFT" ); dm = MACD(); // dm holds MACD of MSFT regardless of currently selected symbol RestorePriceArrays(); Plot( dm, "MACD of MSFT", colorRed ); Plot( MACD(), "MACD of " + Name(), colorBlue ); 
• RestorePriceArrays();
restores arrays overwritten by SetForeign/TimeFrameSet

CHANGES FOR VERSION 4.40.3 (as compared to 4.40.2)

• Stochastic Slow has now separate settings for %K and %D slowing inTools->Preferences->Indicators
• StochK and StochD AFL functions now provide new parameters for control over smoothing
StochK( range = 14, Ksmooth = 3 );
StochD( range = 14, Ksmooth = 3, Dsmooth = 3 );
• other minor fixes
(hangup when rescaling Y-axis in log mode)
(improved display of value labels for very low values)
(Tools->Preferences->Main chart VAP: "none" works again)
• HTMLView.exe is launched with the file name parameter enclosed in double quotation marks to ensure correct work even if Windows TEMP path contains spaces
• Database Setting dialog now displays approximate number of days refering to given number of bars selected
• AmiBroker now warns the user (once) about using non-certified 3rd party plugins
• AFL parser now notifies user about missing argument in statement like Ref(,-4); (missing 1st argument)
• when error occurs inside commentary formula then error message is displayed in commentary output window instead of popup error dialog
• study properties dialog now uses modern color picker
• added "Troubleshoot" button to crash recovery window that links to http://www.amibroker.com/troubleshoot.html
CHANGES FOR VERSION 4.40.2 (as compared to 4.40.1)
• garbage collector improvement: memory allocated by single-argument math functions
(ABS, ATAN, CEIL, COS, EXP, FLOOR, FRAC, INT, LOG, LOG10, ROUND, SIN, SQRT)
applied to arrays is freed as soon as possible. (Previously it was released at the formula execution end)
• added new settings to VAP (Tools->Preferences->Main chart), allow you to change the style of histogram (line/area fill) and location (on top of all plots or behind of all plots)
• PlotVAPOverlay now has ability to control style and location
PlotVAPOverlay( lines = 300, width = 5, color = colorGreen, vapstyle = 0 );
where
vapstyle = 0 - right side, area fill, on top of all plots
vapstyle = 1 - left side, area fill, on top of all plots
vapstyle = 2 - right side, lines only, on top of all plots
vapstyle = 3 - left side, lines only, on top of all plots
vapstyle = 4 - right side, area fill, behind all plots
vapstyle = 5 - left side, area fill, behind all plots
vapstyle = 6 - right side, lines only, behind all plots
vapstyle = 7 - left side, lines only, behind all plots Demo formula (move 'style' slider to see all combinations): Plot( Close, "Price", colorWhite, styleCandle );
PlotVAPOverlay( Param("lines",300,10,1000,1), Param("width",10,1,99,1), ParamColor("color", colorDarkBlue), Param("style",0,0,7,1) );

• the AA formula is not copied to equity indicator when there is a syntax error in it
• added ability to stop parsing of AFL formula on first (syntax) error (switchable via Tools->Preferences->AFL: Stop parsing on first error)
• when AFL formula has syntax error, AA does not display warnings about missing buy/sell variables, because anyway the error has to be corrected first.
• added protection against overflowing maximum length of indicator title (now 2048 characters)
• other minor fixes
CHANGES FOR VERSION 4.40.1 (as compared to 4.40.
• added ability to minimize progress window. If progress window is minized then the window 'owning' it is HIDDEN. So for example if you minimize AA scan progress window then Automatic analysis window will be HIDDEN. To re-show simply maximize progress
• added Volume-At-Price (VAP) histogram chart overlay to price chart added new settings for VAP to Tools->Preferences->Main price (to turn it off go to Tools->Preferences : Main chart,
and set "Volume At Price overlay" to "None"
PlotVAPOverlay( lines = 300, width = 5, color = colorGreen, rightside = False);
that plots Volume-At-Price (VAP) overlay chart.
Please note that 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
Example:
Plot( Close, "Price", colorBlack, styleCandle );
PlotVAPOverlay( 350, 4, colorYellow, True );
Example 2:
Plot( Close, "Price", colorBlack, styleCandle );
PlotVAPOverlay( Param("lines",300,10,1000,1), Param("width",10,1,99,1), ParamColor("color", colorYellow), Param("mode",0,0,1,1) );
• fixed 'X' close button in Param window.
• Parameters window now shows parameter list in alphabetical order
• fixed problem with plotting zero values at log scale. Note that Log( 0 ) is minus inifinity and it really can not be plotted, however many people attempted to plot zero data in log scale, so AMiBroker now adjusts zero to 0.0001 when log scale is used to allow plotting.
Example faulty code that did not work in 4.40, but works now:
Plot(IIf(Month() != Ref(Month(),-1),1,0),"", color, styleHistogram | styleOwnScale | styleNoLabel)
• added new setting to Tools->Preferences : Charting "draw vertical line between months"

CHANGES FOR VERSION 4.40.0 (as compared to 4.39.0)

• fixed crash when global or local keyword was used elsewhere than on top of the function definition
• fixed crash that occurred when interpretation code part required more bars than indicator code part
• fixed handling of 1st hour after midnight in Metastock plugin / intraday data
• fixed problem with calling the same user-defined function multiple times in single simple arithmetic expression.
• memory allocated by Equity(0) was freed at the end of the formula execution, now it is freed immediatelly, making possible to create large loops with Equity(0) without memory problems. Note that Equity(1) and Equity(2) released memory immediatelly already.
• when Y-axis grid spacing is lower than or equal to 0.02 then Y axis is displayed with 4 decimal digits (usefull for currencies)
• logarithmic scaling improved, Y-scale shifting and zooming in log scale works better too.
• fixed date column formatting when SetOption("nodefaultcolumns", flag) is switched off and back on
• Param()s in Indicator Builder are set back to defaults only when formula is edited, setting grid line/scalling options do not reset params.
• time compression algorithm modified, now alignment is available in two options:
1. align to midnight (00:00:00) 2. align to trading hours START time
and four time stamp display modes:
1. display time of first tick in bar, 2. display time of last tick in bar
3. display start time of interval bar, 4. display end time of interval bar
These settings are available in Tools->Preferences->Intraday
Fixed also problems with alignment occurred in some cases in previous versions.

CHANGES FOR VERSION 4.39.0 (as compared to 4.38.0)

• added Param dialog to AA window. Note that AA-defined parameters are reset back to defaults only when you LOAD the formula from the file or when you click on 'Reset' button in Parameter dialog.
• colorAqua now has correct value of 36
• when Printing charts (or using Print Preview ) in Real Time mode,
auto-refresh is temporarily disabled to avoid problems with printing
• fixed problem with non-updating last bar of trade arrays by Equity(1)
applied in exploration when built-in trade delays where greater than zero
• operands of arithmetic expressions are evaluated from left to right again (as it was in 4.30) so statements like this
(y = 7)*1000 + y;
(note assignment within expression) do not cause error messages about uninitialized variable
• new feature "Wait for Backfill" in Auto-Analysis window. Causes scans/explorations/backtests
to wait for the plugin to finish data backfill.
The setting applies to real-time plugins only, and only to those that support
this feature.
• three new versions of plugins that support 'wait for backfill' feature are included in the beta archive:
eSignal plugin 1.5.0
myTrack plugin 1.5.3
IQFeed plugin 1.3.1

'Wait for backfill' feature is not supported by QT plugin, and it won't be supported because
QuoteTracker has no interface to allow forcing backfills from 3rd party applications.
• other minor fixes

CHANGES FOR VERSION 4.38.0 (as compared to 4.37.0)

• new setting for candlestick appearance:
Tools->Preferences->Charting
"Use distinct color for" : "None, up candle hollow" -
it plots entire candle with one color but leaves interior of UP candle body hollow.

• added export chart image to PNG (portable network graphics) file
Edit->Image->Export to PNG file
(Please don't ask me to add GIF support. GIF is patented and requires 3500 license fee for Unisys. PNG is free, supported by all browsers, smaller and better ) • added 'send chart by e-mail' feature Edit->Image->Send by email and File->Send chart via e-mail • fixed positioning of arrows in image copies (Edit->Image->Copy) • fixed crash occurring when printer device context did not support bit blit copies. added very simple arrow line drawing for that case (will be improved in future releases) • fixed bug in handling Null with new constructs: if, while and for. In pre-4.38 versions Null used in if, while for was treated as True, which was wrong if( Null ) _TRACE("WRONG"); else _TRACE("CORRECT"); Now Null in if, while, for is treated as False. • numbers (floats) are now automatically 'upsized' to arrays on first use of l-value array subscript operator without causing error. Also r-value subscript can be applied to numbers and return the number itself without causing error, but the underlying variable remains just a single number. This allows to easily intialize arrays to any value without need to write loops. Example 1: in previous versions you would need to write: for( i = 0; i < BarCount; i++ ) myarray[ i ] = 0 ; // fill with zeros myarray[ 5 ] = 6; // write value to 5th element of the array now you can write simply: myarray = 3; // initialize, at this moment myarray is just a number myarray[ 5 ] = 6; // write value to 5th element of the array, the variable is automatically // upsized to array and all elements are filled with a numeric value // that was originally placed in myarray variable /* myarray is holds now the array filled with values of 3 except element 5 that has value of 6 */ mynumber = 5; test = mynumber[ 7 ]; // previous versions would give an error message here // now subscript operator for r-value numeric variable // is allowed and returns just the number // and variable is not upsized to array unless appears on left side // of assignment (l-value) /* mynumber variable here is still a number */ WriteVal( test ); CHANGES FOR VERSION 4.37.0 (as compared to 4.36.0) • printing improved, now all open indicator panes are printed and resolution is increased • Edit->Copy As Image and Edit->Copy As Metafile now generate an image consisting of all indicator panes (not just one) • fixed problem with non-resetting sort arrows in AA window • fixed sometimes occuring crash Signal() function • increased size of error message text buffer to prevent overflow when reporting syntax errors in formulas having long unwrapped lines. • grid lines are drawn with fine dots instead of small dashes (screen output only) • new AFL functions: GetCategorySymbols( category, index ) - retrieves comma-separated list of symbols belonging to given category supported categories: categoryMarket categoryGroup categorySector categoryIndustry categoryWatchlist categoryFavorite categoryIndex index = (market/group/industry/sector/watchlist number) 0..255 for categoryMarket, categoryGroup, categoryIndustry 0..63 for categorySector, categoryWatchlist ignored for categoryFavorite, categoryIndex StrExtract( list, item ) - extracts given item (zero-based) from comma-separated string. Example: StrExtract( "MSFT,AAPL,AMD,INTC", 2 ) will return AMD StrExtract( "MSFT,AAPL,AMD,INTC", 0 ) will return MSFT StrExtract( "MSFT,AAPL,AMD,INTC", 200 ) will return empty string "" + other minor fixes Example code for GetCategorySymbols and StrExtract: /* note: if given watch list contains lots of symbols ** performance may be poor */ function CreateAverageForWatchList( listnum ) { // retrive comma-separated list of symbols in watch list list = GetCategorySymbols( categoryWatchlist, listnum ); Average = 0; // just in case there are no watch list members for( i = 0; ( sym = StrExtract( list, i ) ) != ""; i++ ) { f = Foreign( sym, "C" ); if( i == 0 ) Average = f; else Average = Average + f; } return Average / i; // divide by number of components } Plot( CreateAverageForWatchList( 1 ), "Avg of WL 1", colorGreen ); CHANGES FOR VERSION 4.36.0 (as compared to 4.35.0) • fixed problem with affecting 2 or more identifiers referencing the same array when using l-value subscript operator []. Thanks Herman for pointing this out • global and local keywords - for explicit visibility/scope declarations Allow to override default scope rules that assume that variables defined outside function are global, while those identifiers that appear for the first time inside functions are local. Syntax: local var1 [, var2, ... ] ; global var1 [, var2, ... ] ; (as you can see you can declare more than one variable in one line. Note: using these keywords outside function definition has no meaning (global scope is used). Example: VariableA = 5; // implict global variable function Test() { local VariableA; // explicit local variable with the same identifier as global global VariableB; // explicit global variable not defined earlier // may be used to return more than one value from the function VariableA = 99; VariableB = 333; }   VariableB = 1; // global variable "Before function call"; "VariableA = " + VariableA; "VariableB = " + VariableB;  Test();  "After function call"; "VariableA = " + VariableA + " (not affected by function call )"; "VariableB = " + VariableB + " (affected by the function call )"; • syntax highligting modified so keywords: #include, if, else, while, do, function, procedure, global, local, return are colorised differently than built-in constants or functions. Corresponding color/style setting added to Preferences->Editor • #pragma nocache pre-processor command added to switch off #include file caching mechanism. Note: between '#pragma' and 'nocache' there must be exactly SINGLE space Note 2: disabling caching may slow down execution of the formula (especially in indicators) Note 3: #pragma nocache must be placed before #includes Example: #pragma nocache #include <myfile.afl> • single line comments now work with #includes (and #pragma too) so you can comment out include in regular way: //#include <something> - will not include • changed error message from "unknown identifier" to "Variable 'name' used without having been initialized." which better decribes the problem. For example: function Test( ) { global x; x = 3; }  WriteVal( x ); // variable used without having been initialized, // although declared inside Test() function body   Test( ); // during function call the value of 3 is assigned to variable x  WriteVal( x ); // and now no error is reported • implemented shortcut evaluation of logical operators The operands of logical-AND and logical-OR expressions are evaluated from left to right. Now if the value of the first operand is sufficient to determine the result of the operation, the second operand is not evaluated. This is called “short-circuit evaluation.” The left operand of the logical-AND operator is completely evaluated and all side effects complete before continuing. If the left operand evaluates to false (0), the other operand is not evaluated. The left operand of the logical-OR operator is completely evaluated and all side effects complete before continuing. If the left operand evaluates to true (nonzero), the other operand is not evaluated. (The above description applies to operands that evaluate to single boolean value, it does not apply to arrays. Operands that evaluate to arrays are evaluated always ) Example: for( i = -3; i < BarCount; i++ ) { // using old versions of AMiBroker you would get subscipt out of range // but now // the second operand (C[ i ] > C[ i - 1 ]) is evaluated // ONLY if first operand ( i >= 1 ) evaluates to TRUE  if( i >= 1 && C[ i ] > C[ i - 1 ] ) { _TRACE("TEST " + i); } } CHANGES FOR VERSION 4.35.0 (as compared to 4.34.2) • do-while loop implemented: Syntax: do statement while ( expression ) ; The expression in a do-while statement is evaluated after the body of the loop is executed. Therefore, the body of the loop is always executed at least once. Example: i=0; do { i++; } while( i < 100 ); WriteVal( i ); • it is now allowed to 'add' (or rather concatenate) string to a number / array. This saves quite a bit of typing. This works as in JScript. The left-hand operand of '+' has to be a string. The right-hand operand may be string, number or array. Numbers are coerced to strings using %g sprintf formatting (prints out decimal point only when necessary) and then concatenated. In case of arrays SELECTED VALUE is coerced to string and then concatenated. So now instead of i = 100; "Value is " + WriteVal( i ); "Close : " + WriteVal( Close ) + ", Open : " + WriteVal( Open ) + ", High : " + WriteVal( High ); you can write: i = 100; "Value is " + i; "Close : " + Close + ", Open : " + Open + ", High : " + High; Note that "Test " + 100 + 1; will give you "Test 1001" because statements are parsed from left to right. "Test " is added first to "100" giving "Test 100" and then to "1" giving "Test 1001". If you want to perform numeric adding first please use braces: "Test " + ( 100 + 1 ); - this will give you "Test 101" • additional tweaks in AFL engine & garbage collection, futher speed up of execution of very long loops • more error checking in AFL engine - will report using uninitialized variables that were accepted silently in 4.31.x - 4.34.x • #include now accepts new way of specifying file names to include:  #include <filename.afl> (note < > braces instead of " " ) if you specify the file name this way AmiBroker will look for the file in "standard include path" that is definable using new prefs setting in Tools->Preferences->AFL It makes much shorter to write includes and you can move include folder now without changing all AFL codes using #includes. For example if you have set standard include path to "C:\AFL\MyIncludes" and write in your formula:  #include <common.afl>  AmiBroker will look for C:\AFL\MyIncludes\common.afl file Also now #include reports file(s) not found in regular error message box. • IIf/Min/Max are now overloaded functions (have two variants each) IIF( Condition_ARRAY, True_Array, False_Array ) (old one) IIF( BoolValue, TrueValue, FalseValue ) Min( array1, array2 ) (old one) Min( number1, number2 ) Max( array1, array2 ) (old one) Max( number1, number2 ) The second one is choosen when all arguments are numbers and it is much much faster and returns number so LastValue() call is not neccessary anymore. Example:  // much faster and does not require LastValue()  period = IIF( name() == "MSFT", 5, 10 ); result = Min( 7, 3 ); // (result is still a number not array as in previous versions) • added 'endless loop detection threshold' setting to Preferences "AFL" tab. Recommended value 100000 or higher. • fixed parameter counting in CallFunction plugin callback in case of overloaded functions • fixed problem with premature freeing of arrays passed in default parameters fields (causing for example problem with color exploration output - introduced in 4.32) CHANGES FOR VERSION 4.34.2 (as compared to 4.34.0) • improved crash recovery dialog to include AFL engine state information and (in some cases) the source line of the formula that causes an exception • added ability to catch all exceptions in indicators and commentaries (switchabel via Tools->Preferences->AFL, "catch system exceptions...", ON by default) - allows you to continue to work even in case of serious problem • loop break by Shift+BREAK is now more sensitive • now you can control how often Shift+BREAK key is checked during formula execution (Tools->Preferences->AFL, "check SHIFT+Break every" (1..100, default = 50) (note that specifying low values may degrade performance slightly) • tweaked AFL memory allocator hash tables to get more speed for large looping formulas • although I never reproduced this problem I made some changes so 'TAB' key should not wipe the contents of AFL editor anymore CHANGES FOR VERSION 4.34.0 (as compared to 4.33.0) • user-definable functions and procedures with parameters and local variables • 'A' is NO LONGER predefined symbol. I decided to remove it because people tend to use A as user-variable forgetting the fact that it was build-in array holding typical price (H+L+C)/3. Use 'Avg' instead. • indicator list column width increased in Indicator Builder • DayOfYear - returns the calendar day number counting from beginning of the year January 1st is 1. Maximum number returned is 366 CHANGES FOR VERSION 4.33.0 (as compared to 4.32.2) • Database purify tool implemented (available via Tools->Database Purify) allows to detect missing/extra quotes, possible splits, invalid OHLC relationship Apply to/range settings similar to AA window. You can also right click over result list to add symbols to watch list and copy the list to the clipboard (and paste it later to any other program for futher use) • further improvements to AFL garbage collector, now looping regardless of loop count requires the same amount of memory as just single pass of the code (no growing allocated memory during loops). This enormously lowered memory consumption for some formulas and increased the speed of some loops 3..4 times. • added variable period support to the following functions: LinRegSlope, LinearReg, LinRegIntercept, StdErr, TSF Sample code: Plot( Close, "Test", colorBlack ); range = 15 * MA( ATR( 15 ), 50 ) / ATR( 15 ); //Plot( range, "range", colorBlue, styleOwnScale ); Plot( LinearReg( Close, range ), "Test", colorRed ); • fixed sometimes incorrect output of variable-period version of LLV/HHV • fixed crash occuring when bad arguments were passed to the function (bug introduced in 4.32.x). CHANGES FOR VERSION 4.32.2 (as compared to 4.32.1) • second bug in experimental garbage collector fixed. CHANGES FOR VERSION 4.32.1 (as compared to 4.32.0) • garbage collector was releasing memory too soon in some cases, now fixed. CHANGES FOR VERSION 4.32.0 (as compared to 4.31.1) • added type check in IF/ELSE statements • added type check in array element assignment • error messages now numbered and display changed slightly • you can break running loop by pressing Shift+BREAK (Pause) key combination • calling COM objects works again (was broken in 4.31.x) • changed slightly the way TAB works in editor, if TAB is pressed any selection is deselected to avoid accidential deletion of text • experimental: added 'agressive garbage collector' that extremely decreases the amount of memory required to run AFL formula by releasing the memory used for temporary variables as soon as possible (previously temporary memory was released at the end of formula execution). A side-effect of new garbage collector is some speed up in formula execution. • new tab in preferences for AFL engine settings • experimental feature, NOT for beginners, may be removed/modified in future releases: new _TRACE( "string" ) AFL function added that allows to 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/ CHANGES FOR VERSION 4.31.1 (as compared to 4.31.0) • fixed bug introduced in 4.31.0 causing no text output in commentary/interpretation CHANGES FOR VERSION 4.31.0 (as compared to 4.30.0) • Workspace window uses "icon font" set in the Windows settings instead of hard coded Tahoma 8 • for better readability and ClearType(tm) compatibility on WinXP, all dialog windows use now 'MS Shell Dlg' face name that maps to standard MS Sans Serif on Win 9x/Me/NT and Tahoma on Win 2K and XP. • rewritten AFL parser, now formula is parsed and coverted to syntax tree and then interpreted. This would allow further improvements including compilation. This allowed also to add loops/if-else statements. • implemented IF/ELSE statement, WHILE and FOR loops: The same basic 'for' loop in AFL is 2..3 times faster than in JScript Syntax follows C++/JScript style: while( conditional_expression ) statement; for( initializer_part; conditional_expression; iterator_part ) statement; if( conditional_expression ) statement; if( conditional_expression ) statement; else statement; • implemented compound statements: these are blocks of statements enclosed in opening and closing curly brace { statement1; statement2; ... statementN; } compound statement can appear anywhere when simple statement can. For example: i = 10; while( i < 20 ) { Plot( MA( Close, i ), "MA" + WriteVal( i, 0 ), colorBlack + i ); i = i + 1; } • implemented C-style postfix and prefix increment/decrement operators i = 10; WriteIf( i++ ); WriteIf( ++i ); WriteIf( i ); • implemented array element access (subscript) operator []: WriteVal( Close[ 0 ] ); // prints the first bar of close array  /* a sample low-level implementation of exponential moving average in AFL */  myema[ 0 ] = Close[ 0 ];  for( i = 1; i < BarCount; i++ ) { myema[ i ] = 0.1 * Close[ i ] + 0.9 * myema[ i - 1 ]; } • added built-in constant 'BarCount' that returns number of bars available in arrays (the number of elements of array) When QuickAFL is turned on it may be less than true number of bars because QuickAFL feature attempts to use only visible bars (and few before). You can control how many bars the formula requires using SetBarsRequired() function • implemented infinite-loop protection. Nice if you forgot to increment counter variable in 'for' loop :-) • tab key now works without need to press ALT/CTRL in AFL editors • added C-like synonyms for logical ADD/OR/NOT: &&, ||, ! /* a sample low-level implementation of Profit-target stop in AFL: */ Buy = Cross( MACD(), Signal() ); priceatbuy=0; for( i = 0; i < BarCount; i++ ) { if( priceatbuy == 0 && Buy[ i ] ) priceatbuy = BuyPrice[ i ];  if( priceatbuy > 0 && SellPrice[ i ] > 1.1 * priceatbuy ) { Sell[ i ] = 1; SellPrice[ i ] = 1.1 * priceatbuy; priceatbuy = 0; } else Sell[ i ] = 0; } /* sample EMA rainbow */ Plot( Close, "Price", colorBlack, styleCandle ); for( Range = 15; Range < 100; Range++ ) Plot( EMA( Close, Range ), "MA"+WriteVal(Range,0), colorRose + Range % 8, styleNoLabel ); CHANGES FOR VERSION 4.30.0 (as compared to 4.29.9) • implemented workaround to Windows XP scroll bar bug. (http://groups.yahoo.com/group/amibroker/message/35446) (we disable scroll bar when chart is zoomed out to the max to prevent scroll bar locking on WinXP) • Chart: ScrollPageLeft (default assignment: PAGEUP key), ScrollPageRight (default: PAGEDN), ScrollToBegin (default: HOME), ScrollToEnd (default: END) available in Keyboard shortcut editor, Fixed ScrollLeft, ScrollRight • fixed problem with not updating Param dialog when using 2 sheets with single pane per sheet. CHANGES FOR VERSION 4.29.9 (as compared to 4.29.8) • added key shortcuts for range mark begin (F12), end (Shift+F12), hide (Ctrl+F12) (they are also available in Keyboard editor so assignments can be changed) • chart scroll left/right are now accessible from keyboard editor (ChartScrollLeft, ChartScrollRight) • if type-in is selected from the main menu then watch list selector dialog is displayed. • fixed sometimes wrong sort when many explorations were run one after another with some non-numeric columns. • Study() works correctly even when trendline is drawn past the last available data bar. CHANGES FOR VERSION 4.29.8 (as compared to 4.29.7) • updated param info for LastValue, MarketID, GroupID, SectorID, IndustryID to match the AFL reference • decreased delay time for baloon tooltip (status bar area) • fixed hang of Windows XP when AmiBroker tried to display the tooltip while AB was minimized. (cause of crash of WinXP when QT was closed before AB) • infinite numbers are printed now as {INF}, not-a-numbers are printed as {NAN} by WriteVal. For example: " 1/0 =" + WriteVal((1/0)); " 0/0 =" + WriteVal(0/0); " (1/0) / (1/0) =" + WriteVal((1/0)/(1/0)); " 1 / (1/0) =" + WriteVal( 1 / ( 1 / 0 ) ); " Null =" +WriteVal(Null); • 3 new AFL functions: a) IsNan( x ) - returns a nonzero value (1 or TRUE) if the argument x is a NaN; otherwise it returns 0 (FALSE). A NaN is generated when the result of a floating-point operation cannot be represented in Institute of Electrical and Electronics Engineers (IEEE) format Example: IsNan( 0/0 ); b) IsFinite( x ) - IsFinite returns a nonzero value (1 or TRUE) if its argument x is not infinite, that is, if –INF < x < +INF. It returns 0 (FALSE) if the argument is infinite or a NaN. Example: IsFinite( 1/0 ); c) Nz( x ) - Null (Null/Nan/Infinity) to zero 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). You can use the Nz function as an alternative to the IIf function. Instead of: varTemp = IIf( IsFinite( (H-L)/(C-L) ), (H-L)/(C-L), 0 ); You can write: varTemp = Nz( (H-L)/(C-L) ); • added IsNull() function - it is the synonym to IsEmpty() CHANGES FOR VERSION 4.29.7 (as compared to 4.29.6) • added "ask to save changed data" option to Prefs->Misc page (if it is unchecked AmiBroker saves data without asking) • Symbol -> WatchList ->Import now accepts all formats of .LST files from Quotes Plus • fixed crash when backward ref bar number was too high • date axis drawing modified (should address 'missing oct 2001' problem) • fixed crash when using extreme zoom in factors (via Zoom to range) and scrolling max to the right so only blank area is visible. • added check for neg. # of contracts • Apply in Indicator Builder does not scroll to the top • other minor fixes: CHANGES FOR VERSION 4.29.6 (as compared to 4.29.5) • WriteVal has now new parameter 'separator' that controls if the number should be formatted with thousand separator or not: WriteVal( ARRAY, format = 8.3, separator = True ) WriteVal( Volume, 8.3, True ); // with separators WriteVal( Volume, 8.3, False ); // without separators • thousand separator is not added to numbers in AA->Export • thousand separator does not appear when using AddColumn( DateTime(), formatDateTime ); • fixed inconsistency between AA result line (incorrect) and AA report (correct) when formula was using SetOption("InitialEquity", nn) to change the Init. equity set in the AA settings (thanks Herman) • fix: % change is displayed again in RT quote window. • fix: watch list dialog (watch list->remove) does not show lists above > 32 if given symbol does not belong to given watch list. • new AFL function: GetChartID() allows to retrieve current indicator chart ID. (returns 0 (zero) in AA window) • other minor fixes CHANGES FOR VERSION 4.29.5 (as compared to 4.29.1) • fixed crash in AFL editor that occured when selecting all text and choosing right mouse button -> copy • auto-scaling changed slightly • user-definable thousand separator (in Tools->Preferences->Misc) applied automatically to all list views and indicators and WriteVal function • definable number of decimal places in RT quote window (Tools->Prefs->Misc) • watch-list related functions: (available from context menu in tree and Symbol->Watch list menu) • quick type-in symbols into watch list • import/export watch list from/to .LST file and from/to plugin (ext. database only for plugins that support this feature. The first one will be FT plugin) • context menu is displayed over selected watch list (click with right mouse button on the watch list name in the Workspace window) • 'dirty' flag is set properly after moving/sizing the study • Amibroker again displays message box asking to save changes. (this is useful to undo some unwanted changes but it works only for most recent 'in-memory' symbols (see Tools->Preferernces->Data)) • fixed the case when Preferences has log scale switched OFF but Indicator Builder has "log scale" turned ON for Price chart. CHANGES FOR VERSION 4.29.1 (as compared to 4.29.0) • data tooltips now show study ID and coordinates and point/percent change from start to end when you hover the mouse pointer over the trend line or other study • from-to range selector implemented just double click on chart to mark begin and then double click in other place to mark end of the range. > and < markers will appear above date axis. To delete the markers double click again in the same place where vertical line is positioned. • From-to selected range can be referred from the AFL level via new functions BeginValue( ARRAY ) EndValue( ARRAY ) - these functions give the single value (number) of the ARRAY at the beginning and end of the selected range. If no range is marked then they return the value at the first bar and last bar respectively. Example: WriteVal( BeginValue( DateTime() ), formatDateTime ); WriteVal( EndValue( DateTime() ), formatDateTime ); "Precentage change of close is " + WriteVal( 100 * (EndValue( Close ) - BeginValue( Close ))/BeginValue( Close ) ) + "%"; • WriteVal function now handles formatDateTime WriteVal( DateTime(), formatDateTime ); • Zoom to range implemented (View->Zoom->Range) or hold down both SHIFT and CTRL and click on green zoom in toolbar button (zooms to selected from-to range) CHANGES FOR VERSION 4.29.0 (as compared to 4.28.1) • context help in AFL editor - just press F1 when cursor is over AFL reserved function name and it will display full information about that function • param info/fun reference available also from context menu • fixed bug in Study function working improperly for trendlines with right extend property • tab order fixed in Study properties box • usability: "Filter pre/after hours" is available now from View->Intraday menu • new AFL function: Now( format = 0 ) returns current date / time in numerous of formats: format = 0 - returns string containing current date/time formatted according to system settings format = 1 - returns string containing current date 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 See: http://www.amibroker.com/guide/afl/afl_view.php?name=NOW • new drawing tool: Triangle • new drawing tool: Andrews' Pitchfork • Gann Square tool does not draw controlling trenline during move/resize • added check that prevents freeing memory by Equity(1) function when this memory is referenced by other variables • added Layer combo to the Text properties box • added link to AFL on-line reference to the Help->AmiBroker on the Web menu. • switching layers does not cause unnecessary symbol tree refresh • added switch to AA Settings->Report tab that allows to turn off optimization warning (that is displayed if optimization requires more than 300 steps) • other minor fixes. CHANGES FOR VERSION 4.28.1 (as compared to 4.28.0) • fixed problem with missing some short trades when new flag "Reverse entry signal forces exit" was turned off • Null is now highlighted and present in the auto-complete box. • fixed numeric sorting of colorized columns CHANGES FOR VERSION 4.28.0 (as compared to 4.27.1) • ApplyStop has one more parameter ApplyStop( Type, Mode, Amount, ExitAtStop, Volatile = False ) new Volatile parameters decides if amount (or distance) (3rd parameter) is sampled at the trade entry and remains fixed during the trade (Volatile = FALSE - old behaviour) or if can vary during the trade (Volatile = TRUE) Allows single-line implementation of Chandeliers exit: ApplyStop(stopTypeTrailing, stopModePoint, 3*ATR(14), True, True ); • ApplyStop handles new N-Bar stop - exits the trade after N bars. Type = stopTypeNBar; /* = 3 */ Mode = stopModeBars; /* = 1 */ ApplyStop( stopTypeNBar, stopModeBars, 5 ); // exits trades on 5th bar since entry  • added new "Reverse entry signal forces exit" check box to the Backtester settings. When it is ON (the default setting) - backtester works as in previous versions and closes already open positon if new entry signal in reverse direction is encountered. If this switch is OFF - even if reverse signal occurs backtester maintains currently open trade and does not close positon until regular exit (sell or cover) signal is generated. In other words when this switch is OFF backtester ignores Short signals during long trades and ignores Buy signals during short trades. • added "Allow same bar exit (single bar trade)" option to the Settings When it is ON (the default settings) - entry and exit at the very same bar is allowed (as in previous versions) if it is OFF - exit can happen starting from next bar only (this applies to regular signals,there is a separate setting for ApplyStop-generated exits). Switching it to OFF allows to reproduce the behaviour of MS backtester that is not able to handle same day exits. • long trades now take precedence over short trades so if signals happen on the same bar in both directions only long trade is taken. • new AFL functions: DateTime() - returns array of encoded date/time values suitable for using with AddColumn and formatDateTime constant to produce date time formated according to your system settings AddColumn( DateTime(), "Date / Time", formatDateTime );  new formatChar constant allows outputting single ASCII character codes: Example (produces signal file accepted by various other programs): Buy=Cross(MACD(),Signal()); Sell=Cross(Signal(), MACD()); Filter=Buy OR Sell; SetOption("NoDefaultColumns", True ); AddColumn( DateTime(), "Date", formatDateTime ); AddColumn( IIf( Buy, 66, 83 ), "Signal", formatChar );  • new AFL functions continued: BarIndex() - returns zero-based bar number - the same as Cum(1)-1 but it is much faster than Cum(1) when used in Indicators SetOption( "name", value ) - sets various options in automatic analysis settings currently available options are "NoDefaultColumns" - if set to True - exploration does not have default Ticker and Date/Time columns "InitialEquity" "AllowSameBarExit" "ActivateStopsImmediately" "AllowPositionShrinking" "FuturesMode" "InterestRate" • if you overwrite AA settings via SetTradeDelays/SetOption backtest report gives these actual values instead of originaly set in the settings • new Null constant is equal to -1e10 (empty value) so you can use it instead enigmatic -1e10 obsolete styleLog removed (logarithmic scale setting is not per-line but per-pane and it is selectable from Indicator Builder) • added PlotGrid( level, color = colorDefault ) function that plots grid line using built-in dotted style. • fixed problem with QuoteEditor that was introduced with adding color support to the list view • added support for Win XP common controls 6, which results in enhanced XP-look (on WinXP only of course) • fixed zero-size problem with floating control bars on Windows XP • fixed some compatibility issues with common controls 6. • added sound when plugin status changes • fixed problems with Review window sometimes not showing the results • value label drawing changed slightly • status bar adjusted so plugin state is visible on smaller displays • improved windows version checking for bug reports CHANGES FOR VERSION 4.27.1 (as compared to 4.27.0) • fixed problems with auto-complete and param info features appearing on certain Windows versions CHANGES FOR VERSION 4.27.0 (as compared to 4.26.0) Intellisense-like functionality in AFL editor • auto-completion feature in AFL editor type a few letters and press Ctrl+SPACE and the number of matching functions / reserved words will be displayed • parameters-info tip, type function name and opening brace ( and you will see the tip that shows information about required parameters • two new checkboxes Preferences->Editor control Auto-completion / parameter-info features • fixed exception occuring when optimizing systems that generate zero trades (very rare case) • AlertIF called from the custom indicators sometimes displayed wrong date/time - now it is fixed • when fixup = 1 Foreign() is able to align array past the last foreign bar. For example when using intraday data you can refer to imported EOD data and it will fill intraday data with last value from previous day. CHANGES FOR VERSION 4.26.0 (as compared to 4.25.0) • List view sorting speed increased significantly: • sorting of text columns is 2 times faster (on average) • sorting of numeric column is 5-10 times faster ( sort 660'000 items within 2-3 seconds on 1GHz machine) • Explorations now support definable color of cell text and background AddColumn and AddTextColumn functions extended to support this feature: AddColumn( Array, "Title", format = 1.2, textColor = colorDefault, bkgndColor = colorDefault ); AddTextColumn( "Text", "Title", format = 1.2, textColor = colorDefault, bkgndColor = colorDefault ); New colorDefault constant (-1) defines default windows color for grid cell. Sample code: Filter =1;  AddColumn( Close, "Close", 1.2 ); AddColumn( MACD(), "MACD", 1.4 , IIf( MACD() > 0, colorGreen, colorRed ) ); AddTextColumn( FullName(), "Full name", 77 , colorDefault, IIf( Close < 10, colorLightBlue, colorDefault ) ); • custom indicators - anchors are not offset vertically from the ends of the trend line when Draw dates is selected • custom indicators with auto-scaling can be now dragged in Y-direction like regular charts • Foreign and RelStrength algorithm improved to allow more complex alignment cases • PlotShapes works even without any Plot statement (although it is intended to use in conjunction with Plot) • fixed line disappearing bug that occured when using text tool right after trend line tool • Dec is displayed again on date axis CHANGES FOR VERSION 4.25.0 (as compared to 4.24.0) • support user-definable parameters: new AFL functions Param( "name", default, min, max, step ) ParamStr( "name", "default" ); ParamColor( "name", defaultcolor ); new Parameters dialog : right click over chart pane and select "Parameters" or press Ctrl+R allows to change chart parameters - changes are reflected immediatelly Sample code 1: ticker = ParamStr( "Ticker", "MSFT" ); sp = Param( "MA Period", 12, 2, 100 ); PlotForeign( ticker, "Chart of "+ticker, ParamColor( "Price Color", colorLightYellow ), styleCandle ); Plot( MA( Foreign( ticker, "C" ), sp ), "MA(" + WriteVal( sp, 1.0 ) + ")", ParamColor( "MA Color", colorRed ) ); Sample code 2: sp = Param( "RSI Period", 12, 2, 100 ); r = RSI( sp ); Plot( r, "RSI("+WriteVal(sp,1.0)+")", ParamColor("RSI Color", colorRed ) );  Buy = Cross( r, 30 ); Sell = Cross( 70, r );  PlotShapes( shapeUpArrow * Buy + shapeDownArrow * Sell, IIf( Buy, colorGreen, colorRed ) ); • added missing ':' and '"' characters to the forbidden characters set in file names generated from ticker names. All file-system reserved characters are converted to underscore. • ticker symbol maximum length increased to 25 characters (from previous 15). (these two fixes above solve problem with using very long symbols like • default keyboard accelerators changed Ctrl+R is now for Parameters dialog F5 is for Refresh • fixed calculation bug occuring when drawing objects in the blank chart area ("jumping" effect) • new method in Quotations collection for faster retrieval of quotes long Retrieve( long Count, Variant *Date, Variant *Open, Variant *High, Variant *Low, Variant *Close, Variant *Volume, Variant *OpenInt ); • on Windows Me, 2000 and XP all file dialogs now feature "Places" bar and allows to select few recent file names from the combo • date axis display modified slightly (3 letter month abbrev. used more often • changed resizing algorithm so if "no min size for resizing dialog" option is selected the scroll bar of list / edit is always visible. Also the option is active from the start without need to go to Preferences. • other minor improvements CHANGES FOR VERSION 4.24.0 (as compared to 4.23.0) • saving/loading Automatic Analysis settings to/from the file • Axis font now can be made bold/italic/underline • Text drawing tool uses axis font now • full control over AA window via new OLE/COM interface: Analysis object (accessible via Broker.Application.Analysis) Methods: - Backtest(); - runs backtest - Explore(); - runs exploration - Scan(); - runs scan - Optimize(); - runs optimization - bool Report( FileName: String ) - saves report to the file or displays it if FileName = "" - bool Export( FileName: String ) - exports result list to CSV file - bool LoadFormula( FileName: String ) - loads AFL formula - bool SaveFormula( FileName: String ) - saves AFL formula - bool LoadSettings( FileName: String ) - loads backtest settings - bool SaveSettings( FileName: String ) - saves backtest settings - ClearFilters() - removes all filters Properties: - long ApplyTo - defines apply to mode: 0 - all stocks, 1 - current stock, 2 - use filter - long RangeMode - defines range mode: 0 - all quotes, 1 - n last quotes, 2 - n last days, 3 - from-to date - long RangeN - defines N (number of bars/days to backtest) - DATE RangeFromDate - defines "From" date - DATE RangeToDate - defines "To" date - Filter( nType: short, Category : String ) - sets/retrieves filter setting nType argument defines type of filter 0 - include, 1 - exclude Category argument defines filter category: "index", "favorite", "market", "group", "sector", "index", "watchlist" Examples ClearFilters(); // clear all filters first Filter( 0, "index" ) = 1; // include only indices Filter( 1, "market" ) = 2; // exclude 2nd market Full Example for Windows Scripting Host: ======================================== /* create AB object */ AB = new ActiveXObject("Broker.Application");  /* retrieve automatic analysis object */ AA = AB.Analysis;  /* load formula from external file */ AA.LoadFormula("afl\\macd_c.afl");  /* optional: load settings */ // AA.LoadSettings("the_path_to_the_settings_file.abs");  /* setup filters */ /* backtest over symbols present in market 0 only (zero-based number) */ AA.ClearFilters(); AA.Filter( 0, "market" ) = 0;  /* set apply to and range */ AA.ApplyTo = 2; // use filters AA.RangeMode = 0; // use all available quotes  /* run backtest and display report */ AA.Backtest(); AA.Report(""); // empty file name means display report CHANGES FOR VERSION 4.23.0 (as compared to 4.22.1) • chart axis font can be defined by the user. The default is now Arial, 9pt. (Tools->Preferences->Miscellaneous: "Axis font") • Undo feature added to AFL editor. • PlotShapes now supports offset (or distance) parameter (by default -12 ), Offset is expressed in SCREEN pixels. Negative offsets shift symbols down, positive offsets shift symbol up. To place the shape exactly at ypostion, specify 0 as offset. PlotShapes( shape, color, layer = 0, yposition = graph0, offset = -12 ); • yet another bug fixed that caused problems with drawing lines when multiple windows were showing same symbol but different intervals. • if Y-value is less than 1000 the status bar displays four decimal places , also bar number is displayed in the status bar (next to date/time) • Insert Indicator window (Ctrl+I) does not show empty indicator slots anymore. CHANGES FOR VERSION 4.22.1 (as compared to 4.22.0) • fixed overwrite problem occuring when deleting first indicator in the list in Indicator Builder • fixed shortcut conflict &File and &Format. Now Format menu has Alt+o shortcut • other minor fixes • added constants for shapes "shapeNone", 0 "shapeUpArrow", 1 "shapeDownArrow", 2 "shapeHollowUpArrow", 3 "shapeHollowDownArrow", 4 "shapeSmallUpTriangle", 5 "shapeSmallDownTriangle", 6 "shapeHollowSmallUpTriangle", 7 "shapeHollowSmallDownTriangle", 8 "shapeUpTriangle", 9 "shapeDownTriangle", 10 "shapeHollowUpTriangle", 11 "shapeHollowDownTriangle", 12 "shapeSmallSquare", 13 "shapeHollowSmallSquare", 15 "shapeSquare", 17 "shapeHollowSquare", 19 "shapeSmallCircle", 21 "shapeHollowSmallCircle", 23 "shapeCircle", 25 "shapeHollowCircle", 27 "shapeStar", 29 "shapeHollowStar", 31 "shapeDigit0", 33 "shapeDigit1", 35 "shapeDigit2", 37 "shapeDigit3", 39 "shapeDigit4", 41 "shapeDigit5", 43 "shapeDigit6", 45 "shapeDigit7", 47 "shapeDigit8", 49 "shapeDigit9", 51 "shapePositionAbove", 1 Example: PlotShapes( IIF( buy, shapeDigit9 + shapePositonAbove, shapeNone ), colorGreen ); CHANGES FOR VERSION 4.22.0 (as compared to 4.21.1) • changes made in Indicator Builder are not lost if formula is incorrect - instead error message is displayed and formula is saved even if it has a syntax error • if currently displayed indicator formula has an error - the error message does not pop up in a separate window but is displayed in the indicator pane. • empty indicators are not displayed in the Indicator Builder and new buttons "Add", "Delete" are provided to add new indicator and remove existing • when drawing or moving drawing objects the auto-refresh of the chart is temporarily held to solve problems with drawing on RT charts. • Symbol->Information window is not reset every 3 sec when working with RT data. • interval between chart updates is now configurable (Preferences->Intraday) • Random( seed = none ); function takes new parameter seed. If seed is defined it initializes the seed of random number generator this allows to produce repetitive series of pseudo-random series. If seed is not specified - random number generator continues generation. To reinitialize the generator, use 1 as the seed argument. Any other value for seed sets the generator to a random starting point. Example 1: Graph0 = Random(); // generates different sequence with each refresh Example 2: Graph0 = Random(1); // generates the same sequence with each refresh • new AFL function PlotShapes( shape, color, layer = 0, yposition = graph0 ); that allows to plot arrows and other shapes on any chart. Parameters: • shape defines type of the symbol. when shape is zero nothing is plotted values other than zero cause plotting various pre-defined shapes. Odd values plot shape BELOW indicator, even values plot shape ABOVE indicator. • color defines color of shape • layer defines layer number on which shapes are plotted • yposition defines Y-position where shapes are plotted (by default they are plotted 'around' graph0 (first indicator) line) Currently defined shapes are UP ARROW = 1, (below indicator) DOWN ARROW = 2, (above indicator) HOLLOW UP ARROW = 3, (below) HOLLOW DOWN ARROW = 4, (above) SMALL UP TRIANGLE = 5, (below) SMALL DOWN TRIANGLE = 6, (above) HOLLOW SMALL UP TRIANGLE = 7, (below) HOLLOW SMALL DOWN TRIANGLE = 8 , (above) UP TRIANGLE = 9, (below) DOWN TRIANGLE = 10, (above) HOLLOW UP TRIANGLE = 11, (below) HOLLOW DOWN TRIANGLE = 12, (above) SMALL SQUARE = 13, (below) SMALL SQUARE = 14, (above) HOLLOW SMALL SQUARE = 15, (below) HOLLOW SMALL SQUARE = 16, SQUARE = 17, (below) SQUARE = 18, (above) HOLLOW SQUARE = 19, (below) HOLLOW SQUARE = 20, (above) SMALL CIRCLE = 21, (below) SMALL CIRCLE = 22, (above) HOLLOW SMALL CIRCLE = 23, (below) HOLLOW SMALL CIRCLE = 24,(above) CIRCLE = 25, (below) CIRCLE = 26, (above) HOLLOW CIRCLE = 27, (below) HOLLOW CIRCLE = 28, (above) STAR = 29, (below) STAR = 30, (above) HOLLOW STAR = 31, (below) HOLLOW STAR = 32, (above) NUMBER 0 = 33, (below) NUMBER 0 = 34, (above) NUMBER 1 = 35, (below) NUMBER 1 = 36, (above) NUMBER 2 = 37, (below) NUMBER 2 = 38, (above) NUMBER 3 = 39, (below) NUMBER 3 = 40, (above) NUMBER 4 = 41, (below) NUMBER 4 = 42, (above) NUMBER 5 = 43, (below) NUMBER 5 = 44, (above) NUMBER 6 = 45, (below) NUMBER 6 = 46, (above) NUMBER 7 = 47, (below) NUMBER 7 = 48, (above) NUMBER 8 = 49, (below) NUMBER 8 = 50, (above) NUMBER 9 = 51, (below) NUMBER 9 = 52, (above) Demo formula:  Graph0=MACD(); Graph1=Signal(); Buy=Cross(Graph0, Graph1); Sell=Cross(Graph1, Graph0); PlotShapes( ( Buy OR Sell ) * ( 1 + Cum( Buy OR Sell ) % 52 ), IIf( Buy, colorGreen, colorRed ), 5 ); GraphXSpace = 5; CHANGES FOR VERSION 4.21.1 (as compared to 4.21.0) • AddToComposite marks symbol as dirty so timestamp added in the full name is stored properly. • "Align custom minute bars to regular market hours" works OK now even if filtering is OFF • new methods added to COM interface in 4.21.0 caused incompatibility with AmiQuote because of changed numbering of methods. Now it is fixed so AmiQuote auto-import works again with 4.21.1 • fixed display of watch list >32 in the workspace tree • fixed possible hangup when attempting to draw objects when currently selected layer is hidden CHANGES FOR VERSION 4.21.0 (as compared to 4.20.8) • layers implemented (layers is a well-know concept in every decent painting/drawing/CAD package now it is available to traders for (AFAIK) the first time in technical analysis program) • increased number of watch lists (to 64 watch lists) and sectors (to 64 sectors) (note that broker.workspace file once saved with new version can not be read back with previous versions) • max. number of bars in File->Database Settings increased to 500'000. • ASCII importer: addedSTRICT 1 mode it checks if Open, High, Low prices are greater than zero
• COM/OLE interface:
new property Broker.Application.DatabasePath
new method: Broker.Application.SaveDatabase()

Example VBScript code (Windows Scripting Host):

Set oAB = CreateObject("Broker.Application")

 WScript.Echo( "Current path to database is " + oAB.DatabasePath )

 if oAB.LoadDatabase("c:\program files\amibroker\data") = True then WScript.Echo( "succesfully loaded new database" ) end if

 WScript.Echo( "Current path to database is " + oAB.DatabasePath )

 oAB.SaveDatabase()

CHANGES FOR VERSION 4.20.8 (as compared to 4.20.7)

• fixed #include command (CR/LF pair handling)
• #include now displays error message in the status bar ifincluded file can not be found
• when calling function defined in script AFL does not convert the method name to lowercase
• filtering after hours works also for EndTime < StartTime case (usefull for users from Far East tracking US exchanges)
• fixed bug causing crash on custom indicators using Study() with QuickAFL enabled
• protection against crash when the user tries to plot negative values on semi-log scale
• new AFL function: GetDatabaseName - gives the name of the database - the last part (folder) of the database path
• other minor fixes
• new myTrack plugin
• removed (c) text (4.20.8.3431)

CHANGES FOR VERSION 4.20.7 (as compared to 4.20.6)

• fixed crash occuring on exit on Windows XP (CRegistry class - free() )
• fixed problem with saving keyboard editor settings on Win2k
• fixed problem with different ordering of tickers when case sensitivity is turned on (symbol array is re-sorted on change and re-sorted after loading master file)
• added one more safety check for non-existing directory when saving layout

CHANGES FOR VERSION 4.20.6 (as compared to 4.20.5)

• possible bug with AFL editor fixed (streamin)
• "space" problem in AFL editor fixed
• fixed bug with switching databases
• fixed crash occuring when user specified non-existing pen
• fixed bug in monthly view display (29.02.2000)
• fixed bug in File->Save database As (into blank directory)
• fixed title of built-in volume pane
• ROC function accepts additional parameter that defines how negative
values are handled. ROC( array, periods = 12, absmode = False )
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 ) )
• QuoteTracker plugin now accepts also . (dot) as a date separator
• myTrack plugin startup routine improved

CHANGES FOR VERSION 4.20.5 (as compared to 4.19.0)

• Regression channels calculate percent distances (instead of point) when drawn on log-scale chart
• Zoom All - includes now blank bars
• zoom factor and date selection are now independent for each window in multiple-window setup
• moving of vertical lines is now easier (4 pixel "hot" area instead of 1 pixel)
• styleBar gives normal bars instead of thick
• custom n-tick intervals appear also in chart context menu
• deleted databases are removed from MRU list
• fixed handling of case sensitive tickers when working with local database (4.20.2)
• AddToComposite resets OHLCVI values correctly (when flag=1) even if using "dynamic" symbols
for composites. (4.20.3)
• composite symbol is reset properly even if flused out of in-memory cache (4.20.5)
• when $ALLOWNEG is NOT specified in the ASCII importer definition AmiBroker performs the following range checking and fixup on open, low and high prices if( open == 0 ) open = close; if( high < max( open, close ) ) high = max( open, close ); if( low == 0 ) low = min( open, close ); (4.20.5) • other minor fixes CHANGES FOR VERSION 4.19.0 (as compared to 4.18.0) • minor other fixes fixed bug with date/time axis tree is refreshed after AddtoComposite used in Backtest/Exploration • right-hand axis zone is now mouse moveable/sizable: hover the mouse over right axis and you will see that cursor changes to up/down arrow. now you can click and drag up/down Y axis, when you press down SHIFT you can scale Y axis by moving your mouse when you double click in the right axis area Y axis zoom and position will be reset • as mouse operation is superior toolbar buttons taller/shorter buttons are removed (moved to View->Zoom menu) • View->Profile is back in the "View" toolbar • implemented new drawing tools: - Raff regression channel - Standard error channel - Standard deviation channel (all available from Insert->Regression Channel and new toolbar button) CHANGES FOR VERSION 4.18.0 (as compared to 4.17.0) • fixed too long chart title text bug • fixed scroll bar thumb sizing • RMB->Copy in AA result list works again • better keyboard operation in AA window (window does not loose focus after Check/Load AFL rules) • minor fixes / changes changed date axis min skip step from 4 to 5 added case sensitive check in few more places when Pref.CaseSensitiveTickers is ON intraday interval saved in layouts is properly restored • Real time quote window: DEL works now again • can now display different N-tick bars for the same symbol • fixed bug in Status('firstbarinrange') that occured if range exceeded number of quotes • tooltips are protected against displaying more than 25 lines of text (prevents flashing) • OLE automation application.RefreshAll is asynchronous now • charts are always refreshed after scan using AddToComposite (even if composite ticker already exists) • 'From' date in AA now works as expected in intraday mode • Profile view is refreshed when View->Profile is choosen • new profile template fields {s} - gives ticker symbol in lowercase {S} - gives ticker symbol in UPPERCASE (the old {t} - gives ticker symbol in the orignal case (as typed in Information window) • Categories window saves edits in Profile URL without any extra clicks • AddToComposite has 2 new flags that allow running AddToComposite in backtest/optimization mode and exploration mode atcFlagEnableInBacktest = 8 atcFlagEnableInExplore = 16 • the following constants were added for readability of formulas using AddToComposite: atcFlagResetValues = 1 atcFlagCompositeGroup = 2 atcFlagTimeStamp = 4 atcFlagEnableInBacktest = 8 atcFlagEnableInExplore = 16 atcFlagDefaults = atcFlagResetValues | atcFlagCompositeGroup | atcFlagTimeStamp; • shorter/taller bars (compress/expand Y axis) option added on numerous requests (note that this is temporary solution - better one will come, so please don't ask me to change this because it will be changed anyway) CHANGES FOR VERSION 4.17.0 (as compared to 4.16.0) • added Gann Square and Gann Fan drawing tools with customisation dialogs (angle of line is displayed in the status bar) • added parallel trend line tool • studies can be dragged without "shrinking" effect beyond upper and lower chart border and beyond left and right border (but within available quotation range plus right margin) • New toolbar buttons for ray (right-extend line) and extend (left and right) lines • Format toolbar controls (color, thick, dotted) change selected drawing style & color • snap to price was not accurate in v4.15-4.16 now it is accurate again • snap to price now works in "magnet" mode - so it snaps only if cursor is within 5% distance to high/low price. Snap % threshold is definable in Preferences/Charting • usability improvement: even when "return to select mode after drawing" is ON, you can draw mutliple studies one after another quickly if you hold down CTRL key while releasing the button. • usability improvement: you can now draw objects with OR without holding left mouse button pressed while drawing. • drawing object is now automatically selected when "return to select mode after drawing" is ON and "auto-select last drawn object" is also ON. This makes it easier to delete/copy/cut or see its properties (Alt+Enter) immediatelly. • #include can now be written also in upper case • some UI clean-up: • added "Format" menu just to conform with MS recommendations for user interface, • moved "snap to price" to Format menu and moved "Erase watch lists" to "Symbol" menu. • "Snap to price" now available from toolbar. Right and left extend available from Format menu. • Added "Properties" and "Delete all" to "Edit" for consistency • "Quotations..." has been renamed to "Quote Editor" and toolbar icon has been changed • certain rarely used toolbar icons from "main toolbar" were removed to save space (Add/Delete/Split Symbol - regular menu is more appropriate for that operations) • X-coordinate display pane in status bar enlarged to accommodate time also • added "Copy Image as Metafile" option to Edit menu. Metafile is a vector format so you can resize copied picture without distortion. (useful for creating documents that are printed later) • Quote Editor (QE) improvements: • you can now delete quotes in QE - select one or more quotes from the list (SHIFT/CTRL to multi-select) and press "Delete" button • QE made several times faster displaying 20'000 bars in "current" symbol mode takes about 2 seconds now. • now tickers can be case-sensitive. This is useful if you want to treat. ABC and ABc as different symbols. Tools->Preferences "Miscellaneous" : "Case sensitive ticker symbols" USE WITH CARE AS CERTAIN PLUGINS (eSignal plugin for example) DO NOT HANDLE CASE SENSITIVITY CHANGES FOR VERSION 4.16.0 (as compared to 4.15.1) • completely re-designed Fibonacci retracement tool allowing full customization and more flexibility. Just draw a Fib retracement and double click on it (or choose Edit->Properties). Customization dialog is available on "Fibonacci" tab. • new setting in Tools->Preferences->Charting "Select quote only by CTRL+LMB" - if marked quote selection is accessible only via double click or single click WITH CTRL key depressed (v4.15 style). if unmarked quote selection is possible via single click (old style) • trend line properties dialog moved to property sheet for consistency. CHANGES FOR VERSION 4.15.1 (as compared to 4.15.0) • fixed bug with date axis display that appeared in 4.15.0 • fixed problem with moving/sizing objects when multiple windows were open • removed "Move/Size" toolbar button: now editing/moving/sizing is enabled by default in regular "Select" mode (arrow cursor) the old functionality (pick quotation) is available if you hold down CTRL key while clicking once on the chart or by double click on a chart while not being over an object. Double click over object - shows properties. • added "Return to select mode after drawing" option in Tools->Preferences->Charting - when it is switched ON (by default) - right after drawing any object it is available for moving/sizing/deletion. CHANGES FOR VERSION 4.15.0 (as compared to 4.14.0) • moving and sizing of drawing objects (see new "Move/Size" button in draw tool bar) • cut/copy/paste/delete of drawing objects (Edit menu and standard shortcuts, need to mark object first in Move/Size mode) • blank space in the right-hand side of the chart for drawing future trend line projections • moved charting related preferences setting to new tab "Charting" • new setting for number of blank bars in right margin (Charting tab) CHANGES FOR VERSION 4.14.0 (as compared to 4.13.1) • fixed problem with creating new databases that occurred on certain MSVCRT versions • styleOwnScale adjusts Base level for histogram and area style back to minvalue or zero whichever is less • Plot, PlotOHLC and PlotForeign have 2 additional parameters for specifying fixed minimum and maximum values for Y-axis Note that new parameters work only when styleOwnScale is used: Plot( array, title, color, style = styleLine, min = {empty}, max = {empty} ) PlotOHLC( open, high, low, close, title, color, style = styleLine, min= {empty}, max = {empty} ) PlotForeign( ticker, title, color, style = styleLine, min= {empty}, max = {empty} ) New parameters make it easy to plot ribbons, for example: Plot( Close, "Price", colorBlue, styleCandle ); Plot( 2, /* defines the height of the ribbon in percent of pane width */ "Ribbon", IIf( up, colorGreen, IIf( down, colorRed, 0 )), /* choose color */ styleOwnScale|styleArea|styleNoLabel, -0.5, 100 ); It also makes it easy to plot 2 or more "own scale" plots with the same scaling: minimum = LastValue( Lowest( Volume ) ); maximum = LastValue( Highest( Volume ) );  Plot( Close, "Price", colorBlue, styleCandle );  /* two plots below use OwnScale but the scale is common because we set min and max values of Y axis */ Plot( Volume, "Volume", colorGreen, styleHistogram | styleThick | styleOwnScale, minimum, maximum ); Plot( MA( Volume, 15 ), "MA volume", colorRed, styleLine | styleOwnScale, minimum, maximum ); • fixed date axis display for custom intraday intervals longer than 60 minutes • "dirty" flag is set properly now during ASCII import in$OVERWRITE 1 mode (solves import watch list problem)
• when switching layouts ticker bar selection is now synchronized with active window
• after AA->Scan Foreign symbol cache is flushed
• now styleLeftAxisScale really allows modification of built-in price chart to feature moving average of volume
// Now plot volume and its moving average using left-hand axis scaling Plot( Volume , "Volume", colorBlue, styleLeftAxisScale | styleHistogram | styleThick | styleNoLabel ); Plot( MA( Volume,15), "MAV", colorLightBlue, styleLeftAxisScale | styleNoLabel );
• ASCII importer and Import Wizard now allows to import negative prices (useful for spreads). New command is $ALLOWNEG 1 and new check box in Import Wizard is "allow negative prices". Please note that logarithmic scale can NOT be used to display negative prices because log() function is undefined for negative values. • four new AFL functions: • LinRegIntercept( ARRAY, periods )- calculates intercept of linear regression line the "a" coefficient in a + b*x (LinRegSlope calculates b) • LinearReg( ARRAY, periods )- calculates linear regression line ending value according to a + b * x (where a and b are intercept and slope of linear regression line) • StdErr( ARRAY, periods )- calculates standard error function (standard error of linear regression estimate) - the same as MS' STE function • TSF( ARRAY, periods ) - calculates time series forecast indicator (similar to LinearReg but differs by the value of lin reg slope) CHANGES FOR VERSION 4.13.1 (as compared to 4.13.0) • F4 key for Edit | GoToSymbol works again and can be redefined in the shortcut editor • new style: styleLeftAxisScale = 65536 - allows to plot more than one graph using common scaling but different from regular (right axis) scale. Example: price plot plus volume and moving average plot: // Plot price plot and its moving average Plot( Close, "Price", colorWhite, styleCandle ); Plot( MA( Close, 20 ), "MAC", colorRed );  // Now plot volume and its moving average using left-hand axis scaling Plot( Volume , "Volume", colorBlue, styleLeftAxisScale | styleHistogram | styleThick ); Plot( MA( Volume,15), "MAV", colorLightBlue, styleLeftAxisScale );  (in one of the future betas you will be able to display ruler for left-hand axis)  CHANGES FOR VERSION 4.13.0 (as compared to 4.12.0) • fixed bug with loading layouts for stocks that have spaces in the ticker symbol • new pre-defined shortcut keys: Alt+Left = Next symbol, Alt+Right = Prev symbol, Ctrl+NumPadPLUS = Zoom In, Ctrl+NumPadMINUS = Zoom Out, Ctrl+PageUp = Prev Sheet, Ctrl+PageDown = Next Sheet • new keyboard shortcut editor in Tools->Preferences->Keyboard allow user-definable keyboard shortcuts • fixed display bug in Preferences->Intraday that caused rounding to full hours custom bar intervals of more than 60 minutes • Layouts->Save As does not generate duplicate entries in the tree when already existing name is typed in (it was harmless but still not nice) • A confirmation box is displayed when choosing Edit->Delete session • fixed problem with incorrect interval shown in the settings section of the report when hourly periodicity was selected • new style: styleOwnScale = 32768 allows plotting graphs with independent scalling (like volume graph on price plot) • implemented PlotForeign("ticker", "title", color, style = styleCandle | styleOwnScale ) • implemented PlotOHLC( open, high, low, close, "title", color, style = styleCandle | styleOwnScale ) that allows plotting candlesticks/bars from other arrays without need to overwrite existing OHL arrays. CHANGES FOR VERSION 4.12.0 (as compared to 4.10.3) • color coded and multi-line caption bars in indicators colors are selected automatically when using Plot() function or graphNcolor variable. If you use Title variable you have to specify colors in the string. Colors can be specified using \\cXX sequence where XX is 2 digit number specifying color index \\c38 - defines violet, there is a special sequence \\c-1 that resets to default axis color. For example Title = "This is written in \\c38violet color \\c27and this in green"; You can also use new AFL function that makes it easier. Function is called EncodeColor( colornumber ). And you can write the above example like this: Title = "This is written in " + EncodeColor( colorViolet ) + "violet color " + EncodeColor( colorGreen ) + "and this in green"; Multi-line caption is possible by simply embedding line break \n, for example: Title = "This is 1st line\nThis is second line"; • new layout handling code: • you can now have unlimited number of custom, multiple-window templates that can be switched between with just double click on layout name in the "Layouts" tab of the Workspace window • you can open/save/delete layout by clicking on the Layout tree with right mouse button and choosing appropriate function. "Save As" option saves current layout under new name. • Local layouts are per-database while Global layouts are visible from all databases. • information saved in layouts include: window sizes and postions, maximized/minimized state chart panes available on each sheet (independent for each window), selected bar interval, selected symbol, selected chart sheet • Most recently used layout can be saved on exit and database switch automatically (see: Tools->Prefs->Miscellaneous "Save on exit: Layouts") • old single-window layouts are now renamed to "templates" • CCIa( array, period ) function added - works like CCI but accepts input array instead of working on (C+H+L)/3 • implemented a *very* basic pre-processor with single command #include that allows to include external AFL files into your formula. Syntax: #include "path\to my file\name path.afl" Note 1: include statement need SINGLE backslashes in the path (this is quite the opposite to normal AFL sting parsing) Note 2: using #include command may slow down formula execution even considering the fact that AmiBroker tries to include only once and cache pre-processed text Note 3: that currently no error message is given if #include fails and this code is experimental. Note 4: nesting #include commands is not supported • balloon tooltips for status bar • color-coded plugin status pane in the status bar, plus pop-up balloon notifications when connection state changes • ability to link custom menu to the plugin status pane - new QT plugin (beta) provides Connect/Shutdown options thru such menu. • data plugins receive UNLOAD notification correctly • you can sort columns in Quotation Editor by click on column header • layout of Quick Review window changed to allow smaller window size. • Intraday settings dialog allows wider time shift -23..+23 hours CHANGES FOR VERSION 4.10.2 (as compared to 4.10.1) • several minor fixes CHANGES FOR VERSION 4.10.1 (as compared to 4.10.0) • Equity() function now accepts range type = -2 Equity( 0, -1 ) - calculates Equity using current date range settings while Equity( 0, -2 ) - calculates Equity using the most recent backtest settings (this mode is now used by built-in equity chart to avoid affecting Equity chart by scans/explorations done after backtesting using different range) • -10000000000.00 in chart caption is replaced by {EMPTY} • fixed problem selection bar sometimes disapearing • fixed ALIAS field handling by ASCII importer • other minor fixes CHANGES FOR VERSION 4.10.0 (as compared to 4.09.0) • fixed small COM memory leak when calling methods in COM objects • column widths and ordering in Real time quote window is saved between sessions • other minor fixes CHANGES FOR VERSION 4.09.0 (as compared to 4.08.2) • enhanced backtester: + support "Futures" mode that use contract PointValue and Margin for calculations + support for Round Lot Size allows you to tell backtester to use user-defined round lots + support for TickSize - now built-in stops exit trades only at "allowed" price levels + new commission type "$ per share/contract"
+ improved commission/position size calculation
• added following fields to trade list: number of shares/contracts, position value, entry, exit prices, % price change, cum. profit, # bars in trade, profit per bar
• report now includes new settings (margin req, futures mode, def. round lots, tick size)
• Symbol->Information window allows to specify PointValue, Margin, Round Lot Size and Tick Size on symbol-by-symbol basis
• OLE automation interface: added four new properties to Stock object: PointValue, MarginDeposit, RoundLotSize, TickSize
• ASCII Importer handles now the following additional fields in $FORMAT command: ALIAS, MARGIN, POINTVALUE, ROUNDLOTSIZE, TICKSIZE • double click on entry in the Alert output window displays the chart. • Buy&hold formula in built-in equity chart modified (positionsize=-100) to allocate 100% of funds in B&H (if you modified your formula you may need to add positionsize=-100 to get correct buy-and-hold equity (100% funds invested)) CHANGES FOR VERSION 4.08.2 (as compared to 4.08.0) • added support for margin in backtester (note: pointvalue and futures initial margin support coming up in the next ver) • Changing range and running scans/explorations after backtest does not affect already displayed equity line. • Status provides 2 new fields: "firstbarintest" and "lastbarintest". The work in a similar way to "firstbarinrange" and "lastbarinrange" but they return the settings of last BACKTEST/OPTIMIZATION and intermediate scans/explorations do not affect them ATTENTION: This change affects reference BuyAndHold equity formula, so it now should use FirstBarInTest and LastBarInTest fields /* buy and hold simulation */ Short=Cover=0; Buy=Status("firstbarintest"); Sell=Status("lastbarintest"); SetTradeDelays(0,0,0,0); ApplyStop(0,0,0,0); ApplyStop(1,0,0,0); ApplyStop(2,0,0,0); Plot( Equity(), "Buy&Hold", -9 ); - if you haven't modified default equity plot AmiBroker will update the code, but if you modified it in v4.08.0 you should apply the change yourself. • changed default behaviour of LastValue in commentaries. In pre-4.08.1 versions commentary/interpretation/tooltip code evaluation was somewhat special because LastValue returned in fact not the last but the value of array at selected point (by vertical line or by tooltip) This caused some problems in displaying indicator values that used LastValue in its construction. To address this now LastValue used in Commentaries by default returns true last value. So you should modify your existing commentary/interpretation code that used LastValue to use now SelectedValue( array ) function to maintain the same behaviour. Alternatively you can use LastValue( array, 0 ). • now built-in stops / ApplyStop()s can be activated immediately (at the trade entry bar) • other minor fixes CHANGES FOR VERSION 4.08.0 (as compared to 4.07.4) • Metastock importer: group/watch lists assignments and full name is overwritten even if symbols are already present in the database ASCII and Metastock importers now allow to import "foreign" data to databases using external data sources (via plugin). This is done by marking newly added symbols as using local database only. (Note that this does NOT affect symbols already present in the database - otherwise you would break symbols that are provided by the plugin) (Note 2: in case of ASCII importer this does NOT work if NOQUOTES mode is selected - this is because people sometimes use importer to import just symbols (watch lists)) • new chart style styleArea - draws filled area chart • Equity chart draws also buy-and-hold equity. • Equity chart is user-definable, you can even add interpretation code to equity chart (use Indicator Builder to modify equity formula. Please note that equity chart code contains of your AA formula actual Equity line plotting code. To modify equity chart you should edit code below //--equity-plot line. Code above that line is replaced by AmiBroker after backtest. • Status function supports six new fields: "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 • GraphZOrder variable allows to change the order of plotting indicator lines. When GraphZOrder is not defined or is zero (false) - old ordering (last to first) is used, when GraphZOrder is 1 (true) - reverse ordering is applied. • point commissions are not taken when positionsize is set to zero. • new SetTradeDelays( buydelay, selldelay, shortdelay, coverdelay ) function allows to overwrite delays set in the Settings from the AFL code. • fixed problem that occurred when using cover=buy; short=sell; statement AND multiple Equity(1) statements AND ApplyStop()s in one AA formula. CHANGES FOR VERSION 4.07.4 (as compared to 4.07.3) • fixed bug causing sometimes crash when Interpretation window was open, QuickAFL was enabled • fixed problem occuring when Nth greater than 1 was used with PeakBars, TroughBars • 'Check' feature in AA window does not consider Equity() function as referencing future CHANGES FOR VERSION 4.07.3 (as compared to 4.07.2) • fixed bug causing crash when LastValue() was used and QuickAFL enabled • reduced memory usage of AFL when evaluating expressions like expr1 (operator) expr2 when one of expr is a number (scalar) and another variable is an array • reduced memory usage of Equity() function CHANGES FOR VERSION 4.07.2 (as compared to 4.07.1) • fixed bug causing crash when using formula with Equity() function and QuickAFL enabled • fixed bug causing crash when using variable-period HHV,LLV functions and QuickAFL enabled • fixed invisible short/cover arrows problem (arrows are shifted into visible area now if there is not enough space) • overlaid indicators re-evaluate number of bars required to calculate formula so for example longer averages added to main chart via custom AFL formula are plotted correctly for all bars • new Status() fields "range...." now work also in Scan and Exploration modes • text columns in Explorations are sorted correctly by click on the header CHANGES FOR VERSION 4.07.1 (as compared to 4.07.0) • Equity plot does not generate alerts anymore • SOUND command works now (previously only PLAY was working). Additionally an error message is displayed in the status bar when something goes wrong with playing the audio alert. Please note that you should use \\ (double slashes) in the paths in AlertIF function • small bug fix in displaying Data tooltips and QuickAFL enabled CHANGES FOR VERSION 4.07.0 (as compared to 4.06.1) • help window is detached from application window • arrows generated by commentary window are refreshed properly when new rt bars arrive (arrows are shown for active symbol only) • e-mail alerts: support for servers requiring SMTP authentication. Supported methods: AUTH LOGIN (most popular), POP3-before-SMPT (popular), CRAM-MD5, LOGIN PLAIN • sound alerts: ability to test sound output in Tools->Preferences->Alerts • AFL error box popping up in AA when RT data are flowing does not cause a crash • custom minute bar compression improved - now you can have >60 minute bars and also bars not evenly dividing the hour. So you can have 39 or 73 minute bars for example • drawing date/time axis improved • drawing built-in charts optimized for very long histories • new AFL functions: + Interval() returns bar interval in seconds + RMI( periods = 20, momentum = 5 ) - Altman's Relative Momentum Index (S&C Feb 1993) + Status() function features new fields: "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 note: this should be used only if you really have to, indicator should be written without need to know how it is displayed + LastValue has new optional parameter LastValue( array, forcelastbar = 0 ); forcelastbar - changes the behaviour of LastValue when used in Commentary or Interpretation windows. By default it uses selected value, but if you use LastValue( array, True ) then it always use last bar instead of selected one. + SelectedValue( array ) • selection bar updates caption in all chart panes (displaying current values of all indicators). you can move selection-bar with <- and -> cursor arrows on keyboard as before but now when you reach left most or right most bar- the chart starts to scroll automatically • quote selection and caption display works different now: if selection-bar is NOT visible then the last VISIBLE bar data are displayed (not the LAST available), if selection-bar visible then selected bar data are displayed • new graph style = 8192 - plots point-and-figure-style O and X symbols instead of candlesticks High and Low table are used to determine the height of bar, Close-Open distance determines box size. If Close > Open - X's are drawn if Close < Open - O's are drawn. • added bitwise-and '&' and bitwise-or '|' operators to AFL language (note that floating point number are converted (truncated) to integers before applying bitwise operators) • new pre-defined constants for more descriptive code CHANGES FOR VERSION 4.06.1 (as compared to 4.06.0) • fixed tab order in Analysis window (Range radio buttons) (appeared in 4.06beta) • fixed problem with using AFL.Var with uppercase letters (appeared in 4.06beta) • fixed problem with using gSite.SetVariable / gSite.GetVariable with uppercase letters (appeared in 4.06beta) • fixed problem with exploration (appeared in 4.06beta) • fixed small display issue in the data tooltips (-1e10 displayed instead of {EMPTY}) • disabled QuickAFL until all issues are resolved CHANGES FOR VERSION 4.06.0 (as compared to 4.02.1) • New Interpretation window (View->Interpretation) displays chart-sensitive commentaries • new AlertIF function allows to generate visual, sound, e-mail alerts. It also allows to launch any external program on signal generated by AFL formula. • Automatic Analysis window now allows periodical scans (Scan every n minutes) • new Check feature in Automatic Analysis window allowing you to find out if your formula references future quotes or not. • Data tips show indicator values now and can show also interpretations of indicators • n QuickAFL technology implemented (Tools->Preferences->Miscellaneous -> Enable QuickAFL for indicators) - provides >10x speed-up in custom indicator charting with long histories (>1000 bars) • ability to modify / overlay additional graphs over built-in charts (Indicator Builder->Built-in tab) • ability to create your own interpretation commentaries in Indicator Builder • new AFL functions: • AlertIf( BOOLEAN_EXPRESSION, command, text, type = 0, flags = 1+2+4+8, lookback = 1 ); • SetBarsRequired( backward, forward= -1) - overwrites heuristic guessing algotithm used by QuickAFL technology. Allows to specify the number of previous (backward), and future (forward) quotes required by the formula to properly calculate - for advanced users only • GetBaseIndex() - retrieves symbol of base index as defined in Symbol->Categories. To plot base security chart just use graph0 = Foreign( GetBaseIndex(), "C" ); • EnableTextOutput( flag ) - enables output of strings into commentary / interpretation window. When flag = 0 no string is printed into commentary window, 1 - strings are printed • _N( text ) - the function that prohibits writing the values of assignment of string variables: _N( text = "this is a text" ); this does not print out the text being assigned into commentary window. • filtering weekends (File->Database Settings->Intraday settings->Filter weekends) • Commentary and Interpretation window are automatically refreshed when charts are refreshed • OLE automation Quotation.Date (GetDate) includes time also • AFL engine symbol lookup optimized so AFL engine initializes 2x faster and symbol lookup is also faster • when scrolling zoomed-out chart (that displays more than 2048 data bars) the refresh is delayed a little. This makes scroll bar more responsive and it takes much less to scroll to desired position when working with >100000 bars. CHANGES FOR VERSION 4.02.1 (as compared to 4.02.0) • added automatic ruin stop that closes all trades loosing more than 99.96% CHANGES FOR VERSION 4.02.0 (as compared to 4.01.0) • added ability to filter after-hours trading (File->Database Settings->Intraday settings : Filter after-hours box plus definable session start/end (per-workspace settings) • added ability to shift time displayed on charts/dialogs File->Database Settings->Intraday settings : Time Shift (AmiBroker uses computer local time, so it displays realtime quotes using the time of the timezone you are in. For example if you live in Warsaw - NYSE-quotes stocks will start 15:30 local (Warsaw) time. If you want however to display time as it is in New York (-6 hours -> 9:30) you have to set Time Shift to -6. • fixed problem with importing very long intraday histories > 300000 bars (if you want to import that long histories you have to go to File->Database Settings and change "Default number of bars" to at least 3000) • fixed a bug in intraday -> daily time compression • fixed "no trade list" display of Exposure and RAR • when writing the formula to HTML report < and > characters are encoded to &lt; and &gt; to ensure that formula is not truncated. • "Apply" button in Indicator Builder inserts/modifies the custom indicator only if the formula is correct. This avoids continuously displayed error messages when working with real time streaming data. • fixed bug in list view sorting of numeric columns containing small values • fixed crash occuring when Equity() function was called from Commentary window • fixed display of huge numbers in the chart grid • added option to color up/down (traditional) bars : Preferences -> Main chart • other minor fixes CHANGES FOR VERSION 4.01.0 (as compared to 4.00.0) • Customisable N-tick charts in Real Time version (see Preferences -> Intraday tab) and new View->Intraday menu • Ability to backtest custom N-tick bars • Backtester now makes better decisions on desired order of execution of signals that occur the same day. (if both buy and sell (or short and cover) signals occur on the very same bar and there is already open trade from the any of the previous bars this open trade is closed first, and a new trade is opened next. Otherwise the usual order (buy first then sell) is used. CHANGES FOR VERSION 4.00.0 (as compared to 3.99.2) • ASCII importer now handles also HMM time format (in addition to HHMM) • file dialogs store its most recently used directory properly again (not one level higher) • other minor changes CHANGES FOR VERSION 3.99.2 (as compared to 3.99.0) • fixed bug occuring on exit when no document window was open • double click on ticker tree displays a chart window if no window was open • Foreign() function does not show error message box if referenced symbol does not exits in the database - instead it returns {EMPTY_VAL} • user text holds on chart again (fix to the bug induced by 3.97) • caption of weekly bar shows friday as end date in "show bar begin time" mode • focus switches back to AFL editor on AFL error in AA/Indicator Builder windows • backtester checks if high and low prices are different than zero - before trying to adjust buy/sell/short/coverprice arrays to high-low range. In normal case this was not the case but if you were backtesting composite equity (you should not but...) which has only close array != 0 you got Profit N/A and other strange numbers in previous version (this was really user-error, you should not include composite equity tickers in the backtest because it makes no sense) • by default AddToComposite function adds new tickers to market 253 (instead of 0) now • fixed bug in handling points-only mode by Equity function • fixed predefining of BuyPrice/SellPrice/ShortPrice/CoverPrice arrays in Ind. Builder • obsolete controls removed from Preferences/Data tab • some RT improvements (3.99.1) CHANGES FOR VERSION 3.99.0 (as compared to 3.98.1) • Equity function has new syntax SYNTAX: Equity( Flags = 0, RangeType = -1, From = 0, To = 0 ); where NEW PARAMETER Flags - defines the behaviour of Equity function 0 : (default) Equity works as in 3.98 - 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 visualise 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 flag is documented but in 99% of cases should not be used in your formula. Other values are reserved for the future. RangeType, From, To - arguments as described in v3.98 Example: Buy = High > Ref( HHV( High, 20 ), -1 ); Sell = 0; ApplyStop( 1, 1, 5, 1 ); Equity( 1 ); exit is made only by apply stop, thanks to new equity(1) you can see sell arrow generated by ApplyStop • in Automatic analysis window you are now able to display buy/sell/short/cover arrows for ALL actual trades (a new option is available from right mouse button menu over the result list, and via double click + ALT key) • Backtester now reports the type of stop that exited the trade (max loss), (profit), (trail) - are added to mark trades that were closed by max. loss stop, profit target stop and trailing stop respectively. You can also mark your own reasons for exit by assigning numerical value to sell, cover arrays: 1 - means normal exit, 2 - max loss, 3- profit target, 4-trailing stop, 5 - 9 reserved for future use (other types of built-in stops. 10 and above - custom exits labelled by Long (n) or Short(n) where n is a number > 10 Example: cond1 = Cross( EMA( Close, 20 ), Close ); cond2 = Cross( Signal(), MACD() ); Buy = Cross( MACD(), 0 ); Sell = IIf( cond1, 10, IIf( cond2, 11, 0 ) ); • new AFL function: ExRemSpan( Array, NumBars ) FUNCTION: Removes excessive signals that span NumBars bars since initial signal. (In other words first non-zero bar passes through, then all subsequent non-zero bars are ignored (zero is returned) until NumBars bars have passed since initial signal. From then on a new signal may pass through) This function makes easy writing exits after a fixed number of bars, for example if you want to sell always 5 bars after the buy you should now use combination of ExRemSpan and Ref(). It will work even if initial buy array has lots of redundant signals: Buy = 1; Buy = ExRemSpan( Buy, 5 ); Sell = Ref( Buy, -5 ); • some minor bug fixes CHANGES FOR VERSION 3.98.1 (as compared to 3.98.0) • fixed "freezing" problem when AmiBroker was re-launched with an empty Equity chart • equity graph is plotted correctly even if your system uses graph/Plot statements • previously saved AA settings are restored at the application startup so, Equity plots use correct settings without the need to re-open AA window. CHANGES FOR VERSION 3.98.0 (as compared to 3.97.1) • Equity() function implemented SYNTAX: Equity( RangeType = -1, From = 0, To = 0 ); where 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 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 FUNCTION: returns Equity line based on buy/sell/short/cover, **price, all apply stops, and all other backtester settings. NOTES: 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 USAGE: buy = your buy rule; sell = your sell rule; graph0 = Equity(); • automatic Equity plot (Automatic Analysis window -> click on Equity button (after backtesting)) • BuyPrice, SellPrice, ShortPrice, CoverPrice, PositionSize variables are predefined also in the Indicator Builder (no "undefined identifier" error in IB) • AA scan mode displays also short/cover signals now • Value Label is not displayed when graph has {EMPTY} value • new graphNstyle value = 4096 - don't draw value label for this graph line • immediate refresh after bars are received from eSignal plugin • eSignal plugin now works with afterhours data (FormT) • new docking windows (supporting multiple windows in one row) + renamed window titles • an option to automatically tile mutliple chart windows • zoom out toolbar button added • hourly/intraday periodicity toolbar buttons added • fixed positionsize handling for short trades it is now checked at short signal (not cover as before) • other fixes CHANGES FOR VERSION 3.97.1 (as compared to 3.97.0) • value labels do not overlap (greetings to AmiBroker group:-) • value labels text is written in white or black depending on the brightness of the label • vertical line should be visible much better • fixed problem with overwriting OHLC price arrays in AFL formula CHANGES FOR VERSION 3.97.0 (as compared to 3.95.0) • Realtime Market watch (RT only) window implemented (disabled when data plugin is not RT-enabled) + internal improvements for RT handling • UNDO for Drawing tools implemented (Ctrl+Z, or Edit->Undo) • StrLeft( string, count ), StrRight( string, count ), StrMid( string, start, count ) AFL functions implemented • improvements to AddToComposite function: • AddToComposite( array, "artif_ticker", "X", flags = 7 ) accepts "X" field definition (in addition to regular OHLCVI) "X" means update O, H, L, C fields simultaneously • flags parameter is the sum of the following 1 - reset values at the beginning of scan (recommended) 2 - put composite ticker into group 253 and EXCLUDE all other tickers from group 253 (avoids adding composite to composite) NEW: 4 - put last scan date/time stamp into FullName field • when a AddToComposite() adds a new ticker stock tree is automatically refreshed • when "continuous quotations" box is unchecked - intraday and daily charts default to line chart • candlesticks can be now drawn in 4 different styles - seePreferences - Miscellaneous tab "Use distinct color for candlestick...."- the default settings gives you "classic" AmiBroker look but I suggest to check all 4 possibilities because color bars look much better in "Shadows only" mode for example • vertical line separating days in intraday and years in EOD charts is now optional • added labels showing the end value of each graph line (to switch off go to Preferences - Miscellaneous - "Show value labels") • new style for graphNstyle variable: 2048 - do not rescale Y axis. • new database dialog suggests a following path for a new database <current working directory>\MyNewDatabase • time out for slow external COM objects is increased to 10sec (should help slow responding TC2000 server) CHANGES FOR VERSION 3.95.0 (as compared to 3.93.1) • new functions in AFL: Weighted Moving Average - WMA( array, periods ) - accepts variable periods (array) Double Exponential Moving Average - DEMA( array, periods ) - accepts variable periods (array) Triple Exponential Moving Average - TEMA( array, periods ) - accepts variable periods (array) TimeNum() - returns bar time HHMMSS: 15 hours 23 minutes and 30 seconds is represented by 152330 Hour(), Minute(), Second() - return bar hour, minute and second • AFL Open/Save As file dialogs remember also file name of the most recently saved formula • Printing directly from AFL editors implemented - right mouse button over the formula window then choose "Print" • no overlaping texts on date axis anymore • selected quotation (vertical line) does not disapear when chart is scrolled or refreshed • price chart now display vertical line dividing days (in intraday modes) and years (in daily/weekly/monthly modes) • Refresh feature fixed (once again) + simultaneous refresh of mutliple symbol charts implemented • Auto-refresh driven by plugin implemented (now only eSignal plugin utilises this feature) • if only it is possible, scroll bar is NOT moved to the last bar after chart refresh (but new bars arriving from RT plugin show up :-)) • Edit->Delete quotation and Edit->Delete session force chart refresh • AmiBroker now notifies previously used data plugin when user chooses a different one or loads the database that uses a different plugin (this allows closing internet connections for example) • when ExitAtStop is switched OFF - max. loss and profit target stops are triggered by examining SellPrice/CoverPrice tables instead of High/Low (trailing stop worked that way since the beginning) • trendline properties dialog works correctly also for intraday charts now (additional edit boxes for start/end time) • OLE automation: new method added to Stocks collection: string GetTickerList( long type ) (type = -1 - all tickers) - returns comma separated ticker list • fixed problem tha occured with "show current trade arrows" applied to intraday charts • fixed crash that occured when one tried to import empty tickers using$NOQUOTES mode
• fixed hangup when displaying charts of values greater than 10^15
• fixed crash when importing ASCII files with time given in format HH:MM (without seconds)
• minor bug fixes
• HTMLView.exe program: only Save As... option is now left and it works OK.
Also reduced program size from 36KB to 19KB :-)
Balance Of Power and Money Stream via GetExtraData call:

CHANGES FOR VERSION 3.93.1 (as compared to 3.93.0)

• AddToComposite works ONLY in scan mode now
• fixed "Delete" feature in Symbol->Organize assignments
• fixed "Edit formula" feature
• cosmetic fix in charting: when only flat line = X is plotted scale is set from X to 1.1*X

CHANGES FOR VERSION 3.93.0 (as compared to 3.92.0)

• new AFL function AddToComposite( array, "ticker", "field", flags = 3 )
single function replacement of JScript/VBScript composite formula described in newsletter 12/2001. Allows you to create composite indicators with ease.
Parameters:
array - the array of values to be added to "field" in "ticker" composite symbol
"ticker" - the ticker of composite symbol. It is advised to use ~comp (tilde at the beginning)
newly added composites are assigned to group 253 by default and
have "use only local database" feature switched on for proper operation with external sources

flags - contains the sum of following values
1 - reset values at the beginning of scan (recommended)
2 - put composite ticker into group 253 and EXCLUDE all other tickers from group 253

AddToComposite function also detects the context in which it is run
and does NOT affect composite ticker when run in Indicator or Commentary mode,
so it is now allowed to join scan and indicator into single formula.

Simple usage example:

AddToComposite( MACD() > 0, "~BullMACD", "V");
graph0 = Foreign("~BullMACD", "V");

(now you can use the same formula in scan and indicator)

• Ultimate() indicator now uses H/L prices instead of just close
• Status() function supports new argument:
Status("action") - gives information in what context given formula is run
1 - INDICATOR, 2 - COMMENTARY, 3 - SCAN, 4 - EXPLORATION, 5 - BACKTEST / OPTIMIZE
• Quotations editor now allows easy adding new quotes in Single symbol mode (note (new) entry at the beginning of the quote list - select it and edit new quote)
• Stock menu renamed to "Symbol"
• Market, Group, Sector and Industry information is shown in the status bar
• Fixed synchronization between tree and ticker bar
• Deleting stock selects next symbol (not 2nd next)
• View->Refresh fixed
• Metastock importer and plug-in now support also intraday MS databases
• Double click on the result list in Auto-Analysis window switches correctly the periodicity also for intraday charts
• buy arrows are green and sell arrows are red regardless of custom palette settings
• removed warning for running backtest over 1000 issues in no-trade mode
• when new database is loaded charts are switched automatically to DB's base interval.

CHANGES FOR VERSION 3.92.0 (as compared to 3.90.6)

• intra-day support implemented in charting engine
• ASCII importer & wizard now feature new field definition: TIME (allowable formats: HHMM, HH:MM, HHMMSS, HH:MM:SS )
• intra-day support added to the backtester/optimizer
• Database settings window features time base setting
• sorting by ticker after backtest in no-trades mode works OK now
• number of rows in the result list is reported in exploration/scan modes
• AA export to CSV file does not include formula when you unmark "formula" check box in the settings
• Find feature implemented in all AFL editors - press Ctrl+F to find text
• specifying graphNstyle 64 or 128 causes scaling based on H/L array in custom indicators
• added "Edit formula" option in the chart context menu that allows instant editing of custom indicator formula.
• other minor fixes

CHANGES FOR VERSION 3.90.5 (as compared to 3.90.4)

• Assignment organizer: Delete option asks for confirmation and allows you to cancel
• Assignment organizer: Tooltip texts updated: more appropriate "Move" is used instead of "Copy"

CHANGES FOR VERSION 3.90.4 (as compared to 3.90.3)

• the fixup file name procedure checks also for CON, AUX, NUL reserved words, also it matches only full strings not substrings so tickers like LPTH, WBPRN are no longer translated to LP_H and WBPR_
• Foreign and RelStrength functions now have one additional argument
Foreign( "ticker", "field", fixup = 1 )
RelStrength( "ticker", fixup = 1 )
the default value of fixup is 1 and causes filling the holes in data with previous values (behaviour introduced in 3.90.3), if fixup is 0 - the holes are not fixed (the old, pre-3.90.3 behaviour)
Note: you can still use Foreign/RelStrength in the old way:
Foreign( "ticker", "field" ), RelStrength( "ticker" ) - then the holes will be fixed.
• Plugins: QP2 and TC2000 plugins always refresh the most recent bar data
(useful for performing intra-day updates of the last daily bar)
• other minor fixes and checks

CHANGES FOR VERSION 3.90.3 (as compared to 3.90.2)

• safety check added to AA/Scan to prevent occasional access violation exceptions while running scans that add quotes to the current symbol
• added safety check for too long graph title strings specified in Plot() function
• stock tree is properly refreshed after Edit->Erase watch list(s)
• now View->Refresh updates just charts and 'in-memory' cache so after updating your external source it is enough just to click View->Refresh. "View->Refresh ALL" additionally refills symbol tree and ticker list
• Database settings dialog does "Flush cache" automatically if "number of bars" or "data source" have changed
• a new setting in the Preferences->Misc allowing you to switch off the display of data plugin activity (this provides a little speed-up)
• a confirmation box added to "Delete all studies"
• Tab order fixed in quotations editor
• a new checkbox "Load this database at startup" added to the "File->New Database" dialog - this allows to automatically set newly created database as a default one.
• if there are data holes / misalignment in the foreign security Foreign() function returns a previous quotation value instead of {EMPTY}
• bug report window now provides memory status and cache stats.
• new button "copy to clip" added to the bug report window to make copying the text of the report easier.

CHANGES FOR VERSION 3.90.2 (as compared to 3.90.1)

• fixed random crashes occuring when list view column was clicked for sorting
• 2 digit year window changed to cover 1920-2019 instead of 1950-2049 so ASCII importer treats YY as 19YY when YY >= 20 and 20YY when YY < 20
• fixed sorting of very large numbers (bug was present only in 3.90.x)
• AmiBroker now protects the user from saving the database into the folder that contains other applications' data files - this avoids problems when user does not recognize the fact that AmiBroker database is different than MS, QP2 or TC2000 databases and should be stored in a separate folder.
• AmiBroker estimates the optimal size of "in memory" cache at start-up when the user hasn't changed the default 10. (here is how it works: AmiBroker checks your Preferences->Data "in memory cache" setting at startup (only) - if it is equal to "10" (the old default) - it calculates the estimate according to the following formula:
25% * (total RAM memory in your computer)/( (size of single quotation) * (default number of bars loaded) ). So the goal is to utilise 25% of physical RAM for the cache.)
• Optimizer uses more accurate calculations for fractional step, min, max values
• Bug report button handling modified: spaces in mailto: string are replaced with %20 sequences - this should address the problems with Outlook
• a nice "N/A" is shown instead of ugly "1.#R" in the backtester
• a "system % drawdown" figure in optimization result list matches the correct value shown in the backtest report (multiple security test/optimize).

CHANGES FOR VERSION 3.90.1 (as compared to 3.90.0)

• OLE automation Quotations.Add method initializes the fields to zeroas pre-3.84 versions did, so VB/JScript composite formulas work OK again.
• adding a new symbol in the formula (via Stocks.Add) sometimes caused reallocation of the symbol table and misplaced pointers - a check and fixup after parsingis added
• risk/yield map now shows progress window during calculation
• workaround over the limitation of Windows progress bar (65536 items max.) implemented to display bar properly for more than 65K steps of optimization
• review window layout changed, introduced a "Show" button and a new 'entertaining' mode: "Show immediately"
• other minor fixes

CHANGES FOR VERSION 3.90.0 (as compared to 3.88.0)

• Automatic Analysis result list works now in virtual mode which is much faster:
• Now "Removing items" time is virtually eliminated :-) (>100 times faster)
• scans/backtests/explorations run 20%-70% faster
• sorting by columns is approx. 2 times faster
• copying contents to the clipboard is >20 times faster (200'000 rows (1MB) below 1 sec.)
• stock tree works faster and better (actually I could write a book on this point :-))
• "Use only local database" box in the Stock->Information window allows to store certain symbols in local database while the others are retrieved from external database (as set in File->Database Settings)
• OLE Automation interface: 2 new properties of Stock object:
DataSource ( 0 - default, 1 - local only )
DataLocalMode ( 0 - default, 1 - store locally, 2 - don't store locally)
• new AFL function Version( minrequired = 0 ) that returns the AmiBroker version number as float ( 3.88 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 :)
• new AFL function: Random() returns an array of random values in 0..1 range (to get single random value use LastValue( Random() ) )
• info tip added to list view controls (to see truncated cell items...)
• fixed bug causing double delay when using short = sell; cover = buy; in your formula and setting non-zero delays for all buy/short/sell/cover
• Clicking "OK" in File->Database Settings dialog marks database as "changed" so it gets saved automatically.
• ASCII importer now supports retrieving date from filename use $DATE_YMD,$DATE_DMY, $DATE_MDY in .format file to specify the date format • every module uses its separate progress bar so potential conflicts are eliminated • progress bar shows only changes greater or equal to 1% - this provides a little speed up • a progress window is shown also for single-symbol optimization • an estimated time left for multiple symbol optimization shown in the progress window is a time needed to complete the whole process (not just the single step) • data field names in Foreign() function are no longer case sensitive • AFL editor preferences now allow to switch on/off word wrap (requires re-run) • Automatic analysis window now contains Ln/Col indicator • AFL errors are now reported with a line and column numbers and the place where error occurred is automatically selected in the editor • JScript/VBScript errors are now reported with the absolute line number (not relative to the beginning of the script block) and automatically selected in the editor (caveat: due to the way how JScript/VBScript engines work the line number is correct when lines are not wrapped in the editor (line numbers in AFL-only are always OK) ) • optimizer displays error message "missing buy/sell variables" only once • other minor fixes CHANGES FOR VERSION 3.88.0 (as compared to 3.87.2) • position sizing in backtester implemented: new reserved variable PositionSize = <size array> • new checkbox in the AA settings window: "Allow position size shrinking" - this controls how backtester handles the situation when requested position size (via PositionSize variable) exceeds available cash: • when this flag is checked the position is entered with size shinked to available cash • if it is unchecked the position is not entered • new report mode in AA settings window: "Trade list with prices and pos. size" CHANGES FOR VERSION 3.87.2 (as compared to 3.87.1) • the most recently used AFL path is now saved separately for Systems, Indicators and Commentaries • caption bar's maximize button works now also in Indicator builder and Commentary windows • "Flush cache" button added in the File->Database settings window to clear in memory cache without exiting AmiBroker • a safety check added for GetQuotationAt() function • fixed the problem with running AmiBroker on Windows 2000 as a restricted user causing harmless but annoying message "Failed to update the system registry. Please try using REGEDIT" (This is a bug of Windows 2000 described in MSDN: Q254957 ) • fixed problem with handling C++ like comment (//) at the end of the formula • fixed bug with converting empty AmiVar to array (at @42ecc7/3.87.1) • fixed problem with "Save database AS" (into a new directory) • QP2 plugin: GetExtraData("HasOptions") returns true (1) when stock is optionable false (0) otherwise CHANGES FOR VERSION 3.87.1 (as compared to 3.87.0) • fixed bug occuring when there was a syntax error at the end of a very long single-line statement (>256 characters in single line) and AFL tried to display the error message. • fixed bug causing infinite loop when running auto-analysis in weekly/monthly mode (bug appeared in 3.84 beta) • fixed small bug in Metastock plugin causing duplication of last bar quote CHANGES FOR VERSION 3.87.0 (as compared to 3.86.0) • in "report no trades" mode backtester generates a summary result list instead of listing every trade - this consumes less memory and makes backtesting 2-3 times faster and it is recommended for backtesting more than 1000 symbols at one time it also allows to export performance statistics to CSV file • status bar now shows DB changed state as yellow icon - also it displays additional information - number of symbols loaded and the path to the database when you hover the mouse over the status bar icon. • fixed bug when recalculating composites • fixed bug sometimes causing access violation when accessing weekly/monthly data • fixed potential bug in progress bar causing FLT INVALID OPERATION at address 10007dd9 • fixed problem with weekly data compression of pre-1970 dates • About box shows more links • fixed problem with interference between buy/sell/short/coverprice tables and built-in trailing stops (ApplyStop) when testing both short & long • Quotations editor now displays a progress bar in All Stocks/Single quote mode • COM message filter implemented allowing proper operation of slow, out-proc data plugins like TC2000 • QuotesPlus plugin (QP2.DLL) exposes 2 new extra data: GetExtraData("briefing") - gives briefing text (STRING) GetExtraData("QRS") - gives Quotes Plus relative strength (ARRAY) • QuotesPlus plugin (QP2.DLL) checks for qp_ticker_invalid to exclude invalid tickers • TC2000 data plugin implemented featuring direct quote read, sector/industry retrieving, exchange/index grouping • Metastock data plugin implemented featuring support for unlimited MS data directories (so you can setup AmiBroker to use multiple MS directories to overcome MS 4096 symbols per folder limit) • Tools->Plugins dialog does not load DLLs multiple times when "Load" button is hit more than once. • Tools->Plugins dialog now shows if given DLL is certified. ("certified plugin" means it was tested by AmiBroker.com for stability and compatibility with AmiBroker) CHANGES FOR VERSION 3.86.0 (as compared to 3.85.0) • num of winners / num of loosers figures in the backtesting reports take commissions into acount (previously only gross profit (without subtracting commission) decided if given trade was considered winner or looser) • optimization results now include point gain (in addtion to % gain) so "point only" optimization results are sorted correctly • optimization results now list "N/A" instead of ugly "-1.$" or "-1.#" when the figure is not available
• after "optimization" mode is run "Report" button is disabled because it always gives last optimize step result which in most cases is not the best one - and thus may be confusing
• Metastock importer handles correctly dates before 1950
• names like PRN, LPT, AUX are converted to PR_, LP_, and AU_ to avoid problems with Windows file system reserved words

CHANGES FOR VERSION 3.85.0 (as compared to 3.84.0)

• new AFL function GetExtraData() - allows retrieving vendor-specific data (QP2 plugin demonstrates accessing fundamental data)
• fixed bug causing crash when saving database after copying AA result list to watch list
• adding full name in tree and ticker bar works again
• "In memory cache" setting in Preferences/Data had no effect on real cache size - this is fixed now
• Quotes Plus plugin (QP2.DLL) retrieves now also mutual funds, futures, in addition to sectors/industries it sets up also markets and groups
• Quotes Plus plugin allows access (via AFL function GetExtraData( <fieldname> ) ) to the following fundamental figures:
"AnnDividend" ,"Shares", "SharesFloat", "SharesOut", "SharesShort", "TTMsales", "Beta", "TTMEps", "HiPERange", "LoPERange" , "PEG", "InstHolds", "LTDebtToEq", "CashFlowPerShare", "ROE","TTMSales", "Yr1EPSGrowth", "Yr5EPSGrowth", "Yr1ProjEPSGrowth", "Yr2ProjEPSGrowth", "Yr3to5ProjEPSGrowth" , "BookValuePerShare"

CHANGES FOR VERSION 3.84.0 (as compared to 3.80.4)

• internal database handling rewritten for more speed and external data link capability
• data plug-ins interface implemented
• Open Interest displayed in the data tip
• a new settings in Preferences window for Data feed selection
• local caching (both in-memory and file-based) implemented
• tree filling optimized for large number of stocks >1000
• ticker bar rewritten - now allows direct typing of ticker name (F4 - hot key)
• trailing stops work correct when testing both long & short trades

VERSION 3.80 RELEASE NOTES

Version 3.80.2 (November 18th, 2001) includes following new features and bug-fixes (as compared to 3.70.0)

• text box uses the color set in the toolbar color picker
• "Exclude" variable works correctly also with arrays
• ASCII Importer accepts also comma (,) as a decimal part separator if fields are delimited by different separator
• Import wizard generates correct $SEPARATOR \t command when Tab separator is selected • the color indexes in graphNcolor, graphNbarcolor, Plot() are now consistently encoded • a default argument mode = 0 added to the following functions: GroupID( mode = 0 ), MarketID( mode = 0 ), SectorID( mode = 0 ), IndustryID( mode = 0 ) when mode = 0 (or no argument is given)- these functions return numerical ID (as in 3.79) mode = 1 - these functions return name of the category (text) • added predefined symbols True = 1 and False = 0 • Avg and A are highlighted by the AFL editor now • The number of chart sheet tabs is now definable by the user (from 1 upto 20 tabs) The default was increased to 8. A pager control added to scroll the tabs if there is not enough space to fit all tabs and the horizontal scroll bar • New AFL functions: AddColumn( array, name, format = 1.2 ); AddTextColumn( text, name ); Plot( array, name, color/barcolor, style = 1 ) • New reserved variable GraphNname = "string"; • "show current trade arrows" in AA window works correct also for "open long" and "open short" • AND, OR, NOT are highlighted in AFL editor • BuyPrice, SellPrice, ShortPrice, CoverPrice arrays are checked against High/Low range for every bar and adjusted if they are outside of the allowed range due to the wrong formula. Also these arrays are checked for {empty} values and fixed to back to the default set in Settings if an {empty} is encountered. • data tooltip is less sensitive to the mouse movement when a chart is zoomed in • sharing violation exception is now caught when trying to save AFL/CSV over the file that is opened exclusively by another application. • The on/off status of format toolbar buttons (thick line, dotted, right extend) is preserved between sessions • points only test for futures (prelim.) - commission handling adjusted to this kind of test • snap to price mode is active only in main price chart • show current trade arrows scrolls chart correctly also for short trades • bug report window lists also cooltool and mfc versions • if broker.prefs file is missing charts are not black anymore (bug occurred in 3.78) • additional safety check when loading layout files implemented • ability to sort custom indicators by name (ascending/descending) in Indicator Builder and Insert Indicator dialogs ( just click on the caption bar) • indicators are alpha-sorted now in all Insert menus and Indicator Builder • "Display in quick insert menu" option added in the Indicator Builder allowing to control which custom indicators appear in the menu. • when no data is available "N/A" is displayed in the backtesting reports instead of ugly 1.#J or 1.$
• plugin interface has GetVariable( name ), SetVariable( name, value ) functions this in fact was present in 3.78 - but not mentioned :-)
• ability to add entry/exit prices to the back test report, precision selectable 2 or 4 decimal digits
• Buy/sell arrows are not shown for out-positions
• 5 new AFL functions: GroupID(), MarketID(), SectorID(), IndustryID(), InWatchList( listno )
• a new option in Automatic Analysis window menu to add only *selected* items from the results list to the watch list(s) - multiple selection as usual Click+SHIFT, +CTRL
• snap to price does not affect horizontal line and text tools anymore
• fixed bug with handling unterminated C-like comments
• progress dialog does not flicker during optimization
• dynamic (time-variable) stops implemented (ApplyStop() function accepts now array as a third parameter)
• trailing stops implemented
• syntax highlighting editor: fixed bug causing deletion of the last character in the editor after delete (and other) command choosen from right mouse button menu.
• palette size increased to 56 colours - 40 pre-defined + 16 custom (from only 16 custom colours)
• Preferences now use new-style colour pickers
• a new toolbar to select study colour, dot/thick style and right-extend mode
• fixed problem with reporting a short trade followed immediately by single day long trade
• fixed problem with changing font face/size during paste via Ctrl-V
• fixed problem with uninitialized **price arrays in optimization mode
• log scale in custom indicator works now correctly:
• a new check box in the Indicator Builder added (Grid: Logarithmic)
• graphNstyle = 32 is not needed anymore (has no effect now) (this is to avoid confusion having different styles (log/lin) in multiple graphs)
• zooming does not scroll the chart to the end anymore
• wheel zoom/scroll is two times more sensitive (allows faster zooming/scrolling)
• Right-mouse-button menu came back in AFL editor
• Snap-to-price is 100% exact now
• AFL editor colorizes graphX*** and columnX*** variables also for X>2 (upto 29)
• AFL editor supports drag-and-drop operation
• AFL: GetScriptObject() function allows calling functions in the script part
• New AFL Syntax Highlighting editor (highlights AFL code only)
• New preferences settings for AFL editor font/colors/highlighting features
• New color picker implemented (currently used only in AFL editor settings)
• Edit->Snap to price - enables "snap to high/low" mode when drawing trend lines
• Edit->Copy (as bitmap) implemented
• Copy to clipboard list of results in AA and Quick Review implemented (press Ctrl-C to copy)
• AFL engine - DLL Plug-in interface implemented (separate specification available)
• AFL engine - COM support added:
• CreateObject( "server.class" )
• CreateStaticObject( "server.class" )
• ability to call methods in COM objects directly from AFL: ob.MethodName( param1, .... );
this allows writing/debugging your trading system in Visual Basic/Delphi and similar COM-enabled languages
• AFL: scripting host - added 2 new methods to AFL host object:
• AFL.CreateObject( "server.class" ) - mainly for completeness (duplicates new ActiveXObject functionality)
• AFL.CreateStaticObject( "server.class" ) - this one is very useful for COM objects that are slow to initialize (like QP2 objects). Thanks to this function initialization is done only once per AmiBroker session
• AFL: parser stops after first error
• AFL: RelStrength() and Foreign() functions now two times faster

VERSION 3.70 RELEASE NOTES

Version 3.70.1 (September 3rd, 2001) includes following new features and bug-fixes (as compared to 3.65.1)

• Optimization engine implemented
• added simple crosshair display (View->Crosshair)
• added refresh all views feature (View->Refresh)
• added Rectangle and Ellipse drawing tools
• Activation of child dialog makes also main frame active (currently works only for non-modal dialogs)
• AmiBroker MS importer now attempts to read Metastock's MASTER file first (before EMASTER) - this is changed because there is a bug in QuotesPlus MS export functionality - it does not update EMASTER properly so the dates in UI are displayed wrong even if they are imported correctly.
• Mouse wheel zooms the chart when CTRL key is depressed
• Variable-period simple moving average (MA function) does not crash if periods array has {empty} entries at the beginning
• a new button added to automatic analysis window allowing you to enlarge result list
• changing selected date automatically refreshes Guru chart commentary
• commentary output window background is now white by default
• reorganized toolbars and Insert menu
• double click on a study (in select mode) brings properties dialog
• Exploration does not crash anymore when a columnX has string value assigned to
• Exploration handles text columns (limitation: only the value of string at the ending point of analysis range is reported)
• new property of OLE Automation Stock object:
WatchListBits (long) - each bit 0..31 represents assignment to one of 32 watch lists to add a stock to nth watch list write (JScript example):
Stock.WatchListBits |= 1 << nth;
• AFL: modulo operator (%) added. Example 10 % 7 gives 3.
• fixed bug in reading filter settings in AA window causing (rarely) crash on Windows NT/2000 (3.69.0 only)
• added WATCHLIST <n> command and WATCHLIST field type to ASCII importer • Import Wizard now allows to select destination group and watch list • Metastock(TM) importer now allows to select destination group and watch list • Crosshairs are hidden when mouse is outside of chart windows • A Ctrl-H hot key is added for switching Crosshairs on/off • Chart context menu works OK when mouse is set to left-handed mode • Commentary buy/sell arrows are refreshed when switching from one stock to another (as in pre-3.68 versions) • AFL: ApplyStop( type, mode, amount, exitatstop ) function added that allows controlling stops from the formula level (overrides settings). This enables optimization of stops. Parameters: type = 0 - maximum loss stop, 1 - profit target stop, (more to be added) mode = 0 - disable stop, 1 - amount in percent, 2 - amount in points amount = percent/point loss/profit trigger amount exitatstop = 0 - exits at defined price field, 1 - exits at stop level • ability to change the number of custom indicators (Tools->Preferences->Other indicators : "Custom indicators" ) • Automatic analysis Range, Type, Date From/to and Filters are saved between sessions • AFL now recognizes "\t" escape sequence and converts it to the tab character (this allows easier columnized output in commentary window) • Recently used commentary formula is preserved between sessions • Editing study properties marks stock as "dirty" therefore causes proper saving • ASCII importer now allows space as year/month/day separators in date fields so dates like "20 Jan 2001" are accepted • variable-period version of Sum() is immune to {empty} values in periods table • variable-period versions of High/LowestSinceBars functions are more robust • other minor fixes VERSION 3.65 RELEASE NOTES Version 3.65.1 (August 6th, 2001) includes following new features and bug-fixes (as compared to 3.64.1) • AFL: Highest/LowestSinceBars accessed one array element too much when working with very short histories this is fixed now. • AFL scripting host: fixed passing string variables from AFL to the script • added a switch in Automatic Analysis Settings window to include/exclude listing out-of-market positions • Preferences "cancel" behaviour fixed • An underscore ('_') character can be now used in AFL identifiers • new look of "About" window • application code is optimized so it is both smaller and at least 10% faster • AFL: a new function status( "what" ) added for now only one propery is available "stocknum" which reports the ordinal number of the stock being currently scanned/explored/back tested in the future more run-time properties will be available • support for mouse wheel (scrolling charts) • back-testing reports now can include formula listing and settings • assignment organizer has ability to delete multiple stocks • stocks could be moved between watch lists using assignment organizer • eliminated memory leaks in AFL scripting host • AFL scripting host is at least 20% faster • AFL scripting host gives meaningful error messages • comments after script block are handled correctly VERSION 3.64.1 RELEASE NOTES Version 3.64.1 (July 24th, 2001) includes following new features and bug-fixes (compared to 3.64.0) • Intraday drawdowns calculated through all timespan of the system added • Switching periodicity to monthly/weekly works correctly now (previous version required switching to another stock first) • Compound annual returns are calculated correctly now • Fixed hang happening when backtesting very short date ranges VERSION 3.64 RELEASE NOTES Version 3.64 (July 22th, 2001) includes following new features and bug-fixes (compared to 3.61): • Backtester: Interest rate could be earned when out of the market • Out of the market positions are shown in the result list • Open trades are shown in the trade list • New backtest statistics: annual % profit for system and B&H, days in test, bars out of market, interest earned • Exposure and risk adjusted return stats added • Minor fixes in report statistics • Setting 1 day/quote range in AA gives really one day/quote in the results (instead of 2) • Metastock importer saves recently used selection list in import.tls file inside metastock data dir, so when you choose this directory again, your previous selection will be applied automatically. • Max. point and percent intraday drawdown calculation for system and buy&hold added • Backtesting report output uses separate CSS styles for <TH> and <TD> tags to avoid ALIGN=RIGHT in every cell that needs right alignment • Buy&hold profit and open positions reporting do not depend on at least one trade generated anymore - they are now reported regardless of any trades • a new reserved variable "exclude" added to handle cases when you want to exclude completely certain tickers from back testing AND buy&hold calculation • Metastock importer supports now more than 256 securities per folder • Metastock importer dialog features new mark all/none/add selection functions and allows sorting ticker list by symbol, full name, dates and type • Histogram custom indicator charts look better now (no lines below minimum drawn) • Date axis in the main chart looks better now (no overlapping month names when chart is zoomed out) • Backtest, scan and exploration support now also weekly and monthly mode • Auto-analyser settings allow you to choose different periodicity and show buy/sell arrows swith the chart to the current test mode automatically • Weekly/monthly mode time-compression now sets the date to the last day of each week/month for which quotes are available- this matches reality better (weekly mode is "end-of-week" and monthly is "end-of-month") • Small fix in weekly date handling VERSION 3.61 RELEASE NOTES Version 3.61 (July 8th, 2001) includes following new features and bug-fixes (compared to 3.60): • Fixed garbling text when storing the most recently used formula to registry after saving the AFL to file • AFL formula in automatic analysis is saved to registry BEFORE running any scan/explore/backtest so in case of crash the edited formula is preserved. • Fixed Stock->Split date handling (was broken since AmiBroker is handling date display according to system settings) • Second parameter (data field) in Foreign() function is not case sensitive anymore • Indicator Builder: when custom scaling Min/Max levels are equal AmiBroker switches to automatic scaling • Comparative Relative Strength chart, relstrength() and foreign() AFL functions work properly now also in Weekly and Monthly modes. VERSION 3.60 RELEASE NOTES Version 3.60 (June 5th/11th, 2001) includes following new features and bug-fixes (compared to 3.55): • SAR overlay in the main price pane uses accel. step/max defined in preferences • SAR preferences edit boxes now accept typing dot . (ES_NUMBER style removed) • Back testing settings are preserved between sessions • buyprice, sellprice, coverprice, shortprice arrays are now available in scan/exploration (to avoid "undefined variable" errors) • More detailed version info in About box. • Analyser now supports displaying arrows in two modes - • all (dbl. click on result list) - shows all signals/trades • current trade/signal (dbl. click with SHIFT key pressed) • When showing current trade arrows the chart is automatically scrolled to ensure that they are visible • Stochastic %K and %D as well as stochk stochd use the most common formulation with simple moving average smoothing instead of Wilder's smoothing. • AFL scripting host now implements IActiveScriptSiteWindow interface (this enables MsgBox and InputBox functions in VBScript) • Fixed bug in analysis settings - sell price field combo now works OK again • Improvement: buyprice, sellprice, shortprice, coverprice arrays available in AFL formula for reading (pre-initialized properly by the engine) • Tickers are not truncated to 3 letters in Risk/Yield map anymore. • Short/Cover arrows have the same color as sell/buy but they are hollow • Show dates setting in Indicator builder allows to add date axis to any custom indicator pane • AFL formula entry fields accept now upto 65535 characters on Win95,98,Me and 1 million characters on Win NT/2000 • Lexical analyser in AFL handles scripting begin/end (<% and %>) tags better • Stops are now working more precisely • Buy/sell arrows after backtesting show only currently selected trade entry and exit points. • Built-in stochastics use High and Low prices (not only close) • Trades closed out by stops are marked in the result list accordingly • Implemented AFL Active Scripting Host that enable mixing AFL with JScript/VBScript - (EXPERIMENTAL) • Prefs/Misc setting - No minimum size for resizing dialogs • Buy and sell at the same bar possible • Added separate variables for Short trades short/cover • Ability to control trade price : buyprice, sellprice, shortprice, coverprice (simulation of stop orders possible) • Added missing Broker.Application.Markets read-only property • Watch lists implemented: Add/Remove to/from watch list from stock tree context menu • Add/Remove favourites, info, delete and split from context menu • Erase watch list(s) (Edit menu) • Analysis results can be now added to a watch list automatically (context menu over result list) • Filters now include watch list selection • Fixed Bug in BAck-tester - stops do not generate false buys when testing long only • Implemented Profit Target stops • Fixed LLVBars, HHVBars problem appearing with very short histories (6 quotes) • "Exit at stop" option in Automatic Analysis allows to close the position at exact stop price (no slippage) • Automatic analysis window now support "Exploration" - for generating user-defined reports from database screens. Short instructions: You need to: • define filter variable that equals "1" for stock accepted • define numcolumns variable that defines the number of columns in the report • define column0, column1, column2, ...., columnX variables that get the values displayed in the report • optionally: define column0name, column1name, ... to name column headers accordingly • optionally: define column0format, column1format, ... to change the default 2 decimal digits output (1.5 gives 5 decimal digits, 1.0 gives no decimal digits) After running Exploration you can export the report to the CSV file using "Export" button. • Variable period MA() • Small fix to variable period Sum() • Layouts can be now saved to a file, enabling unlimited user-definable layouts possible - accessible by Right Mouse button menu over the chart "Layout" submenu options: Load, Save, Load default, Save as default • Switchable Excel-like chart sheets • Variable-period HHV, HHVBars, LLV, LLVBars, Sum(), Ref() functions (EXPERIMENTAL) • Polymorphic AFL function dispatcher choosing optimized version of the function depending if parameters are time-variant or not • Fixed problem with saving corrupted layout (happened when closing main frame when document frame was already closed by the user) • fixed "return from portfolio" figures shown in Automatic Analysis bottom line (reports worked well all the time) (v3.60.3) • showing buy/sell arrows works OK now if routines use *price fields (v3.60.3) • fixed yet another issue with chart sheets causing crash with very narrow panes (v3.60.3) VERSION 3.55 RELEASE NOTES Version 3.55 (April 22nd, 2001) includes following new features and bug-fixes (compared to 3.50): • Export Auto-Analysis trade list to a CSV file • Fibonacci retracement tool enhanced • now works in 4 different modes depending on the direction of trend line drawn: NE - gives (old-style) retracement in up trend SE - gives retracement in down trend NW - gives extension in up trend SW - gives extension in down trend • Added also 261.8% and 423.6% levels • Added very simple ASCII export of portfolio contents • AmiBroker now automatically saves preferences and current chart layout on exit - this can be changed back however (to the old behaviour) using new settings in Preferences->Miscellanous • "Current" button in Prefs/Miscellaneous sets the default database path to currently loaded database path • Merge Quotes feature (with overwrite/delete switchable and optional merged Ticker->Alias) • Double-click in Indicator builder list inserts chart pane when not already present • Open Interest field type available in ASCII Import wizard • Minor bug fixes • Metastock importer now handles correctly also 6-field binary Metastock format (in addition to 5- and 7-field formats) • 100 custom indicators + more indicators dialog • Apply in Indicator builder inserts chart pane when not already present • Study ID field added to study properties window • StrLen( String ) implemented • AMA( Array, SmoothingFactor ) implemented • AMA2( Array, ForwardFactor, FeedbackFactor ) implemented • Study( StudyID, ChartID = 1 ); implemented • ExRem( Array1, Array2 ) implemented • Flip( Array1, Array2 ) implemented • IsEmpty( Array ) implemented • IsTrue( Array ) implemented • Foreign( Ticker, DataField ) implemented • sorting by date works correctly in all list views • additional check for existing workspace directory is made during save • fixed bug occuring when blank pane was inserted and the user tried to read X,Y coords from it • auto-colouring bar trends possible from AFL (i.e. up in green, down in red, ) • date formatting works according to system settings • show currently selected "Guru Commentary" and "Auto-Analyser" in menu bar. • fixed display problem when using "Large fonts" Windows setting • Logical AFL operators cast {EMPTY} to FALSE automatically VERSION 3.50 RELEASE NOTES Version 3.50 (February 25th, 2001) includes following new features and bug-fixes (compared to 3.45): • fixed calculation of percentage profits for short trades in Automatic Analysis window • graphxspace parameter for custom indicators (defines % extra space added at the top and the bottom of the chart) • live display of X (date) and Y (value) co-ordinates in the status bar • charting engine now supports styles 512 (staircase) and 1024 (swing dots) needed for Gann Swing chart • ASCII importer capable of importing non-quotation data (NOQUOTES 1 command)
• fixed ASCII import wizard (user settings are accepted now without the need to switch back and forward again)
• ASCII import wizard handles non quotation data formats
• Automatic analysis and commentary windows display now currently loaded file name (in the title bar)
• buy/sell arrows generated from Automatic Analysis are now cleared when switching to another stock
• Sizable Find window
• Sizable Assignments organizer
• Sizable Categories window
• Sizable Quotations editor
• Automatically generated bug-report now features history of commands
• fixed DateNum() function: due to the limited resolution of single precision floating point number (7 significant digits) it was imposible to represent numbers like 20011231 accuratelly - the result was rounding to the nearest even number -> 20011232 which was wrong.
Therefore I decided that datenum() function will return numbers calculated as follows:
10000 * (year - 1900) + 100 * month + day
So 20011231 becomes 1011231 and 19951231 becomes 991231
• ValueWhen() accepts negative (and zero) occurence index allowing referencing future (needed for true Gann swing chart)
• charting engine now support individually coloured bars (graphNbarcolor variable in AFL)
• Buy/sell arrows after screening/system test (When the result list in Auto Analysis window is clicked AmiBroker draws now buy/sell arrows on the chart (like Commentary does))
• Fixed lots of potential access violation holes when using empty database and/or stocks with no quotes
• New setting for Volume/Turnover chart in Preferences
• Turnover chart caption display fixed
• Crash recovery system implemented
• Fixed bugs in ASCII importer
a) Full Name as a last field does not need quotation marks anymore
b) Data conversion is more fault tolerant
• Sectors and Industries in the tree
• Find window remebers last search type (name/ticker)
• Fixed bug in Automatic analysis "Load all when selected" feature causing partial data loss when saving data

VERSION 3.45 RELEASE NOTES

Version 3.45 (January 6th, 2001) includes following new features and bug-fixes (compared to 3.42):

I User interface / usability enhancements

• ASCII Import Wizard
• improved Stock Finder window (single click select, sorting columns, remebers last search, asynchronous (non-modal) window)
• sizing Quick Review
• sorting columns in Quick Review
• sorting columns in Automatic Analysis
• sorting columns in Portfolio manager
• full row select in Indicator builder

II AFL - 17 new built-in functions

• HighestSince( expr, array, nth )
• HighestSinceBars( expr, array, nth )
• LowestSince( expr, array, nth )
• LowestSinceBars( expr, array, nth )
• Wilders() averaging
• LinRegSlope( array, periods )
• RWILo( minperiods, maxperiods)
• RWIHi( minperiods, maxperiods)
• RWI( minperiods, maxperiods )
• StDev( array, periods )
• DateNum()
• Year()
• Month()
• Day()
• DayOfWeek()
• Correlation( array1, array2, periods )
• Prefs( index )

III Fixes and other enhancements

• Fixed PeakBars(), TroughBars functions (Nth parameter was working correctly only for Nth=1, now they work correctly for all Nth values)

• ADX/DMI and SAR charts now use proper colors and parameters (taken from prefs) (also ADX/DMI now prints +DI -DI in the title bar - less confusion)
• Printout background is always white and white chart elements are replaced with screen background color for printing
• News URL edit box in categories is disabled (will be used in the future)
• Traditional bars are plotted now with open (left) tick
• Fixed date handling in Quotations Editor, Review dialog, and Split dialog

VERSION 3.42 RELEASE NOTES

Version 3.42 (December 16th, 2000) includes following new features and bug-fixes (compared to 3.41):

• A bug with OLE Automation fixed: in all pre 3.42 versions when you assigned (from the script) a different ticker to a stock using Ticker property of Stock object AmiBroker updated the ticker but didn't sort the ticker list. Because many internal functions assume that stock list is sorted correctly this caused: duplicate entries, crashes, wrong update of quotes, etc. Also when given ticker already exists it is overwritten with a new one correctly (no duplicate entries). All these problems should be gone now.
• A new method of Broker.Application object: Log( Action). Where possible values for Action are: 0 - delete import log, 1 - display import.log, 2- ask the user and display import.log.
• Sharenet importer now handles all possible locations of Sharenet downloader and data folder. The location of Sharenet downloader is defined by "Initial directory" parameter in Tools->Customize dialog, and location of data folder is now defined by "Arguments" parameter in Tools->Customize. The defaults for these parameters are: C:\Program Files\Sharenet\Sharenet Download Service and C:\snet. If you installed Sharenet downloader to other than default locations you may change these parameters accordingly and importer script will work correctly
• Sharenet importer now uses new Log() method so it displays warning messages if there were any erroneous lines in the data file(s).
• Risk yield map now handles high standard deviation (risk) better (this was included in 3.41 just forgot to mention)

VERSION 3.41 RELEASE NOTES

Version 3.41 (December 10th, 2000) includes following new features and bug-fixes (compared to 3.40):

• Automatic analysis, Indicator Builder and Commentary windows are now resizable (see the sizing gripper in the bottom right corner of these dialogs) and could be also minimized;
• ASCII importer now warns that errors occurred during import process and displays the log on your request;
• "Rename" button added to Indicator Builder window for easier change of custom indicator names;
• A brand new installer (using InnoSetup technology) with modern look and much better functionality:
• upgrade procedure is much easier (no need to manually replace files)
• All import format definition files (*.format) and import.types file are moved to \Formats subdirectory. Additional import formats added.

VERSION 3.40 RELEASE NOTES

Version 3.40 (November 1st, 2000) includes following new features and bug-fixes (compared to 3.32):

I AFL

1.1 New built-in functions in AFL:

• sar( accel = 0.02, max = 0.2 ) - Parabolic Stop-And-Reverse
• pdi( period = 14) - Plus Directional Movement +DI
• mdi( period = 14 ) - Minus Directional Movement -DI
• adx( period = 14) - Average Directional Movement
• atr( period ) - Average True Range
• relstrength( tickername ) - comparative Relative Strength

1.2 Detailed statistics after back-testing your system

1.3 New report viewer allows PRINTING reports (and saving in HTML format)

1.4 Definable back testing parameters:

• initial equity
• commissions
• max. loss stop
• reporting options

1.5 Automatic analysis window:

• now allows scanning for only buy or only sell signals
• saves recently used formula automatically instead of macd() crossover
• allows scanning and back testing in user-defined from/to date range
• allows to analyse/back test all quotes even if partial loading is switched on

1.6 Indicator builder:

• new graphXstyle and graphXcolor allow more control over custom chart appearance
• now custom indicators can include even candlestick charts

1.7 AFL engine now supports overwriting built-in O, H, L, C, V arrays so you can calculate all built-in functions from different data.

For example you can calculate macd() from rsi():

close = rsi(); // overwrite built-in close with rsi()
macd_from_rsi = macd(); // macd indirectly uses close but this is overwritten with rsi

##### II USER INTERFACE & GRAPHICS TOOLS

2.1 More graphical analysis tools, enhanced existing ones:

• definable colors and styles for trend lines
• auto left- and right- extending trend lines
• vertical and horizontal line tools
• Fibonacci retracement tool
• Fibonacci time zones tool
• Text box tool

2.2 Study properties can be modified using special "Properties" dialog

2.3 Main chart:

• moving averages calculation could be simple or exponential
• Parabolic SAR can be added to a main price chart
• Price chart can be now displayed using Traditional bars

2.4 Candlestick fill colors definable and much more color settings

2.5 New built-in indicators: ADX/DMI, SAR

2.6 The ability to search for a stock by name, for when the ticker is unknown ( Stock Finder window (F3) )

2.7 The OPEN price in the grab bar of the main chart

2.8 Full name can be added to ticker in both tree/ticker windows

2.9 Ticker window is now resizeable

2.10 WebID field in Stock Information window works correctly now

3.1 $PRICEFACTOR command allowing multiplying prices by definable factor 3.2 Reorganized database file layout and enhanced database engine Using separate sub-directories for tickers beginning with each letter and digit improves database loading/saving times dramatically (up to 3 times when partial loading is on) 3.3 Import of long histories (for example AmiQuote .AQH files) speeded up to 10 times 3.4 Database and program is enabled for storing OpenInterest data. Support for OpenInterest is added to: • ASCII importer • Metastock(R) importer • OLE Automation interface • Quotation editor • AFL (openint predefined array) 3.6 OLE Automation interface: • Added IndustryID property in Stock object • Added IsDirty property - this property marks "changed" state of the stock and it is automatically updated when setting other Stock object properties ##### IV OTHER 4.1 Fixed directory structure creation (bug occurred in 3.40 beta) 4.2 A directory does not get appended to the recently used list if it does not contain valid AmiBroker database 4.3 For SHARENET users: Sharenet DN format definition added (sharenet.format file) and six.js script file modified in order to use new file - this should solve the problems with upgrading. Now you can import .DN files from directly from ASCII importer file dialog choosing appropriate type from "Files of type" combo VERSION 3.32 RELEASE NOTES Version 3.32 (August 9th, 2000) includes following new features and bug-fixes (compared to 3.31): • Any changes made using Assignments Organizer are now correctly saved • New options in View/Toolbars allowing to re-show hidden toolbars without tweaking the registry • OLE automation method Stocks.Remove() and Stock.Ticker property (setting the value) are working correctly now changing the file name accordingly • A new option "New workspace" added allowing you to create a directory for a new workspace • File/New removed (previous versions opened new chart window). This functionality is now provided by Window/New menu, that creates new window for simultaneous viewing charts of two or more stocks. Also new option Window/Clone allows you to open a new window for the same stock giving you the chance to see charts of the stock from different time ranges. • The update archive contains fixed aqd.format and import.types files for using with AmiQuote 1.1 VERSION 3.31 RELEASE NOTES Version 3.31 (July 4th, 2000) includes following bug-fixes (compared to 3.30): • Metastock importer now handles prices lower than 2.00 correctly (there was a bug in floating point conversion routine - Metastock uses very old Microsoft basic floating point format in the data file instead of standard IEEE format) • Metastock importer removes trailing spaces in ticker symbol and full name strings VERSION 3.30 RELEASE NOTES Version 3.30 (Jun 29th, 2000) includes following new features and fixes(compared to 3.25): • the ability to save the location of a custom indicator's window ("Save layout" option in the right mouse button menu) • the current price to the Portfolio manager's details • upto 8 recent database locations are available in File menu for quick open • the ability to skip what AmiBroker thinks are splits, then find the next • individual RS settings for group/industry/market (evaluated in this order) • the ability to have custom indicators display upon booting ("Save layout" option( • a visible indicator of when the database is changed • Enhanced database engine: ability to load database partially at start and load the rest on demand. This feature speeds up both loading and savind and allows to use AmiBroker on machines equipped with less memory (Preferences/Miscellanous) • Enhanced analysis support: Stop conditions and short-positions available during auto-analysis. • Enhanced quick-review and analysis windows support now filtering by market, group, sector, industry. Also double-click on the quick-review list will display its chart immediatelly • indicate the price under the pointer's hot spot (Price data tooltips - Prefs/Miscellanous) • Assignments to sectors/industries. • Position and state of toolbars is remembered between runs • Fixed out-of-bound array access when using AFL with very short quotation histories • Fixed minor memory leak when using Review/Analysis tools • Handling$DATE_*** format definition commands fixed Bug fix Import & export tools
• Built-in company Profile view using embedded web-browser (Win32) or multiview(Amiga)
• Built-in assignment organizer
• Handling composites: automatic recalculation of number of advancing/declining/unchanged issues
• Removed excessive line-feeds added when saving AFL formulas to a file
• Market/Group/Sector/Industry information is now workspace-related (not global anymore)
• Fixed handling quotation marks in ASCII importer
• Better handling of sizing of the splitter window
• TRIN indicator added (with two simple moving averages 15 + 45day) + settings in preferences
• Fixed right-mouse-button + SHIFT (chart reselection) menu handling
• Added $APPENDTICKER,$OVERWRITE, $FULLNAME,$INDUSTRY, $RECALCVOL,$RECALCAD commands and APPENDTICKER, ADVISSUES, ADVVOLUME, DECISSUES, DECVOLUME, UNCISSUES, UNCVOLUME field identifiers to the ASCII importer definitions
• Fixed memory handling bug sometimes causing crashes of Automatic analysis window
• "Save Results" option in Automatic analysis window now works (worked in Amiga version but it didn't in Win32)
• Ticker symbols now can contain file-system reserved characters such as *, ?, #, <, >, |, /, \. These characters are replaced by underscore _ in appropriate file name (ticker however remains unchanged).
• Added full support for composite data handling (advances, declines, unchanged) to the OLE automation interface: new objects Markets (collection), Market, ADQuotations (collection), ADQuotation
• AFL interpreter now displays meaningful error messages in AFL error window (already implemented on Amiga)
• Preferences dialog now handles "Apply now" button correctly
• AFL file dialog now "remebers" its last directory (Win32)
• WebID property to the Stock automation class added
• Custom tool menu items are displayed now correctly after adding items to the empty list in Customize Tools dialog
• "Toggle" button in Metastock importer added to simplify selection/deselection of multiple items
• Found workaround for extremely slow DeleteAllItems() method in Windows list control: now removing all items from list-view control is about 5 times faster (especially noticeable in Auto-Analysis window)
• Double clicking on the analysis results and in the portfolio shares list automatically selects given stock chart
• P/E and P/BV comparisons in Quick review dialog shows values even if they are negative

VERSION 3.25 RELEASE NOTES

Version 3.25 (Apr 26th, 2000) includes following fixes & new features(compared to 3.24):

• Progress indicator is displayed now on the status bar during ASCII import
• Quotation database handling is now optimized for fast access to the most recent data. The most often operation: adding new/updating recent quotations is 2-3 times faster. This is noticeable when working with large databases (>40MB)
• Fixed crash when deleting trend lines in weekly/monthly mode.
• Refreshing stock tree & combo is now optimized (2-3 times faster)

VERSION 3.24 RELEASE NOTES

Version 3.24 (Mar 23rd, 2000) includes following fixes (compared to 3.23):

• Fixed bug in Metastock importer which appeared in v3.23
• Deleting vertical trend lines now works without problems
• File open dialogs for Import ASCII, Teletext and Metastock "remember" recently used directories

VERSION 3.23 RELEASE NOTES

Version 3.23 (Mar 21st, 2000) includes following new features and fixes (compared to 3.22):

• New format definition commands in ASCII import:
Added $CONT,$MARKET, $GROUP,$HYBRID commands and MARKET, GROUP, INFO, REDUCTION fields descriptions
• Added user-definable file types and formats
• Ticker aliases added (recognizable by ASCII, Metastock and Teletext importers)
• Stock information enhancements: address field in enlarged to 128 characters, country and currency fields added (now informative only, but in future currency information will be used in portfolio for calculations)
• Bug fix: Stock list is now refreshed after ASCII import
• Fixed some stability issues

New format definition commands in ASCII import

The following new commands are available:

• $CONT <0 or 1> - continuous quotations flag this affects$AUTOADD 1 mode - if this is set, newly added stocks are switched to continuous quotation mode (this means enabling candlestick charts for example)
• $MARKET <number> this affects$AUTOADD 1 mode - if this is specified, newly added stocks are assigned to market with given number.
• $GROUP <number> this affects$AUTOADD 1 mode - if this is specified, newly added stocks are assigned to group with given number
• $HYBRID <0 or 1> - combine data in hybrid mode switch when this flag is set, you can combine quotations from multiple files - for example one file can contain only open prices and volume and the other file can contain high/low/close data. Useful especially for Warsaw Stock Exchange for combining the data from fixing and later continuous quotations. Moreover followin new field definitions are accepted now by$FORMAT command:

• MARKET
specify a field that contains market ID (affects $AUTOADD mode only) • GROUP specify a field that contains group ID (affects$AUTOADD mode only)
• INFO
specify a field with additional information (WSE specific: nk, ns, rk, rs, ok, os, zd, bd )
• REDUCTION
specify a field with reduction rate in percents (WSE specific)

User-definable file types and formats

Now AmiBroker can use not only default.format definition file but also other user-specified files. File types, filters and format definition files are specified in import.types file (example is included in the update package). Now user can prepare/modify import.types file with the description of supported ASCII formats and filters to use. The format of import.types file is:

<Descriptive name>|<File filter>|<definition file name>

Note vertical line characters between these three fields. Example import.types file looks as follows:

Default ASCII (*.*)|*.*|default.format Yahoo's CSV (*.csv)|*.csv|yahoo.format Metastock ASCII (*.mst)|*.mst|metastock.format Omega SC ASCII (*.txt)|*.txt|omega.format S-Files (s*.*)|s*.*|sfile.format C-Files (c*.*)|c*.*|cfile.format Sharenet DAT (*.dat)|*.dat|dat.format

If such file exists you will see your types in the "Files of type" combo-box and when you select one - appropriate filter will be used and after selecting some files and clicking OK - importer will use specified ".format" file.

In that way you can define as many text-based data formats as you like and AmiBroker will be able to "understand" them all.

Ticker aliases

Now each ticker can have an alias assigned, so the AmiBroker's built-in importers can recognize that stock by both ticker and alias names. This is useful when you are using two data sources that are using slighty different stock naming convention or if you want to give the stocks more intuitive name while retaining the ability to use importers without problems.

VERSION 3.22 RELEASE NOTES

Version 3.22 (Mar 5th, 2000) includes following new features and fixes (compared to 3.21):

• ASCII import is fixed now. Moreover the ASCII importer offers now much more flexibility thru format definition files (see Data management chapter of AmiBroker User's Guide for details). Example *.format files are included in the AmiBroker main directory.
• AFL analysis tools have been moved to a new "Analysis" menu
• Tools menu has been redesigned. Now it is customizable, so user can assign his new command/tools to the menu. You can lanuch executables (*.exe), Scripts (*.js, *vbs), HTML web pages (*.html) and any other type of file thru this custom tools mechanism.
• Save workspace now saves only those stocks that have changed. Save Workspace As.. now works and saves all stocks to a new directory.
• Stock information window works better now

VERSION 3.21 RELEASE NOTES

Version 3.21 (Feb 16th, 2000) includes following fixes (compared to 3.20):

• manual quotation editor works fine now