Table of Contents

Class MoneyManager

Namespace
Balsam.MoneyManagement
Assembly
Balsam.Backtester.dll

An abstract base class for implementing position sizing and portfolio construction logic.

public abstract class MoneyManager
Inheritance
MoneyManager
Derived
Inherited Members
Extension Methods

Constructors

MoneyManager()

Initializes a new money manager object.

protected MoneyManager()

Properties

CanIssueMoneyManagerTrades

Returns true if the money manager is in a state where money manager trades can be generated.

protected bool CanIssueMoneyManagerTrades { get; }

Property Value

bool

Cash

Gets the most recent day's cash balance.

protected double Cash { get; }

Property Value

double

ChangeToday

The P&L today. Useful for position sizing in reversal systems. Prior to OnMarketClosing(), ChangeToday reflects the day's P&L only for positions closed that day; however, for OnMarketClosing(), it is updated to include the change in P&L for open positions as well.

protected double ChangeToday { get; }

Property Value

double

ClosedEquity

Gets the amount of equity not at risk.

protected double ClosedEquity { get; }

Property Value

double

ClosedPnL

Gets the P&L of all closed positions.

protected double ClosedPnL { get; }

Property Value

double

ClosedPositions

Gets a collection of all closed positions.

public PositionCollection ClosedPositions { get; }

Property Value

PositionCollection

CoreEquity

Gets equity minus open risk.

protected double CoreEquity { get; }

Property Value

double

CurrentDate

Gets the current date being processed.

protected DateTime CurrentDate { get; }

Property Value

DateTime

CurrentPosition

Returns the current position if only one open position or the last opened position for multiple positions or null if there are no open positions.

protected Position CurrentPosition { get; }

Property Value

Position

DataStore

Gets/sets the datastore that provides trade, risk, and pricing information.

public DataStoreBase DataStore { get; set; }

Property Value

DataStoreBase

EndDate

Gets/sets the end date of the simulation. Use DateTime.MaxValue to reset.

public DateTime EndDate { get; set; }

Property Value

DateTime

Equity

Gets the prior day's equity value.

protected double Equity { get; }

Property Value

double

HasTrading

Returns true if there has been trading activity on the current date.

protected bool HasTrading { get; }

Property Value

bool

LongMargin

The initial margin requirement for all open long positions.

protected double LongMargin { get; }

Property Value

double

LongRisk

Gets the total risk of all open long positions.

protected double LongRisk { get; }

Property Value

double

MarginCalls

Gets a collection of MarginCall objects.

protected MarginCallCollection MarginCalls { get; }

Property Value

MarginCallCollection

Name

Gets or sets the name of the money manager.

public string Name { get; set; }

Property Value

string

NetInterest

Gets the most recent amount of net interest (debit + credit + short rebates).

protected double NetInterest { get; }

Property Value

double

OpenPnL

Gets the P&L of all open positions.

protected double OpenPnL { get; }

Property Value

double

OpenPositions

Gets a collection of all currently open positions.

public PositionCollection OpenPositions { get; }

Property Value

PositionCollection

Options

Gets or sets various money manager options.

public MoneyManagerOptions Options { get; set; }

Property Value

MoneyManagerOptions

PnL

Gets the cumulative P&L.

protected double PnL { get; }

Property Value

double

Results

Gets the results of the simulation.

public PerformanceStats Results { get; }

Property Value

PerformanceStats

Series

Gets a BarSeriesCollection that automatically synchronizes series with the current date.

public BarSeriesCollection Series { get; set; }

Property Value

BarSeriesCollection

ShortMargin

The initial margin requirement for all open short positions.

protected double ShortMargin { get; }

Property Value

double

ShortRisk

Gets the total risk of all open short positions.

protected double ShortRisk { get; }

Property Value

double

StartDate

Gets/sets the start date of the simulation. Use DateTime.MinValue to reset.

public DateTime StartDate { get; set; }

Property Value

DateTime

StartupCash

Gets or sets the starting cash balance in base currency.

public double StartupCash { get; set; }

Property Value

double

TotalMargin

Gets the most recent aggregate net margin requirement.

protected double TotalMargin { get; }

Property Value

double

TotalRisk

Gets the total risk of all open positions.

protected double TotalRisk { get; }

Property Value

double

TradeFilter

Gets/sets a function used to filter opening trades. Only trades with a value of true will be included.

public Func<Trade, bool> TradeFilter { get; set; }

