
    'ip                     b   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Z	 ej                  Z
d dlZddlmZmZmZmZmZmZ ddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlm Z m!Z!m"Z"m#Z# ddl$m%Z%m&Z& ddl'm(Z(m)Z)m*Z* ddl+m,Z,  G d de-      Z. G d d eee-            Z/y# e$ r eZ
Y w xY w)    )absolute_importdivisionprint_functionunicode_literalsN   )maprangezipwith_metaclassstring_typesinteger_types)
linebuffer)	indicator)
BackBroker)
MetaParams)	observers)
WriterFile)OrderedDicttzparsenum2datedate2num)StrategySignalStrategy)TradingCalendarBaseTradingCalendarPandasMarketCalendar)Timerc                       e Zd Zd Zy)	OptReturnc                 j    |x| _         | _        |j                         D ]  \  }}t        | ||        y N)pparamsitemssetattr)selfr#   kwargskvs        P/var/www/app/trading-bot/venv/lib/python3.12/site-packages/backtrader/cerebro.py__init__zOptReturn.__init__6   s5    %%LLN 	 DAqD!Q	     N)__name__
__module____qualname__r+    r,   r*   r   r   5   s     r,   r   c            
       6   e Zd ZdZdZd Zed        Zd Zd>dZ	d Z
 ej                          ej                         g d	g dd
d
d	d	f
dZ ej                          ej                         g d	g dd
d
d	d	f
dZd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Z d Z!d  Z"d! Z#d" Z$d?d#Z%d$ Z&d% Z'd?d&Z(d?d'Z)d( Z*d) Z+d* Z,d+ Z-d, Z. e/e.e-      Z0	 	 d@d-Z1d. Z2d/ Z3d0 Z4d1 Z5d2 Z6d3 Z7dAd4Z8d5 Z9d6 Z:d7 Z;d8 Z<d9 Z=d: Z>d; Z?d< Z@dAd=ZAy
)BCerebroaO"  Params:

      - ``preload`` (default: ``True``)

        Whether to preload the different ``data feeds`` passed to cerebro for
        the Strategies

      - ``runonce`` (default: ``True``)

        Run ``Indicators`` in vectorized mode to speed up the entire system.
        Strategies and Observers will always be run on an event based basis

      - ``live`` (default: ``False``)

        If no data has reported itself as *live* (via the data's ``islive``
        method but the end user still want to run in ``live`` mode, this
        parameter can be set to true

        This will simultaneously deactivate ``preload`` and ``runonce``. It
        will have no effect on memory saving schemes.

        Run ``Indicators`` in vectorized mode to speed up the entire system.
        Strategies and Observers will always be run on an event based basis

      - ``maxcpus`` (default: None -> all available cores)

         How many cores to use simultaneously for optimization

      - ``stdstats`` (default: ``True``)

        If True default Observers will be added: Broker (Cash and Value),
        Trades and BuySell

      - ``oldbuysell`` (default: ``False``)

        If ``stdstats`` is ``True`` and observers are getting automatically
        added, this switch controls the main behavior of the ``BuySell``
        observer

        - ``False``: use the modern behavior in which the buy / sell signals
          are plotted below / above the low / high prices respectively to avoid
          cluttering the plot

        - ``True``: use the deprecated behavior in which the buy / sell signals
          are plotted where the average price of the order executions for the
          given moment in time is. This will of course be on top of an OHLC bar
          or on a Line on Cloe bar, difficulting the recognition of the plot.

      - ``oldtrades`` (default: ``False``)

        If ``stdstats`` is ``True`` and observers are getting automatically
        added, this switch controls the main behavior of the ``Trades``
        observer

        - ``False``: use the modern behavior in which trades for all datas are
          plotted with different markers

        - ``True``: use the old Trades observer which plots the trades with the
          same markers, differentiating only if they are positive or negative

      - ``exactbars`` (default: ``False``)

        With the default value each and every value stored in a line is kept in
        memory

        Possible values:
          - ``True`` or ``1``: all "lines" objects reduce memory usage to the
            automatically calculated minimum period.

            If a Simple Moving Average has a period of 30, the underlying data
            will have always a running buffer of 30 bars to allow the
            calculation of the Simple Moving Average

            - This setting will deactivate ``preload`` and ``runonce``
            - Using this setting also deactivates **plotting**

          - ``-1``: datafreeds and indicators/operations at strategy level will
            keep all data in memory.

            For example: a ``RSI`` internally uses the indicator ``UpDay`` to
            make calculations. This subindicator will not keep all data in
            memory

            - This allows to keep ``plotting`` and ``preloading`` active.

            - ``runonce`` will be deactivated

          - ``-2``: data feeds and indicators kept as attributes of the
            strategy will keep all points in memory.

            For example: a ``RSI`` internally uses the indicator ``UpDay`` to
            make calculations. This subindicator will not keep all data in
            memory

            If in the ``__init__`` something like
            ``a = self.data.close - self.data.high`` is defined, then ``a``
            will not keep all data in memory

            - This allows to keep ``plotting`` and ``preloading`` active.

            - ``runonce`` will be deactivated

      - ``objcache`` (default: ``False``)

        Experimental option to implement a cache of lines objects and reduce
        the amount of them. Example from UltimateOscillator::

          bp = self.data.close - TrueLow(self.data)
          tr = TrueRange(self.data)  # -> creates another TrueLow(self.data)

        If this is ``True`` the 2nd ``TrueLow(self.data)`` inside ``TrueRange``
        matches the signature of the one in the ``bp`` calculation. It will be
        reused.

        Corner cases may happen in which this drives a line object off its
        minimum period and breaks things and it is therefore disabled.

      - ``writer`` (default: ``False``)

        If set to ``True`` a default WriterFile will be created which will
        print to stdout. It will be added to the strategy (in addition to any
        other writers added by the user code)

      - ``tradehistory`` (default: ``False``)

        If set to ``True``, it will activate update event logging in each trade
        for all strategies. This can also be accomplished on a per strategy
        basis with the strategy method ``set_tradehistory``

      - ``optdatas`` (default: ``True``)

        If ``True`` and optimizing (and the system can ``preload`` and use
        ``runonce``, data preloading will be done only once in the main process
        to save time and resources.

        The tests show an approximate ``20%`` speed-up moving from a sample
        execution in ``83`` seconds to ``66``

      - ``optreturn`` (default: ``True``)

        If ``True`` the optimization results will not be full ``Strategy``
        objects (and all *datas*, *indicators*, *observers* ...) but and object
        with the following attributes (same as in ``Strategy``):

          - ``params`` (or ``p``) the strategy had for the execution
          - ``analyzers`` the strategy has executed

        In most occassions, only the *analyzers* and with which *params* are
        the things needed to evaluate a the performance of a strategy. If
        detailed analysis of the generated values for (for example)
        *indicators* is needed, turn this off

        The tests show a ``13% - 15%`` improvement in execution time. Combined
        with ``optdatas`` the total gain increases to a total speed-up of
        ``32%`` in an optimization run.

      - ``oldsync`` (default: ``False``)

        Starting with release 1.9.0.99 the synchronization of multiple datas
        (same or different timeframes) has been changed to allow datas of
        different lengths.

        If the old behavior with data0 as the master of the system is wished,
        set this parameter to true

      - ``tz`` (default: ``None``)

        Adds a global timezone for strategies. The argument ``tz`` can be

          - ``None``: in this case the datetime displayed by strategies will be
            in UTC, which has been always the standard behavior

          - ``pytz`` instance. It will be used as such to convert UTC times to
            the chosen timezone

          - ``string``. Instantiating a ``pytz`` instance will be attempted.

          - ``integer``. Use, for the strategy, the same timezone as the
            corresponding ``data`` in the ``self.datas`` iterable (``0`` would
            use the timezone from ``data0``)

      - ``cheat_on_open`` (default: ``False``)

        The ``next_open`` method of strategies will be called. This happens
        before ``next`` and before the broker has had a chance to evaluate
        orders. The indicators have not yet been recalculated. This allows
        issuing an orde which takes into account the indicators of the previous
        day but uses the ``open`` price for stake calculations

        For cheat_on_open order execution, it is also necessary to make the
        call ``cerebro.broker.set_coo(True)`` or instantite a broker with
        ``BackBroker(coo=True)`` (where *coo* stands for cheat-on-open) or set
        the ``broker_coo`` parameter to ``True``. Cerebro will do it
        automatically unless disabled below.

      - ``broker_coo`` (default: ``True``)

        This will automatically invoke the ``set_coo`` method of the broker
        with ``True`` to activate ``cheat_on_open`` execution. Will only do it
        if ``cheat_on_open`` is also ``True``

      - ``quicknotify`` (default: ``False``)

        Broker notifications are delivered right before the delivery of the
        *next* prices. For backtesting this has no implications, but with live
        brokers a notification can take place long before the bar is
        delivered. When set to ``True`` notifications will be delivered as soon
        as possible (see ``qcheck`` in live feeds)

        Set to ``False`` for compatibility. May be changed to ``True``

    ))preloadT)runonceT)maxcpusN)stdstatsT)
