
    +jq                        U d Z ddlmZ ddlZddlZddlmZmZmZ ddlm	Z	 ddl
mZmZmZmZmZmZmZ ddlmZ ddlmZ  ej,                  d	      Zd
dddddddddd
Zded<   ddZ G d de      ZddZddZy)u  
APEX V16 — TopstepX broker (BrokerBase implementation).

Wraps the V15 TopstepXAdapter (reused AS-IS) and adapts its API to
the V16 BrokerBase abstract interface:
  - dict returns -> structured OrderResult / Position / CancelResult
  - bool returns -> OrderResult with .success populated
  - method renames: get_current_price -> get_last_price,
                    modify_sl          -> 
modify_stop,
                    cancel_all_orders_for_contract -> cancel_all_for_symbol
  - is_connected: V15 sync attribute -> V16 async method
  - Exceptions from the underlying adapter are caught and converted
    to OrderResult(success=False, error=...). The orchestrator never
    sees raw broker exceptions.

Why a wrapper instead of editing the adapter:
  - topstepx_adapter.py is shared with V15 (still running on burned
    account during transition). Editing it would risk regressing V15.
  - Single responsibility: the adapter speaks "TopstepX dict-y", the
    wrapper speaks "V16 typed". Each can evolve independently.
    )annotationsN)datetime	timedeltatimezone)Optional)
BrokerBaseBrokerReadErrorCancelResultClosedTradeOrderOrderResultPosition)TopstepXAdapter)
ASSETS_MAPtopstepx_v16BP6EU6A6JY6CA6ESNQYMMGCMCL)
6B6E6A6J6CMESMNQMYMr   r   zdict[str, str]_SYMBOL_TAG_MAPc                D    | syt         j                  | |       }||xs dv S )NT )r$   get)symbolcontract_idtags      */home/work/apex_v16/broker/topstepx_v16.py_symbol_matchesr,   7   s*    


ff
-C;$"%%    c                     e Zd ZdZdZddZddZddZddZd dZ	d!d"d	Z
d!d#d
Z	 	 	 d$	 	 	 	 	 	 	 d%dZddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d&dZ	 	 	 	 	 	 	 	 	 	 d'dZ	 	 	 	 	 	 	 	 	 	 d(dZ	 	 	 	 	 	 	 	 	 	 	 	 d)dZd*dZd+dZ	 d!	 	 	 	 	 d,dZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d-dZ	 	 	 	 	 	 	 	 d.dZd/dZd0dZd1dZdd	 	 	 	 	 	 	 	 	 d2dZy)3TopstepXBrokerz
    BrokerBase implementation for TopstepX / ProjectX.

    Holds a TopstepXAdapter instance and delegates to it, translating
    return shapes at the boundary.
    TopstepXc                0    t               | _        || _        y)a&  
        Args:
            instruments: list of symbols to subscribe at connect time
                         (e.g., ["MES", "MNQ", "6E", "6B"]).
                         The TopstepX SDK requires this up-front; symbols
                         not in this list cannot be traded later.
        N)r   _adapter_instruments)selfinstrumentss     r+   __init__zTopstepXBroker.__init__H   s     ()'r-   c                   K   	 | j                   j                  | j                         d {   S 7 # t        $ r$}t        j                  d| d       Y d }~yd }~ww xY ww)Nzconnect failed: Texc_infoF)r2   connectr3   	Exceptionlogerrorr4   es     r+   r:   zTopstepXBroker.connectW   sV     	..t/@/@AAAA 	II(,tI<	s6   A#(3 13 A#3 	A AA#A  A#c                   K   	 | j                   j                          d {    y 7 # t        $ r"}t        j	                  d|        Y d }~y d }~ww xY ww)Nzdisconnect raised (non-fatal): )r2   
