
    i                        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 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)BalancesIntNumOrder	OrderBook	OrderSide	OrderTypePositionStrStringsTickerTickersTrade)Client)List)AuthenticationError)ArgumentsRequired)
BadRequest)InvalidNoncec                       e Zd Z fdZd<d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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dddi fd	ed
e	de	de
e         fdZddi fde
e
e                  d
e	de	fdZdefdZdi fd	ede	defdZdi fde
e         de	defdZd Zd ZdefdZdefdZi fdZ i fde!fd Z"defd!Z#d=d"Z$dddi fd	e%d
e	de	de
e         fd#Z&dddi fded
e	de	de
e'         fd$Z(d% Z)dddi fd	e%d
e	de	de
e*         fd&Z+d=defd'Z,defd(Z-di fd	ed)e.d*e/d+e0d,e1de*fd-Z2defd.Z3di fd/ed	ed)e.d*e/d+e0d,e1de*fd0Z4di fd/ed	e%de*fd1Z5di fd2e
e         d	e%fd3Z6di fd	e%fd4Z7defd5Z8defd6Z9defd7Z:d8 Z;defd9Z<defd:Z=defd;Z> xZ?S )>okxc                 B   |                      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iddiddidddidddiddiddiddiddidd ii dd!
| j        d"d#d$          S )%NwsTwatchTickerwatchTickerswatchOrderBookwatchTradeswatchTradesForSymbolswatchOrderBookForSymbolswatchBalance
watchOHLCVwatchOHLCVForSymbolswatchOrderswatchMyTradeswatchPositionscreateOrderWseditOrderWscancelOrderWscancelOrdersWscancelAllOrdersWszwss://ws.okx.com:8443/ws/v5zwss://wspap.okx.com:8443/ws/v5)apitestdepthbooksspotchanneltickerstypeANYopbatch-ordersamend-order)
r    r$   r   r   r'   r(   r*   r+   r   checksumi N  )ping	keepAlive)hasurlsoptions	streaming)deep_extendsuperr   describer<   )self	__class__s    R/var/www/html/crypto-bot/backend/venv/lib/python3.11/site-packages/ccxt/pro/okx.pyrD   zokx.describe   s   c4 0 0 9 9 ; ;dt  !$	
 t ( +D  d ' t   !$   t   !" !$#$ $T% , 7 :	 B W1#4 !'y  y! E  E" ." -  !c2 2l 	"	 aV>
 V>
 V V V	    publicr4   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 businessrI   r/   r   candleorders-algoz	/businessz/publicz/private)r@   r?   find)rE   r4   access	isSandboxsandboxSuffix
isBusinessisPublicurls           rG   get_urlzokx.get_urlm   s    L/	,5=((2
*
h&it$ 	3',,x002557m;S;S$}44 	3?]22Z-//rH   Nsymbolsc                   K   |                                   d {V  || j        }|                     |          }|                     ||          }|}g }|dd                    |          z   z  }t          dt          |                    D ]K}|                     ||                   }	||	d}
|                    | 	                    |
|                     Ld|d}| 
                    ||||           d {V S )N::,r   r4   instId	subscriber8   args)load_marketsrY   market_symbolsrX   joinrangelen	market_idappendextendwatch)rE   rR   r4   rY   paramsrW   messageHashra   imarketIdargrequests               rG   subscribe_multiplezokx.subscribe_multiplez   s*     !!!!!!!!!?lG%%g..ll7F++tchhw////q#g,,'' 	2 	2A~~gaj11H"" C KKC001111
 
 ZZ[';GGGGGGGGGrH   c                 >  K   |                                   d {V  |                     ||          }d|i}|.|                     |          }|d|d         z   z  }|d         |d<   d|                     ||          gd}	|                     |||	|           d {V S )Nr4   :idr^   r_   r`   )rb   rX   marketrB   rj   )
rE   rR   rl   r4   symbolrk   rW   firstArgumentru   rp   s
             rG   r_   zokx.subscribe   s      !!!!!!!!!ll7F++w
 [[((F3--K&,TlM(#  77
 
 ZZ[';GGGGGGGGGrH   rv   sincelimitreturnc                 D   K   |                      |g|||           d{V S )  
        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)rE   rv   rx   ry   rk   s        rG   watch_tradeszokx.watch_trades   s6       22F8UE6RRRRRRRRRrH   c                   K   t          |          }|dk    rt          | j        dz             |                                  d{V  |                     |          }d}g }g }t          dt          |                    D ]T}	||	         }
