
    ei)                         d dl 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 d dlmZ d dlmZ d dlmZ  G d dej        j                  ZdS )	    N)
ArrayCacheArrayCacheBySymbolByIdArrayCacheBySymbolBySide)
AnyBalancesIntOrder	OrderBookPositionStrStringsTickerTrade)Client)List)ExchangeErrorc            
           e Zd Zdef fdZd ZdefdZdefdZi i fde	de	defd	Z
i i fde	d
e	defdZddi fde	dededee         fdZdefdZi fde	defdZdefdZdi fde	dedefdZdefdZd Zdddi fdedededee         fdZdefdZdddi fdedededee         fdZdefdZi fdefdZdefdZ dddi fde!dededee"         fdZ#defdZ$defd Z%defd!Z& xZ'S )"bullishreturnc                     |                      t          t          |                                           ddddddddddd
ddddiddd	did
ddi ii| j        ddd          S )NTF)
wswatchTickerwatchTickerswatchOrderBookwatchOrderswatchTradeswatchPositionswatchMyTradeswatchBalance
watchOHLCVr   zwss://api.exchange.bullish.comz:wss://api.exchange.bullish.com/trading-api/v1/private-data)publicprivatez"wss://api.simnext.bullish-test.comz>wss://api.simnext.bullish-test.com/trading-api/v1/private-data)apitestcookiesi )ping	keepAlive)hasurlsoptions	streaming)deep_extendsuperr   describer&   )self	__class__s    N/var/www/html/volatility/venv/lib/python3.11/site-packages/ccxt/pro/bullish.pyr.   zbullish.describe   s    gt 4 4 = = ? ?# %"&##"&!% $#  "B#_  "F#c   r 	" A$B
 $B
 $ $ $	    c                 z    |                      |                     | j        dd          d          }|| j        d<   |S )N	requestIdr      )sumsafe_integerr*   )r/   r4   s     r1   
request_idzbullish.request_id7   s;    HHT..t|[!LLaPP	$-[!r2   clientc                 T    t          |                                           }dddi |dS )N2.0commandkeepalivePingjsonrpctypemethodparamsid)strr8   )r/   r9   rC   s      r1   r&   zbullish.ping<   s9     ""##%
 
 	
r2   c                 8    |                                  |_        |S )N)millisecondslastPong)r/   r9   messages      r1   handle_pongzbullish.handle_pongH   s     ++--r2   urlmessageHashc                    K   t          |                                           }ddd||d}| j        d         d         d         |z   }|                     |||                     ||          |           d {V S )Nr;   r<   	subscriber>   r#   r   r!   )rD   r8   r)   watchr,   )r/   rJ   rK   requestrB   rC   rH   fullUrls           r1   watch_publiczbullish.watch_publicW   s      ""##!
 
 )E"4(2S8ZZd6F6FwPV6W6WYdeeeeeeeeer2   subscribeHashc                 N  K   | j         d         d         d         }|                                  d {V }d|i}|| j        d         d<   t          |                                           }ddd||d	}	|                     |||                     |	|          |           d {V }
|
S )
Nr#   r   r"   
JWT_COOKIEr%   r;   r<   rM   r>   )r)   handleTokenr*   rD   r8   rN   r,   )r/   rK   rR   rO   rB   rJ   tokenr%   rC   rH   results              r1   watch_privatezbullish.watch_privatec   s      it$Y/&&((((((((%
 )0T9%""##!
 
 zz#{D4D4DWf4U4UWdeeeeeeeer2   Nsymbolsincelimitc                 <  K   |                                   d{V  |                     |          }d|d         z   }d}d|d         d}|                     ||||           d{V }	| j        r|	                    ||          }|                     |	||dd	          S )
a`  
        get the list of most recent trades for a particular symbol

        https://api.exchange.bullish.com/docs/api/rest/trading-api/v2/#overview--unified-anonymous-trades-websocket-unauthenticated

        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/?id=public-trades>`
        Ntrades::rY   z"/trading-api/v1/market-data/tradesanonymousTradesrC   topicrY   	timestampT)load_marketsmarketrQ   
newUpdatesgetLimitfilter_by_since_limit)
r/   rY   rZ   r[   rB   rc   rK   rJ   rO   tradess
             r1   watch_tradeszbullish.watch_tradesu   s       !!!!!!!!!V$$ 6(#332&Tl
 
 ((k7FKKKKKKKK? 	3OOFE22E))&%TRRRr2   c                 p   |                      |di           }|                     |d          }|                     |          }|                     |          }|                     |dg           }|                     ||          }|| j        vr5|                     | j        dd          }	t          |	          }
