
    ei+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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& d dl'm(Z(  G d dej)        j*                  Z*dS )    N)
ArrayCacheArrayCacheBySymbolByIdArrayCacheBySymbolBySideArrayCacheByTimestamp)AnyBalancesBoolIntLiquidationMarket
MarketTypeNumOrder	OrderBookOrderRequest	OrderSide	OrderTypePositionStrStringsTickerTickersTrade)Client)List)ExchangeError)AuthenticationError)ArgumentsRequired)
BadRequest)NotSupported)ChecksumError)Precisec                   $    e Zd Zdef fdZdi fdedededede	f
d	Z
i fd
ee         fdZdi fdefdZdi fdedefdZddi fdedededede	de	fdZdi fdedef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ddi fdededededee         f
dZdi fdededefdZi fdedefdZdefdZdefdZd Zd Z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i fd e#de$fd#Z'defd$Z(ddi fd e#d%ede$fd&Z)d'ede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-Z0d.ddi fded/edededee1         f
d0Z2defd1Z3dddi fdedededee+         fd2Z4defd3Z5i fde6fd4Z7defd5Z8dddi fd e#dededee9         fd6Z:dUded e#fd7Z;d8 Z<d9 Z=dddi fdedededee         fd:Z>defd;Z?ddi fdedededee@         fd<ZAddi fd ee         dededee@         fd=ZBdefd>ZCdUd?ZDdedeEfd@ZFdUdefdAZGdefdBZHdefdCZIdefdDZJdE ZKdFeLfdGZMdVdeNfdIZOdJefdKZPdL ZQi dfdMZRi fdNZSi fdOZTdP ZUdefdQZVdUdRefdSZWdVdTZX xZYS )Wgatereturnc                 l   |                      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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i d%dd&dd'dd(dd)dd*dd+dd,dd-dd.dd/dd0dd1dd2dd3dd4dd5d6d7d8d9d:d;d9d<d=d9d>d?d@d9d?d@d9dAdBd9dCdDdEdEi i i dFdGidHdIdJddKdLdMdNdddOdP	dt          t          t
          t
          t
          dQi dRidS          S )TNwsTcancelAllOrdersWscancelOrderWscreateMarketBuyOrderWithCostWscreateMarketOrderWscreateMarketOrderWithCostWsFcreateMarketSellOrderWithCostWscreateOrderWscreateOrdersWscreatePostOnlyOrderWscreateReduceOnlyOrderWscreateStopLimitOrderWscreateStopLossOrderWscreateStopMarketOrderWscreateStopOrderWscreateTakeProfitOrderWscreateTriggerOrderWseditOrderWsfetchOrderWsfetchOrdersWsfetchOpenOrdersWsfetchClosedOrdersWswatchOrderBookwatchBidsAskswatchTickerwatchTickerswatchTradeswatchTradesForSymbolswatchMyTrades
watchOHLCVwatchBalancewatchOrderswatchLiquidationswatchLiquidationsForSymbolswatchMyLiquidationswatchMyLiquidationsForSymbolswatchPositionsunWatchTickerunWatchTickersunWatchOHLCVunWatchOHLCVForSymbolsunWatchOrderBookunWatchOrderBookForSymbolsunWatchTradesunWatchTradesForSymbolsunWatchMyTradesunWatchOrdersunWatchPositionsunWatchMarkPricesunWatchMarkPricezwss://ws.gate.io/v4zwss://api.gateio.ws/ws/v4/z wss://fx-ws.gateio.ws/v4/ws/usdtzwss://fx-ws.gateio.ws/v4/ws/btc)usdtbtcz)wss://fx-ws.gateio.ws/v4/ws/delivery/usdtz(wss://fx-ws.gateio.ws/v4/ws/delivery/btcz"wss://op-ws.gateio.live/v4/ws/usdtz!wss://op-ws.gateio.live/v4/ws/btc)r'   spotswapfutureoptionz(wss://fx-ws-testnet.gateio.ws/v4/ws/usdtz'wss://fx-ws-testnet.gateio.ws/v4/ws/btcz*wss://op-ws-testnet.gateio.live/v4/ws/usdtz)wss://op-ws-testnet.gateio.live/v4/ws/btc)r\   r]   r^   )apitest  nametickers100ms
      )intervalsnapshotDelaysnapshotMaxRetrieschecksumrY   zspot.balances)settler[   )fetchPositionsSnapshotawaitPositionsSnapshot)	tradesLimit
OHLCVLimitwatchTradesSubscriptionswatchTickerSubscriptionswatchOrderBookSubscriptionsr?   r=   rE   rK   )124611)exactbroad)hasurlsoptions
exceptions)deep_extendsuperr$   describer   r   )self	__class__s    K/var/www/html/volatility/venv/lib/python3.11/site-packages/ccxt/pro/gate.pyr   zgate.describe   s    dD 1 1 : : < <3d3#T3  3 1$	3
 &t3 .u3 253  3 !$3 (3 *43 )$3 (3 *53 $T3  *4!3" '#3 3$ t%3& '3(  )3* $T+3, &t-3. !$/30  132 t334 536 t738 (93:  ;3< d=3> ?3@ tA3B $UC3D .uE3 3 3F &tG3H 0I3J !$K3L  M3N !%O3P Q3R )%S3T #DU3V -eW3X  Y3Z *4[3\ "5]3^  _3` #Ea3b $Uc3d #Ee3 3l 08 B@ 
 !LI 
 !EB  $ !KH 
 !KH 
 !MJ  # B  $",.,./1I  !(%'*+ $	# # %+! !
 /3.2# #' 2 ''001   	 	[y?
 y?
 y y y	    Nsymboltypesideamountpricec                   K   |                                   d{V  |                     |          }|d         }|                     |          }|dz   }	|                     |          }
d|d<   |                     ||||||          }|                     |
|           d{V  |                     |
||	           d{V }|                     ||          }|S )a	  

        https://www.gate.io/docs/developers/apiv4/ws/en/#order-place
        https://www.gate.io/docs/developers/futures/ws/en/#order-place

        Create an order on the exchange
        :param str symbol: Unified CCXT market symbol
        :param str type: 'limit' or 'market' *"market" is contract only*
        :param str side: 'buy' or 'sell'
        :param float amount: the amount of currency to trade
        :param float [price]: *ignored in "market" orders* the price at which the order is to be fulfilled at in units of the quote currency
        :param dict [params]:  extra parameters specific to the exchange API endpoint
        :param float [params.stopPrice]: The price at which a trigger order is triggered at
        :param str [params.timeInForce]: "GTC", "IOC", or "PO"
        :param float [params.stopLossPrice]: The price at which a stop loss order is triggered at
        :param float [params.takeProfitPrice]: The price at which a take profit order is triggered at
        :param str [params.marginMode]: 'cross' or 'isolated' - marginMode for margin trading if not provided self.options['defaultMarginMode'] is used
        :param int [params.iceberg]: Amount to display for the iceberg order, Null or 0 for normal orders, Set to -1 to hide the order completely
        :param str [params.text]: User defined information
        :param str [params.account]: *spot and margin only* "spot", "margin" or "cross_margin"
        :param bool [params.auto_borrow]: *margin only* Used in margin or cross margin trading to allow automatic loan of insufficient amount if balance is not enough
        :param str [params.settle]: *contract only* Unified Currency Code for settle currency
        :param bool [params.reduceOnly]: *contract only* Indicates if self order is to reduce the size of a position
        :param bool [params.close]: *contract only* Set to close the position, with size set to 0
        :param bool [params.auto_size]: *contract only* Set side to close dual-mode position, close_long closes the long side, while close_short the short one, size also needs to be set to 0
        :param int [params.price_type]: *contract only* 0 latest deal price, 1 mark price, 2 index price
        :param float [params.cost]: *spot market buy only* the quote quantity that can be used alternative for the amount
        :returns dict|None: `An order structure <https://docs.ccxt.com/?id=order-structure>`
        Nr   z.order_placeTtextIsRequired)load_marketsmarketget_type_by_marketget_url_by_marketcreate_order_requestauthenticaterequest_privateparse_order)r   r   r   r   r   r   paramsr   messageTypechannelurlrequestrawOrderorders                 r   create_order_wszgate.create_order_ws   s
     < !!!!!!!!!V$$!--f55.$$V,,#' ++FD$vVV[111111111--c7GDDDDDDDD  622r   ordersc                   K   |                                   d{V  |                     ||          }|d         }|                     |d                   }|d         durt          | j        dz             |                     |          }|dz   }|                     |          }|                     ||           d{V  |                     |||           d{V }	| 	                    |	|          S )a  
        create a list of trade orders

        https://www.gate.io/docs/developers/futures/ws/en/#order-batch-place

        :param Array orders: list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
        :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   r\   Tz1 createOrdersWs is not supported for swap marketsz.order_batch_place)
