Framework Reference
WEALTHLAB FRAMEWORK / CLASS REFERENCE

UserStrategyBase

API documentation, members, signatures, and C# examples.

Search the framework

Find classes, members, and documentation.

NamespaceWealthLab.Backtest
Parent
StrategyBase

UserStrategyBase represents a trading Strategy in WealthLab 9. When you work with C# Code-Based Strategies, you are actually coding a custom class that is derived from UserStrategyBase. The class provides properties and methods that let you control the logic of the trading system, including placing orders and examining the current state of the system. You hook into the trading system logic by overriding several virtual methods in UserStrategyBase. These methods pass as a parameter the instance of the BarHistory object that contains the historical data to backtest. The following are the most important methods:

  • Initialize - the backtester calls this once at the start of processing
  • Execute - the backtester calls this once for each data point in the BarHistory being backtested, and you are supplied the index that is should be processed in each iteration

Chart Rendering

46

DrawBarAnnotation

public void DrawBarAnnotation(string text, int bar, bool aboveBar, WLColor color, int fontSize, bool center = false, WLFont font = null, bool behindBars = false)
public void DrawBarAnnotation(TextShape ts, int bar, bool aboveBar, WLColor color, int fontSize, bool centerText = true, WLFont font = null, bool behindBars = false)

Draws the specified text or TextShape above or below the specified bar on the chart, using the specified color and fontSize. The text is centered, unless you pass false to the optional center parameter. The final optional font parameter allows you to specify a different WealthLab.Core.Font to use. The behindBars parameter controls whether the drawing is made behind the rendered chart bars, or above them. Remarks

  • See TextShape in the Enums class reference.
  • Examples: TextShape.CircleCrosshair, TextShape.SquareHollow, TextShape.ArrowUp

DrawBorderText

public void DrawBorderText(string txt, bool top, double offsetXPercent, double offsetY, WLColor color, int fontSize, string paneTag = "Price", bool centerText = false, WLFont font = null, bool behindBars = false)

Draws the specified text at the top or bottom of the pane and at a specified offsetXPercent from the left edge of the chart, where 0 is the left edge and 100 is the right edge. To draw along the top edge, pass true for the top parameter. Positive values for offsetY move text a number of pixels toward the middle of the chart. The color parameter determines the text's color, and the fontSize parameter determines its size. A size of 12 is standard for chart text rendering. The behindBars parameter controls whether the drawing is made behind the rendered chart bars, or above them. DrawBorderText has several optional parameters that let you further customize the text:

  • paneTag - lets you control which pane the text is rendered to. Possible values are "Price", "Volume", or an indicator pane tag such as "RSI" or "CMO".
  • centerText - *true specifies that the text should be centered at the location identified by offsetXPercent. If false (the default value) it renders with the left edge beginning at that point.
  • font - specifies the Font to use to render the text, as an instance of the WealthLab.Core.Font class.

DrawBottomText

public void DrawBottomText(string txt, int bar, double horizontalOffset, WLColor color, int fontSize, string paneTag = "Price", WLFont font = null, bool behindBars = false)

Draws the specified text rotated -90 degrees at the bottom of the pane and at a specified bar number. Use it to identify dates or events on a specific bar without cluttering the area around prices. Positive values for horizontalOffset move the text the same number of pixels to the right. By default, the bottom of the text will be to the left of the specified bar. To center the text on the bar, pass half the font size for horizontalOffset. The color parameter determines the text's color, and the fontSize parameter determines its size. A size of 12 is standard for chart text rendering. The behindBars parameter controls whether the drawing is made behind the rendered chart bars, or above them. DrawBottomText has several optional parameters that let you further customize the text:

  • paneTag - lets you control which pane the text is rendered to. Possible values are "Price", "Volume", or an indicator pane tag such as "RSI" or "CMO".
  • font - specifies the Font to use to render the text, as an instance of the WealthLab.Core.Font class.

DrawDot

public void DrawDot(int bar, double value, WLColor color, int radius, string paneTag = "Price", bool behindBars = false)

Draw a dot on that chart at the specified bar number and price value. The color parameter determines the color of the dot, and the radius parameter determines its size. The behindBars parameter controls whether the drawing is made behind the rendered chart bars, or above them. Remarks

  • See PlotStopsAndLimits to automatically draw dots at stop and limit prices on bars where the Transactions (orders) are active.

DrawEllipse

public void DrawEllipse(int startBar, double startValue, int endBar, double endValue, WLColor color, int lineWidth = 1, LineStyle lineStyle = LineStyle.Solid, string paneTag = "Price", bool behindBars = false)

Draws an ellipse on the chart using the specified parameters, color, line width, and style. The behindBars parameter controls whether the drawing is made behind the rendered chart bars, or above them.

DrawHeaderText

public void DrawHeaderText(string text, WLColor color, int fontSize, string paneTag = "Price")
public void DrawHeaderText(string txt, string paneTag = "Price", bool behindBars = false)

Draws the specified text on the chart, under the upper left hand corner box that displays the symbol and price values. The first overload allows you to control the color and fontSize of the text. Both overloads have a final, optional, parameter paneTag that defaults to "Price". Specify a different paneTag to draw the text in a different pane. The behindBars parameter controls whether the drawing is made behind the rendered chart bars, or above them.

DrawHint

public void DrawHint(string hintText, string bodyText, int idx, bool aboveBar, WLColor hintTextColor = null, WLColor hintBkgColor = null, WLColor bodyTextColor = null)

Draws the text specified in hintText either above or below (aboveBar parameter) the bar of the chart specified in the idx parameter. When the user hovers the mouse over the hint text, a popup box appears on the chart containing the text from the bodyText parameter. The final three optional parameters allow you to control the color of the hint text, hint text background, and text, respectively.

DrawHorzLine

public void DrawHorzLine(double value, WLColor color, int lineWidth = 1, LineStyle lineStyle = LineStyle.Solid, string paneTag = "Price", bool behindBars = false)

Draws a horizontal line on the chart at the specified value, using the specified color, line width, and style. The behindBars parameter controls whether the drawing is made behind the rendered chart bars, or above them.

DrawImage

public void DrawImage(Image img, int idx, double value, string paneTag = "Price", bool behindBars = false)

Draws the specified Image on the chart, at the specified location. The behindBars parameter controls whether the drawing is made behind the rendered chart bars, or above them. Remarks

  • To run the example, modify the Bitmap.FromFile() statement to point to an image file on your computer.

DrawImageAt

public void DrawImageAt(Image img, double x, double y, string paneTag = "Price", bool behindBars = false)

