
    'i-                     t    d dl mZmZmZmZ d dlZddlmZ ddlm	Z	 ddl
mZ  G d de      Z G d	 d
e      Zy)    )absolute_importdivisionprint_functionunicode_literalsN   )AutoOrderedDict)num2date)rangec                   :     e Zd ZdZ	 d fd	Zd Zd ZddZ xZS )TradeHistoryaY  Represents the status and update event for each update a Trade has

    This object is a dictionary which allows '.' notation

    Attributes:
      - ``status`` (``dict`` with '.' notation): Holds the resulting status of
        an update event and has the following sub-attributes

        - ``status`` (``int``): Trade status
        - ``dt`` (``float``): float coded datetime
        - ``barlen`` (``int``): number of bars the trade has been active
        - ``size`` (``int``): current size of the Trade
        - ``price`` (``float``): current price of the Trade
        - ``value`` (``float``): current monetary value of the Trade
        - ``pnl`` (``float``): current profit and loss of the Trade
        - ``pnlcomm`` (``float``): current profit and loss minus commission

      - ``event`` (``dict`` with '.' notation): Holds the event update
        - parameters

        - ``order`` (``object``): the order which initiated the``update``
        - ``size`` (``int``): size of the update
        - ``price`` (``float``):price of the update
        - ``commission`` (``float``): price of the update
    c                 p   t         t        |           || j                  _        || j                  _        || j                  _        || j                  _        || j                  _        || j                  _        || j                  _	        || j                  _
        |	| j                  _        |
|
| _        yy)z9Initializes the object to the current status of the TradeN)superr   __init__statusdtbarlensizepricevaluepnlpnlcommtzevent)selfr   r   r   r   r   r   r   r   r   r   	__class__s              N/var/www/app/trading-bot/venv/lib/python3.12/site-packages/backtrader/trade.pyr   zTradeHistory.__init__:   s     	lD*,##!!%DJ     c                    | j                   | j                  j                  | j                  j                  | j                  j                  | j                  j                  | j                  j
                  | j                  j                  | j                  j                  | j                  j                  | j                  j                  | j                  f
fS N)r   r   r   r   r   r   r   r   r   r   r   r   s    r   
__reduce__zTradeHistory.__reduce__J   s    !3!3T[[^^T[[EWEWY]YdYdYiYi!%!2!2DKK4E4Et{{X\XcXcXkXk!%!? @ 	@r   c                     || j                   _        || j                   _        || j                   _        || j                   _        | j                          y)z5Used to fill the ``update`` part of the history entryN)r   orderr   r   
commission_close)r   r#   r   r   r$   s        r   doupdatezTradeHistory.doupdateO   s<     



 

 *

 	r   c                 t    t        | j                  j                  |xs | j                  j                  |      S )z9Returns a datetime for the time the update event happened)r	   r   r   r   r   r   naives      r   datetimezTradeHistory.datetimeY   s&    (<dkknneDDr   r   NT)	__name__
__module____qualname____doc__r   r!   r&   r*   __classcell__)r   s   @r   r   r      s%    6 RV @
Er   r   c                       e Zd ZdZ ej
                  d      Zg dZ ed      \  Z	Z
Zd Z	 	 ddZd Zd	 ZeZd
 ZddZddZd Zy)Tradea  Keeps track of the life of an trade: size, price,
    commission (and value?)

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

    An trade is not meant to be reversed (no support in the logic for it)

    Member Attributes:

      - ``ref``: unique trade identifier
      - ``status`` (``int``): one of Created, Open, Closed
      - ``tradeid``: grouping tradeid passed to orders during creation
        The default in orders is 0
      - ``size`` (``int``): current size of the trade
      - ``price`` (``float``): current price of the trade
      - ``value`` (``float``): current value of the trade
      - ``commission`` (``float``): current accumulated commission
      - ``pnl`` (``float``): current profit and loss of the trade (gross pnl)
      - ``pnlcomm`` (``float``): current profit and loss of the trade minus
        commission (net pnl)
      - ``isclosed`` (``bool``): records if the last update closed (set size to
        null the trade
      - ``isopen`` (``bool``): records if any update has opened the trade
      - ``justopened`` (``bool``): if the trade was just opened
      - ``baropen`` (``int``): bar in which this trade was opened

      - ``dtopen`` (``float``): float coded datetime in which the trade was
        opened

        - 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

      - ``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

      - ``barlen`` (``int``): number of bars this trade was open
      - ``historyon`` (``bool``): whether history has to be recorded
      - ``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

    r   )CreatedOpenClosed   c                 <     d}dj                   fd|D              S )N)refdatatradeidr   r   r   r$   r   r   