r   createOrdersRequestr   r    idr   r   r   r   parse_orders)
r   r   r   r   
firstOrderr   r   r   r   	rawOrderss
             r   create_orders_wszgate.create_orders_ws   s      !!!!!!!!!**66::AY
Z122&>%%tw)\\]]]--f55 44$$V,,[111111111..sGWEEEEEEEE	  F333r   c                   K   |                                   d{V  |dn|                     |          }|                     |dd          }|                     |          }|dz   }|                     |dd|          \  }}|                     |          }|                     |ddg          }|                     d||          \  }}	|dk    r|                     |||	          n| 	                    |||	          \  }
}| 
                    ||           d{V  |                     ||                     |
|          |           d{V }|                     ||          S )	a  
        cancel all open orders

        https://www.gate.com/docs/developers/futures/ws/en/#cancel-matched-open-orders
        https://www.gate.io/docs/developers/apiv4/ws/en/#order-cancel-all-with-specified-currency-pair

        :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
        :param str [params.channel]: the channel to use, defaults to spot.order_cancel_cp or futures.order_cancel_cp
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        Nstoptriggerz.order_cancel_cpr(   r   cancelAllOrdersr[   )r   r   safe_bool_2r   handle_option_and_paramsr   omithandle_market_type_and_paramsmultiOrderSpotPrepareRequestprepareRequestr   r   extendr   )r   r   r   r   r   r   r   r   r   queryr   requestParamsr   s                r   cancel_all_orders_wszgate.cancel_all_orders_ws   s      !!!!!!!!! .t{{6/B/B""669==--f55 2277@SU^`ghh$$V,,6FI#677889JFTZ[[e_cgm_m_m!B!B67TY!Z!Z!Ztx  uH  uH  IO  QU  W\  u]  u][111111111..sDKK4W4WY`aaaaaaaa	  F333r   r   c                   K   |                                   d{V  |dn|                     |          }|                     |g dd          }|                     |g d          }|                     d||          \  }}|dk    s|dk    r|                     |||          n|                     |||          \  }}	|                     |          }
|
dz   }|                     |          }| 	                    ||
           d{V  t          |          |d<   |                     ||                     ||	          |           d{V }|                     ||          S )	a  
        Cancels an open order

        https://www.gate.io/docs/developers/apiv4/ws/en/#order-cancel
        https://www.gate.io/docs/developers/futures/ws/en/#order-cancel

        :param str id: Order id
        :param str symbol: Unified market symbol
        :param dict [params]: Parameters specified by the exchange api
        :param bool [params.trigger]: True if the order to be cancelled is a trigger order
        :returns: An `order structure <https://docs.ccxt.com/?id=order-structure>`
        N)is_stop_orderr   r   FcancelOrderr[   marginz.order_cancelorder_id)r   r   safe_value_nr   r   spotOrderPrepareRequestr   r   r   r   strr   r   r   )r   r   r   r   r   r   r   r   r   r   r   r   r   ress                 r   cancel_order_wszgate.cancel_order_ws   s      !!!!!!!!! .t{{6/B/B##F,P,P,PRWXX6#G#G#GHH88PVWWeZ^bhZhZhlpt|l|l|!=!=fgu!U!U!U  DH  DW  DW  X^  `d  fk  Dl  Dl--f55/$$V,,[111111111!"gg
((dkk'=.Q.QSZ[[[[[[[[V,,,r   c           	        K   |                                   d{V  |                     |          }|                     |||||||          }	|                     |          }
|
dz   }|                     |          }|                     ||
           d{V  |                     ||	|           d{V }|                     ||          S )a^  
        edit a trade order, gate currently only supports the modification of the price or amount fields

        https://www.gate.io/docs/developers/apiv4/ws/en/#order-amend
        https://www.gate.io/docs/developers/futures/ws/en/#order-amend

        :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 [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>`
        Nz.order_amend)r   r   edit_order_requestr   r   r   r   r   )r   r   r   r   r   r   r   r   r   extendedRequestr   r   r   r   s                 r   edit_order_wszgate.edit_order_ws  s        !!!!!!!!!V$$11"fdD&RWY_``--f55.$$V,,[111111111--c?GLLLLLLLL&111r   c                   K   |                                   d{V  |dn|                     |          }|                     |||          \  }}|                     |          }|dz   }|                     |          }	|                     |	|           d{V  |                     |	|                     ||          |           d{V }
|                     |
|          S )a  
        Retrieves information on an order

        https://www.gate.io/docs/developers/apiv4/ws/en/#order-status
        https://www.gate.io/docs/developers/futures/ws/en/#order-status

        :param str id: Order id
        :param str symbol: Unified market symbol, *required for spot and margin*
        :param dict [params]: Parameters specified by the exchange api
        :param bool [params.trigger]: True if the order being fetched is a trigger order
        :param str [params.marginMode]: 'cross' or 'isolated' - marginMode for margin trading if not provided self.options['defaultMarginMode'] is used
        :param str [params.type]: 'spot', 'swap', or 'future', if not provided self.options['defaultMarginMode'] is used
        :param str [params.settle]: 'btc' or 'usdt' - settle currency for perpetual swap and future - market settle currency is used if symbol is not None, default="usdt" for swap and "btc" for future
        :returns: An `order structure <https://docs.ccxt.com/?id=order-structure>`
        Nz.order_status)	r   r   fetchOrderRequestr   r   r   r   r   r   )r   r   r   r   r   r   r   r   r   r   r   s              r   fetch_order_wszgate.fetch_order_ws%  s       !!!!!!!!! .t{{6/B/B!%!7!7FF!K!K--f55/$$V,,[111111111--c4;;w3V3VX_````````&111r   sincelimitc                 D   K   |                      d||||           d{V S )a  
        fetch all unfilled currently open orders

        https://www.gate.io/docs/developers/futures/ws/en/#order-list

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch open orders for
        :param int [limit]: the maximum number of  open orders structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        openNfetch_orders_by_status_wsr   r   r   r   r   s        r   fetch_open_orders_wszgate.fetch_open_orders_ws?  s7       33FFE5RXYYYYYYYYYr   c                 D   K   |                      d||||           d{V S )a:  
        fetches information on multiple closed orders made by the user

        https://www.gate.io/docs/developers/futures/ws/en/#order-list

        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        finishedNr   r   s        r   fetch_closed_orders_wszgate.fetch_closed_orders_wsM  s7       33JuV\]]]]]]]]]r   statusc                 x  K   |                                   d{V  d}|>|                     |          }|d         }|d         durt          | j        dz             |                     |||||          \  }}|                     |dg          }	|                     |          }