|                    |dz   |
z              |                     |
          }||d}|                    |           Ud|d}|                     |d	          }| 	                    ||||           d{V }| j
        rB|                     |d          }|                     |d
          }|                    ||          }|                     |||dd          S )r|   r   z> watchTradesForSymbols() requires a non-empty array of symbolsNtradesrs   r]   r_   r`   rI   rv   	timestampT)rf   r   rt   rb   rc   re   rh   rg   rX   watch_multiple
newUpdates
safe_valuesafe_stringgetLimitfilter_by_since_limit)rE   rY   rx   ry   rk   symbolsLengthr4   topicsmessageHashesrm   rv   rn   topicrp   rW   r   firsttradeSymbols                     rG   r}   zokx.watch_trades_for_symbols   s      GA#DG.n$nooo!!!!!!!!!%%g..q#g,,'' 	! 	!AQZF  3!7888~~f--H"" E MM%    
 
 ll7H--**3wVVVVVVVV? 	8OOFA..E**5(;;KOOK77E))&%TRRRrH   clientc                 d   |                      |di           }|                     |d          }|                     |d          }|                     |          }|                      |dg           }|                     | j        dd          }t          dt          |                    D ]}	|                     ||	                   }
|dz   |z   }|                      | j        |          }|t          |          }|| j        |<   |
                    |
           |                    ||           d S )	Nro   r4   r^   datatradesLimit  r   rs   )r   r   safe_symbolsafe_integerr@   re   rf   parse_trader   r   rh   resolve)rE   r   messagero   r4   rn   rv   r   r   rm   traderl   storeds                rG   handle_tradeszokx.handle_trades   s.     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 	0rH   c                    K   d}|                      |ddd          \  }}||d<   |                     |g|           d{V }|                     ||          S )a  
        :see: 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   r4   r5   )handle_option_and_paramswatch_tickersr   )rE   rv   rk   r4   tickers        rG   watch_tickerzokx.watch_ticker   sr       77yZcdd#y))6(F;;;;;;;;vv...rH   c                   K   |                      |          rt          | j        dz             d}|                     |ddd          \  }}|                     d|||           d{V }| j        r|S |                     | j        d|          S )a  
        :see: 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>`
        z( watchTickers requires a list of symbolsNr   r4   r5   rI   rv   )is_emptyr   rt   r   rq   r   filter_by_arrayr5   )rE   rY   rk   r4   
newTickerss        rG   r   zokx.watch_tickers  s       ==!! 	Z#DG.X$XYYY77PY[dee228WgvVVVVVVVV
? 	##DL(GDDDrH   c                    |                      |di           }|                     |d          }|                      |dg           }g }t          dt          |                    D ]D}|                     ||                   }|d         }	|| j        |	<   |                    |           E|                     ||dz             }
t          dt          |
                    D ]}|
|         }|                    d          }|d         }|                    d          }| 	                    |d|          }t          |                                          }t          |          }|dk    r|                    ||           |S )	Nro   r4   r   r   rv   r[      r\   )r   r   re   rf   parse_tickerr5   rh   find_message_hashessplitr   listkeysr   )rE   r   r   ro   r4   r   r   rm   r   rv   r   rl   partssymbolsStringrY   r5   tickersSymbols
numTickerss                     rG   handle_tickerzokx.handle_ticker  sz   4 oogub11""3	22w33
q#d))$$ 	& 	&A&&tAw//FH%F#)DL f%%%%004HHq#m,,-- 		5 		5A'*K%%d++E!!HM#))#..G**:xIIG!',,..11N^,,JA~~w444rH   1mc                 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
        NrN   rI   r   T)rb   rv   r   
