Your interactive trading laboratory!
 • 
6 users online

Quantacula Help

How-To
C# API Reference
Extensions
Development Blog
API-Extensions

QCommunity Extensions
The open-source GitHub repository of source code for the QCommunity Extensions library. Contains indicators and other extensions submitted by the Quantacula Community. Look for QCommunity indicators when you create a Building Block model, mark the "QCommunity" library check box to expose them.

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
Published by Q Glitch on 9/28/2018

Quantacula uses the Microsoft .NET Framework as the basis of its C# Coded Models. A Model is a .NET class derived from the UserModelBase base class. You override virtual methods in UserModelBase to plug into different phases 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 this framework. For a tour of the .NET Framework, we recommend 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.

Initialize

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.

Execute

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.

Cleanup

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.

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.

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 model'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 model 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.

CurrentCash

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.

CurrentEquity

public double CurrentEquity

Returns the current equity level in the simulation. This 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.

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.

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.

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.

GetHistory

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.

AddParameter

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. The method returns an instance of the Parameter class that represents the parameter you added.

Parameters

public ParameterList Parameters

Returns a List containing the model's parameters, all instances of the Parameter class. 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.

PlaceTrade

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

Places a simulated order, and returns an instance of the Transaction class the represents it. 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. The method returns an instance of the Transaction class that represents the transaction.

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

ClosePosition

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

Use this method to explicitly close a Position object (pos). Specify the orderType (OrderType.Market, OrderType.Limit or OrderType.Stop) to use to close the position. If you use a limit or stop order, specify the order price in the price parameter.

CloseAtTrailingStop

public void CloseAtTrailingStop(Position pos, TrailingStopTypes tst, double amount)

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 or point based 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 or point value.

Position Related

When buys and shorts are executed and filled by the backtester, this results in Position objects. 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.

FindOpenPosition

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, PositionType.Long or PositionType.Short.

FindOpenPositionAllSymbols

public Position FindOpenPositionAllSymbols(int positionTag)

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 model 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 model calls FindOpenPositionAllSymbols to locate the position in this bond ETF that it had opened previously, and closes it.

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.

LastPosition

public virtual Position LastPosition

Return the most recently created open Position object, or null if there are no open Positions currently.

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 model processing, but this can be handy for certain summary processing you might perform during the BacktestComplete method.

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.

Chart Rendering

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

DrawBarAnnotation

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.

DrawEllipse

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.

DrawHeaderText

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.

DrawImage

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

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

DrawLine

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.

DrawPolygon

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 represents a point on the chart. It contains 2 properties; an int Index and a double Value.

DrawRectangle

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.

DrawText

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.

FillEllipse

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.

FillRectangle

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.

Plot

public void Plot(IndicatorBase ib);public void Plot(IndicatorBase ib, Color color, PlotStyles plotStyle = PlotStyles.Line);public void Plot(TimeSeries ts, string name, string paneTag = "Price");public void Plot(TimeSeries ts, string name, Color color, PlotStyles plotStyle, string paneTag);public void Plot(BarHistory bars, Color color, string paneTag)

The Plot method has been deprecated as of QStudio Q164. For cleaner and more understandable code, use the following methods instead:

  1. PlotIndicator
  2. PlotTimeSeries
  3. PlotBarHistory

There are several overloads of the Plot method, two for plotting indicators, two for plotting vanilla TimeSeries instances, and two for plotting BarHistory instances.

The Plot methods contain a plotStyle parameter that specified how to plot the data. It is a member of the PlotStyles enum.

Some methods include a paneTag parameter, a string which specifies which chart pane to plot the data. You can pass "Price" for the price pane, "Volume" for the volume pane, or a unique string to plot the data in its own pane.

The overloads the plot a TimeSeries require a name parameter. Provide a descriptive label for the data that will be displayed at the top of the chart pane where the data is plotted.

There are two overloads for plotting a secondary BarHistory instance, for example, one returned via a call to GetHistory. In the first overload you specify a paneTag. The vertical axis of the pane will increase to accommodate the BarHistory instance. In the second overload, 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 without disrupting it.

PlotIndicator

public virtual void PlotIndicator(IndicatorBase ib, Color color = default(Color), PlotStyles plotStyle = PlotStyles.Line)

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

The color parameter is optional. If not specified Quantacula will use the indicator's default color.

The plotStyle parameter is optional, and is a member of the PlotStyles enum. If not specified, Quantacula uses the indicator's default plot style.

PlotTimeSeries

public void PlotTimeSeries(TimeSeries ts, string name, string paneTag, Color color = default(Color), PlotStyles plotStyle = PlotStyles.Line)

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, Quantacula will use a default color.

The plotStyle parameter is also optional, and is a member of the PlotStyles enum. If not specified, Quantacula will use PlotStyles.Line.

PlotBarHistory

public void PlotBarHistory(BarHistory bh, string paneTag, Color color = default(Color), 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, Quantacula 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.

SetBackgroundColor

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.

SetBarColor

public void SetBarColor(int bar, Color color)

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

Miscellaneous

WriteToDebugLog

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.

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.