amibroker

HomeKnowledge Base

Why can’t I change the symbol? (Symbol lock)

If you can not change the active symbol for the chart, chances are that you have accidentally clicked “Symbol Lock” icon (a small padlock) located near the scroll bar.

Symbol Lock

When it is activated (yellow) then AmiBroker will prevent any symbol changes for active chart window. To toggle lock simply press the padlock icon.

How to identify signal that triggered entry/exit if multiple signals are used

When designing a trading system we often need to quickly identify which of the rules used in the code triggered the particular Buy or Sell signal. Here are some techniques that may be useful in such identification.

For the purpose of this demonstration let us use a sample formula, where the Buy signal may be triggered by one of three independent rules:

Buy1 CrossMACD(), Signal() );
Buy2 CrossCloseMA(Close50) );
Buy3 CrossRSI(), 30 );
//
Buy buy1 OR Buy2 OR Buy3

To determine which of those three rules generates the entry signal, we can either visualize signals in the chart or use Exploration feature of the Analysis window.

In case a custom chart is used, we can do the following:

  1. display the signal in custom chart title
  2. use PlotShapes function to indicate certain buy rule
  3. use PlotText to add pre-defined text labels.

The formula below shows sample implementations of these three techniques. This is actually one of many ways that can be used for coding such custom output:

Buy1 CrossMACD(), Signal() );
Buy2 CrossCloseMA(Close,50) );
Buy3 CrossRSI(), 30 );
//
Buy buy1 OR Buy2 OR Buy3;
//
// Standard price plot
PlotClose"Close"colorBlackstyleCandle);
//
// Custom title definition
BuyReason EncodeColor(colorGreen ) + WriteIf(Buy,"Buy signals: ","")
           + 
WriteIf(buy1"Buy1 """) +WriteIf(buy2"Buy2""")
           + 
WriteIf(buy3"Buy3""");
Title StrFormat"{{NAME}} - {{INTERVAL}} {{DATE}} Close %g ",Close ) +BuyReason;
//
// Plotshapes function calls
PlotShapes(Buy*shapeUpArrowcolorGreen0Low);
PlotShapes(Buy1*shapedigit1colorGreen0Low,-30);
PlotShapes(Buy2*shapedigit2colorGreen0Low,-45);
PlotShapes(Buy3*shapedigit3colorGreen0Low,-60);
//
//
// Custom text labels displayed with PlotText
if( SelectedValue(Buy) )
{
   
SelectedValueBarIndex() );
   
maxy Status("axismaxy");
   
miny Status("axisminy");
   
0.15 * (maxy miny) + miny;
   
text WriteIf(buy1], "\nBuy1 """)
          +  
WriteIf(buy2], "\nBuy2 """)
          +  
WriteIf(buy3], "\nBuy3 """);
   
PlotTexttexti,  ycolorWhitecolorGreen );

The chart below shows how to use signal visualization technique implemented in the formula.

Chart Example 1

The other method is to use the Exploration feature of Analysis window that allows to generate tabular output, where we can display the values of selected variables. The detailed tutorial explaining this feature is available at:
http://www.amibroker.com/guide/h_exploration.html

For the discussed purpose of tracking the signals that triggered entry or exit, we can add the following code to our trading system to show the values of each Buy1, Buy2, Buy3 variables:

Filter Buy;
AddColumnBuy1"Buy1"1colorDefaultIIfBuy1colorGreencolorDefault ) );
AddColumnBuy2"Buy2"1colorDefaultIIfBuy2colorGreencolorDefault ) );
AddColumnBuy3"Buy3"1colorDefaultIIfBuy3colorGreencolorDefault ) )

Exploration Signal tracking

With regard to exit signals they can be visualized in a similar way as shown above, but there is also an additional functionality in the backtester, which allows to indicate the exit condition directly in the trade list. This can be done by assigning values higher than 1 (but not more than 127) to Sell variable.

Sell1 CrossSignal(), MACD() );
sell2 CrossMA(Close50), Close );
Sell Sell1 10 Sell2 20

The above expression will result in assigning value of 10 to Sell variable for the bars where Sell1 is true, 20 for the bars where Sell2 is true and 30 for the bars where both conditions are true.

These values will be indicated in the trade list:

Backtest exit signal tracking

It is worth to mention that values 1 to 9 are reserved for built-in stops and used internally by the backtester, and have special meaning:

  1. normal exit
  2. maximum loss stop
  3. profit target stop
  4. trailing stop
  5. n-bar stop
  6. ruin stop (losing 99.96% of entry value)
  7. reserved
  8. reserved
  9. reserved

