
    'i                         d dl mZmZmZmZ d dlZd dlZd dlZd dl	m
Z
 d dlmZmZmZ d dlmZ d dlmZmZ ddgZ G d	 dej*                        ZeZy)
    )absolute_importdivisionprint_functionunicode_literalsN)CommInfoBase)OrderBuyOrder	SellOrder)Position)string_typesinteger_types
BackBroker
BrokerBackc                       e Zd ZdZdZ fdZ fdZd Zd9dZd Z	 e
e	e      Zd Zd	 Zd
 Zd Zd Z	 	 d:dZ	 	 d:dZd Zd Zd ZeZd ZeZd ZeZd Zd Z e
e      Zd Z e
e      Zd;dZ d<dZ!e!Z"d=dZ#d=dZ$d Z%d;dZ&d Z'd Z(d Z)d>d Z*d>d!Z+d" Z,d# Z-d;d$Z.d% Z/d& Z0d>d'Z1d( Z2	 	 	 	 	 d?d)Z3	 	 	 	 	 d?d*Z4	 	 d@d+Z5d, Z6d- Z7d. Z8d/ Z9d0 Z:d1 Z;d2 Z<dAd3Z=dAd4Z>d5 Z?d6 Z@d7 ZAd8 ZB xZCS )Br   a  Broker Simulator

      The simulation supports different order types, checking a submitted order
      cash requirements against current cash, keeping track of cash and value
      for each iteration of ``cerebro`` and keeping the current position on
      different datas.

      *cash* is adjusted on each iteration for instruments like ``futures`` for
       which a price change implies in real brokers the addition/substracion of
       cash.

      Supported order types:

        - ``Market``: to be executed with the 1st tick of the next bar (namely
          the ``open`` price)

        - ``Close``: meant for intraday in which the order is executed with the
          closing price of the last bar of the session

        - ``Limit``: executes if the given limit price is seen during the
          session

        - ``Stop``: executes a ``Market`` order if the given stop price is seen

        - ``StopLimit``: sets a ``Limit`` order in motion if the given stop
          price is seen

      Because the broker is instantiated by ``Cerebro`` and there should be
      (mostly) no reason to replace the broker, the params are not controlled
      by the user for the instance.  To change this there are two options:

        1. Manually create an instance of this class with the desired params
           and use ``cerebro.broker = instance`` to set the instance as the
           broker for the ``run`` execution

        2. Use the ``set_xxx`` to set the value using
           ``cerebro.broker.set_xxx`` where ```xxx`` stands for the name of the
           parameter to set

        .. note::

           ``cerebro.broker`` is a *property* supported by the ``getbroker``
           and ``setbroker`` methods of ``Cerebro``

      Params:

        - ``cash`` (default: ``10000``): starting cash

        - ``commission`` (default: ``CommInfoBase(percabs=True)``)
          base commission scheme which applies to all assets

        - ``checksubmit`` (default: ``True``)
          check margin/cash before accepting an order into the system

        - ``eosbar`` (default: ``False``):
          With intraday bars consider a bar with the same ``time`` as the end
          of session to be the end of the session. This is not usually the
          case, because some bars (final auction) are produced by many
          exchanges for many products for a couple of minutes after the end of
          the session

        - ``filler`` (default: ``None``)

          A callable with signature: ``callable(order, price, ago)``

            - ``order``: obviously the order in execution. This provides access
              to the *data* (and with it the *ohlc* and *volume* values), the
              *execution type*, remaining size (``order.executed.remsize``) and
              others.

              Please check the ``Order`` documentation and reference for things
              available inside an ``Order`` instance

            - ``price`` the price at which the order is going to be executed in
              the ``ago`` bar

            - ``ago``: index meant to be used with ``order.data`` for the
              extraction of the *ohlc* and *volume* prices. In most cases this
              will be ``0`` but on a corner case for ``Close`` orders, this
              will be ``-1``.

              In order to get the bar volume (for example) do: ``volume =
              order.data.voluume[ago]``

          The callable must return the *executed size* (a value >= 0)

          The callable may of course be an object with ``__call__`` matching
          the aforementioned signature

          With the default ``None`` orders will be completely executed in a
          single shot

        - ``slip_perc`` (default: ``0.0``) Percentage in absolute termns (and
          positive) that should be used to slip prices up/down for buy/sell
          orders

          Note:

            - ``0.01`` is ``1%``

            - ``0.001`` is ``0.1%``

        - ``slip_fixed`` (default: ``0.0``) Percentage in units (and positive)
          that should be used to slip prices up/down for buy/sell orders

          Note: if ``slip_perc`` is non zero, it takes precendence over this.

        - ``slip_open`` (default: ``False``) whether to slip prices for order
          execution which would specifically used the *opening* price of the
          next bar. An example would be ``Market`` order which is executed with
          the next available tick, i.e: the opening price of the bar.

          This also applies to some of the other executions, because the logic
          tries to detect if the *opening* price would match the requested
          price/execution type when moving to a new bar.

        - ``slip_match`` (default: ``True``)

          If ``True`` the broker will offer a match by capping slippage at
          ``high/low`` prices in case they would be exceeded.

          If ``False`` the broker will not match the order with the current
          prices and will try execution during the next iteration

        - ``slip_limit`` (default: ``True``)

          ``Limit`` orders, given the exact match price requested, will be
          matched even if ``slip_match`` is ``False``.

          This option controls that behavior.

          If ``True``, then ``Limit`` orders will be matched by capping prices
          to the ``limit`` / ``high/low`` prices

          If ``False`` and slippage exceeds the cap, then there will be no
          match

        - ``slip_out`` (default: ``False``)

          Provide *slippage* even if the price falls outside the ``high`` -
          ``low`` range.

        - ``coc`` (default: ``False``)

          *Cheat-On-Close* Setting this to ``True`` with ``set_coc`` enables
           matching a ``Market`` order to the closing price of the bar in which
           the order was issued. This is actually *cheating*, because the bar
           is *closed* and any order should first be matched against the prices
           in the next bar

        - ``coo`` (default: ``False``)

          *Cheat-On-Open* Setting this to ``True`` with ``set_coo`` enables
           matching a ``Market`` order to the opening price, by for example
           using a timer with ``cheat`` set to ``True``, because such a timer
           gets executed before the broker has evaluated

        - ``int2pnl`` (default: ``True``)

          Assign generated interest (if any) to the profit and loss of
          operation that reduces a position (be it long or short). There may be
          cases in which this is undesired, because different strategies are
          competing and the interest would be assigned on a non-deterministic
          basis to any of them.

        - ``shortcash`` (default: ``True``)

          If True then cash will be increased when a stocklike asset is shorted
          and the calculated value for the asset will be negative.

          If ``False`` then the cash will be deducted as operation cost and the
          calculated value will be positive to end up with the same amount

        - ``fundstartval`` (default: ``100.0``)

          This parameter controls the start value for measuring the performance
          in a fund-like way, i.e.: cash can be added and deducted increasing
          the amount of shares. Performance is not measured using the net
          asset value of the porftoflio but using the value of the fund

        - ``fundmode`` (default: ``False``)

          If this is set to ``True`` analyzers like ``TimeReturn`` can
          automatically calculate returns based on the fund value and not on
          the total net asset value

    ))cashg     @)checksubmitT)eosbarF)fillerN)	slip_perc        )
slip_fixedr   )	slip_openF)
slip_matchT)
slip_limitT)slip_outF)cocF)cooF)int2pnlT)	shortcashT)fundstartvalg      Y@)fundmodeFc                 |    t         t        |           g | _        g | _        t        d      t        d      g| _        y )NNaN)superr   __init__	_userhist	_fundhistfloat
_fhistlastself	__class__s    X/var/www/app/trading-bot/venv/lib/python3.12/site-packages/backtrader/brokers/bbroker.pyr%   zBackBroker.__init__   s2    j$(* <u6    c                    t         t        |           | j                  j                  x| _        | _        | j                  | _        d| _        d| _        d| _	        d| _
        d| _        t               | _        t        j                         | _        t        j                         | _        t        j$                  t&              | _        t        j$                  t*              | _        t        j                         | _        t        j                         | _        t        j$                  t        j                        | _        t5               | _        t        j$                  t              | _        | j                  j:                  | _        | j                  j                  | j<                  z  | _        t        j                         | _         y )Nr         ?)!r$   r   initpr   startingcash_value	_valuemkt_valuelever_valuemktlever	_leverage_unrealizedlistorderscollectionsdequepending_toactivatedefaultdictr   	positionsr(   d_creditnotifs	submitted
_pchildrendict_ocos_ocolr    _fundval_fundshares_cash_additionr*   s    r-   r1   zBackBroker.init   s6   j$$&(,3DIii!f"((*&,,.$00:#//6!'')$**, &11+2C2CDV
 ,,T2
++66;;6)//1r.   c                 V    	 | j                   j                         S # t        $ r Y y w xY wN)rC   popleft
IndexErrorr+   s    r-   get_notificationzBackBroker.get_notification  s/    	;;&&(( 		s    	((c                 N    || j                   _        || j                  |       yy)ztSet the actual fundmode (True or False)

        If the argument fundstartval is not ``None``, it will used
        N)r2   r!   set_fundstartval)r+   r!   r    s      r-   set_fundmodezBackBroker.set_fundmode#  s(    
 ##!!,/ $r.   c                 .    | j                   j                  S )z+Returns the actual fundmode (True or False))r2   r!   rP   s    r-   get_fundmodezBackBroker.get_fundmode,  s    vvr.   c                 &    || j                   _        y)z;Set the starting value of the fund-like performance trackerN)r2   r    )r+   r    s     r-   rS   zBackBroker.set_fundstartval2  s    *r.   c                 &    || j                   _        y)z3Configure assignment of interest to profit and lossN)r2   r   )r+   r   s     r-   set_int2pnlzBackBroker.set_int2pnl6  s     r.   c                 &    || j                   _        y)zAConfigure the Cheat-On-Close method to buy the close on order barN)r2   r   )r+   r   s     r-   set_coczBackBroker.set_coc:      
r.   c                 &    || j                   _        y)z@Configure the Cheat-On-Open method to buy the close on order barN)r2   r   )r+   r   s     r-   set_coozBackBroker.set_coo>  r\   r.   c                 &    || j                   _        y)z"Configure the shortcash parametersN)r2   r   )r+   r   s     r-   set_shortcashzBackBroker.set_shortcashB  s    $r.   c                     || j                   _        d| j                   _        || j                   _        || j                   _        || j                   _        || j                   _        y)z)Configure slippage to be percentage basedr   Nr2   r   r   r   r   r   r   )r+   percr   r   r   r   s         r-   set_slippage_perczBackBroker.set_slippage_percF  sK      $&&"r.   c                     d| j                   _        || j                   _        || j                   _        || j                   _        || j                   _        || j                   _        y)z+Configure slippage to be fixed points basedr   Nrb   )r+   fixedr   r   r   r   s         r-   set_slippage_fixedzBackBroker.set_slippage_fixedQ  sK     !$&&"r.   c                 &    || j                   _        y)z1Sets a volume filler for volume filling executionN)r2   r   )r+   r   s     r-   
set_fillerzBackBroker.set_filler\      r.   c                 &    || j                   _        y)zSets the checksubmit parameterN)r2   r   )r+   r   s     r-   set_checksubmitzBackBroker.set_checksubmit`  s    (r.   c                 &    || j                   _        y)z/Sets the eosbar parameter (alias: ``seteosbar``N)r2   r   )r+   r   s     r-   
set_eosbarzBackBroker.set_eosbard  rj   r.   c                     | j                   S )z-Returns the current cash (alias: ``getcash``))r   rP   s    r-   get_cashzBackBroker.get_cashj  s    yyr.   c                 P    |x| _         x| _        | j                  _        || _        y)z,Sets the cash parameter (alias: ``setcash``)N)r3   r   r2   r4   r+   r   s     r-   set_cashzBackBroker.set_cashp  s#    6:::DIr.   c                 :    | j                   j                  |       y)z>Add/Remove cash to the system (use a negative value to remove)N)rK   appendrr   s     r-   add_cashzBackBroker.add_cashw  s    ""4(r.   c                     | j                   S )z:Returns the current number of shares in the fund-like mode)rJ   rP   s    r-   get_fundshareszBackBroker.get_fundshares{  s    r.   c                     | j                   S )z!Returns the Fund-like share value)rI   rP   s    r-   get_fundvaluezBackBroker.get_fundvalue  s    }}r.   c                     	 | j                   j                  |       |j                          | j	                  |       | j                  |       |s| j                  |d       y# t        $ r Y yw xY w)NFTcancel)r>   remove
ValueErrorr}   notify	_ococheck_bracketize)r+   orderbrackets      r-   r}   zBackBroker.cancel  si    	LL&
 	EuU40  		s   A% %	A10A1c                     |6|r|s| j                   S | j                  S |s| j                  S | j                  S | j	                  ||      S )zReturns the portfolio value of the given datas (if datas is ``None``, then
        the total portfolio value will be returned (alias: ``getvalue``)
        )dataslever)r5   r7   r4   r6   