|
dz   }|                     |          }|                     ||
           d{V  | 	                    || 
                    |	|          |           d{V }|                     ||          }|                     ||||          S )a  

        https://www.gate.io/docs/developers/futures/ws/en/#order-list

        fetches information on multiple orders made by the user by status
        :param str status: requested order status
        :param str symbol: unified market symbol of the market orders were made in
        :param int|None [since]: the earliest time in ms to fetch orders for
        :param int|None [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.orderId]: order id to begin at
        :param int [params.limit]: the maximum number of order structures to retrieve
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        Nr   r\   TzX fetchOrdersByStatusWs is only supported by swap markets. Use rest API for other marketsrk   z.order_list)r   r   r    r   prepareOrdersByStatusRequestr   r   r   r   r   r   r   filter_by_symbol_since_limit)r   r   r   r   r   r   r   r   r   
newRequestr   r   r   r   r   s                  r   r   zgate.fetch_orders_by_status_ws[  s}      !!!!!!!!![[((FH%Ff~T))"47  .H  $H  I  I  I!%!B!B66SXZ_ag!h!hYYw
33
--f55-$$V,,[111111111..sDKK
M4Z4Z\cdddddddd	""9f5500NNNr   c                   K   |                                   d{V  |                     |          }|d         }|d         }|                     |ddd          \  }}|                     |          }|dz   }	d|z   }
|                     |          }||g}|
d	}|d
k    rd}|d         r$t          |          }|                    |           ||d}|                     ||
||	||           d{V }|                                S )a  
        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://www.gate.com/docs/developers/apiv4/ws/en/#order-book-channel
        https://www.gate.com/docs/developers/apiv4/ws/en/#order-book-v2-api
        https://www.gate.com/docs/developers/futures/ws/en/#order-book-api
        https://www.gate.com/docs/developers/futures/ws/en/#order-book-v2-api
        https://www.gate.com/docs/developers/delivery/ws/en/#order-book-api
        https://www.gate.com/docs/developers/options/ws/en/#order-book-channel

        :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
        Nr   r   r=   rg   rd   .order_book_update
orderbook:d   r|   2   contract)r   r   )	r   r   r   r   r   r   appendsubscribe_publicr   )r   r   r   r   r   marketIdrg   r   r   r   messageHashr   payloadstringLimitsubscription	orderbooks                   r   watch_order_bookzgate.watch_order_book{  sN       !!!!!!!!!V$$!$<77@PR\^eff%--f55 44'&0$$V,,X&=Ei''* 	(e**KNN;'''
 
 //['7TY[ghhhhhhhh	   r   c           
        K   |                                   d{V  |                     |          }|d         }|d         }d}|                     |dd|          \  }}|                     |          }|dz   }d|z   }d	|z   }	|                     |          }
||g}|                     |d
d          }|d         r$t          |          }|                    |           |                     |
d|g|	g|g|||           d{V S )a  
        unWatches 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 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   r   rd   r=   rg   r   r   zunsubscribe:orderbook:r   r   r   r   )	r   r   r   r   r   safe_integerr   r   un_subscribe_public_multiple)r   r   r   r   r   rg   r   r   subMessageHashr   r   r   r   r   s                 r   un_watch_order_bookzgate.un_watch_order_book  sj      !!!!!!!!!V$$!$<88AQS]_ghh&--f55 44*V33f<$$V,,X&!!&'377* 	(e**KNN;'''66sK&T_S`cqbrt{  ~E  GM  N  N  N  N  N  N  N  N  	Nr   clientc                     |                      |d          }|                     |d          }|                     i |          | j        |<   d S )Nr   r   )safe_stringr   
order_book
orderbooks)r   r   messager   r   r   s         r   handle_order_book_subscriptionz#gate.handle_order_book_subscription  sL    !!,99!!,88"&//"e"<"<r   c                    |                      |d          }|                    d          }|                      |d          }|dk    }|rdnd}|                     |d          }|                     |d          }	|                     |d          }
|                      |d	          }|                     |d d
|          }d|z   }|                     | j        ||                     i                     }|                     |d          }|d}|t          |j                  }| 	                    ddd          }|r|nd}||k    rB|j
        |         }|                     |d          }|                     | j        ||||i            |j                            |           d S ||
k    rd S ||	dz
  k    r|                     ||           nl|j
        |= | j        |= | 	                    ddd          }|rCt          | j        dz   |                     |          z             }|                    ||           |                    ||           d S )Nr   .r   r[   r   resultUus_r   noncer=   rh   re   r      rj   T )r   split
safe_valuer   safe_symbolr   r   lencachehandle_optionsubscriptionsspawnload_order_bookr   handle_deltar!   r   orderbook_checksum_messagerejectresolve)r   r   r   r   channelPartsrawMarketTypeisSpot
marketTypedelta
deltaStartdeltaEndr   r   r   storedOrderBookr   cacheLengthrh   
waitAmountr   r   rj   errors                          r   handle_order_bookzgate.handle_order_book  sx   l ""7I66}}S))((q99&(%5VV:
22&&uc22
$$UC00##E3//!!(D#zBB"V+//$/64??SUCVCVWW!!/7;;=K*!/"788 ../?RTUUM*07aJj((%3K@)),@@

4/feUWXXX!((///FhFj1n$$ou5555$[1'))*:JMMH 2%dgmd6U6UV\6]6]&]^^e[11144444r   c                 f   |                      |d          }|d         }|                      |d          }||k     rdS t          dt          |                    D ]I}||         }|                      |d          }|                      |d          }	||dz
  k    r
||	k     r|c S Jt          |          S )Nr   r   r   r   r   )r   ranger   )
r   	orderBookr   r   
firstDeltafirstDeltaStartir	  r
  r  s
             r   get_cache_indexzgate.get_cache_index  s    !!)W551X
++J<<?""2q#e**%% 	 	A!HE**5#66J((44Ha''eh.>.>5zzr   c                 V   t          dt          |                    D ]}||         }t          |t                    r)|                    |                     |                     H|                     |d          }|                     |d          }|                    ||           d S )Nr   pr   )r  r   
isinstancelist
storeArrayparse_bid_ask
safe_floatstore)r   bookSidebidAsksr  bidAskr   r   s          r   handle_bid_askszgate.handle_bid_asks,  s    q#g,,'' 	. 	.AQZF&$'' .##D$6$6v$>$>????4455uf----	. 	.r   c                 r   |                      |d          }||d<   |                     |          |d<   |                      |d          |d<   |                     |dg           }|                     |dg           }|d         }|d	         }|                     ||           |                     ||           d S )
Nt	timestampdatetimer   r   babidsasks)r   iso8601r   r$  )r   r   r	  r'  r+  r,  
storedBids
storedAskss           r   r  zgate.handle_delta6  s    %%eS11	!*	+ $Y 7 7	*!..uc::	'uc2..uc2..v&
v&
Z...Z.....r   c                    K   |                                   d{V  |                     |          }|d         }d|d<   |                     |g|           d{V }|                     ||          S )aj  

        https://www.gate.io/docs/developers/apiv4/ws/en/#tickers-channel
        https://www.gate.com/docs/developers/futures/ws/en/#tickers-api
        https://www.gate.com/docs/developers/delivery/ws/en/#tickers-api

        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
        :returns dict: a `ticker structure <https://docs.ccxt.com/?id=ticker-structure>`
        Nr   r?   callerMethodName)r   r   watch_tickersr   )r   r   r   r   r   s        r   watch_tickerzgate.watch_tickerB  s       !!!!!!!!!V$$!%2!"))6(F;;;;;;;;vv...r   symbolsc                 l   K   |                      |d|                     ddi|                     d{V S )az  

        https://www.gate.io/docs/developers/apiv4/ws/en/#tickers-channel
        https://www.gate.com/docs/developers/futures/ws/en/#tickers-api
        https://www.gate.com/docs/developers/delivery/ws/en/#tickers-api

        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
        :returns dict: a `ticker structure <https://docs.ccxt.com/?id=ticker-structure>`
        r@   methodrc   N%subscribe_watch_tickers_and_bids_asksr   r   r4  r   s      r   r2  zgate.watch_tickersU  sr       ??Y]YdYdfnpyez  }C  ZD  ZD  E  E  E  E  E  E  E  E  	Er   c                 4    |                      d||           d S )Ntickerhandle_ticker_and_bid_askr   r   r   s      r   handle_tickerzgate.handle_tickerc  s"    & 	&&xAAAAAr   c                 l   K   |                      |d|                     ddi|                     d{V S )a$  

        https://www.gate.io/docs/developers/apiv4/ws/en/#best-bid-or-ask-price
        https://www.gate.io/docs/developers/apiv4/ws/en/#order-book-channel
        https://www.gate.com/docs/developers/options/ws/en/#best-bid-or-ask-price

        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>`
        r>   r6  book_tickerNr7  r9  s      r   watch_bids_askszgate.watch_bids_asksx  sr       ??Z^ZeZegoq~f  BH  [I  [I  J  J  J  J  J  J  J  J  	Jr   c                 4    |                      d||           d S )Nbidaskr<  r>  s      r   handle_bid_askzgate.handle_bid_ask  s"    $ 	&&xAAAAAr   r1  c                   K   |                                   d {V  |                     |d|          \  }}|                     |d d          }|                     |d                   }|                     |          }|                     |          }d }|                     ||d          \  }}|                     |          }|dz   |z   }	|                    d          dk    }
|
rdnd}g }t          dt          |                    D ]%}||         }|                    |d	z   |z              &|                     ||||	|           d {V }| j        ri }|||d
         <   |S |
r| j        n| j        }|                     |d
|d          S )Nr1  Fr   r6  r   r?   r;  rD  :r   T)r   handle_param_stringmarket_symbolsr   r   
market_idsr   r   findr  r   r   subscribe_public_multiple
newUpdatesrc   bidsasksfilter_by_array)r   r4  r1  r   r   r   	marketIdschannelNamer   r   isWatchTickersprefixmessageHashesr  r   tickerOrBidAskitemsr   s                     r   r8  z*gate.subscribe_watch_tickers_and_bids_asks  s     !!!!!!!!!#'#;#;FDVXh#i#i &%%gtU;;WQZ((--f55OOG,,	";;FDTV^__V$$V,,#k1)..}==B+9q#g,,'' 	8 	8AQZF  #!67777#==c=R[]dflmmmmmmmm? 	E.<E.*+L!/BT]##FHgtDDDr   
objectNamec                    |                      |d          }|                    d          }|                      |d          }|dk    rdnd}|                     |d          }g }	t          |t                    r|                     |dg           }	n|                     |di           }
|
g}	|dk    }t          dt          |	                    D ]}|	|         }
|                      |
d	          }| 	                    |d d
|          }| 
                    |
|          }|d         }|r|| j        |<   n
|| j        |<   |dz   |z   }|                    ||           d S )Nr   r   r   futuresr   r[   r   r;  r   r   r   rG  )r   r   r   r  r  	safe_list	safe_dictr  r   safe_marketparse_tickerrc   rN  r  )r   rW  r   r   r   partsr  r  r   results	rawTickerisTickerr  r   r   
parsedItemr   r   s                     r   r=  zgate.handle_ticker_and_bid_ask  s   ""7I66c""((22$1Y$>$>ZZV
(33fd## 	"nnWh;;GGw"==I kG(*q#g,,'' 	4 	4A
I''	377H%%hc:FFF**9f==J)F 3'1V$$(2f%$s*V3KNN:{3333	4 	4r   c                 D   K   |                      |g|||           d{V S )a  

        https://www.gate.com/docs/developers/apiv4/ws/en/#public-trades-channel
        https://www.gate.com/docs/developers/futures/ws/en/#trades-api
        https://www.gate.com/docs/developers/delivery/ws/en/#trades-api
        https://www.gate.com/docs/developers/options/ws/en/#public-contract-trades-channel

        get the list of most recent trades for a particular symbol
        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/?id=public-trades>`
        N)watch_trades_for_symbolsr   s        r   watch_tradeszgate.watch_trades  s6       22F8UE6RRRRRRRRRr   c                   K   |                                   d{V  |                     |          }|                     |          }|                     |d                   }|                     |          }|dz   }g }	t          dt          |                    D ]"}
