Algorithm Reference

Reality Modelling


Models can be used to improve the accuracy of your backtesting. We provide basic default models which assume you are trading on highly liquid assets, but if you are trading high volumes, or on low volume assets you should update these models to be more realistic.

All models are set on a per security basis. To set a model first fetch the security object and apply your model.

//Set IBM to have a constant $1 transaction fee. 
Securities["IBM"].FeeModel = new ConstantFeeTransactionModel(1); 

All models should be setup in your Initialize() method.

Brokerage Models

We provide a shortcut to set common models and properties relating to each of the brokerages we support. These brokerage models set fees, fill models, slippage models and trading markets for a brokerage. In addition they validate it is possible to submit trades to the brokerage (e.g. submitting equity trades to a forex only brokerage).

Brokerage models set:

  • Transaction fees.
  • Supported asset classes for the brokerage.
  • Validate orders types and settings.
  • Default account type (margin or cash account).
  • Support for extended market hours.
  • Default leverage for assets
  • Default settlement models

This gives you enormous control over your algorithm behavior and allow you to model virtually any brokerage in the world.

In addition to our default brokerage model ( DefaultBrokerageModel ), we provide brokerage models for Interactive Brokers ( InteractiveBrokersBrokerageModel ) , FXCM ( FxcmBrokerageModel ), OANDA ( OandaBrokerageModel ) and GDAXBrokerageModel ( GDAX ).

Brokerage models override any other models you may set for a security.

// Set brokerage model using helper methods:
SetBrokerageModel(BrokerageName.FxcmBrokerage); // Defaults to margin account
SetBrokerageModel(BrokerageName.GDAX, AccountType.Cash); //Or override account type