timeframesr_   r   r   r   )	rE   rv   	timeframerx   ry   rk   intervalnameohlcvs	            rG   watch_ohlcvzokx.watch_ohlcvD  s       !!!!!!!!!V$$##DOY	JJ("nnXtT66JJJJJJJJ? 	2NN6511E))%q$GGGrH   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   zu watchOHLCVForSymbols() requires a an array of symbols and timeframes, like  [['BTC/USDT', '1m'], ['LTC/USDT', '5m']]Nr   rN   r]   multi:rs   r_   r`   rI   T)rf   
isinstancer   r   rt   rb   re   rg   r   r   rh   rX   r   r   r   r   create_ohlcv_object)rE   r   rx   ry   rk   r   r   r   rm   symbolAndTimeframesymtfrn   r   r4   r   rp   rW   rv   r   candlesfiltereds                         rG   watch_ohlcv_for_symbolszokx.watch_ohlcv_for_symbolsW  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DrH   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 )Nro   r4   r   r^   rv   rN   rL   r   
OHLCVLimitr   rs   rt   r   )r   r   safe_marketreplacefind_timeframere   rf   parse_ohlcvohlcvsr   r@   r   rh   r   )rE   r   r   ro   r4   r   rn   ru   rv   r   r   rm   parsedr   ry   rl   messageHashForMultis                    rG   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rH   c                 B   K   |                      |g||           d{V S )a  
        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
        :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)rE   rv   ry   rk   s       rG   watch_order_bookzokx.watch_order_book  s4      > 66xOOOOOOOOOrH   c                 
  K   |                                   d{V  |                     |          }|                     | j        di           }|                     |dd          }|2|dk    rd}n)|dk    r	|dk    rd}n|d	k    rd}n|d
