Amibroker How To: Using graph styles, colors, titles and parameters in Indicators

 

Using graph styles, colors, titles and parameters in Indicators

AmiBroker provides customizable styles and colors of graphs in custom indicators. These features allow more flexibility in designing your indicators. This article will explain how to use styles and colors. It will also explain how to define chart title that appears at the top of the chart.

Plot() function

Plot is the function used to plot a chart. It takes 9 parameters, out of which first 3 are required.

Plot( arraynamecolorstyle = styleLine, minvalue = Null, maxvalue = Null, XShift = 0, ZOrder = 0, width = 1 )

  • array parameter represents data to be plotted,
  • name parameter defines the name of the graph (used in title string to show the values of the indicator),
  • color parameter defines the color of plot,
  • style defines "the look" of the chart (i.e. line/histogram/candlestick/bar, etc). Default style is line.
  • minvalue and maxvalue are rarely used paremeters that define hard-coded minimum and maximum values used when graph uses "independent" scaling, i.e. styleOwnScale is specified in style parameter. Usually you don't need to specify them at all.
  • XShift allows shifting chart past the last bar (for example displaced moving averages or projections into the future)
  • ZOrder - defines the Z-axis position of given plot. 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.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 this picture. 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)
  • width - (new in 5.60) defines pixel or percent width of given plot. The default is 1 pixel. 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.

An example, the following single function call plots a RSI indicator with red color line:

PlotRSI(14), "My RSI"colorRed );

As you can see we have provided only first three (required) parameters. First parameter is the array we need to plot. In our example it is RSI(14) indicator. Second parameter is just the name. It can be any name you want. It will be displayed in the title line along with indicator value as shown in the picture below:

Third parameter is the color. To specify plot color you can use one of the following pre-defined constants:

Color constants

Custom colors refer to color user-defined palette editable using Tools->Preferences->Colors, the numerical values that appear after = (equation) mark are for reference only and you don't need to use them. Use just the name such as colorDarkGreen.

colorCustom1 = 0
colorCustom2 = 1
colorCustom3 = 2
colorCustom4 = 3
colorCustom5 = 4
colorCustom6 = 5
colorCustom7 = 6
colorCustom8 = 7
colorCustom9 = 8
colorCustom10 = 9
colorCustom11 = 10
colorCustom12 = 11
colorCustom13 = 12
colorCustom14 = 13
colorCustom15 = 14
colorCustom16 = 15

colorBlack = 16
colorBrown = 17
colorDarkOliveGreen = 18
colorDarkGreen = 19
colorDarkTeal = 20
colorDarkBlue = 21
colorIndigo = 22
colorDarkGrey = 23

colorDarkRed = 24
colorOrange = 25
colorDarkYellow = 26
colorGreen = 27
colorTeal = 28
colorBlue = 29
colorBlueGrey = 30
colorGrey40 = 31

colorRed = 32
colorLightOrange = 33
colorLime = 34
colorSeaGreen = 35
colorAqua = 35
colorLightBlue = 37
colorViolet = 38
colorGrey50 = 39

colorPink = 40
colorGold = 41
colorYellow = 42
colorBrightGreen = 43
colorTurquoise = 44
colorSkyblue = 45
colorPlum = 46
colorLightGrey = 47

colorRose = 48
colorTan = 49
colorLightYellow = 50
colorPaleGreen = 51
colorPaleTurquoise = 52
colorPaleBlue = 53
colorLavender = 54
colorWhite = 55

You can also use new 24-bit (full color palette) functions ColorRGB and ColorHSB

You can easily plot multi colored charts using both Plot functions. All you need to do is to define array of color indexes.
In the following example MACD is plotted with green color when it is above zero and with red color when it is below zero.

dynamic_color = IIfMACD() > 0colorGreencolorRed );
PlotMACD(), "My MACD", dynamic_color  );

In addition to defining the color we can supply 4th parameter that defines style of plot. For example we can change previous MACD plot to thick histogram instead of line:

dynamic_color = IIfMACD() > 0colorGreencolorRed );
PlotMACD(), "My MACD", dynamic_color, styleHistogram | styleThick  );

As you can see, multiple styles can be combined together using | (binary-or) operator. (Note: the | character can be typed by pressing backslash key '\' while holding down SHIFT key). Resulting chart looks like this:

To plot candlestick chart we are using styleCandle constant, as in this example:

PlotClose"Price"colorBlackstyleCandle );

