
    T>qjN                    *   d Z ddlZddlZddlZddl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mZmZ ddlmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2 ddl3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z: dd	l;m<Z< dd
l=m>Z>  G d d      Z?e@dk(  rj ej                         ZBeBj                  d        ej                  ej                          e?       ZFeFj                  ddd       eFj                          yy)z,High-level interface to Interactive Brokers.    N)	AwaitableDictIteratorListOptionalUnion)Event)Client)ContractContractDescriptionContractDetails)AccountValueBarDataListDepthMktDataDescription	ExecutionExecutionFilterFillHistogramDataHistoricalNewsHistoricalScheduleNewsArticleNewsBulletinNewsProviderNewsTickOptionChainOptionComputationPnL	PnLSinglePortfolioItemPositionPriceIncrementRealTimeBarListScanDataListScannerSubscriptionSmartComponentTagValueTradeLogEntryWshEventData)BracketOrder
LimitOrderOrder
OrderStateOrderStatus	StopOrderTrade)Ticker)Wrapperc                      e Zd ZU dZdZdZeed<   dZe	ed<   dZ
eed<   d	Zeed
<   d Zd Zd Zd Zd Zd Z	 	 ddedededede	defdZd Zde	fdZd Z eej4                        Z eej6                        Z eej8                        Z eej:                        Z eej<                        Z eej>                        Zde fdZ!ddede	fdZ"	 ddede#e$   fd!Z%ddefd#Z&de'e   fd$Z(ddede'e)   fd%Z*ddede'e)   fd&Z+ddede'e,   fd'Z-ddede'e.   fd(Z/dde'e0   fd)Z1	 	 dded*ed+ede'e2   fd,Z3de'e4   fd-Z5de'e4   fd.Z6de'e7   fd/Z8de'e7   fd0Z9de'e:   fd1Z;de'e<   fd2Z=d3e>de?e@   fd4ZAde'e@   fd5ZBde'e@   fd6ZCde'eDeEeFf      fd7ZGde'eH   fd8ZIde'eJ   fd9ZKdd:d;e>d<e	de'e@   fd=ZLd;e>de'e>   fd>ZMd?ed@edAedBedCedeNfdDZOedEe'e7   dFedGede'e7   fdH       ZPd3e>dIe7deQfdJZRd3e>dIe7de4fdKZSddIe7dLede?e4   fdMZTdN ZUdeVj                  fdOZWddefdPZX	 dded*efdQZYdR ZZddSe	fdTZ[de'e4   fdUZ\de'e4   fdVZ]dWe	de'e4   fdXZ^	 ddYe?e_   de'e:   fdZZ`de'e.   fd[Zadded*ede0fd\Zbdd*efd]Zcded*ed+ede2fd^Zdded*ed+efd_Zed3e>de'ef   fd`Zgdaede'eh   fdbZidcedejfddZkg fd3e>deedfedge	dhe'el   deFfdiZmdjeFfdkZnddg d"fd3e>dleDeVj                  eVj                  ed f   dmednedfedge	doedpe	dqe'el   dedeEfdrZpdjeEfdsZq	 	 dd3e>dtedleDeVj                  eVj                  ed f   dge	derf
duZsdg fd3e>dveDeeVj                  f   dleDeeVj                  f   dwedfedxe	dye	dze'el   de'fd{Ztd|efd}Zu	 dd3e>dfedge	doedeVj                  f
d~Zvd	ddg fd3e>dede	d<e	de'el   de@fdZwd3e>fdZx	 dd3e>dedwedye	de@f
dZyd3e>defdZzdede'e{   fdZ|de'e}   fdZ~	 	 dd3e>dede	de@fdZdd3e>fdZd3e>dge	dede'e   fdZg fd3e>dede'el   defdZg g fdede'el   de'el   defdZg g fdede'el   de'el   defdZdefdZdefdZg fd3e>dedede'el   def
dZg fd3e>dedede'el   def
dZdedededede'e   f
dZd3e>dedededef
dZde'e   fdZg fdedede'el   defdZg fd+ededveDeeVj                  f   dleDeeVj                  f   dede'el   defdZde	fdZd ZdefdZdedefdZd Zd ZdefdZd ZdefdZdedefdZdefdZ	 	 	 ddededede?e   de	defdÄZd;e>de'e>   fdĄZdd:d;e>d<e	de'e@   fdńZd3e>dIe7de eQ   fdƄZde eVj                     fdǄZdede d    fdȄZ	 dded*ede d    fdɄZddede'e)   fdʄZde d    fd˄Zde e'e4      fd̄Zde e'e4      fd̈́ZdWe	de e'e4      fd΄Z	 ddYe?e_   de e'e:      fdτZde e'e.      fdЄZd3e>de e'ef      fdфZdaede?e'eh      fd҄Zdcede?e'ej      fdӄZddg d"fd3e>dleDeVj                  eVj                  ed f   dmednedfedge	doedpe	dqe'el   dedeEfdԄZ	 	 dd3e>dtedleDeVj                  eVj                  ed f   dge	de er   f
dՄZdg fd3e>dveDeeVj                  f   dleDeeVj                  f   dwedfedxe	dye	dze'el   de e'   fdքZd3e>dfedge	doedeVj                  f
dׄZd؄ Zde e'e}      fdلZd3e>dge	dede e'e      fdڄZg fd3e>dede'el   de e   fdۄZg g fdede'el   de'el   defd܄Zde e   fd݄Zg fd3e>dedede'el   de?e   f
dބZg fd3e>dedede'el   de?e   f
d߄Zdedededede e'e      f
dZde e'e      fdZg fdedede'el   de e   fdZg fd+ededveDeeVj                  f   dleDeeVj                  f   dede'el   de?e   fdZdefdZdefdZdedefdZd Zy )IBa  
    Provides both a blocking and an asynchronous interface
    to the IB API, using asyncio networking and event loop.

    The IB class offers direct access to the current state, such as
    orders, executions, positions, tickers etc. This state is
    automatically kept in sync with the TWS/IBG application.

    This class has most request methods of EClient, with the
    same names and parameters (except for the reqId parameter
    which is not needed anymore).
    Request methods that return a result come in two versions:

    * Blocking: Will block until complete and return the result.
      The current state will be kept updated while the request is ongoing;

    * Asynchronous: All methods that have the "Async" postfix.
      Implemented as coroutines or methods that return a Future and
      intended for advanced users.

    **The One Rule:**

    While some of the request methods are blocking from the perspective
    of the user, the framework will still keep spinning in the background
    and handle all messages received from TWS/IBG. It is important to
    not block the framework from doing its work. If, for example,
    the user code spends much time in a calculation, or uses time.sleep()
    with a long delay, the framework will stop spinning, messages
    accumulate and things may go awry.

    The one rule when working with the IB class is therefore that

    **user code may not block for too long**.

    To be clear, the IB request methods are okay to use and do not
    count towards the user operation time, no matter how long the
    request takes to finish.

    So what is "too long"? That depends on the situation. If, for example,
    the timestamp of tick data is to remain accurate within a millisecond,
    then the user code must not spend longer than a millisecond. If, on
    the other extreme, there is very little incoming data and there
    is no desire for accurate timestamps, then the user code can block
    for hours.

    If a user operation takes a long time then it can be farmed out
    to a different process.
    Alternatively the operation can be made such that it periodically
    calls IB.sleep(0); This will let the framework handle any pending
    work and return when finished. The operation should be aware
    that the current state may have been updated during the sleep(0) call.

    For introducing a delay, never use time.sleep() but use
    :meth:`.sleep` instead.

    Parameters:
        RequestTimeout (float): Timeout (in seconds) to wait for a
          blocking request to finish before raising ``asyncio.TimeoutError``.
          The default value of 0 will wait indefinitely.
          Note: This timeout is not used for the ``*Async`` methods.
        RaiseRequestErrors (bool):
          Specifies the behaviour when certain API requests fail:

          * :data:`False`: Silently return an empty result;
          * :data:`True`: Raise a :class:`.RequestError`.
        MaxSyncedSubAccounts (int): Do not use sub-account updates
          if the number of sub-accounts exceeds this number (50 by default).
        TimezoneTWS (str): Specifies what timezone TWS (or gateway)
          is using. The default is to assume local system timezone.

    Events:
        * ``connectedEvent`` ():
          Is emitted after connecting and synchronzing with TWS/gateway.

        * ``disconnectedEvent`` ():
          Is emitted after disconnecting from TWS/gateway.

        * ``updateEvent`` ():
          Is emitted after a network packet has been handeled.

        * ``pendingTickersEvent`` (tickers: Set[:class:`.Ticker`]):
          Emits the set of tickers that have been updated during the last
          update and for which there are new ticks, tickByTicks or domTicks.

        * ``barUpdateEvent`` (bars: :class:`.BarDataList`,
          hasNewBar: bool): Emits the bar list that has been updated in
          real time. If a new bar has been added then hasNewBar is True,
          when the last bar has changed it is False.

        * ``newOrderEvent`` (trade: :class:`.Trade`):
          Emits a newly placed trade.

        * ``orderModifyEvent`` (trade: :class:`.Trade`):
          Emits when order is modified.

        * ``cancelOrderEvent`` (trade: :class:`.Trade`):
          Emits a trade directly after requesting for it to be cancelled.

        * ``openOrderEvent`` (trade: :class:`.Trade`):
          Emits the trade with open order.

        * ``orderStatusEvent`` (trade: :class:`.Trade`):
          Emits the changed order status of the ongoing trade.

        * ``execDetailsEvent`` (trade: :class:`.Trade`, fill: :class:`.Fill`):
          Emits the fill together with the ongoing trade it belongs to.

        * ``commissionReportEvent`` (trade: :class:`.Trade`,
          fill: :class:`.Fill`, report: :class:`.CommissionReport`):
          The commission report is emitted after the fill that it belongs to.

        * ``updatePortfolioEvent`` (item: :class:`.PortfolioItem`):
          A portfolio item has changed.

        * ``positionEvent`` (position: :class:`.Position`):
          A position has changed.

        * ``accountValueEvent`` (value: :class:`.AccountValue`):
          An account value has changed.

        * ``accountSummaryEvent`` (value: :class:`.AccountValue`):
          An account value has changed.

        * ``pnlEvent`` (entry: :class:`.PnL`):
          A profit- and loss entry is updated.

        * ``pnlSingleEvent`` (entry: :class:`.PnLSingle`):
          A profit- and loss entry for a single position is updated.

        * ``tickNewsEvent`` (news: :class:`.NewsTick`):
          Emit a new news headline.

        * ``newsBulletinEvent`` (bulletin: :class:`.NewsBulletin`):
          Emit a new news bulletin.

        * ``scannerDataEvent`` (data: :class:`.ScanDataList`):
          Emit data from a scanner subscription.

        * ``wshMetaEvent`` (dataJson: str):
          Emit WSH metadata.

        * ``wshEvent`` (dataJson: str):
          Emit WSH event data (such as earnings dates, dividend dates,
          options expiration dates, splits, spinoffs and conferences).

        * ``errorEvent`` (reqId: int, errorCode: int, errorString: str,
          contract: :class:`.Contract`):
          Emits the reqId/orderId and TWS error code and string (see
          https://interactivebrokers.github.io/tws-api/message_codes.html)
          together with the contract the error applies to (or None if no
          contract applies).

        * ``timeoutEvent`` (idlePeriod: float):
          Is emitted if no data is received for longer than the timeout period
          specified with :meth:`.setTimeout`. The value emitted is the period
          in seconds since the last update.

        Note that it is not advisable to place new requests inside an event
        handler as it may lead to too much recursion.
    )connectedEventdisconnectedEventupdateEventpendingTickersEventbarUpdateEventnewOrderEventorderModifyEventcancelOrderEventopenOrderEventorderStatusEventexecDetailsEventcommissionReportEventupdatePortfolioEventpositionEventaccountValueEventaccountSummaryEventpnlEventpnlSingleEventscannerDataEventtickNewsEventnewsBulletinEventwshMetaEventwshEvent
