
    ei                       d dl Zd dlmZmZmZmZ d dl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 d dlmZ d dlmZ d dlm Z  d dlm!Z! d dlm"Z" d d	lm#Z# d d
lm$Z$ d dlm%Z%  G d dej&        j'                  Z'dS )    N)
ArrayCacheArrayCacheBySymbolByIdArrayCacheBySymbolBySideArrayCacheByTimestamp)AnyBalancesBoolIntLiquidationNumOrder	OrderBook	OrderSide	OrderTypePositionStrStringsTickerTickersFundingRateFundingRatesTrade)Client)List)ExchangeError)AuthenticationError)ArgumentsRequired)
BadRequest)InvalidNonce)ChecksumErrorc                       e Zd Zdef fdZdZdefdZdi fdefdZi fd	Z	ddi fd
ede
de
dee         fdZddi fdee         de
de
dee         fdZi fdee         defdZi fd
edefdZdefdZi fd
edefdZdi fdedefdZdefdZi fd
edefdZi fd
edefdZdi fdedefdZi fd
edefdZdi fdedefdZdi fdedefdZdefdZ di fdedefdZ!defdZ"d[dZ#ddi fdee         de
de
dee$         fd Z%defd!Z&ddi fdee         de
de
dee$         fd"Z'defd#Z(d[d$Z)d[d%Z*d&ddi fd
ed'ede
de
dee+         f
d(Z,d&i fd
ed'edefd)Z-ddi fd*eee                  de
de
fd+Z.i fd*eee                  defd,Z/defd-Z0di fd
ede
de1fd.Z2di fdee         de
de1fd/Z3i fdee         defd0Z4i fd
edefd1Z5d2 Z6d3 Z7d[defd4Z8defd5Z9i fd6Z:i fde;fd7Z<defd8Z=defd9Z>d[d:Z?dddi fd
e@de
de
dee         fd;ZAdddi fdede
de
deeB         fd<ZCd= ZDdddi fd
e@de
de
deeE         fd>ZFdefd?ZGdefd@ZHdA ZIdi fd
edBeJdCeKdDeLdEeMdeEfdFZNdefdGZOddi fdHed
edBeJdCeKdDeMdEeMdeEfdIZPdi fdHed
e@deEfdJZQdi fdKee         d
e@fdLZRdi fd
e@deeE         fdMZSdefdNZTdefdOZUdefdPZVdefdQZWdefdRZXdedeYfdSZZdefdTZ[ded
edefdUZ\ded
edefdVZ]ded
edefdWZ^ded
efdXZ_defdYZ` xZaS )\okxreturnc                 T   |                      t          t          |                                           i ddddddddddddddd	dd
dddddddddddddddddddddddddddd
ddiddidddddddiddiddiddidd idd!ii d"	| j        d#d$d%          S )&NwsTwatchTickerwatchMarkPricewatchMarkPriceswatchTickerswatchBidsAskswatchOrderBookwatchTradeswatchTradesForSymbolswatchOrderBookForSymbolswatchBalancewatchLiquidationsemulatedwatchLiquidationsForSymbolswatchMyLiquidationswatchMyLiquidationsForSymbols
watchOHLCVwatchOHLCVForSymbols)
watchOrderswatchMyTradeswatchPositionswatchFundingRatewatchFundingRatescreateOrderWseditOrderWscancelOrderWscancelOrdersWscancelAllOrdersWszwss://ws.okx.com:8443/ws/v5zwss://wspap.okx.com:8443/ws/v5)apitestbooks)checksumdepthspotchanneltickerstypeANYopbatch-ordersamend-order)	r+   r/   r&   r)   r7   r8   r<   r=   r%   iPF  )ping	keepAlive)hasurlsoptions	streaming)deep_extendsuperr"   describerN   )self	__class__s    J/var/www/html/volatility/venv/lib/python3.11/site-packages/ccxt/pro/okx.pyrV   zokx.describe   s   c4 0 0 9 9 ; ;dt !$ "4	
    !$ t ( +D  $Z .t &z 0  d!" '#$  $!%"&$(%)!%#!%"&%)7  > 7 :	  !%0 %3# #6 !'y  y! E  E" ." - _2 2l 	"	 s_>
 _>
 _ _ _	    publicrG   c                     | j         d         }|rdnd}|dk    }|dk    }| j        d         d         }|s|                    d          d	k    s|d
k    r|dz   |z   S |r|dz   |z   S |dz   |z   S )NsandboxModez?brokerId=9999 businessr[   rA   r%   candleorders-algoz	/businessz/publicz/private)rR   rQ   find)rW   rG   access	isSandboxsandboxSuffix
isBusinessisPublicurls           rY   get_urlzokx.get_urlx   s    L/	,5=((2
*
h&it$ 	3',,x002557m;S;S$}44 	3?]22Z-//rZ   Nsymbolsc                   K   |                                   d {V  || j        }|                     |          }|                     ||          }g }g }t	          dt          |                    D ]l}|                     ||                   }	||	d}
|                    |                     |
|                     |                    |dz   ||         z              md|d}| 	                    ||||           d {V S )Nr   rG   instId::	subscriberK   args)
load_marketsrk   market_symbolsrj   rangelen	market_idappendextendwatch_multiple)rW   rd   rG   rk   paramsri   messageHashesrr   imarketIdargrequests               rY   subscribe_multiplezokx.subscribe_multiple   s2     !!!!!!!!!?lG%%g..ll7F++q#g,,'' 	> 	>A~~gaj11H"" C KKC00111  4'!*!<====
 
 ((mWmTTTTTTTTTrZ   c                 >  K   |                                   d {V  |                     ||          }d|i}|.|                     |          }|d|d         z   z  }|d         |d<   d|                     ||          gd}	|                     |||	|           d {V S )NrG   :idrn   rp   rq   )rs   rj   marketrT   watch)
rW   rd   messageHashrG   symbolr{   ri   firstArgumentr   r   s
             rY   rp   zokx.subscribe   s      !!!!!!!!!ll7F++w
 [[((F3--K&,TlM(#  77
 
 ZZ[';GGGGGGGGGrZ   r   sincelimitc                 D   K   |                      |g|||           d{V S )a  

        https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-trades-channel
        https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-all-trades-channel

        get the list of most recent trades for a particular symbol
        :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)watch_trades_for_symbols)rW   r   r   r   r{   s        rY   watch_tradeszokx.watch_trades   s6       22F8UE6RRRRRRRRRrZ   c                 f  K   t          |          }|dk    rt          | j        dz             |                                  d{V  |                     |          }d}|                     |ddd          \  }}g }g }t          dt          |                    D ]T}	||	         }
|                    |dz   |
z              |                     |
          }||d}|                    |           Ud	|d
}d}|dk    rd}| 	                    d|i           d{V  | 
                    ||          }|                     ||||           d{V }| j        rB|                     |d          }|                     |d          }|                    ||          }|                     |||dd          S )a  

        https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-trades-channel
        https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-all-trades-channel

        get the list of most recent trades for a particular symbol
        :param str symbols:
        :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
        :param str [params.channel]: the channel to subscribe to, trades by default. Can be 'trades' and 'trades-all'
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/?id=public-trades>`
        r   z> watchTradesForSymbols() requires a non-empty array of symbolsNr,   rG   tradesr   rm   rp   rq   r[   
trades-allr_   rd   r   	timestampT)rv   r   r   rs   rt   handle_option_and_paramsru   rx   rw   authenticaterj   rz   
newUpdates
safe_valuesafe_stringgetLimitfilter_by_since_limit)rW   rk   r   r   r{   symbolsLengthrG   topicsr|   r}   r   r~   topicr   rd   ri   r   firsttradeSymbols                      rY   r   zokx.watch_trades_for_symbols   s
      GA#DG.n$nooo!!!!!!!!!%%g..77yZbccq#g,,'' 	! 	!AQZF  3!7888~~f--H"" E MM%    
 
 l""F##Xv$6777777777ll7F++**3wVVVVVVVV? 	8OOFA..E**5(;;KOOK77E))&%TRRRrZ   c                 T  K   |                                   d{V  |                     |dd          }d}|                     |ddd          \  }}g }g }t          dt	          |                    D ]W}||         }|                    d|z   dz   |z              |                     |          }||d	}	|                    |	           Xd
|d}
d}|dk    rd}|                     d|i           d{V  |                     ||          }| 	                    |||
|           d{V S )au  
        unWatches from the stream channel
        :param str[] symbols:
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.channel]: the channel to subscribe to, trades by default. Can be trades, trades-all
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/?id=public-trades>`
        NFr,   rG   r   r   unsubscribe:r   rm   unsubscriberq   r[   r   r_   rd   )
rs   rt   r   ru   rv   rx   rw   r   rj   rz   )rW   rk   r{   rG   r   r|   r}   r   r~   r   r   rd   ri   s                rY   un_watch_trades_for_symbolszokx.un_watch_trades_for_symbols   s      !!!!!!!!!%%gtU;;77yZbccq#g,,'' 	! 	!AQZF  '!9C!?&!HIII~~f--H"" E MM%    
 
 l""F##Xv$6777777777ll7F++((mWmTTTTTTTTTrZ   c                 @   K   |                      |g|           d{V S )a4  
        unWatches from the stream channel
        :param str symbol: unified symbol of the market to fetch trades for
        :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)r   rW   r   r{   s      rY   un_watch_tradeszokx.un_watch_trades  s2       55vhGGGGGGGGGrZ   clientc                 d   |                      |di           }|                     |d          }|                     |d          }|                     |          }|                      |dg           }|                     | j        dd          }t          dt          |                    D ]}	|                     ||	                   }
|dz   |z   }|                      | j        |          }|t          |          }|| j        |<   |
                    |
           |                    ||           d S )	Nr   rG   rn   datatradesLimit  r   r   )r   r   safe_symbolsafe_integerrR   ru   rv   parse_trader   r   rx   resolve)rW   r   messager   rG   r~   r   r   r   r}   trader   storeds                rY   handle_tradeszokx.handle_trades  s/   B oogub11""3	22##C22!!(++w33''mTJJq#d))$$ 	0 	0A$$T!W--E!C-&0K__T[&99F~#K00&,F#MM%   NN6;////	0 	0rZ   c                 z   K   |                      |          }|                     |g|           d{V }||         S )ap  
        watch the current funding rate

        https://www.okx.com/docs-v5/en/#public-data-websocket-funding-rate-channel

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `funding rate structure <https://docs.ccxt.com/?id=funding-rate-structure>`
        N)r   watch_funding_rates)rW   r   r{   frs       rY   watch_funding_ratezokx.watch_funding_rateH  sL       V$$++VHf========&zrZ   c                 |  K   |t          | j        dz             |                                  d{V  |                     |          }d}g }g }t	          dt          |                    D ]T}||         }|                    |dz   |z              |                     |          }||d}	|                    |	           Ud|d}