disconnectr;   r<   warningr>   s     r+   rA   zTopstepXBroker.disconnect^   sG     	?--**,,, 	?KK9!=>>	?s6   A) ') A) 	AA
AAAc                p   K   	 t        | j                  j                               S # t        $ r Y yw xY ww)NF)boolr2   is_connectedr;   )r4   s    r+   rE   zTopstepXBroker.is_connectedd   s4     	22455 		s   6"' 6	3636c                   K   	 | j                   j                  |       d {   }|t        |      S d S 7 # t        $ r%}t        j                  d| d|        Y d }~y d }~ww xY ww)Nzget_last_price(z
) failed: )r2   get_current_pricefloatr;   r<   rB   )r4   r(   pricer?   s       r+   get_last_pricezTopstepXBroker.get_last_pricen   sg     	--99&AAE#(#45<>$> B 	KK/&A3?@	s@   A)8 68 A)8 A)8 	A&A!A)!A&&A)Nc                Z  K   d}d}	 | j                          d{   \  }}|r|sd|rdnd d|rdnd d}n,| j                  ddt        |      i|d	
       d{   }|d}|=	 | j                  j                          d{   }|s|t        d| d      |xs g }n|j                  dg       xs g }| j                  j                  j                         D 	
ci c]  \  }	}
|
d   |	 }}	}
g }|D ]  }|j                  dd      xs d}|j                  |      }	|	s-|r|	|k7  r5	 |j                  dd      }t        |j                  dd            }|dk(  }|j                  t        |	|rdnd|t        |j                  dd            |              |S 7 7 G# t        $ r}d| }Y d}~Ud}~ww xY w7 =# t        $ r}t        d| d| d      d}~ww xY wc c}
}	w # t        t        t        f$ r&}t         j#                  d|d|        Y d}~+d}~ww xY ww)a  
        Direct REST /Position/searchOpen with raw-search fallback.
        Bypasses the SDK Position class (broken on contractDisplayName)
        AND the adapter's silent []-on-error fallback that caused the
        28 apr 6J duplicate-bracket incident.

        Tri-state contract:
          - returns []         when the API definitively reports no positions
          - returns [Position] on success with one or more positions
          - raises BrokerReadError when BOTH the primary REST path and
            the raw-search fallback fail (auth, account_id unresolved,
            HTTP non-200, transport exception)

        Callers that gate destructive actions on the result MUST treat
        the exception as 'unknown state', not 'flat'.
        Nz"auth/account_id unresolved (token=okmissingz, account_id=)z/Position/searchOpen	accountId   timeoutz"/Position/searchOpen returned Nonezprimary REST raised: z+positions_get: both paths failed (primary: z; fallback raised: z-; fallback _raw_positions_search returned [])	positionsr)   
contractIdr&   typer   size   BUYSELLaveragePrice        )r(   	direction	contracts	avg_pricerawz&positions_get: skipping malformed row : )
_rest_auth
_rest_postintr;   r2   _raw_positions_searchr	   r'   _instrument_cacheitemsappendr   rH   KeyError	TypeError
ValueErrorr<   rB   )r4   r(   primary_errrowstoken
account_idr?   raw_listraw_positionssyminfocontract_to_symboloutpr)   pos_typesize_valis_buys                     r+   positions_getzTopstepXBroker.positions_getz   s    " &*#	6&*oo&7 7E:
&+d; <"*4$)!DAG  "__* #j/2	 -   <"FK
 <!%!D!D!FF  7 &!!, .BC 
 %NM HH["5;M "]]<<BBD