_get_value)r+   r   mktr   s       r-   	get_valuezBackBroker.get_value  sM     =-2t~~K8K8KK&+4;;A1A1AAU%88r.   c                 (    | j                  ||      S )N)r   r   )r   )r+   r   r   s      r-   get_value_leverzBackBroker.get_value_lever  s    ~~Es~33r.   c                 B   d}d}d}| j                   r^| j                   j                         }| xj                  || j                  z  z  c_        | xj                  |z  c_        | j                   r^|xs | j
                  D ]E  }| j                  |      }| j
                  |   }	| j                  j                  s |j                  |	|j                  d         }
n)|j                  |	j                  |j                  d         }
|j                  |	j                  |	j                  |j                  d         }|r6t        |      dk(  r(|r"|
dkD  r|
|z  }
|
|j!                         z  |z   c S |
c S | j                  j                  st#        |
      }
||
z  }||z  }|
dkD  r"|
|z  }
||
|j!                         z  z  }||z  }A||
z  }H | j$                  s5| j                  |z   x| _        }| j&                  | j                  z  | _        nE| j)                         \  }}|| _        ||z
  | _        || _        ||z  | _        ||xs dz  }|}||z  }|| _        | j                  |z   | _        || _        ||xs dz  | _        || _        |s| j&                  S | j,                  S )Nr   r      r0   )rK   rN   rJ   rI   r   rA   getcommissioninfor2   r   getvalueclosegetvaluesizesizeprofitandlosspricelenget_leverageabsr'   r4   _process_fund_historyr5   r6   r7   r8   r9   )r+   r   r   	pos_valuepos_value_unlever
