Your interactive trading laboratory!
5 users online

Quantacula Help

How-To
C# API Reference
Extensions
Development Blog

TASC-Extensions
The open-source GitHub repository of source code for the TASCExtensions Quantacula extension. Contains indicators and other extensions adapted from the Traders' Tips articles in Technical Analysis of Stocks & Commodities magazine.
UserModelBase Reference

C# coded models in Quantacula are .NET classes derived from the UserModelBase base class. You override virtual methods in UserModelBase to react to different points of the backtest process. You call methods defined in UserModelBase to place simulated trades, plot indicators, and perform other rendering on the chart.

The C# Language

C# is a popular programming language created by Microsoft. A complete primer on C# programming is beyond the score of this site, but this page provides a good start.

The .NET Framework

The .NET framework is a set of libraries and classes developed by Microsoft. Your C# coded models can leverage all the capabilities of the .NET framework. For a tour of the .NET framework, try this site.

Model Execution

UserModelBase provides several virtual methods that you override to tap into the backtesting process. The most widely used points of interaction are the Initialize method, which gets called once for each symbol in the backtest, and the Execute method, which gets called once for every bar of data in each of the backtest symbols.

public virtual void Initialize(BarHistory bars)

The backtester calls the model'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 model will need.

public abstract void Execute(BarHistory bars, int idx)

The backtester calls the model'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 model's primary logic.

public virtual void Cleanup(BarHistory bars)

The backtester calls the model'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.

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.

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.

public int StartIndex

You can set this property to something other than the default of 0 in the Initialize method if your backtest should begin at some index above 0. For example, if you are using an indicator with a period of 20, you can assign StartIndex to 20 to cause the backtester to begin iterating at index 20 instead of 0. In this case, the first time the backtester calls your Execute method, the idx parameter will have a value of 20.

public double CurrentCash

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

public double CurrentEquity

Returns the current equity level in the simulation. The backtest's equity level is initially determined by the "Starting Equity" that you established in "Model Settings". As your model executes bar by bar, and enters and exits positions, the equity level will rise and fall.

public BarHistory GetHistory(BarHistory synchWith, string symbol)

Lets you access data for another symbol from within your model. 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.

Parameter Related

The following methods and properties refer to how a model interacts with its model parameters. Model parameters let you define values in your model that can fluctuate between a minimum and maximum value, and can be optimized in QStudio.

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

Call this from within the model's constructor to add a parameter to the model.

public ParameterList Parameters

Returns a List<Parameter> containing the model's parameters. Model parameters should be added in the constructor, by calling the AddParameter method.

Trading Related

The following methods relate to placing simulated trades in a model.

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

Places a simulated trade. The Quantacula backtester will determine the number of shares based on the position size settings you established in the "Model 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 Buy, Sell, Short, or Cover.
  • For the "orderType" parameter, specify Market, Limit or Stop.
  • For limit and stop order, supply an order price in the "price" parameter. This parameter is optional.
  • 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 parameter is optional.
public void ClosePosition(Position pos, OrderType orderType, double price = 0)

Use this method to explicit close a position that you found via a call to FindOpenPosition.

Position Related

The following methods and properties provide access to the positions during a backtest. Some of these reference the NSF property of the Position class. If the NSF property is true, this means that the position was not included in the final backtest because the backtester did not have sufficient simulated capital to open it.

public Position FindOpenPosition(int positionTag)

Looks for an open position with the specified numeric "positionTag". Positions that were created as a result of passing a value in the PlaceTrade method's "positionTag" parameter can be found in this way.

public Position FindOpenPosition(PositionType pt)

Looks for an open position of the specified type, Long or Short.

public bool HasOpenPosition(BarHistory bh, PositionType pt)

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

public virtual List<Position> OpenPositions

Returns a list of the open positions for the BarHistory currently being processed. This includes positions that are marked NSF.