T $
 

 ! 	A%%b17RK$((5C#-55+quuVQ/0"a-

8'-e6&#AEE.#$>? 	* 
I !8  	61!5K	6 G %!!,-@1F $
0 i4 DQEA3OPs   H+F& F A F& F#F& %H+(G GG 
AH+!G(1<H+.A.G.H+ F& #F& &	F?/F:4H+:F??H+G 	G%G  G%%	H+.H(H#H+#H((H+c                  K   | j                          d{   \  }}|r|sg S | j                  dd|i|d       d{   }|g S |j                  dg       xs g }g }|D ]  }	 |j                  dd      xs d}t        ||      s'|j                  d	      }	d
dddj                  |	d      }
|j	                  t        t        |j                  dd            ||
t        |j                  d      xs( |j                  d      xs |j                  d      xs d      t        |j                  dd      xs d                    |S 7 47 # t        t        f$ r&}t        j                  d|d|        Y d}~d}~ww xY ww)u  
        Direct REST /Order/searchOpen (V15 parity, _watchdog_naked_positions
        riga 2072-2078). The TopstepXAdapter does not surface pending orders,
        so we issue a thin REST call here, parallel to _fetch_last_close_price.

        Returns empty list on any auth/transport failure — caller (Reconciler)
        treats "no pending orders" and "REST failed" identically (log-only).
        Nz/Order/searchOpenrO   rP   rQ   ordersrT   r&   rU   LIMITMARKETSTOP)rW      rP   OTHERid
limitPrice	stopPricerI   r[   rV   r   )order_idr(   kindrI   r]   z'pending_orders: skipping malformed row r`   )ra   rb   r'   r,   rg   r   strrH   rc   ri   rj   r<   rB   )r4   r(   rm   rn   rl   
orders_rawrt   ocidtr   r?   s               r+   pending_orderszTopstepXBroker.pending_orders   s     #'//"33zJI__*%	 % 
 
 <IXXh+1r
 	AeeL"-3&vs3EE&M"xF;??7K

5 tR1l+ 55-55> 	 "!%%"2"7a8 	. 
M 4
> z* EaU"QCPQsV   FE
'FE%F%"EFB>EFFFF :F FFc                h  K   | j                          d{   \  }}|r|sg S t        j                  t        j                        }||n|t        d      z
  }|j                   |j                  t        j                        }| j                  d||j                         |j                         d|d       d{   }|g S |j                  d	g       xs g }	g }
|	D ]  }	 |j                  d
d      xs d}t        ||      s't        |j                  d      xs d      }|dk(  rK|j                  d      }|dk(  rdn|dk(  rdnd}|
j                  t        t        |j                  dd            |t!        |j                  dd      xs d      |t        |j                  d      xs d      |t        |j                  dd                          |
j+                  d d       |
d| S 7 7 9# t"        t$        f$ r&}t&        j)                  d|d|        Y d}~Id}~ww xY ww)au  
        Direct REST /api/Trade/search (V15 parity, _fetch_last_close_price
        riga 1997-2009). Used by Reconciler case (ii) to recover P&L for a
        trade that closed broker-side while bot was down.

        Filters server-side by accountId + time window; client-side by symbol
        tag and profitAndLoss != 0 (open legs are also returned by the API).
        N   )hours)tzinfoz/Trade/search)rO   startTimestampendTimestamp   rQ   tradesrT   r&   profitAndLossr[   sider   rX   rW   rY   r   rV   rI   creationTimestamp)trade_idr(   r]   r   