Draws the specified Image on the chart, at the specified location. The behindBars parameter controls whether the drawing is made behind the rendered chart bars, or above them. Remarks

  • x and y are pixels, where [0, 0] is the top left of the pane.
  • To locate the bottom of the image at the bottom of the pane, pass Double.MaxValue for the y parameter.

DrawLine

public void DrawLine(int startBar, double startValue, int endBar, double endValue, WLColor color, int lineWidth = 1, LineStyle lineStyle = LineStyle.Solid, string paneTag = "Price", bool extendLeft = false, bool extendRight = false, bool behindBars = false)

Draws a line on the chart using the specified parameters, line width, color, and style. The behindBars parameter controls whether the drawing is made behind the rendered chart bars, or above them.

DrawPolygon

public void DrawPolygon(List<IChartPoint> pts, WLColor color, int lineWidth = 1, LineStyle lineStyle = LineStyle.Solid, string paneTag = "Price", bool behindBars = false)

Draws a polygon based on the list of points in the pts parameter, using the specific color, line width, and style. The ChartPoint class represents a point on the chart. It contains 2 properties; an int Index and a double Value. The behindBars parameter controls whether the drawing is made behind the rendered chart bars, or above them.

DrawRectangle

public void DrawRectangle(int startBar, double startValue, int endBar, double endValue, WLColor color, int lineWidth = 1, LineStyle lineStyle = LineStyle.Solid, string paneTag = "Price", bool behindBars = false)

Draws a rectangle on the chart using the specified parameters, color, line width, and style. The behindBars parameter controls whether the drawing is made behind the rendered chart bars, or above them.

DrawText

public void DrawText(string txt, int idx, double value, WLColor color, int fontSize, string paneTag = "Price", bool centerText = false, WLFont font = null, bool behindBars = false)

Draws the specified text on the chart, at the location specified by the idx (x-axis) and value (y-axis) parameters. The idx parameter corresponds to an index in the BarHistory being charted. The value parameter corresponds to a numeric value along the y-axis. The color parameter determines the text's color, and the fontSize parameter determines its size. A size of 12 is standard for chart text rendering. The behindBars parameter controls whether the drawing is made behind the rendered chart bars, or above them. DrawText has several optional parameters that let you further customize the text:

  • paneTag - lets you control which pane the text is rendered to. Possible values are "Price", "Volume", or an indicator pane tag such as "RSI" or "CMO".
  • centerText - if true, specified that the text should be centered along the idx parameter. If false (the default value) it renders with the left edge beginning at that point.
  • font - specifies the Font to use to render the text, as an instance of the WealthLab.Core.Font class.

DrawTextVAlign

public void DrawTextVAlign(string txt, int idx, double value, VerticalAlignment valign, WLColor color, int fontSize, double marginVert = 0.0, double marginHorz = 0.0, string paneTag = "Price", bool centerText = false, WLFont font = null, bool behindBars = false)

You can use DrawTextVAlign to vertically align the text to a pane's y-value. Accordingly, the alignment is controlled by the valign VerticalAlignment enum parameter: Top, Bottom, or Center Like DrawText, DrawTextVAlign draws the specified text in a pane at the location specified by the idx (x-axis) and value (y-axis) parameters. The idx parameter corresponds to an index in the BarHistory being charted. The value parameter corresponds to a numeric value along the y-axis. The color parameter determines the text's color, and the fontSize parameter determines its size. A size of 12 is standard for chart text rendering. The behindBars parameter controls whether the drawing is made behind the rendered chart bars, or above them. The optional parameters that let you further customize the text:

  • marginVert - the vertical margin property lets you add an offset in pixels to create "margin" from the plot value.
  • marginHorz - since all text may not align perfectly when drawn centered, the horizontal margin property lets you add or subtract an offset in pixels.
  • paneTag - lets you control which pane the text is rendered to. Possible values are "Price", "Volume", or an indicator pane tag such as "RSI" or "CMO".
  • centerText - if true, specified that the text should be centered along the idx parameter. If false (the default value) it renders with the left edge beginning at that point.
  • font - specifies the Font to use to render the text, as an instance of the WealthLab.Core.Font class.

ExtendLine

public double ExtendLine(double x1, double y1, double x2, double y2, double x, bool isLog = false)

Does not actually plot, but rather calculates the extension of a line specified by two points (x1,x2 and y1,y2), and returns the value of y extended to the point along the line where the x parameter occurs. Pass true for isLog for a straight line on a semi-log chart.

FillEllipse

public void FillEllipse(int startBar, double startValue, int endBar, double endValue, WLColor color, string paneTag = "Price", bool behindBars = false)

Fills an ellipse on the chart using the specified parameters, color, and style. The behindBars parameter controls whether the drawing is made behind the rendered chart bars, or above them.

FillPolygon

public void FillPolygon(List<IChartPoint> pts, WLColor color, string paneTag = "Price", bool behindBars = false)

Fills a polygon based on the list of points in the pts parameter, using the specific color. The ChartPoint class represents a point on the chart. It contains 2 properties; an int Index and a double Value. The behindBars parameter controls whether the drawing is made behind the rendered chart bars, or above them.

FillRectangle

public void FillRectangle(int startBar, double startValue, int endBar, double endValue, WLColor color, string paneTag = "Price", bool behindBars = false)

Fills a rectangle on the chart using the specified parameters, color, and style. The behindBars parameter controls whether the drawing is made behind the rendered chart bars, or above them.

GetChartImage

public object GetChartImage(int width = 1024, int height = 768)

Returns a System.Drawing.Bitmap instance of the visual depiction of the chart, including any plotted indicators and other cosmetic drawings. You can specify the size of the Bitmap using the width and height parameters. Chart properties such as Bar Width, Show Volume Pane, Show Event icons, etc. come from your settings in Preferences (F12) > Chart.

PlotBarHistory

public void PlotBarHistory(BarHistory bh, string paneTag, WLColor color = default(WLColor), bool fitInAxis = false)

Plots a BarHistory instance on the chart. BarHistory instances are typically obtained as a result of the GetHistory method. Provide the BarHistory to be plotted in the bh parameter. The paneTag parameter should specify what pane to plot the data. You can specify Price for the price pane, Volume for the volume pane, or some other unique string for a custom pane. The color parameter is optional. If not specified, WealthLab will plot the data in black. The fitInAxis parameter is also optional, with a default of false. If set to true, it will cause the BarHistory data to fit within the existing scale of the pane, so as not to distort it. If false, the pane's scale will adjust to accommodate the BarHistory data.

PlotBarHistoryStyle

public void PlotBarHistoryStyle(BarHistory bh, string paneTag, string styleName, WLColor color = default(WLColor), bool fitInAxis = false)

