backtrader.trade module¶
Trade Module - Position and trade tracking.
This module provides the Trade class for tracking the lifecycle of trades including size, price, commission, and profit/loss calculations.
- Key Classes:
Trade: Tracks the life of a trade from opening to closing. TradeHistory: Records status and event updates for each trade.
A trade starts at 0, can be increased (adding to position) or reduced (closing part of position), and is considered closed when size returns to 0. Trades can be long (positive size) or short (negative size).
Example
Accessing trade information: >>> trade.status # Created, Open, or Closed >>> trade.pnl # Current profit/loss >>> trade.pnlcomm # PnL minus commission
- class backtrader.trade.TradeHistory[source]¶
Bases:
AutoOrderedDictRepresents the status and update event for each update a Trade has
This object is a dictionary which allows ‘.’ notation # This class saves the status and event updates for each trade .. attribute:: -
statusHolds the resulting status of an update event and has the following sub-attributes # Status, dict format, accessible via ‘.’, used to save the status of an update event, with the following sub-attributes -
status(int): Trade status# Trade status, integer format
dt(float): float coded datetime# Time, string format
barlen(int): number of bars the trade has been active# Number of bars when trade was generated
size(int): current size of the Trade# Current size of the trade, in integer format. In actual trading, non-integer trade sizes may be used
price(float): current price of the Trade# Current price of the trade
value(float): current monetary value of the Trade# Current monetary value of the trade
pnl(float): current profit and loss of the Trade# Current profit and loss of the trade
pnlcomm(float): current profit and loss minus commission# Current net profit and loss of the trade
- type:
dictwith ‘.’ notation
- - ``event``
Holds the event update - parameters # Event attributes, saves event update parameters -
order(object): the order which initiated the``update``# Order that generated the trade
size(int): size of the update# Size of the update
price(float):price of the update# Price of the update
commission(float): price of the update# Commission of the update
- Type:
dictwith ‘.’ notation
- class backtrader.trade.Trade[source]¶
Bases:
objectKeeps track the life of an trade: size, price, commission (and value?)
A trade starts at 0 can be increased and reduced and can be considered closed if it goes back to 0.
The trade can be long (positive size) or short (negative size)
A trade is not meant to be reversed (no support in the logic for it) # Track the life of a trade: size, price, commission (and value?) # A trade starts at 0, can be increased and reduced, and is considered closed when it returns to 0 # A trade can be long (positive size) or short (negative size) # A trade cannot reverse from long to short or short to long, such logic is not supported
Member Attributes:
ref: unique trade identifier # Trade identifierstatus(int): one of Created, Open, Closed # Trade statustradeid: grouping tradeid passed to orders during creation The default in orders is 0 # Trade id passed to orders during creation, default value in orders is 0size(int): current size of the trade # Current size of the tradeprice(float): current price of the trade # Current price of the tradevalue(float): current value of the trade # Current market value of the tradecommission(float): current accumulated commission # Current accumulated commissionpnl(float): current profit and loss of the trade (gross pnl) # Current profit and losspnlcomm(float): current profit and loss of the trade minus commission (net pnl) # Current net profit and loss after deducting commissionisclosed(bool): records if the last update closed (set size to null the trade # Whether the last update event closed this trade, if closed, set size to nullisopen(bool): records if any update has opened the trade # Whether the trade has been openedjustopened(bool): if the trade was just opened # Whether the trade was just openedbaropen(int): bar in which this trade was opened # Record which bar opened the positiondtopen(float): float coded datetime in which the trade was opened # Record the time when the trade was opened, can use open_datetime or num2date to get Python format time - Use methodopen_datetimeto get a Python datetime.datetimeor use the platform provided
num2datemethodbarclose(int): bar in which this trade was closed # Which bar the trade ended ondtclose(float): float coded datetime in which the trade was closed - Use methodclose_datetimeto get a Python datetime.datetimeor use the platform provided
num2datemethod# Record the time when the trade was closed, can use close_datetime or num2date to get Python format time
barlen(int): number of bars this trade was open # Number of bars when trade was openhistoryon(bool): whether history has to be recorded # Whether to record historical trade update eventshistory(list): holds a list updated with each “update” event containing the resulting status and parameters used in the update The first entry in the history is the Opening Event The last entry in the history is the Closing Event # Use a list to save past trade events and status, first is opening event, last is closing event
- refbasis = count(1)¶
- status_names = ['Created', 'Open', 'Closed']¶
- Created = 0¶
- Open = 1¶
- Closed = 2¶
- __init__(data=None, tradeid=0, historyon=False, size=0, price=0.0, value=0.0, commission=0.0)[source]¶
Initialize a Trade object.
- Parameters:
data – Data source associated with this trade.
tradeid – Unique identifier for the trade.
historyon – Whether to record trade history.
size – Initial position size.
price – Initial price.
value – Initial value.
commission – Initial commission.
- __nonzero__()¶
Trade size is not 0
- open_datetime(tz=None, naive=True)[source]¶
Returns a datetime.datetime object with the datetime in which the trade was opened
- close_datetime(tz=None, naive=True)[source]¶
Returns a datetime.datetime object with the datetime in which the trade was closed
- update(order, size, price, value, commission, pnl, comminfo)[source]¶
Updates the current trade. The logic does not check if the trade is reversed, which is not conceptually supported by the object.
If an update sets the size attribute to 0, “closed” will be set to true
Updates may be received twice for each order, once for the existing size which has been closed (sell undoing a buy) and a second time for the the opening part (sell reversing a buy) # Update current trade. Logic doesn’t check if trade is reversed, not conceptually supported :param order: the order object which has (completely or partially)
generated this updatede
- Parameters:
update (# Order that caused trade)
size (int) – amount to update the order if size has the same sign as the current trade a position increase will happen if size has the opposite sign as current op size a reduction/close will happen
trade (# Commission generated by new)
trade
trade
close (causes position reduction or)
price (float) – always be positive to ensure consistency
Price (#)
negative (always positive to ensure consistency. Unknown what happens if)
value (# Market) – (unused) cost incurred in new size/price op Not used because the value is calculated for the trade
value
trade
commission (float) – incurred commission in the new size/price op
trade
pnl (float) – (unused) generated by the executed part Not used because the trade has an independent pnl
part (# Profit/loss generated by executed)
profit/loss (not used because trade has independent)
comminfo – commission information