
    ":h                       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 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jJ                  jL                        Z&y)    N)
ArrayCacheArrayCacheBySymbolByIdArrayCacheBySymbolBySideArrayCacheByTimestamp)AnyBalances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dXd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i fde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"dYdZ#dddi fdee   d
e
de
dee$   fdZ%defd Z&dddi fdee   d
e
de
dee$   fd!Z'defd"Z(dYd#Z)dYd$Z*d%ddi fd	ed
e
de
dee+   fd&Z,d%i f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d.Z4i fd	edefd/Z5d0 Z6d1 Z7dYdefd2Z8defd3Z9i fd4Z:i fde;fd5Z<defd6Z=defd7Z>dYd8Z?dddi fd	e@d
e
de
dee   fd9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<ZFdYdefd=ZGdefd>ZHd? ZIdi fd	ed@eJdAeKdBeLdCeMdeEfdDZNdefdEZOddi fdFed	ed@eJdAeKdBeMdCeMdeEfdGZPdi fdFed	e@deEfdHZQdi fdIee   d	e@fdJZRdi fd	e@fdKZSdefdLZTdefdMZUdefdNZVdefdOZWdefdPZXdefdQZYdefdRZZded	efdSZ[ded	edefdTZ\ded	edefdUZ]ded	efdVZ^defdWZ_ xZ`S )Zokxreturnc                 ,   | j                  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(   r6   r7   r;   r<   r$   iPF  )ping	keepAlive)hasurlsoptions	streaming)deep_extendsuperr!   describerM   )self	__class__s    F/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/pro/okx.pyrU   zokx.describe   s   c4 9 ;dt !$ "4	
    !$ t ( +D  $Z .t &z 0  d!" '#$  $!%"&$(%)!%#!%"&%)7> 7 :	 !%0 %3#6 !'y  y! E  E" ." - _2l 		"	s_>
 _ _	    rF   c                     | j                   d   }|rdnd}|dk(  }|dk(  }| j                  d   d   }|s|j                  d      d	kD  s|d
k(  r|dz   |z   S |r|dz   |z   S |dz   |z   S )NsandboxModez?brokerId=9999 businesspublicr@   r$   candleorders-algoz	/businessz/publicz/private)rQ   rP   find)rV   rF   access	isSandboxsandboxSuffix
isBusinessisPublicurls           rX   get_urlzokx.get_urlx   s    LL/	,5(2
*
h&iit$',,x0257m;S$}44?]22Z-//rY   Nsymbolsc                   K   | j                          d {    || j                  }| j                  |      }| j                  ||      }g }g }t	        dt        |            D ]V  }| j                  ||         }	||	d}
|j                  | j                  |
|             |j                  |dz   ||   z          X d|d}| j                  ||||       d {   S 7 7 w)Nr   rF   instId::	subscriberJ   args)
load_marketsrj   market_symbolsri   rangelen	market_idappendextendwatch_multiple)rV   rc   rF   rj   paramsrh   messageHashesrq   imarketIdargrequests               rX   subscribe_multiplezokx.subscribe_multiple   s     !!!?llG%%g.ll7F+q#g,' 	>A~~gaj1H""C KKC01  4'!*!<=	> 
 ((mWmTTT' 	"& Us"   C#CCC#C!C#!C#c                   K   | j                          d {    | j                  ||      }d|i}|$| j                  |      }|d|d   z   z  }|d   |d<   d| j                  ||      gd}	| j	                  |||	|       d {   S 7 r7 w)NrF   :idrm   ro   rp   )rr   ri   marketrS   watch)
rV   rc   messageHashrF   symbolrz   rh   firstArgumentr   r   s
             rX   ro   zokx.subscribe   s     !!!ll7F+w
 [[(F3--K&,TlM(#  7
 ZZ[';GGG 	" Hs"   BB	A-BBBBr   sincelimitc                 H   K   | j                  |g|||       d{   S 7 w)a  
        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)rV   r   r   r   rz   s        rX   watch_tradeszokx.watch_trades   s'      22F8UE6RRRRs   " "c                   K   t        |      }|dk(  rt        | j                  dz         | j                          d{    | j	                  |      }d}g }g }t        dt        |            D ]E  }	||	   }
|j                  |dz   |
z          | j                  |
      }||d}|j                  |       G d|d}| j                  |d	      }| j                  ||||       d{   }| j                  r6| j                  |d      }| j                  |d
      }|j                  ||      }| j                  |||dd      S 7 7 ^w)a  
        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
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        r   z> watchTradesForSymbols() requires a non-empty array of symbolsNtradesr   rl   ro   rp   r^   r   	timestampT)ru   r   r   rr   rs   rt   rw   rv   ri   ry   
newUpdates
safe_valuesafe_stringgetLimitfilter_by_since_limit)rV   rj   r   r   rz   symbolsLengthrF   topicsr{   r|   r   r}   topicr   rh   r   firsttradeSymbols                     rX   r   zokx.watch_trades_for_symbols   sZ     GA#DGG.n$noo!!!%%g.q#g,' 	!AQZF  3!78~~f-H""E MM% 	! 
 ll7H-**3wVV??OOFA.E**5(;KOOK7E))&%TRR1 	"& Ws#   <EEB&E%E&AEEc                   K   | j                          d{    | j                  |dd      }d}g }g }t        dt        |            D ]B  }||   }|j	                  d|z          | j                  |      }||d}	|j	                  |	       D d|d}
| j                  |d	      }| j                  |||
|       d{   S 7 7 w)
a  
        unWatches from the stream channel
        :param str[] symbols:
        :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>`
        NFr   r   unsubscribe:trades:rl   unsubscriberp   r^   )rr   rs   rt   ru   rw   rv   ri   ry   rV   rj   rz   rF   r   r{   r|   r   r}   r   r   rh   s               rX   un_watch_trades_for_symbolszokx.un_watch_trades_for_symbols   s      !!!%%gtU;q#g,' 	!AQZF  !6!?@~~f-H""E MM% 	!  
 ll7H-((mWmTTT' 	"& Us"   CCB%C<C=CCc                 D   K   | j                  |g|       d{   S 7 w)a6  
        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   rV   r   rz   s      rX   un_watch_tradeszokx.un_watch_trades   s#      55vhGGGG     clientc                    | j                  |di       }| j                  |d      }| j                  |d      }| j                  |      }| j                  |dg       }| j                  | j                  dd      }t        dt        |            D ]y  }	| j                  ||	         }
|dz   |z   }| j                  | j                  |      }|t        |      }|| j                  |<   |j                  |
       |j                  ||       { y )	Nr~   rF   rm   datatradesLimit  r   r   )r   r   safe_symbolsafe_integerrQ   rt   ru   parse_trader   r   rw   resolve)rV   r   messager~   rF   r}   r   r   r   r|   trader   storeds                rX   handle_tradeszokx.handle_trades  s      oogub1""3	2##C2!!(+w3''mTJq#d)$ 	0A$$T!W-E!C-&0K__T[[&9F~#K0&,F#MM% NN6;/	0rY   c                 p   K   | j                  |      }| j                  |g|       d{   }||   S 7 	w)ar  
        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)rV   r   rz   frs       rX   watch_funding_ratezokx.watch_funding_rate#  s<      V$++VHf==&z >s   (64