|                     |d	          }| 	                    |||
|           d{V }| j
        r|                     |d
          }i }|||<   |S |                     | j        d
|          S )a  
        watch the funding rate for multiple markets

        https://www.okx.com/docs-v5/en/#public-data-websocket-funding-rate-channel

        :param str[] symbols: a list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `funding rates structures <https://docs.ccxt.com/?id=funding-rate-structure>`, indexed by market symbols
        Nz1 watchFundingRates() requires an array of symbolsfunding-rater   r   rm   rp   rq   r[   r   )r   r   rs   rt   ru   rv   rx   rw   rj   rz   r   r   filter_by_arrayfundingRates)rW   rk   r{   rG   r   r|   r}   r   r~   r   r   ri   fundingRateresults                 rY   r   zokx.watch_funding_ratesV  s      ?#DG.a$abbb!!!!!!!!!%%g.. q#g,,'' 	! 	!AQZF  3!7888~~f--H"" E MM%    
 
 ll7H-- //]G][[[[[[[[? 	%%k8<<FF(F6NM##D$5xIIIrZ   c                    |                      |dg           }t          dt          |                    D ]P}||         }|                     |          }|d         }|| j        |<   |                    |d|d         z              Qd S )Nr   r   r   zfunding-rate:)	safe_listru   rv   parse_funding_rater   r   )rW   r   r   r   r}   rawfrr   r   s           rY   handle_funding_ratezokx.handle_funding_rate}  s    ( ~~gvr22q#d))$$ 	V 	VAGE11%88K *F(3Df%NN;(<{8?T(TUUUU	V 	VrZ   c                    K   d}|                      |ddd          \  }}||d<   |                     |          }|d         }|                     |g|           d{V }|                     ||          S )a{  

        https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-tickers-channel

        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.channel]: the channel to subscribe to, tickers by default. Can be tickers, sprd-tickers, index-tickers, block-tickers
        :returns dict: a `ticker structure <https://docs.ccxt.com/?id=ticker-structure>`
        Nr&   rG   rH   r   )r   r   watch_tickersr   rW   r   r{   rG   r   tickers         rY   watch_tickerzokx.watch_ticker  s       77yZcdd#yV$$!))6(F;;;;;;;;vv...rZ   c                 @   K   |                      |g|           d{V S )a}  

        https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-tickers-channel

        unWatches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.channel]: the channel to subscribe to, tickers by default. Can be tickers, sprd-tickers, index-tickers, block-tickers
        :returns dict: a `ticker structure <https://docs.ccxt.com/?id=ticker-structure>`
        N)un_watch_tickersr   s      rY   un_watch_tickerzokx.un_watch_ticker  s2       **F8V<<<<<<<<<rZ   c                 (  K   |                                   d{V  |                     |dd          }d}|                     |ddd          \  }}|                     d|||           d{V }| j        r|S |                     | j        d|          S )a  

        https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-tickers-channel

        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list
        :param str[] [symbols]: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.channel]: the channel to subscribe to, tickers by default. Can be tickers, sprd-tickers, index-tickers, block-tickers
        :returns dict: a `ticker structure <https://docs.ccxt.com/?id=ticker-structure>`
        NFr)   rG   rH   r[   r   rs   rt   r   r   r   r   rH   rW   rk   r{   rG   
newTickerss        rY   r   zokx.watch_tickers  s       !!!!!!!!!%%gtU;;77PY[dee228WgvVVVVVVVV
? 	##DL(GDDDrZ   c                    K   d}|                      |ddd          \  }}||d<   |                     |          }|d         }|                     |g|           d{V }||         S )a  

        https://www.okx.com/docs-v5/en/#public-data-websocket-mark-price-channel

        watches a mark price
        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.channel]: the channel to subscribe to, tickers by default. Can be tickers, sprd-tickers, index-tickers, block-tickers
        :returns dict: a `ticker structure <https://docs.ccxt.com/?id=ticker-structure>`
        Nr'   rG   
mark-pricer   )r   r   watch_mark_pricesr   s         rY   watch_mark_pricezokx.watch_mark_price  s       77@PR[]ijj#yV$$!--vh????????f~rZ   c                 (  K   |                                   d{V  |                     |dd          }d}|                     |ddd          \  }}|                     d|||           d{V }| j        r|S |                     | j        d|          S )a  

        https://www.okx.com/docs-v5/en/#public-data-websocket-mark-price-channel

        watches mark prices
        :param str[] [symbols]: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.channel]: the channel to subscribe to, tickers by default. Can be tickers, sprd-tickers, index-tickers, block-tickers
        :returns dict: a `ticker structure <https://docs.ccxt.com/?id=ticker-structure>`
        NFr(   rG   r   r[   r   r   r   s        rY   r   zokx.watch_mark_prices  s       !!!!!!!!!%%gtU;;77@QS\^jkk228WgvVVVVVVVV
? 	##DL(GDDDrZ   c                   K   |                                   d{V  |                     |dd          }d}|                     |ddd          \  }}g }g }t          dt	          |                    D ]Q}||         }|                    d|z              |                     |          }||d}	|                    |	           Rd	|d
}
|                     |d          }|                     |||
|           d{V S )a  

        https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-tickers-channel

        unWatches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list
        :param str[] [symbols]: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.channel]: the channel to subscribe to, tickers by default. Can be tickers, sprd-tickers, index-tickers, block-tickers
        :returns dict: a `ticker structure <https://docs.ccxt.com/?id=ticker-structure>`
        NFr)   rG   rH   r   unsubscribe:ticker:rm   r   rq   r[   )	rs   rt   r   ru   rv   rx   rw   rj   rz   )rW   rk   r{   rG   r   r|   r}   r   r~   r   r   ri   s               rY   r   zokx.un_watch_tickers  s@      !!!!!!!!!%%gtU;;77PY[deeq#g,,'' 	! 	!AQZF  !6!?@@@~~f--H"" E MM%    
 
 ll7H--((mWmTTTTTTTTTrZ   c                    |                      ||           |                     |di           }|                     |d          }|                     |d d          }|d         }|                     |d          }|                     |dg           }i }	t	          dt          |                    D ],}
