amibroker

HomeKnowledge Base

Number of stopped-out trades as a custom metric

For the purpose of counting trades closed by particular stop we can refer to ExitReason property of the trade object in the custom backtester. The custom backtest formula presented below iterates through the list of closed trades, then counts the trades, which indicate exit reason = 2, that is stop-loss.

The following values are used for indication of the particular exit reason:

  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)
SetCustomBacktestProc"" );

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

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

    // initialize counter
    
stoplossCountLong stoplossCountShort 0;

    
// iterate through closed trades
    
for( trade bo.GetFirstTrade(); tradetrade bo.GetNextTrade() )
    {

      
// check for stop-loss exit reason
        
if( trade.ExitReason == )
        {
         
// increase long or short counter respectively
            
if( trade.IsLong() )
                
stoplossCountLong++;
            else
                
stoplossCountShort++;
        }
    }

   
// add the custom metric
    
bo.AddCustomMetric"Stoploss trades"stoplossCountLong stoplossCountShort,
                         
stoplossCountLongstoplossCountShort);

}

Buy CrossMACD(), Signal() );
Sell CrossSignal(), MACD() );
Short Sell;
Cover Buy;
ApplyStopstopTypeLossstopModePercent2)

How to hide unused categories

AmiBroker categories offer 256 Markets, 256 Groups, 256 industries grouped within 64 sectors, plus unlimited number of watchlist (and support for other categorization standards such as ICB and GICS).

By default all markets, groups, sectors and industries are displayed, even if no symbol is assigned to them (so they are “empty”).

Hide categories

To avoid showing all the categories in Symbols window tree, we can use one of Hide empty markets/groups/sectors/industries/watchlists options available in the menu in Symbols window:

Hide categories

Now the list of categories shows only those, which contain at least one symbol and empty ones are omitted. More information about categories in AmiBroker can be found in the following chapter of the User’s Guide: http://www.amibroker.com/guide/h_categories.html

How to fix Error 61 in printf/StrFormat calls

AmiBroker version 6.07 has introduced a strict check for correct string formatting in printf and StrFormat functions. These functions allow to specify the string followed by the list of arguments that will be inserted into the string in places, where %f, %g or %e specifiers are entered.

This works the following way:

StrFormat example

It is important for the list of subsequent arguments to match the number of % specifiers in the string. In cases, where there is no match – AmiBroker will display Error 61 message. Strict check is required because Microsoft C runtime crashes if wrong parameters are passed. Passing on earlier version was dangerous because it would lead to random crashes now and then depending on machine configuration.

There may be the following typical problems in the code:

Example 1. Four % specifiers, five value arguments

In this example formatting string contains four % specifiers so AmiBroker expects four arguments coming later, but five are given instead (too many).
// WRONG - too many value arguments
Title StrFormat"Open: %g, High: %g, Low: %g, Close: %g"OpenHighLowCloseVolume );

// CORRECT
Title StrFormat"Open: %g, High: %g, Low: %g, Close: %g"OpenHighLowClose )

Example 2. Five % specifiers, four value arguments

In this example formatting string contains five % specifiers so AmiBroker expects five arguments coming later, but four are given instead (too few).

// WRONG - %.0f specifier does not have a matching argument
Title StrFormat"Open: %g, High: %g, Low: %g, Close: %g, Volume: %.0f"OpenHighLowClose );

// CORRECT
Title StrFormat"Open: %g, High: %g, Low: %g, Close: %g, Volume: %.0f"OpenHighLowCloseVolume )

Example 3. Incorrectly coded percent (%) sign

In this example user wanted to print just % (percent sign), but used % (wrong) instead of %% (correct specifier of literal percent sign).

// WRONG - to show the % sign in the output we need to use %%
Title StrFormat"Close: %g (%.1f%)"CloseSelectedValueROCClose1) ) );

// CORRECT - you should use %% to print actual percent sign
Title StrFormat"Close: %g (%.1f%%)"CloseSelectedValueROCClose1) ) )

The example 3 requires special attention, as it is a common mistake. Due to the fact that % sign is a special character, we need to use %% in our string if we want to print % sign in the output string.

Adding custom grid levels to RSI indicator

Built-in RSI indicator offers the ability to display one of predefined grid levels to indicate oversold and overbought regions. This can be done in Axes&Grid tab of Parameters window available under right-mouse button.

Grid settings

If we require more flexibility, then as an alternative, we could modify the code and call PlotGrid function to display the custom grid lines. This allows to specify any level for the grids. A modified formula is presented below:

SetChartOptions0chartShowArrows);
periods Param"Periods"151200);
oversold Param"Oversold level"151100);
overbought Param"Overbought level"851100);

PlotRSIperiods), _DEFAULT_NAME(), ParamColor"Color"colorCycle ), ParamStyle("Style")  );
PlotGridoversold );
PlotGridoverbought )

Param window settings

Now, since the formula uses Param function as input, the custom grid levels can be defined and modified in Parameters tab.

Automatic support and resistance lines based on last HHV and LLV value

In this example we will present a method to plot automatic support and resistance lines based on recently hit highs/lows. In order to draw horizontal lines showing levels of recent HHV/LLV values and start drawing at the point of the chart, which defines given price level – we first need to identify the bar, where the line should start. This can be done with use of HHVBars / LLVBars functions.

These functions allow to find out the number of bars that have passed since our support or resistance level was established, so we could prevent from drawing the lines before these points.

This example shows how to draw support and resistance lines based on HHV/LLV levels:

// define reusable function
function SupResLevelsbarscolorUpColorDn )
{
   
bi BarIndex();
   
lvbi LastValuebi );

   
// return HHV value only for bars starting from the bar where HHV level was established
   
hv IIfbi >= lvbi LastValueHHVBarsHighbars ) ), LastValueHHVHighbars ) ), Null );

   
// the same approach for LLV
   
lv IIfbi >= lvbi LastValueLLVBarsLowbars ) ), LastValueLLVLowbars ) ), Null );

   
// plot levels
   
Plothv"hv"colorUpstyleDashed );
   
Plotlv"lv"ColorDnstyleDashed );
}

// price plot
PlotClose"Close"colorDefaultstyleBar );

// call function with various parameters
SupResLevels10colorGreencolorRed );
SupResLevels50colorGreencolorRed )

The chart below shows the output produced by the formula:

Automatic resistance/support levels

« Previous Page