Note also that you must not assign value greater than 127 to Sell or Cover variable. If you assign bigger value it will be truncated.

This is further discussed here: http://www.amibroker.com/guide/afl/equity.html

Make icons larger on high DPI displays

When running AmiBroker on high-DPI displays like Retina screens, 4K screens or small tablets with hi-res displays the toolbar icons may become so small that they are difficult to use.

To solve the problem you need to choose Tools->Customize menu to display Customize dialog, go to Options tab and
select Large Icons check box as shown in the picture below.

Options page, Large Icons

Do NOT use “registry cleaners” to avoid problems

Every now and then a user contacts support saying that some functionality (like OLE interface) stopped working and after some e-mail exchange it turns out that the culprit was a “Registry Cleaner” program that was run and deleted some vital registry entries.

I already warned users NOT to use “registry cleaners” or “memory turbo” here:
http://www.amibroker.com/guide/x_performance.html

These programs are written pretty much often by amateurs and they often blindly delete registry entries that they assume are “no longer used”. First off, there is no freaking way a 3rd party program can ever determine when a registry key is “unused”. It was evidently put there for a reason and could have been accessed hundreds or thousands of times. “Registry cleaners” usually make assumptions that are simply not valid. For example, they may check for the presence of file referenced by the registry key, but they silently ignore the fact that the file may be on removable media (such as USB disk) and that Windows may change drive letters when new drive is inserted. In such cases “registry cleaner” would delete perfectly valid registry key causing problems with the software that was using this key.

AmiBroker can live with most of its registry entries deleted (you would lose all your UI customizations though) with one exception: OLE. AmiBroker exposes OLE automation server (Broker.Application) and if 3rd party “registry cleaner” wipes its registry keys, the OLE would stop working. This affects also auto-import feature in AmiQuote as it relies on AmiBroker’s OLE automation server.

So bottom line is: To avoid problems DO NOT USE “registry cleaners”.

More evidence of problems caused by “registry cleaners” can be found here:

  1. Why I don’t use registry cleaners

  2. Are registry cleaners safe to use?
  3. Registry cleaner won’t speed up your PC

Now, what to do if you already run registry cleaner and have problems?
The solution is to use full setup again. You do NOT need to uninstall anything, you don’t need to delete anything. Just run the setup again over existing installation, with “Full Installation” option selected as shown in the picture below:

Full setup

That should cure the problem with OLE within seconds. Good luck!

How to backfill all symbols in RT database

Various data sources have different backfill capabilities, therefore the procedure to backfill all symbols varies. There are three categories of data sources, those that offer:

  1. unlimited backfills (eSignal, IQFeed),
  2. limited, 1-symbol at a time backfill (Interactive Brokers),
  3. no backfill at all (for example DDE)

As a general rule, all real-time data sources provide backfills on-demand, which means that backfill for each symbol has to be requested separately. If data source provides backfill and there are missing quotes in the database, AmiBroker will automatically request backfill on first access to given symbol. So, as soon as you display its chart fresh data will be requested and backfilled. Backfill is not immediate, because it is Internet-based process that involves request-response procedure, so data are requested from external server and arrive in a few seconds or so.
The same procedure is performed when doing any access including running Analysis, so backfill is requested as soon as given symbol is accessed, but by default Analysis window will not wait until backfill data arrive unless you turn on the Wait for backfill option (provided that data source supports it).

Wait for backfill option

It is worth to note that not all data sources support this feature. It needs to be handled by the data plugin, and many 3rd party plugins do not offer this.

If you are using eSignal or IQFeed or other data source with automatic, unlimited backfill you can use procedure described in How to use Real-Time data sources tutorial.

If you are using Interactive Brokers then the procedure is differnet since Interactive Brokers puts lots of limitations on backfills. To learn how to backfill all symbols using Interactive Brokers please read this dedicated tutorial on IB.

If you are using data source that does not offer any backfill, the only option is to use ASCII import to import the historical data from text files.

Do NOT make assumptions on number of bars

From time to time some users face “Error 10. Subscript out of range” in their formulas. The error itself is described in the manual, but still a few words of explanation why it happens may be useful.

The error usually occurs when formula uses hard-coded number of bars in the loop statements like this:

for( 0300i++ ) // MISTAKE: FIXED number of bars
{
  
Close]; // ERROR 10. because 'i' becomes greater than BarCount

or like this:

for( BarCount 1BarCount 300i-- ) // MISTAKE: FIXED number of bars
{
  
Close]; // ERROR 10. because 'i' becomes LESS than zero