errorEventtimeoutEventr   RequestTimeoutFRaiseRequestErrors2   MaxSyncedSubAccounts TimezoneTWSc                 <   | j                          t        |       | _        t        | j                        | _        | xj
                  | j                  z  c_        | j                  xj                  | j                  z  c_        t        j                  d      | _        y )Nzib_insync.ib)_createEventsr1   wrapperr
   clientrK   _onErrorapiEndr5   logging	getLogger_loggerselfs    K/opt/rentech/trading_bot/.venv/lib/python3.12/site-packages/ib_insync/ib.py__init__zIB.__init__   sh    t}T\\*4==(d444((8    c                 $   t        d      | _        t        d      | _        t        d      | _        t        d      | _        t        d      | _        t        d      | _        t        d      | _        t        d      | _        t        d	      | _	        t        d
      | _
        t        d      | _        t        d      | _        t        d      | _        t        d      | _        t        d      | _        t        d      | _        t        d      | _        t        d      | _        t        d      | _        t        d      | _        t        d      | _        t        d      | _        t        d      | _        t        d      | _        t        d      | _        y )Nr4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   )r	   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   r\   s    r^   rT   zIB._createEvents   sT   #$45!&':!; /#()>#? #$45"?3 %&8 9 %&8 9#$45 %&8 9 %&8 9%*+B%C"$)*@$A!"?3!&':!;#()>#? j)#$45 %&8 9"?3!&':!;!.1j)-!.1r`   c                 $    | j                          y N
disconnectr\   s    r^   __del__z
IB.__del__       r`   c                     | S rc    r\   s    r^   	__enter__zIB.__enter__   s    r`   c                 $    | j                          y rc   rd   )r]   _excs     r^   __exit__zIB.__exit__   rg   r`   c                    | j                   j                         rGd| j                   j                   d| j                   j                   d| j                   j                   nd}d| j
                  j                   d| dS )Nzconnected to :z
 clientId=znot connected< >)rV   isConnectedhostportclientId	__class____qualname__)r]   conns     r^   __repr__zIB.__repr__   s{     '')   0 01;;##$Jt{{/C/C.DF/> 	 4>>../qa88r`      rt   ru   rv   timeoutreadonlyaccountc           
      L    | j                  | j                  ||||||            S )a8  
        Connect to a running TWS or IB gateway application.
        After the connection is made the client is fully synchronized
        and ready to serve requests.

        This method is blocking.

        Args:
            host: Host name or IP address.
            port: Port number.
            clientId: ID number to use for this client; must be unique per
              connection. Setting clientId=0 will automatically merge manual
              TWS trading with this client.
            timeout: If establishing the connection takes longer than
              ``timeout`` seconds then the ``asyncio.TimeoutError`` exception
              is raised. Set to 0 to disable timeout.
            readonly: Set to ``True`` when API is in read-only mode.
            account: Main account to receive updates for.
        )_runconnectAsync)r]   rt   ru   rv   r|   r}   r~   s          r^   connectz
IB.connect  s/    , yy**$'8W> ? 	?r`   c                 ^   | j                   j                         sy| j                   j                         }| j                  j	                  d| j                   j
                   d| j                   j                   dt        j                  |j                         d|j                   dt        j                  |j                         d|j                   dt        j                  |j                         d	       | j                   j                          | j                  j!                          y)
zm
        Disconnect from a TWS or IB gateway application.
        This will clear all session state.
        NzDisconnecting from ro   z, z
B sent in z messages, zB received in z messages, session time zs.)rV   rs   connectionStatsr[   infort   ru   utilformatSInumBytesSent
numMsgSentnumBytesRecv
numMsgRecvdurationre   r5   emit)r]   statss     r^   re   zIB.disconnect  s    
 {{&&(++-!$++"2"2!31T[[5E5E4Fb}}U//01 2""#;}}U//01 2""# $ MM%..9:">	? 	 ##%r`   returnc                 6    | j                   j                         S )z0Is there an API connection to TWS or IB gateway?)rV   isReadyr\   s    r^   rs   zIB.isConnected,  s    {{""$$r`   c                 V    |dk(  r$t        j                  | j                                y y )NiN  )asyncioensure_futurereqAccountSummaryAsync)r]   reqId	errorCodeerrorStringcontracts        r^   rW   zIB._onError0  s(     !!$"="="?@ r`   
awaitablesc                 @    t        j                  |d| j                  iS )Nr|   )r   runrM   )r]   r   s     r^   r   zIB._run=  s    xxAT-@-@AAr`   c                     |r5	 t        j                  t        j                  | j                  |             yt        j                  | j                         y# t        j
                  $ r Y yw xY w)a^  
        Wait on any new update to arrive from the network.

        Args:
            timeout: Maximum time in seconds to wait.
                If 0 then no timeout is used.

        .. note::
            A loop with ``waitOnUpdate`` should not be used to harvest
            tick data from tickers, since some ticks can go missing.
            This happens when multiple updates occur almost simultaneously;
            The ticks from the first update are then cleared.
            Use events instead to prevent this.

        Returns:
            ``True`` if not timed-out, ``False`` otherwise.
        FT)r   r   r   wait_forr6   TimeoutErrorr]   r|   s     r^   waitOnUpdatezIB.waitOnUpdate@  sa    $ ))$*:*:GDE
  HHT%%&	 '' s   3A A.-A.Nc              #      K   t        j                          |z   }	 |xr  |       }|r| y|rt        j                          |kD  rd y| | j                  |r|t        j                          z
  nd       _w)as  
        Iterate until condition is met, with optional timeout in seconds.
        The yielded value is that of the condition or False when timed out.

        Args:
            condition: Predicate function that is tested after every network
            update.
            timeout: Maximum time in seconds to wait.
                If 0 then no timeout is used.
        NFr   )timer   )r]   	conditionr|   endTimetests        r^   	loopUntilzIB.loopUntil[  sq      ))+',D
TYY[72
wg		3AF s   A8A:<   c                 :    | j                   j                  |       y)a?  
        Set a timeout for receiving messages from TWS/IBG, emitting
        ``timeoutEvent`` if there is no incoming data for too long.

        The timeout fires once per connected session but can be set again
        after firing or after a reconnect.

        Args:
            timeout: Timeout in seconds.
        N)rU   
setTimeoutr   s     r^   r   zIB.setTimeoutt  s     	(r`   c                 @    t        | j                  j                        S )zList of account names.)listrU   accountsr\   s    r^   managedAccountszIB.managedAccounts  s    DLL))**r`   c                     |rA| j                   j                  j                         D cg c]  }|j                  |k(  r| c}S t	        | j                   j                  j                               S c c}w )z
        List of account values for the given account,
        or of all accounts if account is left blank.

        Args:
            account: If specified, filter for this account name.
        )rU   accountValuesvaluesr~   r   r]   r~   vs      r^   r   zIB.accountValues  se     #||99@@B -!yyG+  - - 2299;<<-s   A1c                 B    | j                  | j                  |            S )a  
        List of account values for the given account,
        or of all accounts if account is left blank.

        This method is blocking on first run, non-blocking after that.

        Args:
            account: If specified, filter for this account name.
        )r   accountSummaryAsyncr]   r~   s     r^   accountSummaryzIB.accountSummary  s     yy11':;;r`   c                    |r0t        | j                  j                  |   j                               S | j                  j                  j                         D cg c]  }|j                         D ]  }|  c}}S c c}}w )z
        List of portfolio items for the given account,
        or of all retrieved portfolio items if account is left blank.

        Args:
            account: If specified, filter for this account name.
        )r   rU   	portfolior   r]   r~   dr   s       r^   r   zIB.portfolio  t     ..w7>>@AA#||55<<> )!XXZ)  )A ) ) )   A<c                    |r0t        | j                  j                  |   j                               S | j                  j                  j                         D cg c]  }|j                         D ]  }|  c}}S c c}}w )z
        List of positions for the given account,
        or of all accounts if account is left blank.

        Args:
            account: If specified, filter for this account name.
        )r   rU   	positionsr   r   s       r^   r   zIB.positions  r   r   c                     | j                   j                  j                         D cg c]&  }|r|j                  |k(  r|r|j                  |k(  r|( c}S c c}w )aT  
        List of subscribed :class:`.PnL` objects (profit and loss),
        optionally filtered by account and/or modelCode.

        The :class:`.PnL` objects are kept live updated.

        Args:
            account: If specified, filter for this account name.
            modelCode: If specified, filter for this account model.
        )rU   	reqId2PnLr   r~   	modelCode)r]   r~   r   r   s       r^   pnlzIB.pnl  sV      <<1188: Aa		W 4"akkY&>  A 	A As   +Ar   conIdc                     | j                   j                  j                         D cg c]7  }|r|j                  |k(  r$|r|j                  |k(  r|r|j
                  |k(  r|9 c}S c c}w )a  
        List of subscribed :class:`.PnLSingle` objects (profit and loss for
        single positions).

        The :class:`.PnLSingle` objects are kept live updated.

        Args:
            account: If specified, filter for this account name.
            modelCode: If specified, filter for this account model.
            conId: If specified, filter for this contract ID.
        )rU   reqId2PnlSingler   r~   r   r   )r]   r~   r   r   r   s        r^   	pnlSinglezIB.pnlSingle  s`      <<77>>@ 5a		W 4"akkY&>!''U"2  5 	5 5s   <A&c                 \    t        | j                  j                  j                               S )z+List of all order trades from this session.r   rU   tradesr   r\   s    r^   r   z	IB.trades  s     DLL''..011r`   c                     | j                   j                  j                         D cg c]*  }|j                  j                  t
        j                  vr|, c}S c c}w )zList of all open order trades.)rU   r   r   orderStatusstatusr-   