Plots the specified BarHistory instance in bh in a chart pane with the specified paneTag, using the specified color. The fitInAxis parameter is optional, with a default of false. If set to true, it will cause the BarHistory data to fit within the existing scale of the pane, so as not to distort it. If false, the pane's scale will adjust to accommodate the BarHistory data. The styleName parameter must be the exact string of a Chart Style name: "Bar", "Candlestick", or "Line". The method does not support variable-width styles like "Equivolume", and if one is specified it defaults to "Bar".

PlotIndicator

public override void PlotIndicator(IndicatorBase ib, WLColor color = default(WLColor), PlotStyle? plotStyle = null, bool suppressLabels = false, string paneTag = null)

Plots an indicator on the chart. The ib parameter is an indicator is an instance of the IndicatorBase class, the class which all indicators in WealthLab are derived from. Any time you create an indicator in code, you're returned an instance of the indicator's specialized class, which is a descendant of IndicatorBase. Parameter remarks

  • color is optional. If not specified WealthLab will use the indicator's default color.
  • plotStyle is optional, and is a member of the PlotStyle enum. If not specified, WealthLab uses the indicator's default plot style.
  • suppressLabels lets you disable to indicator pane labels and the value markers along the chart's right margin for this plot.
  • paneTag is optional for indicators. Pass your own paneTag to plot multiple indicators of different types in the same pane, for example.

PlotIndicatorBands

public override void PlotIndicatorBands(IndicatorBase ib1, IndicatorBase ib2, WLColor color = null, int lineWidth = 2, int opacity = 50, bool suppressLabels = false, string paneTag = null, LineStyle ls = LineStyle.Solid)

Plots the two IndicatorBase series ib1 and ib2 as a companion bands with solid lines using the color, if specified, filling the area between the lines with same color with the specified opacity, a number from 0 (transparent) to 100 (opaque). Remarks

  • Except for the IndicatorBase parameters, all others are optional.
  • The two indicator need not be typical "companions", but they should be indicators that plot in the same pane by default.

PlotIndicatorChartStyle

public virtual void PlotIndicatorChartStyle(IndicatorBase ib, WLColor color = default(WLColor), int width = 2, bool useChartColors = false, string chartStyleName = "Bar", bool suppressLabels = false, string paneTag = null)

This method is designated to plot the VChart indicator (or any other indicator that returns values for the GetBarChartCompanion method) ib in a custom plot style, with the specified color and width parameters. Pass on a supported ChartStyle name i.e. Bar, Candlestick, Line, Heikin Ashi.

PlotIndicatorCloud

public override void PlotIndicatorCloud(IndicatorBase ib1, IndicatorBase ib2, WLColor colorUp = null, WLColor colorDown = null, int width = 2, LineStyle ls = LineStyle.Solid, int opacity = 25, bool suppressLabels = false, string paneTag = null)

Plots and fills bands composed of two indicators, ib1 and ib2, that periodically cross over each other on the specified pane. Each indicator is plotted as a line using colorUp for ib1 and colorDown for ib2, style, and width. The band between the indicators is filled with alternating colors. When ib1 is above ib2 colorUp is used and colorDown when ib2 is above ib1. Note!
SetSeriesBarColor may be used to change the color of the lines on specified bars. To make this work independently for both lines, it's required to plot ib2 using a PlotIndicator/TimeSeries function as shown in the example. Parameter remarks

  • ib1 and ib2 parameters are indicators, instances of the IndicatorBase class. Any time you create an indicator in code, you're returned an instance of the indicator's specialized class, which is a descendant of IndicatorBase. See also: PlotTimeSeriesCloud
  • colorUp/Down are optional. If not specified WealthLab will use the indicators' default colors.
  • width is the line width (default is 2) for both indicator plots. Pass 0 for no line.
  • lineStyle is optional, and is a member of the LineStyle enum. Default is a solid line.
  • opacity is a number between 0 and 100, default 25, that determines the transparency of the cloud, where 0 is fully transparent (no fill) and 100 is opaque.
  • suppressLabels lets you disable to indicator pane labels and the value markers along the chart's right margin for this plot.
  • paneTag is optional for indicators. Pass your own paneTag to plot multiple indicators of different types in the same pane, for example.

PlotIndicatorHistogramTwoColor

public override void PlotIndicatorHistogramTwoColor(IndicatorBase ib, WLColor colorUp = null, WLColor colorDown = null, int width = 2, bool suppressLabels = false, string paneTag = null)

Plots the indicator ib using a histogram plot style with two colors. The colorUp is used to plot histogram bars greater than zero, and colorDown bars less than zero. The width of the histogram bars is specified in width.

PlotIndicatorLine

public override void PlotIndicatorLine(IndicatorBase ib, WLColor color = default, int lineWidth = 2, LineStyle lineStyle = LineStyle.Solid, bool suppressLabels = false, string paneTag = null)

Similar to PlotIndicator, but instead of specifying a plot style, this version always plots a line. You can control the thickness and style of the line using the lineThickness and lineStyle parameters. Parameter remarks

  • color is optional. If not specified WealthLab will use the indicator's default color.
  • *lineStyle * is optional.
  • suppressLabels lets you disable to indicator pane labels and the value markers along the chart's right margin for this plot.
  • paneTag is optional for indicators. Pass your own paneTag to plot multiple indicators of different types in the same pane, for example.

PlotIndicatorMountain

public override void PlotIndicatorMountain(IndicatorBase ib, WLColor color = null, int lineWidth = 2, int opacityStart = 50, int opacityEnd = 20, bool suppressLabels = false, string paneTag = null)

Plots the indicator ib in a mountain (shaded area) plot style, with the specified color. The lineWidth parameter controls the width of the mountain plot outline. The filled area will have a gradient controlled by the opacityStart and opacityEnd (0-100).

PlotIndicatorOscillator

public override void PlotIndicatorOscillator(IndicatorBase ib, WLColor color = null, WLColor colorOversold = null, WLColor colorOverbought = null, int opacity = 25, bool suppressLabels = false, string paneTag = null)

Plots the specified IndicatorBase series ib as a solid line using the color, if specified. When ib moves below its oversold area, this area of the chart is filled using colorOversold. Conversely, when ib moves above the overbought area, that area of the chart is filled with colorOverbought. Overbought/Oversold colors are subject to the opacity percentage setting, a number from 0 (transparent) to 100 (opaque). Remarks

  • Except for the IndicatorBase parameter, all others are optional.
  • Standard overbought and and oversold levels are pre-assigned to oscillator-type indicators. To override these levels, use PlotTimeSeriesOscillator() instead.

PlotStopsAndLimits