exit_pricepnl_usd	closed_atz&recent_trades: skipping malformed row r`   c                    | j                   S N)r   )xs    r+   <lambda>z.TopstepXBroker.recent_trades.<locals>.<lambda>F  s
    q{{ r-   T)keyreverse)ra   r   nowr   utcr   r   replacerb   	isoformatr'   r,   rH   rg   r   r   rc   ri   rj   r<   rB   sort)r4   r(   sincelimitrm   rn   endstartrl   
trades_rawrt   r   r   pnlside_rawr   r?   s                    r+   recent_tradeszTopstepXBroker.recent_trades  s     #'//"33zJIll8<<(*yr7J1J<<MMM6E__'"'//"3 #
  % 	
 	
 <IXXh+1r
!# 	AeeL"-3&vs3AEE/29c:#:55= (Auh!mFQV

; tR1!!%%"2"7a8$QUU7^%:s;!!%%(;R"@A 	2 	*D96E{e 4	
H z* DQEA3OPse   H2G4B'H2>G7?%H2%"G:H2#G:+H2,B-G:H27H2:H/	H*$H2*H//H2ATR)sl_absolute_pricesl_tickstp_ticks	sl_sourcec               F  K   	 | j                   j                  |||||||||		       d {   }
t        |
t              s#t        ddt        |
      j                   
      S |
j                  d      sO|
j                  d      }||dk(  rdt        |
j                                d}nt        |      }t        d||
      S t        dt        |
ddd      t        |
dd      t        |
dd      t        |
ddd      t        |
ddd      t        |
dd d!      |
"      S 7 # t        $ rw}t        j	                  d| d| d| d| d       t        |      }t        d|rt        |      j                   d| nt        |      j                   d	
      cY d }~S d }~ww xY ww)#N)	r(   r   rV   sl_pricetp_pricer   r   r   r   zplace_market_bracket( 
) raised: Tr8   Fr`   z(no msg)successr=   adapter returned non-dict: r   r=   r&   z9adapter returned success=False without error (resp keys: rN   r   r=   r_   entry_price
fill_pricefilled_pricer   
stop_pricer   target_priceentry_identry_order_idorderIdstop_idstop_order_idsl_order_id	target_idtarget_order_idtp_order_id)r   r   r   r   r   r   r   r_   )r2   place_market_bracketr;   r<   r=   r   r   rU   __name__
isinstancedictr'   listkeys_first_float
_first_str)r4   r(   r\   r]   r   r   r   r   r   r   respr?   msgraw_errerr_strs                  r+   r   z#TopstepXBroker.place_market_bracketM  s    	;;!!"3!!# < 
 
D, $%3DJ4G4G3HI 
 xx	"hhw'G'R-UVZ[_[d[d[fVgUhhijg,  $T=,W!$
LA!$
NCj2BINtYO {4E}U	
 		
_
  		II'xq1YK H#)-   a&C69a))*"SE2$q'BRBRASS[?\ 		sE   F!'D DD C,F!D 	F'A,FFF!FF!c                J   K   | j                  ||||d       d{   S 7 w)z
        Standalone STOP order via ctx.orders.place_stop_order (V15 parity,
        adapter riga 1168-1176). Used by orphan recovery to re-attach SL.
        stopr   N_place_protective_order)r4   r(   r   r]   r   s        r+   place_stop_orderzTopstepXBroker.place_stop_order  s5      11D)Zf 2 
 
 	
 
   #!#c                J   K   | j                  ||||d       d{   S 7 w)z>Standalone LIMIT order (TP re-attach). Adapter riga 1204-1211.r   r   Nr   )r4   r(   r   r]   limit_prices        r+   place_limit_orderz TopstepXBroker.place_limit_order  s5      11D)[w 2 
 
 	
 