DoneStates)r]   r   s     r^   
openTradeszIB.openTrades  sP    <<..557 Ga==''{/E/EE  G 	G Gs   /Ac                 j    t        d | j                  j                  j                         D              S )z%List of all orders from this session.c              3   4   K   | ]  }|j                     y wrc   )order).0trades     r^   	<genexpr>zIB.orders.<locals>.<genexpr>  s      C!EKKC   r   r\   s    r^   ordersz	IB.orders  s3     C%)\\%8%8%?%?%AC C 	Cr`   c                     | j                   j                  j                         D cg c]4  }|j                  j                  t
        j                  vr|j                  6 c}S c c}w )zList of all open orders.)rU   r   r   r   r   r-   r   r   )r]   r   s     r^   
openOrderszIB.openOrders  sV    )-)<)<)C)C)E K$$++;3I3II  K 	K Ks   9A#c                 \    t        | j                  j                  j                               S )z$List of all fills from this session.r   rU   fillsr   r\   s    r^   r   zIB.fills  s     DLL&&--/00r`   c                 j    t        d | j                  j                  j                         D              S )z)List of all executions from this session.c              3   4   K   | ]  }|j                     y wrc   )	execution)r   fills     r^   r   z IB.executions.<locals>.<genexpr>  s     KtDNNKr   r   r\   s    r^   
executionszIB.executions  s&    Kt||/A/A/H/H/JKKKr`   r   c                 ^    | j                   j                  j                  t        |            S )a$  
        Get ticker of the given contract. It must have been requested before
        with reqMktData with the same contract object. The ticker may not be
        ready yet if called directly after :meth:`.reqMktData`.

        Args:
            contract: Contract to get ticker for.
        )rU   tickersgetidr]   r   s     r^   tickerz	IB.ticker  s#     ||##''855r`   c                 \    t        | j                  j                  j                               S )zGet a list of all tickers.)r   rU   r   r   r\   s    r^   r   z
IB.tickers  s     DLL((//122r`   c                 @    t        | j                  j                        S )z>Get a list of all tickers that have pending ticks or domTicks.)r   rU   pendingTickersr\   s    r^   r   zIB.pendingTickers  s    DLL//00r`   c                 \    t        | j                  j                  j                               S )z
        Get a list of all live updated bars. These can be 5 second realtime
        bars or live updated historical bars.
        )r   rU   reqId2Subscriberr   r\   s    r^   realtimeBarszIB.realtimeBars  s"    
 DLL1188:;;r`   c                 .    | j                   j                  S )z}
        List of ticks with headline news.
        The article itself can be retrieved with :meth:`.reqNewsArticle`.
        )rU   	newsTicksr\   s    r^   r   zIB.newsTicks  s    
 ||%%%r`   c                 \    t        | j                  j                  j                               S )zList of IB news bulletins.)r   rU   msgId2NewsBulletinr   r\   s    r^   newsBulletinszIB.newsBulletins  s     DLL33::<==r`   )regulatorySnapshot	contractsr   c                D    | j                   | j                  |d|i      S )a)  
        Request and return a list of snapshot tickers.
        The list is returned when all tickers are ready.

        This method is blocking.

        Args:
            contracts: Contracts to get tickers for.
            regulatorySnapshot: Request NBBO snapshots (may incur a fee).
        r   )r   reqTickersAsync)r]   r   r   s      r^   
reqTickerszIB.reqTickers  s4     yy D  C/ACD 	Dr`   c                 >    | j                   | j                  |       S )a;  
        Fully qualify the given contracts in-place. This will fill in
        the missing fields in the contract, especially the conId.

        Returns a list of contracts that have been successfully qualified.

        This method is blocking.

        Args:
            contracts: Contracts to qualify.
        )r   qualifyContractsAsync)r]   r   s     r^   qualifyContractszIB.qualifyContracts.  s!     yy333Y?@@r`   actionquantity
limitPricetakeProfitPricestopLossPricec                 \   |dv sJ |dk(  rdnd}t        |||f| j                  j                         dd|}t        |||f| j                  j                         d|j                  d|}	t	        |||f| j                  j                         d|j                  d|}
t        ||	|
      S )a6  
        Create a limit order that is bracketed by a take-profit order and
        a stop-loss order. Submit the bracket like:

        .. code-block:: python

            for o in bracket:
                ib.placeOrder(contract, o)

        https://interactivebrokers.github.io/tws-api/bracket_order.html

        Args:
            action: 'BUY' or 'SELL'.
            quantity: Size of order.
            limitPrice: Limit price of entry order.
            takeProfitPrice: Limit price of profit order.
            stopLossPrice: Stop price of loss order.
        )BUYSELLr  r  F)orderIdtransmit)r  r  parentIdT)r*   rV   getReqIdr  r.   r)   )r]   r   r   r   r   r   kwargsreverseActionparent
takeProfitstopLosss              r^   bracketOrderzIB.bracketOrder<  s    , (((!'6!1vHjKK((* 	
  8_KK((*^^	
 
 8]KK((*^^	
  FJ99r`   r   ocaGroupocaTypec                 0    | D ]  }||_         ||_         | S )z
        Place the trades in the same One Cancels All (OCA) group.

        https://interactivebrokers.github.io/tws-api/oca.html

        Args:
            orders: The orders that are to be placed together.
        )r  r  )r   r  r  os       r^   oneCancelsAllzIB.oneCancelsAllg  s(      	 A!AJAI	  r`   r   c                 D    | j                  | j                  ||            S )a  
        Retrieve commission and margin impact without actually
        placing the order. The given order will not be modified in any way.

        This method is blocking.

        Args:
            contract: Contract to test.
            order: Order to test.
        )r   whatIfOrderAsync)r]   r   r   s      r^   whatIfOrderzIB.whatIfOrderw  s      yy..x?@@r`   c                    |j                   xs | j                  j                         }| j                  j                  |||       t        j                  j                  t        j                  j                        }| j                  j                  | j                  j                  ||j                        }| j                  j                  j                  |      }|r|j                  j                  t         j"                  vsJ t%        ||j                  j                  d      }|j&                  j)                  |       | j*                  j-                  d|        |j.                  j1                  |       | j2                  j1                  |       |S | j                  j                  |_
        ||_         t!        |t         j4                        }t%        ||j                        }t7        |||g |g      }|| j                  j                  |<   | j*                  j-                  d|        | j8                  j1                  |       |S )a  
        Place a new order or modify an existing order.
        Returns a Trade that is kept live updated with
        status changes, fills, etc.

        Args:
            contract: Contract to use for order.
            order: The order to be placed.
        ModifyzplaceOrder: Modify order )r  r   zplaceOrder: New order )r  rV   r  
placeOrderdatetimenowtimezoneutcrU   orderKeyrv   permIdr   r   r   r   r-   r   r'   logappendr[   r   modifyEventr   r:   PendingSubmitr/   r9   )	r]   r   r   r  r  keyr   logEntryr   s	            r^   r  zIB.placeOrder  s    --94;;#7#7#9w%8##H$5$5$9$9:ll##LL!!7ELL:##'',$$++;3I3IIII$S%*;*;*B*BHMHIIX&LL 9%AB""5)!!&&u-  "\\22EN#EM%(A(ACK$S+*<*<=H%b8*>E',DLL$LL 6ug>?##E*r`   manualCancelOrderTimec                    | j                   j                  |j                  |       t        j                  j	                  t        j
                  j                        }| j                  j                  |j                  |j                  |j                        }| j                  j                  j                  |      }|rl|j                         sY|j                  j                  }|t         j"                  k(  r|j$                  r|t         j&                  k(  rt         j(                  }nt         j*                  }t-        ||      }|j.                  j1                  |       ||j                  _        | j2                  j5                  d|        |j6                  j9                  |       |j:                  j9                  |       | j<                  j9                  |       | j>                  j9                  |       |t         j(                  k(  r|j@                  j9                  |       |S | j2                  jC                  d|j                          |S )z
        Cancel the order and return the Trade it belongs to.

        Args:
            order: The order to be canceled.
            manualCancelOrderTime: For audit trail.
        zcancelOrder: zcancelOrder: Unknown orderId )"rV   cancelOrderr  r  r  r  r  rU   r  rv   r  r   r   isDoner   r   r-   r!  r  Inactive	CancelledPendingCancelr'   r  r  r[   r   cancelEventr   statusEventr;   r=   cancelledEventerror)	r]   r   r$  r  r"  r   r   	newStatusr#  s	            r^   r&  zIB.cancelOrder  s    	/DE##H$5$5$9$9:ll##NNEMM5<<9##'',<<>**11k777![%9%99 + 5 5I + 9 9I(i8		  *+4!!(!!M%"9:!!&&u-!!&&u-%%**51%%**51 5 55((--e4  LL!>u}}oNOr`   c                 n    | j                   j                          | j                  j                  d       y)zm
        Cancel all active trades including those placed by other
        clients or TWS/IB gateway.
        reqGlobalCancelN)rV   r1  r[   r   r\   s    r^   r1  zIB.reqGlobalCancel  s'    
 	##%+,r`   c                 @    | j                  | j                               S )zM
        Request TWS current time.

        This method is blocking.
        )r   reqCurrentTimeAsyncr\   s    r^   reqCurrentTimezIB.reqCurrentTime  s     yy11344r`   c                 D    | j                  | j                  |             y)aP  
        This is called at startup - no need to call again.

        Request account and portfolio values of the account
        and keep updated. Returns when both account values and portfolio
        are filled.

        This method is blocking.

        Args:
            account: If specified, filter for this account name.
        N)r   reqAccountUpdatesAsyncr   s     r^   reqAccountUpdateszIB.reqAccountUpdates  s     			$--g67r`   c                 F    | j                  | j                  ||             y)aG  
        It is recommended to use :meth:`.accountValues` instead.

        Request account values of multiple accounts and keep updated.

        This method is blocking.

        Args:
            account: If specified, filter for this account name.
            modelCode: If specified, filter for this account model.
        N)r   reqAccountUpdatesMultiAsync)r]   r~   r   s      r^   reqAccountUpdatesMultizIB.reqAccountUpdatesMulti  s     			$227IFGr`   c                 B    | j                  | j                                y)z
        It is recommended to use :meth:`.accountSummary` instead.

        Request account values for all accounts and keep them updated.
        Returns when account summary is filled.

        This method is blocking.
        N)r   r   r\   s    r^   reqAccountSummaryzIB.reqAccountSummary  s     			$--/0r`   autoBindc                 :    | j                   j                  |       y)a  
        Bind manual TWS orders so that they can be managed from this client.
        The clientId must be 0 and the TWS API setting "Use negative numbers
        to bind automatic orders" must be checked.

        This request is automatically called when clientId=0.

        https://interactivebrokers.github.io/tws-api/open_orders.html
        https://interactivebrokers.github.io/tws-api/modifying_orders.html

        Args:
            autoBind: Set binding on or off.
        N)rV   reqAutoOpenOrders)r]   r=  s     r^   r?  zIB.reqAutoOpenOrders  s     	%%h/r`   c                 @    | j                  | j                               S )a  
        Request and return a list of open orders.

        This method can give stale information where a new open order is not
        reported or an already filled or cancelled order is reported as open.
        It is recommended to use the more reliable and much faster
        :meth:`.openTrades` or :meth:`.openOrders` methods instead.

        This method is blocking.
        )r   reqOpenOrdersAsyncr\   s    r^   reqOpenOrderszIB.reqOpenOrders  s     yy00233r`   c                 @    | j                  | j                               S )a  
        Request and return a list of all open orders over all clients.
        Note that the orders of other clients will not be kept in sync,
        use the master clientId mechanism instead to see other
        client's orders that are kept in sync.
        )r   reqAllOpenOrdersAsyncr\   s    r^   reqAllOpenOrderszIB.reqAllOpenOrders$  s     yy33566r`   apiOnlyc                 B    | j                  | j                  |            S )z
        Request and return a list of completed trades.

        Args:
            apiOnly: Request only API orders (not manually placed TWS orders).
        )r   reqCompletedOrdersAsync)r]   rF  s     r^   reqCompletedOrderszIB.reqCompletedOrders-  s     yy55g>??r`   