k    rd}n|dk    rd}|dk    s|dk    r|                     ddi           d{V  g }g }t          dt          |                    D ]T}||         }	|                    |dz   |	z              | 	                    |	          }
||
d}|                    |           Ud|d}| 
                    |d          }|                     ||||           d{V }|                                S )a  
        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
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        Nr    r1   r2   r   bbo-tbt   books5  2   books50-l2-tbti  books-l2-tbtrR   rI   r   rs   r]   r_   r`   )rb   rc   r   r@   r   authenticatere   rf   rh   rg   rX   r   ry   )rE   rY   ry   rk   r@   r1   r   r   rm   rv   rn   r   rp   rW   	orderbooks                  rG   r   z okx.watch_order_book_for_symbols  s      !!!!!!!!!%%g..//$,0@"EE  '7;;zz!uzz #"($&^##2B)B)B##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	   rH   c                     |                      |d          }|                      |d          }|                    ||           d S )Nr   r   )
safe_floatstore)rE   booksidedeltapriceamounts        rG   handle_deltazokx.handle_delta  sD     q))**uf%%%%%rH   c                 ~    t          dt          |                    D ]}|                     |||                    d S )Nr   )re   rf   r   )rE   r   deltasrm   s       rG   handle_deltaszokx.handle_deltas  sH    q#f++&& 	3 	3Ahq	2222	3 	3rH   c                    |                      |dg           }|                      |dg           }|d         }|d         }|                     ||           |                     ||           |                     | j        dd          }	|	rt	          |          }
t	          |          }g }t          dd          D ]}||k     rh|                    |                     ||         d                              |                    |                     ||         d                              ||
k     rh|                    |                     ||         d                              |                    |                     ||         d                              d                    |          }| 	                    |d          }| 
                    |d          }||k    r-t          | j        d	z             }|                    ||           | 	                    |d
          }||d<   |                     |          |d<   |S )Nasksbidsr;   Tr      r   rs   z invalid checksumtsr   datetime)r   r   	safe_boolr@   rf   re   rh   number_to_stringrd   r   crc32r   rt   rejectiso8601)rE   r   r   r   rl   r   r   
storedAsks
storedBidsr;   
asksLength
bidsLengthpayloadArrayrm   payloadresponseChecksumlocalChecksumerrorr   s                      rG   handle_order_book_messagezokx.handle_order_book_message  s)   " w33w33v&
v&
:t,,,:t,,,>>$,
DAA 	2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=00$TW/B%BCCe[111%%gt44	!*	+ $Y 7 7	*rH   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<   |                     ||||           |	                    ||           ^n@|dk    rm|	| j        v rc| j        |	         }t	          dt          |                    D ]8}||         }|                     ||||           |	                    ||           9n|dk    s|dk    r|                      | j        |	          }||                     i |          }|| j        |	<   t	          dt          |                    D ]f}||         }|                     |d          }| 
                    ||	|dddd          }|                    |           |	                    ||           g|S )Nro   r4   actionr   r^   rv   r   r   r   r   )r   r2   r   r   r   rs   snapshotr   updater   r   r   r   r   )r   r   r   r   re   rf   
order_book
orderbooksr   r   parse_order_bookreset)rE   r   r   ro   r4   r   r   rn   ru   rv   depthsry   rl   rm   r   r   r   r   s                     rG   handle_order_bookzokx.handle_order_book5  s   l oogub11""3	22!!'844w33##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ZZZNN9k::::!!w)';';@@I  OOB66	&/DOF#1c$ii(( 7 7a --fd;;	00FTZ\]_`aa)))y+6666rH   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 S )NrR   privateusersauthenticatedGETz/users/self/verifybase64login)apiKey
passphraser   signr`   )check_required_credentialsr   omitrX   r   futurer   subscriptionsstrsecondshmacencodesecrethashlibsha256r  passwordri   rj   )rE   rk   rR   rW   rl   r   r  r  r   methodpathauth	signature	operationrp   r   s                   rG   r   zokx.authenticate  sp     '')))!!&(I>>6H:..ll7F++%S!!{++(<kJJ DLLNN++IF'Dv%,D		$++d"3"3T[[5M5Mw~_ghhII #'+&*m%. )	 
 
G kk'622GJJsK+>>>||||||rH   c                    K   |                                   d{V  |                                  d{V  |                     dddd|           d{V S )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)rb   r   r_   )rE   rk   s     rG   watch_balancezokx.watch_balance  s|       !!!!!!!!!!!!!!!!!!^^Iy)T6RRRRRRRRRrH   c                 n   |                      |di           }|                     |d          }d}|                     |          }|                      | j        |i           }|                     ||          }|                     |          | j        |<   |                    | j        |         |           d S )Nro   r4   r3   )r   r   parseTradingBalancebalancerB   safe_balancer   )	rE   r   r   ro   r4   r6   r$  
oldBalance
newBalances	            rG   handle_balancezokx.handle_balance  s    X oogub11""3	22**733__T\4<<
%%j'::
!..z::Tt|D)733333rH   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 )NinfofillTime
fillFeeCcyexecTyperL   Trv   tradeIdrt   r6   takermakersidefillPxfillSzcostfillFee)r5  currency)r*  r   r   rv   rt   orderr6   takerOrMakerr2  r   r   r5  fee)r   r   r   
safe_trader   safe_numbersafe_currency_code)rE   r8  ru   r*  r   feeMarketIdisTakers          rG   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@@  
  
" #  	rH   c           
        K   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
        :see: 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.stop]: 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]{@link https://docs.ccxt.com/#/?id=trade-structure
        Nr(   r6   r7   stopFrR   rM   r  rP   orders
::myTradesrv   r[   r  futuresSPOTMARGINinstTypeT)r   r   r  rb   r   ru   upperhandle_margin_mode_and_paramsr_   ri   r   r   filter_by_symbol_since_limit)rE   rv   rx   ry   rk   r6   isStopr4   rl   ru   uppercaseType
marginModerp   rC  s                 rG   watch_my_tradeszokx.watch_my_trades-  s      44V_fV[\\f666F8,,!!!!!!!!!+N::Y OPPPPPPPPP#)7--x,[[((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TrH   c           	        K   |                                   d{V  |                     |           d{V  |                     |          }ddi}d}d}|Bddd}|g}	d|	d}
|                     |d          }|                     |||
|           d{V }n2|                     d|||                     ||                     d{V }| j        r|S |                     | j	        |||d	          S )
a  
        :see: 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 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>`
        NrH  r7   	positions)r4   rH  r_   r`   r  T)
rb   r   rc   rX   rj   rq   ri   r   filter_by_symbols_since_limitrQ  )rE   rY   rx   ry   rk   rp   r4   newPositionsro   ra   nonSymbolRequestrW   s               rG   watch_positionszokx.watch_positionsY  s_      !!!!!!!!!'''''''''%%g..
 ?&! C 5D!    ,,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]^^^rH   c                 <   |                      |di           }|                     |dd          }|                      |dg           }| j        t                      | _        | j        }g }t	          dt          |                    D ]I}||         }	|                     |	          }
|                    |
           |                    |
           J|                     ||dz             }t	          dt          |                    D ]}||         }|	                    d          }|d         }|	                    d          }| 
                    |d	|d
          }|                     |          s|                    ||           |                    ||           d S )Nro   r4   rL   r   r   r[   r   r\   rv   F)r   r   rQ  r   re   rf   parse_positionrh   r   r   r   r   r   )rE   r   r   ro   r4   r   cacherS  rm   rawPositionpositionr   rl   r   r   rY   rQ  s                    rG   handle_positionszokx.handle_positions{  s   F oogub11""3	266w33>!577DNq#d))$$ 	# 	#Aq'K**;77H)))LL""""004HHq#m,,-- 	7 	7A'*K%%d++E!!HM#))#..G,,\8WeTTI==++ 7y+666|W-----rH   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
        :see: 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.stop]: 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>`
        Nr'   r6   r7   rB  triggerFrR   rM   r  rv   r  rE  rF  rG  rH  rP   rC  T)r   safe_value_2r  rb   r   ru   rI  rJ  r_   ri   r   r   rK  )rE   rv   rx   ry   rk   r6   rL  ru   rM  rN  rp   r4   rC  s                rG   watch_orderszokx.watch_orders  s      44V]FTYZZf""669eDD6FI#677!!!!!!!!!+N::Y OPPPPPPPPP[[((FH%F&>D8D