unrealizedcdatacomminfopositiondvaluedunrealizedvfvalfvaluelevs                   r-   r   zBackBroker._get_value  s   	
!!##++-ADMM 11IINI !!
 +T^^ 	,D--d3H~~d+H66##!**8TZZ]C!..x}}djjmL"0015A@KUqVaZk)F"X%:%:%<<KK66##VI+%Jz+%!fx/D/D/F&FG!![0!!V+!9	,< ~~"ii*;;;DK! KK$*:*::DM  557LD& DK!22DI DM%}D07C8C !'I*99y0'"&7&>3?%"'t{{=T-=-==r.   c                     | j                   S rM   )r8   rP   s    r-   r   zBackBroker.get_leverage  s    ~~r.   c                     |r)| j                   D cg c]  }|j                          }}|S | j                   D cg c]  }| }}|S c c}w c c}w )zReturns an iterable with the orders which are still open (either not
        executed or partially executed

        The orders returned must not be touched.

        If order manipulation is needed, set the parameter ``safe`` to True
        )r>   clone)r+   safexoss       r-   get_orders_openzBackBroker.get_orders_open  sQ     %)\\2!'')2B2 	 "\\*!*B*		 3*s
   A	Ac                      | j                   |   S )z\Returns the current position status (a ``Position`` instance) for
        the given ``data``)rA   )r+   r   s     r-   getpositionzBackBroker.getposition  s     ~~d##r.   c                     	 | j                   j                  |      }|j                  S # t        $ r |}Y |j                  S w xY wrM   )r;   indexr   status)r+   r   os      r-   orderstatuszBackBroker.orderstatus   sE    	!!%(A xx  	Axx	s   ) AAc                     |j                   }t        |j                  d|      }||k7  r0|| j                  vr"|j	                          | j                  |       y |S )Nref)r   getattrparentrE   rejectr   )r+   r   orefprefs       r-   _take_childrenzBackBroker._take_children  sM    yyu||UD14<4??*E"r.   c                     | j                  |      }||S | j                  |   }|j                  |       |j                  r%|D cg c]  }| j                  ||       }}|d   S |S c c}w )Ncheck)r   rE   ru   transmit)r+   r   r   r   pcr   retss          r-   submitzBackBroker.submit  sp    ""5)<L__T"
		%>>;=>aDMM!5M1>D>8O ?s   A)c                 
   |ro| j                   j                  rY|j                          | j                  j	                  |       | j
                  j	                  |       | j                  |       |S | j                  |       |S rM   )r2   r   r   rD   ru   r;   r   submit_accept)r+   r   r   s      r-   r   zBackBroker.transmit#  sf    TVV''LLNNN!!%(KKu%KK  u%r.   c                 X   | j                   }t               }| j                  r| j                  j                         }| j	                  |      9| j                  |j                        }|j                  |j                  | j                  |j                     j                               }| j                  |||      }|dk\  r| j                  |       |j                          | j                  |       | j                  |       | j                  |d       | j                  ry y )N)r   r   r   Tr|   )r   rF   rD   rN   r   r   r   