r   c          	       K   | j                   j                  j                  t        |t              r|j                         n|      }|t        dd|       S | j                   j                  j                  |      }|st        dd|       S |d   }| j                   j                  |      }		 |dk(  r1|	j                  j                  ||t        |      |       d {   }
n0|	j                  j                  ||t        |      |       d {   }
t!        |
dd       xs t!        |
dd       }|s9t!        |
dd       xs t!        |
dd       xs | d}t        dt	        |            S |dk(  r!t        d|t	        |      t	        |            S t        d|t	        |      t	        |            S 7 7 # t        $ r>}t        j                  d	| d
| d|        t        dt	        |            cY d }~S d }~ww xY ww)NFzinvalid side: r   zno contract cached for r)   r   )r)   r   rV   r   )r)   r   rV   r   place_z_order(r   r   r   errorMessageerror_messagez order returned no idT)r   r   r   r   )r   r   r   r   )r2   SIDE_MAPr'   r   r   upperr   re   _get_ctxr{   r   rc   r   r;   r<   r=   getattr)r4   r(   r   r]   rI   r   side_intrr   r)   ctxr   r?   r   errs                 r+   r   z&TopstepXBroker._place_protective_order  s     ==))--&tS1DJJLt
 unTF4KLL}}..226:u6MfX4VWW=)mm$$V,	<v~ ZZ88 +(YE 9  
 !ZZ99 +(YU :   D)T* /tZ. 	 nd3 24$72V01 
 uCH==6>teS](+H7 74%3x=$'M3 	39
  	<IItfGF8:aSABuCF;;	<s[   B/H20F: "F6#0F: F8F: BH6F: 8F: :	H3G<6H7H<HHc           	       K   	 	 t        |      }| j
                  j                  ||       d {   }t        t        |      t	        |      |rd       S d      S # t        t        f$ r t        dt	        |      d|      cY S w xY w7 \# t        $ rH}t        j                  d| d| d|        t        dt	        |      t	        |            cY d }~S d }~ww xY ww)NForder_id not int-convertible: )r   r   r=   zcancel_order(, r   zadapter returned False)rc   ri   rj   r
   r   r2   cancel_orderr;   r<   r=   rD   )r4   r(   r   oid_intrL   r?   s         r+   r   zTopstepXBroker.cancel_order  s     	Uh- }}11&'BBB
 H]$
 	
 #;
 	
 z* #! ]:8,G  C 	UIIfXRzA3GHHSQRVTT	Us`   C"A B BB )C")B	B C"B		B 	C=CCC"CC"c                  K   	 | j                   j                  |       d {   }t        |t              st        j                  d|       y|j                  d      rt        j                  d| d|d           t        |j                  dd            S 7 w# t        $ r%}t        j	                  d| d|        Y d }~yd }~ww xY ww)Nzcancel_all_for_symbol(r   r   z)cancel_all_for_symbol: unexpected return r=   z): cancelled_count)
r2   cancel_all_orders_for_contractr;   r<   r=   r   r   rB   r'   rc   )r4   r(   r   r?   s       r+   cancel_all_for_symbolz$TopstepXBroker.cancel_all_for_symbol  s     	EEfMMD
 $%KKCD8LM88GKK0DM?KL488-q122 N 	II.vhjDE	s>   CB BB A3CB 	C
%C CC

Cc           	     $  K   	 | j                   j                  ||       d {   }t        |t              s#t        dd	t        |      j                         S |j                  d
      s=t        dt        |j                  d      xs |j                  d      xs d      |      S t        dt        |d      |      S 7 # t        $ r@}t        j	                  d| d| d| d       t        dt        |            cY d }~S d }~ww xY ww)N)rV   zclose_position(r   r   Tr8   Fr   r   r   r=   r   zclose failedr   r   )r   r   r_   )r2   close_positionr;   r<   r=   r   r   r   r   rU   r   r'   r   )r4   r(   r]   r   r?   s        r+   r   zTopstepXBroker.close_position  s    
	<55f95MMD $%3DJ4G4G3HI 
 xx	"$((7+ ,!XXn5,+-   i0
 	
+ N 	<IIxr)JqcJ#  %uCF;;	<sD   D C CC BDC 	D5DDDDDc	           
       K   	 | j                   j                  ||t        |      t        |      t        |      t        |      ||       d{   }	t        |	t              s#t        dd	t        |	      j                         S |	j                  d
      s*t        dt        |	j                  d      xs d      |	      S t        dt        |	d      t        |	d      t        |	d      |	j                  d      |	j                  d      |	      S 7 # t        $ r=}
t
        j                  d| d|
 d       t        dt        |
            cY d}
~
S d}
~
ww xY ww)uA  V18 12-mag — workaround per /Position/partialCloseContract 400.

        Vedi `broker_base.BrokerBase.partial_close_via_opposite_order`.
        OrderResult.stop_id / target_id valorizzati con i NUOVI ID del
        bracket sul residuo; caller aggiorna entry.stop_order_id /
        target_order_id su success.
        )r(   r\   contracts_to_closeresidual_contractsnew_sl_pricenew_tp_priceold_stop_order_idold_target_order_idNz!partial_close_via_opposite_order(r   Tr8   Fr   r   r   r=   z!partial close via opposite failedr   closing_order_idnew_stop_idnew_target_idr   r   )r   r   r   r   r   r   r_   )r2    partial_close_via_opposite_orderrc   rH   r;   r<   r=   r   r   r   r   rU   r   r'   r   )r4   r(   r\   r   r   r   r   r   r   r   r?   s              r+   r   z/TopstepXBroker.partial_close_via_opposite_order)  sZ    $	<GG##&'9#:#&'9#:"<0"<0"3$7 H 	 	D" $%3DJ4G4G3HI 
 xx	"$((7+R/RS  &89t]3 7XXn-XXn-
 	
