
    (i                        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
mZmZ ddlmZ ddl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)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z? dd
l@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZR ddlSmTZT ddlUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z] ddl^m_Z_m`Z`maZambZbmcZcmdZdmeZe ddlfmgZgmhZhmiZimjZjmkZk ddllmmZm  G d d      Zny)    N)Optional)BuilderConfig   )OrderBuilder)create_level_1_headerscreate_level_2_headers&enrich_l2_headers_with_builder_headers)Signer)get_contract_config).CANCELCANCEL_ORDERSCANCEL_MARKET_ORDERS
CANCEL_ALLCREATE_API_KEYDELETE_API_KEYDERIVE_API_KEYGET_API_KEYSCLOSED_ONLYCREATE_READONLY_API_KEYGET_READONLY_API_KEYSDELETE_READONLY_API_KEYVALIDATE_READONLY_API_KEYGET_LAST_TRADE_PRICE	GET_ORDERGET_ORDER_BOOK	MID_POINTORDERS
POST_ORDERPOST_ORDERSPRICETIMETRADESGET_NOTIFICATIONSDROP_NOTIFICATIONSGET_BALANCE_ALLOWANCEUPDATE_BALANCE_ALLOWANCEIS_ORDER_SCORINGGET_TICK_SIZEGET_NEG_RISKGET_FEE_RATEARE_ORDERS_SCORINGGET_SIMPLIFIED_MARKETSGET_MARKETS
GET_MARKETGET_SAMPLING_SIMPLIFIED_MARKETSGET_SAMPLING_MARKETSGET_MARKET_TRADES_EVENTSGET_LAST_TRADES_PRICES
MID_POINTSGET_ORDER_BOOKS
GET_PRICES
GET_SPREADGET_SPREADSGET_BUILDER_TRADESPOST_HEARTBEAT)ApiCredsReadonlyApiKeyResponseTradeParamsOpenOrderParams	OrderArgsRequestArgsDropNotificationParamsOrderBookSummaryBalanceAllowanceParamsOrderScoringParamsTickSizeCreateOrderOptionsOrdersScoringParams	OrderTypePartialCreateOrderOptions
BookParamsMarketOrderArgsPostOrdersArgs)PolyException)add_query_trade_paramsadd_query_open_orders_paramsdeletegetpostdrop_notifications_query_params#add_balance_allowance_params_to_urladd_order_scoring_params_to_url)L0L1L1_AUTH_UNAVAILABLEL2L2_AUTH_UNAVAILABLE
END_CURSORBUILDER_AUTH_UNAVAILABLE)parse_raw_orderbook_summarygenerate_orderbook_summary_hashorder_to_jsonis_tick_size_smallerprice_valid)	RfqClientc                      e Zd Z	 	 	 	 	 	 	 didededededededefd	Zd
 Z	d Z
d ZdjdZd Zd ZdkdedefdZdkdedefdZdkdedefdZdefdZd Zd Zd ZdefdZdee   fdZdedefdZdededefdZd Zd ee   fd!Zd" Z d ee   fd#Z!d$ Z"d ee   fd%Z#d&ede$fd'Z%dkd&efd(Z&d)e'fd*Z(d&edefd+Z)d&edefd,Z*	 dkd&ed-e$de$fd.Z+dkd&ed/edefd0Z,	 dkd1e-d2e.e/   fd3Z0	 dkd1e1d2e.e/   fd4Z2d5ee3   fd6Z4e5jl                  dfd7e5d8efd9Z7	 dkd1e-d2e/fd:Z8d; Z9d< Z:d= Z;d>e.e   fd?Z<dld@edAefdBZ=dmd e>fdCZ?de'fdDZ@d ee   dee'   fdEZAdFe'defdGZBdH ZCdmd eDfdIZEdJ ZFd ee   fdKZGdL ZHdM ZIdN ZJdefdOZKdP ZLdQeMdReNfdSZOdkdTedUedVe.e   fdWZPdX ZQdkd eRfdYZSdkd eTfdZZUdkd eTfd[ZVd eWfd\ZXd eYfd]ZZdnd^Z[dnd_Z\dnd`Z]dndaZ^db Z_dc Z`dmd eDfddZad&edeedfedge5def
dhZby)o
ClobClientNchain_idkeycredssignature_typefunderbuilder_configtick_size_ttlc	                    |j                  d      r|dd n|| _        || _        |rt        ||      nd| _        || _        | j                         | _        | j                  rt        | j                  ||      | _	        d| _
        |r|| _
        i | _        i | _        || _        i | _        i | _        t!        |       | _        t%        j&                  | j(                  j*                        | _        y)a  
        Initializes the clob client
        The client can be started in 3 modes:
        1) Level 0: Requires only the clob host url
                    Allows access to open CLOB endpoints

        2) Level 1: Requires the host, chain_id and a private key.
                    Allows access to L1 authenticated endpoints + all unauthenticated endpoints

        3) Level 2: Requires the host, chain_id, a private key, and Credentials.
                    Allows access to all endpoints
        /r   N)sig_typerh   )endswithhostrd   r
   signerrf   _get_client_modemoder   builderri   _ClobClient__tick_sizes!_ClobClient__tick_size_timestamps_ClobClient__tick_size_ttl_ClobClient__neg_risk_ClobClient__fee_ratesra   rfqlogging	getLogger	__class____name__logger)	selfrp   rd   re   rf   rg   rh   ri   rj   s	            F/var/www/br/venv/lib/python3.12/site-packages/py_clob_client/client.py__init__zClobClient.__init__u   s    . #'--"4D2J$	 /2fS(+
))+	;;'nVDL #"0D &(#, T?''(?(?@    c                 R    | j                   r| j                   j                         S dS )z:
        Returns the public address of the signer
        N)rq   addressr   s    r   get_addresszClobClient.get_address   s"     )-t{{""$==r   c                 J    t        | j                        }|r|j                  S y)z6
        Returns the collateral token address
        N)r   rd   