setdefaultrA   r   _executer   marginr   r   r   )r+   r   rA   r   r   r   s         r-   check_submittedzBackBroker.check_submitted.  s    yyF	nnNN**,E""5)1--ejj9H ++

DNN5::6<<>@H ==TH=EDs{""5)LLNKKNN5!U40+ nnr.   c                     d |_         |j                          |j                          | j                  j	                  |       | j                  |       y rM   )
pannotatedr   acceptr>   ru   r   r+   r   s     r-   r   zBackBroker.submit_acceptI  s:    E"Er.   c                 F   |j                   }t        |j                  d|      }||k(  }| j                  |   }|s|s4|r$| j	                  |j                         d       |r$| j                  |= y |j                          |D ]  }| j                  j                  |        y )Nr   T)r   )r   r   r   rE   r}   rN   r?   ru   )r+   r   r}   r   r   r   r   r   s           r-   r   zBackBroker._bracketizeP  s    yyu||UD1__T"BJJL$7  % JJL +  ''*+r.   c                    | j                   |j                     }| j                   j                  |d       }| j                  j	                  |d       }|rxt        t        | j                        dz
  dd      D ]Q  }| j                  |   }||j                  |v s$| j                  |= |j                          | j                  |       S y y )Nr   r   )
rG   r   getrH   popranger   r>   r}   r   )r+   r   	parentrefocorefocolir   s          r-   r   zBackBroker._ocochecka  s    JJuyy)		40zz~~fd+3t||,q0"b9 #LLO=QUUd]QHHJKKN# r.   c                    |j                   }|.|| j                  |<   | j                  |   j                  |       y | j                  |j                      }|| j                  |<   | j                  |   j                  |       y rM   )r   rG   rH   ru   )r+   r   ocor   r   s        r-   _ocoizezBackBroker._ocoizen  sl    yy;#DJJtJJt##D)ZZ(F%DJJtJJv%%d+r.   c                 n    t        |      }t        |d       }| j                  j                  |||g       y rM   )iternextr&   ru   )r+   r;   r   oiterr   s        r-   add_order_historyzBackBroker.add_order_historyx  s0    Vq%01r.   c                     t        |      }t        t        |            }||g| _        | j	                  t        |d                y )N   )r   r:   r   r'   rs   r(   )r+   fundfiterfs       r-   set_fund_historyzBackBroker.set_fund_history}  s<     T
eU 	eAaDk"r.   c                     t        |||||||||
||||      } |j                  di | | j                  ||	       | j                  ||      S N)ownerr   r   r   
pricelimitexectypevalidtradeidtrailamounttrailpercentr   r   
histnotifyr    )r	   addinfor   r   r+   r   r   r   r   plimitr   r   r   r   r   r   r   r   r   _checksubmitkwargsr   s                     r-   buyzBackBroker.buy  sa     u4"%F"*%%0| &$.0 	UC {{5{55r.   c                     t        |||||||||
||||      } |j                  di | | j                  ||	       | j                  ||      S r   )r
   r   r   r   r   s                     r-   sellzBackBroker.sell  sa     D#5V#+5'&1!'(%/1 	UC {{5{55r.   c                    ||y | j                   j                  ||j                  j                  }n0| j                   j                  |||      }|j	                         s| }| j                  |j                        }|j                  j                  (|j                  j                  }	| j                  |	      }
n|j                  }	|}
|S| j                  |	   }|j                  }|j                  ||      \  }}}}|j                  | ||      }| j                  }nd}| j                   j                  s|j                  j                  x}}nQ|j                  t         j"                  k(  r|j                  j$                  d   x}}n|j                  j                  x}}|j'                  ||      \  }}}}|r| j                   j(                  r|j+                  | |      }n|j-                  ||      }|}|dkD  r||j/                         z  }||||j0                  z  z   z  }|j3                  ||      }||z  }|-||j5                  | |j6                  |      z  }|| _        ndx}}|}|r| j                   j(                  r|j+                  ||      }n|j-                  ||      }|}|dkD  r||j/                         z  }||z  }|
j3                  ||      }||z  }|dk  rd}dx}}nQ|Ot9        |      t9        |      kD  r%||z
  }||j5                  ||j6                  |      z  }||_        || _        ndx}}||S ||z   }|r|j;                  ||       |j'                  |||	j<                  j=                                |r5| j                   j>                  r|| j@                  jC                  |	d      z  }|jE                  |xs |	j<                  |   |||||||||jF                  |||       |jI                  |       | jK                  |       | jM                  |       |rI|sF|jG                          | jK                  |       | jM                  |       | jO                  |d       y y y )Nr   r   Tr|   )(r2   r   executedremsizeisbuyr   r   _compensaterA   r   pseudoupdater   r   r   createdr   r   Marketopenupdater   r   getoperationcostr   	stocklikegetcommission