public void PlotStopsAndLimits(int dotSize = 6, bool stops = true, bool limits = true, WLColor colorBuy = default(WLColor), WLColor colorSell = default(WLColor), WLColor colorShort = default(WLColor), WLColor colorCover = default(WLColor), string paneTag = "Price")

Call PlotStopsAndLimits once in Initialize() to cause stop and/or limit orders to be plotted on the chart. Stop and limit orders are drawn as colored dots on the chart at the bar and price levels at which they are active. All parameters are optional but can be specified for customization. Remarks
Default color codes by order type as follows:

  • %Buy = blue%
  • %Sell = red%
  • %Short = fuchsia%
  • %Cover = green%

PlotTimeSeries

public void PlotTimeSeries(TimeSeries ts, string name, string paneTag, WLColor color = default(WLColor), PlotStyle plotStyle = PlotStyle.Line, bool suppressLabels = false)

Plots a TimeSeries on the chart. The ts parameter is a TimeSeries instance. PlotTimeSeries is useful when plotting the results of mathematical operations on indicators and other TimeSeries. These operations always return instances of the TimeSeries class. The name parameter should be a descriptive name of the data being plotted. This appears in the pane label. The paneTag specifies which chart pane to plot the data in. You can specify Price for the price pane, Volume for the volume pane, or some other string value for a custom pane. The color parameter is optional. If not provided, WealthLab will use a default color. The plotStyle parameter is also optional, and is a member of the PlotStyle enum. If not specified, WealthLab will use PlotStyle.Line. The suppressLabels parameter lets you disable to indicator pane labels and the value markers along the chart's right margin for this plot.

PlotTimeSeriesBands

public void PlotTimeSeriesBands(TimeSeries ts1, TimeSeries ts2, string name, string paneTag, WLColor color = default(WLColor), int lineWidth = 2, int opacity = 50, bool suppressLabels = false)

Plots the two TimeSeries instances specified in ts1 and ts2 as a filled band. The opacity parameter can range from 0 (transparent) to 100 (fully opaque). Remarks

  • Color, line width, and opacity parameters are optional.
  • The specified name label is displayed in the pane specified by paneTag. Pass true to suppressLabels to hide the label.

PlotTimeSeriesCloud

public void PlotTimeSeriesCloud(TimeSeries ts1, TimeSeries ts2, string name, string paneTag, WLColor colorUp, WLColor colorDown, int width = 2, LineStyle ls = LineStyle.Solid, int opacity = 25, bool suppressLabels = false)

Plots and fills bands composed of two TimeSeries, ts1 and ts2, that periodically cross over each other on the specified pane. Each TimeSeries is plotted as a line using colorUp for ts1 and colorDown for ts2, style, and width. The band between series is filled with alternating colors. When ts1 is above ts2 colorUp is used and colorDown when ts2 is above ts1. Note!
SetSeriesBarColor may be used to change the color of the lines on specified bars. To make this work independently for both lines, it's required to plot ts2 again using a PlotTimeSeries function. Parameter remarks

  • ts1 and ts2 parameters are TimeSeries instances. TimeSeries are the result of mathematical operations on indicators and other TimeSeries always return instances of the TimeSeries class.
  • name is a description of the plotted series/clouds
  • paneTag specifies which chart pane to plot the data in. You can specify Price for the price pane, Volume for the volume pane, or some other string value for a custom pane.
  • colorUp and colorDown are specified for the ts1 and ts2 line plots, respectively, as well as for the clouds as described above.
  • width is the line width (default is 2) for both indicator plots. Pass 0 for no line.
  • lineStyle is optional, and is a member of the LineStyle enum. Default is a solid line.
  • opacity is a number between 0 and 100, default 25, that determines the transparency of the cloud, where 0 is fully transparent (no fill) and 100 is opaque.
  • suppressLabels lets you disable to indicator pane labels and the value markers along the chart's right margin for this plot.

PlotTimeSeriesHistogramTwoColor

public void PlotTimeSeriesHistogramTwoColor(TimeSeries ts, string name, string paneTag, WLColor colorUp = default(WLColor), WLColor colorDown = default(WLColor), int width = 2, bool suppressLabels = false)

Plots the TimeSeries ts using a histogram plot style with two colors. The colorUp is used to plot histogram bars greater than zero, and colorDown bars less than zero. The width of the histogram bars is specified in width.

PlotTimeSeriesLine

public void PlotTimeSeriesLine(TimeSeries ts, string name, string paneTag, WLColor color = default(WLColor), int lineWidth = 2, LineStyle lineStyle = LineStyle.Solid, bool suppressLabels = false)

Similar to PlotTimeSeries, but instead of specifying a plot style, this version always plots a line. You can control the thickness and style of the line using the lineThickness and lineStyle parameters.

PlotTimeSeriesOscillator

public void PlotTimeSeriesOscillator(TimeSeries ts, string name, string paneTag, double oversold, double overbought, WLColor color = default(WLColor), WLColor colorOversold = default(WLColor), WLColor colorOverbought = default(WLColor), int opacity = 25, bool suppressLabels = false)

Plots the specified TimeSeries ts as a solid line in the specified paneTag using the color, if specified. When ts moves below the oversold value, this area of the chart is filled using colorOversold. Conversely, when ts moves above the overbought value, that area of the chart is filled with colorOverbought. Overbought/Oversold colors are subject to the opacity percentage setting, a number from 0 (transparent) to 100 (opaque). Remarks

  • Colors and opacity parameters are optional.
  • The specified name label is displayed in the pane specified by paneTag. Pass true to suppressLabels to hide the label.
  • Also see PlotIndicatorOscillator()

SetBackgroundColor

public void SetBackgroundColor(BarHistory bars, int bar, WLColor color, string paneTag = "Price")

Sets the background of the specified chart pane, at the specified bar index, to the color you specify.

SetBackgroundColorAllPanes

public void SetBackgroundColorAllPanes(BarHistory bh, int bar, WLColor color)

Sets the background to the color specified from the top to bottom of the chart at the specified bar index.

SetBarColor

public void SetBarColor(BarHistory bars, int bar, WLColor color)

Sets the chart bar color at the specified index to the color you specify.

SetChartDrawingOptions

public void SetChartDrawingOptions(ChartDisplaySettings cds)