oldbuysellF)	oldtradesF)	lookaheadr   )	exactbarsF)optdatasT)	optreturnT)objcacheF)liveF)writerF)tradehistoryF)oldsyncF)tzN)cheat_on_openF)
broker_cooT)quicknotifyFc                    d| _         d| _        d| _        t               | _        t               | _        t               | _        t        j                         | _	        t               | _
        t               | _        t               | _        t               | _        t               | _        t               | _        t               | _        t               | _        t               | _        t               | _        d| _        d| _        d| _        t1        j2                  d      | _        t7               | _        | | j8                  _        d | _        t               | _        t               | _         d | _!        y )NFNNNr   )"_dolive	_doreplay_dooptimizeliststoresfeedsdatascollectionsr   datasbynamestratsoptcbsr   	analyzers
indicatorsdictsizerswritersstorecbsdatacbssignals_signal_strat_signal_concurrent_signal_accumulate	itertoolscount_dataidr   _brokercerebro_tradingcal
_pretimers	_ohistory	_fhistoryr&   s    r*   r+   zCerebro.__init__(  s     fV
V
&224ff&fvvv/"'"' q)!|#&r,   c                     t               }| D ]D  }t        |t              r|f}nt        |t        j                        s|f}|j                  |       F |S )zlHandy function which turns things into things that can be iterated upon
        including iterables
        )rK   
isinstancer   collectionsAbcIterableappend)iterable	niterableelems      r*   iterizezCerebro.iterizeI  sX    
 F	 	#D$-wn&=&=>wT"	# r,   c                     || _         y)a4  
        Add a history of orders to be directly executed in the broker for
        performance evaluation

          - ``fund``: is an iterable (ex: list, tuple, iterator, generator)
            in which each element will be also an iterable (with length) with
            the following sub-elements (2 formats are possible)

            ``[datetime, share_value, net asset value]``

            **Note**: it must be sorted (or produce sorted elements) by
              datetime ascending

            where:

              - ``datetime`` is a python ``date/datetime`` instance or a string
                with format YYYY-MM-DD[THH:MM:SS[.us]] where the elements in
                brackets are optional
              - ``share_value`` is an float/integer
              - ``net_asset_value`` is a float/integer
        N)rf   )r&   funds     r*   set_fund_historyzCerebro.set_fund_historyY  s    , r,   Tc                 >    | j                   j                  ||f       y)a  
        Add a history of orders to be directly executed in the broker for
        performance evaluation

          - ``orders``: is an iterable (ex: list, tuple, iterator, generator)
            in which each element will be also an iterable (with length) with
            the following sub-elements (2 formats are possible)

            ``[datetime, size, price]`` or ``[datetime, size, price, data]``

            **Note**: it must be sorted (or produce sorted elements) by
              datetime ascending

            where:

              - ``datetime`` is a python ``date/datetime`` instance or a string
                with format YYYY-MM-DD[THH:MM:SS[.us]] where the elements in
                brackets are optional
              - ``size`` is an integer (positive to *buy*, negative to *sell*)
              - ``price`` is a float/integer
              - ``data`` if present can take any of the following values

                - *None* - The 1st data feed will be used as target
                - *integer* - The data with that index (insertion order in
                  **Cerebro**) will be used
                - *string* - a data with that name, assigned for example with
                  ``cerebro.addata(data, name=value)``, will be the target

          - ``notify`` (default: *True*)

            If ``True`` the 1st strategy inserted in the system will be
            notified of the artificial orders created following the information
            from each order in ``orders``

        **Note**: Implicit in the description is the need to add a data feed
          which is the target of the orders. This is for example needed by
          analyzers which track for example the returns
        N)re   rl   )r&   ordersnotifys      r*   add_order_historyzCerebro.add_order_historyq  s    N 	vv./r,   c                      y)a  Receives a timer notification where ``timer`` is the timer which was
        returned by ``add_timer``, and ``when`` is the calling time. ``args``
        and ``kwargs`` are any additional arguments passed to ``add_timer``

        The actual ``when`` time can be later, but the system may have not be
        able to call the timer before. This value is the timer value and no the
        system time.
        Nr0   )r&   timerwhenargsr'   s        r*   notify_timerzCerebro.notify_timer  s     	r,   FNc                     t        |t        | j                        ||||||||||	|