||
         }|	                    d|z              #|                     |          }| 	                    ||	|||           d{V }| j
        rB|                     |d          }|                     |d          }|                    ||          }|                     |||dd          S )a  

        https://www.gate.com/docs/developers/apiv4/ws/en/#public-trades-channel
        https://www.gate.com/docs/developers/futures/ws/en/#trades-api
        https://www.gate.com/docs/developers/delivery/ws/en/#trades-api
        https://www.gate.com/docs/developers/options/ws/en/#public-contract-trades-channel

        get the list of most recent trades for a particular symbol
        :param str[] symbols: 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>`
        Nr   .tradestrades:r   r'  T)r   rI  rJ  r   r   r  r   r   r   rL  rM  r   r   getLimitfilter_by_since_limit)r   r4  r   r   r   rP  r   r   r   rT  r  r   r   tradesfirsttradeSymbols                   r   rd  zgate.watch_trades_for_symbols  sn      !!!!!!!!!%%g..OOG,,	WQZ((--f55	)q#g,,'' 	5 	5AQZF  V!34444$$V,,55c=)U\^deeeeeeee? 	8OOFA..E**5(;;KOOK77E))&%TRRRr   c           
        K   |                                   d{V  |                     |          }|                     |          }|                     |d                   }|                     |          }|dz   }g }g }t          dt          |                    D ]:}	||	         }
|                    d|
z              |                    d|
z              ;|                     |          }| 	                    |d||||||           d{V S )aP  
        get the list of most recent trades for a particular symbol
        :param str[] symbols: 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>`
        Nr   rg  rh  zunsubscribe:trades:rk  )
r   rI  rJ  r   r   r  r   r   r   r   )r   r4  r   rP  r   r   r   subMessageHashesrT  r  r   r   s               r   un_watch_trades_for_symbolsz gate.un_watch_trades_for_symbols  s[      !!!!!!!!!%%g..OOG,,	WQZ((--f55	)q#g,,'' 	A 	AAQZF##I$6777  !6!?@@@@$$V,,66sHg}^npy  |C  EK  L  L  L  L  L  L  L  L  	Lr   c                 @   K   |                      |g|           d{V S )aM  
        get the list of most recent trades for a particular symbol
        :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)rp  )r   r   r   s      r   un_watch_tradeszgate.un_watch_trades  s2       55vhGGGGGGGGGr   c                    |                      |d          }t          |t                    s|g}|                     |          }t	          dt          |                    D ]}||         }|d         }|                      | j        |          }|5|                     | j        dd          }	t          |	          }|| j        |<   |
                    |           d|z   }
|                    ||
           d S )Nr   r   r   rn   ra   rh  )r   r  r  parse_tradesr  r   rk  r   r|   r   r   r  )r   r   r   r   parsedTradesr  trader   cachedTradesr   hashs              r   handle_tradeszgate.handle_trades  s   " (33&$'' 	XF((00q#l++,, 
	/ 
	/A OE8_F??4;??L#))$,tLL)%00&2F#&&&v%DNN<....
	/ 
	/r   1m	timeframec                   K   |                                   d{V  |                     |          }|d         }|d         }|                     | j        ||          }|                     |          }	|	dz   }
d|z   dz   |d         z   }|                     |          }||g}|                     ||||
|           d{V }| j        r|                    ||          }| 	                    |||dd          S )	a=  

        https://www.gate.com/docs/developers/apiv4/ws/en/#candlesticks-channel
        https://www.gate.com/docs/developers/futures/ws/en/#candlesticks-api
        https://www.gate.com/docs/developers/delivery/ws/en/#candlesticks-api

        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   z.candlestickscandles:rG  r   T)