=	  	<II3F8:aSI   uCF;;	<sH   EA
D DD B<ED 	E2EEEEEc                T  K   t        j                  |i       }t        |j                  dd      xs d      }|dkD  rt        t        ||z        |z  d      }n|}	 	 t	        |      }| j                  j                  |||       d {   }|st        dd      S t        d|t        |            S # t
        t        f$ r t        dd|      cY S w xY w7 O# t        $ rA}	t        j                  d	| d
| d
| d|	        t        dt        |	            cY d }	~	S d }	~	ww xY ww)N	tick_sizer[   r      Fr   r   )r(   r   new_slzmodify_stop(r   r   z adapter modify_sl returned FalseT)r   r   r   )r   r'   rH   roundrc   ri   rj   r   r2   	modify_slr;   r<   r=   r   )
r4   r(   r   r   spects
aligned_slr   rL   r?   s
             r+   modify_stopzTopstepXBroker.modify_stopd  sJ     ~~fb)488K-456u\B%67"<a@J%J	<h- }}..%! /  B 8 
 M
 	
- z* "!:8,G 

  	<IIvhb
"\N*QCP uCF;;		<sf   AD(B4 (!C 	C
C &D(4CC D(CC 	D%$6D D%D( D%%D(c                   K   | j                   j                          d{   }t        |j                  dd            S 7 w)u   
        Current TopstepX account balance via TopstepXAdapter.get_account_info.
        SDK keeps account_info refreshed via socket events — V16 adds no cache.
        Nbalancer[   )r2   get_account_inforH   r'   )r4   rr   s     r+   get_account_balancez"TopstepXBroker.get_account_balance  s8     
 ]]3355TXXi-.. 6s   AA  Ac                X   K   | j                   j                  |||       d{   S 7 w)zU
        Delegate to TopstepXAdapter.get_bars (V15 hybrid WS+REST strategy).
        N)r2   get_bars)r4   r(   	timeframens       r+   
fetch_barszTopstepXBroker.fetch_bars  s'      ]]++FIqAAAAs   !*(*c                \  K   	 t        j                  d      }t        j                  d      }|r|syt        j                  t        j
                        j                         }t        | j                  dd      }t        | j                  dd      xs d}|r||k  r|}nrddl	}|j                  d||d	d
      }|j                  dk7  ry|j                         j                  d      }|sy|| j                  _        |dz   | j                  _        | j                  j                   r | j                  j                   j"                  nd}	|	rt        |	dd      nd}
|
rt        |
dd      nd}||rt%        |      fS dfS # t&        $ r"}t(        j+                  d|        Y d}~yd}~ww xY ww)z
        Returns (bearer_token, account_id). Token is cached for 30min on
        the wrapped adapter (shared with adapter._direct_rest_token to avoid
        double-authing). Returns (None, None) on any failure.
        PROJECT_X_API_KEYPROJECT_X_USERNAME)NN_direct_rest_tokenN_direct_rest_token_expr   z*https://api.topstepx.com/api/Auth/loginKey)userNameapiKeyr   )jsonrR      rm   i  account_infor   z_rest_auth failed: )osgetenvr   r   r   r   	timestampr   r2   requestspoststatus_coder  r'   r  r  _suiteclientrc   r;   r<   rB   )r4   api_keyusernamenow_tscached_token