execFilterc                 B    | j                  | j                  |            S )a  
        It is recommended to use :meth:`.fills`  or
        :meth:`.executions` instead.

        Request and return a list of fills.

        This method is blocking.

        Args:
            execFilter: If specified, return executions that match the filter.
        )r   reqExecutionsAsync)r]   rJ  s     r^   reqExecutionszIB.reqExecutions6  s     yy00<==r`   c                 @    | j                  | j                               S )z
        It is recommended to use :meth:`.positions` instead.

        Request and return a list of positions for all accounts.

        This method is blocking.
        )r   reqPositionsAsyncr\   s    r^   reqPositionszIB.reqPositionsE  s     yy//122r`   c                 ,   ||f}|| j                   j                  vsJ | j                  j                         }|| j                   j                  |<   t	        ||      }|| j                   j
                  |<   | j                  j                  |||       |S )a  
        Start a subscription for profit and loss events.

        Returns a :class:`.PnL` object that is kept live updated.
        The result can also be queried from :meth:`.pnl`.

        https://interactivebrokers.github.io/tws-api/pnl.html

        Args:
            account: Subscribe to this account.
            modelCode: If specified, filter for this account model.
        )rU   pnlKey2ReqIdrV   r  r   r   reqPnL)r]   r~   r   r"  r   r   s         r^   rS  z	IB.reqPnLO  s     	"$,,33333$$&).!!#&'9%(+u%5'95
r`   c                 "   ||f}| j                   j                  j                  |d      }|rB| j                  j	                  |       | j                   j
                  j                  |d       y| j                  j                  d| d|        y)z
        Cancel PnL subscription.

        Args:
            account: Cancel for this account.
            modelCode: If specified, cancel for this account model.
        Nz'cancelPnL: No subscription for account , modelCode )rU   rR  poprV   	cancelPnLr   r[   r.  )r]   r~   r   r"  r   s        r^   rW  zIB.cancelPnLe  s     	"))--c48KK!!%(LL""&&ud3LL")<	{<=r`   c                 2   |||f}|| j                   j                  vsJ | j                  j                         }|| j                   j                  |<   t	        |||      }|| j                   j
                  |<   | j                  j                  ||||       |S )a  
        Start a subscription for profit and loss events for single positions.

        Returns a :class:`.PnLSingle` object that is kept live updated.
        The result can also be queried from :meth:`.pnlSingle`.

        https://interactivebrokers.github.io/tws-api/pnl.html

        Args:
            account: Subscribe to this account.
            modelCode: Filter for this account model.
            conId: Filter for this contract ID.
        )rU   pnlSingleKey2ReqIdrV   r  r   r   reqPnLSingle)r]   r~   r   r   r"  r   r   s          r^   rZ  zIB.reqPnLSinglew  s     	5)$,,99999$$&/4'',gy%8	.7$$U+  EBr`   c                 *   |||f}| j                   j                  j                  |d      }|rB| j                  j	                  |       | j                   j
                  j                  |d       y| j                  j                  d| d| d|        y)a  
        Cancel PnLSingle subscription for the given account, modelCode
        and conId.

        Args:
            account: Cancel for this account name.
            modelCode: Cancel for this account model.
            conId: Cancel for this contract ID.
        Nz-cancelPnLSingle: No subscription for account rU  z, conId )rU   rY  rV  rV   cancelPnLSingler   r[   r.  )r]   r~   r   r   r"  r   s         r^   r\  zIB.cancelPnLSingle  s     	5)//33C>KK''.LL((,,UD9LL")<	{(5'KLr`   c                 B    | j                  | j                  |            S )a  
        Get a list of contract details that match the given contract.
        If the returned list is empty then the contract is not known;
        If the list has multiple values then the contract is ambiguous.

        The fully qualified contract is available in the the
        ContractDetails.contract attribute.

        This method is blocking.

        https://interactivebrokers.github.io/tws-api/contract_details.html

        Args:
            contract: The contract to get details for.
        )r   reqContractDetailsAsyncr   s     r^   reqContractDetailszIB.reqContractDetails  s      yy55h?@@r`   patternc                 B    | j                  | j                  |            S )a  
        Request contract descriptions of contracts that match a pattern.

        This method is blocking.

        https://interactivebrokers.github.io/tws-api/matching_symbols.html

        Args:
            pattern: The first few letters of the ticker symbol, or for
                longer strings a character sequence matching a word in
                the security name.
        )r   reqMatchingSymbolsAsync)r]   r`  s     r^   reqMatchingSymbolszIB.reqMatchingSymbols  s     yy55g>??r`   marketRuleIdc                 B    | j                  | j                  |            S )a  
        Request price increments rule.

        https://interactivebrokers.github.io/tws-api/minimum_increment.html

        Args:
            marketRuleId: ID of market rule.
                The market rule IDs for a contract can be obtained
                via :meth:`.reqContractDetails` from
                :class:`.ContractDetails`.marketRuleIds,
                which contains a comma separated string of market rule IDs.
        )r   reqMarketRuleAsync)r]   rd  s     r^   reqMarketRulezIB.reqMarketRule  s     yy00>??r`   barSize
whatToShowuseRTHrealTimeBarsOptionsc                 $   | j                   j                         }t               }||_        ||_        ||_        ||_        ||_        |xs g |_        | j                  j                  |||       | j                   j                  ||||||       |S )a   
        Request realtime 5 second bars.

        https://interactivebrokers.github.io/tws-api/realtime_bars.html

        Args:
            contract: Contract of interest.
            barSize: Must be 5.
            whatToShow: Specifies the source for constructing bars.
                Can be 'TRADES', 'MIDPOINT', 'BID' or 'ASK'.
            useRTH: If True then only show data from within Regular
                Trading Hours, if False then show all data.
            realTimeBarsOptions: Unknown.
        )rV   r  r"   r   r   rh  ri  rj  rk  rU   startSubscriptionreqRealTimeBars)r]   r   rh  ri  rj  rk  r   barss           r^   rn  zIB.reqRealTimeBars  s    $ $$& 
 $#6#<" &&udH=##8Wj&:M	Or`   ro  c                     | j                   j                  |j                         | j                  j	                  |       y)z
        Cancel the realtime bars subscription.

        Args:
            bars: The bar list that was obtained from ``reqRealTimeBars``.
        N)rV   cancelRealTimeBarsr   rU   endSubscriptionr]   ro  s     r^   rq  zIB.cancelRealTimeBars  s,     	&&tzz2$$T*r`   endDateTimedurationStrbarSizeSetting
formatDatekeepUpToDatechartOptionsc                 T    | j                  | j                  |||||||||	|

            S )a  
        Request historical bar data.

        This method is blocking.

        https://interactivebrokers.github.io/tws-api/historical_bars.html

        Args:
            contract: Contract of interest.
            endDateTime: Can be set to '' to indicate the current time,
                or it can be given as a datetime.date or datetime.datetime,
                or it can be given as a string in 'yyyyMMdd HH:mm:ss' format.
                If no timezone is given then the TWS login timezone is used.
            durationStr: Time span of all the bars. Examples:
                '60 S', '30 D', '13 W', '6 M', '10 Y'.
            barSizeSetting: Time period of one bar. Must be one of:
                '1 secs', '5 secs', '10 secs' 15 secs', '30 secs',
                '1 min', '2 mins', '3 mins', '5 mins', '10 mins', '15 mins',
                '20 mins', '30 mins',
                '1 hour', '2 hours', '3 hours', '4 hours', '8 hours',
                '1 day', '1 week', '1 month'.
            whatToShow: Specifies the source for constructing bars.
                Must be one of:
                'TRADES', 'MIDPOINT', 'BID', 'ASK', 'BID_ASK',
                'ADJUSTED_LAST', 'HISTORICAL_VOLATILITY',
                'OPTION_IMPLIED_VOLATILITY', 'REBATE_RATE', 'FEE_RATE',
                'YIELD_BID', 'YIELD_ASK', 'YIELD_BID_ASK', 'YIELD_LAST'.
                For 'SCHEDULE' use :meth:`.reqHistoricalSchedule`.
            useRTH: If True then only show data from within Regular
                Trading Hours, if False then show all data.
            formatDate: For an intraday request setting to 2 will cause
                the returned date fields to be timezone-aware
                datetime.datetime with UTC timezone, instead of local timezone
                as used by TWS.
            keepUpToDate: If True then a realtime subscription is started
                to keep the bars updated; ``endDateTime`` must be set
                empty ('') then.
            chartOptions: Unknown.
            timeout: Timeout in seconds after which to cancel the request
                and return an empty bar series. Set to ``0`` to wait
                indefinitely.
        )r   reqHistoricalDataAsync)r]   r   rt  ru  rv  ri  rj  rw  rx  ry  r|   s              r^   reqHistoricalDatazIB.reqHistoricalData  s=    b yy''+{NJ
L,IJ 	Jr`   c                     | j                   j                  |j                         | j                  j	                  |       y)z
        Cancel the update subscription for the historical bars.

        Args:
            bars: The bar list that was obtained from ``reqHistoricalData``
                with a keepUpToDate subscription.

        N)rV   cancelHistoricalDatar   rU   rr  rs  s     r^   r~  zIB.cancelHistoricalData3  s,     	((4$$T*r`   numDaysc                 H    | j                  | j                  ||||            S )a[  
        Request historical schedule.

        This method is blocking.

        Args:
            contract: Contract of interest.
            numDays: Number of days.
            endDateTime: Can be set to '' to indicate the current time,
                or it can be given as a datetime.date or datetime.datetime,
                or it can be given as a string in 'yyyyMMdd HH:mm:ss' format.
                If no timezone is given then the TWS login timezone is used.
            useRTH: If True then show schedule for Regular Trading Hours,
                if False then for extended hours.
        )r   reqHistoricalScheduleAsync)r]   r   r  rt  rj  s        r^   reqHistoricalSchedulezIB.reqHistoricalSchedule?  s+    ( yy88g{F4 5 	5r`   startDateTimenumberOfTicksuseRth
ignoreSizemiscOptionsc	                 P    | j                  | j                  ||||||||            S )ap  
        Request historical ticks. The time resolution of the ticks
        is one second.

        This method is blocking.

        https://interactivebrokers.github.io/tws-api/historical_time_and_sales.html

        Args:
            contract: Contract to query.
            startDateTime: Can be given as a datetime.date or
                datetime.datetime, or it can be given as a string in
                'yyyyMMdd HH:mm:ss' format.
                If no timezone is given then the TWS login timezone is used.
            endDateTime: One of ``startDateTime`` or ``endDateTime`` can
                be given, the other must be blank.
            numberOfTicks: Number of ticks to request (1000 max). The actual
                result can contain a bit more to accommodate all ticks in
                the latest second.
            whatToShow: One of 'Bid_Ask', 'Midpoint' or 'Trades'.
            useRTH: If True then only show data from within Regular
                Trading Hours, if False then show all data.
            ignoreSize: Ignore bid/ask ticks that only update the size.
            miscOptions: Unknown.
        )r   reqHistoricalTicksAsync)	r]   r   r  rt  r  ri  r  r  r  s	            r^   reqHistoricalTickszIB.reqHistoricalTicksV  s6    @ yy((-mFJ=> 	>r`   marketDataTypec                 :    | j                   j                  |       y)aC  
        Set the market data type used for :meth:`.reqMktData`.

        Args:
            marketDataType: One of:

                * 1 = Live
                * 2 = Frozen
                * 3 = Delayed
                * 4 = Delayed frozen

        https://interactivebrokers.github.io/tws-api/market_data_type.html
        N)rV   reqMarketDataType)r]   r  s     r^   r  zIB.reqMarketDataType{  s     	%%n5r`   c                 H    | j                  | j                  ||||            S )a  
        Get the datetime of earliest available historical data
        for the contract.

        Args:
            contract: Contract of interest.
            useRTH: If True then only show data from within Regular
                Trading Hours, if False then show all data.
            formatDate: If set to 2 then the result is returned as a
                timezone-aware datetime.datetime with UTC timezone.
        )r   reqHeadTimeStampAsync)r]   r   ri  rj  rw  s        r^   reqHeadTimeStampzIB.reqHeadTimeStamp  s,     yy&&*fj:; 	;r`   genericTickListsnapshotmktDataOptionsc                     | j                   j                         }| j                  j                  ||d      }| j                   j	                  ||||||       |S )a	  
        Subscribe to tick data or request a snapshot.
        Returns the Ticker that holds the market data. The ticker will
        initially be empty and gradually (after a couple of seconds)
        be filled.

        https://interactivebrokers.github.io/tws-api/md_request.html

        Args:
            contract: Contract of interest.
            genericTickList: Comma separated IDs of desired
                generic ticks that will cause corresponding Ticker fields
                to be filled:

                =====  ================================================
                ID     Ticker fields
                =====  ================================================
                100    ``putVolume``, ``callVolume`` (for options)
                101    ``putOpenInterest``, ``callOpenInterest`` (for options)
                104    ``histVolatility`` (for options)
                105    ``avOptionVolume`` (for options)
                106    ``impliedVolatility`` (for options)
                162    ``indexFuturePremium``
                165    ``low13week``, ``high13week``, ``low26week``,
                       ``high26week``, ``low52week``, ``high52week``,
                       ``avVolume``
                221    ``markPrice``
                225    ``auctionVolume``, ``auctionPrice``,
                       ``auctionImbalance``
                233    ``last``, ``lastSize``, ``rtVolume``, ``rtTime``,
                       ``vwap`` (Time & Sales)
                236    ``shortableShares``
                258    ``fundamentalRatios`` (of type
                       :class:`ib_insync.objects.FundamentalRatios`)
                293    ``tradeCount``
                294    ``tradeRate``
                295    ``volumeRate``
                375    ``rtTradeVolume``
                411    ``rtHistVolatility``
                456    ``dividends`` (of type
                       :class:`ib_insync.objects.Dividends`)
                588    ``futuresOpenInterest``
                =====  ================================================

            snapshot: If True then request a one-time snapshot, otherwise
                subscribe to a stream of realtime tick data.
            regulatorySnapshot: Request NBBO snapshot (may incur a fee).
            mktDataOptions: Unknown
        mktData)rV   r  rU   startTicker
reqMktData)r]   r   r  r  r   r  r   r   s           r^   r  zIB.reqMktData  sV    j $$&))%9E8_h	0 r`   c                     | j                  |      }|r| j                  j                  |d      nd}|r| j                  j	                  |       y| j
                  j                  d|        y)z
        Unsubscribe from realtime streaming tick data.

        Args:
            contract: The exact contract object that was used to
                subscribe with.
        r  r   +cancelMktData: No reqId found for contract N)r   rU   	endTickerrV   cancelMktDatar[   r.  )r]   r   r   r   s       r^   r  zIB.cancelMktData  s^     X&=C&&vy9KK%%e,LL@