r   r   r   
timeframesr   r   r   rM  ri  rj  )r   r   r{  r   r   r   r   r   rg   r   r   r   r   r   ohlcvs                  r   watch_ohlcvzgate.watch_ohlcv?  s#      !!!!!!!!!V$$!$<##DOY	JJ--f55/ 8+c1F84DD$$V,,X&++CgwPVWWWWWWWW? 	2NN6511E))%q$GGGr   c                    |                      |d          }|                    d          }|                      |d          }|dk    rdnd}|                     |d          }t          |t                    s|g}i }t          dt          |                    D ]F}	||	         }
|                      |
dd          }|                    d	          }|                      |d          }|                     |          }|d	z   }|                    |d          }| 	                    |d d	|          }| 
                    |
          }|                     | j        |i           | j        |<   |                     | j        |         |          }|;|                     | j        d
d          }t          |          }|| j        |         |<   |                    |           |||<   Ht	          |                                          }t          dt          |                    D ]i}	||	         }||         }|                     |          }d|z   dz   |z   }|                     | j        |         |          }|                    ||           jd S )Nr   r   r   r[   r   r   n r   ro   ra   r}  rG  )r   r   r   r  r  r  r   find_timeframereplacer   parse_ohlcvohlcvsr   r|   r   r   keysr  )r   r   r   r   r  r  r  r   rP  r  r  r   r^  timeframeIdr{  rS  r   r   parsedstoredr   r  rg   rx  s                           r   handle_ohlcvzgate.handle_ohlcv^  s   " ""7I66}}S))((q99 - 7 7VVj
(33&$'' 	XF	q#f++&& 	* 	*A1IE++E3;;L &&s++E**5!44K++K88I_F#++FB77H%%hc:FFF%%e,,F"&//$+vr"J"JDK__T[%8)DDF~))$,dKK.u5517F#I.MM&!!! )IfINN$$%%q#d))$$ 	) 	)A!WF!&)I**955H"X-3f<D__T[%8(CCFNN64((((	) 	)r   c           	      @  K   |                                   d{V  d}d}d}d}||                     |          }|d         }|                     d||          \  }}|                     d||          \  }}|                     |dddddd          }	|	d	z   }
d
}||d|z   z  }|dk    }|                     ||          }|g}|dk    }|                     ||||
||           d{V }| j        r|                    ||          }| 	                    ||||d          S )a#  

        https://www.gate.com/docs/developers/apiv4/ws/en/#user-trades-channel
        https://www.gate.com/docs/developers/futures/ws/en/#user-trades-api
        https://www.gate.com/docs/developers/delivery/ws/en/#user-trades-api
        https://www.gate.com/docs/developers/options/ws/en/#user-trades-channel

        watches information on multiple trades made by the user
        :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
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/?id=trade-structure>`
        N!allr   rC   r[   rY  r|   r[   r   r]   r\   r^   z.usertradesmyTradesrG  inverseT)
r   r   r   handle_sub_type_and_paramsget_supported_mappingget_url_by_market_typesubscribe_privaterM  ri  r   )r   r   r   r   r   subTyper   r   r   r   r   r   	isInverser   r   requiresUidrk  s                    r   watch_my_tradeszgate.watch_my_trades  s      !!!!!!!!![[((Fd|H99/6SYZZf99/6SYZZ008
 8
   - 3<'K	)	))$	::*v~--c;RXZeffffffff? 	3OOFE22E00tTTTr   c                    |                      |dg           }t          |          }|dk    rd S | j        }|2|                     | j        dd          }t          |          }|| _        |                     |          }i }t          dt          |                    D ],}	||	         }
|                    |
           |
d         }d||<   -t          |
                                          }t          dt          |                    D ]%}	||	         }d|z   }|                    ||           &|                    |d           d S )	Nr   r   rn   ra   r   Tz	myTrades:r  )r   r   r  r   r|   r   rt  r  r   r  r  r  )r   r   r   r   tradesLengthrw  r   r  rP  r  rv  r   r  r   rx  s                  r   handle_my_tradeszgate.handle_my_trades  sR   * (B776{{1F}%%dlM4HHE1%88L(DM""6**	q#f++&& 	% 	%A1IE&&&8_F $IfINN$$%%q#d))$$ 	/ 	/A!WF'DNN<....|Z00000r   c           	      z  K   |                                   d{V  d}d}|                     dd|          \  }}|                     dd|          \  }}|dk    }|                     ||          }|dk    }|                     |dddddd          }|dz   }|d	z   }	|                     ||	d|||           d{V S )
aL  
        watch balance and get the amount of funds available for trading or funds locked in orders

        https://www.gate.com/docs/developers/apiv4/ws/en/#spot-balance-channel
        https://www.gate.com/docs/developers/futures/ws/en/#balances-api
        https://www.gate.com/docs/developers/delivery/ws/en/#balances-api
        https://www.gate.com/docs/developers/options/ws/en/#balances-channel

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/?id=balance-structure>`
        NrE   r  r[   rY  r|   r  z	.balances.balance)r   r   r  r  r  r  )
r   r   r   r  r  r   r  channelTyper   r   s
             r   watch_balancezgate.watch_balance  s      !!!!!!!!!99.$PVWWf99.$PVWW	)	))$	::v~008
 8
   +Z'++CdGVU`aaaaaaaaar   c                 t   |                      |dg           }|| j        d<   t          dt          |                    D ]}||         }|                                 }|                     |dd          }|                     |          }|                     |dd          }	|	| j        d<   |                     |	          | j        d	<   |                     |d
          |d<   |                     |d          |d<   | 	                    |dd          |d<   || j        |<   |                     |d          }
|

                    d          }|                     |d          }|                     |dddd          }|dz   }|                     | j                  | _        |                    | j        |           d S )Nr   infor   currencyUSDTtime_mstimestamp_msr'  r(  freezeused	availablefreetotalbalancer   r   r[   r\   r^   )r[   rY  r|   r  )r   r  r  r   accountr   safe_currency_codesafe_integer_2r-  safe_string_2r   r  safe_balancer  )r   r   r   r   r  
rawBalancer  
currencyIdcoder'  r   r^  rawTyper  r   s                  r   handle_balancezgate.handle_balance  s   B (B77%Vq#f++&& 	) 	)AJllnnG))*j&IIJ**:66D++J	>RRI(1DL%'+||I'>'>DL$"..z8DDGFO"..z;GGGFO#11*gyQQGG!(DL""7I66c""""5!,,00;
 ;
  
 "J.((66t|[11111r   c                   K   |                                   d{V  d}|                     |          }dg}|                     |          s|                     |          }d}d}|                     d||          \  }}|dk    rd}|                     |dddd          }	|d	z   }
|                     |          s|
d
d                    |          z   z  }
|	dz   }d}|                     d||          \  }}|dk    }|                     ||          }| 	                    |          }| 
                    |||           |                     ddd          }|                     ddd          }|                     | j        |          }|r"|r ||                    |dz              d{V S |                     ||
|||d           d{V }| j        r|S |                     | j        |         |||d          S )a  

        https://www.gate.io/docs/developers/futures/ws/en/#positions-subscription
        https://www.gate.io/docs/developers/delivery/ws/en/#positions-subscription
        https://www.gate.io/docs/developers/options/ws/en/#positions-channel

        watch all open positions
        :param str[] [symbols]: list of unified market symbols to watch positions for
        :param int [since]: the earliest time in ms to fetch positions for
        :param int [limit]: the maximum number of positions to retrieve
        :param dict params: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/en/latest/manual.html#position-structure>`
        Nr  rK   r[   r\   rY  r|   r]   r\   r^   
