
    'iU                     V   d dl mZmZmZmZ d dlZd dlmZ d dlZd dlZddl	m
Z
mZmZ ddlmZ ddlmZ  G d d	e      Z G d
 de      Z G d d eee            Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Zy)    )absolute_importdivisionprint_functionunicode_literalsN)copy   )rangewith_metaclass	iteritems)
MetaParams)AutoOrderedDictc                   "    e Zd ZdZ	 	 	 	 	 ddZy)OrderExecutionBita  
    Intended to hold information about order execution. A "bit" does not
    determine if the order has been fully/partially executed, it just holds
    information.

    Member Attributes:

      - dt: datetime (float) execution time
      - size: how much was executed
      - price: execution price
      - closed: how much of the execution closed an existing postion
      - opened: how much of the execution opened a new position
      - openedvalue: market value of the "opened" part
      - closedvalue: market value of the "closed" part
      - closedcomm: commission for the "closed" part
      - openedcomm: commission for the "opened" part

      - value: market value for the entire bit size
      - comm: commission for the entire bit execution
      - pnl: pnl generated by this bit (if something was closed)

      - psize: current open position size
      - pprice: current open position price

    Nc                     || _         || _        || _        || _        || _        || _        || _        || _        |	| _        ||z   | _	        ||	z   | _
        |
| _        || _        || _        y N)dtsizepriceclosedopenedclosedvalueopenedvalue
closedcomm
openedcommvaluecommpnlpsizeppriceselfr   r   r   r   r   r   r   r   r   r   r   r   s                N/var/www/app/trading-bot/venv/lib/python3.12/site-packages/backtrader/order.py__init__zOrderExecutionBit.__init__>   sr     	
&&$$ ;.
+	
    )Nr           r   r%   r%   r   r%   r%   r%   r   r%   )__name__
__module____qualname____doc__r#    r$   r"   r   r   #   s    6 ),7:7:!$r$   r   c                   t    e Zd ZdZ	 	 ddZd Zd Z eee      Zd Z	d Z
	 	 	 	 ddZd	 Zd
 Zd Zd Zd Zy)	OrderDataa  
    Holds actual order data for Creation and Execution.

    In the case of Creation the request made and in the case of Execution the
    actual outcome.

    Member Attributes:

      - exbits : iterable of OrderExecutionBits for this OrderData

      - dt: datetime (float) creation/execution time
      - size: requested/executed size
      - price: execution price
        Note: if no price is given and no pricelimite is given, the closing
        price at the time or order creation will be used as reference
      - pricelimit: holds pricelimit for StopLimit (which has trigger first)
      - trailamount: absolute price distance in trailing stops
      - trailpercent: percentage price distance in trailing stops

      - value: market value for the entire bit size
      - comm: commission for the entire bit execution
      - pnl: pnl generated by this bit (if something was closed)
      - margin: margin incurred by the Order (if any)

      - psize: current open position size
      - pprice: current open position price

    Nc	                 b   || _         t        j                         | _        d\  | _        | _        || _        || _        || _        || _	        || _
        || _        || _        |s| j                  | _
        |r	|s|| _	        || _        d| _        d| _        d | _        d| _        d| _        d| _        y )N)r   r   r%   r   )pclosecollectionsdequeexbitsp1p2r   r   remsizer   
pricelimittrailamounttrailpercentplimitr   r   marginr   r   r   )	r!   r   r   r   r5   r4   r.   r6   r7   s	            r"   r#   zOrderData.__init__   s     !'')	
$&("jjDOe#DJ 
	
r$   c                     | j                   S r   _plimitr!   s    r"   
_getplimitzOrderData._getplimit       ||r$   c                     || _         y r   r;   r!   vals     r"   
_setplimitzOrderData._setplimit   	    r$   c                 ,    t        | j                        S r   )lenr1   r=   s    r"   __len__zOrderData.__len__   s    4;;r$   c                      | j                   |   S r   )r1   )r!   keys     r"   __getitem__zOrderData.__getitem__   s    {{3r$   c                 N    | j                  t        |||||||||	|
||             y r   )addbitr   r    s                r"   addzOrderData.add   s3     	b$$k:$k:s#V-	.r$   c                 h   | j                   j                  |       | xj                  |j                  z  c_        |j                  | _        | j                  | j
                  z  }|j                  |j
                  z  }| xj                  |j                  z  c_        ||z   | j                  z  | _        | xj                  |j                  z  c_        | xj                  |j                  z  c_        | xj                  |j                  z  c_        |j                  | _	        |j                  | _
        y r   )r1   appendr4   r   r   r   r   r   r   r   r   )r!   exbitoldvaluenewvalues       r"   rL   zOrderData.addbit   s    5!