cashadjustadjbaser   confirmexecdatetimer   rB   r   executer   addcomminfor   r   r   )r+   r   agor   r   r   dtcocr   r   r   	cinfocomppprice_origpsizeppriceopenedclosedpnlclosedvalue	closecash
closedcommpopenedopenedvalueopencash
openedcommadjsizeexecsizes                             r-   r   zBackBroker._execute  s[    ?u}66== CK>>))D 66==s3D;;=u ))%**5 ::!!-::))D..t4I::D I ?~~d+H"..K,4,A,A$,N)E666 ((&+uEC99DC66::&+mm&9&99
 >>U\\1*/**//!*<<EK*/--*=*==EK,4OOD%,H)E666 vv&33VG[I&77L#IQX2244	Ih&8&8 888D!//>JJD ++VG,4,<,<,13 3
 !	'**K*vv&33FEB&77F"HQH1133HD"00?JJDcz+..ju:F+ $fnGH//080@0@%I ID $)  !	'**K*;KF?  51 OOHeT]]-C-C-EF$&&..dmm//c::
 MM%54==#5"E +z +z"//3) h'KKNN5!6LLNKKNN5!U40 "7r.   c                 V    | j                   j                  |j                                y rM   )rC   ru   r   r   s     r-   r   zBackBroker.notifyO  s    5;;=)r.   c                 T    | j                  |d|j                  j                         y )Nr   r  r   )r   r   r   r   s     r-   _try_exec_historicalzBackBroker._try_exec_historicalR  s    e%--*=*=>r.   c                 H   d}| j                   j                  rI|j                  j                  dd      r-|j                  j
                  }|j                  j                  }nK| j                   j                  s1|j                  j                  d   |j                  j
                  k  ry d }|}|j                         r)| j                  ||| j                   j                        }n(| j                  ||| j                   j                        }| j                  |d||       y )Nr   r   Tdoslip)r  r   r  )r2   r   infor   r   dtpcloser   r   r
  r   _slip_upr   