:positions::,z
.positionsr  rl   Trm   :fetchPositionsSnapshot)r   rI  is_emptyget_market_from_symbolsr   r  joinr  r  r   set_positions_cacher   r   	positionsr]   r  rM  filter_by_symbols_since_limit)r   r4  r   r   r   r   r   r   r   typeIdr   r   r  r  r   r   rl   rm   r   r  s                       r   watch_positionszgate.watch_positionsg  sr      !!!!!!!!!%%g..-}}W%% 	;11'::F889I6SYZZe6>>D++D3
 3
  
 \)}}W%% 	44#((7"3"333K<'889I6SXYY	)	))$	::S!!  w777!%!3!34DF^`d!e!e!%!3!34DF^`d!e!e55! 	I&< 	It.G'GHHHHHHHHH00k7GUZ\`aaaaaaaa	? 	11$.2FQVX]_cdddr   c                    | j         i | _         || j         v rd S |                     ddd          }|rD|dz   }||j        vr4|                    |           |                     | j        |||           d S d S t                      | j         |<   d S )NrK   rl   Fr  )r  r   rY  r]   r   load_positions_snapshotr   )r   r   r   r4  rl   r   s         r   r  zgate.set_positions_cache  s    >!DN4>!!F!%!3!34DF^`e!f!f! 	>!::K6>11k***

47dSSSSS 21 $<#=#=DN4   r   c                   K   |                      d d|i           d {V }t                      | j        |<   | j        |         }t          dt	          |                    D ]<}||         }|                     |dd          }|dk    r|                    |           =||j        v r=|j        |         }	|	                    |           |                    ||dz              d S d S )Nr   r   	contractsz	:position)	fetch_positionsr   r  r  r   safe_numberr   rY  r  )
r   r   r   r   r  r   r  positionr  r]   s
             r   r  zgate.load_positions_snapshot  s      ..tfd^DDDDDDDD	799tt$q#i..)) 	' 	'A |H((;BBI1}}X&&&&.((^K0FNN5!!!NN5$"455555 )(r   c                    |                      |j                  }|                     |dg           }| j        |         }g }t	          dt          |                    D ]M}||         }|                     |          }	|                     |	d          }
|                     |	d          }||                     ||
dz             }|5|d         |	d<   |	                    |	           |	                    |	           |                     ||
dz             }|5|d         |	d<   |	                    |	           |	                    |	           |1|/d|	d<   |	                    |	           |	                    |	           #|	                    |	           |	                    |	           O| 
                    ||dz             }t	          dt          |                    D ]}||         }|                    d          }|d	         }|                    d
          }|                     |d|d          }|                     |          s|                    ||           |                    ||dz              d S )Nr   r   r   r   longshortz:positions::r  r   r  Fr  )get_market_type_by_urlr   r   r  r  r   parse_positionr   r[  r   find_message_hashesr   rO  r  r  )r   r   r   r   datar   newPositionsr  rawPositionr  r   r   prevLongPositionprevShortPositionrT  r   r^  symbolsStringr4  r  s                       r   handle_positionszgate.handle_positions  s   > **6:66w"55t$q#d))$$ 	' 	'Aq'K**;77H%%h99F##Hf55D|#'>>%&#I#I #/'7'?HV$ ''111LL***$(NN5&7:J$K$K!$0'8'@HV$ ''111LL***#+0A0I'-HV$ ''111LL***##H---X&&&&009NOOq#m,,-- 	7 	7A'*K%%d++E!!HM#))#..G,,\8WeTTI==++ 7y+666|TL%899999r   c           	      ^  K   |                                   d{V  d}||                     |          }|d         }d}d}|                     d||          \  }}|                     |dddddd          }|dz   }	d	}
d
g}||
d|d         z   z  }
|d         g}d}|                     d||          \  }}|dk    }|                     ||          }|dk    }|                     ||
||	||           d{V }| j        r|                    ||          }| 	                    |||dd          S )a  
        watches information on multiple orders made by the user

        https://www.gate.com/docs/developers/apiv4/ws/en/#orders-channel
        https://www.gate.com/docs/developers/futures/ws/en/#orders-api
        https://www.gate.com/docs/developers/delivery/ws/en/#orders-api
        https://www.gate.com/docs/developers/options/ws/en/#orders-channel

        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.type]: spot, margin, swap, future, or option. Required if listening to all symbols.
        :param boolean [params.isInverse]: if future, listen to inverse or linear contracts
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        Nr   rF   r[   rY  r|   r  z.ordersr   r  rG  r   r  r'  T)
r   r   r   r  r  r  r  rM  ri  rj  )r   r   r   r   r   r   r   r   r  r   r   r   r  r  r   r  r   s                    r   watch_orderszgate.watch_orders  s     " !!!!!!!!![[((FH%F88PVWWe++D3
 3
   9$-3--Kd|nG88PUVV	)	))$	::v~--c;RWYdeeeeeeee? 	3OOFE22E))&%TRRRr   c                    |                      |dg           }|                     | j        dd          }| j        t	          |          | _        | j        }i }|                     |          }t          dt          |                    D ]}||         }	|                      |	d          }
|                     |
d          }|dk    s|dk    rd	|	d
<   nA|dk    r;|                     |	d
          }|#|                     |
d          }|dk    rdnd|	d
<   |	                    |	           |	d         }| 
                    |          }d||d         <   t          |                                          }t          dt          |                    D ](}d||         z   }|                    | j        |           )|                    | j        d           d S )Nr   ordersLimitra   r   r  eventputupdater   r   finishleftclosedcanceledr   Tr   zorders:r   )r   r   r|   r   r   r   r  r   r   r   r   r  r  r  )r   r   r   r   r   r  rP  parsedOrdersr  r  r  r  r   r  r   r   r  r   s                     r   handle_orderzgate.handle_order.  s   V (B77!!$,tDD;077DK	((00q#l++,, 	+ 	+A!!_F??6622D$$T733E~~(!2!2#)x  (""))&(;;>,,T6::D48AIIxxJF8$MM&!!!H%F[[((F&*IfTl##INN$$%%q#d))$$ 	5 	5A#d1g-KNN4;4444t{H-----r   c                 8   K   |                      |g|||          S )a  
        watch the public liquidations of a trading pair

        https://www.gate.io/docs/developers/futures/ws/en/#liquidates-api
        https://www.gate.io/docs/developers/delivery/ws/en/#liquidates-api
        https://www.gate.io/docs/developers/options/ws/en/#liquidates-channel

        :param str symbol: unified CCXT market symbol
        :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 bitmex api endpoint
        :returns dict: an array of `liquidation structures <https://github.com/ccxt/ccxt/wiki/Manual#liquidation-structure>`
        )!watch_my_liquidations_for_symbolsr   s        r   watch_my_liquidationszgate.watch_my_liquidationsv  s$       55vhufUUUr   c                 P  K   |                                   d{V  |                     |ddd          }|                     |          }d}d}|                     d||          \  }}|                     |dddd          }d}	|                     d||          \  }	}|	dk    }
|                     ||
          }g }d}|                     |          r7|dk    r|