To plot traditional bars with color (green up bars and red down bars) we just specify color depending on relationship between open and close price and styleBar in style argument:

PlotClose"Price"IIfClose > OpencolorGreencolorRed ), styleBar | styleThick );

All available style constants are summarized in the table below.

Style constants

Style is defined as a combination (using either addition (+) or binary-or (|) operator) of one or more following flags ( you can use predefined style__ constants instead of numbers)

styleLine = 1 - normal (line) chart (default)
styleHistogram = 2 - histogram chart
styleThick =4 - fat (thick)
styleDots = 8 - include dots
styleNoLine = 16 - no line
styleDashed = 32 - dashed line style
styleCandle = 64 - candlestick chart
styleBar = 128 - traditional bar chart
styleNoDraw = 256 - no draw (perform axis scaling only)
styleStaircase = 512 - staircase (square) chart
styleSwingDots = 1024 - middle dots for staircase chart
styleNoRescale = 2048 - no rescale
styleNoLabel = 4096 - no value label
stylePointAndFigure = 8192 - point and figure
styleArea = 16384 - area chart (extra wide histogram)
styleOwnScale = 32768 - plot is using independent scaling
styleLeftAxisScale = 65536 - plot is using left axis scale (independent from right axis)
styleNoTitle = 131072 - do not include this plot value in title string
styleCloud = 262144 - paint a "cloud" (filled area) chart (see examples below)
styleClipMinMax = 524288 - clip area between Min and Max levels defined in Plot statement. (Note: this style is not compatible with most printers)
styleGradient - (new in 5.60) - gradient area chart. Upper gradient color is specified by color parameter in Plot() function, bottom gradient color is either background color or can be defined using SetGradientFill function. styleGradient can be combined with styleLine

Not all flag combinations make sense, for example (64+1) (candlestick + line) will result in candlestick chart (style=64)

Note on candlestick/bar charts: if these styles are applied to Plot() function then they use indirectly O, H, L arrays.
If you want to specify your own OHL values you need to use PlotOHLC() function.

New styleCloud and styleClipMinMax styles bring new interesting possibilities shown in the sample image below:

The formula for chart in the middle pane (rainbow 24-bit multiple moving averages) looks as follows:

side = 1;
increment = 
Param("Increment",21101 );
for( i = 10; i < 80; i = i + increment )
{
 up = 
MAC, i );
 down = 
MAC, i + increment );

 ifParamToggle("3D effect?""No|Yes"1 ) )
   side =  
IIf(up<=down AND Ref( up<=down, 1 ), 10.6 );

 PlotOHLC( up,up,down,down, "MA"+i, ColorHSB3*(i - 10),
           Param
("Saturation"1280255 ),
           
side * Param("Brightness"2550255 ) ), styleCloud | styleNoLabel );
}

The formula for the chart in the lower pane (slow stochastic %K with colored tops and bottoms) looks as follows. It uses styleClipMinMax to achieve clipping of the cloud region between min and max levels specified in the plot statement. Without this style area between min/max would be filled. Please note that due to Windows GDI limitation clipping region (styleClipMinMax) is supported only on raster (bitmap) devices so it is not compatible with printers or WMF (windows metafile) output.

SetChartOptions(0,0,ChartGrid30 | ChartGrid70 );
r = 
StochK(14);
Plot( r, "StochK"colorBlack );
PlotOHLC( r,r,50,r, ""IIf( r > 50colorRedcolorGreen ), styleCloud | styleClipMinMax, 3070 );

X-shift feature

The XShift parameter allows to displace (shift) the plot in horizontal direction by specified number of bars. This allows to plot displaced moving averages and projections into the future. See the following sample code of displaced moving average:

Periods = Param("Periods"302100 );
Displacement = 
Param("Displacement"15, -5050 );

PlotMAC, Periods ), _DEFAULT_NAME(), ColorCycle, styleLine00, Displacement );

PlotForeign() function

It is now easy to overlay price plots of multiple symbols using PlotForeign function:

PlotForeign( tickersymbolnamecolor/barcolorstyle = styleCandle | styleOwnScaleminvalue = {empty}, maxvalue = {empty}, xshift = 0)