|                     ||
                   }|| j        |<   ||	|<   -|dz   |z   }|                    |	|           d S )	Nr   rn   -r   rG   r   r   ro   )	handle_bid_askr   r   safe_marketru   rv   parse_tickerrH   r   )rW   r   r   r   r~   r   r   rG   r   r   r}   r   r   s                rY   handle_tickerzokx.handle_ticker  s   4 	FG,,,oogub11##C22!!(D#66!""3	22w33
q#d))$$ 	( 	(A&&tAw//F#)DL !'Jvnv-z;/////rZ   c                   K   |                                   d{V  |                     |dd          }d}|                     |ddd          \  }}|                     |d          }g }g }t	          dt          |                    D ]i}|                     ||                   }||d}	|                    |                     |	|                     |                    d	||         z              jd
|d}
| 	                    |||
|           d{V }| j
        ri }|||d         <   |S |                     | j        d|          S )a  

        https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-tickers-channel

        watches best bid & ask for symbols
        :param str[] symbols: 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>`
        NFr*   rG   rH   r[   r   rm   bidask::rp   rq   r   )rs   rt   r   rj   ru   rv   rw   rx   ry   rz   r   r   bidsasks)rW   rk   r{   rG   ri   r|   rr   r}   r~   r   r   r   rH   s                rY   watch_bids_askszokx.watch_bids_asks>  s      !!!!!!!!!%%gtU;;77QZ\effll7H--q#g,,'' 	: 	:A~~gaj11H"" C KKC00111  gaj!89999
 
  ..sM7MZZZZZZZZ
? 	G,6GJx()N##DM8WEEErZ   c                     |                      |dg           }|                     |di           }|                     |          }|d         }|| j        |<   d|z   }|                    ||           d S )Nr   r   r   r   )r   	safe_dictparse_ws_bid_askr   r   )rW   r   r   r   r   parsedTickerr   r   s           rY   r   zokx.handle_bid_askb  s{    4 ~~gvr22a,,,,V44h' ,f 6)|[11111rZ   c                    |                      |d          }|                     ||          }|                      |d          }|                     |d          }|                     |||                     |          |                      |d          |                      |d          |                      |d          |                      |d          |d|          S )	Nrn   r   tsaskPxaskSzbidPxbidSz)r   r   datetimeask	askVolumebid	bidVolumeinfo)r   r   r   safe_tickeriso8601)rW   r   r   r~   r   r   s         rY   r   zokx.parse_ws_bid_ask  s    ##FH55!!(F33!!&(33%%fd33	"Y//##FG44))&'::##FG44))&'::	!
 	!
 	 	 		rZ   c                   K   |                                   d{V  |                     |ddd          }d}g }|Dt          dt          |                    D ]%}||         }|                    |dz   |z              &n|                    |           |                     |          }	d}
|                     d|	|          \  }
}d}|
dk    rd	}
n|
d
k    rd}
|
                                }d||dgd}|                     |d          }| 	                    ||||           d{V }| j
        r|S |                     | j        |||d          S )a,  
        watch the public liquidations of a trading pair

        https://www.okx.com/docs-v5/en/#public-data-websocket-liquidation-orders-channel

        :param str symbols:
        :param int [since]: the earliest time in ms to fetch liquidations for
        :param int [limit]: the maximum number of liquidation structures to retrieve
        :param dict [params]: exchange specific parameters for the okx api endpoint
        :returns dict: an array of `liquidation structures <https://github.com/ccxt/ccxt/wiki/Manual#liquidation-structure>`
        NTliquidationsr   ro   watchliquidationsForSymbolsliquidation-ordersrF   SWAPfuturefuturesrp   rG   instTyperq   r[   )rs   rt   ru   rv   rx   get_market_from_symbolshandle_market_type_and_paramsupperrj   rz   r   filter_by_symbols_since_limitr   )rW   rk   r   r   r{   r   r|   r}   r   r   rI   rG   uppercaseTyper   ri   newLiquidationss                   rY   watch_liquidations_for_symbolsz"okx.watch_liquidations_for_symbols  s      !!!!!!!!!%%gtT4@@$1c'll++ B B $$[4%7&%@AAAAB   -----g6699:WY_aghhf&6>>DDXD

  ' - 
 
 ll7H-- $ 3 3CQ^ _ _______? 	#""11$2CWeUZ\`aaarZ   c                    |                      |dg           }t          dt          |                    D ]}||         }|                     |          }|                     |d          }| j        0|                     | j        dd          }t          |          | _        | j        }	|		                    |           |
                    |gd           |
                    |gd|z              d S )Nr   r   r   liquidationsLimitr   r   zliquidations::)r   ru   rv   parse_ws_liquidationr   r   r   rR   r   rx   r   )
rW   r   r   rawLiquidationsr}   rawLiquidationliquidationr   r   caches
             rY   handle_liquidationzokx.handle_liquidation  s    8 ..&"==q#o..// 
	E 
	EA,Q/N33NCCK%%k8<<F ())$,8KTRR$.u$5$5!%ELL%%%NNK=.999NNK=*:V*CDDDD
	E 
	ErZ   c                   K   |                                   d{V  |                     |ddd          }|                     |ddg          }|                     d|rdndi           d{V  |                     |ddd          }d	}g }|Dt          d
t          |                    D ]%}||         }	|                    |dz   |	z              &n|                    |           d}
dd|
igd}|                     |
d          }| 	                    ||| 
                    ||          |           d{V }| j        r|S |                     | j        |||d          S )a5  
        watch the private liquidations of a trading pair

        https://www.okx.com/docs-v5/en/#trading-account-websocket-balance-and-position-channel

        :param str[] symbols:
        :param int [since]: the earliest time in ms to fetch liquidations for
        :param int [limit]: the maximum number of liquidation structures to retrieve
        :param dict [params]: exchange specific parameters for the okx api endpoint
        :returns dict: an array of `liquidation structures <https://github.com/ccxt/ccxt/wiki/Manual#liquidation-structure>`
        NstoptriggerFrd   r_   privateTmyLiquidationsr   ro   balance_and_positionrp   rG   rq   )rs   safe_value_2omitr   rt   ru   rv   rx   rj   rz   rT   r   r   r   )rW   rk   r   r   r{   	isTriggerr   r|   r}   r   rG   r   ri   r   s                 rY   !watch_my_liquidations_for_symbolsz%okx.watch_my_liquidations_for_symbols  s      !!!!!!!!!%%ffiGG	6FI#677+Q::	 RSSSSSSSSS%%gtT4@@&1c'll++ B B $$[4%7&%@AAAAB   ---( w
 
 ll7I.. $ 3 3CHXHXY`bhHiHikx y yyyyyyy? 	#""11$2CWeUZ\`aaarZ   c                     |                      |dg           }t          dt          |                    D ]}||         }|                     |d          }|dk    r d S |                     |          }|                     |d          }| j        0|                     | j        dd          }	t          |	          | _        | j        }
|
	                    |           |
                    |gd           |
                    |gd	|z              d S )
Nr   r   	eventTyper  r   r  r   r  zmyLiquidations::)r   ru   rv   r   parse_ws_my_liquidationr   r   rR   r   rx   r   )rW   r   r   r  r}   r  r  r  r   r   r  s              rY   handle_my_liquidationzokx.handle_my_liquidation  s%   F ..&"==q#o..// 	G 	GA,Q/N((EEIM))66~FFK%%k8<<F ())$,8KTRR$.u$5$5!%ELL%%%NNK=*:;;;NNK=*<v*EFFFF	G 	GrZ   c                    |                      |dg           }|                     |di           }|                     |d          }|                     ||          }|                     |d          }|                     ||                     ||          |                     |d          |                     |d          |                     |d          d d ||                     |          d	          S )	NposDatar   rn   uTImeposcontractSizeavgPx)	r   r   	contractsr  price	baseValue
quoteValuer   r   	r   r   r   r   r   safe_liquidationr   safe_numberr   )rW   r  r   r  firstPosDatar~   r   s          rY   r  zokx.parse_ws_my_liquidationF  s    : ..i<<~~gq"55##L(;;!!(F33%%lG<<	$$&&x88)),>> ,,V^DD%%k7;;"Y//
&
 
&
 
 
 
	rZ   c                    |                      |dg           }|                     |di           }|                     |d          }|                     ||          }|                     |d          }|                     ||                     ||          |                     |d          |                     |d          |                     |d          |                     |d          d d ||                     |          d	
          S )
Ndetailsr   rn   r   szr  bkPxside)
r   r   r  r  r  r)  r  r   r   r   r!  )rW   r  r   r&  liquidationDetailsr~   r   s          rY   r  zokx.parse_ws_liquidationt  s   * ..i<<!^^GQ;;##K::!!(F33%%&8$??	$$&&x88))*<dCC ,,V^DD%%&8&AA$$%7@@"Y//&
 &
   	rZ   1m	timeframec                 P  K   |                                   d{V  |                     |          }|                     | j        ||          }d|z   }|                     d||||           d{V }| j        r|                    ||          }|                     |||dd          S )aQ  
        watches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param int [since]: timestamp in ms of the earliest candle to fetch
        :param int [limit]: the maximum amount of candles to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        Nr`   r[   r   T)rs   r   r   