6c                   K   | j                          d{    | j                  |      }d}g }g }t        dt        |            D ]E  }||   }|j	                  |dz   |z          | j                  |      }||d}	|j	                  |	       G d|d}
| j                  |d      }| j                  |||
|       d{   }| j                  r| j                  |d	      }i }|||<   |S | j                  | j                  d	|      S 7 7 Jw)
a  
        watch the funding rate for multiple markets

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

        :param str[] symbols: 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-rates-structure>`, indexe by market symbols
        Nfunding-rater   r   rl   ro   rp   r^   r   )rr   rs   rt   ru   rw   rv   ri   ry   r   r   filter_by_arrayfundingRates)rV   rj   rz   rF   r   r{   r|   r   r}   r   r   rh   fundingRateresults                 rX   r   zokx.watch_funding_rates1  s)     !!!%%g. q#g,' 	!AQZF  3!78~~f-H""E MM% 	! 
 ll7H- //]G][[??%%k8<FF(F6NM##D$5$5xII3 	"& \s#   D
DB&D
=D>A	D
D
c                     | j                  |dg       }t        dt        |            D ]D  }||   }| j                  |      }|d   }|| j                  |<   |j                  |d|d   z          F y )Nr   r   r   zfunding-rate:)	safe_listrt   ru   parse_funding_rater   r   )rV   r   r   r   r|   rawfrr   r   s           rX   handle_funding_ratezokx.handle_funding_rateV  s~    ( ~~gvr2q#d)$ 	VAGE11%8K *F(3Df%NN;(<{8?T(TU	VrY   c                    K   d}| j                  |ddd      \  }}||d<   | j                  |      }|d   }| j                  |g|       d{   }| j                  ||      S 7 w)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%   rF   rG   r   )handle_option_and_paramsr   watch_tickersr   rV   r   rz   rF   r   tickers         rX   watch_tickerzokx.watch_tickerr  sw      77yZcd#yV$!))6(F;;vv.. <s   AA&A$A&c                 D   K   | j                  |g|       d{   S 7 w)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      rX   un_watch_tickerzokx.un_watch_ticker  s#      **F8V<<<<r   c                 (  K   | j                          d{    | j                  |dd      }d}| j                  |ddd      \  }}| j                  d|||       d{   }| j                  r|S | j                  | j                  d|      S 7 w7 1w)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(   rF   rG   r^   r   rr   rs   r   r   r   r   rG   rV   rj   rz   rF   
newTickerss        rX   r   zokx.watch_tickers  s      !!!%%gtU;77PY[de228WgvVV
??##DLL(GDD 	" W"   BBABB0BBc                    K   d}| j                  |ddd      \  }}||d<   | j                  |      }|d   }| j                  |g|       d{   }||   S 7 	w)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&   rF   
mark-pricer   )r   r   watch_mark_pricesr   s         rX   watch_mark_pricezokx.watch_mark_price  ss      77@PR[]ij#yV$!--vh??f~ @s   AAA
Ac                 (  K   | j                          d{    | j                  |dd      }d}| j                  |ddd      \  }}| j                  d|||       d{   }| j                  r|S | j                  | j                  d|      S 7 w7 1w)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'   rF   r   r^   r   r   r   s        rX   r   zokx.watch_mark_prices  s      !!!%%gtU;77@QS\^jk228WgvVV
??##DLL(GDD 	" Wr   c                   K   | j                          d{    | j                  |dd      }d}| j                  |ddd      \  }}g }g }t        dt	        |            D ]B  }||   }|j                  d|z          | j                  |      }||d}	|j                  |	       D d	|d
}
| j                  |d      }| j                  |||
|       d{   S 7 7 w)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(   rF   rG   r   unsubscribe:ticker:rl   r   rp   r^   )	rr   rs   r   rt   ru   rw   rv   ri   ry   r   s               rX   r   zokx.un_watch_tickers  s      !!!%%gtU;77PY[deq#g,' 	!AQZF  !6!?@~~f-H""E MM% 	!  
 ll7H-((mWmTTT) 	"( Us"   CCB<CCCCc                    | j                  ||       | j                  |di       }| j                  |d      }| j                  |d d      }|d   }| j                  |d      }| j                  |dg       }i }	t	        dt        |            D ]*  }
| j                  ||
         }|| j                  |<   ||	|<   , |dz   |z   }|j                  |	|       y )	Nr~   rm   -r   rF   r   r   rn   )	handle_bid_askr   r   safe_marketrt   ru   parse_tickerrG   r   )rV   r   r   r~   r}   r   r   rF   r   r   r|   r   r   s                rX   handle_tickerzokx.handle_ticker  s    4 	FG,oogub1##C2!!(D#6!""3	2w3
q#d)$ 	(A&&tAw/F#)DLL !'Jv	( nv-z;/rY   c                 J  K   | j                          d{    | j                  |dd      }d}| j                  |ddd      \  }}| j                  |d      }g }g }t	        dt        |            D ]S  }| j                  ||         }||d}	|j                  | j                  |	|             |j                  d	||   z          U d
|d}
| j                  |||
|       d{   }| j                  ri }|||d   <   |S | j                  | j                  d|      S 7 7 <w)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)   rF   rG   r^   r   rl   bidask::ro   rp   r   )rr   rs   r   ri   rt   ru   rv   rw   rx   ry   r   r   bidsasks)rV   rj   rz   rF   rh   r{   rq   r|   r}   r~   r   r   rG   s                rX   watch_bids_askszokx.watch_bids_asks  sA     !!!%%gtU;77QZ\efll7H-q#g,' 	:A~~gaj1H""C KKC01  gaj!89	: 
  ..sM7MZZ
??G,6GJx()N##DMM8WEE1 	"& [s"   D#DCD#$D!%:D#!D#c                     | j                  |dg       }| j                  |di       }| j                  |      }|d   }|| j                  |<   d|z   }|j	                  ||       y )Nr   r   r   r   )r   	safe_dictparse_ws_bid_askr   r   )rV   r   r   r   r   parsedTickerr   r   s           rX   r   zokx.handle_bid_ask;  sh    4 ~~gvr2a,,,V4h' ,f 6)|[1rY   c                 f   | j                  |d      }| j                  ||      }| j                  |d      }| j                  |d      }| j                  ||| j	                  |      | j                  |d      | j                  |d      | j                  |d      | j                  |d      |d|      S )	Nrm   r   tsaskPxaskSzbidPxbidSz)r   r   datetimeask	askVolumebid	bidVolumeinfo)r   r   r   safe_tickeriso8601)rV   r   r   r}   r   r   s         rX   r   zokx.parse_ws_bid_ask]  s    ##FH5!!(F3!!&(3%%fd3	"Y/##FG4))&':##FG4))&':	!
 	 		rY   c                 d  K   | j                          d{    | j                  |ddd      }d}g }|7t        dt        |            D ]  }||   }|j	                  |dz   |z            n|j	                  |       | j                  |      }	d}
| j                  d|	|      \  }
}d}|
dk(  rd	}
n|
d
k(  rd}
|
j                         }d||dgd}| j                  |d      }| j                  ||||       d{   }| j                  r|S | j                  | j                  |||d      S 7 7 4w)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   rn   watchliquidationsForSymbolsliquidation-ordersrE   SWAPfuturefuturesro   rF   instTyperp   r^   )rr   rs   rt   ru   rw   get_market_from_symbolshandle_market_type_and_paramsupperri   ry   r   filter_by_symbols_since_limitr   )rV   rj   r   r   rz   r   r{   r|   r   r   rH   rF   uppercaseTyper   rh   newLiquidationss                   rX   watch_liquidations_for_symbolsz"okx.watch_liquidations_for_symbolsm  si     !!!%%gtT4@$1c'l+ B $$[4%7&%@AB   ---g699:WY_aghf&6>DXD

  ' -
 ll7H- $ 3 3CQ^ __??""11$2C2CWeUZ\`aaA 	": `s"   D0D+C"D09D.:2D0.D0c                    | j                  |dg       }t        dt        |            D ]  }||   }| j                  |      }| j	                  |d      }| j                  | j                  |      }|(| j                  | j                  dd      }	t        |	      }|j                  |       || j                  |<   |j                  |gd       |j                  |gd|z           y )Nr   r   r   liquidationsLimitr   r   zliquidations::)r   rt   ru   parse_ws_liquidationr   r   r   r   rQ   r   rw   r   )