Plots the foreign-symbol price chart (symbol is defined by tickersymbol parameter). Second argument name defines graph name used for displaying values in a title bar. Graph color could be static (if third argument is a number) or dynamic (when third argument is an array). Color indexes are related to the current palette (see Preferences/Color)
style defines chart plot style (see Plot() function for possible values)

PlotForeign( "^DJI", "Dow Jones", colorRed );
PlotForeign( "^NDX", "Nasdaq 100", colorBlue );
PlotForeign( "^IXIC", "Nasdaq Composite", colorGreen );

Multiple plots using different scaling

Two new styles can be used to plot multiple graphs using different Y-scale: styleOwnScale and styleLeftAxisScale.

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

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

New parameters make it also 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 );

Using custom defined parameters

AmiBroker allows to create user-defined parameters. Such parameters are then available via Parameters dialog for quick and fast adjustment of indicator.

Most often used parameter functions are (click on the links to get more detailed description):

  • Param( "name", default, min, max, steps, incr = 0 )
  • ParamStr( "name", "default" );
  • ParamColor( "name", defaultcolor );
  • ParamStyle(''name'', defaultval = styleLine, mask = maskDefault )

They make it possible to define your own parameters in your indicators. Once Param functions are included in the formula you can right click over chart pane and select "Parameters" or press Ctrl+R, and change them via Parameters dialog and get immediate response.

The simplest case looks like this:

period = Param("RSI period"122501 );
PlotRSI( period ), "RSI( " + period + ") "colorRed );

Right click over the chart and choose "Parameters" and move the slider and you will see RSI plotted with different periods immediatelly as you move the slider.

Sample code below shows how to use ParamStr to get the ticker symbol and ParamColor to get colors.

ticker = ParamStr"Ticker""MSFT" );
sp = 
Param"MA Period"122100 );
PlotForeign( ticker, "Chart of "+ticker,
             ParamColor
"Price Color"colorBlack ), styleCandle );
PlotMAForeign( ticker, "C" ), sp ), "MA"ParamColor"MA Color"colorRed ) );

The following sample formula (from AmiBroker mailing list) that allows to visually align price peak/troughs with sine curve on the chart:

Cycle = Param("Cycle Months", 121121 )*22;//264==12mth,22==1mth
xfactor = 
Param("Stretch",1,0.1,2,0.1);//1==1yr,2==2yr
xshift = 
Param("slide",0,-22,22,2)/3.1416^2;//slide curve 1==5days

x = 
2*3.1416/Cycle/xfactor;
y = 
sin(Cum(x)-xshift);

Plot(C,"Daily Chart"colorBlackstyleCandle | styleNoLabel);
Plot(y,
 "cycle =" WriteVal(Cycle*xfactor/22,1.0)+"months",
 colorBlue,styleLine|styleNoLabel|styleOwnScale);

Right click over the chart and choose "Parameters" and move the sliders and you will see chart immediatelly reflecting your changes.

For more information on user-definable parameters please check also Tutorial: Using drag-and-drop interface

Plotting texts at arbitrary positions on the chart

AmiBroker now allows annotation of the chart with text placed on any x, y position specified on the formula level using new PlotText function.

PlotText( "text", x, y, color, bkcolor = colorDefault )

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"colorBlackstyleLine );
Plot(MA(C,20),"MA20"colorRed );

Buy=CrossCMA(C,20 ) );
SellCrossMAC20 ), C );

dist = 
1.5*ATR(10);

for( i = 0; i < BarCount; i++ )
{
ifBuy[i] ) PlotText"Buy\n@" + C[ i ], i, L[ i ]-dist[i], colorGreen );
ifSell[i] ) PlotText"Sell\n@" + C[ i ], i, H[ i ]+dist[i], colorRedcolorYellow );
}

PlotShapesBuy * shapeUpArrow + Sell * shapeDownArrowIIfBuycolorGreencolorRed ) );

Gradient fill of the background

AmiBroker 4.90 allows to fill indicator background with gradually changing color. To achieve this you need to use new function SetChartBkGradientFill( topcolor, bottomcolor, titlebkcolor = default )

The function enables background gradient color fill in indicators.
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). Parameters are as follows:

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:

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

Gradient fill area charts

Version 5.60 brings native gradient area charts. To display a simple gradient chart it is enough to use styleGradient in the Plot() function call. By default upper gradient color is specified by color parameter in Plot() function, bottom gradient color is either background color. styleGradient can be combined with styleLine.