_slip_downr   )	r+   r   popenphighplowr  r  expricer2   s	            r-   _try_exec_marketzBackBroker._try_exec_marketU  s    66::%**..5MM$$Emm**G66::%**"5"5a"8EMM<L<L"LEG;;=eWTVV5E5EFAgdff6F6FGAe!59r.   c                    |j                   j                  d   }||j                  j                  kD  rR||j                  k\  rC|j
                  r||j                  kD  rd}|j
                  }nd}|}| j                  |||       y ||_        y )Nr   r   r!  )r   r
  r   r'  dteosr   r   )r+   r   r(  dt0r  	execprices         r-   _try_exec_closezBackBroker._try_exec_closeh  s     jj!!!$!!!ekk!##ekk(9C % 0 0IC &IeI> "r.   c                    |j                         rj||k\  rJt        ||      }| j                  ||| j                  j                  d      }| j                  |d|       y ||k\  r| j                  |d|       y y ||k  rJt        ||      }| j                  ||| j                  j                  d      }| j                  |d|       y ||k  r| j                  |d|       y y )NT)r%  limr   r!  )r   minr)  r2   r   r   maxr*  )	r+   r   r+  r,  r-  r   pmaxr2   pmins	            r-   _try_exec_limitzBackBroker._try_exec_limit  s    ;;=5&)MM$dff6F6F&* " ,e!44e&9  
 4(OOFE$&&:J:J(, $ .e!45e&9 !r.   c                 Z   |j                         rn||k\  r=| j                  ||| j                  j                        }| j	                  |d|       n||k\  r| j                  ||      }| j	                  |d|       nm||k  r=| j                  ||| j                  j                        }| j	                  |d|       n+||k  r&| j                  ||      }| j	                  |d|       |j                         r0|j                  t        j                  k(  r|j                  |       y y y )Nr$  r   r!  )r   r)  r2   r   r   r*  aliver   r   	StopTrailtrailadjust)r+   r   r+  r,  r-  pcreatedr(  r2   s           r-   _try_exec_stopzBackBroker._try_exec_stop  s    ;;= MM%tvv7G7GMHe!4("MM%2e!4  OOD%8H8HOIe!4!OOD(3e!4 ;;=U^^u>f% ?=r.   c                 J   |j                         r||k\  rd|_        | j                  |||||       n0||k\  r*d|_        ||kD  rH||k\  r)| j                  ||d      }| j	                  |d|       n||k\  r| j	                  |d|       n||k\  r| j                  ||d      }| j	                  |d|       n||k  rd|_        | j                  |||||       n||k  rd|_        ||k  rH||k  r)| j                  ||d      }| j	                  |d|       nG||k  rB| j	                  |d|       n-||k  r(| j                  ||d      }| j	                  |d|       |j                         r0|j                  t        j                  k(  r|j                  |       y y y )NT)r6  r   r!  )r   	triggeredr;  r)  r   r*  r=  r   r   StopTrailLimitr?  )	r+   r   r+  r,  r-  r(  r@  r   r2   s	            r-   _try_exec_stoplimitzBackBroker._try_exec_stoplimit  s    ;;= "&$$UE5$G(""&6>) MM%tMDe!<6)e&A) MM%tMDe!< "&$$UE5$G!"&F?) OOD(OEe!<6)e&A ) OOD(OEe!< ;;=U^^u/C/CCf% D=r.   c                 ,   |s|S | j                   j                  }| j                   j                  }|r	|d|z   z  }n