timeframesrp   r   r   r   )	rW   r   r,  r   r   r{   intervalnameohlcvs	            rY   watch_ohlcvzokx.watch_ohlcv  s       !!!!!!!!!V$$##DOY	JJ("nnXtT66JJJJJJJJ? 	2NN6511E))%q$GGGrZ   c                 x   K   |                                   d{V  |                     ||gg|           d{V S )a  
        watches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        N)rs   un_watch_ohlcv_for_symbols)rW   r   r,  r{   s       rY   un_watch_ohlcvzokx.un_watch_ohlcv  s\       !!!!!!!!!44vy6I5JFSSSSSSSSSrZ   symbolsAndTimeframesc                 0  K   t          |          }|dk    st          |d         t                    st          | j        dz             |                                  d{V  g }g }t          dt          |                    D ]}||         }	|	d         }
|	d         }|                     |
          }|                     | j	        ||          }d|z   }||d}|
                    |           |
                    d|z   dz   |
z              d	|d
}|                     dd          }|                     ||||           d{V \  }}}| j        r|                    ||          }|                     |||dd          }|                     |||          S )aj  
        watches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :param str[][] symbolsAndTimeframes: array of arrays containing unified symbols and timeframes to fetch OHLCV data for, example [['BTC/USDT', '1m'], ['LTC/USDT', '5m']]
        :param int [since]: timestamp in ms of the earliest candle to fetch
        :param int [limit]: the maximum amount of candles to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        r   u watchOHLCVForSymbols() requires a an array of symbols and timeframes, like  [['BTC/USDT', '1m'], ['LTC/USDT', '5m']]N   r`   rm   multi:r   rp   rq   r[   T)rv   
isinstancelistr   r   rs   ru   rw   r   r.  rx   rj   rz   r   r   r   create_ohlcv_object)rW   r6  r   r   r{   r   r   r|   r}   symbolAndTimeframesymtfr~   r/  rG   r   r   ri   r   r,  candlesfiltereds                         rY   watch_ohlcv_for_symbolszokx.watch_ohlcv_for_symbols  s      011AZ0DQ0G%N%N#DG  /f  %f  g  g  g!!!!!!!!!q#23344 	A 	AA!5a!8$Q'C#A&B~~c**H''R@@H)G"" E MM%     G!3c!9C!?@@@@
 
 ll8X..+/+>+>sMSZ\i+j+j%j%j%j%j%j%j"	7? 	4$$VU33E--gueQMM''	8DDDrZ   c                   K   t          |          }|dk    st          |d         t                    st          | j        dz             |                                  d{V  g }g }t          dt          |                    D ]}||         }|d         }|d         }	|                     |          }
|                     | j	        |	|	          }d|z   }||
d}|
                    |           |
                    d|z   dz   |z              d	|d
}|                     dd          }|                     ||||           d{V S )a  
        unWatches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :param str[][] symbolsAndTimeframes: array of arrays containing unified symbols and timeframes to fetch OHLCV data for, example [['BTC/USDT', '1m'], ['LTC/USDT', '5m']]
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        r   r8  Nr9  r`   rm   zunsubscribe:multi:r   r   rq   r[   )rv   r;  r<  r   r   rs   ru   rw   r   r.  rx   rj   rz   )rW   r6  r{   r   r   r|   r}   r>  r?  r@  r~   r/  rG   r   r   ri   s                   rY   r4  zokx.un_watch_ohlcv_for_symbols  s      011AZ0DQ0G%N%N#DG  /f  %f  g  g  g!!!!!!!!!q#23344 	M 	MA!5a!8$Q'C#A&B~~c**H''R@@H)G"" E MM%     !5!?#!E!KLLLL
 
 ll8X..((mWmTTTTTTTTTrZ   c                    |                      |di           }|                     |d          }|                      |dg           }|                     |d          }|                     |          }|d         }|                    dd          }	|                     |	          }
t          dt          |                    D ]}|                     ||         |          }|                      | j        |i           | j        |<   |                      | j        |         |
          }|;| 	                    | j
        d	d
          }t          |          }|| j        |         |
<   |                    |           |dz   |d         z   }|                    ||           d|z   dz   |z   }|                    ||
|g|           d S )Nr   rG   r   rn   r   r`   r^   r   
OHLCVLimitr   r   r   r:  )r   r   r   replacefind_timeframeru   rv   parse_ohlcvohlcvsr   rR   r   rx   r   )rW   r   r   r   rG   r   r~   r   r   r/  r,  r}   parsedr   r   r   messageHashForMultis                    rY   handle_ohlcvzokx.handle_ohlcv  s   " oogub11""3	22w33##C22!!(++!??8R00''11	q#d))$$ 	M 	MA%%d1gv66F"&//$+vr"J"JDK__T[%8)DDF~))$,dKK.u5517F#I.MM&!!!!C-&,6KNN6;/// #+W"4s":V"CNNFIv68KLLLL	M 	MrZ   c                 B   K   |                      |g||           d{V S )a  

        https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-order-book-channel

        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :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
        :param str [params.depth]: okx order book depth, can be books, books5, books-l2-tbt, books50-l2-tbt, bbo-tbt
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/?id=order-book-structure>` indexed by market symbols
        N)watch_order_book_for_symbols)rW   r   r   r{   s       rY   watch_order_bookzokx.watch_order_book,  s5      F 66xOOOOOOOOOrZ   c                 $  K   |                                   d{V  |                     |          }d}|                     |ddd          \  }}|)|dk    rd}n |dk    r	|dk    rd}n|d	k    rd
}n|dk    rd}|dk    s|d
k    rI|                     d          st	          | j        dz             |                     ddi           d{V  g }g }t          dt          |                    D ]T}||         }|	                    |dz   |z              | 
                    |          }	||	d}