Lets you control various chart rendering settings via code. The cds parameter should be an instance of the ChartDisplaySettings class, with properties assigned for the various chart settings you want to change. Properties that you do not assign a value to will default to the current chart preferences. The ChartDisplaySettings class has the following properties:

  • public Color? ColorBackground - the chart background color
  • public Color? ColorAxisBackground - the chart axis background color
  • public Color? ColorUpBar - the color of the chart's "up" bars
  • public Color? ColorDownBar - the color of the chart's "down" bars
  • public Color? ColorPaneSeparator - the color of the chart's pane separator lines
  • public Color? ColorGridLines - the color of the chart's grid lines
  • public Color? ColorAxisLabels - the color of the chart's axis labels
  • public Color? ColorCursors - the color of the vertical and crosshair cursors
  • public Color? ColorWatermark - the color of the chart watermark that displays the symbol and security name
  • public bool? ShowVolumePane - whether or not the volume pane should be displayed
  • public bool? ShowEventIcons - whether or not icons for Events (fundamental, etc.) should be displayed
  • public bool? DrawTradeArrows - controls whether the entry/exit arrows are displayed for trades
  • public bool? LogScale - whether or not the chart price pane should be log scale
  • public bool? ShowStatusBar - whether or not the chart status bar should appear
  • public bool? AlwaysShowToolbar - whether the chart toolbar should always appear, or appear only when the mouse is near the top area of the chart
  • public double? BarSpacing - the number of pixels between chart bars
  • public int? Margin - how much space should appear above and below chartable data
  • public int? PaneSeparatorWidth - the size of the pane separator lines, setting this to zero hides the separator lines
  • public int? CursorThickness - how thick the vertical and crosshair cursor lines should be

SetPaneDrawingOptions

public void SetPaneDrawingOptions(string paneTag, int height, int sortValue = 50)

Controls the height and sort order of the chart pane with the specified paneTag (case sensitive). The price pane has a paneTag of "Price", and the volume pane "Volume". Indicator panes typically have a paneTag equal to the plotted indicator's abbreviation. But, to be sure, you can access the PaneTag property of a plotted indicator to obtain its paneTag. The height parameter determines the relative vertical size of the chart pane. For example, given two panes, one with a height of 100 and one with a height of 50, the first pane will take up twice as much vertical space on the chart. By default, the price pane has a height of 100 and volume and indicator panes 33. The optional sortValue parameter controls the order that the panes appear in the chart. The price pane has a default sortValue of 0, the volume pane 100, and indicator panes 50. This causes the price pane to sort to the top, the volume pane to the bottom, and indicator panes in between.

SetPaneMinMax

public void SetPaneMinMax(string paneTag, double min, double max)

Allows you to manually set the scale of the pane identified by paneTag. The min and max values will be used to define the visible range of the pane. When required to keep price and indicators visible, the actual visible scale of the pane will still be dynamically extended beyond the range that you specify.

SetSeriesBarColor

public void SetSeriesBarColor(TimeSeries bars, int bar, WLColor color)

Sets the series bar color at the specified index to the color you specify.

SetTextDrawingFont

public void SetTextDrawingFont(WLFont font)

Changes the font that will be used in subsequent text rendering calls in your Strategy code.

SetTextDrawingOptions

public void SetTextDrawingOptions(WLColor backgroundColor, WLColor borderColor, int borderWidth)

Lets you control how text is rendered to the chart by any of the text drawing methods. You can specify a background color (backgroundColor parameter), and/or a border color (borderColor parameter) and width (borderWidth parameter) to use when text is rendered. If you don't want a background color and/or border, specify Color.Transparent in these parameters. The settings affect all subsequent calls to text drawing methods.

Miscellaneous

20

BacktestData

public List<BarHistory> BacktestData

Returns a List of BarHistory objects that contain the historical data being backtested.

BacktestSettings

public BacktestSettings BacktestSettings

Exposes the instance of the BacktestSettings class that contains the backtest settings used by the Backtester. You can override one or more of the backtest settings by changing the properties of the BacktestSettings instance. These changes affect your Strategy run only, and not the overall backtest settings established in Preferences. Remarks

  • You should make assignments to BacktestSettings properties in the Initialize() method.

CurrentBars

public BarHistory CurrentBars

Returns the BarHistory currently being processed by this Strategy instance. During normal Strategy execution this identifies the symbol context used by position-related members such as OpenPositions, LastPosition, and FindOpenPosition.

CurrentCash

public double CurrentCash

Returns the current cash level available in the simulation. The cash level decreases as your Strategy opens new positions, and increases as it exits positions.

CurrentEquity

public double CurrentEquity

Returns the current equity level in the simulation. This is initially determined by the Starting Equity that you established in Strategy Settings. As your Strategy executes bar by bar, and enters and exits positions, the equity level will rise and fall.

ExternalDataDRO

public DataRequestOptions ExternalDataDRO

Returns the DataRequestOptions used when the Strategy requests external historical data. You can use this instance to control applicable options for data obtained through methods such as GetHistory and GetHistoryUnsynched.

GetChartDrawings

public List<ManuallyDrawnObject> GetChartDrawings(BarHistory bars, string objectType, string name)

Returns a List of ManuallyDrawnObject instances that represent the chart drawing objects that exist for the specified BarHistory (bars parameter.) Drawing objects are segregated by symbol and HistoryScale (Daily, Weekly, etc.) The objectType and name parameters allow you to optionally filter the results by the type of object ("Line", "Horizontal Line", etc.) and/or the name you provided for the drawing object when you created or edited it. Pass null to either of these parameters to ignore it.

GetCurrentIndex

public override int GetCurrentIndex(BarHistory bh)

This method is intended to be called in either the PreExecute or PostExecute methods. These two methods provide you a list of BarHistory objects that are being processed during the current Execute cycle. GetCurrentIndex takes a BarHistory parameter, which should be one of the instances in the list mentioned above. It returns the int index into that BarHistory that represents the bar currently being processed by Execute.

GetGlobal

public object GetGlobal(string key)

Gets a value out of the global Dictionary that is available throughout the current WL9 session. Specify a key and a value. If the keyed item is not present, returns null.

GetHistory

public BarHistory GetHistory(BarHistory synchWith, string symbol, string dataSetName = null)

Lets you access data for another symbol from within your Strategy. Returns a BarHistory object for the specified symbol. The synchWith parameter specifies a BarHistory object to synch the historical data with. Generally, this will be the bars parameter from the Initialize or Execute method. You can optionally pass a DataSet name in the dataSetName parameter to retrieve the data from that DataSet, if it's found there. Remarks

  • GetHistory does not use statically cached data collected by the Data Manager. It's primary intent is to allow a Strategy to make decisions using data that does not reside in the DataSet being tested. For example, buy a stock if the corresponding index is oversold.
  • For statically cached data, use the BacktestData property, which returns a List containing the BarHistory instances being backtested.

GetHistoryUnsynched

public BarHistory GetHistoryUnsynched(string symbol, HistoryScale scale, string dataSetName = null)

