
    'i.k                         d dl mZmZmZm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mZmZmZ d dlmZ d dlmZ  G d d	e	j,                        Z G d
 d eee	            Zy)    )absolute_importdivisionprint_functionunicode_literalsN)DataBase)	TimeFramedate2numnum2date)integer_typesqueuestring_typeswith_metaclass)
MetaParams)ibstorec                        e Zd Z fdZ xZS )
MetaIBDatac                 Z    t         t        |   |||       | t        j                  _        y)z+Class has already been created ... registerN)superr   __init__r   IBStoreDataCls)clsnamebasesdct	__class__s       U/var/www/app/trading-bot/venv/lib/python3.12/site-packages/backtrader/feeds/ibdata.pyr   zMetaIBData.__init__$   s&     	j#'eS9 #&    )__name__
__module____qualname__r   __classcell__r   s   @r   r   r   #   s    & &r   r   c                        e Zd ZdZdZej                  Zej                  dfZ
 ed      \  ZZZZZd Zd Zd Zd Z fdZd	 Z fd
Z fdZd Zd Zd Zd Zd ZddZd Z xZ S )IBDataa:  Interactive Brokers Data Feed.

    Supports the following contract specifications in parameter ``dataname``:

          - TICKER  # Stock type and SMART exchange
          - TICKER-STK  # Stock and SMART exchange
          - TICKER-STK-EXCHANGE  # Stock
          - TICKER-STK-EXCHANGE-CURRENCY  # Stock

          - TICKER-CFD  # CFD and SMART exchange
          - TICKER-CFD-EXCHANGE  # CFD
          - TICKER-CDF-EXCHANGE-CURRENCY  # Stock

          - TICKER-IND-EXCHANGE  # Index
          - TICKER-IND-EXCHANGE-CURRENCY  # Index

          - TICKER-YYYYMM-EXCHANGE  # Future
          - TICKER-YYYYMM-EXCHANGE-CURRENCY  # Future
          - TICKER-YYYYMM-EXCHANGE-CURRENCY-MULT  # Future
          - TICKER-FUT-EXCHANGE-CURRENCY-YYYYMM-MULT # Future

          - TICKER-YYYYMM-EXCHANGE-CURRENCY-STRIKE-RIGHT  # FOP
          - TICKER-YYYYMM-EXCHANGE-CURRENCY-STRIKE-RIGHT-MULT  # FOP
          - TICKER-FOP-EXCHANGE-CURRENCY-YYYYMM-STRIKE-RIGHT # FOP
          - TICKER-FOP-EXCHANGE-CURRENCY-YYYYMM-STRIKE-RIGHT-MULT # FOP

          - CUR1.CUR2-CASH-IDEALPRO  # Forex

          - TICKER-YYYYMMDD-EXCHANGE-CURRENCY-STRIKE-RIGHT  # OPT
          - TICKER-YYYYMMDD-EXCHANGE-CURRENCY-STRIKE-RIGHT-MULT  # OPT
          - TICKER-OPT-EXCHANGE-CURRENCY-YYYYMMDD-STRIKE-RIGHT # OPT
          - TICKER-OPT-EXCHANGE-CURRENCY-YYYYMMDD-STRIKE-RIGHT-MULT # OPT

    Params:

      - ``sectype`` (default: ``STK``)

        Default value to apply as *security type* if not provided in the
        ``dataname`` specification

      - ``exchange`` (default: ``SMART``)

        Default value to apply as *exchange* if not provided in the
        ``dataname`` specification

      - ``currency`` (default: ``''``)

        Default value to apply as *currency* if not provided in the
        ``dataname`` specification

      - ``historical`` (default: ``False``)

        If set to ``True`` the data feed will stop after doing the first
        download of data.

        The standard data feed parameters ``fromdate`` and ``todate`` will be
        used as reference.

        The data feed will make multiple requests if the requested duration is
        larger than the one allowed by IB given the timeframe/compression
        chosen for the data.

      - ``what`` (default: ``None``)

        If ``None`` the default for different assets types will be used for
        historical data requests:

          - 'BID' for CASH assets
          - 'TRADES' for any other

        Use 'ASK' for the Ask quote of cash assets
        
        Check the IB API docs if another value is wished

      - ``rtbar`` (default: ``False``)

        If ``True`` the ``5 Seconds Realtime bars`` provided by Interactive
        Brokers will be used as the smalles tick. According to the
        documentation they correspond to real-time values (once collated and
        curated by IB)

        If ``False`` then the ``RTVolume`` prices will be used, which are based
        on receiving ticks. In the case of ``CASH`` assets (like for example
        EUR.JPY) ``RTVolume`` will always be used and from it the ``bid`` price
        (industry de-facto standard with IB according to the literature
        scattered over the Internet)

        Even if set to ``True``, if the data is resampled/kept to a
        timeframe/compression below Seconds/5, no real time bars will be used,
        because IB doesn't serve them below that level

      - ``qcheck`` (default: ``0.5``)

        Time in seconds to wake up if no data is received to give a chance to
        resample/replay packets properly and pass notifications up the chain

      - ``backfill_start`` (default: ``True``)

        Perform backfilling at the start. The maximum possible historical data
        will be fetched in a single request.

      - ``backfill`` (default: ``True``)

        Perform backfilling after a disconnection/reconnection cycle. The gap
        duration will be used to download the smallest possible amount of data

      - ``backfill_from`` (default: ``None``)

        An additional data source can be passed to do an initial layer of
        backfilling. Once the data source is depleted and if requested,
        backfilling from IB will take place. This is ideally meant to backfill
        from already stored sources like a file on disk, but not limited to.

      - ``latethrough`` (default: ``False``)

        If the data source is resampled/replayed, some ticks may come in too
        late for the already delivered resampled/replayed bar. If this is
        ``True`` those ticks will bet let through in any case.

        Check the Resampler documentation to see who to take those ticks into
        account.

        This can happen especially if ``timeoffset`` is set to ``False``  in
        the ``IBStore`` instance and the TWS server time is not in sync with
        that of the local computer

      - ``tradename`` (default: ``None``)
        Useful for some specific cases like ``CFD`` in which prices are offered
        by one asset and trading happens in a different onel

        - SPY-STK-SMART-USD -> SP500 ETF (will be specified as ``dataname``)

        - SPY-CFD-SMART-USD -> which is the corresponding CFD which offers not
          price tracking but in this case will be the trading asset (specified
          as ``tradename``)

    The default values in the params are the to allow things like ```TICKER``,
    to which the parameter ``sectype`` (default: ``STK``) and ``exchange``
    (default: ``SMART``) are applied.

    Some assets like ``AAPL`` need full specification including ``currency``
    (default: '') whereas others like ``TWTR`` can be simply passed as it is.

      - ``AAPL-STK-SMART-USD`` would be the full specification for dataname

        Or else: ``IBData`` as ``IBData(dataname='AAPL', currency='USD')``
        which uses the default values (``STK`` and ``SMART``) and overrides
        the currency to be ``USD``
    ))sectypeSTK)exchangeSMART)currency )rtbarF)
historicalF)whatN)useRTHF)qcheckg      ?)backfill_startT)backfillT)backfill_fromN)latethroughF)	tradenameN   c                 6    | j                   j                         S N)ib
timeoffsetselfs    r   _timeoffsetzIBData._timeoffset   s    ww!!##r   c                    t        | j                  j                  t              }| j                  j                  ?|s=t        j
                  j                  j                  | j                  j                        S | j                  y 	 dd l	}|r| j                  j                  n| j                  j                  }|dk(  rd}	 |j                  |      }|S # t        $ r Y y w xY w# |j                  $ r Y y w xY w)Nr   CSTCST6CDT)
isinstanceptzr   btutilsdate	LocalizercontractdetailspytzImportErrorm_timeZoneIdtimezoneUnknownTimeZoneError)r<   tzstrrI   tzsrC   s        r   _gettzzIBData._gettz   s     46699l36699 88==**4669955'	 !dffiid&:&:&G&G%<C	s#B
 	  		 (( 		s$   C C$ 	C! C!$C65C6c                 0    | j                   j                   S )z`Returns ``True`` to notify ``Cerebro`` that preloading and runonce
        should be deactivated)rB   r-   r;   s    r   islivezIBData.islive   s     66$$$$r   c                      | j                   di || _        | j                  | j                  j                        | _        | j                  | j                  j                        | _        y )N )_storer9   parsecontractrB   datanameprecontractr5   pretradecontract)r<   kwargss     r   r   zIBData.__init__  sO    $++''--dffoo> $ 2 24663C3C Dr   c                 b    t         t        |   |       |j                  | j                         y)zWReceives an environment (cerebro) and passes it over to the store it
        belongs toN)r   r%   setenvironmentaddstorer9   )r<   envr   s     r   r\   zIBData.setenvironment	  s$     	fd*3/TWWr   c           
      .   |y| j                   j                  }| j                   j                  }d}d}d}d}t        |j	                  d            }t        |      }		 t        |      }