A simple gradient area chart can be displayed using:

PlotC"C"colorDefaultstyleGradient | styleLine );

For detailed control over gradient colors and baseline there is an extra function SetGradientFill( topcolor, bottomcolor, baseline, baselinecolor ) that should be called before Plot().

When you use SetGradientFill function, the upper gradient color is specified by topcolor argument, bottom gradient color is specified by botttomcolor. Optional parameters (baseline/baselinecolor) allow reverse gradient chart (such as underwater equity) and 3 color gradients top->baseline->bottom. See code for Underwater Equity for example usage of reverse gradient chart (with baseline at the top). Baseline parameter specifies the Y-axis position of chart baseline. The baselinecolor parameter specifies the color of gradient that is to be used at that level. If baselinecolor is not specified, then only 2-color gradient is plotted (topcolor->bottomcolor).

For example to display three-color gradient Rate Of Change that will use green as "top" color for positive values, background color as "baseline" color and red as "bottom" color for negative values it is enough to write:

SetGradientFillcolorGreen /*top*/colorRed /*bottom*/0 /*baseline level*/GetChartBkColor() /*baseline color */);
PlotROCC14), "ROC"colorLightOrangestyleLine | styleGradientNullNull0, -1  );

The resulting chart will look as follows (using Basic chart theme):

 

.. or this way (using Black chart theme):


 

Super thick charts

Version 5.60 allows to define the line width beyond styleThick that was the only option before.

Now 9th parameter of Plot() defines pixel or percent width of given plot. The default is 1 pixel. 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:

PlotC"Close"colorDefaultstyleBarNullNull01, -20 /* line width as percent of bar */ );

As you zoom-in the bars will become thicker and thicker.

Now you can get super thick lines as shown in the example below (10-pixel thick line chart):

PlotC"Close"colorRedstyleLineNullNull0110 /* 10 pixel wide */ );

Miscellaneous

As you already know each plot has its own name that is used to create a title string which displays names and values of indicators. AmiBroker however allows you to override this automatic mechanism and define your own title string from the scratch. The Title reserved variable is used for that. You just assign a string to it and it will be displayed in the chart instead of automatically generated one.

Also there two more reserved variables (GraphXSpace and GraphZOrder) that allow to fine-tune indicator look.

They are all described in the table below.

VariableUsageApplies to
Title

Defines title text

If you use Title variable you can specify colors in the string.

It is advised to use AFL EncodeColor function that makes it easier than coding escape sequences.

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

For sake of completeness: colors can also be specified using espace sequences but it is NOT recommended because is hard to write and hard to read. \\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";

Indicators
Tooltip

Obsolete in 5.40. Use Data window instead or use Plot() with styleHidden if you want to add your custom values to data tooltip.

For example:
Plot( my_value, "MyValueForTooltip", colorBlack, styleHidden );

Indicators
GraphXSpace

defines how much extra space should be added above and below graph line (in percent).
For example:

GraphXSpace = 5;

adds 5% extra space above and below the graph line. When GraphXSpace is not defined in the formula then default 2% is used.

Indicators
GraphLabelDecimals(new in 5.90) controls number of decimals in chart value labes (example, adding GraphLabelDecimals = 2; to the formula would give you value lables with 2 decimal places)
Indicators
GraphZOrderGraphZOrder 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.Indicators

Obsolete graph variables

This table shows obsolete reserved variables. They are still functional for backward-compatibility but new code should use Plot() functions only. What's more, when using new Plot() functions you should NOT use obsolete variables below.

VariableUsageApplies to
maxgraphspecifies maximum number of graphs to be drawn in custom indicator window (default=3)Indicators
graphNdefines the formula for the graph number N (where N is a number 0,1,2,..., maxgraph-1)Indicators

graphNopen,
graphNhigh,
graphNlow,

define additional O, H, L price arrays for candlestick and traditional bar chartsIndicators
graphNcolor

defines the color index of Nth graph line. Color indexes are related to the current palette - see Preferences/Color.

 

Indicators
graphNbarcolordefines the array that holds palette indexes for each bar drawnIndicators
graphNstyle

defines the style of Nth graph. Style is defined as a combination (sum) of one or more following flags ( you can use predefined style__ constants instead of numbers)

Indicators

 


EmoticonEmoticon