st          | j	        d	z             d
}|
                    d           nRt          |          }|dk    rt          | j	        dz             d|d         z   }|
                    |d                    |dz   }|                     |||||d           d{V }| j        r|S |                     | j        |||d          S )a  
        watch the private liquidations of a trading pair

        https://www.gate.io/docs/developers/futures/ws/en/#liquidates-api
        https://www.gate.io/docs/developers/delivery/ws/en/#liquidates-api
        https://www.gate.io/docs/developers/options/ws/en/#liquidates-channel

        :param str[] symbols: unified CCXT market 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 gate api endpoint
        :returns dict: an array of `liquidation structures <https://github.com/ccxt/ccxt/wiki/Manual#liquidation-structure>`
        NTrJ   rY  r|   r  r  r  z watchMyLiquidationsForSymbols() does not support listening to all symbols, you must call watchMyLiquidations() instead for each symbol you wish to watch.myLiquidationsznot allr   z watchMyLiquidationsForSymbols() only allows one symbol at a time. To listen to several symbols call watchMyLiquidationsForSymbols() several times.myLiquidations::r   r   z.liquidates)r   rI  r  r   r  r  r  r  r   r   r   r   r  rM  r  liquidations)r   r4  r   r   r   r   r   r   r  r  r  r   r   r   symbolsLengthr   newLiquidationss                    r   r  z&gate.watch_my_liquidations_for_symbols  s'      !!!!!!!!!%%gtT4@@--g66889XZ`bhiie++D3
 3
  
 889XZ`bghh	)	))$	::==!! 
	)""9"   ,H  "H  I  I  I*KNN9%%%%LLM!!   ,A  "A  B  B  B,wqz9KNN6$<(((=( $ 6 6sKRY[`bf g ggggggg? 	#""11$2CWeUZ\`aaar   c                    |                      |dg           }g }| j        0|                     | j        dd          }t	          |          | _        | j        }t          dt          |                    D ]z}||         }|                     |          }	|                    |	           | 	                    |	d          }
| 
                    ||
g           }|                    |d|
z              {|                    |d           d S )Nr   liquidationsLimitra   r   r   r  r  )rZ  r  r   r|   r   r  r   parse_ws_liquidationr   r   r   r  )r   r   r   rawLiquidationsr  r   r   r  rawLiquidationliquidationr   symbolLiquidationss               r   handle_liquidationzgate.handle_liquidation  s   X ..(B??$%%dl4GNNE *5 1 1D!q#o..// 	L 	LA,Q/N33NCCKLL%%%%%k8<<F!%!C!CNN-/AF/JKKKK(899999r   c                 .   |                      |d          }|                     ||          }|                     |d          }|                      |d          }|                      |d          }t          j        t          j        ||                    }|                     ||                     ||          |                     |          | 	                    |d          | 	                    |d          d d || 
                    |          d	          S )Nr   r  sizer  contractSize
fill_price)	r  r   r  r  r   	baseValue
quoteValuer'  r(  )r   r\  r   r"   
string_abs
string_subsafe_liquidationr   parse_numberr  r-  )r   r  r   r   r'  originalSizer  r   s           r   r  zgate.parse_ws_liquidation  s   : ##K<<!!(F33%%k9==	''V<<V44#G$6|T$J$JKK$$&&x88**622 ,,V^DD%%k<@@"Y//
&
 
&
 
 
 
	r   c                 R   |                      |d          }|                      |d          }|                      |d|          }|                     |dd          }|                     |g d          }|1|                     |j        |          }	 |                     | j        d         d         ||                     |                     |                     | j        d         ||                     |                     |                     |d	|                     |d	                    }	|                     | j        d         d
         |	|                     |                     t          |                     |                    # t          $ r}
|                    |
|           |||j        v r|j        |= |                     |d          }||                    d          dk    r|                    d          }|                     |dg           }t          dt!          |                    D ]M}|d         dk    }|                     ||         d d|          }|d         dz   |z   }|||j        v r|j        |= NY d }
~
nd }
~
ww xY w|||j        v r|j        |= dS dS )Nr  errsr  r  label)r   	requestId
request_idr'   rx   r   ry   r   r   r   r   rY  r\   r   r   rG  TF)r[  r  safe_string_nr   r   throw_exactly_matched_exceptionr}   jsonthrow_broadly_matched_exceptionr   	Exceptionr  rK  r   rZ  r  r   r   )r   r   r   r  r  r  r  r   r   errorMessageer   parsedChannelr   r  r  r   messageHashSymbols                     r   handle_error_messagezgate.handle_error_message   s   h ~~gv..~~dF++w66!!%99)J)J)JKK**6+?DDKH44T_T5J75SUY[_[d[del[m[mnnn44T_W5MtUYU^U^_cUdUdeee#//y$BRBRSWYbBcBcdd44T_T5J75SUacgclclmtcucuvvv#DIIg$6$6777 H H Ha---++AU2U2U,[9**7I>>'gll3.?.?!.C.C$+MM#$6$6M"nnWiDDG"1c'll33 H H%21%5%?
!%!1!1'!*dC!T!T,9!,<s,BV,K)-9@QU[Ui@i@i & 45F GH R6+?%?%?(,4us   C8F
 

JC1J

Jc                     i | _         d S N)r  )r   r   r   r   s       r   handle_balance_subscriptionz gate.handle_balance_subscriptionu  s    r   c                 X   |                      |d          }| j        | j        | j        | j        d}|                      |d          }||v rK|                      |j        |          }|                     |j        |          }||         } ||||           ||j        v r
|j        |= d S d S )Nr   )r  zspot.order_book_updatezfutures.order_book_updatezoptions.order_book_updater   )r   r  r   r   r   )	r   r   r   r   methodsr   subscriptionHashr   r6  s	            r   handle_subscription_statuszgate.handle_subscription_statusx  s    ""7I667&*&I)-)L)-)L	
 
 gt,,g#//0DbII??6+?AQRRLW%FF67L111%%%$R((( &%r   c                 t   |                      |d          }t          |j                                                  }t	          dt          |                    D ]}||         }||j        vr|                    d          r|j        |         }|                      |d          }||k    rS|                     |dg           }	|                     |dg           }
t	          dt          |	                    D ])}|	|         }|
|         }|                     |||           *| 	                    |           d S )Nr   r   unsubscriberT  ro  )
r   r  r   r  r  r   
startswithrZ  clean_unsubscriptionclean_cache)r   r   r   r   r  r  r   r   subIdrT  ro  j	unsubHashsubHashs                 r   handle_un_subscribezgate.handle_un_subscribe  sP   & gt,,F(--//00q#d))$$ 	/ 	/Aq'K6#777%%m44 /%3K@((t<<;; $|_b Q Q#'>>,@RTV#W#W q#m"4"455 J JA -a 0I.q1G--fgyIIII  ...!	/ 	/r   c                 P   |                      ||          rd S |                     |d          }|dk    r|                     ||           d S |dk    r|                     ||           d S |                     |dd          }|                    d          }|                     |d          }| j        | j        | j        | j	        | j
        | j        | j        | j        | j        | j        d
}|                     ||          }| |||           |                     |d	          }	|	d
k    r|                     ||           d S |	^|                     |d          }
|                     |
d          }|                     |d          }|dur|                    ||	           d S d S d S )Nr  	subscriber  r   r  r   r   )

usertradescandlesticksr   r  rc   rA  rk  order_book_updatebalances
liquidatesr  authenticatedr  r   ackT)r  r   r  r!  r   r   r  r  r  r  r?  rE  ry  r  r  r  handle_authentication_messager[  	safe_boolr  )r   r   r   r  r   r  r  	v4Methodsr6  r  r  r   r*  s                r   handle_messagezgate.handle_message  s   t $$VW55 	F  '22K++FG<<<FM!!$$VW555F""7Ir::}}S))oolA66/ -'.).(!%!7+1
 
	 K88F67###$$Wl;;	''..vw???F >>'622D__T844F..%00C$vy11111 ! 
 r   c                 x    | j         d         |d                  }|d         r|d         r|d         n|d         S |S )Nr_   r   r   linearrY   rZ   r{   )r   r   baseUrls      r   r   zgate.get_url_by_market1  sE    )E"6&>2* 	&,X&6J76??GENJNr   r   c                 .    |d         rdS |d         rdS dS )Nr[   r^   r|   rY   )r   r   s     r   r   zgate.get_type_by_market8  s*    &> 	6H 	99r   Fc                 l    | j         d         }||         }|dk    s|dk    r|r|d         n|d         S |S )Nr_   r\   r]   rZ   rY   r1  )r   r   r  r_   r   s        r   r  zgate.get_url_by_market_type@  sF    i$iFNN 0 0!*;3u::F;Jr   r   c                     dddd}t          |                                          }t          dt          |                    D ]/}||         }||         }|                    |          dk    r|c S 0dS )Nr^   r]   r\   )zop-deliveryfxr   r[   )r  r  r  r   rK  )r   r   findByr  r  keyvalues          r   r  zgate.get_market_type_by_urlH  s     
 

 FKKMM""q#d))$$ 	 	Aq'C3KExx}}!! "vr   c                     |                                   |                     |                     | j        dd          d          }|| j        d<   |                                  |S )Nreqidr   r   )lock_idsumr   r|   	unlock_id)r   r=  s     r   r  zgate.request_idV  sW    **4<!DDaHH %Wr   c                 B  K   |                                  }|                                 }|||d|d}	|7|                     |          }