|d|}| j                  j                  |       |S )zInternal method to really create the timer (not started yet) which
        can be called by cerebro instances or other objects which can access
        cerebro)tidownerrQ   rz   offsetrepeatweekdays	weekcarry	monthdays
monthcarryallowtzdatacheat)r   lenrd   rl   )r&   r   rz   r   r   r   r   r   r   r   r   rQ   r   r{   r'   ry   s                   r*   
_add_timerzCerebro._add_timer  sb       DOO$fVJ	
 	
 	u%r,   c                 @     | j                   || |||||||||	|
|d|S )a  
        Schedules a timer to invoke ``notify_timer``

        Arguments:

          - ``when``: can be

            - ``datetime.time`` instance (see below ``tzdata``)
            - ``bt.timer.SESSION_START`` to reference a session start
            - ``bt.timer.SESSION_END`` to reference a session end

         - ``offset`` which must be a ``datetime.timedelta`` instance

           Used to offset the value ``when``. It has a meaningful use in
           combination with ``SESSION_START`` and ``SESSION_END``, to indicated
           things like a timer being called ``15 minutes`` after the session
           start.

          - ``repeat`` which must be a ``datetime.timedelta`` instance

            Indicates if after a 1st call, further calls will be scheduled
            within the same session at the scheduled ``repeat`` delta

            Once the timer goes over the end of the session it is reset to the
            original value for ``when``

          - ``weekdays``: a **sorted** iterable with integers indicating on
            which days (iso codes, Monday is 1, Sunday is 7) the timers can
            be actually invoked

            If not specified, the timer will be active on all days

          - ``weekcarry`` (default: ``False``). If ``True`` and the weekday was
            not seen (ex: trading holiday), the timer will be executed on the
            next day (even if in a new week)

          - ``monthdays``: a **sorted** iterable with integers indicating on
            which days of the month a timer has to be executed. For example
            always on day *15* of the month

            If not specified, the timer will be active on all days

          - ``monthcarry`` (default: ``True``). If the day was not seen
            (weekend, trading holiday), the timer will be executed on the next
            available day.

          - ``allow`` (default: ``None``). A callback which receives a
            `datetime.date`` instance and returns ``True`` if the date is
            allowed for timers or else returns ``False``

          - ``tzdata`` which can be either ``None`` (default), a ``pytz``
            instance or a ``data feed`` instance.

            ``None``: ``when`` is interpreted at face value (which translates
            to handling it as if it where UTC even if it's not)

            ``pytz`` instance: ``when`` will be interpreted as being specified
            in the local time specified by the timezone instance.

            ``data feed`` instance: ``when`` will be interpreted as being
            specified in the local time specified by the ``tz`` parameter of
            the data feed instance.

            **Note**: If ``when`` is either ``SESSION_START`` or
              ``SESSION_END`` and ``tzdata`` is ``None``, the 1st *data feed*
              in the system (aka ``self.data0``) will be used as the reference
              to find out the session times.

          - ``strats`` (default: ``False``) call also the ``notify_timer`` of
            strategies

          - ``cheat`` (default ``False``) if ``True`` the timer will be called
            before the broker has a chance to evaluate the orders. This opens
            the chance to issue orders based on opening price for example right
            before the session starts
          - ``*args``: any extra args will be passed to ``notify_timer``

          - ``**kwargs``: any extra kwargs will be passed to ``notify_timer``

        Return Value:

          - The created timer

        )r   rz   r   r   r   r   r   r   r   r   rQ   r   )r   )r&   rz   r   r   r   r   r   r   r   r   rQ   r   r{   r'   s                 r*   	add_timerzCerebro.add_timer  sF    v t  T&J&  	r,   c                 &    || j                   _        y)a  
        This can also be done with the parameter ``tz``

        Adds a global timezone for strategies. The argument ``tz`` can be

          - ``None``: in this case the datetime displayed by strategies will be
            in UTC, which has been always the standard behavior

          - ``pytz`` instance. It will be used as such to convert UTC times to
            the chosen timezone

          - ``string``. Instantiating a ``pytz`` instance will be attempted.

          - ``integer``. Use, for the strategy, the same timezone as the
            corresponding ``data`` in the ``self.datas`` iterable (``0`` would
            use the timezone from ``data0``)

        N)r"   rB   )r&   rB   s     r*   addtzzCerebro.addtz!  s    & 	r,   c                     t        |t              rt        |      }|| _        yt        |d      rt        |      }|| _        y	 t	        |t
              r |       }|| _        y# t        $ r
 Y || _        yw xY w)a  Adds a global trading calendar to the system. Individual data feeds
        may have separate calendars which override the global one

        ``cal`` can be an instance of ``TradingCalendar`` a string or an
        instance of ``pandas_market_calendars``. A string will be will be
        instantiated as a ``PandasMarketCalendar`` (which needs the module
        ``pandas_market_calendar`` installed in the system.

        If a subclass of `TradingCalendarBase` is passed (not an instance) it
        will be instantiated
        )calendar
valid_daysN)ri   r   r   hasattr
issubclassr   	TypeErrorrc   )r&   cals     r*   addcalendarzCerebro.addcalendar6  s     c<(&4C  S,'&4C c#67%C   s   A% %	A87A8c                 B    | j                   j                  ||||f       y)zUAdds a signal to the system which will be later added to a
        ``SignalStrategy``N)rZ   rl   )r&   sigtypesigclssigargs	sigkwargss        r*   
add_signalzCerebro.add_signalP  s     	WfgyABr,   c                     |||f| _         y)z7Adds a SignalStrategy subclass which can accept signalsN)r[   )r&   stratclsr{   r'   s       r*   signal_strategyzCerebro.signal_strategyU  s    &f5r,   c                     || _         y)zyIf signals are added to the system and the ``concurrent`` value is
        set to True, concurrent orders will be allowedN)r\   r&   onoffs     r*   signal_concurrentzCerebro.signal_concurrentY  s     #(r,   c                     || _         y)zIf signals are added to the system and the ``accumulate`` value is
        set to True, entering the market when already in the market, will be
        allowed to increase a positionN)r]   r   s     r*   signal_accumulatezCerebro.signal_accumulate^  s     #(r,   c                 X    || j                   vr| j                   j                  |       yy)z8Adds an ``Store`` instance to the if not already presentN)rL   rl   )r&   stores     r*   addstorezCerebro.addstored  s%    #KKu% $r,   c                 @    | j                   j                  |||f       y)zkAdds an ``Writer`` class to the mix. Instantiation will be done at
        ``run`` time in cerebro
        N)rW   rl   )r&   wrtclsr{   r'   s       r*   	addwriterzCerebro.addwriteri  s     	VT623r,   c                 (    |||f| j                   d<   y)zoAdds a ``Sizer`` class (and args) which is the default sizer for any
        strategy added to cerebro
        NrV   )r&   sizerclsr{   r'   s       r*   addsizerzCerebro.addsizero  s     &tV4Dr,   c                 (    |||f| j                   |<   y)zAdds a ``Sizer`` class by idx. This idx is a reference compatible to
        the one returned by ``addstrategy``. Only the strategy referenced by
        ``idx`` will receive this size
        Nr   )r&   idxr   r{   r'   s        r*   addsizer_byidxzCerebro.addsizer_byidxu  s    
 %dF3Cr,   c                 @    | j                   j                  |||f       y)z
        Adds an ``Indicator`` class to the mix. Instantiation will be done at
        ``run`` time in the passed strategies
        N)rT   rl   )r&   indclsr{   r'   s       r*   addindicatorzCerebro.addindicator|  s    
 	f56r,   c                 @    | j                   j                  |||f       y)zk
        Adds an ``Analyzer`` class to the mix. Instantiation will be done at
        ``run`` time
        N)rS   rl   )r&   anclsr{   r'   s       r*   addanalyzerzCerebro.addanalyzer  s    
 	udF34r,   c                 B    | j                   j                  d|||f       y)zk
        Adds an ``Observer`` class to the mix. Instantiation will be done at
        ``run`` time
        FNr   rl   r&   obsclsr{   r'   s       r*   addobserverzCerebro.addobserver  s    
 	ufdF;<r,   c                 B    | j                   j                  d|||f       y)a>  
        Adds an ``Observer`` class to the mix. Instantiation will be done at
        ``run`` time

        It will be added once per "data" in the system. A use case is a
        buy/sell observer which observes individual datas.

        A counter-example is the CashValue, which observes system-wide values
        TNr   r   s       r*   addobservermultizCerebro.addobservermulti  s     	tVT6:;r,   c                 :    | j                   j                  |       y)a  Adds a callback to get messages which would be handled by the
        notify_store method

        The signature of the callback must support the following:

          - callback(msg, \*args, \*\*kwargs)

        The actual ``msg``, ``*args`` and ``**kwargs`` received are
        implementation defined (depend entirely on the *data/broker/store*) but
        in general one should expect them to be *printable* to allow for
        reception and experimentation.
        N)rX   rl   r&   callbacks     r*   
addstorecbzCerebro.addstorecb  s     	X&r,   c                 j    | j                   D ]  } ||g|i |   | j                  |g|i | y r!   )rX   notify_store)r&   msgr{   r'   r   s        r*   _notify_storezCerebro._notify_store  sC     	+HS*4*6*	+ 	#///r,   c                      y)au  Receive store notifications in cerebro

        This method can be overridden in ``Cerebro`` subclasses

        The actual ``msg``, ``*args`` and ``**kwargs`` received are
        implementation defined (depend entirely on the *data/broker/store*) but
        in general one should expect them to be *printable* to allow for
        reception and experimentation.
        Nr0   )r&   r   r{   r'   s       r*   r   zCerebro.notify_store       	r,   c                     | j                   D ]Z  }|j                         D ]E  }|\  }}} | j                  |g|i | | j                  D ]  } |j                  |g|i |  G \ y r!   )rL   get_notificationsr   runningstratsr   )r&   r   notifr   r{   r'   strats          r*   _storenotifyzCerebro._storenotify  s    [[ 	=E002 =$)!T6"""3888!// =E&E&&s<T<V<=	=	=r,   c                 :    | j                   j                  |       y)a  Adds a callback to get messages which would be handled by the
        notify_data method

        The signature of the callback must support the following:

          - callback(data, status, \*args, \*\*kwargs)

        The actual ``*args`` and ``**kwargs`` received are implementation
        defined (depend entirely on the *data/broker/store*) but in general one
        should expect them to be *printable* to allow for reception and
        experimentation.
        N)rY   rl   r   s     r*   	adddatacbzCerebro.adddatacb  s     	H%r,   c                     | j                   D ]\  }|j                         D ]G  }|\  }}} | j                  ||g|i | | j                  D ]  } |j                  ||g|i |  I ^ y r!   )rN   r   _notify_datar   notify_data)r&   datar   statusr{   r'   r   s          r*   _datanotifyzCerebro._datanotify  s    JJ 	ED//1 E',$f!!!$@@@!// EE%E%%dFDTDVDEE	Er,   c                 n    | j                   D ]  } |||g|i |   | j                  ||g|i | y r!   )rY   r   )r&   r   r   r{   r'   r   s         r*   r   zCerebro._notify_data  sG     	4HT63D3F3	4 	v777r,   c                      y)ak  Receive data notifications in cerebro

        This method can be overridden in ``Cerebro`` subclasses

        The actual ``*args`` and ``**kwargs`` received are
        implementation defined (depend entirely on the *data/broker/store*) but
        in general one should expect them to be *printable* to allow for
        reception and experimentation.
        Nr0   )r&   r   r   r{   r'   s        r*   r   zCerebro.notify_data  r   r,   c                 z   |||_         t        | j                        |_        |j	                  |        | j
                  j                  |       || j                  |j                   <   |j                         }|r)|| j                  vr| j                  j                  |       |j                         rd| _        |S )z
        Adds a ``Data Feed`` instance to the mix.

        If ``name`` is not None it will be put into ``data._name`` which is
        meant for decoration/plotting purposes.
        T)_namenextr`   _idsetenvironmentrN   rl   rP   getfeedrM   isliverH   )r&   r   namefeeds       r*   adddatazCerebro.adddata  s     DJ%D!