Returns an instance of the BarHistory class the represents historical data for the symbol and scale you specify. If WealthLab could not locate historical data for the symbol/scale, the method returns null. You can optionally pass a DataSet name in the dataSetName parameter to retrieve the data from that DataSet, if it's found there. The resulting data is not synched to the BarHistory currently being processed on the chart. Therefore, you should not plot indicators or TimeSeries derived from this data, unless you first synchronize these series using the TimeSeriesSynchronizer helper class. Remarks

  • GetHistoryUnsynched does not use statically cached data collected by the Data Manager. It's primary intent is to allow a Strategy to make decisions using data that does not reside in the DataSet being tested. For example, buy a stock if the corresponding index is oversold.
  • For statically cached data, use the BacktestData property, which returns a List containing the BarHistory instances being backtested.

GetPairHistory

public BarHistory GetPairHistory(BarHistory syncWith, string symbol, int timeout = 15, string dataSetName = null)

Returns a synchronized BarHistory for a paired symbol. Especially during intraday operation, GetHistory can often return a BarHistory for a secondary symbol without the latest up-to-date bar if the request occurs before the Historical Provider has built the bar on its server. Instead, GetPairHistory will wait and try to acquire an updated BarHistory for a specified number of seconds. The call returns immediately when the result is up-to-date with the syncWith BarHistory or after the timeout period. Remarks

  • GetPairHistory will make a new request every 1 second until the data is up-to-date. Extra requests can impact providers that throttle or otherwise limit the number of request allowed.

GetSameBarExitIndex

public int GetSameBarExitIndex(BarHistory bh)

Returns the index to use when evaluating a same-bar exit for the supplied BarHistory. WealthLab bases the result on the current processing index and adjusts it so that it does not exceed the final index of the BarHistory.

HasGlobal

public bool HasGlobal(string key)

Returns true if the specified key item is in the global Dictionary.

SendEmail

public void SendEmail(string fromEmail, string smtpServer, string login, string password, int smtpPort, string toEmail, string messageSubject, string messageText, bool smtpEnableSSL = true)

Call this method to send e-mail from your Strategy code. If messageText contains HTML tags, SendEmail will set the email format to HTML, allowing rich formatting (bold, links, tables, etc.) to be rendered in the recipient's email client. Email providers like Gmail and Hotmail have restrictions for sending email from less secure apps. However, you Use this method with Gmail (and other email clients) by creating an App Password: a 16-digit passcode that gives a less secure app permission to access your Google Account. App passwords can only be used with gmail accounts that have 2-Step Verification turned on. Here's how to set it up:

  1. Go to your Google Account - myaccount.google.com
  2. Navigate to Security > 2-Step Verification and enable it.
  3. In the same Security section, use Search Google Account at the top to find "App passwords" and click on it in the results.
  4. Type a name, e.g., WealthLabStrategy, and click Create.
  5. Copy the 16-digit App Password and remove spaces (e.g., abcdefghijklmnop) to use for the password in SendEmail(). The example has a reusable routine that emails all signals from a Strategy. Simply copy the BacktestComplete() method and modify the email variables where indicated.

SetGlobal

public void SetGlobal(string key, object value)

Sets a value in the global Dictionary that is available throughout the current WL9 session. Specify a key and a value. Tip: To make a variable available for all symbols during script execution, declare a static class variable instead of using global variables.

StrategyName

public string StrategyName

Returns the class name of the executing strategy that derives from UserStrategyBase.

WriteListToDebugLog

public void WriteListToDebugLog<T>(string header, IEnumerable<T> items, int itemsPerLine = 10, string separator = ",", bool groupBySymbol = true)

Writes a list of items to the debug log with a maximum of itemsPerLine per row.

WriteToDebugLog

public void WriteToDebugLog(object txt, bool groupBySymbol = true)

Writes a line of output to the Debug Log tab. Remarks

  • The Debug Log is refreshed for each Backtest run unless you uncheck Automatically Clear Before Each Run in the Debug Log toolbar.
  • The Log is explicitly segregrated by writes for the symbol under test. You don't need to add bars.Symbol to know for which symbol the write occurred. You can override this behavior to create a sequential output by passing false as the groupBySymbol parameter.
  • If you WriteToDebugLog in BacktestBegin, BacktestComplete, PreExecute, or PreExecute virtual methods, WealthLab will generally write to the same random symbol, but you can't count on it especially when using Wealth-Data dynamic DataSets. In this case, the order of writes may not appear intuitive. One way around this is to save writes to a private static List and WriteToDebugLog while iterating through the list in BacktestComplete() as shown in the example. Another way is to simply pass false as the groupBySymbol parameter.

WriteToStatusBar

public void WriteToStatusBar(string txt, WLColor color = null)

Writes the specified text (txt) to the Strategy Window status bar, using the provided color if specified. If color is not specified, the theme appropriate foreground color is used.

Parameter Related

2

AddParameter

public Parameter AddParameter(string label, ParameterType paramType, object defaultValue, double minValue = -999999999, double maxValue = 999999999, double stepValue = 1)

Call this from within the Strategy's constructor to add a parameter to the Strategy. The method returns an instance of the Parameter class that represents the parameter you added. Remarks

  • Do not use commas in the parameter's label.

Parameters

public ParameterList Parameters

Returns a List containing the Strategy's parameters, all instances of the Parameter class. Strategy parameters should be added in the constructor, by calling the AddParameter method.

Positions

14

AverageEntryPrice

public double AverageEntryPrice()

Returns the average entry price of open positions at the moment.

BarsSinceLastExit

public int BarsSinceLastExit(int idx, int limitSearch = 100, string exitSignal = "")

Returns the number of bars ago of the most recent exit for all symbols in the Backtest by finding the most recent exit bar from all exited positions that have the exitSignal, if specified. To speed up large simulations, the limitSearch parameter limits the number of position exits to search starting from the most recent Position. Pass 0 for no limit. Remarks

  • NSF Positions are not included.

The sample code show how to trigger on the last exit for the current symbol, and also how to filter trades based on the last exit of all symbols in the backtest using BarsSinceLastExit(). Run it with one symbol and then a Portfolio backtest on the Dow 30, for example.

FindOpenPosition

public Position FindOpenPosition(int positionTag)
public Position FindOpenPosition(PositionType pt)

Looks for an open Position that has specified numeric positionTag for the BarHistory being processed. Positions that were created as a result of passing a value in the PlaceTrade method's positionTag parameter can be found in this way. The second version of FindOpenPosition allows you to look for primary symbol positions by type, where the pt parameter can contain PositionType.Long or PositionType.Short. Remarks

  • To find open Positions for other symbols/BarHistories use FindOpenPositionAllSymbols.

FindOpenPositionAllSymbols