rV   r   r   rawLiquidationsr|   rawLiquidationliquidationr   r   r   s
             rX   handle_liquidationzokx.handle_liquidation  s    8 ..&"=q#o./ 	EA,Q/N33NCK%%k8<F??4+<+<fEL#))$,,8KTR)%0,(4Df%NNK=.9NNK=*:V*CD	ErY   c                   K   | j                          d{    | j                  |ddd      }| j                  |ddg      }| j                  d|rdndi       d{    | j	                  |ddd      }d	}g }|7t        d
t        |            D ]  }||   }	|j                  |dz   |	z            n|j                  |       d}
dd|
igd}| j                  |
d      }| j                  ||| j                  ||      |       d{   }| j                  r|S | j                  | j                  |||d      S 7 #7 7 6w)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triggerFrc   r]   privateTmyLiquidationsr   rn   balance_and_positionro   rF   rp   )rr   safe_value_2omitauthenticaters   rt   ru   rw   ri   ry   rS   r   r   r   )rV   rj   r   r   rz   	isTriggerr   r{   r|   r   rF   r   rh   r   s                 rX   !watch_my_liquidations_for_symbolsz%okx.watch_my_liquidations_for_symbols  sq     !!!%%ffiG	6FI#67:	 RSSS%%gtT4@&1c'l+ B $$[4%7&%@AB   -( w
 ll7I. $ 3 3CHXHXY`bhHikx yy??""11$2C2CWeUZ\`aa5 	" 	T( zs5   E D9AE D<B)E D>2E <E >E c                    | j                  |dg       }t        dt        |            D ]  }||   }| j                  |d      }|dk7  r y | j	                  |      }| j                  |d      }| j                  | j                  |      }	|	(| j                  | j                  dd      }
t        |
      }	|	j                  |       |	| j                  |<   |j                  |gd       |j                  |gd	|z           y )
Nr   r   	eventTyper  r   myLiquidationsLimitr   r  zmyLiquidations::)r   rt   ru   r   parse_ws_my_liquidationr   r   r   rQ   r   rw   r   )rV   r   r   r  r|   r  r  r  r   r   r   s              rX   handle_my_liquidationzokx.handle_my_liquidation  s   F ..&"=q#o./ 	GA,Q/N((EIM)66~FK%%k8<F??4+<+<fEL#))$,,8MtT)%0,(4Df%NNK=*:;NNK=*<v*EF	GrY   c                    | j                  |dg       }| j                  |di       }| j                  |d      }| j                  ||      }| j	                  |d      }| j                  || j                  ||      | j                  |d      | j                  |d      | j                  |d      d d || j                  |      d	      S )	NposDatar   rm   uTImeposcontractSizeavgPx	r   r   	contractsr  price	baseValue
quoteValuer   r   	r   r   r   r   r   safe_liquidationr   safe_numberr   )rV   r  r   r  firstPosDatar}   r   s          rX   r  zokx.parse_ws_my_liquidation!  s    : ..i<~~gq"5##L(;!!(F3%%lG<	$$&&x8)),> ,,V^D%%k7;"Y/
&
 
 
	rY   c                    | j                  |dg       }| j                  |di       }| j                  |d      }| j                  ||      }| j	                  |d      }| j                  || j                  ||      | j                  |d      | j                  |d      | j                  |d      d d || j                  |      d	      S )	Ndetailsr   rm   r   szr  bkPxr  r#  )rV   r  r   r(  liquidationDetailsr}   r   s          rX   r  zokx.parse_ws_liquidationO  s    * ..i<!^^GQ;##K:!!(F3%%&8$?	$$&&x8))*<dC ,,V^D%%&8&A"Y/
&
 
 
	rY   1mc                 H  K   | j                          d{    | j                  |      }| j                  | j                  ||      }d|z   }| j	                  d||||       d{   }| j
                  r|j                  ||      }| j                  |||dd      S 7 7 9w)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)rr   r   r   
timeframesro   r   r   r   )	rV   r   	timeframer   r   rz   intervalnameohlcvs	            rX   watch_ohlcvzokx.watch_ohlcvu  s      !!!V$##DOOY	J("nnXtT66JJ??NN651E))%q$GG 	" Ks"   B"BAB"&B '8B" B"c                 |   K   | j                          d{    | j                  ||gg|       d{   S 7 !7 w)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)rr   un_watch_ohlcv_for_symbols)rV   r   r/  rz   s       rX   un_watch_ohlcvzokx.un_watch_ohlcv  sA      !!!44vy6I5JFSSS 	"Ss   <8<:<<symbolsAndTimeframesc                   K   t        |      }|dk(  st        |d   t              st        | j                  dz         | j                          d{    g }g }t        dt        |            D ]t  }||   }	|	d   }
|	d   }| j                  |
      }| j                  | j                  ||      }d|z   }||d}|j                  |       |j                  d|z   dz   |
z          v d	|d
}| j                  dd      }| j                  ||||       d{   \  }}}| j                  r|j                  ||      }| j                  |||dd      }| j!                  |||      S 7 7 Qw)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_   rl   multi:r   ro   rp   r^   T)ru   
isinstancelistr   r   rr   rt   rv   r   r.  rw   ri   ry   r   r   r   create_ohlcv_object)rV   r7  r   r   rz   r   r   r{   r|   symbolAndTimeframesymtfr}   r0  rF   r   r   rh   r   r/  candlesfiltereds                         rX   watch_ohlcv_for_symbolszokx.watch_ohlcv_for_symbols  s     01AZ0DQ0G%N#DGG  /f  %f  g  g!!!q#234 	AA!5a!8$Q'C#A&B~~c*H''R@H)G""E MM%   G!3c!9C!?@	A 
 ll8X.+/+>+>sMSZ\i+j%j"	7??$$VU3E--gueQM''	8DD3 	"* &ks&   AE(E#CE(E&AE(&E(c                 >  K   t        |      }|dk(  st        |d   t              st        | j                  dz         | j                          d{    g }g }t        dt        |            D ]t  }||   }|d   }|d   }	| j                  |      }
| j                  | j                  |	|	      }d|z   }||
d}|j                  |       |j                  d|z   dz   |z          v d	|d
}| j                  dd      }| j                  ||||       d{   S 7 7 w)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   r9  Nr:  r_   rl   zunsubscribe:multi:r   r   rp   r^   )ru   r<  r=  r   r   rr   rt   rv   r   r.  rw   ri   ry   )rV   r7  rz   r   r   r{   r|   r?  r@  rA  r}   r0  rF   r   r   rh   s                   rX   r5  zokx.un_watch_ohlcv_for_symbols  sT     01AZ0DQ0G%N#DGG  /f  %f  g  g!!!q#234 	MA!5a!8$Q'C#A&B~~c*H''R@H)G""E MM%   !5!?#!E!KL	M  
 ll8X.((mWmTTT+ 	"* Us%   ADDCDDDDc                    | j                  |di       }| j                  |d      }| j                  |dg       }| j                  |d      }| j                  |      }|d   }|j                  dd      }	| j	                  |	      }
t        dt        |            D ]  }| j                  ||   |      }| j                  | j                  |i       | j                  |<   | j                  | j                  |   |
      }|:| j                  | j                  d	d
      }t        |      }|| j                  |   |
<   |j                  |       |dz   |d   z   }|j                  ||       d|z   dz   |z   }|j                  ||
|g|        y )Nr~   rF   r   rm   r   r_   r\   r   
OHLCVLimitr   r   r   r;  )r   r   r   replacefind_timeframert   ru   parse_ohlcvohlcvsr   rQ   r   rw   r   )rV   r   r   r~   rF   r   r}   r   r   r0  r/  r|   parsedr   r   r   messageHashForMultis                    rX   handle_ohlcvzokx.handle_ohlcv  s   " oogub1""3	2w3##C2!!(+!??8R0''1	q#d)$ 	MA%%d1gv6F"&//$++vr"JDKK__T[[%8)DF~))$,,dK.u517F#I.MM&!!C-&,6KNN6;/ #+W"4s":V"CNNFIv68KL	MrY   c                 F   K   | j                  |g||       d{   S 7 w)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)rV   r   r   rz   s       rX   watch_order_bookzokx.watch_order_book  s&     F 66xOOOOs   !!c                   K   | j                          d{    | j                  |      }d}| j                  |ddd      \  }}|$|dk(  rd}n|dkD  r|dk  rd}n|d	k(  rd
}n|dk(  rd}|dk(  s|d
k(  rD| j                  d      st	        | j
                  dz         | j                  ddi       d{    g }g }t        dt        |            D ]E  }||   }|j                  |dz   |z          | j                  |      }	||	d}
|j                  |
       G d|d}| j                  |d      }| j                  ||||       d{   }|j                         S 7 G7 7 w)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*   rD   rB   r:  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 books5rc   r^   r   r   rl   ro   rp   )rr   rs   r   check_required_credentialsr   r   r  rt   ru   rw   rv   ri   ry   r   )rV   rj   r   rz   rD   r   r{   r|   r   r}   r   r   rh   	orderbooks                 rX   rP  z okx.watch_order_book_for_symbols+  s     !!!%%g.55f>NPWY`avz!uz "(#^#2B)B2259)$''  5E  +E  F  F##Xx$8999q#g,' 	!AQZF  v!56~~f-H "E MM% 	! 
 ll5(+--c='=YY	  E 	"  :" Zs5   E$EBE$4E 5BE$E"	E$ E$"E$c                 `  K   | j                          d{    | j                  |dd      }d}| j                  |ddd      \  }}| j                  |d      }|$|dk(  rd}n|dkD  r|d	k  rd
}n|dk(  rd}n|dk(  rd}g }g }g }t	        dt        |            D ]Y  }||   }	|j                  |dz   |	z          |j                  d|	z          | j                  |	      }
||
d}|j                  |       [ d|d}| j                  |d      }| j                  ||||       d{   S 7 7 w)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*   rD   rB   r   r:  rS  rT  rU  rV  rW  rX  r   r   unsubscribe:orderbook:rl   r   rp   r^   )
rr   rs   r   r   rt   ru   rw   rv   ri   ry   )rV   rj   rz   rD   r   r   subMessageHashesr{   r|   r   r}   r   r   rh   s                 rX   un_watch_order_book_for_symbolsz#okx.un_watch_order_book_for_symbols[  sn     !!!%%gtU;55f>NPWY`av!!&'2z!uz "(#q#g,' 		!AQZF##ECK&$89  !9F!BC~~f-H "E MM% 		!  
 ll5(+((mWmTTTA 	"@ Us"   D.D)DD.$D,%D.,D.c                 D   K   | j                  |g|       d{   S 7 w)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      rX   un_watch_order_bookzokx.un_watch_order_book  s#      996(FKKKKr   c                 p    | j                  |d      }| j                  |d      }|j                  ||       y )Nr   r:  )
safe_floatstore)rV   booksidedeltar   amounts        rX   handle_deltazokx.handle_delta  s2     q)*uf%rY   c                 b    t        dt        |            D ]  }| j                  |||           y )Nr   )rt   ru   rh  )rV   re  deltasr|   s       rX   handle_deltaszokx.handle_deltas  s0    q#f+& 	3Ahq	2	3rY   c                    | j                  |dg       }| j                  |dg       }|d   }|d   }	| j                  ||       | j                  |	|       | j                  |d      }
| j                  |
|      }| j	                  ddd      }| j                  |d      }|r| j                  |d      }|d	   }t        |      }t        |	      }g }t        d
d      D ]  }||k  rL|j                  | j                  |	|   d
                |j                  | j                  |	|   d                ||k  sZ|j                  | j                  ||   d
                |j                  | j                  ||   d                 dj                  |      }| j                  |d      }| j                  |d      }d }|dk7  r||k7  rt        | j                  dz         }||k7  r*t        | j                  dz   | j                  |      z         }|,|j                   |= | j"                  |= |j%                  ||       | j                  |d      }||d	<   ||d<   | j'                  |      |d<   |S )Nasksbidsrm   r*   rC   TseqId	prevSeqIdnoncer      r:  r   r`   z& watchOrderBook received invalid nonce r   r   r   )r   rk  r   r   handle_optionr   ru   rt   rw   number_to_stringjoincrc32r   r   r   orderbook_checksum_messagesubscriptions