|r||z   }n|S ||k  r|S | j                   j                  s|r0| j                   j                  r| j                   j
                  s|S |S y Nr   r2   r   r   r   r   r   )r+   r9  r   r%  r6  r   r   pslips           r-   r)  zBackBroker._slip_up      LFF$$	VV&&
Q]+EJ&ELD=LVV3466+<+<66??Lr.   c                 ,   |s|S | j                   j                  }| j                   j                  }|r	|d|z
  z  }n
|r||z
  }n|S ||k\  r|S | j                   j                  s|r0| j                   j                  r| j                   j
                  s|S |S y rG  rH  )r+   r:  r   r%  r6  r   r   rI  s           r-   r*  zBackBroker._slip_down  rJ  r.   c           	         |j                   }t        |dd       }||j                  d   }t        |dd       }||j                  d   }t        |dd       }||j                  d   }t        |dd       }||j
                  d   }|j                  j                  }|j                  j                  }|j                  t        j                  k(  r| j                  ||||       y |j                  t        j                  k(  r| j                  ||       y |j                  t        j                  k(  r| j!                  |||||       y |j"                  rB|j                  t        j$                  t        j&                  fv r| j!                  |||||       y |j                  t        j(                  t        j*                  fv r| j-                  ||||||       y |j                  t        j$                  t        j&                  fv r| j/                  |||||||       y |j                  t        j0                  k(  r| j3                  |       y y )N	tick_openr   	tick_hightick_low
tick_close)r   r   r  highlowr   r   r   r   r   r   r  r/  Closer4  Limitr;  rC  	StopLimitrD  Stopr>  rA  rE  
Historicalr"  )	r+   r   r   r+  r,  r-  r(  r@  r   s	            r-   	_try_execzBackBroker._try_exec  s   zzk40=IIaLEk40=IIaLEtZ.<88A;D|T2>ZZ]F==&&))>>U\\)!!%t<^^u{{*  /^^u{{*  udHEoonn%2F2F GG  udFC^^

EOO<<ueT8VL^^1E1EFF$$U%*E4%-v7 ^^u///%%e, 0r.   c                 L   | j                   }|\  }}|s| j                  S |d   }t        |t              r:d}d|v r|dz  }d|v r|dz  }t        j                  j                  ||      }||d<   npt        |t        j                        rnUt        |t        j                        r;t	        j                  |j                  |j                  |j                        }||d<   || j                  j                  k  r"|dd  | _        t        t        |g             |d<   | j                  S )	Nr   %Y-%m-%dT	T%H:%M:%S..%fyearmonthdayr   )r'   r)   
isinstancer   r
  strptimedater`  ra  rb  cerebro	_dtmasterr:   r   )r+   fhistr   fundsr'  dtfmts         r-   r   z BackBroker._process_fund_history;  s   5??"qTb,'Eby$"9UNE""++B6BAaDH--.HMM*""rxxRVVLBAaD '''eDODO,E!Hr.   c           
      D   | j                   D ]  }|\  }}}|t        |      }	 |d   }|| j                  j                  d   }nCt        |t              r| j                  j                  |   }n| j                  j                  |   }t        |      s|d   }t        |t              r:d}d|v r|dz  }d|v r|dz  }t        j                  j                  ||      }||d<   npt        |t        j                        rnUt        |t        j                        r;t        j                  |j                  |j                  |j                        }||d<   ||j                  j                         kD  rg|d	   }	|d
   }
| j                  j                   d   }|	dkD  r'| j#                  |||	|
t$        j&                  |d      }n4|	dk  r/| j)                  ||t+        |	      |
t$        j&                  |d      }t-        |d       x|d<   }| y # t        $ r d }Y w xY w)N   r   rZ  r[  r\  r]  r^  r_  r   r   F)r   r   r   r   r   r   r   )r&   r:   rO   rf  r   rc  r   datasbynamer   r   r
  rd  re  r`  ra  rb  runningstratsr   r   rW  r   r   r   )r+   uhistuhorderuhordersuhnotifydataidxdr'  rj  r   r   r   r   s                r-   _process_order_historyz!BackBroker._process_order_history\  s   ^^ 9	:E*/'GXx%w-#%ajG ?**1-A7**73A009A1vQZb,/&Eby,"9!UNE!**33B>B!#GAJH$5$56HMM2!**13/1vv7B "$GAJ

++--qz
2215!8u1&*%*/*:*:,4.3	 ! 5A AX		A'*4y+0+;+;-5/4	 " 6A &*(D%99a7o %9	: " #"G#s   HHHc           	         | j                   r5| j                   j                         j                          | j                   r5| j                  j                  r| j                          d}| j                  j                         D ]i  \  }}|s	| j                  |      }|j                  j                         }|j                  |||      }| j                  |xx   |z  cc<   ||z  }||_	        k | xj                  |z  c_        | j                          | j                  j                  d        	 | j                  j                         }|n|j!                         r6| j#                  |       | j%                  |       | j'                  |d       n|j)                         s| j                  j                  |       nk| j+                  |       |j-                         r| j                  j                  |       n.|j.                  t0        j2                  k(  r| j'                  |       | j                  j                         D ]t  \  }}|s	| j                  |      }| xj                  |j5                  |j6                  |j8                  |j:                  d         z  c_        |j:                  d   |_        v | j=                          y )Nr   Tr|   r   )r?   rN   activater2   r   r   rA   itemsr   r
  get_credit_interestrB   r   ru  r>   ru   expirer   r   r   activerX  r=  r   r   	Completedr  r   r  r   r   )r+   creditr   posr   r2  dcreditr   s           r-   r   zBackBroker.next  s@   $$&//1  66  " --/ 	#ID#11$7mm,,."66tS#Fd#w.#'!"	# 			V	##% 	D!LL((*E}||~E"u%  t 4\\^##E* u%;;=LL''.\\U__4$$U+) . --/ 	,ID#11$7		X001415A@ @	 #jjm	, 	r.   rM   )TTTF)F)NFF)NF)T)NNNNr   NNNNTFT)NNNNN)TF)D__name__
__module____qualname____doc__paramsr%   r1   rQ   rT   rV   propertyr!   rS   rY   r[   r^   r`   rd   rg   ri   rl   rn   	seteosbarrp   getcashrs   setcashrv   rx   
fundsharesrz   	fundvaluer}   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r"  r/  r4  r;  rA  rE  r)  r*  rX  r   ru  r   __classcell__)r,   s   @r-   r   r   $   s   zvF(72@0 l3H+!%
 6:49	# 7;5:	#) I G
 G)  .)J 'I
9 H4A>F$

	16+"#,2
# &*6:+/"&+/6* '+7;,0#',06( IM^1@*?:&"4:.&2.&`..)-VB::x9r.   )
__future__r   r   r   r   r<   r
  
backtraderbtbacktrader.comminfor   backtrader.orderr   r	   r
   backtrader.positionr   backtrader.utils.py3r   r   __all__
BrokerBaser   r   r   r.   r-   <module>r     sM   ** *    , 7 7 ( <
&m mb% 
r.   