Property Value

Func<Trade, bool>

TransactionCosts

Gets/sets a transaction cost object which can be used to override transaction costs globally.

public TransactionCostModel TransactionCosts { get; set; }

Property Value

TransactionCostModel

Methods

AddDividend(Dividend)

Adds the specified dividend to the cash balance. This amount will be included in the day's return.

protected void AddDividend(Dividend dividend)

Parameters

dividend Dividend

AdjustCash(double)

Debits or credits the base currency cash balance. This amount will be included as part of the day's return.

protected void AdjustCash(double amount)

Parameters

amount double

AdjustCash(double, string)

Debits or credits the cash balance for the specified currenty and amount. This will be included in the day's return.

protected void AdjustCash(double amount, string currency)

Parameters

amount double
currency string

Buy(BarSeries, double, double)

Creates a new long position for the specified BarSeries using the specified price, quantity, and order instructions.

protected void Buy(BarSeries series, double quantity, double price)

Parameters

series BarSeries
quantity double
price double

Buy(Position, double, double)

Adds to a long position using the specified price, quantity, and order instructions.

protected void Buy(Position position, double quantity, double price)

Parameters

position Position
quantity double
price double

BuyClose(BarSeries, double)

Creates a new long position on the close for the specified BarSeries.

protected void BuyClose(BarSeries series, double quantity)

Parameters

series BarSeries
quantity double

BuyClose(Position, double)

Adds the specified quantity to a long position on the close.

protected void BuyClose(Position position, double quantity)

Parameters

position Position
quantity double

BuyOpen(BarSeries, double)

Creates a new long position on the open for the specified BarSeries.

protected void BuyOpen(BarSeries series, double quantity)

Parameters

series BarSeries
quantity double

BuyOpen(Position, double)

Adds the specified quantity to a long position on the open.

protected void BuyOpen(Position position, double quantity)

Parameters

position Position
quantity double

Clear()

Clears all positions and calculated statistics. Called internally before every simulation.

public void Clear()

ConvertCashBalance(CashBalance)

Converts the specified balance to base currency.

protected void ConvertCashBalance(CashBalance balance)

Parameters

balance CashBalance

ConvertCashBalance(string)

Converts the entire balance of the specified currency to the base currency.

protected void ConvertCashBalance(string currency)

Parameters

currency string

ConvertCashBalance(string, double)

Converts the specified currency balance to the base currency.

protected void ConvertCashBalance(string currency, double amount)

Parameters

currency string
amount double

ConvertCashBalance(string, string, double)

Converts currency balances using the specified parameters.

protected void ConvertCashBalance(string fromCurrency, string toCurrency, double amount)

Parameters

fromCurrency string
toCurrency string
amount double

Cover(Position, double, double)

Reduces a short position using the specified quantity, price, and order instruction.

protected void Cover(Position position, double quantity, double price)

Parameters

position Position
quantity double
price double

CoverClose(Position)

Covers the specified short position on the close.

protected void CoverClose(Position position)

Parameters

position Position

CoverClose(Position, double)

Reduces a short position by the specified quantity on the close.

protected void CoverClose(Position position, double quantity)

Parameters

position Position
quantity double

CoverOpen(Position)

Covers the specified short position on the open.

protected void CoverOpen(Position position)

Parameters

position Position

CoverOpen(Position, double)

Reduces a short position by the specified quantity on the open.

protected void CoverOpen(Position position, double quantity)

Parameters

position Position
quantity double

ExitOnClose(Position)

Exits a position on the close. A convenience method instead of having to determine side before calling SellClose or CoverClose.

protected void ExitOnClose(Position position)

Parameters

position Position

ExitOnClose(Position, double)

Exits the specified quantity on the close.

protected void ExitOnClose(Position position, double quantity)

Parameters

position Position
quantity double

GetAccountingRecords()

Gets a read-only collection of the daily accounting records.

public ReadOnlyCollection<AccountingRecord> GetAccountingRecords()

Returns

ReadOnlyCollection<AccountingRecord>

GetCashBalance(string)

Returns the up-to-date cash balance for the specified currency.

protected double GetCashBalance(string currency)

Parameters

currency string

Returns

double

GetCashBalanceHistory()

Gets the timeseriescollection of cash balances. Used in money manager reporting.

public TimeSeriesCollection GetCashBalanceHistory()

Returns

TimeSeriesCollection

GetCashBalances()