|	                    |
           Ud|d}|                     |d          }|                     ||||           d{V }|                                S )a  

        https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-order-book-channel

        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :param str[] symbols: unified array of symbols
        :param int [limit]: 1,5, 400, 50(l2-tbt, vip4+) or 40000(vip5+) the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.depth]: okx order book depth, can be books, books5, books-l2-tbt, books50-l2-tbt, bbo-tbt
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/?id=order-book-structure>` indexed by market symbols
        Nr+   rE   rC   r9  bbo-tbt   books52   books50-l2-tbt  books-l2-tbtFz watchOrderBook/watchOrderBookForSymbols requires authentication for self depth. Add credentials or change the depth option to books or books5rd   r[   r   r   rm   rp   rq   )rs   rt   r   check_required_credentialsr   r   r   ru   rv   rx   rw   rj   rz   r   )rW   rk   r   r{   rE   r   r|   r}   r   r~   r   r   ri   	orderbooks                 rY   rO  z okx.watch_order_book_for_symbolsQ  s      !!!!!!!!!%%g..55f>NPWY`aavzz!uzz "(#^##2B)B)B22599 F)$'  5E  +E  F  F  F##Xx$8999999999q#g,,'' 	! 	!AQZF  v!5666~~f--H " E MM%    
 
 ll5(++--c='=YYYYYYYY	   rZ   c                   K   |                                   d{V  |                     |dd          }d}|                     |ddd          \  }}|                     |d          }|)|dk    rd}n |dk    r	|d	k    rd
}n|dk    rd}n|dk    rd}g }g }g }t	          dt          |                    D ]l}||         }	|                    |dz   |	z              |                    d|	z              |                     |	          }
||
d}|                    |           md|d}|                     |d          }| 	                    ||||           d{V S )a  

        https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-order-book-channel

        unWatches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :param str[] symbols: unified array of symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.limit]: the maximum amount of order book entries to return
        :param str [params.depth]: okx order book depth, can be books, books5, books-l2-tbt, books50-l2-tbt, bbo-tbt
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/?id=order-book-structure>` indexed by market symbols
        NFr+   rE   rC   r   r9  rR  rS  rT  rU  rV  rW  r   r   unsubscribe:orderbook:rm   r   rq   r[   )
rs   rt   r   r   ru   rv   rx   rw   rj   rz   )rW   rk   r{   rE   r   r   subMessageHashesr|   r}   r   r~   r   r   ri   s                 rY   un_watch_order_book_for_symbolsz#okx.un_watch_order_book_for_symbols  s      !!!!!!!!!%%gtU;;55f>NPWY`aav!!&'22zz!uzz "(#q#g,,'' 		! 		!AQZF##ECK&$8999  !9F!BCCC~~f--H " E MM%    
 
 ll5(++((mWmTTTTTTTTTrZ   c                 @   K   |                      |g|           d{V S )a  

        https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-order-book-channel

        unWatches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :param str symbol: unified array of symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.limit]: the maximum amount of order book entries to return
        :param str [params.depth]: okx order book depth, can be books, books5, books-l2-tbt, books50-l2-tbt, bbo-tbt
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/?id=order-book-structure>` indexed by market symbols
        N)r^  r   s      rY   un_watch_order_bookzokx.un_watch_order_book  s2       996(FKKKKKKKKKrZ   c                     |                      |d          }|                      |d          }|                    ||           d S )Nr   r9  )
safe_floatstore)rW   booksidedeltar  amounts        rY   handle_deltazokx.handle_delta  sD     q))**uf%%%%%rZ   c                 ~    t          dt          |                    D ]}|                     |||                    d S )Nr   )ru   rv   rg  )rW   rd  deltasr}   s       rY   handle_deltaszokx.handle_deltas  sH    q#f++&& 	3 	3Ahq	2222	3 	3rZ   c                    |                      |dg           }|                      |dg           }|d         }|d         }	|                     ||           |                     |	|           |                     |d          }
|                     |
|          }|                     ddd          }|                     |d          }|r|                     |d          }|d	         }t          |          }t          |	          }g }t          d
d          D ]}||k     rh|                    | 	                    |	|         d
                              |                    | 	                    |	|         d                              ||k     rh|                    | 	                    ||         d
                              |                    | 	                    ||         d                              d
                    |          }|                     |d          }|                     |d          }d }|dk    r||k    rt          | j        dz             }||k    r-t          | j        dz   |                     |          z             }|(|j        |= || j        |= |                    ||           |                     |d          }||d	<   ||d<   |                     |          |d<   |S )Nasksbidsrn   r+   rD   TseqId	prevSeqIdnoncer      r9  r   ra   z& watchOrderBook received invalid nonce r   r   r   )r   rj  r   r   handle_optionr   rv   ru   rx   number_to_stringjoincrc32r   r   r    orderbook_checksum_messagesubscriptions
orderbooksrejectr   )rW   r   r   rZ  r   r   rl  rm  
storedAsks
storedBidsr~   r   rD   rn  ro  rp  
asksLength
bidsLengthpayloadArrayr}   payloadresponseChecksumlocalChecksumerrorr   s                            rY   handle_order_book_messagezokx.handle_order_book_message  s   ( w33w33v&
v&
:t,,,:t,,,##GX66!!(F33%%&6
DII!!'733 	2))';??Ig&EZJZJL1b\\ Q Qz>> ''(=(=jmA>N(O(OPPP ''(=(=jmA>N(O(OPPPz>> ''(=(=jmA>N(O(OPPP ''(=(=jmA>N(O(OPPPhh|,,G#00*EE JJw55MEB5I#5#5$TW/W%WXX=00%dgmd6U6UV\6]6]&]^^ (5%/e[111%%gt44	"	'!*	+ $Y 7 7	*rZ   c           
         |                      |di           }|                     |d          }|                     |d          }|                     |dg           }|                     |d          }|                     |          }|d         }	ddd	dd
d}
|                     |
|          }|dz   |	z   }|dk    r}t          dt          |                    D ]]}||         }|                     i |          }|| j        |	<   |	|d<   | 	                    ||||           |
                    ||           ^n8|dk    rn|	| j        v rd| j        |	         }t          dt          |                    D ]9}||         }| 	                    |||||           |
                    ||           :n|dk    s|dk    r|	| j        vr|                     i |          | j        |	<   | j        |	         }t          dt          |                    D ]f}||         }|                     |d          }|                     ||	|dddd          }|                    |           |
                    ||           g|S )Nr   rG   actionr   rn   r   r9  rW  rS  rU  )rR  rC   rT  rX  rV  r   snapshotr   updaterT  rR  r   rm  rl  )r   r   r   r   r   ru   rv   
order_bookry  r  r   parse_order_bookreset)rW   r   r   r   rG   r  r   r~   r   r   depthsr   r   r}   r  rZ  r   r  s                     rY   handle_order_bookzokx.handle_order_book  s   l nnWeR00""3	22!!'844~~gvr22##C22!!(++! 
 
 !!&'22mf,Z1c$ii(( 7 7a OOB66	*3'&,	(#..vvy+VVVy+66667 x(( OF3	q#d)),, ; ;A!!WF22669k[abbbNN9k::::!!w)';';do--*.//"e*D*D'/I1c$ii(( 7 7a --fd;;	00FTZ\]_`aa)))y+6666rZ   c                   K   |                                   |                     |dd          }|                     |dg          }|                     d|          }d}|                     |          }|                    |          }|                     |j        |          }|t          | 	                                          }d}	d}
