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
Cash
Gets the most recent day's cash balance.
protected double Cash { get; }
Property Value
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
ClosedEquity
Gets the amount of equity not at risk.
protected double ClosedEquity { get; }
Property Value
ClosedPnL
Gets the P&L of all closed positions.
protected double ClosedPnL { get; }
Property Value
ClosedPositions
Gets a collection of all closed positions.
public PositionCollection ClosedPositions { get; }
Property Value
CoreEquity
Gets equity minus open risk.
protected double CoreEquity { get; }
Property Value
CurrentDate
Gets the current date being processed.
protected DateTime CurrentDate { get; }
Property Value
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
DataStore
Gets/sets the datastore that provides trade, risk, and pricing information.
public DataStoreBase DataStore { get; set; }
Property Value
EndDate
Gets/sets the end date of the simulation. Use DateTime.MaxValue to reset.
public DateTime EndDate { get; set; }
Property Value
Equity
Gets the prior day's equity value.
protected double Equity { get; }
Property Value
HasTrading
Returns true if there has been trading activity on the current date.
protected bool HasTrading { get; }
Property Value
LongMargin
The initial margin requirement for all open long positions.
protected double LongMargin { get; }
Property Value
LongRisk
Gets the total risk of all open long positions.
protected double LongRisk { get; }
Property Value
MarginCalls
Gets a collection of MarginCall objects.
protected MarginCallCollection MarginCalls { get; }
Property Value
Name
Gets or sets the name of the money manager.
public string Name { get; set; }
Property Value
NetInterest
Gets the most recent amount of net interest (debit + credit + short rebates).
protected double NetInterest { get; }
Property Value
OpenPnL
Gets the P&L of all open positions.
protected double OpenPnL { get; }
Property Value
OpenPositions
Gets a collection of all currently open positions.
public PositionCollection OpenPositions { get; }
Property Value
Options
Gets or sets various money manager options.
public MoneyManagerOptions Options { get; set; }
Property Value
PnL
Gets the cumulative P&L.
protected double PnL { get; }
Property Value
Results
Gets the results of the simulation.
public PerformanceStats Results { get; }
Property Value
Series
Gets a BarSeriesCollection that automatically synchronizes series with the current date.
public BarSeriesCollection Series { get; set; }
Property Value
ShortMargin
The initial margin requirement for all open short positions.
protected double ShortMargin { get; }
Property Value
ShortRisk
Gets the total risk of all open short positions.
protected double ShortRisk { get; }
Property Value
StartDate
Gets/sets the start date of the simulation. Use DateTime.MinValue to reset.
public DateTime StartDate { get; set; }
Property Value
StartupCash
Gets or sets the starting cash balance in base currency.
public double StartupCash { get; set; }
Property Value
TotalMargin
Gets the most recent aggregate net margin requirement.
protected double TotalMargin { get; }
Property Value
TotalRisk
Gets the total risk of all open positions.
protected double TotalRisk { get; }
Property Value
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
TransactionCosts
Gets/sets a transaction cost object which can be used to override transaction costs globally.
public TransactionCostModel TransactionCosts { get; set; }
Property Value
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
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
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
BuyClose(BarSeries, double)
Creates a new long position on the close for the specified BarSeries.
protected void BuyClose(BarSeries series, double quantity)
Parameters
BuyClose(Position, double)
Adds the specified quantity to a long position on the close.
protected void BuyClose(Position position, double quantity)
Parameters
BuyOpen(BarSeries, double)
Creates a new long position on the open for the specified BarSeries.
protected void BuyOpen(BarSeries series, double quantity)
Parameters
BuyOpen(Position, double)
Adds the specified quantity to a long position on the open.
protected void BuyOpen(Position position, double quantity)
Parameters
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
ConvertCashBalance(string, string, double)
Converts currency balances using the specified parameters.
protected void ConvertCashBalance(string fromCurrency, string toCurrency, double amount)
Parameters
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
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
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
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
GetAccountingRecords()
Gets a read-only collection of the daily accounting records.
public ReadOnlyCollection<AccountingRecord> GetAccountingRecords()
Returns
GetCashBalance(string)
Returns the up-to-date cash balance for the specified currency.
protected double GetCashBalance(string currency)
Parameters
currency
string
Returns
GetCashBalanceHistory()
Gets the timeseriescollection of cash balances. Used in money manager reporting.
public TimeSeriesCollection GetCashBalanceHistory()
Returns
GetCashBalances()
Returns an enumerable of all cash balances.
protected IEnumerable<CashBalance> GetCashBalances()
Returns
GetEquityCurve()
Returns a TimeSeries of the equity curve.
public TimeSeries GetEquityCurve()
Returns
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
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
stringA 3 character ISO code assuming the base currency as the quote, or a full 6 character code (e.g. EURUSD).
date
DateTime
Returns
GetGlobalVariables()
Returns the global variable dictionary.
protected VariableDictionary GetGlobalVariables()
Returns
GetInstruments()
Gets a dictionary of all the instruments referenced in the datastore.
protected InstrumentCollection GetInstruments()
Returns
GetLongPositions()
Gets a collection of all currently open long positions.
protected PositionCollection GetLongPositions()
Returns
GetMoneyManagerPositions()
Returns a collection of open positions that were generated by money management logic.
protected PositionCollection GetMoneyManagerPositions()
Returns
GetPositionsByCurrency(string)
Returns a collection of open positions that are denominated in the specified currency.
protected PositionCollection GetPositionsByCurrency(string currency)
Parameters
currency
string
Returns
GetPositionsByInstrument(Instrument)
Returns a collection of open positions that match the specified instrument.
protected PositionCollection GetPositionsByInstrument(Instrument instrument)
Parameters
instrument
Instrument
Returns
GetPositionsByInstrumentType(InstrumentType)
Returns a collection of open positions that match the specified instrument type.
protected PositionCollection GetPositionsByInstrumentType(InstrumentType kind)
Parameters
kind
InstrumentType
Returns
GetPositionsBySector(string)
Returns a collection of open positions for the specified sector.
protected PositionCollection GetPositionsBySector(string sectorName)
Parameters
sectorName
string
Returns
GetPositionsByStrategy(string)
Returns a collection of open positions that match the specified strategy.
protected PositionCollection GetPositionsByStrategy(string strategyName)
Parameters
strategyName
string
Returns
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
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
GetPricing(Position)
Returns the current bar for the specified position.
protected Bar GetPricing(Position position)
Parameters
position
Position
Returns
GetPricing(Position, DateTime)
Returns the current bar for the specified position.
protected virtual Bar GetPricing(Position position, DateTime date)
Parameters
Returns
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
GetRejectedTradeIds()
Returns the ids of trades that were canceled or rejected.
public IEnumerable<long> GetRejectedTradeIds()
Returns
GetRisk(Position, DateTime)
Gets the risk for a specified position on the specified date.
protected virtual double GetRisk(Position position, DateTime date)
Parameters
Returns
GetRiskByCurrency(string)
Returns the total open risk in base currency for the specified currency.
protected double GetRiskByCurrency(string currency)
Parameters
currency
string
Returns
GetRiskByInstrument(Instrument)
Returns the total open risk in base currency for the specified instrument.
protected double GetRiskByInstrument(Instrument instrument)
Parameters
instrument
Instrument
Returns
GetRiskBySector(string)
Returns the total open risk in base currency for the specified sector.
protected double GetRiskBySector(string sectorName)
Parameters
sectorName
string
Returns
GetRiskByStrategy(string)
Returns the total open risk in base currency for the specified strategy.
protected double GetRiskByStrategy(string strategyName)
Parameters
strategyName
string
Returns
GetRiskBySymbol(string)
Returns the total open risk in base currency for the specified symbol.
protected double GetRiskBySymbol(string symbol)
Parameters
symbol
string
Returns
GetShortPositions()
Gets a collection of all currently open short positions.
protected PositionCollection GetShortPositions()
Returns
GetSpreadPositions()
Returns a collection of open spread positions.
protected PositionCollection GetSpreadPositions()
Returns
GetStrategyNames()
Returns a collection of strategy names being tested.
public ReadOnlyCollection<string> GetStrategyNames()
Returns
GetStrategyVariables(string)
Returns the variable dictionary for the specified strategy.
protected VariableDictionary GetStrategyVariables(string strategyName)
Parameters
strategyName
string
Returns
GetSymbols()
Returns a read-only list of available symbols in the datastore.
protected ReadOnlyCollection<string> GetSymbols()
Returns
GetSymbolsTraded()
Returns a read-only list of symbols that have actually been traded to date during a simulation.
protected ReadOnlyCollection<string> GetSymbolsTraded()
Returns
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
Positionmultiplier
doubletif
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
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
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
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
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
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
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
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
TextWriterprogress
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
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
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
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
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
SellShortClose(BarSeries, double)
Estalishes a new short position on the close for the specified BarSeries.
protected void SellShortClose(BarSeries series, double quantity)
Parameters
SellShortClose(Position, double)
Adds the specified quantity to a short position on the close.
protected void SellShortClose(Position position, double quantity)
Parameters
SellShortOpen(BarSeries, double)
Establishes a new short position on the open for the specified BarSeries.
protected void SellShortOpen(BarSeries series, double quantity)
Parameters
SellShortOpen(Position, double)
Adds the specified quantity to a short position on the open.
protected void SellShortOpen(Position position, double quantity)
Parameters
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
Events
Message
Occurs when the money manager sends a status message.
public event EventHandler<MessageEventArgs> Message
Event Type
TradeRejected
Occurs when a trade is rejected.
public event EventHandler<TradeRejectedEventArgs> TradeRejected