Returns an enumerable of all cash balances.

protected IEnumerable<CashBalance> GetCashBalances()

Returns

IEnumerable<CashBalance>

GetEquityCurve()

Returns a TimeSeries of the equity curve.

public TimeSeries GetEquityCurve()

Returns

TimeSeries

GetFXRate(string)

Gets the current FX rate needed to convert the specified currency into the base currency.

protected double GetFXRate(string currencyCode)

Parameters

currencyCode string

Returns

double

GetFXRate(string, DateTime)

Gets the FX rate for the specified currency and date needed to convert to the base currency.

protected virtual double GetFXRate(string currencyCode, DateTime date)

Parameters

currencyCode string

A 3 character ISO code assuming the base currency as the quote, or a full 6 character code (e.g. EURUSD).

date DateTime

Returns

double

GetGlobalVariables()

Returns the global variable dictionary.

protected VariableDictionary GetGlobalVariables()

Returns

VariableDictionary

GetInstruments()

Gets a dictionary of all the instruments referenced in the datastore.

protected InstrumentCollection GetInstruments()

Returns

InstrumentCollection

GetLongPositions()

Gets a collection of all currently open long positions.

protected PositionCollection GetLongPositions()

Returns

PositionCollection

GetMoneyManagerPositions()

Returns a collection of open positions that were generated by money management logic.

protected PositionCollection GetMoneyManagerPositions()

Returns

PositionCollection

GetPositionsByCurrency(string)

Returns a collection of open positions that are denominated in the specified currency.

protected PositionCollection GetPositionsByCurrency(string currency)

Parameters

currency string

Returns

PositionCollection

GetPositionsByInstrument(Instrument)

Returns a collection of open positions that match the specified instrument.

protected PositionCollection GetPositionsByInstrument(Instrument instrument)

Parameters

instrument Instrument

Returns

PositionCollection

GetPositionsByInstrumentType(InstrumentType)

Returns a collection of open positions that match the specified instrument type.

protected PositionCollection GetPositionsByInstrumentType(InstrumentType kind)

Parameters

kind InstrumentType

Returns

PositionCollection

GetPositionsBySector(string)

Returns a collection of open positions for the specified sector.

protected PositionCollection GetPositionsBySector(string sectorName)

Parameters

sectorName string

Returns

PositionCollection

GetPositionsByStrategy(string)

Returns a collection of open positions that match the specified strategy.

protected PositionCollection GetPositionsByStrategy(string strategyName)

Parameters

strategyName string

Returns

PositionCollection

GetPositionsBySymbol(params string[])

Returns a collection of open positions that match the specified symbol(s).

protected PositionCollection GetPositionsBySymbol(params string[] symbol)

Parameters

symbol string[]

Returns

PositionCollection

GetPricing(BarSeries)

Returns a bar for the current date of the specified series or null if the date is not found.

protected Bar GetPricing(BarSeries series)

Parameters

series BarSeries

Returns

Bar

GetPricing(Position)

Returns the current bar for the specified position.

protected Bar GetPricing(Position position)

Parameters

position Position

Returns

Bar

GetPricing(Position, DateTime)

Returns the current bar for the specified position.

protected virtual Bar GetPricing(Position position, DateTime date)

Parameters

position Position
date DateTime

Returns

Bar

GetPricing(string)

Returns the current bar for the specified symbol if found in the Series collection.

protected Bar GetPricing(string symbol)

Parameters

symbol string

Returns

Bar

GetRejectedTradeIds()

Returns the ids of trades that were canceled or rejected.

public IEnumerable<long> GetRejectedTradeIds()

Returns

IEnumerable<long>

GetRisk(Position, DateTime)

Gets the risk for a specified position on the specified date.

protected virtual double GetRisk(Position position, DateTime date)

Parameters

position Position
date DateTime

Returns

double

GetRiskByCurrency(string)

Returns the total open risk in base currency for the specified currency.

protected double GetRiskByCurrency(string currency)

Parameters

currency string

Returns

double

GetRiskByInstrument(Instrument)

Returns the total open risk in base currency for the specified instrument.

protected double GetRiskByInstrument(Instrument instrument)

Parameters

instrument Instrument

Returns

double

GetRiskBySector(string)

Returns the total open risk in base currency for the specified sector.

protected double GetRiskBySector(string sectorName)

Parameters

sectorName string

Returns

double

GetRiskByStrategy(string)