$'+$||~D

*JJd#;;=DLr,   c                     |j                  dd      }||d   j                  }t        j                  j                  |d|i}| j                  ||       |S )a  
        Chains several data feeds into one

        If ``name`` is passed as named argument and is not None it will be put
        into ``data._name`` which is meant for decoration/plotting purposes.

        If ``None``, then the name of the 1st data will be used
        r   Nr   datanamer   )pop	_datanamebtrM   Chainerr   r&   r{   r'   dnameds        r*   	chaindatazCerebro.chaindata  sV     

64(=G%%EHHd3e3QU#r,   c                     |j                  dd      }||d   j                  }t        j                  j                  |d|i|}| j                  ||       |S )aI  Chains several data feeds into one

        If ``name`` is passed as named argument and is not None it will be put
        into ``data._name`` which is meant for decoration/plotting purposes.

        If ``None``, then the name of the 1st data will be used

        Any other kwargs will be passed to the RollOver class

        r   Nr   r   r   )r   r   r   rM   RollOverr   r   s        r*   rolloverdatazCerebro.rolloverdata  s[     

64(=G%%EHHt>u>v>QU#r,   c                     t        fd| j                  D              rj                          j                  di | | j	                  |       d| _        S )aX  
        Adds a ``Data Feed`` to be replayed by the system

        If ``name`` is not None it will be put into ``data._name`` which is
        meant for decoration/plotting purposes.

        Any other kwargs like ``timeframe``, ``compression``, ``todate`` which
        are supported by the replay filter will be passed transparently
        c              3   &   K   | ]  }|u  
 y wr!   r0   .0xr   s     r*   	<genexpr>z%Cerebro.replaydata.<locals>.<genexpr>6       1x1}1   r   Tr0   )anyrN   clonereplayr   rI   r&   r   r   r'   s    `  r*   