|
j                         r|
}t        |
      dk(  rd}
nd}
|
dk(  r|	j	                  d	      \  }	}	 t        |      }t        |      }|
dk(  r>|st        |      }t        |      }t        |      }d
}
t        |      d}}t        |      }n<|
dk(  r7|st        |      }t        t        |            }t        |      }t        |      }| j                  j                  |	|
||||||      }|S # t        $ r | j                   j                  }
Y w xY w# t        $ r Y Vw xY w)z,Parses dataname generates a default contractNr+   g        -   FUTOPTCASH.FOP)symbolr&   exchcurrexpirystrikerightmult)rB   r(   r*   itersplitnextStopIterationr&   isdigitlenfloatr9   makecontract)r<   rW   rh   ri   rj   rk   rl   rm   tokensrg   r&   precons               r   rV   zIBData.parsecontract  s    vvvv hnnS)* f	%6lG
 ??F7|q f!<<,LFD	<D<D%!&\FF| V$T{BF|E!!&\FtF|,VF| %%7D&D & B c  	%ffnnG	%R  		s%   E" (BF "FF	FFc                    t         t        |           | j                  j                  |       | _        d| _        | j                  j                   | _        | j                  | j                  f}|| j                  k  rd| _        d| _        d| _        d| _        d| _        | j                  j                   e| j"                  | _        | j                  j                   j'                  | j(                         | j                  j                   j+                          n| j,                  | _        d| _        d| _        t3               | _        | j                  j7                         sy| j9                  | j:                         | j                  j=                  | j>                  d      }|2|d   }|j@                  jB                  | _        |j@                  | _        n| j9                  | jD                         y| jF                  #| j                  | _        | j                  | _        nw| j                  j=                  | jF                  d      }|2|d   }|j@                  jB                  | _        |j@                  | _        n| j9                  | jD                         y| j$                  | j,                  k(  r!| jI                          | jK                          yy)z]Starts the IB connecction and gets the real contract and
        contractdetails if it exists)dataNTF   )maxcountr   )&r   r%   startr9   qliveqhistrB   r,   	_usertvol