In both cases the code will FAIL if it is run on symbol that has LESS than 300 bars (BarCount < 300). In fact it will even fail on symbol that has more than 300 bars because of two facts:

  1. during AFL Editor’s Verify Syntax not more than 200 most recent bars are used
  2. a chart may be zoomed in so number of visible bars may be much lower and QuickAFL kicks in (so your AFL is executed with visible bars only).

This all means that one should never make any assumptions on number of bars your formula would get, because if you do, the formula will fail.

The formula should be written so it is able to execute without errors with BarCount as small as 1 (ONE).

This is normally done by writing a ‘for’ loop in a way recommended in the manual:

for( 0BarCounti++ )
{
   
Close]; // this will never produce Error 10 because i is in the range 0..BarCount-1

If your formula references past data, say 10-bars earlier, you should start your loop with index 10, as below:

for( 10BarCounti++ )
{
  
x] = Close] - Close10 ]; // both subscripts will be OK

What to do if your formula, for some reason, really requires fixed number of bars? Well, the answer is that you should check if you really get as many bars as you think:

if( BarCount 300 // check first if you have enough bars
{
   
// here we know that we have more than 300 bars
   
for( 0300i++ )
   {
      
Close]; 
   }

A function with multiple return values

A typical AFL function returns one value. For example sin( x ) returns sine value of argument x. Sometimes however it is useful and/or required to return more than one value from the function.

Returning multiple values is possible only via arguments passed by reference, but trouble is that in AFL all arguments are passed by value (as in C language). Passing by value means that only value of variable is passed, not the variable itself, so original variable is not modified as shown in the example below:

function Dummy)
{
    
7// x is treated as function-local
}
//
val 10;
Dummyval );
printf"%g\\n"val ); // will print 10 because 'val' is unaffected by function cal

The behaviour shown above is desirable because we usually want the function to be opaque and do not interfere with what is defined outside of the function except for returning the result of the function.

But what if we actually wanted to write to variables passed as arguments? Well that is possible if we pass the names of the variables as arguments.

// This example shows how to return multiple values
// the idea is to pass the name of the variable instead of
// value
//
function fun_multiple_resultsresult1nameresult2name )
{
  
VarSetresult1name); // setting variable using passed name
  
VarSetresult2name);
  return;
}
//
// to get multiple values from a function
// we call the function passing NAMES of variables
//
10;
20;
printf("a = %g\\n");
printf("b = %g\\n");
//
fun_multiple_results"a""b" ); // pass the names of variables
//
printf("a = %g\\n"); // see new values assigned to variables
printf("b = %g\\n")

Of course we can use arguments passed by name for two-way communication – we can use them as both inputs and outputs as shown in the following example that swaps the values of arguments

function Swapvar1namevar2name )
{
    
temp1 VarGetvar1name ); // read the value from variable
    
temp2 VarGetvar2name );
    
VarSetvar1nametemp2 ); // write the value to variable
    
VarSetvar2nametemp1 );
}
// Initial values
5;
37;
//
printf("Before swap x = %g, y = %g\\n"x);
//
Swap"x""y" ); // pass names of variables
//
printf("After swap x = %g, y = %g\\n"x)

The code above will produce output like this:

Before swap x = 5, y = 37
After swap x = 37, y = 5

So it is clear that variables were passed to the function, swapped and returned successfully.

Broad market timing in system formulas

Some trading systems may benefit from attempt to time the broad market. A market-wide valuation, such as moving average, sentiment or some other mechanism may be used to tell if we should be in the market or not.

Flexibility of AFL language allows to create rules or indicators, which are based on more than just one symbol. This enables us to introduce additional filters based on wide-market index performance.

For the purpose of reading quotes of another symbol one can use Foreign or SetForeign functions.

The following formula shows how to generate entry signals in individual stocks when S&P500 index is above its 200-period moving average and exit signals when S&P500 is equal or below 200-period average (^GSPC is a ticker for Yahoo Finance data for S&P500)

//
// read S&P 500 values from ^GSPC ticker
//
sp500 Foreign"^GSPC""C" );
//
// market-wide filter should be in "state" form
// (so it is True all the time when market is up)
//
marketup sp500 MAsp500200 );
marketdown NOT marketup;
//
// sample trading rules (MACD crossovers)
//
BuySignal CrossMACD(), Signal() );
SellSignal CrossSignal(), MACD() );
//
// combine per-symbo signals with broad-market timing
//
Buy BuySignal AND marketup// enter trade only when buy signal AND market is in up trend
Sell SellSignal OR marketdown// exit position if sell signal OR market turns dow