!??vVV
FF""% (
 $*7--x~~i'64;;W^`fKgKghhhhhhhh? 	3OOFE22E00tTTTrH   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 )Nro   r4   r   r   ordersLimitr   rP   rv   rt   rs   )handle_my_tradesr   r   rf   r   r@   rC  r   triggerOrdersparse_ordersre   rh   ru   r   )rE   r   r   subscriptionro   r4   rC  ordersLengthry   r   	marketIdsr   rm   r8  rv   ru   rl   s                    rG   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 4rH   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 )Nro   r4   r   r   r/  rL   r   r   rv   TrD  r[   )r   r   re   rf   parse_orderrh   myTradesr   r@   r   r@  r   r   r   rC  )rE   r   r   ro   r4   	rawOrdersfilteredOrdersrm   rawOrderr/  r8  tradesLengthry   rk  rY   rawTrader   rv   rl   tradeSymbolssymbolMessageHashs                        rG   rb  zokx.handle_my_tradesN  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;(9::::	; 	;rH   r6   r2  r   r   c                 |  K   |                                   d{V  |                                  d{V  |                     dd          }t          |                                           }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  
        :see: 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 fullfilled, 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*   r8   r9   ordTyper]  conditionalocomove_order_stopicebergtwapzw createOrderWs() does not support algo trading. self.options["createOrderWs"]["op"] must be either order or batch-orderr8  z createOrderWs() does not support algo trading. self.options["createOrderWs"]["op"] must be either order or privatePostTradeOrder or privatePostTradeOrderAlgort   r8   ra   )rb   r   rX   r  noncer   create_order_requestr   r   rt   rj   )rE   rv   r6   r2  r   r   rk   rW   rl   r8   ra   rt  rp   s                rG   create_order_wszokx.create_order_ws  s      !!!!!!!!!!!!!!!!!!ll9i00$**,,''226?DR`aa
F((tVUFSS""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GrH   c                    |                      |d          }|                     |dg           }|                     |dd          }|                     |          rM|                      |d          }|                     |          }|                     d d |j        |d ||d d 	  	         |                     |d d d           }|                     |di           }|	                    ||           d S )Nrt   r   sCode0r8   r   )
r   r   	filter_byr   jsonhandle_errorsrW   rd  	safe_dictr   )	rE   r   r   rl   ra   r  	stringMsgrC  r   s	            rG   handle_place_orderszokx.handle_place_orders  s    & &&w55w33~~dGS11== 	g%%gt44F		'**ItT6:vtYPY[_aefff""4tT::vq"--uk*****rH   rt   c           	        K   |                                   d{V  |                                  d{V  |                     dd          }t          |                                           }	d}
|                     |ddd          \  }
}|                     |||||||          }|	|
|gd}|                     ||	|                     ||          |	           d{V S )aA  
        edit a trade order
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-trade-ws-amend-order
        :see: 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 fullfilled, 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+   r8   r:   rz  )	rb   r   rX   r  r{  r   edit_order_requestrj   ri   )rE   rt   rv   r6   r2  r   r   rk   rW   rl   r8   ra   rp   s                rG   edit_order_wszokx.edit_order_ws  s      !!!!!!!!!!!!!!!!!!ll9i00$**,,''226=$P]^^
F&&r64vufUUF
 

 ZZ[$++gv2N2NP[\\\\\\\\\rH   c                 &  K   |t          | j        dz             |                                  d{V  |                                  d{V  |                     dd          }t          |                                           }|                     |dd          }|                     |ddg          }d| 	                    |          i}|||d<   n||d<   |d| 
                    ||          gd	}|                     ||||           d{V S )
a  
        :see: 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-orderrz  )r   rt   rb   r   rX   r  r{  safe_string_2r  rg   ri   rj   )	rE   rt   rv   rk   rW   rl   r  ro   rp   s	            rG   cancel_order_wszokx.cancel_order_ws  sH      >TW'TTUUU!!!!!!!!!!!!!!!!!!ll9i00$**,,''**69oNN6OY#?@@dnnV,,
 $*C	NNCL [[f--.
 

 ZZ[';GGGGGGGGGrH   idsc                 f  K   t          |          }|dk    rt          | j        dz             |t          | j        dz             |                                  d{V  |                                  d{V  |                     dd          }t          |                                           }g }t          d|          D ]5}| 	                    |          ||         d}	|
                    |	           6|d|d	}
|                     |||                     |
|          |           d{V S )
a  
        :see: 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-ordersrz  )rf   r   rt   rb   r   rX   r  r{  re   rg   rh   rj   rB   )rE   r  rv   rk   	idsLengthrW   rl   ra   rm   ro   rp   s              rG   cancel_orders_wszokx.cancel_orders_ws!  sf      HH	r>>TW'YYZZZ>TW'UUVVV!!!!!!!!!!!!!!!!!!ll9i00$**,,''q)$$ 	 	A..00Q C KK'
 

 ZZ[$2B2B7F2S2SU`aaaaaaaaarH   c                   K   |t          | j        dz             |                                  d{V  |                                  d{V  |                     |          }|d         dk    rt          | j        dz             |                     dd          }t          |                                           }|d|                     d|d	         d