collateralr   contract_configs     r   get_collateral_addressz!ClobClient.get_collateral_address   s&     .dmm<"--- r   c                 J    t        | j                        }|r|j                  S y)z7
        Returns the conditional token address
        N)r   rd   conditional_tokensr   s     r   get_conditional_addressz"ClobClient.get_conditional_address   s&     .dmm<"555 r   Fc                 L    t        | j                  |      }|r|j                  S y)z.
        Returns the exchange address
        N)r   rd   exchange)r   neg_riskr   s      r   get_exchange_addresszClobClient.get_exchange_address   s(     .dmmXF"+++ r   c                 J    t        dj                  | j                              S )zc
        Health check: Confirms that the server is up
        Does not need authentication
        z{}/)rP   formatrp   r   s    r   get_okzClobClient.get_ok   s    
 5<<		*++r   c                 T    t        dj                  | j                  t                    S )zb
        Returns the current timestamp on the server
        Does not need authentication
        {}{})rP   r   rp   r!   r   s    r   get_server_timezClobClient.get_server_time   s    
 6==D122r   noncereturnc                     | j                          dj                  | j                  t              }t	        | j
                  |      }t        ||      }	 t        |d   |d   |d         }|S #  | j                  j                  d       Y yxY w)	z:
        Creates a new CLOB API key for the given
        r   headersapiKeysecret
passphraseapi_key
api_secretapi_passphrasez!Couldn't parse created CLOB credsN)
assert_level_1_authr   rp   r   r   rq   rQ   r:   r   errorr   r   endpointr   	creds_rawrf   s         r   create_api_keyzClobClient.create_api_key   s     	  "==N;(e<73		!(+$X.(6E 	KKAB   A. .Bc                     | j                          dj                  | j                  t              }t	        | j
                  |      }t        ||      }	 t        |d   |d   |d         }|S #  | j                  j                  d       Y yxY w)	zZ
        Derives an already existing CLOB API key for the given address and nonce
        r   r   r   r   r   r   z!Couldn't parse derived CLOB credsN)