public Position FindOpenPositionAllSymbols(int positionTag)
public Position FindOpenPositionAllSymbols(string symbol, PositionType pt)

Returns the open position with the specified positionTag among the entire set of currently open postions, regardless of symbol. This method was created to support a Strategy that stops normal trading during a specific technical event, and instead swaps the entire portfolio into a bond ETF. When the technical condition is over, and normal trading can begin again, the Strategy calls FindOpenPositionAllSymbols to locate the position in this bond ETF that it had opened previously, and closes it. Remarks

  • If the strategy trades multiple secondary symbols, the positionTag must be unique for each one.

GetOpenPositionQuantity

public double GetOpenPositionQuantity(string symbol, PositionType pt)

Returns the total number of shares/contracts in all open Positions of the type specified in pt (Long or Short), for the specified symbol.

GetPositions

public override List<Position> GetPositions(bool includeNSF = false)

Returns the list of positions (instances of the Position class) for the current symbol being processed. Use the includeNSF parameter to determine if NSF Positions should be included.

GetPositionsAllSymbols

public List<Position> GetPositionsAllSymbols(bool includeNSF = false)

Returns the list of positions (instances of the Position class) for all symbols in the backtest. Use the includeNSF parameter to determine if NSF Positions should be included.

HasOpenPosition

public bool HasOpenPosition(BarHistory bars, PositionType pt)

Lets you determine if there is currently an open Position of the current type (PositionType.Long or PositionType.Short). For the bars parameter, pass the value of the bars parameter that you received in the Execute method.

LastOpenPosition

public virtual Position LastOpenPosition

Only for the BarHistory being processed, LastOpenPosition returns the most-recently created open Position object. Returns null if there are no open Positions currently.

LastPosition

public virtual Position LastPosition

Only for the BarHistory being processed, LastPosition returns the most-recently created Position object or null if no Positions have been created. Remarks

  • If the Strategy creates trades for secondary symbols see GetPositionAllSymbols().

OpenPositions

public virtual List<Position> OpenPositions

Returns a list of the open positions (instances of the Position class) for the BarHistory currently being processed. This includes positions that are marked NSF.

OpenPositionsAllSymbols

public List<Position> OpenPositionsAllSymbols

Returns a list of open positions (instances of the Position class) for all symbols being backtested. You generally won't need to access other symbol positions during normal Strategy processing, but this can be handy for certain summary processing you might perform during the BacktestComplete method.

OpenQuantity

public double OpenQuantity

Returns the net total number of shares/contracts held by open positions for the current symbols being processed. Long positions return positive quantities and short positions negative.

OpenQuantityAllSymbols

public double OpenQuantityAllSymbols

Returns the net total number of shares/contracts held by open positions for all symbols in a portfolio backtest. Long positions return positive quantities and short positions negative.

Strategy Execution

15

AssignAutoStopTargetPrices

public virtual void AssignAutoStopTargetPrices(Transaction t, double basisPrice, double executionPrice)

You can override this method to assign values to the AutoProfitTargetPrice and AutoStopLossPrice properties of the Transaction instance passed in the t parameter. See the corresponding entries for these properties in the Transaction class for more details on same-bar exits. The advantage of assigning these properties within this method is that it provides you the actual executionPrice, upon which you can base the desired profit target and stop loss prices.

BacktestBegin

public virtual void BacktestBegin()

The backtester calls this method for the first symbol (sorted alphabetically) in the universe prior to the backtest beginning its processing.

BacktestComplete

public virtual void BacktestComplete()

The backtester calls this method for the last symbol (sorted alphabetically) in the universe after the backtest processing is completed for all symbols.

Cleanup

public virtual void Cleanup(BarHistory bars)

The backtester calls the Strategy's Cleanup method after all processing is complete for a symbol. Override the Cleanup method to dispose of any necessary objects or data that are not handled by normal .NET garbage collection.

Execute

public abstract void Execute(BarHistory bars, int idx)

The backtester calls the Strategy's Execute method for each bar of data being processed. The BarHistory being processed is passed in the bars parameter. The numeric index being processed is passed in the idx parameter. Override the Execute method to implement the Strategy's primary logic.

ExecuteSessionOpen

public virtual void ExecuteSessionOpen(BarHistory bars, int idx, double sessionOpenPrice)

**Note!**
The indicator ***NextSessionOpen*** is a better overall option for strategies that use the session's opening price. This ExecuteSessionOpen() method can be considered *obsolete*, but remains functional for legacy code. Override and use this method to perform any processing that requires the session open price of the current trading day. The price is passed via the sessionOpenPrice parameter. During backtesting, WealthLab looks at the next daily bar of data to determine the session open price. With respect to Daily bars, sessionOpenPrice is the opening price of the next bar. For an intraday chart, sessionOpenPrice returns the open of the current session but looks to the next session when processing the last bar of the day. For live trading, WealthLab will attempt to load the price from active quote streams or by Historical Data Providers that are enabled in the Data Manager and will keep trying to get the session open price during market hours for up to 20 seconds, so overriding this method could impact live trading Strategy performance. For a more than 4 to 6 symbols, drag the DataSet into a Quotes tool, check the market at the bottom and start Streaming Remarks

  • ExecuteSessionOpen() is called after Execute().
  • The Execute() method needs to be included but need not be used.
  • On the final bar (bars.Count - 1), ExecuteSessionOpen() will be called only during market hours on a trading day.
  • The Wealth-Data Provider generally returns the primary market opening price. If the primary market has not yet traded (could be several minutes after the opening bell for NYSE stocks), the first-traded price may be returned. Run the example on Daily bars and take note (see Debug Window) that ExecuteSessionOpen() is not called outside of market hours since the next session opening price is unknown. The example uses sessionOpenPrice to determine if a -2% gap down occurred, and if the RSI value is over 40, the strategy shorts at a limit price 1% above the sessionOpenPrice and covers at the close.

ExecutionDataSetName

public string ExecutionDataSetName

Returns the name of the DataSet that is currently being processed. If the Strategy was not executed on a DataSet (single symbol mode), returns null.

ExecutionMode

public StrategyExecutionMode ExecutionMode

Returns the execution mode of the backtester. For details and an example, see Enums > StrategyExecutionMode

GetMaxRiskStopLevel

public virtual double GetMaxRiskStopLevel(BarHistory bars, PositionType pt, int idx)

If your Strategy uses the Max Risk Percent position sizing method, WL9 calls this method to determine the stop loss level for a trade at the time it is placed. The default implementation uses the Max Risk Indicator that is defined in Trading Preferences. Override this method to customize the stop loss level.

Initialize

public virtual void Initialize(BarHistory bars)