|          gd}| 	                    ||||           d{V S )a  
        :see: 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 argumentr6   optionzgcancelAllOrdersWs is only applicable to Option in Portfolio Margin mode, and MMP privilege is required.r  mass-cancelOPTIONrt   )rH  
instFamilyrz  )
r   rt   rb   r   ru   rX   r  r{  ri   rj   )rE   rv   rk   ru   rW   rl   rp   s          rG   cancel_all_orders_wszokx.cancel_all_orders_wsA  sE      >TW'XXYYY!!!!!!!!!!!!!!!!!!V$$&>X%%TW  (Q  Q  R  R  Rll9i00$**,,''[[$$Tl" "   
 
 ZZ[';GGGGGGGGGrH   c                     |                      |d          }|                     |dg           }|                    ||           d S )Nrt   r   )r   r   r   )rE   r   r   rl   r   s        rG   handle_cancel_all_orderszokx.handle_cancel_all_orders\  sH     &&w55w33t[)))))rH   c                     |S N rE   r   r   s      rG   handle_subscription_statuszokx.handle_subscription_statusn  s	     rH   c                 f    |                      |j        d          }|                    d           d S )Nr  T)r   rE  r   )rE   r   r   r  s       rG   handle_authenticatezokx.handle_authenticatev  s1     AAtrH   c                     dS )Nr<   r  )rE   r   s     rG   r<   zokx.ping}  s	     vrH   c                 8    |                                  |_        |S r  )millisecondslastPongr  s      rG   handle_pongzokx.handle_pong  s    ++--rH   c                    |                      |d          }	 |r|| j        dz   |                     |          z   }|                     | j        d         ||           |                     |d          }|"|                     | j        d         ||           np# t          $ rc}t          |t                    r/d}|
                    ||           ||j        v r|j        |= Y d }~dS |
                    |           Y d }~nd }~ww xY w|S )Ncode exactmsgbroadr  F)r   rt   r  throw_exactly_matched_exception