public List<Position> OpenPositionsAllSymbols

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

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

Returns the list of positions for the current symbol being processed.

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

Returns the list of positions for all symbols in the backtest.

Chart Rendering

The following methods can be used to render various shapes, lines, and annotations on the chart.

public void DrawBarAnnotation(string text, int bar, bool aboveBar, Color color, int fontSize)

Draws the specified text above or below the specified bar on the chart.

public void DrawEllipse(int startBar, double startValue, int endBar, double endValue, Color color, LineStyles lineStyle, string paneTag = "Price")

Draws an ellipse on the chart using the specified parameters, color, and style.

public void DrawHeaderText(string text, Color color, int fontSize)

Draws the specified text on the chart, under the upper left hand corner box that displays the symbol and price values.

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

Draws the specified Image on the chart, at the specified location.

public void DrawLine(int startBar, double startValue, int endBar, double endValue, Color color, LineStyles lineStyle, string paneTag = "Price")

Draws a line on the chart using the specified parameters, color, and style.

public void DrawPolygon(List<ChartPoint> pts, Color color, LineStyles lineStyle, string paneTag = "Price")

Draws a polygon based on the list of points in the "pts" parameter, using the specific color and style. The ChartPoint class contains 2 properties, an int "Index" and a double "Value" that represents a point on the chart.

public void DrawRectangle(int startBar, double startValue, int endBar, double endValue, Color color, LineStyles lineStyle, string paneTag = "Price")

Draws a rectangle on the chart using the specified parameters, color, and style.

public void DrawText(string text, int idx, double value, Color color, int fontSize, string paneTag = "Price")

Draws the specified text on the chart, at the specified location.

public void FillEllipse(int startBar, double startValue, int endBar, double endValue, Color color, string paneTag = "Price")

Fills an ellipse on the chart using the specified parameters, color, and style.

public void FillRectangle(int startBar, double startValue, int endBar, double endValue, Color color, string paneTag = "Price")

Fills a rectangle on the chart using the specified parameters, color, and style.

public void Plot(IndicatorBase ib)

Plots the specified indicator instance onto the chart, using a unique color, and the line plot style.

public void Plot(IndicatorBase ib, Color color, PlotStyles plotStyle = PlotStyles.Line)

Plots the specified indicator instance onto the chart, using a color that you specify. You can optionally specify a plot style here (Line, Histogram, Dots, ThickLine, ThickHistogram, Dotted, Dashed).

public void Plot(TimeSeries ts, string name, string paneTag = "Price")

Plots the specified TimeSeries instance onto the chart, using a unique color.

  • Provide a descriptive name for the data in the "name" parameter, this will be displayed at the top of the chart pane where the TimeSeries is plotted.
  • Optionally specify the "paneTag" of the chart pane that the TimeSeries should be plotted in. This can be "Price", "Volume", or some other unique string to plot in a different pane.
public void Plot(TimeSeries ts, string name, Color color, PlotStyles plotStyle, string paneTag)

As above, but allows you to also specify the color to plot.

public void Plot(BarHistory bars, Color color, string paneTag)

Plots another BarHistory on the chart, for example one obtained by a call to GetHistory. Specify the color and the name of the chart pane ("Price" for the price pane) to plot the history. The vertical axis of the pane will increase to accommodate the plot.

public void Plot(BarHistory bars, Color color)

Plots a BarHistory like above, but the history is plotted in the price pane, and is overlaid atop the existing vertical axis scale. The history values are transformed behind the scenes to plot in the existing scale of the price pane.

public void SetBackgroundColor(int bar, Color color, string paneTag = "Price")

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

public void SetBarColor(int bar, Color color)

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

Miscellaneous

public void WriteToDebugLog(string txt)

Writes a line of output to the Debug Log window. Quantacula Studio shows the Debug Log window automatically after your model runs, if you've called this method. You can also show the Debug Log window explicitly from the Tools menu.