A more complex broad-market timing that requires not only closing price of market index can be implemented using SetForeign function. SetForeign replaces all OHLCV data series with that of the “other” security and allows to calculate all kind of indicators that would normally use current security. Broad market timing does not need to be just “all-in” or “all-out” switch. For example one can switch the trading method depending on whenever broad market is trending or sideways.

//
// Switch to S&P symbol to calculate broad-market timing
//
SetForeign"^GSPC" );
//
// now we can calculate any indicator based on SP500
//
MarketIsTrending ADX40 ) > 20// ADX (40 days) from SP500
//
// now go back to original data (current symbol)
//
RestorePriceArrays();
//
// you can have different rules that are switched
// depending on what broad market is doing
//
TrendingBuy CrossCMAC30 ) );
TrendingSell CrossMAC30 ), );
//
SidewaysBuy CrossMACD(), Signal() );
SidewaysSell CrossSignal(), MACD() );
//
// switch methods using broad-market timing
//
Buy IIfMarketIsTrendingTrendingBuySidewaysBuy );
Sell IIfMarketIsTrendingTrendingSellSidewaysSell )

In this simple example we assume that market timing signals change very infrequently so they change much less often than Trending/Sideways Buy/Sell signals are generated. If that is not the case the switching logic would need to be more complex to decide what to do when we are in the “trending” trade and market switches to sideways mode. In such situation, the code above uses SidewaysSell signal to sell the position, which may or may not be what you are after.

Another example is changing position sizing depending on broad market conditions. We can choose to be fully invested when broead market is up and only 30% invested in down market.

//
// Switch to S&P symbol to calculate broad-market timing
//
SetForeign"^GSPC" );
//
// now we can calculate any indicator based on
// SP500
//
MarketIsUp MAC200 ); // here C represents closing price of SP500
//
// now go back to origiginal data (current symbol)
//
RestorePriceArrays();
//
// normal rules (in this example they do not chang)
//
Buy CrossMACD(), Signal() );
Sell CrossSignal(), MACD() );
//
// no more than 10 positions open at a time
//
SetOption("MaxOpenPositions"10 );
//
// change position sizing depending on broad market conditions
// in this example we will allocate:
// 10% per position
// if broad market is up (so we can be allocated upto 100% of funds)
// 3% per position
// if broad market is down (so we can be allocated upto 30% of funds)
//
SetPositionSizeIIfMarketIsUp10), spsPercentOfEquity )

How to display Range Bars

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

AmiBroker fully supports range-bar type of charting and the bar size is based on the TickSize of given symbol. This allows to define symbol-specific tick sizes individually, them display a chart which for example shows 10R bars (meaning bars using a range of 10-ticks for each symbol respectively).

To display range charts, first you need to specify the TickSize in the Symbol–>Information window.

Information window

This can be done manually as shown above, however in case of larger group of symbols it is also possible to use ASCII Importer for this purpose (more details about ASCII imports can be found here: http://www.amibroker.com/guide/d_ascii.html).

Once TickSize has been defined, then in order to display chosen range chart, the easiest way is to use Interval box in the toolbar and just type-in the desired bar size. For example, to select the range bar of 10-ticks, one can type-in 10R in the toolbar:

Range bar selection

Custom range intervals can also be defined in Tools–>Preferences, Intraday tab:

Preferences window

Then the pre-defined interval can be selected from View->Intraday menu.

It is worth noting that for best results, your database should use Tick as Base Time Interval, as then each trade is represented by an individual record in the database and can be consistently compressed to range bars. Using higher-interval data (such as 1-minute) may produce bars that are not perfect, especially if 1-minute bar high-low difference is comparable with selected range.

How to print result list from Analysis window

As far as backtest results are considered, they can be printed directly from Report Viewer.

Report printing

But sometimes we may want to print just the result list of scan, exploration or optimization. In order to print out the results list from Analysis window it is necessary to store the results list into a file first. This can be achieved by using File->Export HTML/CSV option from the main menu of the program (Export option is available when Analysis window is open):

Export

I recommend saving in HTML format as only then color output will be preserved.

Export as HTML

Once the result list is saved to a HTML file, you can double click on the file to open it with your default web browser. From web browser you can choose Print option.

If you prefer to modify the file prior to printing you can also save the result list in CSV format that can be open with Excel or any other application of your choice.

An alternative solution is to use system clipboard and to copy the results (using Ctrl+C keyboard shortcut or Copy option from the context menu available under right-mouse button), paste to the application like MS Excel for example and printing the results there.

« Previous PageNext Page »