// Supported brokerage names:
// You can also create your own brokerage model: IBrokerageModel
class MyBrokerage: DefaultBrokerage {
   // Custom implementation of brokerage here.

SetBrokerageModel(new MyBrokerage());
# Set brokerage model using helper methods:
self.SetBrokerageModel(BrokerageName.FxcmBrokerage) # Defaults to margin account
self.SetBrokerageModel(BrokerageName.GDAX, \ 
                       AccountType.Cash) # Or override account type

# Supported brokerage names:

Transaction Fee Models

Transaction fee models set the fees for each order. We provide customized transaction models for all brokerages, but you can also set your own. Like all models they must be set on a security by security basis.

Transaction models implement the ISecurityTransactionModel interface. If you wish to implement your own transaction model you can start with the SecurityTransactionModel and override methods you wish to change.

// Set IBM to use a fixed $1.5 per trade fee model.
Securities["IBM"].FeeModel = new ConstantFeeTransactionModel(1.5);

// Set EURUSD to use FXCM's transaction fees:
Securities["EURUSD"].FeeModel = new FxcmTransactionModel();
# Set IBM to use a fixed $1.5 per trade fee model.
self.Securities["IBM"].FeeModel = ConstantFeeTransactionModel(1.5)

# Set EURUSD to use FXCM's transaction fees:
self.Securities["EURUSD"].FeeModel = new FxcmTransactionModel()
// Assigning securities custom fee models:
Securities["SPY"].SetFeeModel(new CustomFeeModel());

// Custom fee implementation
public class CustomFeeModel : IFeeModel {
    public decimal GetOrderFee(Security security, Order order) {
        return 1;
# Assigning securities custom fee models:

# Custom fee implementation
class CustomFeeModel:
    def GetOrderFee(self, security, order):
        return 1

Slippage Models

Slippage is the difference in price between your last reported quote and the real price the trade filled at. This difference can be positive or negative, as sometimes the price can slip in your favor. In volatile markets you are likely to experience more slippage.

Slippage models implement the ISlippageModel interface. We provide the VolumeShareSlippageModel for forex based securities, and the ConstantSlippageModel for Equities.

Advanced users may wish to implement their own volatility based slippage model - increasing the accuracy of your backtests in volatile markets.

// Assigning securities custom slippage models:
Securities["SPY"].SetSlippageModel(new CustomSlippageModel());

// Custom slippage implementation
public class CustomSlippageModel : ISlippageModel {
    public decimal GetSlippageApproximation(Security asset, Order order) {
        return 0.1m;
# Assigning securities custom slippage models:

# Custom slippage implementation
class CustomSlippageModel:
    def GetSlippageApproximation(self, asset, order):
        return 0.1

Fill Models

Fill models give you control over order fills. Each supported order type is passed through a dedicated method and returns an OrderEvent object. OrderEvents are used to carry information about order partial fills or errors.

The Fill Models implement the IFillModel interface. They have the following key methods:

public interface IFillModel {
    OrderEvent MarketFill(Security asset, MarketOrder order);
    OrderEvent StopMarketFill(Security asset, StopMarketOrder order);
    OrderEvent StopLimitFill(Security asset, StopLimitOrder order);
    OrderEvent LimitFill(Security asset, LimitOrder order);
    OrderEvent MarketOnOpenFill(Security asset, MarketOnOpenOrder order);
    OrderEvent MarketOnCloseFill(Security asset, MarketOnCloseOrder order);
We provide the ImmediateFillModel which assumes orders and immediately and completely filled.

// Set the fill models in initialize:
Securities["IBM"].SetFillModel(new PartialFillModel());

// Custom fill model implementation stub
public class PartialFillModel : ImmediateFillModel {
    public override OrderEvent MarketFill(Security asset, MarketOrder order) {
        //Override order event handler and return partial order fills,
# Set the fill models in initialize:

# Custom fill model implementation stub
class PartialFillModel(ImmediateFillModel):
    def MarketFill(self, asset, order):
        # Override order event handler and return partial order fills

Margin Models

Margin models control how much buying power (leverage) your algorithm has to make trades. Margin calculations can be very complex and depend on many factors including the brokerage or even time of day.

Margin models implement the IBuyingPowerModel interface and default to the SecurityMarginModel class. We also provide the PatternDayTradingMarginModel to model intraday pattern day trading for US equities which provides 4x intraday leverage and 2x overnight leverage.

// Example of setting a security to use PDT margin models:
// Generally you do not need to adjust margin models
Securities["AAPL"].MarginModel = new PatternDayTradingMarginModel();
# Example of setting a security to use PDT margin models:
# Generally you do not need to adjust margin models
self.Securities["AAPL"].MarginModel =  PatternDayTradingMarginModel()

The margin call model can be disabled by easily setting the model to Null at portfolio level.

// In Initialize()
Portfolio.MarginCallModel = MarginCallModel.Null;
#In Initialize()
self.Portfolio.MarginCallModel = MarginCallModel.Null

Settlement Models

After a trade is made brokerages settle the cash depending on the markets and account type. This is managed by our Settlement Models. The most common settlement type is immediate - where the funds are available for trading immediately. This is handled by the ImmediateSettlementModel. US Equities trading with cash accounts is typically settled 3 days after the transaction occurred. This is managed by the DelayedSettlementModel.

Settlement models implement the ISettlementModel interface. You can create your own settlement model by implementing this method. Most users will not need to create their own settlement model and can use one of the ones provided above.

// Set a security to a delayed settlement model: settle 7 days later, at 8am.
Securities["IBM"].SettlementModel = new DelayedSettlementModel(7, new TimeSpan(8, 0, 0));
# Set a security to a delayed settlement model: settle 7 days later, at 8am.
self.Securities["IBM"].SettlementModel =  DelayedSettlementModel(7, timedelta(hours = 8))

Portfolio Models

Portfolio models control how order fills are applied to your portfolio. They take an OrderEvent, Security and SecurityPortfolioManager object and update the holdings to reflect the new final position. You should only need to update your portfolio model when you are create a new asset type.

Portfolio models implement the ISecurityPortfolioModel interface.

Volatility Model

The volatility model is a property of a security. Exactly how volatility is calculated varies a lot between strategies so we've provided an override point here. Volatility models get updated with data each time step and are expected to be updated immediately. This is primarily required for options backtesting.

Volatility models implement the VolatilityModel interface. We default to the NullVolatilityModel which returns 0 volatility at all times. As a helper we also provide the RelativeStandardDeviationVolatilityModel which calculates the volatility based on standard deviation.

You can also see our Tutorials and Videos. You can also get in touch with us via Chat.

Did you find this page Helpful ?