orderbooksrejectr   )rV   r   r   r[  r   r   rm  rn  
storedAsks
storedBidsr}   r   rC   ro  rp  rq  
asksLength
bidsLengthpayloadArrayr|   payloadresponseChecksumlocalChecksumerrorr   s                            rX   handle_order_book_messagezokx.handle_order_book_message  s|   ( w3w3v&
v&
:t,:t,##GX6!!(F3%%&6
DI!!'73))';?Ig&EZJZJL1b\ Qz> ''(=(=jmA>N(OP ''(=(=jmA>N(OPz> ''(=(=jmA>N(OP ''(=(=jmA>N(OPQ hh|,G#00*E JJw5MEB5I#5$TWW/W%WX=0%dggmd6U6UV\6]&]^ ((5OOF+e[1%%gt4	"	'!*	+ $Y 7	*rY   c           
      H   | j                  |di       }| j                  |d      }| j                  |d      }| j                  |dg       }| j                  |d      }| j                  |      }|d   }	ddd	dd
d}
| j	                  |
|      }|dz   |	z   }|dk(  rmt        dt        |            D ]S  }||   }| j                  i |      }|| j                  |	<   |	|d<   | j                  ||||       |j                  ||       U |S |dk(  re|	| j                  v rU| j                  |	   }t        dt        |            D ].  }||   }| j                  |||||       |j                  ||       0 |S |dk(  s|dk(  r|	| j                  vr| j                  i |      | j                  |	<   | j                  |	   }t        dt        |            D ]S  }||   }| j	                  |d      }| j                  ||	|dddd      }|j                  |       |j                  ||       U |S )Nr~   rF   actionr   rm   r   r:  rX  rT  rV  )rS  rB   rU  rY  rW  r   snapshotr   updaterU  rS  r   rn  rm  )r   r   r   r   r   rt   ru   
order_bookrz  r  r   parse_order_bookreset)rV   r   r   r~   rF   r  r   r}   r   r   depthsr   r   r|   r  r[  r   r  s                     rX   handle_order_bookzokx.handle_order_book  sY   l nnWeR0""3	2!!'84~~gvr2##C2!!(+! 
 !!&'2mf,Z1c$i( 7a OOB6	*3'&,	(#..vvy+Vy+670 # x( OOF3	q#d), ;A!!WF22669k[abNN9k:;  !w)';doo-*.//"e*D'/I1c$i( 7a --fd;	00FTZ\]_`a)y+67 rY   c                   K   | j                          | j                  |dd      }| j                  |dg      }| j                  d|      }d}| j	                  |      }|j                  |      }| j                  |j                  |      }|t        | j                               }d}	d}
||	z   |
z   }| j                  | j                  |      | j                  | j                        t        j                  d      }d}|| j                  | j                   ||d	gd
}d|v r|d   |d<   | j#                  ||||       | d {   S 7 w)Nrc   r  usersauthenticatedGETz/users/self/verifybase64login)apiKey
passphraser   signrp   )rZ  r   r  ri   r   r   r   ry  strsecondshmacencodesecrethashlibsha256r  passwordr   )rV   rz   rc   rh   r   r   r   r  r   methodpathauth	signature	operationr   s                  rX   r  zokx.authenticatef  sA    '')!!&(I>6H:.ll7F+%S!{+(<(<kJ DLLN+IF'Dv%,D		$++d"3T[[5Mw~~_ghII #'++&*mm%. )	
G 6!$*8$4!JJsK+>||s   E E	EE	c                    K   | j                          d{    | j                          d{    | j                  dddd|       d{   S 7 97 #7 w)a  
        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)rr   r  ro   )rV   rz   s     rX   watch_balancezokx.watch_balance  sS      !!!!!!^^Iy)T6RRR 	"!Rs1   AAAAAAAAAc                 (    | j                  ||       y N)r  rV   r   r   s      rX   handle_balance_and_positionzokx.handle_balance_and_position  s    ""673rY   c                 L   | j                  |di       }| j                  |d      }d}| j                  |      }| j                  | j                  |i       }| j	                  ||      }| j                  |      | j                  |<   |j                  | j                  |   |       y )Nr~   rF   rE   )r   r   parseTradingBalancebalancerS   safe_balancer   )	rV   r   r   r~   rF   rH   r  
oldBalance
newBalances	            rX   handle_balancezokx.handle_balance  s    X oogub1""3	2**73__T\\4<
%%j':
!..z:Tt||D)73rY   c                 F   | j                  |di       }| j                  |d      }| j                  |d      }| j                  |dd      dk(  }| j                  ||| j	                  |      | j                  |d      | j                  |d      | j                  |d	      | j                  |d
      |rdnd| j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |      dd|      S )Nr   fillTime