r   r   rp   r   r   rq   rP   r:   r   r   r   s         r   derive_api_keyzClobClient.derive_api_key   s     	  "==N;(e<'2		!(+$X.(6E 	KKABr   c                 V    	 | j                  |      S #  | j                  |      cY S xY w)z\
        Creates API creds if not already created for nonce, otherwise derives them
        )r   r   )r   r   s     r   create_or_derive_api_credsz%ClobClient.create_or_derive_api_creds   s0    	.&&u--	.&&u--s    (c                 <    || _         | j                         | _        y)z'
        Sets client api creds
        N)rf   rr   rs   )r   rf   s     r   set_api_credszClobClient.set_api_creds  s     
))+	r   c                     | j                          t        dt              }t        | j                  | j
                  |      }t        dj                  | j                  t              |      S )z\
        Gets the available API keys for this address
        Level 2 Auth required
        GETmethodrequest_pathr   r   )	assert_level_2_authr?   r   r   rq   rf   rP   r   rp   r   request_argsr   s      r   get_api_keyszClobClient.get_api_keys  sN    
 	  ""%lK(djj,O6==L97KKr   c                     | j                          t        dt              }t        | j                  | j
                  |      }t        dj                  | j                  t              |      S )z_
        Gets the closed only mode flag for thsi address
        Level 2 Auth required
        r   r   r   r   )	r   r?   r   r   rq   rf   rP   r   rp   r   s      r   get_closed_only_modezClobClient.get_closed_only_mode  sN    
 	  ""%kJ(djj,O6==K8'JJr   c                     | j                          t        dt              }t        | j                  | j
                  |      }t        dj                  | j                  t              |      S )zB
        Deletes an API key
        Level 2 Auth required
        DELETEr   r   r   )	r   r?   r   r   rq   rf   rO   r   rp   r   s      r   delete_api_keyzClobClient.delete_api_key#  sN    
 	  ""(P(djj,OfmmDII~>PPr   c                 @   | j                          t        dt              }t        | j                  | j
                  |      }t        dj                  | j                  t              |      }	 t        |d         S #  | j                  j                  d       Y yxY w)	zY
        Creates a new readonly API key for a user
        Level 2 Auth required
        POSTr   r   r   r   )r   z(Couldn't parse readonly API key responseN)r   r?   r   r   rq   rf   rQ   r   rp   r;   r   r   )r   r   r   responses       r   create_readonly_api_keyz"ClobClient.create_readonly_api_key.  s    
 	  ""&?VW(djj,Odii1HISZ[	)(82DEE	KKHIs   /A> >Bc                     | j                          t        dt              }t        | j                  | j
                  |      }t        dj                  | j                  t              |      S )ze
        Gets the available readonly API keys for this address
        Level 2 Auth required
        r   r   r   r   )	r   r?   r   r   rq   rf   rP   r   rp   r   s      r   get_readonly_api_keysz ClobClient.get_readonly_api_keys?  sP    
 	  ""%>ST(djj,O6==,ABGTTr   c                    | j                          d|i}t        j                  |dd      }t        dt        ||      }t        | j                  | j                  |      }t        dj                  | j                  t              ||      S )	zU
        Deletes a readonly API key for a user
        Level 2 Auth required
        re   ,:F
separatorsensure_asciir   r   r   bodyserialized_bodyr   r   data)r   jsondumpsr?   r   r   rq   rf   rO   r   rp   )r   re   r   
serializedr   r   s         r   delete_readonly_api_keyz"ClobClient.delete_readonly_api_keyJ  s    
 	  "s|ZZ%P
"0&	
 )djj,OMM$))%<=
 	