_timeframe_compressionRTBAR_MINSIZEcontractrH   tradecontracttradecontractdetailsr3   _ST_FROM_stater\   _env_start	_ST_START_statelivereconn_subcription_validdict
_storedmsg	connectedput_notification	CONNECTEDgetContractDetailsrX   contractDetails	m_summaryDISCONNECTEDrY   _start_finish	_st_start)r<   tfcompcdscdetailsr   s       r   r|   zIBData.startV  sA    	fd!#WW]]]-

!VV\\)//4#4#45D&&&!DN#!$(!66+--DKFF  //		:FF  '')..DK %"'&ww  "dnn-gg(()9)9A(F?1vH$44>>DM#+#;#;D  !!$"3"34  (!%D(,(<(<D% '',,T-B-BQ,OCq6%-%=%=%G%G",4,D,D) %%d&7&78;;$..( NN )r   c                 ^    t         t        |           | j                  j                          y)z!Stops and tells the store to stopN)r   r%   stopr9   )r<   r   s    r   r   zIBData.stop  s    fd "r   c                 F   | j                   | j                  ry| j                  r@| j                  j	                  | j                   | j
                  j                        | _        n*| j                  j                  | j                         | _        d| _        | j                  S )z@request real-time data. checks cash vs non-cash) and param useRTNT)	r   r   r   r9   