"((99tzz)::+		UZZ	)TYY6


ekk!
		UZZ	EII[[
llr$   c                 4    t        | j                               S r   )listiterpendingr=   s    r"   
getpendingzOrderData.getpending   s    D$$&''r$   c                 l    t        j                  | j                  | j                  | j                        S r   )	itertoolsislicer1   r2   r3   r=   s    r"   rU   zOrderData.iterpending   s#    TWWdgg>>r$   c                 \    | j                   t        | j                        c| _        | _         y r   )r3   rF   r1   r2   r=   s    r"   markpendingzOrderData.markpending   s    77C$4r$   c                 <    | j                          t        |       }|S r   )r[   r   r!   objs     r"   clonezOrderData.clone   s    4j
r$   )Nr   r%   r%   r   r%   r%   r%   )	r   r%   r%   r   r%   r%   r%   r   r%   )r&   r'   r(   r)   r#   r>   rC   propertyr8   rG   rJ   rM   rL   rV   rU   r[   r_   r*   r$   r"   r,   r,   X   sf    R LM;>B j*-F   3625	
.#"(?5r$   r,   c            	           e Zd ZdZ ej
                         Z ed      \  ZZ	Z
Z ed      Z ed      \  ZZZZZZZZg dZddgZ ed      \  ZZ ed	      \	  ZZZZZZZZ Z!eZ"g d
Z# e$jJ                  d      Z&d Z'd Z( e)e'e(      Z*d Z+ fdZ,d Z-d Z.d Z/d+dZ0d+dZ1e2d        Z3d+dZ4d Z5d Z6d Z7d Z8d Z9d Z:d Z;d Z<d Z=d Z>d+d Z?d+d!Z@d" ZAd+d#ZBd$ ZCd% ZDd& ZEd' ZFd( ZGd) ZHd* ZI xZJS ),	OrderBase))ownerN)dataN)r   N)r   N)r5   N)exectypeN)validN)tradeidr   )ocoN)r6   N)r7   N)parentN)transmitT)	simulatedF)
histnotifyF   r      )MarketCloseLimitStop	StopLimit	StopTrailStopTrailLimit
HistoricalBuySell   	   )	Created	SubmittedAcceptedPartial	CompletedCanceledExpiredMarginRejectedc                     | j                   S r   r;   r=   s    r"   r>   zOrderBase._getplimit  r?   r$   c                     || _         y r   r;   rA   s     r"   rC   zOrderBase._setplimit	  rD   r$   c                 .    t        | j                  |      S r   )getattrparams)r!   names     r"   __getattr__zOrderBase.__getattr__  s    t{{D))r$   c                     t        | j                  |      rt        | j                  ||       y t        t        |   ||       y r   )hasattrr   setattrsuperOrder__setattribute__)r!   r   r   	__class__s      r"   r   zOrderBase.__setattribute__  s2    4;;%DKKu-%/e<r$   c                    t               }|j                  dj                  | j                               |j                  dj                  | j                               |j                  dj                  | j                                      |j                  dj                  | j                               |j                  dj                  | j                                      |j                  dj                  | j                               |j                  dj                  | j                               |j                  dj                  | j                               |j                  dj                  | j                               |j                  dj                  | j                               |j                  d	j                  | j                               |j                  d	j                  | j                                      |j                  d
j                  | j                               |j                  dj                  | j                                |j                  dj                  | j"                               |j                  dj                  | j$                               |j                  dj                  | j'                                      dj)                  |      S )NzRef: {}zOrdType: {}z
Status: {}zSize: {}z	Price: {}zPrice Limit: {}zTrailAmount: {}zTrailPercent: {}zExecType: {}zCommInfo: {}zEnd of Session: {}zInfo: {}z
Broker: {}z	Alive: {}
)rT   rO   formatrefordtypeordtypenamestatusgetstatusnamer   r   r5   r6   r7   re   getordernamecomminfodteosinfobrokeralivejoin)r!   tojoins     r"   __str__zOrderBase.__str__  s   i&&txx01m**4<<89m**4+;+;+=>?l))$++67l))$*<*<*>?@j''		23k((45'..t?@'..t/?/?@A(//0A0ABCn++DMM:;n++D,=,=,?@An++DMM:;*11$**=>j''		23l))$++67k((67yy  r$   c           	      D
   t        | j                        | _        d | _        t	               | _        d | _        d| _        | j                  d u | _	        t        j                  | _        | j                  j                  | _        | j                   t        j"                  | _        | j%                         s| j&                   | _        | j                  j(                  s| j*                  j,                  d   n| j.                  }| j.                  s| j                  s|n| j.                  }| j                  j(                  s| j*                  j0                  d   nd}t3        || j&                  || j                  || j4                  | j6                        | _        | j                   t        j:                  t        j<                  fv r| j8                  j.                  | j8                  j                  z
  | _        | j8                  j.                  }tA        d| j%                         z  xs d      | j8                  _        | jC                  |       nd| _        t3        | j&                        | _"        d| _#        tI        | jJ                  t0        jL                        r,| j*                  jO                  | jJ                        | _%        ntI        | jJ                  t0        jP                        r| jJ                  | jR                  k(  rYt0        j0                  jU                  | j*                  j0                  jM                         t1        jV                  dd	d	d
            }n1| j*                  j0                  j1                         | jJ                  z   }| j*                  jO                  |      | _%        n| jJ                  | jJ                  sYt0        j0                  jU                  | j*                  j0                  jM                         t1        jV                  dd	d	d
            }n&| j*                  j0                  d   | jJ                  z   }| j                  j(                  s| j*                  j0                  j1                  d      }| j*                  j                  jX                  }|j[                  |j\                  |j^                  |j`                  |jb                        }||k  r|t1        jP                  d      z  }| j*                  jO                  |      | _2        y d| _2        y )NFr   r%   )r   r   r   r5   r.   r6   r7   infz-inf)r4      ;   i'  )hourminutesecondmicrosecondr   )days)3nextrefbasisr   r   r   r   r   	triggeredri   _activer   r{   r   pr5   r8   re   ro   isbuyr   rk   rd   closer   datetimer,   r6   r7   createdrt   ru   _limitoffsetfloattrailadjustexecutedposition
isinstancerf   datedate2num	timedeltaDAYcombinetime
sessionendreplacer   r   r   r   r   )r!   r.   r   dcreatedrf   dtimesessionr   s           r"   r#   zOrderBase.__init__.  s   &#%	{{d*mmff''== !LLDMzz|
DI ,066+;+;#"jjdjj040@0@499%%a(c H&*ii',,0OO(.-1-=-=.2.?.?A ==U__e.B.BCC $ 2 2T\\5L5L LDLL&&E!&utzz|';'Ev!FDLLU# #D!$))4djj(--0++DJJ7DJ

H$6$67 zzTXX% ))11II&&++-x}}RR/NP 		**335

B++E2DJZZ#:: ))11II&&++-x}}RR/NP 		**1-

:vv II&&//2Eiikk,,GMMw||GNN)0.5.A.A " CE u}++33++E2DJDJr$   c                 Z    t        |       }| j                  j                         |_        |S r   )r   r   r_   r]   s     r"   r_   zOrderBase.clone  s&     4j}}**,
r$   c                 @    | j                   || j                     S |   S )z;Returns the name for a given status or the one of the order)Statusr   )r!   r   s     r"   r   zOrderBase.getstatusname  s!    {{&.4;;EEfEEr$   c                 @    | j                   || j                     S |   S )z=Returns the name for a given exectype or the one of the order)	ExecTypesre   )r!   re   s     r"   r   zOrderBase.getordername  s"    ~~x/?dmmNNXNNr$   c                     t        | |      S r   )r   )clsre   s     r"   ExecTypezOrderBase.ExecType  s    sH%%r$   c                 @    | j                   || j                     S |   S )z<Returns the name for a given ordtype or the one of the order)OrdTypesr   )r!   r   s     r"   r   zOrderBase.ordtypename  s!    }}W_T\\JJ'JJr$   c                     | j                   S r   r   r=   s    r"   activezOrderBase.active  r?   r$   c                     d| _         y )NTr   r=   s    r"   activatezOrderBase.activate  s	    r$   c                     | j                   t        j                  t        j                  t        j                  t        j
                  fv S )z[Returns True if the order is in a status in which it can still be
        executed
        )r   r   r{   r|   r~   r}   r=   s    r"   r   zOrderBase.alive  s3     {{u}}eoo$}}enn> > 	>r$   c                     || _         y)z2Stores a CommInfo scheme associated with the assetN)r   )r!   r   s     r"   addcomminfozOrderBase.addcomminfo  	     r$   c                 H    t        |      D ]  \  }}|| j                  |<    y)zwAdd the keys, values of kwargs to the internal info dictionary to
        hold custom information in the order
        N)r   r   )r!   kwargsrI   rB   s       r"   addinfozOrderBase.addinfo  s)     "&) 	!HC DIIcN	!r$   c                 @    |d uxr | j                   |j                   k(  S r   r   r!   others     r"   __eq__zOrderBase.__eq__  s    D :TXX%::r$   c                 4    | j                   |j                   k7  S r   r   r   s     r"   __ne__zOrderBase.__ne__  s    xx599$$r$   c                 4    | j                   | j                  k(  S )z(Returns True if the order is a Buy order)r   rw   r=   s    r"   r   zOrderBase.isbuy  s    ||txx''r$   c                 4    | j                   | j                  k(  S )z)Returns True if the order is a Sell order)r   rx   r=   s    r"   issellzOrderBase.issell  s    ||tyy((r$   c                     || _         y)z:Receives the current position for the asset and stotres itN)r   )r!   r   s     r"   setpositionzOrderBase.setposition  r   r$   c                 p    t         j                  | _        || _        t	        | j
                        | _        y)zSMarks an order as submitted and stores the broker to which it was
        submittedN)r   r|   r   r   rF   rd   plenr!   r   s     r"   submitzOrderBase.submit  s%     oo		N	r$   c                 <    t         j                  | _        || _        y)zMarks an order as acceptedN)r   r}   r   r   r   s     r"   acceptzOrderBase.accept  s    nnr$   c                 h    | j                   r| j                   j                  |       S | j                  S )zTries to retrieve the status from the broker in which the order is.

        Defaults to last known status if no broker is associated)r   orderstatusr   r=   s    r"   brokerstatuszOrderBase.brokerstatus  s*     ;;;;**400{{r$   c                     | j                   t        j                  k(  ryt        j                  | _         || _        | j                  j
                  s(| j                  j                  d   | j                  _	        y)zMarks an order as rejectedFr   T)
r   r   r   r   r   rk   rd   r   r   r   r   s     r"   rejectzOrderBase.reject  sR    ;;%..(nnvv#yy11!4DMMr$   c                     t         j                  | _        | j                  j                  s)| j
                  j                  d   | j                  _        yy)zMarks an order as cancelledr   N)	r   r   r   r   rk   rd   r   r   r   r=   s    r"   cancelzOrderBase.cancel  s:    nnvv#yy11!4DMM  r$   c                     t         j                  | _        | j                  j                  s)| j
                  j                  d   | j                  _        yy)z*Marks an order as having met a margin callr   N)	r   r   r   r   rk   rd   r   r   r   r=   s    r"   r9   zOrderBase.margin  s:    llvv#yy11!4DMM  r$   c                 &    | j                   | _        y)z#Marks an order as completely filledN)r   r   r=   s    r"   	completedzOrderBase.completed  s    nnr$   c                 &    | j                   | _        y)z"Marks an order as partially filledN)r~   r   r=   s    r"   partialzOrderBase.partial  s    llr$   c                 x    |sy| j                   j                  |||||||||	|||       |
| j                   _        y)z+Receives data execution input and stores itN)r   rM   r9   )r!   r   r   r   r   r   r   r   r   r   r9   r   r   r   s                 r"   executezOrderBase.execute  sE     "dE +z +zuf	.
  &r$   c                 &    | j                   | _        y)z4Marks an order as expired. Returns True if it workedT)r   r   r=   s    r"   expirezOrderBase.expire  s    llr$   c                      y r   r*   )r!   r   s     r"   r   zOrderBase.trailadjust  s    r$   r   )Kr&   r'   r(   r   r   r   r   r	   T_CloseT_DayT_DateT_NoneV_Nonero   rp   rq   rr   rs   rt   ru   rv   r   r   rw   rx   r{   r|   r}   r~   r   r   r   r   r   	Cancelledr   rX   countr   r>   rC   r`   r8   r   r   r   r#   r_   r   r   classmethodr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r9   r   r   r   r   r   __classcell__r   s   @r"   rb   rb      sz   	F (


C &+1X"GUFF 1XF 8VUE4I~1I vHaIC /4Ah,GY'9'68IF
 yq!H j*-F*=!,PdFO & &K>!!;%()!#
	55%#&"
r$   rb   c                   .     e Zd ZdZ fdZd Zd Z xZS )r   aV  
    Class which holds creation/execution data and type of oder.

    The order may have the following status:

      - Submitted: sent to the broker and awaiting confirmation
      - Accepted: accepted by the broker
      - Partial: partially executed
      - Completed: fully exexcuted
      - Canceled/Cancelled: canceled by the user
      - Expired: expired
      - Margin: not enough cash to execute the order.
      - Rejected: Rejected by the broker

        This can happen during order submission (and therefore the order will
        not reach the Accepted status) or before execution with each new bar
        price because cash has been drawn by other sources (future-like
        instruments may have reduced the cash or orders orders may have been
        executed)

    Member Attributes:

      - ref: unique order identifier
      - created: OrderData holding creation data
      - executed: OrderData holding execution data

      - info: custom information passed over method :func:`addinfo`. It is kept
        in the form of an OrderedDict which has been subclassed, so that keys
        can also be specified using '.' notation

    User Methods:

      - isbuy(): returns bool indicating if the order buys
      - issell(): returns bool indicating if the order sells
      - alive(): returns bool if order is in status Partial or Accepted
    c                     t         t        |   |||||||||	|