replaydatazCerebro.replaydata,  sP     1djj11~~'H!&!XD)r,   c                     t        fd| j                  D              rj                          j                  di | | j	                  |       d| _        S )aZ  
        Adds a ``Data Feed`` to be resample by the system

        If ``name`` is not None it will be put into ``data._name`` which is
        meant for decoration/plotting purposes.

        Any other kwargs like ``timeframe``, ``compression``, ``todate`` which
        are supported by the resample filter will be passed transparently
        c              3   &   K   | ]  }|u  
 y wr!   r0   r   s     r*   r   z'Cerebro.resampledata.<locals>.<genexpr>I  r   r   r   Tr0   )r   rN   r   resampler   rI   r   s    `  r*   resampledatazCerebro.resampledata?  sR     1djj11~~'H#F#XD)r,   c                 :    | j                   j                  |       y)z
        Adds a *callback* to the list of callbacks that will be called with the
        optimizations when each of the strategies has been run

        The signature: cb(strategy)
        N)rR   rl   )r&   cbs     r*   optcallbackzCerebro.optcallbackR  s     	2r,   c                    d| _         | j                  |      }t        j                  | }t	        |      }| j                  |j                               }t        j                  | }t        t        t        j                  |      |      }t        t        |      }	t        j                  |g||	      }
| j                  j                  |
       y)aQ  
        Adds a ``Strategy`` class to the mix for optimization. Instantiation
        will happen during ``run`` time.

        args and kwargs MUST BE iterables which hold the values to check.

        Example: if a Strategy accepts a parameter ``period``, for optimization
        purposes the call to ``optstrategy`` looks like:

          - cerebro.optstrategy(MyStrategy, period=(15, 25))

        This will execute an optimization for values 15 and 25. Whereas

          - cerebro.optstrategy(MyStrategy, period=range(15, 25))

        will execute MyStrategy with ``period`` values 15 -> 25 (25 not
        included, because ranges are semi-open in Python)

        If a parameter is passed but shall not be optimized the call looks
        like:

          - cerebro.optstrategy(MyStrategy, period=(15,))

        Notice that ``period`` is still passed as an iterable ... of just 1
        element

        ``backtrader`` will anyhow try to identify situations like:

          - cerebro.optstrategy(MyStrategy, period=15)

        and will create an internal pseudo-iterable if possible
        TN)rJ   rp   r^   productrK   valuesr   r
   r   rU   rQ   rl   )r&   strategyr{   r'   optargsoptkeysvalsoptvalsokwargs1	optkwargsits              r*   optstrategyzCerebro.optstrategy[  s    B  ||D!##T*v,||FMMO,##T*sI,,W5w?h'	z7I>2r,   c                 p    | j                   j                  |||fg       t        | j                         dz
  S )aN  
        Adds a ``Strategy`` class to the mix for a single pass run.
        Instantiation will happen during ``run`` time.

        args and kwargs will be passed to the strategy as they are during
        instantiation.

        Returns the index with which addition of other objects (like sizers)
        can be referenced
        r   )rQ   rl   r   )r&   r	  r{   r'   s       r*   addstrategyzCerebro.addstrategy  s4     	XtV4564;;!##r,   c                 "    || _         | |_        |S )zz
        Sets a specific ``broker`` instance for this strategy, replacing the
        one inherited from cerebro.
        )ra   rb   )r&   brokers     r*   	setbrokerzCerebro.setbroker  s    
 r,   c                     | j                   S )zw
        Returns the broker instance.

        This is also available as a ``property`` by the name ``broker``
        )ra   rg   s    r*   	getbrokerzCerebro.getbroker  s     ||r,   c                 p   | j                   dkD  ry|sAddlm} | j                  j                  r |j
                  di |}n |j                  di |}g }| j                  D ]Q  }t        |      D ]1  \  }}|j                  ||dz  |||||
      }|j                  |       3 |j                          S |S )aY  
        Plots the strategies inside cerebro

        If ``plotter`` is None a default ``Plot`` instance is created and
        ``kwargs`` are passed to it during instantiation.

        ``numfigs`` split the plot in the indicated number of charts reducing
        chart density if wished

        ``iplot``: if ``True`` and running in a ``notebook`` the charts will be
        displayed inline

        ``use``: set it to the name of the desired matplotlib backend. It will
        take precedence over ``iplot``

        ``start``: An index to the datetime line array of the strategy or a
        ``datetime.date``, ``datetime.datetime`` instance indicating the start
        of the plot

        ``end``: An index to the datetime line array of the strategy or a
        ``datetime.date``, ``datetime.datetime`` instance indicating the end
        of the plot

        ``width``: in inches of the saved figure

        ``height``: in inches of the saved figure

        ``dpi``: quality in dots per inches of the saved figure

        ``tight``: only save actual content and not the frame of the figure
        r   Nr   )plotd   )figidnumfigsiplotstartenduser0   )
_exactbars r  r"   rA   Plot_OldSyncPlot	runstrats	enumeraterl   show)r&   plotterr  r  r  r   widthheightdpitightr!  r'   r  figs	stratlistsir   rfigs                     r*   r  zCerebro.plot  s    D ??Qvv~~+$++5f5#$))-f-  		I&y1 "	E||Ec,35*/Sc $ C
 D!" LLN		 r,   c                     | j                   j                  xr | j                  xr | j                  }| j	                  ||      S )zw
        Used during optimization to pass the cerebro over the multiprocesing
        module without complains
        )predata)r"   r;   