exceptionsr   throw_broadly_matched_exception	Exceptionr   r   r   r  )rE   r   r   	errorCodefeedbackmessageStringerl   s           rG   handle_error_messagezokx.handle_error_message  s7   
 %%gv66		! l7S=499W+=+==44T_W5MyZbccc $ ? ? ,889QS`bjkkk 	! 	! 	!!011 !-a---&"666,[9uuuuua        	! s   A>B 
D!>C?%C??Dc                    |                      ||          sd S |dk    r|                     ||           d S |                     |dd          }|[| j        | j        | j        | j        | j        | j        | j        | j        d}|                     ||          }| |||           d S d S |                     |di           }|                     |d          }| j	        | j	        | j	        | j	        | j	        | j
        | j        | j
        | j
        | j
        | j        | j        | j        | j        d}|                     ||          }|3|                    d          d	k    r|                     ||           d S d S  |||           d S )
Npongeventr8   )r
  r_   r8  r9   r:   zbatch-amend-ordersr  r  ro   r4   )r   r2   r   r   r   r5   rQ  zindex-tickerszsprd-tickerszblock-tickersr   r   rC  rP   rN   r   )r  r  r  r  r  r  r  r   r   r  r   r[  r   r(  rh  rQ   r   )rE   r   r   r  methodsr  ro   r4   s           rG   handle_messagezokx.handle_message  s   ((99 	FP fVW---F ""7GT:: 1!<1 $ 8#7&*&> $ 8#< G __We44F!vw''''' "! //'5"55C&&sI66G1/0"&"8 $ 6-!2!%!3 $ 2!%!3,.,#1 G" __Wg66F~<<))Q..%%fg66666 /. vw'''''rH   )rI   r  )@__name__
__module____qualname__rD   r  rX   r   rq   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   rO  r   rU  r[  r
   r_  rh  rb  r   r   floatr	   r}  r  r  r  r  r  r  r  r  r<   r  r  r  __classcell__)rF   s   @rG   r   r      s       W W W W Wr0 0s 0 0 0 0 LPXZ H H H H H H, 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0F 0 0 0 0@ 68 / / /F / / / / 6:" E E7 E E E E E$.F . . . .` 8<$]ajl H H HC HWZ Hquvzq{ H H H H& aesw  AC %E %E$tCy/ %EZ] %Emp %E %E %E %EN)M6 )M )M )M )MV @DB P PS P PS\ P P P PB SW_a *! *!$s) *!C *!fo *! *! *! *!X& & &3 3 3, , , , ,\@ @ @ @ @D )+    > *, S S S S S S34V 34 34 34 34j   0 37TX\eg *U *UC *Us *URU *Ulpqvlw *U *U *U *UX 8<$]ajl  _  _W  _C  _WZ  _quv~q  _  _  _  _DX. X. X.t 04$UYbd (U (U (UC (Us (Uimnsit (U (U (U (UTM4 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@+& + + + +@ w{  DF ] ]c ]3 ]i ]y ]bg ]ps ]  KP ] ] ] ]8 <@ H H HS Hu H H H H@ DHPR b b$s) bS b b b b@ 8<B H H H H H H6*v * * * *$    &      
&    6    0Y(V Y( Y( Y( Y( Y( Y( Y( Y(rH   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   !ccxt.async_support.base.ws.clientr   typingr   ccxt.base.errorsr   r   r   r   async_supportr   r  rH   rG   <module>r     s       A  A  A  A  A  A  A  A  A  A  A  A  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G 4 4 4 4 4 4       0 0 0 0 0 0 . . . . . . ' ' ' ' ' ' ) ) ) ) ) )e( e( e( e( e($

  e( e( e( e( e(rH   