cached_exprm   r!  rr%  accrn   r?   s                r+   ra   zTopstepXBroker._rest_auth  sx     	yy!45Gyy!56H(!\\(,,/99;F"4==2FML"4==2JANSRSJ 3$MM@&.'B " 
 ==C'%W-%3807=}448MM4H4HT]]))00dF;A'&.$7tC58dD1dJZ#j/AATAA 	KK-aS12	s^   F,.E> F,BE> 
F,!E> ,F,-BE> :F,;E> =F,>	F)F$F,$F))F,rP   rQ   c               <  K   	 ddl }|j                  d|z   d|z   dd||      }|j                  dk7  r&t        j	                  d	| d
|j                          y|j                         S # t        $ r%}t        j	                  d	| d|        Y d}~yd}~ww xY ww)z=Bare POST to api.topstepx.com/api{path}. None on any failure.r   Nzhttps://api.topstepx.com/apizBearer zapplication/json)AuthorizationzContent-Type)headersr  rR   r  z_rest_post z: HTTP z	 raised: )r!  r"  r#  r<   rB   r  r;   )r4   pathbodyrm   rR   r!  r+  r?   s           r+   rb   zTopstepXBroker._rest_post  s     	.5%.%6$6   A }}#k$wq}}oFG668O 	KK+dV9QC89	s;   BAA+ BA+ *B+	B4BBBB)r5   z	list[str])returnrD   )r2  None)r(   r   r2  Optional[float]r   )r(   Optional[str]r2  zlist[Position])r(   r5  r2  zlist[Order])NN2   )r(   r5  r   zOptional[datetime]r   rc   r2  zlist[ClosedTrade])r(   r   r\   r   r]   rc   r   rH   r   rH   r   r4  r   Optional[int]r   r7  r   r   r2  r   )
r(   r   r   r   r]   rc   r   rH   r2  r   )
r(   r   r   r   r]   rc   r   rH   r2  r   )r(   r   r   r   r]   rc   rI   rH   r   r   r2  r   )r(   r   r   r   r2  r
   )r(   r   r2  rc   )r(   r   r]   r7  r2  r   )r(   r   r\   r   r   rc   r   rc   r   rH   r   rH   r   r5  r   r5  r2  r   )r(   r   r   r   r   rH   r2  r   )r2  rH   )r(   r   r  r   r  rc   )r2  z#tuple[Optional[str], Optional[int]])
r0  r   r1  r   rm   r   rR   rH   r2  zOptional[dict])r   
__module____qualname____doc__namer6   r:   rA   rE   rJ   ry   r   r   r   r   r   r   r   r   r   r   r
  r  r  ra   rb    r-   r+   r/   r/   >   s    D	(?Zx/f !%$(	@@ "@ 	@
 
@\ .2"&"&F
F
 F
 	F

 F
 F
 +F
  F
  F
 F
 
F
P

 
 	

 
 





 

 	


 

 


3333 33 	33
 33 33 
33j
*3" $(

 !
 
	
B9
9
 9
  	9

  9
 9
 9
 )9
 +9
 
9
v.
.
 .
 	.

 
.
h/B&\   	  
r-   r/   c                ~    |D ]#  }| j                  |      }|	 t        |      c S  y# t        t        f$ r Y 8w xY w)zBReturn float-cast of the first key found in d with non-None value.N)r'   rH   ri   rj   dr   kvs       r+   r   r     sO     EE!H=Qx	  z* s   
*<<c                R    |D ]"  }| j                  |      }|t        |      c S  y r   )r'   r   r>  s       r+   r   r     s1     EE!H=q6M r-   )r(   r5  r)   r   r2  rD   )r?  r   r   r   r2  r4  )r?  r   r   r   r2  r5  )r:  
__future__r   loggingr  r   r   r   typingr   broker.broker_baser   r	   r
   r   r   r   r   broker.topstepx_adapterr   core.config_futuresr   	getLoggerr<   r$   __annotations__r,   r/   r   r   r<  r-   r+   <module>rK     s   . #  	 2 2    4 *g' uDUd5# &r
Z r
r	r-   