_dopreload
_dorunoncerunstrategies)r&   	iterstratr3  s      r*   __call__zCerebro.__call__  s9     &&//IdooI$//!!)W!==r,   c                 F    t        |       j                         }d|v r|d= |S )z
        Used during optimization to prevent optimization result `runstrats`
        from being pickled to subprocesses
        r&  )varscopy)r&   rvs     r*   __getstate__zCerebro.__getstate__  s(     $Z__";	r,   c                     d| _         y)zIf invoked from inside a strategy or anywhere else, including other
        threads the execution will stop as soon as possible.TN)_event_stoprg   s    r*   runstopzCerebro.runstop  s      r,   c                    d| _         | j                  sg S | j                  j                         }|j	                         D ]!  \  }}||v st        | j                  ||       # t        j                  j                          t        j                  j                          t        j                  j                  | j                  j                         t        j                  j                  | j                  j                         | j                  j                  | _        | j                  j                   | _        t%        | j                  j&                        | _        | j(                  r)d| _        | j"                  xr | j(                  dk  | _        | j*                  xs t-        d | j                  D              | _        | j*                  rd| _        | j.                  s| j                  j0                  rd| _        d| _        t3               | _        | j                  j6                  du r%t9               }| j4                  j;                  |       | j<                  D ])  \  }}} ||i |}| j4                  j;                  |       + t-        t?        d | j4                              | _         t3               | _!        | jD                  r| jF                  \  }	}
}|	R	 | jH                  jK                  d      \  }	}
}tM        |	tN              s"| jH                  jQ                  d|	|
|f       d}		 |	tN        tU               tW               }}
}	 | jX                  |	g|
| jZ                  | j\                  | jD                  d| | jH                  s| jY                  t^               ta        jb                  | jH                   }| jd                  r| j                  jf                  dk(  r[|D ]T  }| ji                  |      }| jB                  j;                  |       | jd                  s<| jj                  D ]
  } ||        V n| j                  jl                  r| j"                  r| j                  r| j                  D ]t  }|jo                          | j(                  dk  r&|jq                  | j                  jr                  	       |ju                          | j"                  se|j!                          v tw        jx                  | j                  jf                  xs d      }|j{                  | |      D ]6  }| jB                  j;                  |       | jj                  D ]
  } ||        8 |j}                          | j                  jl                  r9| j"                  r-| j                  r!| j                  D ]  }|j                           | jd                  s| jB                  d   S | jB                  S # tR        $ r Y w xY w)
a)  The core method to perform backtesting. Any ``kwargs`` passed to it
        will affect the value of the standard parameters ``Cerebro`` was
        instantiated with.

        If ``cerebro`` has not datas the method will immediately bail out.

        It has different return values:

          - For No Optimization: a list contanining instances of the Strategy
            classes added with ``addstrategy``

          - For Optimization: a list of lists which contain instances of the
            Strategy classes added with ``addstrategy``
        Fr   c              3   4   K   | ]  }|j                     y wr!   	replaying)r   r   s     r*   r   zCerebro.run.<locals>.<genexpr>.  s     .Oqq{{.O   Tc                 .    | j                   j                  S r!   )r"   csvr   s    r*   <lambda>zCerebro.run.<locals>.<lambda>F  s    QSSWW r,   Nr   )_accumulate_concurrentrZ   size)@r?  rN   r#   _getkeysr$   r%   r   LineActions
cleancacher   	Indicatorusecacher"   r=   r4   r5  r3   r4  intr:   r"  rI   r   rH   r>   rK   
runwritersr?   r   rl   rW   r   writers_csvr&  rZ   r[   rQ   r   ri   r   insert
IndexErrortuplerU   r  r]   r\   r   r^   r  rJ   r5   r6  rR   r;   resetextendr9   _startmultiprocessingPoolimapclosestop)r&   r'   pkeyskeyvalwrwrclswrargswrkwargssignalstsargsskwargs
iterstratsr7  runstratr  r   poolrs                      r*   runzCerebro.run  s    !zzI$$& 	/HCe|S#.	/
 	))+&&(''8$$TVV__5&&..&&..dff../??#DO"ooE$//A2EDOO3.ODJJ.O+O>> $DO<<466;;#DO#DO& 66==D BOO""2& (,|| 	'#E68+(+BOO""2&	'
 s#4dooFG<<'+'9'9$HeW(/3{{q/A,HeW &h?**1x.HI#'+957DF% DX ( $	()-)@)@)-)@)@%)\\(
  '( {{X&&&4
466>>Q#6 ( %	--i8%%h/##"kk %8%	% vv4??t JJ 'DJJL*)>)>?KKM' #''(>$?DYYtZ0 %%a(++ BqE
 JJLvv4??t JJ  DIIK  >>!$$~~w " s   W/ /	W<;W<c                 8    t        j                  d      | _        y )Nr   )r^   r_   stcountrg   s    r*   _init_stcountzCerebro._init_stcount  s     q)r,   c                 ,    t        | j                        S r!   )r   rq  rg   s    r*   
_next_stidzCerebro._next_stid  s    DLL!!r,   c                    | j                          t               x| _        }| j                  D ]  }|j	                           | j
                  j                  rG| j
                  j                  r1t        | j                  d      r| j                  j                  d       | j                  %| j                  j                  | j                         | j                  D ]!  \  }}| j                  j                  ||       # | j                  j	                          | j                  D ]  }|j	                           | j                   rt               }| j"                  D ].  }	|	j$                  s|j'                  |	j)                                0 | j*                  D ]*  }
|
j
                  j$                  s|
j-                  |       , |s| j"                  D ]t  }	|	j/                          | j0                  dk  r&|	j'                  | j2                  j4                         |	j7                          | j8                  se|	j;                          v |D ]{  \  }}}| j"                  t        |      z   }	  ||i |}| j
                  jB                  rd|_"        | j
                  jF                  r|jI                          |jK                  |       } | j
                  jL                  }tO        |tP              r| j"                  |   jR                  }ntU        |      }|r| jV                  jY                  dd      }t[        |      D ]'  \  }}| j
                  j\                  r|j_                  dt`        jb                         | j
                  jd                  r!|j_                  dt`        jf                         n"|j_                  dt`        jf                  d       | j
                  jh                  stk        | j"                        dk(  r!|j_                  dt`        jl                         n |j_                  dt`        jn                         | j`                  D ]  \  }}}} |j^                  ||g|i |   | jp                  D ]  \  }}} |jr                  |g|i |  | jt                  D ]  \  }}} |jv                  |g|i |  | jV                  jY                  ||      \  }}}| |jx                  |g|i | |j{                  |       |j7                          | j*                  D ]8  }
|
j
                  j$                  s|
