
    T>qj0                     <   d Z ddlZddlZddlZddlmZ ddlmZ ddlm	Z	 ddl
mZ ddlmZ ddlmZmZ ddlmZ e G d	 d
             Ze G d d             Zedk(  r? eddd      Z e       Z eeed      Zej3                           ej4                          yy)z:Programmatic control over the TWS/gateway client software.    N)suppress)	dataclass)ClassVar)Event)ContractForex)IBc                      e Zd ZU dZej
                  Zeed<   dZ	e
ed<   dZeed<   dZeed<   dZeed	<   dZeed
<   dZeed<   dZeed<   dZeed<   dZeed<   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d Zd Z y)IBCaH  
    Programmatic control over starting and stopping TWS/Gateway
    using IBC (https://github.com/IbcAlpha/IBC).

    Args:
        twsVersion (int): (required) The major version number for
            TWS or gateway.
        gateway (bool):
            * True = gateway
            * False = TWS
        tradingMode (str): 'live' or 'paper'.
        userid (str): IB account username. It is recommended to set the real
            username/password in a secured IBC config file.
        password (str): IB account password.
        twsPath (str): Path to the TWS installation folder.
            Defaults:

            * Linux:    ~/Jts
            * OS X:     ~/Applications
            * Windows:  C:\\Jts
        twsSettingsPath (str): Path to the TWS settings folder.
            Defaults:

            * Linux:     ~/Jts
            * OS X:      ~/Jts
            * Windows:   Not available
        ibcPath (str): Path to the IBC installation folder.
            Defaults:

            * Linux:     /opt/ibc
            * OS X:      /opt/ibc
            * Windows:   C:\\IBC
        ibcIni (str): Path to the IBC configuration file.
            Defaults:

            * Linux:     ~/ibc/config.ini
            * OS X:      ~/ibc/config.ini
            * Windows:   %%HOMEPATH%%\\Documents\IBC\\config.ini
        javaPath (str): Path to Java executable.
            Default is to use the Java VM included with TWS/gateway.
        fixuserid (str): FIX account user id (gateway only).
        fixpassword (str): FIX account password (gateway only).
        on2fatimeout (str): What to do if 2-factor authentication times
            out; Can be 'restart' or 'exit'.

    This is not intended to be run in a notebook.

    To use IBC on Windows, the proactor (or quamash) event loop
    must have been set:

    .. code-block:: python

        import asyncio
        asyncio.set_event_loop(asyncio.ProactorEventLoop())

    Example usage:

    .. code-block:: python

        ibc = IBC(976, gateway=True, tradingMode='live',
            userid='edemo', password='demouser')
        ibc.start()
        IB.run()
    IbcLogLevelr   
twsVersionFgateway tradingModetwsPathtwsSettingsPathibcPathibcInijavaPathuseridpassword	fixuseridfixpasswordon2fatimeoutc                     t         j                  dk(  | _        | j                  s| j                  sdnd| _        d | _        d | _        t        j                  d      | _        y )Nwin32z/opt/ibczC:\IBCzib_insync.IBC)	sysplatform
_isWindowsr   _proc_monitorlogging	getLogger_loggerselfs    U/opt/rentech/trading_bot/.venv/lib/python3.12/site-packages/ib_insync/ibcontroller.py__post_init__zIBC.__post_init__d   sH    ,,'1||-1__:)DL
((9    c                 &    | j                          | S N)startr%   s    r'   	__enter__zIBC.__enter__l   s    

r)   c                 $    | j                          y r+   )	terminate)r&   _excs     r'   __exit__zIBC.__exit__p   s    r)   c                 J    t        j                  | j                                y)zLaunch TWS/IBG.N)utilrun
startAsyncr%   s    r'   r,   z	IBC.starts   s    "#r)   c                 J    t        j                  | j                                y)zTerminate TWS/IBG.N)r3   r4   terminateAsyncr%   s    r'   r/   zIBC.terminatew   s    $$&'r)   c                   K   | j                   ry | j                  j                  d       t        dddddddd	d
dddd      }| j                  r| j
                   dn| j
                   dg}t        j                  |       j                         D ]  \  }}||   | j                     }|s|j                  d      s|j                  d      r|j                  | |        S|r|j                  |       g|j                  t        |              t        j                  |dt        j                  j                  i d {   | _         t        j                   | j#                               | _        y 7 2w)NStarting)r   r   )z	--gatewayz/Gateway)z--mode=z/Mode:)z--tws-path=z	/TwsPath:)z--tws-settings-path=r   )z--ibc-path=z	/IbcPath:)z
--ibc-ini=z/Config:)z--java-path=z
/JavaPath:)z--user=z/User:)z--pw=z/PW:)z--fix-user=z	/FIXUser:)z	--fix-pw=z/FIXPW:)z--on2fatimeout=z/On2FATimeout:)r   r   r   r   r   r   r   r   r   r   r   r   r   z\scripts\StartIBC.batz/scripts/ibcstart.sh=:stdout)r    r$   infodictr   r   r3   dataclassAsDictitemsendswithappendstrasynciocreate_subprocess_exec
subprocessPIPEensure_futuremonitorAsyncr!   )r&   argscmdkvargs         r'   r5   zIBC.startAsync{   sY    ::*% --080-3(&20>
$ 9=t||n34||n013 ((.446 	'DAqq'$//*C<<$S(9JJ#qc{+JJsOJJs1v&	' #992 ++002 2
--d.?.?.AB2s   B)E9,BE9E73E9c           	      ,  K   | j                   sy | j                  j                  d       | j                  r!| j                  j	                          d | _        | j
                  r?dd l}|j                  ddddt        | j                   j                        g       d | _         y t        t              5  | j                   j                          | j                   j                          d {    d d d        d | _         y 7 # 1 sw Y   d | _         y xY ww)NTerminatingr   taskkillz/Fz/Tz/PID)r    r$   r=   r!   cancelr   rF   callrC   pidr   ProcessLookupErrorr/   wait)r&   rF   s     r'   r7   zIBC.terminateAsync   s     zz-(==MM  " DM??OOT4TZZ^^1DEG 
 ,- (

$$&jjoo'''( 
 (( 
s0   B0D28D*C?+D/D?DDDc                 .  K   | j                   r| j                   j                  j                          d {   }|sy | j                  j	                  t
        j                  |j                         j                                | j                   ry y 7 \wr+   )	r    r<   readliner$   logr   r   stripdecode)r&   lines     r'   rI   zIBC.monitorAsync   sa     jj**3355DLLS__djjl.A.A.CD	 jj5s   4BBABBN)!__name__
__module____qualname____doc__r"   DEBUGr   r   __annotations__r   intr   boolr   rC   r   r   r   r   r   r   r   r   r   r   r(   r-   r1   r,   r/   r5   r7   rI    r)   r'   r   r      s    ?B $MMK)JGTKGSOSGSFCHcFCHcIsKL#:$('CR"Er)   r   c                       e Zd ZU dZg dZeed<   eed<   dZe	ed<   dZ
eed<   d	Zeed
<   dZeed<   dZeed<   dZeed<   dZeed<   dZeed<   dZe	ed<    ed      Zeed<   dZeed<   d Zd Zd Zd Zy)Watchdoga	  
    Start, connect and watch over the TWS or gateway app and try to keep it
    up and running. It is intended to be used in an event-driven
    application that properly initializes itself upon (re-)connect.

    It is not intended to be used in a notebook or in imperative-style code.
    Do not expect Watchdog to magically shield you from reality. Do not use
    Watchdog unless you understand what it does and doesn't do.

    Args:
        controller (IBC): (required) IBC instance.
        ib (IB): (required) IB instance to be used. Do not connect this
            instance as Watchdog takes care of that.
        host (str): Used for connecting IB instance.
        port (int):  Used for connecting IB instance.
        clientId (int):  Used for connecting IB instance.
        connectTimeout (float):  Used for connecting IB instance.
        readonly (bool): Used for connecting IB instance.
        appStartupTime (float): Time (in seconds) that the app is given
            to start up. Make sure that it is given ample time.
        appTimeout (float): Timeout (in seconds) for network traffic idle time.
        retryDelay (float): Time (in seconds) to restart app after a
            previous failure.
        probeContract (Contract): Contract to use for historical data
            probe requests (default is EURUSD).
        probeTimeout (float); Timeout (in seconds) for the probe request.

    The idea is to wait until there is no traffic coming from the app for
    a certain amount of time (the ``appTimeout`` parameter). This triggers
    a historical request to be placed just to see if the app is still alive
    and well. If yes, then continue, if no then restart the whole app
    and reconnect. Restarting will also occur directly on errors 1100 and 100.

    Example usage:

    .. code-block:: python

        def onConnected():
            print(ib.accountValues())

        ibc = IBC(974, gateway=True, tradingMode='paper')
        ib = IB()
        ib.connectedEvent += onConnected
        watchdog = Watchdog(ibc, ib, port=4002)
        watchdog.start()
        ib.run()

    Events:
        * ``startingEvent`` (watchdog: :class:`.Watchdog`)
        * ``startedEvent`` (watchdog: :class:`.Watchdog`)
        * ``stoppingEvent`` (watchdog: :class:`.Watchdog`)
        * ``stoppedEvent`` (watchdog: :class:`.Watchdog`)
        * ``softTimeoutEvent`` (watchdog: :class:`.Watchdog`)
        * ``hardTimeoutEvent`` (watchdog: :class:`.Watchdog`)
    )startingEventstartedEventstoppingEventstoppedEventsoftTimeoutEventhardTimeoutEvent
controlleribz	127.0.0.1hostiI  port   clientId   connectTimeout   appStartupTime   
appTimeout
retryDelayFreadonlyr   accountEURUSDprobeContract   probeTimeoutc                    t        d      | _        t        d      | _        t        d      | _        t        d      | _        t        d      | _        t        d      | _        | j                  st        d      | j                  st        d      | j                  j                         rt        d	      d | _        t        j                  d
      | _        y )Nrh   ri   rj   rk   rl   rm   zNo controller suppliedzNo IB instance suppliedz!IB instance must not be connectedzib_insync.Watchdog)r   rh   ri   rj   rk   rl   rm   rn   
ValueErrorro   isConnected_runnerr"   r#   r$   r%   s    r'   r(   zWatchdog.__post_init__	  s    "?3!.1"?3!.1 %&8 9 %&8 9566ww67777 @AA(()=>r)   c                     | j                   j                  d       | j                  j                  |        t	        j
                  | j                               | _        | j                  S )Nr9   )r$   r=   rh   emitrD   rH   runAsyncr   r%   s    r'   r,   zWatchdog.start  sJ    *%%,,T]]_=||r)   c                     | j                   j                  d       | j                  j                  |        | j                  j                          d | _        y )NStopping)r$   r=   rj   r   ro   
disconnectr   r%   s    r'   stopzWatchdog.stop  s?    *%%r)   c                 	  K   fd}fd}fd}| j                   rZ	 | j                  j                          d {    t        j                  | j
                         d {    | j                  j                  | j                  | j                  | j                  | j                  | j                  | j                         d {    | j                  j                  |        | j                  j!                  | j"                         | j                  xj$                  |z  c_        | j                  xj&                  |z  c_        | j                  xj(                  |z  c_        | j                   r%t        j*                          d {    | j,                  j/                  d       | j0                  j                  |        | j                  j3                  | j4                  ddddd	      }d }t7        t        j8                        5  t        j:                  || j<                         d {   }d d d        |s&| j>                  j                  |        tA        d
      | j                  j!                  | j"                         | j                   r%| j                  xj$                  |z  c_        | j                  xj&                  |z  c_        | j                  xj(                  |z  c_        | j                  jK                          d {    | jL                  j                  |        | j                   r(t        j                  | jN                         d {    	 | j                   rYy y 7 =7 7 7 7 R# 1 sw Y   RxY w# tB        $ r Y t@        $ r&}| j,                  jE                  |       Y d }~/d }~wtF        $ r&}| j,                  jI                  |       Y d }~\d }~ww xY w7 7 # | j                  xj$                  |z  c_        | j                  xj&                  |z  c_        | j                  xj(                  |z  c_        | j                  jK                          d {  7   | jL                  j                  |        | j                   r)t        j                  | jN                         d {  7   w w xY ww)Nc                 J    j                         sj                  d        y y r+   )done
set_result)
idlePeriodwaiters    r'   	onTimeoutz$Watchdog.runAsync.<locals>.onTimeout'  s    ;;=!!$' !r)   c                 l    |dv r/j                         sj                  t        d|              y y y )N>   L  d   zError r   set_exceptionWarning)reqId	errorCodeerrorStringcontractr   s       r'   onErrorz"Watchdog.runAsync.<locals>.onError+  s5    K'$$Wvi[-A%BC 1>'r)   c                  \     j                         s j                  t        d             y y )NDisconnectedr   )r   s   r'   onDisconnectedz)Watchdog.runAsync.<locals>.onDisconnected/  s$    ;;=$$W^%<= !r)   zSoft timeoutr   z30 Sz5 secsMIDPOINTFzHard timeout)(r   rn   r5   rD   sleeprw   ro   connectAsyncrp   rq   rs   ru   r{   r|   ri   r   
setTimeoutry   timeoutEvent
errorEventdisconnectedEventFuturer$   debugrl   reqHistoricalDataAsyncr~   r   TimeoutErrorwait_forr   rm   r   ConnectionRefusedErrorwarning	Exception	exceptionr7   rk   rz   )	r&   r   r   r   probebarswer   s	           @r'   r   zWatchdog.runAsync%  s    	(	D	> ll*9oo00222mmD$7$7888gg**IItyy$--9L9LMM4<<1 1 1 !!&&t,""4??3$$	1$""g-"))^;)ll-4^^-=F LLLL&&~6))..t4 GG::**B"E+E  D!'"6"67 P%,%5%5eT=N=N%OOP--2248%n55GG&&t7 ll0 $$	1$""g-"))^;)oo44666!!&&t,<<!--888W ll281 !  PP P *  ($$Q'' *&&q))* 7 9 $$	1$""g-"))^;)oo44666!!&&t,<<!--888  s  SN M;&N %M>&A#N 	N
CN NA?N $N
5N6N
:A!N A:SPAS%P&S9S;N >N N N N

NN 	O> P #O>+OP O>O93P 9O>>P SSA;S RASSSSN)r]   r^   r_   r`   eventsr   rb   r	   rp   rC   rq   rc   rs   ru   floatrw   ry   rz   r{   rd   r|   r   r~   r   r   r(   r,   r   r   re   r)   r'   rg   rg      s    6p0F O
FD#D#HcNENEJJHdGS#HoM8-L%? 99r)   rg   __main__i  Tpaper)r   r      )rw   )r`   rD   r"   r   
contextlibr   dataclassesr   typingr   eventkitr   ib_insync.utilr3   ib_insync.contractr   r   ib_insync.ibr	   r   rg   r]   ibcro   appr,   r4   re   r)   r'   <module>r      s    @   
  !    .  hE hE hEV `9 `9 `9F z
dDg
6C	B
32
.CIIK
BFFH r)   