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).

示例

Accessing trade information: >>> trade.status # Created, Open, or Closed >>> trade.pnl # Current profit/loss >>> trade.pnlcomm # PnL minus commission

class backtrader.trade.TradeHistory[源代码]

基类:AutoOrderedDict

Represents 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:: - status

Holds 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:

dict with '.' 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:

dict with '.' notation

__init__(status, dt, barlen, size, price, value, pnl, pnlcomm, tz, event=None)[源代码]

Initializes the object to the current status of the Trade

doupdate(order, size, price, commission)[源代码]

Used to fill the update part of the history entry

datetime(tz=None, naive=True)[源代码]

Returns a datetime for the time the update event happened

class backtrader.trade.Trade[源代码]

基类:object

Keeps 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 identifier

  • status (int): one of Created, Open, Closed # Trade status

  • tradeid: 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 0

  • size (int): current size of the trade # Current size of the trade

  • price (float): current price of the trade # Current price of the trade

  • value (float): current value of the trade # Current market value of the trade

  • commission (float): current accumulated commission # Current accumulated commission

  • pnl (float): current profit and loss of the trade (gross pnl) # Current profit and loss

  • pnlcomm (float): current profit and loss of the trade minus commission (net pnl) # Current net profit and loss after deducting commission

  • isclosed (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 null

  • isopen (bool): records if any update has opened the trade # Whether the trade has been opened

  • justopened (bool): if the trade was just opened # Whether the trade was just opened

  • baropen (int): bar in which this trade was opened # Record which bar opened the position

  • dtopen (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 method open_datetime to get a Python datetime.datetime

    or use the platform provided num2date method

  • barclose (int): bar in which this trade was closed # Which bar the trade ended on

  • dtclose (float): float coded datetime in which the trade was closed - Use method close_datetime to get a Python datetime.datetime

    or use the platform provided num2date method

    # 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 open

  • historyon (bool): whether history has to be recorded # Whether to record historical trade update events

  • history (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)[源代码]

Initialize a Trade object.

参数:
  • 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.

__len__()[源代码]

Absolute size of the trade

__bool__()[源代码]

Trade size is not 0

__nonzero__()

Trade size is not 0

getdataname()[源代码]

Shortcut to retrieve the name of the data this trade references

open_datetime(tz=None, naive=True)[源代码]

Returns a datetime.datetime object with the datetime in which the trade was opened

close_datetime(tz=None, naive=True)[源代码]

Returns a datetime.datetime object with the datetime in which the trade was closed

update(order, size, price, value, commission, pnl, comminfo)[源代码]

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

参数:
  • 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