r   r   c                 X    t        dj                  | j                  t        ||            S )z
        Validates a readonly API key for a given address
        This is a public endpoint, no authentication required
        z{}{}?address={}&key={})rP   r   rp   r   )r   r   re   s      r   validate_readonly_api_keyz$ClobClient.validate_readonly_api_key`  s-    
 $++		4gs
 	
r   c                 V    t        dj                  | j                  t        |            S )z?
        Get the mid market price for the given market
        {}{}?token_id={})rP   r   rp   r   r   token_ids     r   get_midpointzClobClient.get_midpointk  s#     %,,TYY	8LMMr   paramsc                     |D cg c]  }d|j                   i }}t        dj                  | j                  t              |      S c c}w )zB
        Get the mid market prices for a set of token ids
        r   r   r   )r   rQ   r   rp   r3   r   r   paramr   s       r   get_midpointszClobClient.get_midpointsq  sC     ;AAU^^,AAFMM$))Z8tDD B   Ac                 X    t        dj                  | j                  t        ||            S )z;
        Get the market price for the given market
        z{}{}?token_id={}&side={})rP   r   rp   r    )r   r   sides      r   	get_pricezClobClient.get_pricex  s&     -44TYYxQUVWWr   c                     |D cg c]  }|j                   |j                  d }}t        dj                  | j                  t
              |      S c c}w )z1
        Get the market prices for a set
        )r   r   r   r   )r   r   rQ   r   rp   r5   r   s       r   
get_priceszClobClient.get_prices~  sH     OUUUU^^UZZ@UUFMM$))Z8tDD Vs    Ac                 V    t        dj                  | j                  t        |            S )z5
        Get the spread for the given market
        r   )rP   r   rp   r6   r   s     r   
get_spreadzClobClient.get_spread  s#     %,,TYY
HMNNr   c                     |D cg c]  }d|j                   i }}t        dj                  | j                  t              |      S c c}w )z8
        Get the spreads for a set of token ids
        r   r   r   )r   rQ   r   rp   r7   r   s       r   get_spreadszClobClient.get_spreads  sC     ;AAU^^,AAFMM$))[9EE Br   r   c                    | j                   j                  |      }|| j                  v r5|3t        j                         |z
  | j
                  k  r| j                  |   S t        dj                  | j                  t        |            }t        |d         | j                  |<   t        j                         | j                   |<   | j                  |   S )Nr   minimum_tick_size)
rv   rP   ru   time	monotonicrw   r   rp   r(   str)r   r   	cached_atresults       r   get_tick_sizezClobClient.get_tick_size  s    //33H=	 )))%!I-1E1EE$$X..'..tyy-RS&)&1D*E&F(#040@##H-  **r   c                     |9| j                   j                  |d       | j                  j                  |d       y| j                   j                          | j                  j                          y)z
        Clears the tick size cache, forcing fresh fetches on the next access.

        Args:
            token_id: If provided, only clears the cache for this token.
                      Otherwise clears all cached tick sizes.
        N)ru   poprv   clearr   s     r   clear_tick_size_cachez ClobClient.clear_tick_size_cache  sZ     !!(D1''++Hd;##%''--/r   bookc                     |rr|j                   re|j                  rXt        |j                        | j                  |j                   <   t	        j
                         | j                  |j                   <   yyyy)z\
        Opportunistically updates the tick size cache from an order book response.
        N)asset_id	tick_sizer   ru   r   r   rv   )r   r   s     r   !_update_tick_size_from_order_bookz,ClobClient._update_tick_size_from_order_book  sT     DMMdnn/24>>/BDdmm,9=9ID''6 '5M4r   c                     || j                   v r| j                   |   S t        dj                  | j                  t        |            }|d   | j                   |<   |d   S )Nr   r   )rx   rP   r   rp   r)   )r   r   r   s      r   get_neg_riskzClobClient.get_neg_risk  sY    t&??8,,'..tyy,QR$*:$6!j!!r   c                     || j                   v r| j                   |   S t        dj                  | j                  t        |            }|j                  d      xs d}|| j                   |<   |S )Nr   base_feer   )ry   rP   r   rp   r*   )r   r   r   fee_rates       r   get_fee_rate_bpszClobClient.get_fee_rate_bps  sg    t'''##H--'..tyy,QR::j).Q%-"r   r   c                     | j                  |      }|4t        ||      r&t        dt        |      z   dz   t        |      z         |S |}|S )Nzinvalid tick size (z), minimum for the market is )r   r_   	Exceptionr   )r   r   r   min_tick_sizes       r   __resolve_tick_sizezClobClient.__resolve_tick_size  sl     **84 #I}=))n%56 -()   &Ir   user_fee_ratec                 p    | j                  |      }|"|dkD  r||dkD  r||k7  rt        d| d|       |S )Nr   z!invalid user provided fee rate: (z#), fee rate for the market must be )r  r  )r   r   r	  market_fee_rate_bpss       r   __resolve_fee_ratezClobClient.__resolve_fee_rate  sb    "33H=  +#a')!!443M?Befyez{  #"r   
order_argsoptionsc           	      J   | j                          | j                  |j                  |r|j                  nd      }t	        |j
                  |      sKt        dt        |j
                        z   dz   t        |      z   dz   t        dt        |      z
        z         |r|j                  r|j                  n| j                  |j                        }| j                  |j                  |j                        }||_        | j                  j                  |t        ||            S )J
        Creates and signs an order
        Level 1 Auth required
        Nprice (), min:  - max: r   r   r   )r   _ClobClient__resolve_tick_sizer   r   r`   pricer  r   floatr   r   _ClobClient__resolve_fee_ratefee_rate_bpsrt   create_orderrE   r   r  r  r   r   r  s         r   r  zClobClient.create_order  s,    	  " ,,!(Gd
	
 :++Y7j&&'( i.! 	
 a%	**+,  7++ "":#6#67 	 ..!8!8
 #/
||((#!
 	
r   c           	         | j                          | j                  |j                  |r|j                  nd      }|j                  |j                  dk  rA| j                  |j                  |j                  |j                  |j                        |_        t        |j                  |      sKt        dt        |j                        z   dz   t        |      z   dz   t        dt        |      z
        z         |r|j                  r|j                  n| j                  |j                        }| j                  |j                  |j                         }||_        | j"                  j%                  |t'        ||            S )r  Nr   r  r  r  r   r  )r   r  r   r   r  calculate_market_pricer   amount