||	z   |
z   }| 
                    |                     |          |                     | j                  t          j        d          }d}|| j        | j        ||d	gd
}d|v r|d         |d<   |                     ||||           | d {V S )Nrd   r  usersauthenticatedGETz/users/self/verifybase64login)apiKey
passphraser   signrq   )rY  r   r  rj   r   reusableFuturer   rx  strsecondshmacencodesecrethashlibsha256r  passwordr   )rW   r{   rd   ri   r   r   r   r  r   methodpathauth	signature	operationr   s                  rY   r   zokx.authenticate  sy     '')))!!&(I>>6H:..ll7F++%S!!&&{33(<kJJ DLLNN++IF'Dv%,D		$++d"3"3T[[5M5Mw~_ghhII #'+&*m%. )	 
 
G 6!!$*8$4!JJsK+>>>||||||rZ   c                    K   |                                   d{V  |                                  d{V  |                     dddd|           d{V S )ao  

        https://www.okx.com/docs-v5/en/#trading-account-websocket-account-channel

        watch balance and get the amount of funds available for trading or funds locked in orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/?id=balance-structure>`
        Nr  account)rs   r   rp   )rW   r{   s     rY   watch_balancezokx.watch_balance  s|       !!!!!!!!!!!!!!!!!!^^Iy)T6RRRRRRRRRrZ   c                 2    |                      ||           d S N)r  rW   r   r   s      rY   handle_balance_and_positionzokx.handle_balance_and_position  s    ""6733333rZ   c                 *   |                      |di           }|                     |d          }|                     |          }|                     | j        |          }|                     |          | _        |                    | j        |           d S )Nr   rG   )r   r   parseTradingBalancerT   balancesafe_balancer   )rW   r   r   r   rG   r  
newBalances          rY   handle_balancezokx.handle_balance  s    t oogub11""3	22**733%%dlG<<
((44t|W-----rZ   c                    |                      |di           }|                     |d          }|                     |d          }|                     |dd          dk    }|                     |||                     |          |                     |d          |                     |d          |                     |d	          |                     |d
          |rdnd|                     |d          |                     |d          |                     |d          |                     |d          |                     |d          |                     |          dd|          S )Nr   fillTime
fillFeeCcyexecTyper^   Tr   tradeIdr   rI   takermakerr)  fillPxfillSzcostfillFee)r  currency)r   r   r   r   r   orderrI   takerOrMakerr)  r  rf  r  fee)r   r   r   
safe_trader   r#  safe_currency_code)rW   r  r   r   r   feeMarketIdisTakers          rY   order_to_tradezokx.order_to_trade  si   ufb11%%dJ77	&&t\::""4R88C?"Y//&&uh77""433%%eT22$$UF33(/=GGg$$UF33%%dH55&&tX66$$UF33((y99 33K@@  
  
" #  	rZ   c           
        K   d}|                      |ddd          \  }}|                     |ddd          }|                     |ddg          }|                                  d{V  |                     d|rd	nd
i           d{V  |rdnd}|dz   }d}	|-|                     |          }	|	d         }|	d         }|dz   |z   }|dk    rd}|                                }
d}|                     d|          \  }}|
dk    r|d}
d|
i}|                     d
||d| 	                    ||                     d{V }| j
        r|                    ||          }|                     ||||d          S )a  
        watches information on multiple trades made by the user

        https://www.okx.com/docs-v5/en/#order-book-trading-trade-ws-order-channel

        :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 bool [params.trigger]: True if fetching trigger or conditional trades
        :param str [params.type]: 'spot', 'swap', 'future', 'option', 'ANY', 'SPOT', 'MARGIN', 'SWAP', 'FUTURES' or 'OPTION'
        :param str [params.marginMode]: 'cross' or 'isolated', for automatically setting the type to spot margin
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/?id=trade-structure>`
        Nr8   rI   rJ   r  r
  Frd   r_   r  rb   orders
::myTradesr   ro   r   r   SPOTMARGINr   T)r   safe_bool_2r  rs   r   r   r   handle_margin_mode_and_paramsrp   ry   r   r   filter_by_symbol_since_limit)rW   r   r   r   r{   rI   r  rG   r   r   r   
marginModer   r  s                 rY   watch_my_tradeszokx.watch_my_trades7  s       44V_fV[\\f$$VYFF	6Iv#677!!!!!!!!!+Q::	 RSSSSSSSSS#,:--(,[[((FH%F&>D%,v5K8D


!??QWXX
FF""% (
 ~~igtT[[Y`bhMiMijjjjjjjj? 	3OOFE22E00tTTTrZ   c           	        K   |                                   d{V  |                     |           d{V  |                     |          }ddi}d}d}|Vddd}|                     ||          g}	d|	d}
|                     |d          }|                     |||
|           d{V }n2|                     d|||                     ||                     d{V }| j        r|S |                     | j	        |||d	          S )
a  

        https://www.okx.com/docs-v5/en/#trading-account-websocket-positions-channel

        watch all open positions
        :param str[]|None symbols: list of unified market symbols
 @param since
 @param limit
        :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>`
        Nr   rJ   	positionsr   rp   rq   r  T)
rs   r   rt   ry   rj   r   r   r   r   r  )rW   rk   r   r   r{   r   rG   newPositionsr   rr   nonSymbolRequestri   s               rY   watch_positionszokx.watch_positionse  sn      !!!!!!!!!'''''''''%%g..
 ?&! C KKV,,-D!& & ,,w	22C!%C:JG!T!TTTTTTTLL!%!8!8GWVZVaVabikqVrVr!s!sssssssL? 	 11$.'5RWY]^^^rZ   c                    |                      |di           }|                     |d          }|                     |d d          }|d         }|                     |dd          }|                      |dg           }| j        t	                      | _        | j        }	g }
t          dt          |                    D ]}||         }|                     |          }|d	         dk    rU|d
         dk    rId|d<   |                     |          }d|d<   |		                    |           |
	                    |           |
	                    |           |		                    |           |}||dz   |z   }|
                    |
|           d S )Nr   rn   r   r   rG   r^   r   r   r  posSidenetlongr)  shortro   )r   r   r   r  r   ru   rv   parse_positionclonerx   r   )rW   r   r   r   r~   r   r   rG   r   r  r  r}   rawPositionpositionshortPositionr   s                   rY   handle_positionszokx.handle_positions  s   F oogub11##C22!!(D#66!""3	266w33>!577DNq#d))$$ 
	# 
	#Aq'K**;77H$))k).D.M.M#)  $

8 4 4(/f%]+++##M222)))LL""""!D.61K|[11111rZ   c           
        K   d}|                      |ddd          \  }}|                     |ddd          }|                     |ddg          }|                                  d{V  |                     d|rd	nd
i           d{V  d}|%|                     |          }|d         }|d         }|dk    rd}|                                }d}	|                     d|          \  }	}|dk    r|	d}d|i}
|rdnd}|                     d
|||| 	                    |
|                     d{V }| j
        r|                    ||          }|                     ||||d          S )a  
        watches information on multiple orders made by the user

        https://www.okx.com/docs-v5/en/#order-book-trading-trade-ws-order-channel

        :param str [symbol]: unified market symbol of the market the 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 bool [params.trigger]: True if fetching trigger or conditional orders
        :param str [params.type]: 'spot', 'swap', 'future', 'option', 'ANY', 'SPOT', 'MARGIN', 'SWAP', 'FUTURES' or 'OPTION'
        :param str [params.marginMode]: 'cross' or 'isolated', for automatically setting the type to spot margin
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        Nr7   rI   rJ   r
  r  Frd   r_   r  r   r   r   r  r  r   rb   r  T)r   r  r  rs   r   r   r   r  rp   ry   r   r   r  )rW   r   r   r   r{   rI   r  r   r   r  r   rG   r  s                rY   watch_orderszokx.watch_orders  s      44V]FTYZZf%%ffiGG	6FI#677!!!!!!!!!+Q::	 RSSSSSSSSS[[((FH%F&>D8D


!??vVV
FF""% (
 $-:--(~~i'64;;W^`fKgKghhhhhhhh? 	3OOFE22E00tTTTrZ   c                 t   |                      ||           |                     |di           }|                     |d          }|                     |dg           }t          |          }|dk    rE|                     | j        dd          }| j        (t          |          | _        t          |          | _        |dk    r| j        n| j        }g }	| 	                    |          }
t          dt          |
                    D ]W}|
|         }|                    |           |d         }|                     |          }|	                    |d	                    X|                    ||           t          dt          |	                    D ](}|d
z   |	|         z   }|                    ||           'd S d S )Nr   rG   r   r   ordersLimitr   rb   r   r   r   )handle_my_tradesr   r   rv   r   rR   r  r   triggerOrdersparse_ordersru   rx   r   r   )rW   r   r   r   rG   r  ordersLengthr   r   	marketIdsrK  r}   r  r   r   r   s                   rY   handle_orderszokx.handle_orders  s   n 	fg...oogub11""3	22&"556{{!%%dlM4HHE{"4U;;%;E%B%B",3},D,DT''4;FI&&v..F1c&kk** / /q	e$$$xV,,  ....NN67+++1c)nn-- 4 4%mil:v{3333# 4 4rZ   c                 
   |                      |di           }|                     |d          }|                      |dg           }g }t          dt          |                    D ]^}||         }|                     |dd          }	t          |	          dk    r*|                     |          }
|                    |
           _t          |          }|dk    rd S | j        0|                     | j        dd          }t          |          | _        | j        }i }t          dt          |                    D ]A}||         }| 
                    |          }|                    |           |d	         }d
||<   B|dz   }|                    | j        |           t          |                                          }t          dt          |                    D ]+}|dz   ||         z   }|                    | j        |           ,d S )Nr   rG   r   r   r  r^   r   r   r   Tr  ro   )r   r   ru   rv   parse_orderrx   myTradesr   rR   r   r  r   r<  keys)rW   r   r   r   rG   	rawOrdersfilteredOrdersr}   rawOrderr  r  tradesLengthr   r  rk   rawTrader   r   r   tradeSymbolssymbolMessageHashs                        rY   r  zokx.handle_my_tradesc  s   n oogub11""3	22OOGVR88	q#i..)) 	- 	-A |H&&xB??G7||a((22%%e,,,>**1F= %%dlM4HHE2599DM=q#n--.. 	# 	#A%a(H''11EOOE"""8_F"GFOO,t}k222GLLNN++q#l++,, 	= 	=A +d 2\!_ DNN4=*;<<<<	= 	=rZ   c                     t          |                                           }|                     d          }t          |          }||z   S )N   )r  millisecondsrand_number)rW   r   randomNumber
randomParts       rY   
request_idzokx.request_id  sE    ""$$%%''**&&
JrZ   rI   r)  rf  r  c                   K   |                                   d{V  |                                  d{V  |                     dd          }|                                 }d}	|                     |ddd          \  }	}|                     ||||||          }
|                     |          }|                     |d          }||
d= ||
d<   |                     |
d          }|d	k    s|d
k    s|dk    s|dk    s|dk    s|dk    rt          | j
        dz             |	dk    r|	dk    rt          | j
        dz             ||	|
gd}|                     ||||           d{V S )a  

        https://www.okx.com/docs-v5/en/#websocket-api-trade-place-order

        create a trade order
        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of currency you want to trade in units of base currency
        :param float|None [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean params['test']: test order, default False
        :returns dict: an `order structure <https://docs.ccxt.com/?id=order-structure>`
        Nr  r<   rK   rL   
instIdCodern   ordTyper  conditionalocomove_order_stopicebergtwapzw createOrderWs() does not support algo trading. self.options["createOrderWs"]["op"] must be either order or batch-orderr  z createOrderWs() does not support algo trading. self.options["createOrderWs"]["op"] must be either order or privatePostTradeOrder or privatePostTradeOrderAlgor   rK   rr   )rs   r   rj   r  r   create_order_requestr   r   r   r   r   r   )rW   r   rI   r)  rf  r  r{   ri   r   rK   rr   r   r  r  r   s                  rY   create_order_wszokx.create_order_ws  s      !!!!!!!!!!!!!!!!!!ll9i00oo''226?DR`aa
F((tVUFSSV$$&&v|<<
!X!+D""433y  g&>&>DEMMW[_pWpWpvz  H  wH  wH  NR  V\  N\  N\TW  (a  a  b  b  b'MMn 4 4TW  (H  H  I  I  IF
 

 ZZ[';GGGGGGGGGrZ   c                    |                      |d          }|                     |dg           }|                     |dd          }|                     |          rM|                      |d          }|                     |          }|                     dd|j        |i ||i i 	  	         |                     |d d d           }|                     |di           }|	                    ||           d S )	Nr   r   sCode0rK   r9  r^   r   )
r   r   	filter_byis_emptyjsonhandle_errorsri   r  r   r   )	rW   r   r   r   rr   r  	stringMsgr  r   s	            rY   handle_place_orderszokx.handle_place_orders  s    & &&w55w33~~dGS11== 	Z%%gt44F		'**Iq"fj&"iRTVXYYY""4tT::vq"--uk*****rZ   r   c           	        K   |                                   d{V  |                                  d{V  |                     dd          }|                                 }	d}
|                     |ddd          \  }
}|                     |||||||          }|                     |          }|                     |d          }||d= ||d<   |	|
|gd}|                     ||	| 	                    ||          |	           d{V S )	a4  
        edit a trade order

        https://www.okx.com/docs-v5/en/#order-book-trading-trade-ws-amend-order
        https://www.okx.com/docs-v5/en/#order-book-trading-trade-ws-amend-multiple-orders

        :param str id: order id
        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of the currency you want to trade in units of the base currency
        :param float|None [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/?id=order-structure>`
        Nr  r=   rK   rM   r  rn   r  )
rs   r   rj   r  r   edit_order_requestr   r   r   ry   )rW   r   r   rI   r)  rf  r  r{   ri   r   rK   rr   r   r  r   s                  rY   edit_order_wszokx.edit_order_ws  sC       !!!!!!!!!!!!!!!!!!ll9i00oo''226=$P]^^
F&&r64vufUUV$$&&v|<<
!X!+DF
 

 ZZ[$++gv2N2NP[\\\\\\\\\rZ   c                 <  K   |t          | j        dz             |                                  d{V  |                                  d{V  |                     dd          }|                                 }|                     |dd          }|                     |ddg          }|                     |          }| 	                    |d          }d|i}	|||	d<   n||	d<   |d| 
                    |	|          gd	}
|                     |||
|           d{V S )
a  

        https://okx-docs.github.io/apidocs/websocket_api/en/#cancel-order-trade

        cancel multiple orders
        :param str id: order id
        :param str symbol: unified market symbol, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.clOrdId]: client order id
        :returns dict: an list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        Nz+ cancelOrderWs() requires a symbol argumentr  clOrdIdclientOrderIdr  ordIdcancel-orderr  )r   r   rs   r   rj   r  safe_string_2r  r   r   ry   r   )rW   r   r   r{   ri   r   r  r   r  r   r   s              rY   cancel_order_wszokx.cancel_order_ws*  s\      >TW'TTUUU!!!!!!!!!!!!!!!!!!ll9i00oo''**69oNN6OY#?@@V$$&&v|<<
*
 $*C	NNCL [[f--.
 

 ZZ[';GGGGGGGGGrZ   idsc                   K   t          |          }|dk    rt          | j        dz             |t          | j        dz             |                                  d{V  |                                  d{V  |                     dd          }|                                 }g }|                     |          }|                     |d          }	d|	i}
t          d|          D ]5}| 
                    |
d||         i          }|                    |           6|d	|d
}|                     |||                     ||          |           d{V S )a  

        https://www.okx.com/docs-v5/en/#order-book-trading-trade-ws-mass-cancel-order

        cancel multiple orders
        :param str[] ids: order ids
        :param str symbol: unified market symbol, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an list of `order structures <https://docs.ccxt.com/?id=order-structure>`
           z0 cancelOrdersWs() accepts up to 20 ids at a timeNz, cancelOrdersWs() requires a symbol argumentr  r  r   r  zbatch-cancel-ordersr  )rv   r   r   rs   r   rj   r  r   r   ru   ry   rx   r   rT   )rW   r  r   r{   	idsLengthri   r   rr   r   r  
instParamsr}   r   r   s                 rY   cancel_orders_wszokx.cancel_orders_wsN  s       HH	r>>TW'YYZZZ>TW'UUVVV!!!!!!!!!!!!!!!!!!ll9i00oo''V$$&&v|<<
*

 q)$$ 	 	AJQ1  C KK'
 

 ZZ[$2B2B7F2S2SU`aaaaaaaaarZ   c                   K   |t          | j        dz             |                                  d{V  |                                  d{V  |                     |          }|d         dk    rt          | j        dz             |                     dd          }|                                 }|d|                     d|d	         d
|          gd}|                     ||||           d{V S )a  

        https://docs.okx.com/websockets/#message-cancelAll

        cancel all open orders of a type. Only applicable to Option in Portfolio Margin mode, and MMP privilege is required.
        :param str symbol: unified market symbol, only orders in the market of self symbol are cancelled when symbol is not None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        Nz/ cancelAllOrdersWs() requires a symbol argumentrI   optionzh cancelAllOrdersWs is only applicable to Option in Portfolio Margin mode, and MMP privilege is required.r  mass-cancelOPTIONr   )r   
instFamilyr  )	r   r   rs   r   r   rj   r  ry   r   )rW   r   r{   r   ri   r   r   s          rY   cancel_all_orders_wszokx.cancel_all_orders_wst  s?      >TW'XXYYY!!!!!!!!!!!!!!!!!!V$$&>X%%TW  (R  R  S  S  Sll9i00oo''[[$$Tl" "   
 
 ZZ[';GGGGGGGGGrZ   c                     |                      |d          }|                     |dg           }|                    ||           d S )Nr   r   )r   r   r   )rW   r   r   r   r   s        rY   handle_cancel_all_orderszokx.handle_cancel_all_orders  sH     &&w55w33t[)))))rZ   c                     |S r   r  s      rY   handle_subscription_statuszokx.handle_subscription_status  s	     rZ   c                 f    |                      |j        d          }|                    d           d S )Nr  T)r   r   r   )rW   r   r   r   s       rY   handle_authenticatezokx.handle_authenticate  s1     AAtrZ   c                     dS )NrN   r*  )rW   r   s     rY   rN   zokx.ping  s	     vrZ   c                 8    |                                  |_        |S r  )r  lastPongr  s      rY   handle_pongzokx.handle_pong  s    ++--rZ   c                 v   |                      |d          }	 |rL|dk    rE| j        dz   |                     |          z   }|dk    r"|                     | j        d         ||           |                     |d          }|#|                     | j        d         ||           n|                     |dg           }t          d	t          |                    D ]~}||         }|                      |d
          }|"|                     | j        d         ||           |                     |d          }|"|                     | j        d         ||           t          |          n# t          $ r}	|                      |d          }
|
n|                      |d          }|V|                    d          rA|                    dd          }|                     |          }|                      |d          }
|
|                    |	|
           Y d }	~	dS |                    |	           Y d }	~	dS d }	~	ww xY wdS )Ncoder
  rr  1exactmsgbroadr   r   r	  sMsgr   zIllegal request: {zIllegal request: r^   FT)r   r   r  throw_exactly_matched_exception
exceptionsr   throw_broadly_matched_exceptionr   ru   rv   r   	Exception
startswithrG  
parse_jsonrz  )rW   r   r   	errorCodefeedbackmessageStringr   r}   der   r6  stringifiedJson
parsedJsons                 rY   handle_error_messagezokx.handle_error_message  sh    $$Wf55	"	 .Y#--7S=499W+=+==##889QS\^fggg $ ? ? ,889QS`bjkkkk>>'62>>D"1c$ii00 t t G$($4$4Q$@$@	$0 @@QXAY[dfnooo(,6(B(B(4 @@QXAY[hjrsss#H--- 	 	 	 !!'400Bz&&w66?s~~6J'K'K?&)kk2Er&J&JO!%!A!AJ))*d;;B~a$$$uuuuuMM!55555	  ts   EE( (
H62BH1H11H6c           
         |                      ||          sd S |dk    r|                     ||           d S |                     |dd          }|a| j        | j        | j        | j        | j        | j        | j        | j        | j        d	}|                     ||          }| |||           d S d S |                     |di           }| 	                    |d          }i d| j
        d| j
        d	| j
        d
| j
        d| j
        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        | j        | j        d}|                     ||          }|3|                    d          dk    r|                     ||           d S d S  |||           d S )NpongeventrK   )	r  rp   r   r  rL   rM   zbatch-amend-ordersr  r#  r   rG   rR  rC   rT  rV  rX  rH   r   r  zindex-tickerszsprd-tickerszblock-tickersr   r   r  r   r  rb   )r   r  r`   r   )rF  r1  r  r-  r+  handle_unsubscriptionr  r(  r   r   r  r   r  r   r  r   r  r  r  rc   rM  )rW   r   r   rI  methodsr  r   rG   s           rY   handle_messagezokx.handle_message  s   ((99 	FP fVW---F ""7GT:: 1!<#91 $ 8#7&*&> $ 8#< G __We44F!vw''''' "! //'5"55C&&sI66G41/ $0 !$"8	
  6 4- d0 T2  !3  2  !3 $, d0 4.  8" $,#$ t1%& '+&=(,(H)  G, __Wg66F~<<))Q..%%fg66666 /. vw'''''rZ   c                 t    |dz   |z   }d|z   }|                      |||           || j        v r
| j        |= d S d S )Nr   r   )clean_unsubscriptionr   rW   r   r   rG   subMessageHashr   s         rY   handle_un_subscription_tradesz!okx.handle_un_subscription_tradesH	  sW     3/$~5!!&.+FFFT[  F### ! rZ   c                 t    |dz   |z   }d|z   }|                      |||           || j        v r
| j        |= d S d S )Nr   r\  )rN  ry  rO  s         rY    handle_unsubscription_order_bookz$okx.handle_unsubscription_order_bookO	  sW     3/.7!!&.+FFFT_$$''' %$rZ   c                     |                     dd          }|                     |          }d|z   dz   |z   }d|z   }|                     |||           || j        |         v r| j        |         |= d S d S )Nr`   r^   r:  r   r   )rG  rH  rN  rJ  )rW   r   r   rG   r@  r,  rP  r   s           rY   handle_unsubscription_ohlcvzokx.handle_unsubscription_ohlcvV	  s    __Xr**''++	!G+c1F:$~5!!&.+FFFF+++F#I... ,+rZ   c                 t    |dz   |z   }d|z   }|                      |||           || j        v r
| j        |= d S d S )Nro   r   )rN  rH   rO  s         rY   handle_unsubscription_tickerz okx.handle_unsubscription_ticker_	  sW     4&0+f4!!&.+FFFT\!!V$$$ "!rZ   c                 H   |                      |di           }|                     |dd          }|                     |d          }|                     |          }|dk    s|dk    r|                     |||           d S |                    d          s|                    d          r|                     |||           d S |                    d	          d
k    r|                     |||           d S |                    d          r|                     |||           d S d S )Nr   rG   r^   rn   r   r   bbobookrH   ra   r`   )	r   r   r   rQ  r=  rS  rc   rW  rU  )rW   r   r   r   rG   r~   r   s          rY   rJ  zokx.handle_unsubscriptionf	  sL    nnWeR00""3	266##C22!!(++h'\"9"9..vvwGGGGG&& 	F'*<*<V*D*D 	F11&&'JJJJJ\\)$$r))--ffgFFFFF)) 	F,,VVWEEEEE	F 	FrZ   )r[   r  )b__name__
__module____qualname__r   rV   r  rj   r   r   rp   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<  r2  r5  rC  r4  rM  r   rP  rO  r^  r`  rg  rj  r  r  r   r   r  r  r  r  r   r  r   r  r  r   r  r  r  r  r   r   floatr   r  r  r  r  r   r&  r(  r+  r-  rN   r1  r	   rF  rL  rQ  rS  rU  rW  rJ  __classcell__)rX   s   @rY   r"   r"      s       `# ` ` ` ` ` `D0 0s 0 0 0 0 LPXZ U U U U U U, LN H H H H$ <@d[] S S SS S Sbfglbm S S S S OSaenp .S .Sd3i .S .S[^ .Suyz  vA .S .S .S .S` LN  U  Uc  URU  U  U  U  UD 9; H HC Hs H H H H/0F /0 /0 /0 /0b <>  s +     <@ %J %J %J| %J %J %J %JNV& V V V V8 68 / / /F / / / /& 9; = =C =s = = = = 6:" E E7 E E E E E( :<  S     & :>b E Ew EW E E E E( 9=R U Ug UC U U U UB'0F '0 '0 '0 '0R 8<B "F "FW "F7 "F "F "F "FH 2V  2  2  2  2D     UYgktv ,b ,bDI ,bc ,bad ,b{  AL  |M ,b ,b ,b ,b\'E 'E 'E 'E 'ER X\jnwy &b &btCy &bQT &bdg &b  C  DO  P &b &b &b &bP1GF 1G 1G 1G 1Gf, , , ,\% % % %N ?CQUdhqs H H H H3 H^a Hx|  ~B  yC H H H H& BFb 	T 	T3 	T3 	TUX 	T 	T 	T 	T aesw  AC %E %E$tCy/ %EZ] %Emp %E %E %E %EN ^` U UT$s)_ Udg U U U UB)M6 )M )M )M )MV @DB #P #PS #P #PS\ #P #P #P #PJ SW_a .! .!$s) .!C .!fo .! .! .! .!` PR ,U ,UT#Y ,UVY ,U ,U ,U ,U\ =? L L L3 L L L L& & &3 3 3< < < < < <|    B )+    B *, S S S S S S4& 4 4 4 4_.V _. _. _. _.B   0 37TX\eg ,U ,UC ,Us ,URU ,Ulpqvlw ,U ,U ,U ,U\ 8<$]ajl $_ $_W $_C $_WZ $_quv~q $_ $_ $_ $_L[2 [2 [2z 04$UYbd *U *U *UC *Us *Uimnsit *U *U *U *UXM4F M4 M4 M4 M4^U=v U= U= U= U=n   pt|~ %H %HC %Hy %H	 %H[` %Hil %H  DI %H %H %H %HN+& + + + +@ im{  IK !] !]c !]3 !]i !]y !]be !]ux !]  PU !] !] !] !]F <@ "H "H "HS "Hu "H "H "H "HH DHPR $b $b$s) $bS $b $b $b $bL 8<B H H H4PU; H H H H:*v * * * *$    &    6    
&    *6 *t * * * *X_(V _( _( _( _(B$F $C $RU $ $ $ $(v (s (UX ( ( ( (/& /# /PS / / / /%6 %3 % % % %FF F F F F F F F FrZ   r"   )(ccxt.async_supportccxt ccxt.async_support.base.ws.cacher   r   r   r   r  ccxt.base.typesr   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   !ccxt.async_support.base.ws.clientr   typingr   ccxt.base.errorsr   r   r   r   r   r    async_supportr"   r*  rZ   rY   <module>rh     s2       A  A  A  A  A  A  A  A  A  A  A  A  z  z  z  z  z  z  z  z  z  z  z  z  z  z  z  z  z  z  z  z  z  z  z  z  z  z  z  z  z  z  z  z  z  z  z  z  z  z  z  z 4 4 4 4 4 4       * * * * * * 0 0 0 0 0 0 . . . . . . ' ' ' ' ' ' ) ) ) ) ) ) * * * * * *h%F h%F h%F h%F h%F$

  h%F h%F h%F h%F h%FrZ   