|
| j        |<   | j        |         }t          dt          |                    D ]}|                    ||                    || j        |<   d|d         z   }|                    ||           d S )NdatarY   rg   tradesLimit  r   r]   )	safe_dictsafe_stringsafe_symbolrc   	safe_listparse_tradesrg   r7   r*   r   rangelenappendresolve)r/   r9   rH   rj   marketIdrY   rc   	rawTradesrg   r[   tradesArrayCachetradesArrayirK   s                 r1   handle_tradeszbullish.handle_trades   s7   2 ~~gvr22##D(33!!(++V$$NN4266	""9f55$+%%%%dlM4HHE)%00"2DKk&)q#f++&& 	* 	*Avay)))))F 6(#33{K00000r2   c                   K   |                                   d{V  |                     |          }|d         }| j        d         d         d         dz   |d         z   }d|z   }|                     ||||           d{V S )	a  
        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://api.exchange.bullish.com/docs/api/rest/trading-api/v2/#overview--anonymous-market-data-price-tick-unauthenticated

        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/?id=ticker-structure>`
        NrY   r#   r   r!   z!/trading-api/v1/market-data/tick/rC   ticker::)rb   rc   r)   rN   )r/   rY   rB   rc   rJ   rK   s         r1   watch_tickerzbullish.watch_ticker   s       !!!!!!!!!V$$!it$X.1TTW]^bWcc 6)ZZ[&+FFFFFFFFFr2   c                 0   |                      |dd          }|                     |di           }|                      |d          }|                     |          }|d         }d }|dk    r|                     ||          }ne|dk    r_|                     | j        |i           }	|                     |	di           }
|                     |
|          }|                     ||          }|| j        |<   d|z   }|                    | j        |         |           d S )	Nr@    rj   rY   snapshotupdateinfor}   )rn   rm   safe_marketparse_tickertickersextendru   )r/   r9   rH   
updateTyperj   rv   rc   rY   parsedticker	rawTickermergedrK   s                r1   handle_tickerzbullish.handle_ticker   s    Z %%gvr::
~~gvr22##D(33!!(++!*$$&&tV44FF8##^^DL&"==Fvvr::I[[D11F&&vv66F%V 6)t|F+[99999r2   c                    K   |                                   d{V  |                     |          }d}d|d         z   }d|d         d}|                     ||||           d{V }|                                S )an  
        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://api.exchange.bullish.com/docs/api/rest/trading-api/v2/#overview--multi-orderbook-websocket-unauthenticated

        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/?id=order-book-structure>` indexed by market symbols
        Nz%/trading-api/v1/market-data/orderbookorderbook::rY   l2OrderbookrC   r_   )rb   rc   rQ   r[   )	r/   rY   r[   rB   rc   rJ   rK   rO   	orderbooks	            r1   watch_order_bookzbullish.watch_order_book  s       !!!!!!!!!V$$5#fX&66"Tl
 
 ++CgvNNNNNNNN	   r2   c                    |                      |di           }|                     |d          }|                     |          }d|z   }|                     |d          }|| j        vr|                                 | j        |<   | j        |         }|                     |                     |dg                     }	|                     |                     |dg                     }
|	|
d}|                     |||          }|                     |dg           }t          |          d	k    r+t          |          d
z
  }|                     ||          |d<   |
                    |           || j        |<   |                    ||           d S )Nrj   rY   r   ra   bidsasks)r   r   sequenceNumberRanger   r5   nonce)rm   rn   ro   r7   