Returns the total open risk in base currency for the specified strategy.

protected double GetRiskByStrategy(string strategyName)

Parameters

strategyName string

Returns

double

GetRiskBySymbol(string)

Returns the total open risk in base currency for the specified symbol.

protected double GetRiskBySymbol(string symbol)

Parameters

symbol string

Returns

double

GetShortPositions()

Gets a collection of all currently open short positions.

protected PositionCollection GetShortPositions()

Returns

PositionCollection

GetSpreadPositions()

Returns a collection of open spread positions.

protected PositionCollection GetSpreadPositions()

Returns

PositionCollection

GetStrategyNames()

Returns a collection of strategy names being tested.

public ReadOnlyCollection<string> GetStrategyNames()

Returns

ReadOnlyCollection<string>

GetStrategyVariables(string)

Returns the variable dictionary for the specified strategy.

protected VariableDictionary GetStrategyVariables(string strategyName)

Parameters

strategyName string

Returns

VariableDictionary

GetSymbols()

Returns a read-only list of available symbols in the datastore.

protected ReadOnlyCollection<string> GetSymbols()

Returns

ReadOnlyCollection<string>

GetSymbolsTraded()

Returns a read-only list of symbols that have actually been traded to date during a simulation.

protected ReadOnlyCollection<string> GetSymbolsTraded()

Returns

ReadOnlyCollection<string>

Multiplier(Position, double, TimeInForce)

Executes a multiplier trade using the specified multiplier value and order instruction.

protected void Multiplier(Position position, double multiplier, TimeInForce tif)

Parameters

position Position
multiplier double
tif TimeInForce

MultiplierClose(Position, double)

Executes a multiplier trade on the close to increase or decrease the size of the specified position.

protected void MultiplierClose(Position position, double multiplier)

Parameters

position Position
multiplier double

MultiplierOpen(Position, double)

Exexcutes a multiplier trade on the open to increase or decrease the size of the specified position.

protected void MultiplierOpen(Position position, double multiplier)

Parameters

position Position
multiplier double

OnEntry(Trade)

Called for each opening trade in the database. Set the trade.Quantity property to size positions.

protected abstract void OnEntry(Trade trade)

Parameters

trade Trade

OnExit(Trade, Position)

Called for every closing trade. Position will be null for entries that were rejected; however, OnExit is still called to facilitate money management schemes that use a voting or ensemble method and need to keep track of net number of open/closed positions.

protected virtual void OnExit(Trade trade, Position position)

Parameters

trade Trade
position Position

OnMarginCall(MarginCall)

Called when a margin call is issued.

protected virtual void OnMarginCall(MarginCall marginCall)

Parameters

marginCall MarginCall

OnMarketClosed()

Called after trading has ceased for the day.

protected virtual void OnMarketClosed()

OnMarketClosing()

Called after pricing, risk and margin calculations have been updated. Money manager trades can be submitted from here.

protected virtual void OnMarketClosing()

OnMarketOpened()

Called after the market has opened but before any trades have been processed for the day.

protected virtual void OnMarketOpened()

OnMarketOpening(ReadOnlyCollection<Trade>)

Called before the market opens and trades passed to OnEntry. The list of trades can be sorted here.

protected virtual void OnMarketOpening(ReadOnlyCollection<Trade> trades)

Parameters

trades ReadOnlyCollection<Trade>

OnMessage(MessageEventArgs)

Raises a message event and outputs message to console.

protected virtual void OnMessage(MessageEventArgs e)

Parameters

e MessageEventArgs

OnMoneyManagerTrade(Trade)

Called after a trade is created and submitted from within the Money Management strategy. Use this to set commission, slippage, etc.

protected virtual void OnMoneyManagerTrade(Trade trade)

Parameters

trade Trade

OnMultiplier(Trade, Position)

Called for each multiplier trade.

protected virtual void OnMultiplier(Trade trade, Position position)

Parameters

trade Trade
position Position

OnPositionChanged(Position)

Called when a position is changed due to a mutliplier or money manager generated trade.

protected virtual void OnPositionChanged(Position position)

Parameters

position Position

OnPositionChanging(Position)

Called when a multiplier or money manager generated trade changes an existing position.

protected virtual void OnPositionChanging(Position position)

Parameters

position Position

OnPositionClosed(Position)

Called after a position is closed.

protected virtual void OnPositionClosed(Position position)

Parameters

position Position

OnPositionClosing(Position)