||
j        vrt	          |          }||
j        |<   |                     |	|          }|                     |||||           d {V S Nr#  r   timer   r  r   )r  secondsr   r   r   r   watch)r   r   r   r   r   r   r   r  rD  r   r   tempSubscriptionHashr   s                r   r   zgate.subscribe_public^  s      OO%%	||~~ 
 
 #[[%%F6#777'*9~~$=H$%9:++gv..ZZ[';UUUUUUUUUr   c                    K   |                                  }|                                 }|||d|d}|                     ||          }	|                     |||	|           d {V S rB  )r  rE  r   watch_multiple)
r   r   rT  r   r   r   r  rD  r   r   s
             r   rL  zgate.subscribe_public_multiplep  s~      OO%%	||~~ 
 
 ++gv..((mWmTTTTTTTTTr   c	                    K   |                                  }	|                                 }
|	|
|d|d}t          |	          |d|||d}|                     ||          }|                     |||||           d {V S )Nr  rC  T)r   topicr  rT  ro  r4  )r  rE  r   r   rI  )r   r   rK  r4  rT  ro  r   r   r   r  rD  r   subr   s                 r   r   z!gate.un_subscribe_public_multiple}  s      OO%%	||~~"
 
 i..* 0
 
 ++gv..((mWmUXYYYYYYYYYr   c                    K   |dz   }|                      |          }d}|                    |          }|                     |j        |          }||                     |i ||           d {V S |S )Nz.loginr)  )r   reusableFuturer   r   r   )r   r   r   r   r   r   r]   r)  s           r   r   zgate.authenticate  s      (S!!%&&{33(<kJJ --c2wLLLLLLLLLr   c                 j    d}|                      |j        |          }|                    d           d S )Nr)  T)r   rY  r  )r   r   r   r   r]   s        r   r+  z"gate.handle_authentication_message  s4    %==tr   r  c                 \  K   |                                   d}|#|                                 }t          |          }|}|                                 }d                    |||                     |          t          |          g          }	|                     |                     |	          |                     | j                  t          j
        d          }
|t          |          | j        |
|d}|dk    s|dk    rddi|d	<   |||||d
}|                     |||||           d {V S )Nr_   
hex)req_idr'  api_key	signature	req_paramzspot.order_placezfutures.order_placezX-Gate-Channel-Idccxt
req_headerrC  )check_required_credentialsr  r   rE  r  r	  hmacencodesecrethashlibsha512apiKeyrF  )r   r   	reqParamsr   r  r  reqIdr   rD  signatureStringrU  r   r   s                r   r   zgate.request_private  sI     '')))OO%%EE

I||~~))UGTYYy5I5I3t99$UVVIIdkk/::DKK<T<TV]Vdfkll	T{""
 
 )))w:O/O/O#V%GL! 
 
 ZZ[';	RRRRRRRRRr   c                 &  K   |                                   |rY| j        t          | j                  dk    rt          | j        dz             | j        g}||}n|                     ||          }|                                 }d}	d|z   dz   dz   |	z   dz   dz   t          |          z   }
|                     | 	                    |
          | 	                    | j
                  t          j        d          }d	| j        |d
}|                                 }||||	|d}|||d<   |                     |          }||j        vrt          |          }||j        |<   |                     ||          }|                     |||||           d {V S )Nr   z requires uid to subscriber#  zchannel=&zevent=ztime=rR  rT  )r6  KEYSIGN)r   rD  r   r  authr   )rY  uidr   r   r   array_concatrE  r   rZ  r[  r\  r]  r^  r_  r  r   r   r   rF  )r   r   r   r   r   r   r  idArrayrD  r  signaturePayloadrU  rg  r  r   r   rG  r   s                     r   r  zgate.subscribe_private  s     ''))) 	>x3tx==A#5#5'2N(NOOOxjG!++GW==||~~%/#5@5H3NQXX[^_c[d[ddIIdkk*:;;T[[=U=UW^Weglmm	;
 

 OO%%	
 
 !(GIS!!v333#&y>> 9DF !56++gv..ZZ[';TTTTTTTTTr   r  )F)Z__name__
__module____qualname__r   r   r   r   r   floatr   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  r   r   r2  r?  rB  rE  r8  r=  r   re  rd  rp  rr  ry  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   rL  r   r   r+  r   r  __classcell__)r   s   @r   r$   r$      s       z# z z z z z zx pt|~ ) )C )y )	 )[` )il ) ) ) )V IK 4 4T,-? 4 4 4 40 8<B 4 4 4 4 4 44 <@ - - -S - - - -6 im{  IK 2 2c 23 2i 2y 2be 2ux 2 2 2 24 ;?r 2 2s 2C 2 2 2 24 8<$]ajl Z Z ZC ZWZ Zquv{q| Z Z Z Z :>D_cln ^ ^3 ^c ^Y\ ^swx}s~ ^ ^ ^ ^ JN\`os|~ O Oc O3 OVY Oil O  DH  IN  DO O O O O@ @DB &! &!S &! &!S\ &! &! &! &!P =? N N N3 N N N N2=V = = = =
[5 [5 [5 [5 [5z  . . .
/ 
/ 
/ 68 / / /F / / / /& 6:" E E7 E E E E EBF B B B B* 8<B J JW J7 J J J JBV B B B B( NRkoxz E E7 Eeh E  @G E E E E24C 4 4 4 4 44 <@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B LN L Lc LRU L L L L, 9; H HC Hs H H H H/F / / / /B ?CQUdhqs H H H H3 H^a Hx|  ~B  yC H H H H>2)6 2) 2) 2) 2)h 37TX\eg ,U ,UC ,Us ,URU ,Ulpqvlw ,U ,U ,U ,U\*1v *1 *1 *1 *1X *, b b b b b b@Y2V Y2 Y2 Y2 Y2v 8<$]ajl 0e 0eW 0eC 0eWZ 0equv~q 0e 0e 0e 0ed> >& > > > > >6 6 6E: E: E:N 04$UYbd /S /S /SC /Ss /Simnsit /S /S /S /SbF.6 F. F. F. F.P EIW[df V V# Vc VQT Vkop{k| V V V V  X\jnwy .b .btCy .bQT .bdg .b  C  DO  P .b .b .b .b`9: 9: 9: 9: 9:v- - - -^S6 St S S S Sj &    ) ) ) ) )"%/& %/ %/ %/ %/N2V 2 2 2 2B       :    #       QSae V V V V$ \^ U U U U AC Z Z Z Z*  F    
S S S S S S@$U $U $U $U $U $U $U $Ur   r$   )+ccxt.async_supportrW   ccxt.async_support.base.ws.cacher   r   r   r   r]  ccxt.base.typesr   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   !ccxt.async_support.base.ws.clientr   typingr   ccxt.base.errorsr   r   r   r   r    r!   ccxt.base.preciser"   async_supportr$   r4  r   r   <module>ry     sP       A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A 4 4 4 4 4 4       * * * * * * 0 0 0 0 0 0 . . . . . . ' ' ' ' ' ' ) ) ) ) ) ) * * * * * * % % % % % %PU PU PU PU PU4" PU PU PU PU PUr   