fillFeeCcyexecTyper\   Tr   tradeIdr   rH   takermakersidefillPxfillSzcostfillFee)r  currency)r   r   r   r   r   orderrH   takerOrMakerr  r   rg  r  fee)r   r   r   
safe_trader   r%  safe_currency_code)rV   r  r   r   r   feeMarketIdisTakers          rX   order_to_tradezokx.order_to_trade  s(   ufb1%%dJ7	&&t\:""4R8C?"Y/&&uh7""43%%eT2$$UF3(/Gg$$UF3%%dH5&&tX6$$UF3((y9 33K@ 
" # 	rY   c           
        K   d}| j                  |ddd      \  }}| j                  |ddd      }| j                  |ddg      }| j                          d{    | j	                  d|rd	nd
i       d{    |rdnd}|dz   }d}	|#| j                  |      }	|	d   }|	d   }|dz   |z   }|dk(  rd}|j                         }
d}| j                  d|      \  }}|
dk(  r|d}
d|
i}| j                  d
||d| j                  ||             d{   }| j                  r|j                  ||      }| j                  ||||d      S 7 7 7 ;w)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>`
        Nr7   rH   rI   r
  r	  Frc   r]   r  ra   orders
::myTradesr   rn   r   r   SPOTMARGINr   T)r   safe_bool_2r  rr   r  r   r   handle_margin_mode_and_paramsro   rx   r   r   filter_by_symbol_since_limit)rV   r   r   r   rz   rH   r  rF   r   r   r   
marginModer   r  s                 rX   watch_my_tradeszokx.watch_my_trades  s      44V_fV[\f$$VYF	6Iv#67!!!:	 RSSS#,-(,[[(FH%F&>D%,v5K8D


!??QWX
FF"% (
 ~~igtT[[Y`bhMijj??OOFE2E00tTT1 	"S( ks7   AEEE6E