Called before a position is closed.

protected virtual void OnPositionClosing(Position position)

Parameters

position Position

OnPositionOpened(Position)

Called after a position has been opened.

protected virtual void OnPositionOpened(Position position)

Parameters

position Position

OnPositionOpening(Position)

Called as a position is being opened but before it has been added to the open positions collection.

protected virtual void OnPositionOpening(Position position)

Parameters

position Position

OnRoll(Roll, Position)

Called for every roll trade.

protected virtual void OnRoll(Roll roll, Position position)

Parameters

roll Roll
position Position

OnSeriesAdded(BarSeries)

Called when an item is added to Series.

protected virtual void OnSeriesAdded(BarSeries series)

Parameters

series BarSeries

OnStrategyStart()

Called when the simulation is started. A good place to put any intializiation logic if required.

protected virtual void OnStrategyStart()

OnStrategyStop()

Called after the simulation has been run. A good place for any clean-up or export code.

protected virtual void OnStrategyStop()

OnTradeRejected(TradeRejectedEventArgs)

Called when a trade is rejected.

protected virtual void OnTradeRejected(TradeRejectedEventArgs e)

Parameters

e TradeRejectedEventArgs

OnTradeSubmitting(Trade)

Called before a trade is submitted for processing.

protected virtual void OnTradeSubmitting(Trade trade)

Parameters

trade Trade

RunSimulation()

Runs a simulation.

public void RunSimulation()

RunSimulation(TextWriter, IProgress<Tuple<DateTime, double>>, CancellationToken)

Runs a simulation using the specified parameters. This is typically called by optimizers or remote simulations.

public void RunSimulation(TextWriter output, IProgress<Tuple<DateTime, double>> progress, CancellationToken token)

Parameters

output TextWriter
progress IProgress<Tuple<DateTime, double>>
token CancellationToken

Sell(Position, double, double)

Reduces a long position using the specified quantity, price, and order instruction.

protected void Sell(Position position, double quantity, double price)

Parameters

position Position
quantity double
price double

SellClose(Position)

Exits the specified long position on the close.

protected void SellClose(Position position)

Parameters

position Position

SellClose(Position, double)

Reduces a long position by the specified quantity on the close.

protected void SellClose(Position position, double quantity)

Parameters

position Position
quantity double

SellOpen(Position)

Sells the specified long position on the open.

protected void SellOpen(Position position)

Parameters

position Position

SellOpen(Position, double)

Reduces a long position on the open by the specified quantity.

protected void SellOpen(Position position, double quantity)

Parameters

position Position
quantity double

SellShort(BarSeries, double, double)

Establishes a new short position using the specified quantity, price, and order instruction.

protected void SellShort(BarSeries series, double quantity, double price)

Parameters

series BarSeries
quantity double
price double

SellShort(Position, double, double)

Adds to a short position using the specified quantity, price, and order instruction.

protected void SellShort(Position position, double quantity, double price)

Parameters

position Position
quantity double
price double

SellShortClose(BarSeries, double)

Estalishes a new short position on the close for the specified BarSeries.

protected void SellShortClose(BarSeries series, double quantity)

Parameters

series BarSeries
quantity double

SellShortClose(Position, double)

Adds the specified quantity to a short position on the close.

protected void SellShortClose(Position position, double quantity)

Parameters

position Position
quantity double

SellShortOpen(BarSeries, double)

Establishes a new short position on the open for the specified BarSeries.

protected void SellShortOpen(BarSeries series, double quantity)

Parameters

series BarSeries
quantity double

SellShortOpen(Position, double)

Adds the specified quantity to a short position on the open.

protected void SellShortOpen(Position position, double quantity)

Parameters

position Position
quantity double

SetUserRisk(double)

This value will be reported in the Equity Detail tab of the Money Manager report.

protected void SetUserRisk(double risk)

Parameters

risk double

SubmitTrade(Trade)

Submits a trade for processing.

protected void SubmitTrade(Trade trade)

Parameters

trade Trade

ToString()

Returns the name of the money management strategy.

public override string ToString()

Returns

string

Events

Message

Occurs when the money manager sends a status message.

public event EventHandler<MessageEventArgs> Message

Event Type

EventHandler<MessageEventArgs>

TradeRejected

Occurs when a trade is rejected.

public event EventHandler<TradeRejectedEventArgs> TradeRejected

Event Type

EventHandler<TradeRejectedEventArgs>