orderbooks
order_bookseparate_bids_or_asksrp   parse_order_bookrs   resetru   )r/   r9   rH   rj   rv   rY   rK   ra   r   r   r   r   r   r   	lastIndexs                  r1   handle_order_bookzbullish.handle_order_book  s   . ~~gvr22##D(33!!(++#f,%%dK88	$/))&*oo&7&7DOF#OF+	))$..vr*J*JKK))$..vr*J*JKK
 
 &&xCC"nnT3H"MM"##a''/0014I"//0CYOOF7O"+y+.....r2   c                     g }t          dt          |                    D ]R}|dz  dk    r|                     ||          }|                     ||dz             }|                    ||g           S|S )Nr      r5   )rr   rs   rn   rt   )r/   entryrW   rz   priceamounts         r1   r   zbullish.separate_bids_or_asksK  s     q#e**%% 	+ 	+A1uzz$$UA..E%%eQU33FMM5&/****r2   c                   K   |                                   d{V  d}|}||                     |          }|dz   |z   }ddi}|                     |d          }|||d<   |                     |d          }|                     ||||           d{V }	| j        r|	                    ||          }|                     |	|||d          S )a  
        watches information on multiple orders made by the user

        https://api.exchange.bullish.com/docs/api/rest/trading-api/v2/#overview--private-data-websocket-authenticated

        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.tradingAccountId]: the trading account id to fetch entries for
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        Norders::r`   tradingAccountIdT)rb   rY   rn   omitrX   rd   re   filter_by_symbol_since_limit)
r/   rY   rZ   r[   rB   rR   rK   rO   r   r   s
             r1   watch_orderszbullish.watch_ordersX  s
      !!!!!!!!! #[[((F%,v5KX
  ++F4FGG'*:G&'YYv'9::F))+}gvVVVVVVVV? 	3OOFE22E00tTTTr2   c                 X   |                      |d          }g }|dk    r-|                     |di           }|                    |           n|                     |dg           }t	          |          dk    r1| j        0|                     | j        dd          }t          |          | _        | j        }i }t          dt	          |                    D ]O}	||	         }
| 
                    |
          }|                    |           |                      |d          }d||<   Pd	}|                    ||           t          |                                          }t          dt	          |                    D ]/}	||	         }|d
z   |z   }|                    | j        |           .d S d S )Nr@   r   rj   r   ordersLimitrl   rY   Tr   r   )rn   rm   rt   rp   rs   r   r7   r*   r   rr   parse_orderru   listkeys)r/   r9   rH   r@   	rawOrdersrj   r[   r   symbolsrz   rawOrderparsedOrderrY   rK   r   
hashSymbolsymbolMessageHashs                    r1   handle_orderszbullish.handle_ordersw  s   Z 00	8>>'6266DT""""w;;Iy>>A{"))$,tLL4U;;[FG1c)nn-- ' '$Q<"..x88k***))+x@@"&"KNN6;///''D1c$ii(( ? ?!!W
$/$$6$C!t{,=>>>>% ? ?r2   c                   K   |                                   d{V  d}|}||                     |          }|d|z   z  }ddi}|                     |d          }|||d<   |                     |d          }|                     ||||           d{V }	| j        r|	                    ||          }|                     |	||dd          S )	a  
        watches information on multiple trades made by the user

        https://api.exchange.bullish.com/docs/api/rest/trading-api/v2/#overview--private-data-websocket-authenticated

        :param str symbol: unified market symbol of the market trades were made in
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trade structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.tradingAccountId]: the trading account id to fetch entries for
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/?id=trade-structure>`
        NmyTradesr   r`   rg   r   ra   T)rb   rY   rn   r   rX   rd   re   rf   )
r/   rY   rZ   r[   rB   rR   rK   rO   r   rg   s
             r1   watch_my_tradeszbullish.watch_my_trades  s	      !!!!!!!!!"#[[((F4&=(KX
  ++F4FGG'*:G&'YYv'9::F))+}gvVVVVVVVV? 	3OOFE22E))&%TRRRr2   c                 X   |                      |d          }g }|dk    r-|                     |di           }|                    |           n|                     |dg           }t	          |          dk    r1| j        0|                     | j        dd          }t          |          | _        | j        }i }t          dt	          |                    D ]O}	||	         }
| 
                    |
          }|                    |           |                      |d          }d||<   Pd	}|                    ||           t          |                                          }t          dt	          |                    D ]/}	||	         }|d
z   |z   }|                    | j        |           .d S d S )Nr@   r   rj   r   rk   rl   rY   Tr   r   )rn   rm   rt   rp   rs   r   r7   r*   r   rr   parse_traderu   r   r   )r/   r9   rH   r@   rw   rj   r[   rg   r   rz   rawTradeparsedTraderY   rK   r   r   r   s                    r1   handle_my_tradeszbullish.handle_my_trades  s   L 00	8>>'6266DT""""w;;Iy>>A}$))$,tLL 6u = =]FG1c)nn-- ' '$Q<"..x88k***))+x@@"&$KNN6;///''D1c$ii(( A A!!W
$/$$6$C!t}.?@@@@% A Ar2   c                    K   |                                   d{V  ddi}d}|                     |d          }|#|                     |d          }||d<   |d|z   z  }|                     ||||           d{V S )a  
        watch balance and get the amount of funds available for trading or funds locked in orders

        https://api.exchange.bullish.com/docs/api/rest/trading-api/v2/#overview--private-data-websocket-authenticated

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.tradingAccountId]: the trading account id to fetch entries for
        :returns dict: a `balance structure <https://docs.ccxt.com/?id=balance-structure>`
        Nr`   assetAccountsbalancer   r   )rb   rn   r   rX   )r/   rB   rO   rK   r   s        r1   watch_balancezbullish.watch_balance  s       !!!!!!!!!_
  ++F4FGG'YYv'9::F*:G&'4"222K''['6RRRRRRRRRr2   c                 2   |                      |d          }|| j        vr
i | j        |<   |                      |d          }|dk    r5|                     |dg           }|                     |          | j        |<   n|                     |di           }|                      |d          }|                                 }|                      |d          |d<   |                      |d          |d	<   |                     |          }|| j        |         |<   || j        |         d
<   |                     | j        |                   | j        |<   d}	d|z   }
|                    | j        |         |	           |                    | j        |         |	|
z              d S )Nr   r@   r   rj   assetSymbolavailableQuantitytotallockedQuantityusedr   r   r   )	rn   r   rp   parse_balancerm   accountsafe_currency_codesafe_balanceru   )r/   r9   rH   r   messageTyperj   assetIdr   coderK   tradingAccountIdHashs              r1   handle_balancezbullish.handle_balance5  s   T  ++G5GHH DL00-/DL)*&&w77*$$>>'6266D-1-?-?-E-EDL)**>>'6266D&&t];;GllnnG#//6IJJGG"..t5EFFGFO**733D3:DL)*405<DL)*62-1->->t|L\?]-^-^DL)*#&66t|$45{CCCt|$45{EY7YZZZZZr2   r   c                 T  K   |                                   d{V  d}|}|                     |          s0|                     |          }|dd                    |          z   z  }ddi}|                     ||||           d{V }| j        r|S |                     ||||d          S )a@  

        https://api.exchange.bullish.com/docs/api/rest/trading-api/v2/#overview--private-data-websocket-authenticated

        watch all open positions
        :param str[] [symbols]: list of unified market symbols
        :param int [since]: the earliest time in ms to fetch positions for
        :param int [limit]: the maximum number of positions to retrieve
        :param dict params: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/en/latest/manual.html#position-structure>`
        N	positionsr   ,r`   derivativesPositionsV2T)rb   is_emptymarket_symbolsjoinrX   rd   filter_by_symbols_since_limit)	r/   r   rZ   r[   rB   rR   rK   rO   r   s	            r1   watch_positionszbullish.watch_positionsu  s       !!!!!!!!!##}}W%% 	4))'22G4#((7"3"333K-
 ,,[-RXYYYYYYYY	? 	11)WeUTXYYYr2   c                 p   |                      |d          }g }|dk    r-|                     |di           }|                    |           n|                     |dg           }| j        t                      | _        | j        }g }t          dt          |                    D ]I}||         }	|                     |	          }
|                    |
           |                    |
           J| 	                    |d          }t          dt          |                    D ]}||         }|
                    d          }|d         }|
                    d          }|                     |d	|d
          }|                     |          s|                    ||           |                    |d           d S )Nr@   r   rj   r   zpositions::r   r5   r   rY   Fr   )rn   rm   rt   rp   r   r   rr   rs   parse_positionfind_message_hashessplitfilter_by_arrayr   ru   )r/   r9   rH   r   rawPositionsrj   r   newPositionsrz   rawPositionpositionmessageHashesrK   partssymbolsStringr   symbolPositionss                    r1   handle_positionszbullish.handle_positions  s    &&w77("">>'6266D%%%%>>'62>>L>!577DNN	q#l++,, 	* 	*A&q/K**;77HX&&&))))00GGq#m,,-- 	= 	=A'*K%%d++E!!HM#))#..G"22<7TYZZO==11 =<<<y+.....r2   c                    |                      |di           }| j        dz   |                     |          z   }	 |                     |d          }|                     |d          }|                     | j        d         ||           |                     | j        d         ||           t          |          # t          $ r }|	                    |           Y d }~d S d }~ww xY w)Nrj    	errorCodeerrorCodeNameexactbroad)
rm   rC   jsonrn   throw_exactly_matched_exception
exceptionsthrow_broadly_matched_exceptionr   	Exceptionreject)r/   r9   rH   rj   feedbackr   r   es           r1   handle_error_messagezbullish.handle_error_message  s     ~~gvr227S=499T??2	(({;;I ,,T?CCM001I9V^___001I=Zbccc))) 	 	 	MM!	s   A?B8 8
C"CC"c                 b   |                      |d          }|                     |d          }|6|                      |d          }|dk    r|                     ||           d S d S ||dk    r|                     ||           |dk    r|                     ||           |dk    r|                     ||           |dk    r|                     ||           |d	k    r|                     ||           |d
k    r|                     ||           |dk    r| 	                    ||           d S d S d S )NdataTyperW   rH   zKeep alive pongV1TAAnonymousTradeUpdateV1TATickerResponse
V1TALevel2	V1TAOrder	V1TATradeV1TAAssetAccountV1TAErrorResponse)
rn   rm   rI   r{   r   r   r   r   r   r   )r/   r9   rH   r   rW   responses         r1   handle_messagezbullish.handle_message  s|   ##GZ8822''	::H,,,  11111 -,!555""67333///""67333<''&&vw777;&&""67333;&&%%fg666---##FG444...))&'::::: "! /.r2   )(__name__
__module____qualname__r   r.   r8   r   r&   rI   rD   rQ   rX   r   r   r   rh   r{   r   r~   r   r
   r   r   r   r   r	   r   r   r   r   r   r   r   r   r   r   r   r   r  __classcell__)r0   s   @r1   r   r      s       %# % % % % % %N  


6 

 

 

 

&     FHPR 
f 
fc 
f 
fWZ 
f 
f 
f 
f QS[]  s 3 be    $ <@d[] S S SS S Sbfglbm S S S S2(1F (1 (1 (1 (1T 68 G G GF G G G G"<:F <: <: <: <:| @DB ! !S ! !S\ ! ! ! !,,/ ,/ ,/ ,/ ,/\   04$UYbd U U UC Us Uimnsit U U U U>F?F F? F? F? F?P 37TX\eg S SC Ss SRU Slpqvlw S S S S>?Av ?A ?A ?A ?AB *, S S S S S S,>[V >[ >[ >[ >[@ 8<$]ajl Z ZW ZC ZWZ Zquv~q Z Z Z Z4/v / / / />6    .;V ; ; ; ; ; ; ; ;r2   r   )ccxt.async_supportccxt ccxt.async_support.base.ws.cacher   r   r   ccxt.base.typesr   r   r   r	   r
   r   r   r   r   r   !ccxt.async_support.base.ws.clientr   typingr   ccxt.base.errorsr   async_supportr    r2   r1   <module>r     s        i i i i i i i i i i g g g g g g g g g g g g g g g g g g g g g g g g 4 4 4 4 4 4       * * * * * *L; L; L; L; L;d ( L; L; L; L; L;r2   