KMr`   tickTypec                     | j                   j                         }| j                  j                  |||      }| j                   j	                  |||||       |S )a  
        Subscribe to tick-by-tick data and return the Ticker that
        holds the ticks in ticker.tickByTicks.

        https://interactivebrokers.github.io/tws-api/tick_data.html

        Args:
            contract: Contract of interest.
            tickType: One of  'Last', 'AllLast', 'BidAsk' or 'MidPoint'.
            numberOfTicks: Number of ticks or 0 for unlimited.
            ignoreSize: Ignore bid/ask ticks that only update the size.
        )rV   r  rU   r  reqTickByTickData)r]   r   r  r  r  r   r   s          r^   r  zIB.reqTickByTickData  sQ     $$&))%8D%%8X}j	Br`   c                     | j                  |      }|r| j                  j                  ||      nd}|r| j                  j	                  |       y| j
                  j                  d|        y)z
        Unsubscribe from tick-by-tick data

        Args:
            contract: The exact contract object that was used to
                subscribe with.
        r   r  N)r   rU   r  rV   cancelTickByTickDatar[   r.  )r]   r   r  r   r   s        r^   r  zIB.cancelTickByTickData  s^     X&<B&&vx8KK,,U3LL=hZHJr`   bboExchangec                 B    | j                  | j                  |            S )z
        Obtain mapping from single letter codes to exchange names.

        Note: The exchanges must be open when using this request, otherwise an
        empty list is returned.
        )r   reqSmartComponentsAsync)r]   r  s     r^   reqSmartComponentszIB.reqSmartComponents  s     yy55kBCCr`   c                 @    | j                  | j                               S )z
        Get those exchanges that have have multiple market makers
        (and have ticks returned with marketMaker info).
        )r   reqMktDepthExchangesAsyncr\   s    r^   reqMktDepthExchangeszIB.reqMktDepthExchanges  s    
 yy779::r`   numRowsisSmartDepthc                     | j                   j                         }| j                  j                  ||d      }| j                   j	                  |||||       |S )ab  
        Subscribe to market depth data (a.k.a. DOM, L2 or order book).

        https://interactivebrokers.github.io/tws-api/market_depth.html

        Args:
            contract: Contract of interest.
            numRows: Number of depth level on each side of the order book
                (5 max).
            isSmartDepth: Consolidate the order book across exchanges.
            mktDepthOptions: Unknown.

        Returns:
            The Ticker that holds the market depth in ``ticker.domBids``
            and ``ticker.domAsks`` and the list of MktDepthData in
            ``ticker.domTicks``.
        mktDepth)rV   r  rU   r  reqMktDepth)r]   r   r  r  mktDepthOptionsr   r   s          r^   r  zIB.reqMktDepth  sQ    ( $$&))%:F8WlO	Er`   c                 L   | j                  |      }|r| j                  j                  |d      nd}|rS|rQ| j                  j	                  ||       |j
                  j                          |j                  j                          y| j                  j                  d|        y)z
        Unsubscribe from market depth data.

        Args:
            contract: The exact contract object that was used to
                subscribe with.
        r  r   z,cancelMktDepth: No reqId found for contract N)
r   rU   r  rV   cancelMktDepthdomBidscleardomAsksr[   r.  )r]   r   r  r   r   s        r^   r  zIB.cancelMktDepth8  s     X&>D&&vz:!eKK&&ul;NN  "NN  "LL>xjIKr`   periodc                 F    | j                  | j                  |||            S )a  
        Request histogram data.

        This method is blocking.

        https://interactivebrokers.github.io/tws-api/histograms.html

        Args:
            contract: Contract to query.
            useRTH: If True then only show data from within Regular
                Trading Hours, if False then show all data.
            period: Period of which data is being requested, for example
                '3 days'.
        )r   reqHistogramDataAsync)r]   r   rj  r  s       r^   reqHistogramDatazIB.reqHistogramDataJ  s)    " yy&&x@B 	Br`   
reportTypefundamentalDataOptionsc                 F    | j                  | j                  |||            S )a  
        Get fundamental data of a contract in XML format.

        This method is blocking.

        https://interactivebrokers.github.io/tws-api/fundamentals.html

        Args:
            contract: Contract to query.
            reportType:

                * 'ReportsFinSummary': Financial summary
                * 'ReportsOwnership': Company's ownership
                * 'ReportSnapshot': Company's financial overview
                * 'ReportsFinStatements': Financial Statements
                * 'RESC': Analyst Estimates
                * 'CalendarReport': Company's calendar
            fundamentalDataOptions: Unknown
        )r   reqFundamentalDataAsync)r]   r   r  r  s       r^   reqFundamentalDatazIB.reqFundamentalData^  s+    , yy((*&<>? 	?r`   subscriptionscannerSubscriptionOptions scannerSubscriptionFilterOptionsc                 F    | j                  | j                  |||            S )a  
        Do a blocking market scan by starting a subscription and canceling it
        after the initial list of results are in.

        This method is blocking.

        https://interactivebrokers.github.io/tws-api/market_scanners.html

        Args:
            subscription: Basic filters.
            scannerSubscriptionOptions: Unknown.
            scannerSubscriptionFilterOptions: Advanced generic filters.
        )r   reqScannerDataAsync)r]   r  r  r  s       r^   reqScannerDatazIB.reqScannerDatax  s,    $ yy$$8023 	3r`   c                 
   | j                   j                         }t               }||_        ||_        |xs g |_        |xs g |_        | j                  j                  ||       | j                   j                  ||||       |S )a  
        Subscribe to market scan data.

        https://interactivebrokers.github.io/tws-api/market_scanners.html

        Args:
            subscription: What to scan for.
            scannerSubscriptionOptions: Unknown.
            scannerSubscriptionFilterOptions: Unknown.
        )