j-                  |j)                                : * |s.|D ])  }|j}                  | j0                  | j~                  	       + | j*                  D ]  }
|
j	                           g | _@        g | _A        | j                  D ]m  }|j	                  | j"                  d
          |j2                  j                  r| j                  jK                  |       S| j                  jK                  |       o | j8                  rF| j                  r:| j
                  jB                  r| j                  |       nK| j                  |       n9| j
                  jB                  r| j                  |       n| j                  |       |D ]  }|j                           | j                  j                          |s!| j"                  D ]  }	|	j                           | j                  D ]  }|j                           | j                  D ]  }|j                           | j                  |       | j                  r| j
                  j                  rt               }|D ]  }|jt                  D ]?  }d|_N        d|_O        t        |      D ]!  } | j                  d      st        || d       # A t        |j2                  |jt                  t        |            }!|jK                  |!        |S |S # t<        j>                  j@                  $ r Y w xY w)zP
        Internal method invoked by ``run``` to run a set of strategies
        set_cooTNr   rL  rG   F)barplotrC  r   r   )rS   strategycls)Urr  rK   r   rL   r  r"   rC   rD   r   ra   rv  rf   rs   re   rw   rM   rU  rN   rG  rZ  getwriterheadersrT  
addheadersrY  r"  r#   r9   r[  r4  r3   r   errorsStrategySkipErrorrA   _oldsyncr@   set_tradehistoryrl   rB   ri   r   _tzr   rV   getr'  r6   _addobserverr   Brokerr7   BuySellr8   r   Trades
DataTradesrT   _addindicatorrS   _addanalyzer	_addsizer_settzqbufferrI   _timers_timerscheatrd   r   r5  _runonce_old_runonce_runnext_old_runnext_stopr`  stop_writersrJ   r<   r	  _parentdir
startswithr%   r   type)"r&   r7  r3  r&  r   ru   onotifyr   wheadersr   r?   r   ri  rj  r   rB   defaultsizerr   multir   obsargs	obskwargsr   indargs	indkwargsr   anargsankwargssizerry   resultsaattrnameoreturns"                                     r*   r6  zCerebro.runstrategies  s    	)-/Y[[ 	EKKM	 66DFF$5$5t||Y/$$T*>>%LL))$..9#~~ 	<OFGLL**67;	< 	JJ 	DJJL	 vH

 =88OOD$9$9$;<= // 088<<%%h/0 

 #

??Q&KKT[[%:%:K;??LLN# )2 	$$HeWJJe,E %373 vv~~!%vv""&&(U#	$ VVYYb-(B##BB;;??41CDL'	2  D
U66??&&ui.>.>?vv((**41B1BC**41B1B37 + 9 vv''3tzz?a+?**5)2B2BC**5)2F2FG9= M5E67I&E&&ufLwL)LM 37// G.FGY'E''FFIFG 04~~ C+E68&E&&uBvBBC )-\(J%ug$#EOOE=E=W=R "oo DFxx||))%*@*@*BCD= DD & MEMM$//T^^MLM //  DL "D /DJJqM*<<%%%%,,U3LL''./ 4??66>>%%i0MM),66>>%%i0MM),"  	

 		 JJ 	DIIK	 [[ 	EJJL	 	)$ 0 0fG" 	( 7A!%AJ $AI$'F 7#..v6#Ax677 $ELLEOOY]^cYdew'	( Ng 99.. s   /`;;aac                    t               }t               }t        | j                        D ]  \  }}|j                         |d|z  <    ||d<   t	               }|D ]+  }|j
                  j                  }|j                         ||<   - ||d<   | j                  D ]-  }	|	j                  t	        |             |	j                          / y )NzData%dDatas
Strategies)r2   )
r   r'  rN   getwriterinforU   	__class__r-   rT  	writedictr`  )
r&   r&  cerebroinfo	datainfosir   
stratinfosr   stnamer?   s
             r*   r  zCerebro.stop_writers<  s    !mM	 , 	;GAt&*&8&8&:Ihl#	;  )GV
 	7E__--F!&!4!4!6Jv	7 %/L!oo 	FT+67KKM	r,   c                     | j                   j                          	 | j                   j                         }|y|j                  }|| j                  d   }|j                  || j                  j                         b)zu
        Internal method which kicks the broker and delivers any broker
        notification to the strategy
        Nr   )rE   )ra   r   get_notificationr   r   _addnotificationr"   rE   )r&   orderr   s      r*   _brokernotifyzCerebro._brokernotifyP  sq    
 	LL113E}KKE}**1-""5dff6H6H"I r,   c                    | j                   d   }d}|s|d}| j                          | j                  ry| j                          | j                  ry|j	                         }|rL| j                   dd D ]9  }|j	                  |      r|j                  |       |j	                  |       ; ns|5|j                          | j                   dd D ]  }|j                           n<|j                         }| j                   dd D ]  }||j                  |      z  } |sn|| j                          | j                  ry| j                          | j                  ry|s|r6|D ]1  }|j                          | j                  r y| j                  |       3 |r|| j                          | j                  ry| j                          | j                  ryy)
        Actual implementation of run in full next mode. All objects have its
        ``next`` method invoke on each data arrival
        r   TNFr   
datamaster	forcedata)
rN   r   r?  r   r   _check_lastr  _next_next_writers)r&   r&  data0d0retlastretr   r   s          r*   r  zCerebro._runnext_olda  s   
 

1u}G JJLE JJqrN 4D9996e4		U	34
   JJqrN "DKKM"  ++- JJqrN <DtzzUz;;G<   & 2EKKM''&&y12Y u}h 	 r,   c                    |D ]  }|j                           | j                  d   }| j                  dd }t        |j                               D ]  }|j	                          |D ]  }|j	                  |        | j                          | j                  r y|D ]@  }|j                  |j                  d          | j                  r  y| j                  |       B  y)z
        Actual implementation of run in vector mode.
        Strategies are still invoked on a pseudo-event mode in which ``next``
        is called for each data arrival
        r   r   Nr  )
_oncerN   r	   buflenadvancer  r?  	_oncepostdatetimer  )r&   r&  r   r  rN   r  r   s          r*   r  zCerebro._runonce_old  s      	EKKM	 

1

12u||~& 	.AMMO /./  " .q 12##""9-.	.r,   c                    | j                   sy | j                  rt               }| j                  D ].  }|j                  s|j                  |j                                0 |D ]!  }|j                  |j                                # | j                   D ]:  }|j                  j                  s|j                  |       |j                          < y y r!   )
rT  rU  rK   rN   rG  rZ  getwritervaluesr"   	addvaluesr   )r&   r&  wvaluesr   r   r?   s         r*   r  zCerebro._next_writers  s    fG

 ;88NN4#7#7#9:; # 8u44678 // "88<<$$W-KKM	" r,   c                     d| _         y)z9API for lineiterators to disable runonce (see HeikinAshi)FN)r5  rg   s    r*   _disable_runoncezCerebro._disable_runonce  s	    r,   c                 
    t        | j                  d       }|dd }|d   }d}t        |      D cg c]  \  }}|j                  s| }}}t        |      D cg c]  \  }}|j                  s| }	}}t        |      D cg c]  \  }}|j                  r|j                  s|! c}} t        |      t               k(  }
  }t        d |D              }t        |      }||z
  }d}t        t        j                  j                        d	z
  }|s|t        d
 |D               }|st        d |D              }| xs ||k(  }d}| j                          | j                  ry| j                          | j                  ryg }t        j                  j                         }|D ]d  }t        j                  j                         |z
  }|j                  ||j!                                |j#                  |j%                  d             f t        d |D              }|st        d |D              rd}|rQg }t        |      D ]*  \  }}|j#                  |r||   j                  d   nd       , |