reqMktDatarB   r.   r}   reqRealTimeBarsr;   s    r   reqdatazIBData.reqdata  sn    == D$;$;>>++DMM466;;GDJ00?DJ"&zzr   c                     | j                   y| j                  r&| j                  j                  | j                         y| j                  j                  | j                         y)z?Cancels Market Data subscription, checking asset type and rtbarN)r   r   r9   cancelMktDatar}   cancelRealTimeBarsr;   s    r   
canceldatazIBData.canceldata  sB    == >>GG!!$**-GG&&tzz2r   c                 H    t        | j                  xs | j                        S r8   )boolr   r}   r;   s    r   haslivedatazIBData.haslivedata  s    DOO1tzz22r   c                    | j                   | j                  | j                  k(  ry	 | j                  | j                  k(  r	 | j                  j                  d d       xs& | j                  j                  | j                        }|vd| _        | j;                  | j@                         | j"                  jC                  d      s| j;                  | jD                         y| j*                  jF                  | _        |dk(  r| j;                  | jH                         y|d	k(  r$d| _        | j*                  jF                  | _        "|d
k(  r)| j                  s| j*                  jF                  | _        P|dk(  r@d| _        | j                  s+| j*                  jF                  | _        | jK                          |dk(  r@d| _        | j                  s+| j*                  jF                  | _        | jK                          tM        |tN              r| j;                  | jP                  |       | j                  s| j6                  | jR                  k7  r8| j                  jU                         dk  r| j;                  | jR                         | jV                  r| jY                  |      }n| j[                  |      }|ry|| j                  d <   | j6                  | j8                  k7  r| j;                  | j8                         d }t!        |       dkD  rt        | j                  d         }n0| j\                  t_        d      kD  rt        | j\                        }nd }| jV                  r|j                  n|j`                  }| j"                  j%                  | j                   ||| j&                  | j(                  | j*                  j,                  | j*                  j.                  | j0                  | j*                  j2                  	      | _        | j<                  | _        d| _         | j                  | j<                  k(  r$| j4                  j                         }|#d| _        | j;                  | jD                         y|dk(  r#d| _        | j;                  | jH                         y|dk(  r#d| _        | j;                  | jH                         ytM        |tN              r| j;                  | jP                  |       |jb                  | j[                  |d      ry| j*                  jd                  r| j;                  | jD                         y| j                  | _        >| j                  | jf                  k(  r| j*                  jh                  jk                         s| jl                  | _        | jn                  jq                         D ]J  }ts        | j*                  jh                  jn                  |      }ts        | jn                  |      }|d   |d<   L y| j                  | jl                  k(  r| ju                         sy!# t        j                  $ r 	 Y y w xY w)NFT)timeoutrz   	r   enddate	begindate	timeframecompressionr.   r/   rC   
sessionendresubiiiii-infi\)histr   );r   r   _ST_OVER_ST_LIVEr   popr}   get_qcheckr   Emptyr   r
   r	   datetimeutcnowrs   r9   reqHistoricalDataExr   r   rB   r.   r/   _tzr   r~   _laststatusDELAYEDr   _ST_HISTORBACKr   
CONNBROKEN	reconnectr   r2   NOTSUBSCRIBEDr   rA   r   UNKNOWNLIVEqsizer   _load_rtvolume_load_rtbarfromdatert   timerF   r-   r   r3   rp   r   linesgetlinealiasesgetattrr   )r<   msgdtenddtbeginretaliaslsrcldsts           r   _loadzIBData._load  s   == DKK4==$@{{dmm+??..tT: @::>>$,,>? @ ;.3D+))$//:77,,4,8--d.?.?@$,0FFOOD)$;))$*<*<= E\ /4D+,0FFOOD)E\0004-E\.3D+0004-F].3D+0004-]3 ))$,,< ,,''4994::++-2 11$))<~~"11#6"..s3#  ),% ##t||3))$,,7t9q= 't}}R'89G]]U6]2&t}}5G #G(,CHH!WW88!]]EW"oo4;L;LTVV]]txx#vv00	 9 2
 #11(-% 3 33jjnn&;.3D+))$*;*;< D[.3D+))$*<*<= D[.3D+))$*<*<= ]3 ))$,,<88'''$'7#  66$$))$*;*;<  #mm-vv++002"&..DK "ZZ668 &E"466#7#7#=#=uED"4::u5D"1gDG	& .~~' w 
 {{ #s   AY	 	Y Y c                    | j                   j                  r| j                  | j                         d }| j                  t        d      k  rt        | j                        }d }| j                  t        d      kD  rt        | j                        }| j                  j                  | j                  ||| j                  | j                  | j                   j                  | j                   j                  | j                  | j                   j                   	      | _        | j$                  | _        y| j                  j)                  d      s-| j                  | j*                         | j,                  | _        y| j                   j.                  | _        | j                   j.                  r| j                  | j                         | j2                  | _        y)Ninfr   r   Tr   F)rB   r-   r   r   todatert   r
   r   r9   r   r   r   r   r.   r/   r   r   r~   r   r   r   r   r   r1   r   r   )r<   r   r   s      r   r   zIBData._st_startw  sN   66!!$,,/E{{U5\) -G}}uV},"4==144//t7H7HVV[[48866,,	 5 .DJ --DK ww  t ,!!$"3"34--DK $ 5 566  !!$,,/mmr   c                 r   t        |s|j                  n|j                        }|| j                  j                  d   k  r| j
                  j                  sy|| j                  j                  d<   |j                  | j                  j                  d<   |j                  | j                  j                  d<   |j                  | j                  j                  d<   |j                  | j                  j                  d<   |j                  | j                  j                  d<   d| j                  j                  d<   yNr   Fr   T)r	   r   rF   r   r   rB   r4   openhighlowclosevolumeopeninterest)r<   r,   r   dts       r   r   zIBData._load_rtbar  s    
 ejj%**=

##B''0B0B!#

A"ZZ

"ZZ

!II

q#kk

$||

!%&

"r   c                    t        |j                        }|| j                  j                  d   k  r| j                  j                  sy|| j                  j                  d<   |j
                  }|| j                  j                  d<   || j                  j                  d<   || j                  j                  d<   || j                  j                  d<   |j                  | j                  j                  d<   d| j                  j                  d<   yr   )r	   r   r   rB   r4   pricer   r   r   r   sizer   r   )r<   rtvolr   ticks       r   r   zIBData._load_rtvolume  s    
 enn%

##B''0B0B!#

A {{!

!

 

q"

$zz

!%&

"r   )F)!r   r    r!   __doc__paramsr   r   rU   r   Secondsr   ranger   r   r   r   r   r=   rP   rR   r   r\   rV   r|   r   r   r   r   r   r   r   r   r"   r#   s   @r   r%   r%   -   s    TjF  __F &&*M ?DAh;Hi>8$B%
E
EN?B
33!BB(r   r%   )
__future__r   r   r   r   r   
backtraderrD   backtrader.feedr   r   r	   r
   backtrader.utils.py3r   r   r   r   backtrader.metabaser   backtrader.storesr   r   r   r%   rT   r   r   <module>r      sW   ** *   $ 4 42 2 * %&## &S
^J1 S
r   