rV   r  r#   r   r  r  r  rU   rm  reqScannerSubscription)r]   r  r  r  r   dataLists         r^   r  zIB.reqScannerSubscription  s     $$&> ,.H.NB+,2 	1&&uh7**<!;,	. r`   r  c                     | j                   j                  |j                         | j                  j	                  |       y)z
        Cancel market data subscription.

        https://interactivebrokers.github.io/tws-api/market_scanners.html

        Args:
            dataList: The scan data list that was obtained from
                :meth:`.reqScannerSubscription`.
        N)rV   cancelScannerSubscriptionr   rU   rr  )r]   r  s     r^   r  zIB.cancelScannerSubscription  s,     	--hnn=$$X.r`   c                 @    | j                  | j                               S )z_
        Requests an XML list of scanner parameters.

        This method is blocking.
        )r   reqScannerParametersAsyncr\   s    r^   reqScannerParameterszIB.reqScannerParameters  s     yy779::r`   optionPrice
underPriceimplVolOptionsc                 H    | j                  | j                  ||||            S )a  
        Calculate the volatility given the option price.

        This method is blocking.

        https://interactivebrokers.github.io/tws-api/option_computations.html

        Args:
            contract: Option contract.
            optionPrice: Option price to use in calculation.
            underPrice: Price of the underlier to use in calculation
            implVolOptions: Unknown
        )r   calculateImpliedVolatilityAsync)r]   r   r  r  r  s        r^   calculateImpliedVolatilityzIB.calculateImpliedVolatility  s/    " yy00+z>CD 	Dr`   
volatilityoptPrcOptionsc                 H    | j                  | j                  ||||            S )a  
        Calculate the option price given the volatility.

        This method is blocking.

        https://interactivebrokers.github.io/tws-api/option_computations.html

        Args:
            contract: Option contract.
            volatility: Option volatility to use in calculation.
            underPrice: Price of the underlier to use in calculation
            implVolOptions: Unknown
        )r   calculateOptionPriceAsync)r]   r   r  r  r  s        r^   calculateOptionPricezIB.calculateOptionPrice  s/    " yy***j-AB 	Br`   underlyingSymbolfutFopExchangeunderlyingSecTypeunderlyingConIdc                 H    | j                  | j                  ||||            S )a  
        Get the option chain.

        This method is blocking.

        https://interactivebrokers.github.io/tws-api/options.html

        Args:
            underlyingSymbol: Symbol of underlier contract.
            futFopExchange: Exchange (only for ``FuturesOption``, otherwise
                leave blank).
            underlyingSecType: The type of the underlying security, like
                'STK' or 'FUT'.
            underlyingConId: conId of the underlying contract.
        )r   reqSecDefOptParamsAsync)r]   r  r  r  r  s        r^   reqSecDefOptParamszIB.reqSecDefOptParams  s-    & yy(( .!?45 	5r`   exerciseActionexerciseQuantityoverridec                 x    | j                   j                         }| j                   j                  ||||||       y)a  
        Exercise an options contract.

        https://interactivebrokers.github.io/tws-api/options.html

        Args:
            contract: The option contract to be exercised.
            exerciseAction:
                * 1 = exercise the option
                * 2 = let the option lapse
            exerciseQuantity: Number of contracts to be exercised.
            account: Destination account.
            override:
                * 0 = no override
                * 1 = override the system's natural action
        N)rV   r  exerciseOptions)r]   r   r  r  r~   r  r   s          r^   r  zIB.exerciseOptions  s7    & $$&##8^-=X	r`   c                 @    | j                  | j                               S )zQ
        Get a list of news providers.

        This method is blocking.
        )r   reqNewsProvidersAsyncr\   s    r^   reqNewsProviderszIB.reqNewsProviders  s     yy33566r`   providerCode	articleIdnewsArticleOptionsc                 F    | j                  | j                  |||            S )aK  
        Get the body of a news article.

        This method is blocking.

        https://interactivebrokers.github.io/tws-api/news.html

        Args:
            providerCode: Code indicating news provider, like 'BZ' or 'FLY'.
            articleId: ID of the specific article.
            newsArticleOptions: Unknown.
        )r   reqNewsArticleAsync)r]   r  r  r  s       r^   reqNewsArticlezIB.reqNewsArticle"  s+     yy$$i);=> 	>r`   providerCodestotalResultshistoricalNewsOptionsc           
      L    | j                  | j                  ||||||            S )a  
        Get historical news headline.

        https://interactivebrokers.github.io/tws-api/news.html

        This method is blocking.

        Args:
            conId: Search news articles for contract with this conId.
            providerCodes: A '+'-separated list of provider codes, like
                'BZ+FLY'.
            startDateTime: The (exclusive) start of the date range.
                Can be given as a datetime.date or datetime.datetime,
                or it can be given as a string in 'yyyyMMdd HH:mm:ss' format.
                If no timezone is given then the TWS login timezone is used.
            endDateTime: The (inclusive) end of the date range.
                Can be given as a datetime.date or datetime.datetime,
                or it can be given as a string in 'yyyyMMdd HH:mm:ss' format.
                If no timezone is given then the TWS login timezone is used.
            totalResults: Maximum number of headlines to fetch (300 max).
            historicalNewsOptions: Unknown.
        )r   reqHistoricalNewsAsync)r]   r   r  r  rt  r  r  s          r^   reqHistoricalNewszIB.reqHistoricalNews5  s2    : yy''}m[356 	6r`   allMessagesc                 :    | j                   j                  |       y)z
        Subscribe to IB news bulletins.

        https://interactivebrokers.github.io/tws-api/news.html

        Args:
            allMessages: If True then fetch all messages for the day.
        N)rV   reqNewsBulletins)r]   r  s     r^   r  zIB.reqNewsBulletinsW  s     	$$[1r`   c                 8    | j                   j                          y)z)Cancel subscription to IB news bulletins.N)rV   cancelNewsBulletinsr\   s    r^   r  zIB.cancelNewsBulletinsb  s    '')r`   
faDataTypec                 B    | j                  | j                  |            S )ak  
        Requests to change the FA configuration.

        This method is blocking.

        Args:
            faDataType:

                * 1 = Groups: Offer traders a way to create a group of
                  accounts and apply a single allocation method to all
                  accounts in the group.
                * 2 = Profiles: Let you allocate shares on an
                  account-by-account basis using a predefined calculation
                  value.
                * 3 = Account Aliases: Let you easily identify the accounts
                  by meaningful names rather than account numbers.
        )r   requestFAAsync)r]   r  s     r^   	requestFAzIB.requestFAf  s    $ yy,,Z899r`   xmlc                 r    | j                   j                         }| j                   j                  |||       y)z
        Replaces Financial Advisor's settings.

        Args:
            faDataType: See :meth:`.requestFA`.
            xml: The XML-formatted configuration string.
        N)rV   r  	replaceFA)r]   r  r  r   s       r^   r  zIB.replaceFAz  s,     $$&eZ5r`   c                     | j                   j                  r| j                  j                  d       y| j                  j                         }|| j                   _        | j                  j                  |       y)z
        Request Wall Street Horizon metadata.

        https://interactivebrokers.github.io/tws-api/fundamentals.html
        zreqWshMetaData already activeN)rU   wshMetaReqIdr[   warningrV   r  reqWshMetaDatar]   r   s     r^   r  zIB.reqWshMetaData  sT     <<$$LL  !@AKK((*E(-DLL%KK&&u-r`   c                     | j                   j                  }|s| j                  j                  d       y| j                  j                  |       d| j                   _        y)zCancel WSH metadata.zreqWshMetaData not activer   N)rU   r  r[   r  rV   cancelWshMetaDatar   s     r^   r  zIB.cancelWshMetaData  sE    ))LL  !<=KK))%0()DLL%r`   datac                     | j                   j                  r| j                  j                  d       y| j                  j                         }|| j                   _        | j                  j                  ||       y)a1  
        Request Wall Street Horizon event data.

        :meth:`.reqWshMetaData` must have been called first before using this
        method.

        Args:
            data: Filters for selecting the corporate event data.

        https://interactivebrokers.github.io/tws-api/wshe_filters.html
        zreqWshEventData already activeN)rU   wshEventReqIdr[   r  rV   r  reqWshEventData)r]   r  r   s      r^   r  zIB.reqWshEventData  sV     <<%%LL  !ABKK((*E).DLL&KK''t4r`   c                     | j                   j                  }|s| j                  j                  d       y| j                  j                  |       d| j                   _        y)zCancel active WHS event data.zreqWshEventData not activer   N)rU   r  r[   r  rV   cancelWshEventDatar   s     r^   r  zIB.cancelWshEventData  sE    **LL  !=>KK**51)*DLL&r`   c                 @    | j                  | j                               S )ze
        Blocking convenience method that returns the WSH metadata as
        a JSON string.
        )r   getWshMetaDataAsyncr\   s    r^   getWshMetaDatazIB.getWshMetaData  s    
 yy11344r`   c                 B    | j                  | j                  |            S )z
        Blocking convenience method that returns the WSH event data as
        a JSON string. The request is automatically cancelled after completion.
        )r   getWshEventDataAsync)r]   r  s     r^   getWshEventDatazIB.getWshEventData  s    
 yy224899r`   c                 @    | j                  | j                               S )z&Get the White Branding ID of the user.)r   reqUserInfoAsyncr\   s    r^   reqUserInfozIB.reqUserInfo  s    yy..011r`   c                   K   t        |      }|| j                  _        |xs d }	 | j                  j	                  ||||       d {    |dk(  r| j                  d       | j                  j                         }|st        |      dk(  r|d   }i }| j                         |d<   |s| j                         |d<   |s1| j                  j                         dk\  r| j                  d      |d<   |r| j                  |      |d	<   t        |      | j                  k  r|D ]  }	| j                  |	      |d
