TradeBuilder is a IAlgorithm member used to manage trades. It has a list of Trade object with the information you are looking for: MAE, MFE, Drawdown, etc... Trades are created based on a grouping method and a mathing method that are set with the TradeBuilder.
You can set the TradeBuilder using SetTradeBuilder(tradeBuilder), where tradeBuilder can be defined by:
tradeBuilder = TradeBuilder(fillGroupingMethod, fillMatchingMethod)
self.SetTradeBuilder(tradeBuilder)
We have three fill grouping methods and two fill mathing methods:
# A Trade is defined by a fill that establishes or increases a position and an offsetting fill that reduces the position size.
FillGroupingMethod.FillToFill
# A Trade is defined by a sequence of fills, from a flat position to a non-zero position which may increase or decrease in quantity, and back to a flat position.
FillGroupingMethod.FlatToFlat
# A Trade is defined by a sequence of fills, from a flat position to a non-zero position and an offsetting fill that reduces the position size.
FillGroupingMethod.FlatToReduced
# First In First Out fill matching method
FillMatchingMethod.FIFO
# Last In Last Out fill matching method
FillMatchingMethod.LIFO
If you want to Log the statistics at the end of the algorithm, you can use:
def OnEndOfAlgorithm(self):
for trade in self.TradeBuilder.ClosedTrades:
self.Log(self.trade_to_string(trade))
def trade_to_string(self, trade):
return 'Symbol: {0} EntryTime: {1} EntryPrice {2} Direction: {3} Quantity: {4} ExitTime: {5} ExitPrice: {6} ProfitLoss: {7} TotalFees: {8} MAE: {9} MFE: {10} EndTradeDrawdown: {11}'.format(
trade.Symbol,
trade.EntryTime,
trade.EntryPrice,
trade.Direction,
trade.Quantity,
trade.ExitTime,
trade.ExitPrice,
trade.ProfitLoss,
trade.TotalFees,
trade.MAE,
trade.MFE,
trade.EndTradeDrawdown)
StatisticsBuilder, on the other hand, is used at engine level to calculate portfolio statistics that are shown in the "Overall Statistics". Github issue #1105 proposes making running statistics, calculated by the StatisticsBuilder, available in the algorithm.