justopenedisopenisclosedbaropendtopenbarclosedtcloser   	historyonhistoryr   
c           
   3   j   K   | ]*  }d j                  |t        t        |            f       , yw):N)joinstrgetattr).0xr   s     r   	<genexpr>z Trade.__str__.<locals>.<genexpr>   s+     CaSXXq#gdA./01Cs   03)rG   )r   toprints   ` r   __str__zTrade.__str__   s%     yyC7C
 	
r   Nc                 f   t        | j                        | _        || _        || _        || _        || _        || _        || _        d| _	        d| _
        d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        || _        t)               | _        | j,                  | _        y )N        Fr   )nextrefbasisr8   r9   r:   r   r   r   r$   r   r   r;   r<   r=   r>   r?   r@   rA   r   rB   listrC   r3   r   )r   r9   r:   rB   r   r   r   r$   s           r   r   zTrade.__init__   s     &		

$"vllr   c                 ,    t        | j                        S )zAbsolute size of the trade)absr   r    s    r   __len__zTrade.__len__   s    499~r   c                      | j                   dk7  S )zTrade size is not 0r   )r   r    s    r   __bool__zTrade.__bool__   s    yyA~r   c                 .    | j                   j                  S )z?Shortcut to retrieve the name of the data this trade references)r9   _namer    s    r   getdatanamezTrade.getdataname   s    yyr   c                 R    | j                   j                  | j                  ||      S )zcReturns a datetime.datetime object with the datetime in which
        the trade was opened
        r   r)   )r9   r	   r?   r(   s      r   open_datetimezTrade.open_datetime   s$     yy!!$++"E!BBr   c                 R    | j                   j                  | j                  ||      S )zcReturns a datetime.datetime object with the datetime in which
        the trade was closed
        r]   )r9   r	   rA   r(   s      r   close_datetimezTrade.close_datetime   s$     yy!!$,,2U!CCr   c                 v   |sy| xj                   |z  c_         | j                  }| xj                  |z  c_        t        | xr |      | _        | j                  rdt	        | j
                        | _        |j                  j                  rdn| j
                  j                  d   | _
        | j                  dkD  | _        t        | j                        | _        t	        | j
                        | j                  z
  | _        t        |xr | j                         | _        | j                  rQd| _        t	        | j
                        | _        | j
                  j                  d   | _        | j"                  | _        n| j                  r| j&                  | _        t)        | j                        t)        |      kD  r*|| j*                  z  ||z  z   | j                  z  | _        d}n|j-                  | | j*                  |      }| xj.                  |z  c_        | j.                  | j                   z
  | _        |j3                  | j                  | j*                        | _        | j6                  r|j                  j                  s| j
                  j                  d   nd}	t9        | j$                  |	| j                  | j                  | j*                  | j4                  | j.                  | j0                  | j
                  j:                  	      }
|
j=                  ||||       | j>                  jA                  |
       yy)a*  
        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)

        Args:
            order: the order object which has (completely or partially)
                generated this update
            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

            price (float): always be positive to ensure consistency
            value (float): (unused) cost incurred in new size/price op
                           Not used because the value is calculated for the
                           trade
            commission (float): incurred commission in the new size/price op
            pnl (float): (unused) generated by the executed part
                         Not used because the trade has an independent pnl
        NrP   r   F)!r$   r   boolr;   lenr9   r>   p	simulatedr*   r?   longr<   r   r=   r@   rA   r5   r   r4   rU   r   profitandlossr   r   getvaluesizer   rB   r   _tzr&   rC   append)r   r#   r   r   r   r$   r   comminfooldsizedt0	histentrys              r   updatezTrade.update   sX   >  	:% ))		T	 7{3t4??tyy>DL!&!2!2#		8J8J18MDK		ADI 499o $))nt||3 W6TYY7 ==DK		NDM99--a0DL++DK[[))DKtyy>CL( "DJJ.=JDJC (($

EBCCxx$//1**499djjA
 >>/4ww/@/@$))$$Q'cC$S$++		4::tzz$,,		7I udE:>LL	* r   )Nr   Fr   rP   rP   rP   r+   )r,   r-   r.   r/   	itertoolscountrR   status_namesr
   r3   r4   r5   rN   r   rV   rX   __nonzero__r[   r^   r`   ro    r   r   r2   r2   ^   si    3h yq!H0L!!HGT6
 8=:=#: KCD[+r   r2   )
__future__r   r   r   r   rp   utilsr   
utils.dater	   	utils.py3r
   r   objectr2   rt   r   r   <module>rz      s:   ** *  "   <E? <E~Y+F Y+r   