The backtester calls the Strategy's Initialize method prior to beginning the main trading logic loop. Initialize is called once for each symbol being backtested, and the symbol's BarHistory is passed in the bars parameter. Override this method to create any instances of indicators and other objects your Strategy will need.

NewWFOInterval

public virtual void NewWFOInterval(BarHistory bars)

Use this method to regenerate indicators on each new WFO interval for the WFO out-of-sample backtest. Since indicators are usually created in Initialize, to make a WFO recalculate indicators that use Parameters you must override NewWFOInterval.

PostExecute

public virtual void PostExecute(DateTime dt, List<BarHistory> participants)

Executes immediately after the main backtesting loop that processed each symbol via the Execute method. PostExecute gives you a chance to operate on the list of symbols that have been processed during this backtesting loop iteration. You are provided the date/time being processed via the dt parameter, and a list of BarHistory instances containing the data being processed this iteration in the participants parameter. Use the GetCurrentIndex method to determine the index to use for a particular BarHistory instance.

PreExecute

public virtual void PreExecute(DateTime dt, List<BarHistory> participants)

Executes immediately prior to the main backtesting loop that processed each symbol via the Execute method. PreExecute gives you a chance to operate on the list of symbols that are being processed during this backtesting loop iteration. You are provided the date/time being processed via the dt parameter, and a list of BarHistory instances containing the data being processed this iteration in the participants parameter. Use the GetCurrentIndex method to determine the index to use for a particular BarHistory instance.

StartIndex

public int StartIndex

This property controls the starting point of your backtest, specified as a bar number index. By default, StartIndex return 0, which means that your Strategy's Execute method will first get called with a bar index of zero. If you assign a higher value to StartIndex, the Execute method will first get called at the index you specified. This can be useful to avoid unnecessary calls to Execute. For example, if your Strategy uses a 200 bar moving average, you can set StartIndex to 199 to prevent the Execute method from being called 199 times before the moving average is available. The backtester also uses StartIndex to determine the entry bar for the benchmark buy & hold comparison. In the example above, the buy & hold comparison would have also entered its position at bar 199, making the benchmark a more fair comparison.

Trading

5

CloseAtTrailingStop

public void CloseAtTrailingStop(Position pos, TrailingStopType tst, double amount, string signalName = "", int atrPeriod = 22)

Use this method to close the specified Position object (pos) at a trailing stop. Specify the type of trailing stop in the tst parameter. You can specify percentage, point or ATR based (Chandelier) trailing stops, and specify whether the trailing stop is based off closing prices or off high/lows. The amount parameter specifies the size of the stop, either in percentage, point or ATR multiplier according to the tst parameter. The atrPeriod parameter indicates the ATR lookback period and only applies when parameter tst is TrailingStopType.ATR.

ClosePosition

public void ClosePosition(Position pos, OrderType orderType, double price = 0, string exitSignalName = "")

Use this method to explicitly close a Position object (pos). Specify the orderType to use to close the position. If you use a limit or stop order, specify the order price in the price parameter. OrderType is one of the following enumerations (see Enums for more info):

  • OrderType.Market
  • OrderType.Limit
  • OrderType.Stop
  • OrderType.LimitMove
  • OrderType.MarketClose
  • OrderType.FixedPrice You can pass an optional exitSignalName parameter, which will be assigned to the Transaction object's SignalName property, and will ultimately be assigned to the resulting Position's ExitSignalName property.

PlaceTrade

public Transaction PlaceTrade(BarHistory bars, TransactionType transType, OrderType orderType, double price = 0, int positionTag = -1)
public Transaction PlaceTrade(BarHistory bars, TransactionType transType, OrderType orderType, double price, string signalName)

Places a simulated order, and returns an instance of the Transaction class the represents it. The WealthLab backtester will determine the number of shares based on the position size settings you established in the Strategy Settings. The backtester will attempt to fill the trade at the start of the following bar, and the simulation must have sufficient simulated capital to do so.

  • For the bars parameter, pass the same bars parameter value that you received in the call to the Execute method.
  • For the transType parameter, specify TransactionType.Buy, TransactionType.Sell, TransactionType.Short, or TransactionType.Cover.
  • For the orderType parameter, specify OrderType.Market, OrderType.Limit or OrderType.Stop.
  • For limit and stop orders, supply an order price in the price parameter.
  • The positionTag parameter allows you to optionally maintain groups of positions, using integer codes that you specify. You can locate an open position with a matching positionTag by calling the FindOpenPosition method. This method is used internally by Building Block strategies. The second constructor allows you to pass a signalName parameter. This string will be assigned to the Transaction's SignalName property, and will ultimately end up assigned to the resulting Position's EntrySignalName or ExitSignalName properties. The method returns an instance of the Transaction class that represents the transaction. You can assign a value to the Transaction.Quantity to override the Strategy position sizing, and employ Strategy-specific position sizing. If you assign a Quantity to an exit Transaction (Sell, Cover) then one of the following can occur:
  • If the Quantity is less than the Quantity of the matched open Position, WL9 will split the Position into two, and close out Position with the specified Quantity.
  • If the Quantity is greater than the matched open Position, and there are multiple open Positions in the backtest, WL9 will split the Transaction into multiple instance, and close out as many open Positions as possible with the specified Quantity. You can effectively close out all open Positions by assigning Double.MaxValue to an exit Transaction's Quantity.

Rebalance

public Transaction Rebalance(BarHistory bars, double percentOfEquity)

Issues a buy or sell, as appropriate, to cause the symbol specified in bars to allocate a percentage of the current backtest equity specified in percentOfEquity. If there is no open Position for bars, will issue a buy order for the full number of shares required to allocate the position. If there is already one or more open Positions, will issue a buy if more shares are required or a sell for fewer shares. This will typically cause other smaller Positions to be opened for the symbol, including the splitting of a larger open Position into two in order to sell a portion of it. Remarks:

  • The minimum Position size for rebalance is determined by the SymbolInfo.QuantityDecimals.
  • See Preferences > Other Settings > Position Matching to control which Positions are exited first.

TrailingStopType

public enum TrailingStopType
  • ATR - A Chandelier stop using a 22-period (default period) Average True Range.
  • PercentC - A percentage of closing prices. For example, pass 7.5 for amount for a 7.5% trailing stop based on closing prices.
  • PercentHL - Like PercentC, but adjusts based on intraday progress; uses highs for long positions and lows for short positions.
  • PointC - amount becomes a point-based stop with respect to closing prices.
  • PointHL - Like PointC, but amount is subtracted from highs (long) or added to lows (short) to adjust the trailing stop value.

Need help with this API?

Ask the community or explore custom development services.