order_typer`   r  r   r  r   r   r  r  rt   create_market_orderrE   r  s         r   r   zClobClient.create_market_order  s|    	  " ,,!(Gd
	
 #z'7'71'<#::##!!%%	 J :++Y7j&&'( i.! 	
 a%	**+,  7++ "":#6#67 	 ..!8!8
 #/
||//#!
 	
r   argsc           
      z   | j                          |D cg c]B  }t        |j                  | j                  j                  |j
                  |j                        D }}t        dt        |t        j                  |dd            }t        | j                  | j                  |      }| j                         rJ| j                  ||      }|6t        dj!                  | j"                  t              ||j$                        S t        dj!                  | j"                  t              ||j$                        S c c}w )z
        Posts orders
        r   r   Fr   r   r   r   )r   r^   orderrf   r   	orderTypepostOnlyr?   r   r   r   r   rq   can_builder_auth_generate_builder_headersrQ   r   rp   r   )r   r!  argr   r   r   builder_headerss          r   post_orderszClobClient.post_ordersP  s
    	  "ae
Z]M#))TZZ%7%7U
 
 #$ JJt
QVW	
 )djj,O  ""<<\7SO*MM$))[9+%55  MM$))[1--
 	
)
s   AD8r$  	post_onlyc           
         |r1|t         j                  k7  r|t         j                  k7  rt        d      | j	                          t        || j                  j                  ||      }t        dt        |t        j                  |dd            }t        | j                  | j                  |      }| j                         rJ| j                  ||      }|6t!        dj#                  | j$                  t              ||j&                        S t!        dj#                  | j$                  t              ||j&                        S )	z!
        Posts the order
        z/post_only orders can only be of type GTC or GTDr   r   Fr   r   r   r   )rG   GTCGTDr  r   r^   rf   r   r?   r   r   r   r   rq   r&  r'  rQ   r   rp   r   )r   r#  r$  r+  r   r   r   r)  s           r   
post_orderzClobClient.post_ordero  s    )y}}4imm9SMNN  "UDJJ$6$6	9M"# JJt
QVW	
 )djj,O  ""<<\7SO*MM$))Z8+%55 
 MM$))Z0--
 	
r   c                 H    | j                  ||      }| j                  |      S )zA
        Utility function to create and publish an order
        )r  r/  )r   r  r  ords       r   create_and_post_orderz ClobClient.create_and_post_order  s%     
G4s##r   c           
      *   | j                          d|i}t        dt        |t        j                  |dd            }t        | j                  | j                  |      }t        dj                  | j                  t              ||j                        S )	z@
        Cancels an order
        Level 2 Auth required
        orderIDr   r   Fr   r   r   r   )r   r?   r   r   r   r   rq   rf   rO   r   rp   r   )r   order_idr   r   r   s        r   cancelzClobClient.cancel  s    
 	  "8$" JJt
QVW	
 )djj,OMM$))V,--
 	
r   c                    | j                          |}t        j                  |dd      }t        dt        ||      }t        | j                  | j                  |      }t        dj                  | j                  t              ||      S )>
        Cancels orders
        Level 2 Auth required
        r   Fr   r   r   r   r   )r   r   r   r?   r   r   rq   rf   rO   r   rp   )r   	order_idsr   r   r   r   s         r   cancel_orderszClobClient.cancel_orders  sx    
 	  "ZZ%P
"&&	
 )djj,OMM$))]3W:
 	
r   c                     | j                          t        dt              }t        | j                  | j
                  |      }t        dj                  | j                  t              |      S )zY
        Cancels all available orders for the user
        Level 2 Auth required
        r   r   r   r   )	r   r?   r   r   rq   rf   rO   r   rp   r   s      r   
cancel_allzClobClient.cancel_all  sN    
 	  ""(L(djj,OfmmDIIz:GLLr   heartbeat_idc                    | j                          d|i}t        j                  |dd      }t        dt        ||      }t        | j                  | j                  |      }t        dj                  | j                  t              ||      S )	z
        Sends a heartbeat to the server, if heartbeats are started and one isn't sent within 10s, all orders will be cancelled
        Requires Level 2 authentication
        r=  r   Fr   r   r   r   r   )r   r   r   r?   r9   r   rq   rf   rQ   r   rp   )r   r=  r   r   r   r   s         r   post_heartbeatzClobClient.post_heartbeat  sy    
 	  "-ZZ%P
"&~TXjtu(djj,OMM$))^4
 	
r   marketr   c                    | j                          ||d}t        j                  |dd      }t        dt        ||      }t        | j                  | j                  |      }t        dj                  | j                  t              ||      S )	r8  )r@  r   r   Fr   r   r   r   r   )r   r   r   r?   r   r   rq   rf   rO   r   rp   )r   r@  r   r   r   r   r   s          r   cancel_market_orderszClobClient.cancel_market_orders  s    
 	  " h7ZZ%P
"-&	
 )djj,OMM$))%9:
 	
r   c                 J   | j                          t        dt              }t        | j                  | j
                  |      }g }||nd}|t        k7  rOt        dj                  | j                  t              ||      }t        ||      }|d   }||d   z  }|t        k7  rO|S )zU
        Gets orders for the API key
        Requires Level 2 authentication
        r   r   MA==r   r   next_cursorr   )r   r?   r   r   rq   rf   rZ   rN   r   rp   rP   r   r   rE  r   r   resultsurlr   s           r   
get_orderszClobClient.get_orders  s    
 	  ""%fE(djj,O%0%<k&Z'.dii0&+C 30H"=1Kx''G Z' r   c                     t        dj                  | j                  t        |            }t	        |      }| j                  |       |S )z8
        Fetches the orderbook for the token_id
        r   )rP   r   rp   r   r\   r   )r   r   raw_obsr   s       r   get_order_bookzClobClient.get_order_book  s?     (//		>8TU,W5..v6r   c                    |D cg c]  }d|j                   i }}t        dj                  | j                  t              |      }|D cg c]  }t        |       }}|D ]  }| j                  |        |S c c}w c c}w )z>
        Fetches the orderbook for a set of token ids
        r   r   r   )r   rQ   r   rp   r4   r\   r   )r   r   r   r   rK  rrG  r   s           r   get_order_bookszClobClient.get_order_books  s     ;AAU^^,AAv}}TYY@tL;BCa.q1CC 	9D2248	9 BCs   A9A>	orderbookc                     t        |      S )z=
        Calculates the hash for the given orderbook
        )r]   )r   rP  s     r   get_order_book_hashzClobClient.get_order_book_hash  s     /y99r   c                     | j                          dj                  t        |      }t        d|      }t	        | j
                  | j                  |      }t        dj                  | j                  |      |      S )zi
        Fetches the order corresponding to the order_id
        Requires Level 2 authentication
        r   r   r   r   )	r   r   r   r?   r   rq   rf   rP   rp   )r   r5  r   r   r   s        r   	get_orderzClobClient.get_order  s^    
 	  "==H5"%hG(djj,O6==H5wGGr   c                 J   | j                          t        dt              }t        | j                  | j
                  |      }g }||nd}|t        k7  rOt        dj                  | j                  t              ||      }t        ||      }|d   }||d   z  }|t        k7  rO|S )z^
        Fetches the trade history for a user
        Requires Level 2 authentication
        r   r   rD  r   r   rE  r   )r   r?   r"   r   rq   rf   rZ   rM   r   rp   rP   rF  s           r   
get_tradeszClobClient.get_trades(  s    
 	  ""%fE(djj,O%0%<k&Z'(dii0&+C 30H"=1Kx''G Z' r   c                 V    t        dj                  | j                  t        |            S )z7
        Fetches the last trade price token_id
        r   )rP   r   rp   r   r   s     r   get_last_trade_pricezClobClient.get_last_trade_price=  s$     %,,TYY8LhWXXr   c                     |D cg c]  }d|j                   i }}t        dj                  | j                  t              |      S c c}w )zG
        Fetches the last trades prices for a set of token ids
        r   r   r   )r   rQ   r   rp   r2   r   s       r   get_last_trades_pricesz!ClobClient.get_last_trades_pricesC  sD     ;AAU^^,AAFMM$))-CD4PP Br   c                 H    | j                   t        k  rt        t              y)z#
        Level 1 Poly Auth
        N)rs   rV   rL   rW   r   s    r   r   zClobClient.assert_level_1_authJ        99r> 344 r   c                 H    | j                   t        k  rt        t              y)z#
        Level 2 Poly Auth
        N)rs   rX   rL   rY   r   s    r   r   zClobClient.assert_level_2_authQ  r\  r   c                 B    | j                         st        t              y)z
        Builder Auth
        N)r&  rL   r[   r   s    r   assert_builder_authzClobClient.assert_builder_authX  s!     $$& 899 'r   c                 V    | j                   d uxr | j                   j                         S N)ri   is_validr   s    r   r&  zClobClient.can_builder_auth_  s'    ""$.Q43F3F3O3O3QQr   c                 n    | j                   | j                  t        S | j                   t        S t        S ra  )rq   rf   rX   rV   rU   r   s    r   rr   zClobClient._get_client_modeb  s.    ;;"tzz'=I;;"I	r   r   r   c                     | j                   @| j                  |j                  |j                  |j                        }|yt        ||      S y)zN
        Generates builder headers and attaches them to the L2 Header
        N)ri   _get_builder_headersr   r   r   r	   )r   r   r   r)  s       r   r'  z$ClobClient._generate_builder_headersi  sV     *"77##)),,O
 &9'?SSr   r   pathr   c                 b    | j                   j                  |||      }|r|j                         S y)aZ  
        Generates builder headers for the given method, path, and body.

        Args:
            method (str): HTTP method.
            path (str): Request path.
            body (Optional[str]): Pre-serialized JSON string or None.

        Returns:
            dict or None: Builder headers as a dictionary, or None if not available.
        N)ri   generate_builder_headersto_dict)r   r   rf  r   r   s        r   re  zClobClient._get_builder_headersx  s1     %%>>vtTR??$$r   c                 
   | j                          t        dt              }t        | j                  | j
                  |      }dj                  | j                  t        | j                  j                        }t        ||      S )z^
        Fetches the notifications for a user
        Requires Level 2 authentication
        r   r   z{}{}?signature_type={}r   )r   r?   r#   r   rq   rf   r   rp   rt   rn   rP   )r   r   r   rH  s       r   get_notificationszClobClient.get_notifications  sh    
 	  ""%>OP(djj,O&--II($,,*?*?
 3((r   c                     | j                          t        dt              }t        | j                  | j
                  |      }t        dj                  | j                  t              |      }t        ||      S )z\
        Drops the notifications for a user
        Requires Level 2 authentication
        r   r   r   r   )
r   r?   r$   r   rq   rf   rR   r   rp   rO   r   r   r   r   rH  s        r   drop_notificationszClobClient.drop_notifications  sa    
 	  ""(AST(djj,O-MM$))%78&
 c7++r   c                 H   | j                          t        dt              }t        | j                  | j
                  |      }|j                  dk(  r| j                  j                  |_        t        dj                  | j                  t              |      }t        ||      S )zd
        Fetches the balance & allowance for a user
        Requires Level 2 authentication
        r   r   rm   r   r   )r   r?   r%   r   rq   rf   rg   rt   rn   rS   r   rp   rP   rm  s        r   get_balance_allowancez ClobClient.get_balance_allowance  s    
 	  ""%>ST(djj,O  B&$(LL$9$9F!1MM$))%:;V
 3((r   c                 H   | j                          t        dt              }t        | j                  | j
                  |      }|j                  dk(  r| j                  j                  |_        t        dj                  | j                  t              |      }t        ||      S )zd
        Updates the balance & allowance for a user
        Requires Level 2 authentication
        r   r   rm   r   r   )r   r?   r&   r   rq   rf   rg   rt   rn   rS   r   rp   rP   rm  s        r   update_balance_allowancez#ClobClient.update_balance_allowance  s    
 	  ""%>VW(djj,O  B&$(LL$9$9F!1MM$))%=>
 3((r   c                     | j                          t        dt              }t        | j                  | j
                  |      }t        dj                  | j                  t              |      }t        ||      S )za
        Check if the order is currently scoring
        Requires Level 2 authentication
        r   r   r   r   )
r   r?   r'   r   rq   rf   rT   r   rp   rP   rm  s        r   is_order_scoringzClobClient.is_order_scoring  sa    
 	  ""%>NO(djj,O-MM$))%56
 3((r   c                 *   | j                          |j                  }t        j                  |dd      }t	        dt
        ||      }t        | j                  | j                  |      }t        dj                  | j                  t
              ||      S )zc
        Check if the orders are currently scoring
        Requires Level 2 authentication
        r   Fr   r   r   r   r   )r   orderIdsr   r   r?   r+   r   rq   rf   rQ   r   rp   )r   r   r   r   r   r   s         r   are_orders_scoringzClobClient.are_orders_scoring  s    
 	  "ZZ%P
"+&	
 )djj,OMM$))%78
 	
r   c                 V    t        dj                  | j                  t        |            S )z2
        Get the current sampling markets
        {}{}?next_cursor={})rP   r   rp   r0   r   rE  s     r   get_sampling_marketszClobClient.get_sampling_markets  s(     !((4H+V
 	
r   c                 V    t        dj                  | j                  t        |            S )z=
        Get the current sampling simplified markets
        ry  )rP   r   rp   r/   rz  s     r   get_sampling_simplified_marketsz*ClobClient.get_sampling_simplified_markets  s+     !((		:K
 	
r   c                 V    t        dj                  | j                  t        |            S )z)
        Get the current markets
        ry  )rP   r   rp   r-   rz  s     r   get_marketszClobClient.get_markets  s#     (//		;TUUr   c                 V    t        dj                  | j                  t        |            S )z4
        Get the current simplified markets
        ry  )rP   r   rp   r,   rz  s     r   get_simplified_marketsz!ClobClient.get_simplified_markets  s(     !((4JKX
 	
r   c                 V    t        dj                  | j                  t        |            S )z.
        Get a market by condition_id
        {}{}{})rP   r   rp   r.   r   condition_ids     r   
get_marketzClobClient.get_market  s      8??499j,GHHr   c                 V    t        dj                  | j                  t        |            S )z@
        Get the market's trades events by condition id
        r  )rP   r   rp   r1   r  s     r   get_market_trades_eventsz#ClobClient.get_market_trades_events	  s!     8??499.FUVVr   c                 j   | j                          t        dt              }| j                  |j                  |j
                  |j                        }g }||nd}|t        k7  rOt        dj                  | j                  t              ||      }t        ||      }|d   }||d   z  }|t        k7  rO|S )z6
        Get trades originated by the builder
        r   r   rD  r   r   rE  r   )r_  r?   r8   re  r   r   r   rZ   rM   r   rp   rP   rF  s           r   get_builder_tradeszClobClient.get_builder_trades  s     	  ""%>PQ++!:!:L<M<M
 %0%<k&Z'(dii);<fkC 30H"=1Kx''G Z' r   r   r  r  c                 @   | j                  |      }|t        d      |dk(  r>|j                  t        d      | j                  j	                  |j                  ||      S |j
                  t        d      | j                  j                  |j
                  ||      S )z_
        Calculates the matching price considering an amount and the current orderbook
        zno orderbookBUYzno match)rL  r  asksrt   calculate_buy_market_pricebidscalculate_sell_market_price)r   r   r   r  r  r   s         r   r  z!ClobClient.calculate_market_price&  s     ""8,<N++5=yy 
++<<::		6:  yy 
++<<;;		6: r   )NNNNNNg     r@)Fra  ) r  )NrD  )rD  )cr~   
__module____qualname__intr   r:   r   r  r   r   r   r   r   r   r   r   r   r   r   r   r   r   r;   r   listr   boolr   r   r   rI   r   r   r   r   r   rD   r   r   rA   r   r   r  r  r  r>   r   rH   r  rJ   r   rK   r*  rG   r-  r/  r2  r6  r:  r<  r?  rB  r=   rI  rL  rO  rR  rT  r<   rV  rX  rZ  r   r   r_  r&  rr   r?   dictr'  re  rk  r@   rn  rB   rp  rr  rC   rt  rF   rw  r{  r}  r  r  r  r  r  r   r   r   rc   rc   t   s:    "(,$0A 0A 	0A
 0A 0A 0A &0A 0Ad>.6,,3C 8 *C 8 *. .x .,8 ,	L	K	Q)? "	UtCy 	U
3 
4 
,	
 	
3 	
3 	
NED$4 EXEj!1 EOF$z"2 F+c +h + 0c 0J6F J"S "T "   48(0	 #3 #s #c #" UY+
#+
.67P.Q+
` 8<5
#5
 345
n
^ 4 
> 8A}}X] 
9 
QU 
@ KO$#$.G$
*
&M
8C= 
 
3 
s 
* **: 	d:&6 	4@P;Q 	:-= :# :	H *YQT*-= Q55:R$ Rk D 3 c # "),)? ,),B ))/E ))'9 )
)< 
*

V
IW .#&05CL	r   rc   )or{   r   r   typingr   py_builder_signing_sdk.configr   order_builder.builderr   headers.headersr   r   r	   rq   r
   configr   	endpointsr   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/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   
clob_typesr:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   
exceptionsrL   http_helpers.helpersrM   rN   rO   rP   rQ   rR   rS   rT   	constantsrU   rV   rW   rX   rY   rZ   r[   	utilitiesr\   r]   r^   r_   r`   rz   ra   rc   r  r   r   <module>r     s        7 / 
  '/ / / / / / / / / / / /`    ( &	 	 	    F Fr   