|	 <    |j                         D 
cg c]  }
t!        j"                  |
|       }}
t!        j$                  |ddi d {   }t'        ||      D ]>  \  }}t)        |t         j*                        s!| j,                  j/                  | d       @ t!        j"                  | j1                         |       d {    | j                  j3                         st5        d      | j,                  j7                  d       | j8                  j;                          | S 7 c c}
w 7 7 j# t<        $ r | j?                           w xY ww)Nr   Tr{   r   zopen orders   Fzcompleted orderszaccount updateszaccount updates for return_exceptionsz request timed outz)Socket connection broken while connectingzSynchronization complete) intrU   rv   rV   r   r?  getAccountslenrO  rA  serverVersionrH  r6  rP   r9  r   r   r   gatherzip
isinstancer   r[   r.  rL  r   ConnectionErrorr   r4   r   BaseExceptionre   )r]   rt   ru   rv   r|   r}   r~   r   reqsaccreqtasksrespsnameresps                  r^   r   zIB.connectAsync  sy     x= (/T/	++**4xIII 1}&&t,{{..0Hs8}1"1+ D $ 6 6 8D&*&=&=&?]# 9 9 ;s B+/+G+G+N'(*.*E*Eg*N&'8} 9 99# >C88= /u56>  ;;=*   g.*E * "..%H4HHE!$. D
ddG$8$89LL&&$/A'BCD
 ""4#:#:#<gFFF ;;&&(%?A A LL89$$& ] J2* I G  	OO	sg   #J!I) IDI) I )I) I%0I) 5AI) <I'=AI) JI)  I) 'I) )JJc                 b   K   t        j                   fd|D          d {   }g }t        ||      D ]  \  }}|s j                  j	                  d|        't        |      dkD  r;|D cg c]  }|j                   }} j                  j	                  d| d|        p|d   j                  }|j                  }	|	r|	j                         d   }	|	|_        |j                  dk(  r|j                  |_	        t        j                  ||       |j                  |        |S 7 c c}w w)Nc              3   @   K   | ]  }j                  |        y wrc   )r^  )r   cr]   s     r^   r   z+IB.qualifyContractsAsync.<locals>.<genexpr>  s     A!d**1-As   zUnknown contract: r{   zAmbiguous contract: z, possibles are r   SMART)r   r  r  r[   r  r  r   lastTradeDateOrContractMonthsplitexchanger   dataclassUpdater  )
r]   r   detailsListsresultr   detailsListdetails	possiblesr'  expirys
   `         r^   r   zIB.qualifyContractsAsync  s0    $^^AyAC C%(L%A 	(!Hk$$'9(%DE[!A%=HI'W--I	I$$*8* 5%%.K12  N++77#\\^A.F5;A2$$/!)!2!2AJ$$Xq1h''	(( /C Js#   D/D'AD/.D*B'D/*D/c          	        K   g }g }g }|D ]  }| j                   j                         }|j                  |       | j                  j	                  ||      }|j                  |       | j                  j                  ||d      }	|j                  |	       | j                   j                  ||dd|g         t        j                  |  d {    |D ]  }	| j                  j                  |	d         |S 7 )w)Nr  rQ   T)
rV   r  r  rU   startReqr  r  r   r  r  )
r]   r   r   futuresr   reqIdsr   r   futurer   s
             r^   r   zIB.reqTickersAsync  s      ! 	CHKK((*EMM% \\**5(;FNN6"\\--eXzJFNN6"KK""xT+=rC	C nng&&& 	7FLL""6:6	7 	's   C	C7C5*C7c                     t        j                   |      }d|_        | j                  j                         }| j                  j                  ||      }| j                  j                  |||       |S )NT)copywhatIfrV   r  rU   r4  r  )r]   r   r   r  r   r7  s         r^   r  zIB.whatIfOrderAsync3  s[    ii&!$$&&&uh7uh<r`   c                 p    | j                   j                  d      }| j                  j                          |S )NcurrentTime)rU   r4  rV   r4  r]   r7  s     r^   r3  zIB.reqCurrentTimeAsync<  s+    &&}5""$r`   c                 t    | j                   j                  d      }| j                  j                  d|       |S )Nr   T)rU   r4  rV   r7  )r]   r~   r7  s      r^   r6  zIB.reqAccountUpdatesAsyncA  s/    &&7%%dG4r`   c                     | j                   j                         }| j                  j                  |      }| j                   j	                  |||d       |S )NF)rV   r  rU   r4  r:  )r]   r~   r   r   r7  s        r^   r9  zIB.reqAccountUpdatesMultiAsyncF  sE    $$&&&u-**5'9eLr`   c                 T  K   | j                   j                  s| j                          d {    |rA| j                   j                  j                         D cg c]  }|j                  |k(  r| c}S t        | j                   j                  j                               S 7 tc c}w wrc   )rU   acctSummaryr   r   r~   r   r   s      r^   r   zIB.accountSummaryAsyncM  s     ||''--///#||77>>@ -!yyG+  - - 00779:: 0-s!   *B(B!,B(B#11B(#B(c                     | j                   j                         }| j                  j                  |      }d}| j                   j	                  |d|       |S )NaA  AccountType,NetLiquidation,TotalCashValue,SettledCash,AccruedCash,BuyingPower,EquityWithLoanValue,PreviousDayEquityWithLoanValue,GrossPositionValue,RegTEquity,RegTMargin,SMA,InitMarginReq,MaintMarginReq,AvailableFunds,ExcessLiquidity,Cushion,FullInitMarginReq,FullMaintMarginReq,FullAvailableFunds,FullExcessLiquidity,LookAheadNextChange,LookAheadInitMarginReq,LookAheadMaintMarginReq,LookAheadAvailableFunds,LookAheadExcessLiquidity,HighestSeverity,DayTradesRemaining,DayTradesRemainingT+1,DayTradesRemainingT+2,DayTradesRemainingT+3,DayTradesRemainingT+4,Leverage,$LEDGER:ALLAll)rV   r  rU   r4  r<  )r]   r   r7  tagss       r^   r   zIB.reqAccountSummaryAsyncX  sO    $$&&&u-
9 	 	%%eUD9r`   c                 p    | j                   j                  d      }| j                  j                          |S Nr   )rU   r4  rV   rB  r=  s     r^   rA  zIB.reqOpenOrdersAsyncj  s+    &&|4!!#r`   c                 p    | j                   j                  d      }| j                  j                          |S rF  )rU   r4  rV   rE  r=  s     r^   rD  zIB.reqAllOpenOrdersAsynco  s+    &&|4$$&r`   c                 r    | j                   j                  d      }| j                  j                  |       |S )NcompletedOrders)rU   r4  rV   rI  )r]   rF  r7  s      r^   rH  zIB.reqCompletedOrdersAsynct  s.    &&'89&&w/r`   c                     |xs
 t               }| j                  j                         }| j                  j	                  |      }| j                  j                  ||       |S rc   )r   rV   r  rU   r4  rM  )r]   rJ  r   r7  s       r^   rL  zIB.reqExecutionsAsyncy  sP      4?#4
$$&&&u-!!%4r`   c                 p    | j                   j                  d      }| j                  j                          |S )Nr   )rU   r4  rV   rP  r=  s     r^   rO  zIB.reqPositionsAsync  s+    &&{3  "r`   c                     | j                   j                         }| j                  j                  ||      }| j                   j	                  ||       |S rc   )rV   r  rU   r4  r_  )r]   r   r   r7  s       r^   r^  zIB.reqContractDetailsAsync  sC    $$&&&uh7&&uh7r`   c                 v  K   | j                   j                         }| j                  j                  |      }| j                   j	                  ||       	 t        j                  |d       d {    |j                         S 7 # t
        j                  $ r | j                  j                  d       Y y w xY ww)N   z reqMatchingSymbolsAsync: Timeout)rV   r  rU   r4  rc  r   r   r.  r   r[   r.  )r]   r`  r   r7  s       r^   rb  zIB.reqMatchingSymbolsAsync  s     $$&&&u-&&ug6	""61---==?" .## 	LLAB	s<   AB9B .B/B B9B .B63B95B66B9c                 F  K   | j                   j                  d|       }	 | j                  j                  |       t	        j
                  |d       d {    |j                         S 7 # t        j                  $ r | j                  j                  d       Y y w xY ww)NzmarketRule-r{   zreqMarketRuleAsync: Timeout)
rU   r4  rV   rg  r   r   r.  r   r[   r.  )r]   rd  r7  s      r^   rf  zIB.reqMarketRuleAsync  s     &&\N'CD	KK%%l3""61---==?" .## 	LL<=	s:   B!4A- A+A- *B!+A- -.BB!BB!c                   K   | j                   j                         }t               }||_        ||_        ||_        ||_        ||_        ||_        ||_	        ||_
        ||_        |	xs g |_        | j                  j                  |||      }|r| j                  j                  |||       t!        j"                  |      }| j                   j%                  ||||||||||	
       |
rt'        j(                  ||
      n|}	 | d {    |S 7 # t&        j*                  $ rM | j                   j-                  |       | j.                  j1                  d|        |j3                          Y |S w xY ww)N	containerzreqHistoricalData: Timeout for )rV   r  r   r   r   rt  ru  rv  ri  rj  rw  rx  ry  rU   r4  rm  r   formatIBDatetimer|  r   r   r   r~  r[   r  r  )r]   r   rt  ru  rv  ri  rj  rw  rx  ry  r|   r   ro  r7  endtasks                   r^   r{  zIB.reqHistoricalDataAsync  s\     $$&}
 &&,$$((.B&&uh$&GLL**5$A##K0%%8S+~
L,	H 5<w0	JJ
  ## 	KK,,U3LL  #B8*!MNJJL		s=   C?E3D DD E3D AE0,E3/E00E3c                     | j                   j                         }| j                  j                  ||      }t	        j
                  |      }| j                   j                  |||| ddd|ddd 
       |S )Nz Dz1 daySCHEDULEr{   F)rV   r  rU   r4  r   rS  r|  )r]   r   r  rt  rj  r   r7  rT  s           r^   r  zIB.reqHistoricalScheduleAsync  sq    
 $$&&&uh7##K0%%8SWIR.':Aud	$ r`   c	                    | j                   j                         }	| j                  j                  |	|      }
t	        j
                  |      }t	        j
                  |      }| j                   j                  |	||||||||	       |