|||       | j                  j                  rt        j
                  | _        y t        j                  | _        y r   )r   r   r   r   r4   r~   r   r   )r!   r   r   r   r   r   r   r   r   r   r9   r   r   r   r   s                 r"   r   zOrder.execute6  sV     	eT"2tU#);
#);
#)3v	?
 ==  --DK//DKr$   c                     | j                   t        j                  k(  ry| j                  rd| j                  j
                  d   | j                  kD  r>t        j                  | _        | j                  j
                  d   | j                  _	        yy)NFr   T)
re   r   ro   rf   rd   r   r   r   r   r   r=   s    r"   r   zOrder.expireH  sb    ==ELL(::$)),,Q/$**<--DK#yy11!4DMMr$   c                 D   | j                   r| j                   }n| j                  r|| j                  z  }nd}| j                         rm||z  }|| j                  j                  k  rN|| j                  _        | j
                  t        j                  k(  r|| j                  z
  | j                  _	        y y y ||z  }|| j                  j                  kD  rN|| j                  _        | j
                  t        j                  k(  r|| j                  z
  | j                  _	        y y y )Nr%   )
r6   r7   r   r   r   re   r   ru   r   r5   )r!   r   pamounts      r"   r   zOrder.trailadjustS  s    &&Gd///GG ::<WEt||)))%*"==E$8$88.3d6G6G.GDLL+ 9 *
 WEt||)))%*"==E$8$88 /4d6G6G.GDLL+ 9 *r$   )r&   r'   r(   r)   r   r   r   r  r  s   @r"   r   r     s    #J*$	Hr$   r   c                   $    e Zd Zej                  Zy)BuyOrderN)r&   r'   r(   r   rw   r   r*   r$   r"   r  r  l  s    iiGr$   r  c                       e Zd Zy)StopBuyOrderNr&   r'   r(   r*   r$   r"   r  r  p      r$   r  c                       e Zd Zy)StopLimitBuyOrderNr  r*   r$   r"   r  r  t  r  r$   r  c                   $    e Zd Zej                  Zy)	SellOrderN)r&   r'   r(   r   rx   r   r*   r$   r"   r  r  x  s    jjGr$   r  c                       e Zd Zy)StopSellOrderNr  r*   r$   r"   r  r  |  r  r$   r  c                       e Zd Zy)StopLimitSellOrderNr  r*   r$   r"   r  r    r  r$   r  )
__future__r   r   r   r   r/   r   r   rX   	utils.py3r	   r
   r   metabaser   utilsr   objectr   r,   rb   r   r  r  r  r  r  r  r*   r$   r"   <module>r!     s   ** *     7 7   "2 2jC CLoz62 od	YHI YHxu 	8 		 	 	I 		 	r$   