7BEE8E
EEc           	        K   | j                          d{    | j                  |       d{    | j                  |      }ddi}d}d}|Lddd}| j                  ||      g}	d|	d}
| j	                  |d      }| j                  |||
|       d{   }n,| j                  d||| j                  ||             d{   }| j                  r|S | j                  | j                  |||d	      S 7 7 7 b7 7w)
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   rI   	positionsr   ro   rp   r  T)
rr   r  rs   rx   ri   r   r   r   r   r  )rV   rj   r   r   rz   r   rF   newPositionsr~   rq   nonSymbolRequestrh   s               rX   watch_positionszokx.watch_positions  s     !!!'''%%g.
 ?&!C KKV,-D!& ,,w	2C!%C:JG!TTL!%!8!8GWVZVaVabikqVr!ssL??11$..'5RWY]^^1 	"'$ UssD   C<C4C<C6A%C<C8,C<C:2C<6C<8C<:C<c                    | j                  |di       }| j                  |d      }| j                  |d d      }|d   }| j                  |dd      }| j                  |dg       }| j                  t	               | _        | j                  }	g }
t        dt        |            D ]  }||   }| j                  |      }|d	   dk(  r=d
|d<   | j                  |      }d|d<   |	j                  |       |
j                  |       |
j                  |       |	j                  |        |}||dz   |z   }|j                  |
|       y )Nr~   rm   r   r   rF   r\   r   r   r  longr  shortrn   )r   r   r   r  r   rt   ru   parse_positionclonerw   r   )rV   r   r   r~   r}   r   r   rF   r   cacher  r|   rawPositionpositionshortPositionr   s                   rX   handle_positionszokx.handle_positions5  sN   F oogub1##C2!!(D#6!""3	26w3>>!57DNq#d)$ 
	#Aq'K**;7H$)#)  $

8 4(/f%]+##M2)LL"
	# !D.61K|[1rY   c           
        K   d}| j                  |ddd      \  }}| j                  |ddd      }| j                  |ddg      }| j                          d{    | j	                  d|rd	nd
i       d{    d}|| j                  |      }|d   }|d   }|dk(  rd}|j                         }d}	| j                  d|      \  }	}|dk(  r|	d}d|i}
|rdnd}| j                  d
|||| j                  |
|             d{   }| j                  r|j                  ||      }| j                  ||||d      S 7 7 7 ;w)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>`
        Nr6   rH   rI   r	  r
  Frc   r]   r  r   r   r   r  r  r   ra   r  T)r   r  r  rr   r  r   r   r  ro   rx   r   r   r  )rV   r   r   r   rz   rH   r  r   r   r  r   rF   r  s                rX   watch_orderszokx.watch_orders  sr     44V]FTYZf%%ffiG	6FI#67!!!:	 RSSS[[(FH%F&>D8D


!??vV
FF"% (
 $--(~~i'64;;W^`fKghh??OOFE2E00tTT- 	"S$ is7   AED;E6D=7BED?8E=E?Ec                    | j                  ||       | j                  |di       }| j                  |d      }| j                  |dg       }t        |      }|dkD  r| j	                  | j
                  dd      }| j                   t        |      | _        t        |      | _        |dk(  r| j                  n| j                  }	g }
| j                  |      }t        dt        |            D ]B  }||   }|	j                  |       |d   }| j                  |      }|
j                  |d	          D |j                  |	|       t        dt        |
            D ]  }|d
z   |
|   z   }|j                  |	|       ! y y )Nr~   rF   r   r   ordersLimitr   ra   r   r   r   )handle_my_tradesr   r   ru   r   rQ   r  r   triggerOrdersparse_ordersrt   rw   r   r   )rV   r   r   subscriptionr~   rF   r  ordersLengthr   r   	marketIdsrL  r|   r  r   r   r   s                    rX   handle_orderszokx.handle_orders  sk   n 	fg.oogub1""3	2&"56{!%%dllM4HE{{"4U;%;E%B",3},DT''4;;FI&&v.F1c&k* /q	e$xV,  ./ NN67+1c)n- 4%mil:v{34 rY   c                 z   | j                  |di       }| j                  |d      }| j                  |dg       }g }t        dt        |            D ]K  }||   }| j                  |dd      }	t        |	      dkD  s*| j	                  |      }
|j                  |
       M t        |      }|dk(  ry | j                  -| j                  | j                  dd      }t        |      | _        | j                  }i }t        dt        |            D ]3  }||   }| j                  |      }|j                  |       |d	   }d
||<   5 |dz   }|j                  | j                  |       t        |j                               }t        dt        |            D ])  }|dz   ||   z   }|j                  | j                  |       + y )Nr~   rF   r   r   r  r\   r   r   r   Tr  rn   )r   r   rt   ru   parse_orderrw   myTradesr   rQ   r   r  r   r=  keys)rV   r   r   r~   rF   	rawOrdersfilteredOrdersr|   rawOrderr  r  tradesLengthr   r  rj   rawTrader   r   r   tradeSymbolssymbolMessageHashs                        rX   r  zokx.handle_my_trades  s   n oogub1""3	2OOGVR8	q#i.) 	-A |H&&xB?G7|a((2%%e,	- >*1== %%dllM4HE259DM==q#n-. 	#A%a(H''1EOOE"8_F"GFO	# ,t}}k2GLLN+q#l+, 	=A +d 2\!_ DNN4==*;<	=rY   c                 v    t        | j                               }| j                  d      }t        |      }||z   S )N   )r  millisecondsrand_number)rV   r   randomNumber
randomParts       rX   
request_idzokx.request_idd  s9    ""$%''*&
JrY   rH   r  rg  r   c                 2  K   | j                          d{    | j                          d{    | j                  dd      }| j                         }d}	| j	                  |ddd      \  }	}| j                  ||||||      }
| j                  |
d      }|dk(  s|dk(  s|d	k(  s|d
k(  s
|dk(  s|dk(  rt        | j                  dz         |	dk7  r|	dk7  rt        | j                  dz         ||	|
gd}| j                  ||||       d{   S 7 7 7 w)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;   rJ   rK   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   rJ   rq   )
rr   r  ri   r  r   create_order_requestr   r   r   r   )rV   r   rH   r  rg  r   rz   rh   r   rJ   rq   r   r   s                rX   create_order_wszokx.create_order_wsj  sd     !!!!!!ll9i0oo'226?DR`a
F((tVUFS""43y g&>DEMW[_pWpvz  H  wH  NR  V\  N\TWW  (a  a  b  b'Mn 4TWW  (H  H  I  IF

 ZZ[';GGG# 	"!  Hs2   DDDDCDDDDDc                    | j                  |d      }| j                  |dg       }| j                  |dd      }| j                  |      rF| j                  |d      }| j	                  |      }| j                  d d |j                  |d ||d d 	       | j                  |d d d       }| j                  |di       }|j                  ||       y )Nr   r   sCode0rJ   r   )
r   r   	filter_byis_emptyjsonhandle_errorsrh   r  r   r   )	rV   r   r   r   rq   r  	stringMsgr  r   s	            rX   handle_place_orderszokx.handle_place_orders  s    & &&w5w3~~dGS1==%%gt4F		'*ItT6::vtYPWY]_cd""4tT:vq"-uk*rY   r   c           	        K   | j                          d{    | j                          d{    | j                  dd      }| j                         }	d}
| j	                  |ddd      \  }
}| j                  |||||||      }|	|
|gd}| j                  ||	| j                  ||      |	       d{   S 7 7 7 w)a6  
        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<   rJ   rL   r  )rr   r  ri   r  r   edit_order_requestr   rx   )rV   r   r   rH   r  rg  r   rz   rh   r   rJ   rq   r   s                rX   edit_order_wszokx.edit_order_ws  s       !!!!!!ll9i0oo'226=$P]^
F&&r64vufUF

 ZZ[$++gv2NP[\\\ 	"! ]s2   B>B8B>B:BB>3B<4B>:B><B>c                   K   |t        | j                  dz         | j                          d{    | j                          d{    | j	                  dd      }| j                         }| j                  |dd      }| j                  |ddg      }d| j                  |      i}|||d<   n||d<   |d| j                  ||      gd	}| j                  ||||       d{   S 7 7 7 w)
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clientOrderIdrm   ordIdcancel-orderr  )r   r   rr   r  ri   r  safe_string_2r  rv   rx   r   )	rV   r   r   rz   rh   r   r  r~   r   s	            rX   cancel_order_wszokx.cancel_order_ws  s     >TWW'TTUU!!!!!!ll9i0oo'**69oN6OY#?@dnnV,
 $*C	NCL [[f-.

 ZZ[';GGG% 	"!" Hs4   .C/C)C/C+	BC/$C-%C/+C/-C/idsc                   K   t        |      }|dkD  rt        | j                  dz         |t        | j                  dz         | j                          d{    | j	                          d{    | j                  dd      }| j                         }g }t        d|      D ]*  }| j                  |      ||   d}	|j                  |	       , |d|d	}
| j                  ||| j                  |
|      |       d{   S 7 7 7 w)
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   )rm   r  zbatch-cancel-ordersr  )ru   r   r   rr   r  ri   r  rt   rv   rw   r   rS   )rV   r  r   rz   	idsLengthrh   r   rq   r|   r~   r   s              rX   cancel_orders_wszokx.cancel_orders_ws  s      H	r>TWW'YYZZ>TWW'UUVV!!!!!!ll9i0oo'q)$ 	A..0QC KK	 '

 ZZ[$2B2B7F2SU`aaa! 	"! bs7   AD
DD
0D1BD
?D D
D
D
c                   K   |t        | j                  dz         | j                          d{    | j                          d{    | j	                  |      }|d   dk7  rt        | j                  dz         | j                  dd      }| j                         }|d| j                  d|d	   d
|      gd}| j                  ||||       d{   S 7 7 7 w)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 argumentrH   optionzh cancelAllOrdersWs is only applicable to Option in Portfolio Margin mode, and MMP privilege is required.r  mass-cancelOPTIONr   )r   
instFamilyr  )	r   r   rr   r  r   ri   r  rx   r   )rV   r   rz   r   rh   r   r   s          rX   cancel_all_orders_wszokx.cancel_all_orders_ws  s      >TWW'XXYY!!!!!!V$&>X%TWW  (R  R  S  Sll9i0oo'[[$$Tl"  
 ZZ[';GGG 	"! Hs4   .CCCC	BCCCCCc                 r    | j                  |d      }| j                  |dg       }|j                  ||       y )Nr   r   )r   r   r   )rV   r   r   r   r   s        rX   handle_cancel_all_orderszokx.handle_cancel_all_orders+  s6     &&w5w3t[)rY   c                     |S r   r  s      rX   handle_subscription_statuszokx.handle_subscription_status=  s	     rY   c                 ^    | j                  |j                  d      }|j                  d       y )Nr  T)r   r   r   )rV   r   r   r   s       rX   handle_authenticatezokx.handle_authenticateE  s$     AtrY   c                      y)NrM   r*  )rV   r   s     rX   rM   zokx.pingL  s     rY   c                 0    | j                         |_        |S r  )r  lastPongr  s      rX   handle_pongzokx.handle_pongQ  s    ++-rY   c                    | j                  |d      }	 |r1|dk7  r+| j                  dz   | j                  |      z   }|dk7  r | j                  | j                  d   ||       | j                  |d      }|+| j                  | j                  d   ||       t        |      | j                  |dg       }t        d	t        |            D ]p  }||   }| j                  |d
      }| | j                  | j                  d   ||       | j                  |d      }|Q| j                  | j                  d   ||       r t        |      |S # t        $ r}	| j                  |d      }
|
Z| j                  |d      }|F|j                  d      r5|j                  dd      }| j                  |      }| j                  |d      }
|
|j                  |	|
       Y d }	~	y|j                  |	       Y d }	~	yd }	~	ww xY w)Ncoder  rs  1exactmsgbroadr   r   r
  sMsgr   zIllegal request: {zIllegal request: r\   F)r   r   r  throw_exactly_matched_exception
exceptionsr   throw_broadly_matched_exceptionr   rt   ru   r   	Exception
startswithrH  
parse_jsonr{  )rV   r   r   	errorCodefeedbackmessageStringr   r|   der   r6  stringifiedJson
parsedJsons                 rX   handle_error_messagezokx.handle_error_messageU  s     $$Wf5	"	Y#-77S=499W+==#889QS\^fg $ ? ,889QS`bjk $H--  >>'62>D"1c$i0 t G$($4$4Q$@	$0 @@QXAY[dfno(,(H(4 @@QXAY[hjrst $H--" !  	 !!'40Bz&&w6?s~~6J'K&)kk2Er&JO!%!AJ))*d;B~a$MM!	s%   DE
 -E
 
	G5BG0G00G5c           
      <   | j                  ||      sy |dk(  r| j                  ||       y | j                  |dd      }|| j                  | j                  | j
                  | j                  | j                  | j                  | j                  | j                  | j                  d	}| j                  ||      }|
 |||       y y | j                  |di       }| j                  |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"                  d| j$                  i}| j                  ||      }|(|j'                  d      dk(  r| j)                  ||       y y  |||       y )NpongeventrJ   )	r  ro   r   r  rK   rL   zbatch-amend-ordersr  r#  r~   rF   rS  rB   rU  rW  rY  rG   r   r  zindex-tickerszsprd-tickerszblock-tickersr   r  r   r  ra   r   r  r_   r   )rF  r1  r  r-  r+  handle_unsubscriptionr  r(  r   r   r  r   r  r   r  r   r  r  r  rb   rN  )rV   r   r   rI  methodsr  r~   rF   s           rX   handle_messagezokx.handle_message  s   ((9P fVW- ""7GT: 11!<<#9911 $ 8 8#77&*&>&> $ 8 8#<<G __We4F!vw' " //'5"5C&&sI6G411// $00 !$"8"8	
  6 6 4-- d00 T22  !3!3  2 2  !3!3 $,, 4..  8 8  $,,!" t11#$ %d&=&=%& '(H(H'G* __Wg6F~<<)Q.%%fg6 / vw'rY   c                 v    d|z   }d|z   }| j                  |||       || j                  v r| j                  |= y y )Nztrades:r   )clean_unsubscriptionr   )rV   r   r   subMessageHashr   s        rX   handle_un_subscription_tradesz!okx.handle_un_subscription_trades  sE    "V++f4!!&.+FT[[ F# !rY   c                 |    |dz   |z   }d|z   }| j                  |||       || j                  v r| j                  |= y y )Nr   r]  )rN  rz  rV   r   r   rF   rO  r   s         rX    handle_unsubscription_order_bookz$okx.handle_unsubscription_order_book  sI     3/.7!!&.+FT__$' %rY   c                     |j                  dd      }| j                  |      }d|z   dz   |z   }d|z   }| j                  |||       || j                  |   v r| j                  |   |= y y )Nr_   r\   r;  r   zunsubscribe:)rH  rI  rN  rK  )rV   r   r   rF   rA  r/  rO  r   s           rX   handle_unsubscription_ohlcvzokx.handle_unsubscription_ohlcv  sy    __Xr*''+	!G+c1F:$~5!!&.+FF++F#I. ,rY   c                 |    |dz   |z   }d|z   }| j                  |||       || j                  v r| j                  |= y y )Nrn   r   )rN  rG   rR  s         rX   handle_unsubscription_tickerz okx.handle_unsubscription_ticker  sI     4&0+f4!!&.+FT\\!V$ "rY   c                    | j                  |di       }| j                  |dd      }| j                  |d      }| j                  |      }|dk(  r| j                  ||       y |j	                  d      s|j	                  d      r| j                  |||       y |j                  d      d	kD  r| j                  |||       y |j	                  d
      r| j                  |||       y y )Nr~   rF   r\   rm   r   bbobookrG   r`   r_   )	r   r   r   rP  r=  rS  rb   rW  rU  )rV   r   r   r~   rF   r}   r   s          rX   rJ  zokx.handle_unsubscription  s     nnWeR0""3	26##C2!!(+h..vv>&'*<*<V*D11&&'J\\)$r)--ffgF),,VVWE *rY   )r^   r  )a__name__
__module____qualname__r   rU   r  ri   r   r   ro   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=  r3  r6  rD  r5  rN  r   rQ  rP  r_  ra  rh  rk  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-  rM   r1  rF  rL  rP  rS  rU  rW  rJ  __classcell__)rW   s   @rX   r!   r!      sb   `# `D0s 0 LPXZ U U, LN H$ <@d[] 	S 	SS 	S 	Sbfglbm 	S OSaenp $Sd3i $S $S[^ $Suyz  vA $SL LN Uc URU U8 9; HC Hs H0F 0@ <> s +  DF #Jc #J, #JJV& V8 68 / /F /& 9; =C =s = 6:" E7 E E( :< S  & :>b Ew EW E( 9=R Ug UC UB'0F '0R 8<B "FW "F7 "FH 2V  2D  IM[_nr{} ,bDI ,bUX ,bhk ,b  CG  HS  CT ,b\(E (ET LP^bqu  A &btCy &bX[ &bkn &b  FJ  KV  FW &bP2GF 2Gh,\$L 8<$]ajl H HC HWZ Hquvzq{ H& ;?r 	T3 	Tc 	T aesw  AC %E$tCy/ %EZ] %Emp %EN ^` UT$s)_ Udg UB)M6 )MV @DB #PS #P #PS\ #PJ SW_a .!$s) .!C .!fo .!` PR ,UT#Y ,UVY ,U\ =? L L3 L&3; ;z B )+ B *, S S4& 434V 34j0 37TX\eg ,UC ,Us ,URU ,Ulpqvlw ,U\ 8<$]ajl $_W $_C $_WZ $_quv~q $_L[2z 04$UYbd *U *UC *Us *Uimnsit *UXM4F M4^U=v U=n pt|~  HC  Hy  H	  H[`  Hil  H  DI  HD+& +@ im{  IK ]c ]3 ]i ]y ]be ]ux ]  PU ]< <@  H  HS  Hu  HD DHPR  b$s)  bS  bD 8<B H H:*v *$ & 6 
& *6 *X^(V ^(@$F $C $(v (s (UX (/& /# /PS /%6 %3 %FF FrY   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   !ccxt.async_support.base.ws.clientr   typingr   ccxt.base.errorsr   r   r   r   r   r   async_supportr!   r*  rY   rX   <module>rh     sk     A  A  t  t  t  t  t 4  * 0 . ' ) *A$F$


 
  A$FrY   