S rc   )rV   r  rU   r4  r   rS  r  )r]   r   r  rt  r  ri  r  r  r  r   r7  startrT  s                r^   r  zIB.reqHistoricalTicksAsync  sy     $$&&&uh7%%m4##K0&&8UC
F	% r`   c                 "  K   | j                   j                         }| j                  j                  ||      }| j                   j	                  |||||       | d {    | j                   j                  |       |j                         S 7 /wrc   )rV   r  rU   r4  r  cancelHeadTimeStampr.  )r]   r   ri  rj  rw  r   r7  s          r^   r  zIB.reqHeadTimeStampAsync  sw      $$&&&uh7$$8Z	=''.}} 	s   ABB0Bc                     | j                   j                         }| j                  j                  |      }| j                   j	                  ||       |S rc   )rV   r  rU   r4  r  )r]   r  r   r7  s       r^   r  zIB.reqSmartComponentsAsync  sA    $$&&&u-&&uk:r`   c                 p    | j                   j                  d      }| j                  j                          |S )NmktDepthExchanges)rU   r4  rV   r  r=  s     r^   r  zIB.reqMktDepthExchangesAsync  s,    &&':;((*r`   c                     | j                   j                         }| j                  j                  ||      }| j                   j	                  ||||       |S rc   )rV   r  rU   r4  r  )r]   r   rj  r  r   r7  s         r^   r  zIB.reqHistogramDataAsync  sI     $$&&&uh7$$UHffEr`   c                     | j                   j                         }| j                  j                  ||      }| j                   j	                  ||||       |S rc   )rV   r  rU   r4  r  )r]   r   r  r  r   r7  s         r^   r  zIB.reqFundamentalDataAsync  sN     $$&&&uh7&&8Z)?	Ar`   c                   K   | j                  ||xs g |xs g       }| j                  j                  |j                  |      }| d {    | j                  j                  |j                         |j                         S 7 9w)NrQ  )r  rU   r4  r   rV   r  r.  )r]   r  r  r  r  r7  s         r^   r  zIB.reqScannerDataAsync  sx     
 ..4:,24 &&x~~&J--hnn=}} 	s   AB
B:Bc                 p    | j                   j                  d      }| j                  j                          |S )NscannerParams)rU   r4  rV   r  r=  s     r^   r  zIB.reqScannerParametersAsync  s+    &&7((*r`   c                 *  K   | j                   j                         }| j                  j                  ||      }| j                   j	                  |||||       	 t        j                  |d       d {    |j                         | j                   j                  |       S 7 /# t
        j                  $ r9 | j                  j                  d       Y | j                   j                  |       y w xY w# | j                   j                  |       w xY ww)NrN  z(calculateImpliedVolatilityAsync: Timeout)rV   r  rU   r4  r  r   r   r.   cancelCalculateImpliedVolatilityr   r[   r.  )r]   r   r  r  r  r   r7  s          r^   r  z"IB.calculateImpliedVolatilityAsync!  s     
 $$&&&uh7..8[*n	F	@""61---==?
 KK88? .## 	LLIJKK88?		 KK88?N   ADB$ 2B"3B$ D"B$ $.C0C3 D/C00C3 3DDc                 *  K   | j                   j                         }| j                  j                  ||      }| j                   j	                  |||||       	 t        j                  |d       d {    |j                         | j                   j                  |       S 7 /# t
        j                  $ r9 | j                  j                  d       Y | j                   j                  |       y w xY w# | j                   j                  |       w xY ww)NrN  z"calculateOptionPriceAsync: Timeout)rV   r  rU   r4  r  r   r   r.  cancelCalculateOptionPricer   r[   r.  )r]   r   r  r  r  r   r7  s          r^   r  zIB.calculateOptionPriceAsync3  s      $$&&&uh7((8Z]	D	:""61---==?
 KK2259 .## 	LLCDKK2259		 KK2259rf  c                     | j                   j                         }| j                  j                  |      }| j                   j	                  |||||       |S rc   )rV   r  rU   r4  r  )r]   r  r  r  r  r   r7  s          r^   r  zIB.reqSecDefOptParamsAsyncD  sP     $$&&&u-&&#^	0 r`   c                 p    | j                   j                  d      }| j                  j                          |S )NnewsProviders)rU   r4  rV   r  r=  s     r^   r  zIB.reqNewsProvidersAsyncO  s+    &&7$$&r`   c                     | j                   j                         }| j                  j                  |      }| j                   j	                  ||||       |S rc   )rV   r  rU   r4  r  )r]   r  r  r  r   r7  s         r^   r  zIB.reqNewsArticleAsyncT  sL     $$&&&u-""<,>	@r`   c           	        K   | j                   j                         }| j                  j                  |      }t	        j
                  |      }	t	        j
                  |      }
| j                   j                  ||||	|
||       	 t        j                  |d       d {    |j                         S 7 # t        j                  $ r | j                  j                  d       Y y w xY ww)NrN  zreqHistoricalNewsAsync: Timeout)rV   r  rU   r4  r   rS  r  r   r   r.  r   r[   r.  )r]   r   r  r  rt  r  r  r   r7  rY  rT  s              r^   r  zIB.reqHistoricalNewsAsync^  s      $$&&&u-%%m4##K0%%5-/	1	""61---==?" .## 	LL@A	s<   BC(B4 B2B4 1C(2B4 4.C%"C($C%%C(c                 @  K   | j                   j                  d      }| j                  j                  |       	 t	        j
                  |d       d {    |j                         S 7 # t        j                  $ r | j                  j                  d       Y y w xY ww)Nr  rN  zrequestFAAsync: Timeout)
rU   r4  rV   r  r   r   r.  r   r[   r.  )r]   r  r7  s      r^   r  zIB.requestFAAsyncs  s     &&{3j)	:""61---==?" .## 	:LL89	:s:   7BA* A(A* 'B(A* *.BBBBc                   K   | j                   j                  r| j                          | j                          | j                   j	                  | j                   j                  d      }| d {    |j                         S 7 wNrQ   rQ  )rU   r  r  r  r4  r.  r=  s     r^   r
  zIB.getWshMetaDataAsync|  sk     <<$$""$&&LL%% ' 5}} 	s   A-B/B0Bc                 2  K   | j                   j                  r| j                          | j                  |       | j                   j	                  | j                   j                  d      }| d {    | j                          |j                         S 7 $wrp  )rU   r  r  r  r4  r.  )r]   r  r7  s      r^   r  zIB.getWshEventDataAsync  sy     <<%%##%T"&&LL&&" ' 6!}} 	s   A.B0B1%Bc                     | j                   j                         }| j                  j                  |      }| j                   j	                  |       |S rc   )rV   r  rU   r4  r  )r]   r   r7  s      r^   r  zIB.reqUserInfoAsync  s?    $$&&&u-&r`   )	127.0.0.1I  r{   rN  FrQ   )r   )Nr   )r   )rQ   )rQ   rQ   )rQ   rQ   r   )Trc   )rQ   T)r{   )r   F)   FN)F)__name__
__module__rx   __doc__eventsrM   float__annotations__rN   boolrP   r  rR   strr_   rT   rf   rj   rm   rz   r   re   rs   rW   staticmethodr   r   schedulesleep	timeRangetimeRangeAsync	waitUntilr   r   r   r   objectr   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   r0   r   r   r   r   r   r"   r   r   r   r   r   r   r   r)   r  r  r,   r  r  r&  r1  r  r4  r7  r:  r<  r?  rB  rE  rI  r   rM  rP  rS  rW  rZ  r\  r   r_  r   rc  r!   rg  r&   rn  rq  dater|  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  r   r  r   r  r  r  r  r  r  r  r(   r  r  r  r  r  r   r   r   r  r3  r6  r9  r   r   rA  rD  rH  rL  rO  r^  rb  rf  r{  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r
  r  r  ri   r`   r^   r3   r3      s   _B
&F NE$$ "#"K9269 NOGI??14?GJ??*.?AD?2&$%T %A txx
 CDMM*H$ET^^,I!$"5"56NT^^,IB	 BE $ 8 45G+0G9A&9IG2)% )+c +=S =$|2D =
<c 
<43E 
<) )d=.A )) )d8n )AtCy A  79550355#I5&2U 2GDK G
CU C
KDK K
1tDz 1LDO L	6x 	6HV,< 	63f 31V 1<d5o)E#FG <&4> &>tL1 > (-D&D $D15fD"A8 AX A):):).):):05): !): 0<):V K+.9<AEe AH AU Az A$8 $E $e $L" "s ""H-5 1 1 58 8  79HH03H	10$ 0 4tE{ 47$u+ 7@$ @4; @ ;?>&7>CG:>3d8n 3c c 3 ,=C =$+.7:?H0LL+.L7:L*A8 A_8M A$@# @$7J2K @@# @. @$ 35$/2%) "&h :I>+ + -.E+-4J$4Jx00(--dJK4J 4J /24J @C4J 	4J '*	4J >B	4J
 x.4J
 9>4J 4Jl
+ 
+ @B	5$5/25!!8==#t;=5 	5 %7	58  %*,#>$#> hmm!34#> sHMM12#> 	#> -0	#> :>	#>
 #> h#> 26#>J6 6$ -.;$;25;;&);2:2C2C;& >@"u-/:$:7:::8<: !N: 5;:xMh M$ 8=$0304AG*JX J J Dc Dd>6J D;d+B&C ; 678<$/2AG4Kx K$B$BB"%B*.}*=B, 68?$?25?$(N?<??8 :<?A3 33(,X3 /38n3 	32 :<?A 3(,X /38n 	8/, /;c ; .0D$DD,1D !ND 5FD0 -/B$BB+0B  >B 4EB*5$'55475 !5 &*+%650$69!,/;>07$|"4 7 24> #>03> $X>8C>0 57 6 6-0 6 hmm!34 6 sHMM12 6 	 6
 $(> 6  6D	2D 	2*:C :(	6C 	6c 	6.*5L 5&+5 5:L :S :2S 2 8<:;35771477(07 7 .17rh H~8 DI&<@F|( % $Yx/@/@%A 
c io  24+.8A$	; 	;L!	;	$ $Id5k$: 
ye'= 
t 	$u+8N  ;?&7d$9T(^#< 
 o./
S 
012
	 #	(0n1E(F	   e+-"$"x00(--dJK" " /2" 	" &*	"
 "
 04" x." 9>" "N @B	$/2!!8==#t;= 	 %..@$A	$  %*,$ hmm!34 sHMM12 	 -0	 :>	
  h 2;4 	$	25		&)	.6.?.?	567$.2<?m,- 68$25$(N ~ :<?A 3(,X /38n 	9S>  .0@$@@,1@ !N@ )*	@* -/:$::+0:  >: 4<<M3N:"	$'		47	 !	 &/tK/@%A	yl1C'D  24 #03 $X % 57-0 hmm!34 sHMM12 	
 $(> '*:s :3 |  r`   r3   __main__Trs  rt  r{   )rv   )Irx  r   r9  r  rY   r   typingr   r   r   r   r   r   eventkitr	   ib_insync.utilr   ib_insync.clientr
   ib_insync.contractr   r   r   ib_insync.objectsr   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(   ib_insync.orderr)   r*   r+   r,   r-   r.   r/   ib_insync.tickerr0   ib_insync.wrapperr1   r3   rv  getLooploop	set_debuglogToConsoleDEBUGibr   re   ri   r`   r^   <module>r     s    2      C C   # M M+ + + + + + + +P P P # %w! w!tC z4<<>DNN4Dgmm$	BJJ{D1J-MMO r`   