s|rt'        d |D              }nt'         fdt        |      D              }||j)                  |         }|j+                  |      | _        t+        |      | _        t        |      D ]E  \  }}|r	||   }|j1                  |       |j%                  |d      r|j                  d   ||<   FG t        |      D ]G  \  }}|	||   }d}||kD  r|r|j3                          )|j                  r6|j5                  d       I nI||D ]  }|j1                           n/|j7                         }|D ]  }||j7                  |      z  } |sn| j                          | j                  ry|s|rO| j9                  ||d       | j:                  j<                  r%|D ]   }|j?                          | j                  s  y | jA                          | j                  ry|s|rJ| j9                  ||d       |D ]1  }|jC                          | j                  r y| jE                  |       3 |r|| j                          | j                  ry| j                          | j                  ryyc c}}w c c}}w c c}}w )r  c                 2    | j                   | j                  fS r!   
_timeframe_compressionrH  s    r*   rI  z"Cerebro._runnext.<locals>.<lambda>      allANN%C r,   rb  r   Nr   Tc              3   4   K   | ]  }|j                     y wr!   )_cloner   r   s     r*   r   z#Cerebro._runnext.<locals>.<genexpr>  s     1a1rE  F   c              3   <   K   | ]  }|j                           y wr!   )haslivedatar  s     r*   r   z#Cerebro._runnext.<locals>.<genexpr>  s     ?A?s   c              3   N   K   | ]  }|j                   |j                  k(    y wr!   )_laststatusLIVEr  s     r*   r   z#Cerebro._runnext.<locals>.<genexpr>  s     GA 7Gs   #%)ticksc              3       K   | ]  }|  y wr!   r0   r   drets     r*   r   z#Cerebro._runnext.<locals>.<genexpr>  s     0$0s   c              3   $   K   | ]  }|d u  
 y wr!   r0   r  s     r*   r   z#Cerebro._runnext.<locals>.<genexpr>  s     !A4$$,!As   c              3   &   K   | ]	  }||  y wr!   r0   r  s     r*   r   z#Cerebro._runnext.<locals>.<genexpr>  s     ?Qq?s   c              3   4   K   | ]  \  }}||vr|  y wr!   r0   )r   r  r   rsonlys      r*   r   z#Cerebro._runnext.<locals>.<genexpr>  s)      ETQ"#-AVO  ! Es   r  )r  r  )forcer  r   )#sortedrN   r'  
resamplingrD  r   sumr   r  maxr   r   r?  r   utcnow	do_qchecktotal_secondsrl   r   minindexr   	_dtmaster
_udtmasterr  rewind
_tick_fillr  _check_timersr"   rC   
_next_openr  r  r  )!r&   r&  rN   datas1r  r  r  r   rsrponlyresample
noresample
clonecountldatasldatas_noclones
lastqcheckdt0	newqcheck	livecountr  dretsqstartr   qlapsedtsretdmasterdtidirpir   r   r  s!                                   @r*   r  zCerebro._runnext  s   
 tzzCEqra%e,=DAqa==%e,<DAqa<< )% 0 71\\!++  75zS[0Z
1511
U :-
x((,,-1u}????I  GGG	 )MIY/-I	G  E&&--/F 2!**113f<Iv';';'=>QVV%V012
 0%01ES!A5!AB'. FFAsJJsuQx003EF  :?#?@C EYs^ E FC  		#/!(!1!1#!6"*3- (. FAs  aAHHwH/vvv>!"AA  (n 
6FAs"1X#9#& "		!#MMM5
6  " "DKKM"  ++-" <DtzzUz;;G<  ""9c">66''!* #((*++"#
  ""9c"?& 2EKKM''&&y12c u}r 	 S ><7s   S2	S2S83S8$S>c                    |D ]"  }|j                          |j                          $ t        | j                  d       }	 |D cg c]  }|j	                          }}t        |      }|t        d      k(  ryt        |d         }t        |      D ]  \  }}	|	|k  r||   j                            | j                  ||d       | j                  j                  r%|D ]   }|j                          | j                  s  y | j                          | j                  ry| j                  ||d       |D ]2  }|j!                  |       | j                  r y| j#                  |       4 *c c}w )	z
        Actual implementation of run in vector mode.

        Strategies are still invoked on a pseudo-event mode in which ``next``
        is called for each data arrival
        c                 2    | j                   | j                  fS r!   r  rH  s    r*   rI  z"Cerebro._runonce.<locals>.<lambda>  r  r,   r  Tinfr   r  NF)r  rY  r  rN   advance_peekr  floatr   r'  r  r  r"   rC   _oncepost_openr?  r  r  r  )
r&   r&  r   rN   r   r  r  slenr  r
  s
             r*   r  zCerebro._runonceq  sm     	EKKMKKM	 tzzCE -231>>#3C3c(CeEl" y|$D#C. 3#:!H$$&  y#T:vv##& E((*''
  y#U;" .$##""9-.A 3s   E+c                    |s| j                   n| j                  }|D ]  }|j                  |      s |j                  j                  j
                  ||j                  g|j                  i |j                   |j                  j                  su|D ]7  } |j
                  ||j                  g|j                  i |j                   9  y r!   )
r  r  checkr#   r   r|   lastwhenr{   r'   rQ   )r&   r&  r  r   timerstr   s          r*   r  zCerebro._check_timers  s    %*0A0A 	KA773<'AHHNN''1::KK!((Kxx& KE&E&&q!**JqvvJJK	Kr,   )Tr!   )
Nr   TNN   	   i,  TN)F)Br-   r.   r/   __doc__r#   r+   staticmethodrp   rs   rw   r|   r  	timedeltar   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r  propertyr  r  r8  r=  r@  ro  rr  rt  r6  r  r  r  r  r  r  r  r  r  r0   r,   r*   r2   r2   <   s   SjF,B  0'0R	 -(,,.7Ix7I7I7K%DuE4 ,++-6Hh6H6H6J4e5aF*4C
6(
(&
45475=
<'0
=&E8
0"&&&/b$ i+FHL:>>@>	 
EN*"gR(J"@D.@"& Un7.r
Kr,   r2   )0
__future__r   r   r   r   r  rO   r^   r\  abcrj   AttributeError
backtraderr   	utils.py3r   r	   r
   r   r   r   r#  r   r   brokersr   metabaser   r   r?   r   utilsr   r   r   r   r	  r   r   
tradingcalr   r   r   ry   r   objectr   r2   r0   r,   r*   <module>r)     s   ** *    ! __N ' '        ; ; ./ / 
   xKnZ0 xK;  ! N!s   B$ $B.-B.