
    ei                       d dl mZ d dl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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+m,Z, d dl-m.Z. d dl/m0Z0 d dl/m1Z1 d dl/m2Z2 d d	l/m3Z3 d d
l/m4Z4 d dl/m5Z5 d dl/m6Z6 d dl/m7Z7 d dl/m8Z8 d dl/m9Z9 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lAmBZB  G d dee          ZCdS )    )Exchange)ImplicitAPIN)'AnyBalancesBorrowInterestBool
CurrenciesCurrencyDepositAddressFundingHistoryGreeksIntLedgerEntryLeverage	LeveragesLeverageTierLeverageTiersMarginModificationMarketNumOptionOptionChainOrder	OrderBookOrderRequestCancellationRequest	OrderSide	OrderTypePositionStrStringsTickerTickersFundingRateFundingRatesTradeTradingFeeInterfaceTradingFeesTransactionMarketInterfaceTransferEntry)List)ExchangeError)AuthenticationError)PermissionDenied)AccountNotEnabled)AccountSuspended)ArgumentsRequired)
BadRequest)	BadSymbol)InsufficientFunds)InvalidOrder)OrderNotFound)OrderImmediatelyFillable)NotSupported)RateLimitExceeded)ExchangeNotAvailable)	TICK_SIZE)Precisec                   
    e Zd Zdef fdZdef fdZi fdZi fdZi fde	fdZ
defd	Zddededededef
 fdZi fdee         fdZi fdZi fdZi fdZd Zi fdZd Zd
d
i fdZd
di fdZd
di fdZd Zd Zi fdefdZi fdede fdZ!d
i fde"de#fd Z$ddede fd!Z%d" Z&i fd#efd$Z'i fd#edee(         fd%Z)i fd#ede(fd&Z*dd'Z+i fdede,fd(Z-i fde.fd)Z/d* Z0ddefd+Z1d
i fd,e"fd-Z2d
i fd,e"fd.Z3dd/e4fd0Z5d
d
d
i fded1e	d2e	fd3Z6dee7         fd4Z8ddefd5Z9d
i fded2e	de:fd6Z;i fdede<fd7Z=dd8e>dede<fd9Z?d
i fde"de@fd:ZAd; ZBi fdeCfd<ZDd=d
d
i fded>ed1e	d2e	deeE         f
d?ZFd=d
d
i fded1e	d2e	fd@ZGd
d
d
i fded1e	d2e	fdAZHddedeEfdBZId
d
i fded1e	d2e	deeJ         fdCZKd
d
d
i fdDeded1e	d2e	fdEZLd
d
d
i fded1e	d2e	fdFZMddGe>dedeJfdHZNd
d
d
i fd#ed1e	d2e	deeO         fdIZPd
d
d
i fd#ed1e	d2e	deeO         fdJZQd
i fd#edKeRdLedMedeOf
dNZSdOefdPZTdQ ZUddRe>d/e4deOfdSZVd
i fdedTeWdUeXdKeRdVeYf
dWZZi fdXee[         fdYZ\i fdXee[         fdZZ]d
i fdedTeWdUeXdKeRdVeYf
d[Z^i fded\eRfd]Z_d
d
i fdDededTeWdUeXdKeYdVeYfd^Z`d
d
i fdDededTeWdUeXdKeYdVeYfd_ZadOefd`Zbddae>dedecfdbZdd
i fdDedefdcZed
i fdDedefddZfd
d
d
i fded1e	d2e	deec         fdeZgd
d
d
i fded1e	d2e	deec         fdfZhd
d
d
i fded1e	d2e	fdgZid
d
d
i fded1e	d2e	fdhZjd
i fdDedefdiZkd
i fdjee         defdkZli fdXeem         fdlZnd
i fdefdmZoi fd#edKeRdnedoedepf
dpZqddqe>d/e4depfdrZrd
i fdsesdefdtZtddue>defdvZui fdefdwZvd
i fde"deew         fdxZxd
i fde"deyfdyZzi fdedee{         fdzZ|ddee{         fd{Z}ddedee{         fd|Z~i fded#efd}Zi fd#efd~Zi fded#edKeRfdZi fd#edKeRfdZdd/e4fdZd
d
d
d
i fd#eded1e	d2e	dee         f
dZdde>dedefdZd Zg di d
d
fdZi fdefdZdde>dedefdZi fdedKeRdefdZi fdedKeRdefdZdd
d
i fded1e	d2e	fdZddefdZd
d
d
i fded1e	d2e	fdZd
d
d
i fded1e	d2e	fdZd Zd Zd
d
d
i fd#ed1e	d2e	dee         fdZdde>d/e4defdZd Zd
i fdedefdZi fdZd
d
i fded1e	d2e	fdZd
d
d
i fded1e	d2e	fdZddefdZi fdedefdZdde>dedefdZd
i fdedUeXdecfdZi fdedefdZd
i fde"defdZddse>dedefdZi fdedefdZi fd#edefdZdde>d/e4dedefdZd
d
d
i fde"d1e	d2e	deew         fdZd#esdededede>defdZ xZS )gatereturnc                 ,   |                      t          t          |                                           i ddddddgddd	d
ddddddddddddddddddddddddddddddddddddddddddd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d0dd1dd2dd3dd4dd5d-d6dd7dd8dd9dd:dd;dd<d-d=d-d>dd?d-i d@d-dAddBddCd-dDddEddFdGdHddIddJddKddLddMddNddOd-dPd-dQdi dRddSddTddUddVd-dWd-dXddYddZdd[dd\dd]dd^dd_dd`d-daddbdi dcdddddeddfddgddhdGdid-djddkddld-dmddnddoddpddqddrddsdddd-ddddddd-dd-dddtdudvdwdxiidvdxdxdyidvdxdxdxdxdxdxdxdxdxdxdz
idvdxdxdxdxdxdxdxdxd{idvdxdxd|idvdxdxdxdxdxdxdxdxdxdxdxdxdxd}idvdxdxdxdxdxdxdxdxd~idvdxdxdxdxdxdxdxdxdxdxdxdxdidvdxdxdxdxdidvdxdxdxdxdxdid
ddxdddxidi ddxddxddxddxddxddxddddddddddxddxddddxddxddxddxddddxddddddddddddddiddidi ddddddddddddddddddddddddddddddddddddddddiddxdxdxdxdxdxdxdxdxdxd
ddxdddddddddddddidi dddddddddddddddddddddddddddddddddddddddddddddǜ
dddddddddȜdddɜddidʜdxdxd˜dxdxd̜di ddxddxddxddxddxddxddxddxddxddxddxddxddxddxddxddxddxddxii ddxddxddxddxddxddxddxddxddxddxddxddddddddddddddidxdxddddddddddddddddddddddddddddddddddddddddddd
dddddddd˜di ddddddddddddddddddddddd dddddddddddddddddddiddi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ddddddddddddddddddddddiddvdddddddddd	idxdxdxdxddxdxdxdxdxddd dd!d"d#d$d%d&d'd(d)d*d+d,d,d-d.i d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHd4dIdJdKdLdMdNdOdPdQdRdSdTdUdddVdWdXdYidZd[d-d-d d\d]idi d^d^d_d`dadadbdadcdcdddcdedfdgdfdhdhdidhdjdjdkdkdldmdndndodpdqdqdrdsi dtdudvdvdwdxdxdxdydydzd{d|d}d~d~dddddddddddddddddddddddddddddddddddbdbdddddgdgdididkdkddddddddddddddddddZdZddg didYdddgiidYddgiiddddddd ddd dddd-dd-d-ddd-dddddiddd dd-dd-dd-ddddd-dd-dd ddd-ddd d d-dddid	ddidd-dddddddid-d ddd-id-d ddddidddiddidĜddiddidĜdŜdt          ddvd|                     dǦ          |                     dǦ          |                     dȦ          |                     dǦ          g|                     dɦ          |                     dʦ          g|                     d˦          |                     d̦          g|                     dͦ          |                     dΦ          g|                     dϦ          |                     dЦ          g|                     dѦ          |                     dҦ          g|                     dӦ          |                     dԦ          g|                     dզ          |                     d֦          g|                     dצ          |                     dئ          g|                     d٦          |                     dڦ          g|                     dۦ          |                     dܦ          g|                     dݦ          |                     dަ          g|                     dߦ          |                     d          g|                     d          |                     d          g|                     d          |                     d          g|                     d          |                     d          g|                     d          |                     d          gg|                     dȦ          |                     dǦ          g|                     dɦ          |                     d          g|                     d˦          |                     dʦ          g|                     dͦ          |                     d̦          g|                     dϦ          |                     dΦ          g|                     dѦ          |                     dЦ          g|                     dӦ          |                     dҦ          g|                     dզ          |                     dԦ          g|                     dצ          |                     d֦          g|                     d٦          |                     dئ          g|                     dۦ          |                     dڦ          g|                     dݦ          |                     dܦ          g|                     dߦ          |                     dަ          g|                     d          |                     d          g|                     d          |                     d          g|                     d          |                     d          g|                     d          |                     d          ggddddd|                     d          |                     d          |                     dȦ          |                     d          g|                     dɦ          |                     d          g|                     d˦          |                     d          g|                     dͦ          |                     d          g|                     dϦ          |                     d          g|                     dѦ          |                     d          g|                     dӦ          |                     d          g|                     dզ          |                     d          g|                     dצ          |                     d          g|                     d٦          |                     d          g|                     dۦ          |                     d          g|                     dݦ          |                     d          g|                     dߦ          |                     d          g|                     d          |                     d          g|                     d          |                     d          g|                     d          |                     d          g|                     d          |                     d          gg|                     dȦ          |                     d          g|                     dɦ          |                     d          g|                     d˦          |                     d          g|                     dͦ          |                     d          g|                     dϦ          |                     d          g|                     dѦ          |                     d          g|                     dӦ          |                     d          g|                     dզ          |                     d          g|                     dצ          |                     d          g|                     d٦          |                     d          g|                     dۦ          |                     d          g|                     dݦ          |                     d          g|                     dߦ          |                     d          g|                     d          |                     d          g|                     d          |                     d          g|                     d          |                     d          g|                     d          |                     d          ggddd i dt          dt          dt          dt          dt          dt          dt          dt          d	t          d
t          dt          dt          dt          dt          dt          dt          dt          i dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          d t          d!t          d"t          i d#t          d$t           d%t           d&t"          d't$          d(t$          d)t          d*t          d+t          d,t          d-t          d.t          d/t          d0t          d1t          d2t$          d3t$          i d4t          d5t          d6t          d7t          d8t          d9t          d:t          d;t          d<t          d=t&          d>t          d?t           d@t          dAt          dBt          dCt          dDt          i dEt          dFt          dGt          dHt          dIt          dJt          dKt          dLt          dMt          dNt          dOt          dPt          dQt          dRt          dSt          dTt"          dUt          t          t          t          t          t          t          t          t          t          t          t          t          dVdWt          idXdYdZ          S ([  Nidr?   nameGate	countriesKR	rateLimit2   versionv4	certifiedTprourlszOhttps://github.com/user-attachments/assets/64f988c5-07b6-4652-b5c1-679a6bf67c85z-https://www.gate.com/docs/developers/apiv4/enzhttps://gate.comzhttps://api.gateio.ws/api/v4)walletfuturesmargindeliveryspotoptionssub_accountsearn)withdrawalsrN   rO   rP   rQ   rR   rS   subAccountsunifiedrebaterU   accountloanotc)publicprivatez%https://api-testnet.gateapi.io/api/v4)rO   rQ   rS   rR   rN   rP   rT   rZ   z#https://www.gate.com/share/CCXTGATEg?)urldiscount)logodocwwwapitestreferralhasCORSrR   rP   swapfutureoption	addMarginborrowCrossMarginborrowIsolatedMargincancelAllOrderscancelOrdercancelOrderscancelOrdersForSymbolscreateMarketBuyOrderWithCostcreateMarketOrdercreateMarketOrderWithCostFcreateMarketSellOrderWithCostcreateOrdercreateOrderscreatePostOnlyOrdercreateReduceOnlyOrdercreateStopLimitOrdercreateStopLossOrdercreateStopMarketOrdercreateStopOrdercreateTakeProfitOrdercreateTriggerOrder	editOrderfetchBalancefetchBorrowInterestfetchBorrowRateHistoriesfetchBorrowRateHistoryfetchClosedOrdersfetchCrossBorrowRatefetchCrossBorrowRatesfetchCurrenciesfetchDepositAddressfetchDepositAddressesfetchDepositAddressesByNetworkfetchDepositsfetchDepositWithdrawFeeemulatedfetchDepositWithdrawFeesfetchFundingHistoryfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchGreeksfetchIndexOHLCVfetchIsolatedBorrowRatefetchIsolatedBorrowRatesfetchLedgerfetchLeveragefetchLeveragesfetchLeverageTiersfetchLiquidationsfetchMarginAdjustmentHistoryfetchMarginModefetchMarketLeverageTiersfetchMarketsfetchMarkOHLCVfetchMyLiquidationsfetchMySettlementHistoryfetchMyTradesfetchNetworkDepositAddress
fetchOHLCVfetchOpenInterestfetchOpenInterestHistoryfetchOpenOrdersfetchOptionfetchOptionChain
fetchOrderfetchOrderBookfetchPositionfetchPositionHistoryfetchPositionModefetchPositionsfetchPositionsHistoryfetchPremiumIndexOHLCVfetchSettlementHistoryfetchTickerfetchTickers	fetchTimefetchTradesfetchTradingFeefetchTradingFees)fetchTransactionFeesfetchUnderlyingAssetsfetchVolatilityHistoryfetchWithdrawalsreduceMarginrepayCrossMarginrepayIsolatedMarginsandboxsetLeveragesetMarginModesetPositionModesignIntransferwithdrawrd   getcurrency_chains   )
currencieshistory_loan_rate)
r   zcurrencies/{currency}currency_pairscurrency_pairs/{currency_pair}tickers
order_booktradescandlestickstimeinsurance_history)zuni/currency_pairsz"uni/currency_pairs/{currency_pair}loan_margin_tiersr   r   funding_bookzcross/currencieszcross/currencies/{currency})r   r   ){settle}/contracts{settle}/contracts/{contract}{settle}/order_book{settle}/trades{settle}/candlesticksz{settle}/premium_index{settle}/tickersz{settle}/funding_rate{settle}/insurancez{settle}/contract_statsz#{settle}/index_constituents/{index}z{settle}/liq_orders{settle}/risk_limit_tiers)r   r   r   r   r   r   r   r   )underlyingsexpirations	contractszcontracts/{contract}settlementszsettlements/{contract}r   r   zunderlying/tickers/{underlying}r   zunderlying/candlesticksr   )uni/currenciesuni/currencies/{currency}zdual/investment_planzstructured/products)collateral/currenciesmulti_collateral/currenciesmulti_collateral/ltvmulti_collateral/fixed_ratemulti_collateral/current_rate)
rN   rX   rR   rP   
flash_swaprO   rQ   rS   rU   r[      )rV   pushzwithdrawals/{withdrawal_id})postdeletedeposit_addressrV   depositssub_account_transfersorder_statuswithdraw_statussub_account_balancesg      @sub_account_margin_balancessub_account_futures_balances!sub_account_cross_margin_balancessaved_addressfeetotal_balancesmall_balancesmall_balance_historyr   getLowCapExchangeList)	transfersr   sub_account_to_sub_accountr   )r   r   )rT   zsub_accounts/{user_id}sub_accounts/{user_id}/keys!sub_accounts/{user_id}/keys/{key})rT   r  zsub_accounts/{user_id}/lockzsub_accounts/{user_id}/unlockr  )r   r   putr   accountsgUUUUUU?
borrowabletransferabletransferablesbatch_borrowableloansloan_recordsinterest_records
risk_unitsunified_modeestimate_ratecurrency_discount_tiersr   zleverage/user_currency_configleverage/user_currency_settingaccount_modeg*@)r
  portfolio_calculatorr  collateral_currenciesr  )r   r   r  )
r   	batch_feer  account_bookopen_ordersordersorders/{order_id}	my_tradesprice_ordersprice_orders/{order_id}g?g?)batch_orderscross_liquidate_ordersr  cancel_batch_orderscountdown_cancel_allamend_batch_ordersr  )r  r  r  r  r  )r   r   r   patchr  funding_accounts
auto_repayzuni/estimate_rate	uni/loanszuni/loan_recordszuni/interest_recordszuni/borrowablezuser/loan_margin_tierszuser/accountloans/{loan_id}loans/{loan_id}/repaymentloan_records/{loan_record_id})
r  zcross/accountszcross/account_bookcross/loanszcross/loans/{loan_id}cross/repaymentszcross/interest_recordszcross/transferablezcross/estimate_ratezcross/borrowable)r$  r%  zleverage/user_market_settingr
  merged_loansr'  r)  r*  )r&  r(  )r   r   r"  r   )r  r  )r  zorders/preview{settle}/accounts{settle}/account_book{settle}/positions{settle}/positions/{contract}z {settle}/get_leverage/{contract}z'{settle}/dual_comp/positions/{contract}{settle}/ordersz{settle}/orders_timerange{settle}/orders/{order_id}{settle}/my_tradesz{settle}/my_trades_timerange{settle}/position_close{settle}/liquidatesz{settle}/auto_deleveragesz{settle}/feez{settle}/risk_limit_table{settle}/price_orders {settle}/price_orders/{order_id}${settle}/positions/{contract}/margin&{settle}/positions/{contract}/leveragez*{settle}/positions/{contract}/set_leverage({settle}/positions/{contract}/risk_limitz{settle}/positions/cross_modez'{settle}/dual_comp/positions/cross_modez{settle}/dual_modez{settle}/set_position_modez.{settle}/dual_comp/positions/{contract}/marginz0{settle}/dual_comp/positions/{contract}/leveragez2{settle}/dual_comp/positions/{contract}/risk_limitz{settle}/batch_ordersz{settle}/countdown_cancel_allz{settle}/batch_cancel_ordersz{settle}/batch_amend_ordersz{settle}/bbo_orders)r1  r6  )r0  r1  r5  r6  )r,  r-  r.  r/  r0  r1  r2  r3  r4  z{settle}/settlementsr5  r6  )r7  r8  r9  r0  r5  )r   r   r   )
my_settlementsr  r  	positionszpositions/{contract}position_closer  r  r  mmp)r  r   r=  z	mmp/reset	uni/lendszuni/lend_recordszuni/interests/{currency}zuni/interest_status/{currency}z	uni/chartzuni/ratezstaking/eth2/rate_recordsdual/orderszdual/balancestructured/orderszstaking/coinszstaking/order_listzstaking/award_listzstaking/assetsr   r   )r>  zstaking/eth2/swapr?  r@  zstaking/swapzuni/interest_reinvest)r   r   r  r"  collateral/orderszcollateral/orders/{order_id}zcollateral/repay_recordscollateral/collateralszcollateral/total_amountzcollateral/ltvmulti_collateral/ordersz"multi_collateral/orders/{order_id}multi_collateral/repaymulti_collateral/mortgagezmulti_collateral/currency_quotar   r   r   r   r   )rA  zcollateral/repayrB  rC  rD  rE  )detail	main_keys
rate_limit
stp_groupsstp_groups/{stp_id}/userszstp_groups/debit_fee	debit_fee)rI  rJ  rK  rJ  )	zagency/transaction_historyzagency/commission_historyzpartner/transaction_historyzpartner/commission_historyzpartner/sub_listzbroker/commission_historyzbroker/transaction_historyz	user/infozuser/sub_relation)get_user_def_bankz
order/listzstable_coin/order/listzorder/detail)quotezorder/createzstable_coin/order/createz
order/paidzorder/cancel)rV   rN   rW   rX   rR   rP   r   rO   rQ   rS   rU   r[   rZ   rY   r\   
timeframes10s1m5m15m30m1h2h4h8h1d7d)rO  rP  rQ  rR  rS  rT  rU  rV  rW  rX  rY  1wcommonCurrenciesORTXREATORSASSASSF88MPHMPHAXISAXISDEFIBIFIBITCOINFILEBOXDEFIBOXBYNBEYONDFIEGGGOOSEFINANCEGTCGAMECOMGTC_HT
GAMECOM_HTGTC_BSCGAMECOM_BSCHITHITCHAINMMMILLIONMORPHERPOINT	GATEPOINTRAIRAIREFLEXINDEXREDRedLangSUPERBITCOINTRINITYNETWORKCREDITVAIOTTRACO)SBTCTNCVAITRACrequiredCredentials)apiKeysecretheaderszX-Gate-Channel-IdccxtrS   r   
expirationiQ BTCBRC20BTCBRCETHERC20TRXTRC20HECOHTHRC20BSCBEP20SOLMATICOPTIMISMOPETHADAAVAXCAVAX_CNEARARBONEARBEVMBASEBASEEVMSUICRONOSCROAPTSCROLL	SCROLLETHTAIKOTAIKOETHHYPEALGOLINEALINEAETHBLASTBLASTETHXLMRSKRBTCTONMNTCELOHBARZKSERAKLAYEOSACAXTZEGLDGLMR	AURORAEVMKONETGTEVMKSMSMOKTDOTSMLUNC)r  r  r  r  r  r  r  AURORAKON	GATECHAINKUSAMAOKCPOLKADOTLUNAOP)r  r  r  r  r  r  r  r  r  POLYGONPOLgtciocpocfok)rl  IOCPOPOCFOKcross_marginrO   rQ   )fundingrR   rP   r  crossisolatedri   rj   rO   rQ   rk   rS   typesrR   ri   rj   rk   settlementCurrenciesusdtbtc)timeDifferenceadjustForTimeDifferencesandboxModeunifiedAccountrw   !createMarketBuyOrderRequiresPricenetworksnetworksByIdtimeInForceaccountsByTyper   ri   rj   features)r  r  r  GTD)
marginModetriggerPricetriggerDirectiontriggerPriceTypestopLossPricetakeProfitPriceattachedStopLossTakeProfitr  hedgedtrailingicebergselfTradePreventionleveragemarketBuyByCostmarketBuyRequiresPricemax(        )r  limitdaysBack	untilDayssymbolRequired)r  triggerr  r  d   )r  r  r  r  r  )r  r  r  r  r   r  daysBackCanceledr  r  )	r   rw   rx   r   r   r   fetchOrdersr   r   extendsdefault)lastmarkindex)r  r  
   )r  r   r  )r  r   r    )r  rw   rx   r   r   r   r   forDerivatives)linearinverse)r  rR   r  ri   rj   precisionModez0.0020z1.5z0.001853z0.001756z0.00165z12.5z0.0015525z0.0014575z0.00135200z0.00125500z0.001151250z0.001052500z0.000953000z0.0008560000.0007511000z0.0006520000z0.000554000075000z0.00195)makertaker)	tierBasedfeeSide
percentager!  r"  tiersbasez0.00.0005z0.0000z-0.00005z-0.00008z-0.01000z-0.01002z-0.01005z-0.02000z-0.02005z0.00050z0.00048z0.00046z0.00044z0.00042z0.00040z0.00038z0.00036z0.00034z0.00032z0.00030)tradingri   INVALID_PARAM_VALUEINVALID_PROTOCOLINVALID_ARGUMENTINVALID_REQUEST_BODYMISSING_REQUIRED_PARAMBAD_REQUESTINVALID_CONTENT_TYPENOT_ACCEPTABLEMETHOD_NOT_ALLOWED	NOT_FOUNDAUTHENTICATION_FAILEDINVALID_CREDENTIALSINVALID_KEYIP_FORBIDDEN	READ_ONLYINVALID_SIGNATUREMISSING_REQUIRED_HEADERREQUEST_EXPIREDACCOUNT_LOCKED	FORBIDDENSUB_ACCOUNT_NOT_FOUNDSUB_ACCOUNT_LOCKEDMARGIN_BALANCE_EXCEPTIONMARGIN_TRANSFER_FAILEDTOO_MUCH_FUTURES_AVAILABLEFUTURES_BALANCE_NOT_ENOUGHACCOUNT_EXCEPTIONSUB_ACCOUNT_TRANSFER_FAILEDADDRESS_NOT_USEDTOO_FASTWITHDRAWAL_OVER_LIMITAPI_WITHDRAW_DISABLEDINVALID_WITHDRAW_IDINVALID_WITHDRAW_CANCEL_STATUSINVALID_PRECISIONINVALID_CURRENCYINVALID_CURRENCY_PAIRPOC_FILL_IMMEDIATELYORDER_NOT_FOUNDCLIENT_ID_NOT_FOUNDORDER_CLOSEDORDER_CANCELLEDQUANTITY_NOT_ENOUGHBALANCE_NOT_ENOUGHMARGIN_NOT_SUPPORTEDMARGIN_BALANCE_NOT_ENOUGHAMOUNT_TOO_LITTLEAMOUNT_TOO_MUCHREPEATED_CREATIONLOAN_NOT_FOUNDLOAN_RECORD_NOT_FOUNDNO_MATCHED_LOANNOT_MERGEABLEREPAY_TOO_MUCHTOO_MANY_CURRENCY_PAIRSTOO_MANY_ORDERSTOO_MANY_REQUESTSMIXED_ACCOUNT_TYPEAUTO_BORROW_TOO_MUCHTRADE_RESTRICTEDUSER_NOT_FOUNDCONTRACT_NO_COUNTERCONTRACT_NOT_FOUNDRISK_LIMIT_EXCEEDEDINSUFFICIENT_AVAILABLELIQUIDATE_IMMEDIATELYLEVERAGE_TOO_HIGHLEVERAGE_TOO_LOWORDER_NOT_OWNEDORDER_FINISHEDPOSITION_CROSS_MARGINPOSITION_IN_LIQUIDATIONPOSITION_IN_CLOSEPOSITION_EMPTYREMOVE_TOO_MUCHRISK_LIMIT_NOT_MULTIPLERISK_LIMIT_TOO_HIGHRISK_LIMIT_TOO_lOWPRICE_TOO_DEVIATEDSIZE_TOO_LARGESIZE_TOO_SMALLPRICE_OVER_LIQUIDATIONPRICE_OVER_BANKRUPTORDER_POC_IMMEDIATEINCREASE_POSITION)CONTRACT_IN_DELISTINGINTERNALSERVER_ERRORTOO_BUSYCROSS_ACCOUNT_NOT_FOUNDRISK_LIMIT_TOO_LOWAUTO_TRIGGER_PRICE_LESS_LASTAUTO_TRIGGER_PRICE_GREATE_LASTPOSITION_HOLDINGUSER_LOAN_EXCEEDED	NO_CHANGEPRICE_THRESHOLD_EXCEEDEDzYour order size)exactbroadg     @)fees
exceptionsrollingWindowSize)deep_extendsuperr?   describer<   parse_numberr3   r2   r-   r.   r/   r1   r5   r:   r;   r6   r4   r8   r7   r0   )self	__class__s    G/var/www/html/volatility/venv/lib/python3.11/site-packages/ccxt/gate.pyr  zgate.describe    s(   dD 1 1 : : < < |?
&|?
F|?
 $|?
 	|?

 t|?
 |?
 4|?
 iF) #A#A"@$B >#A(F >	 	 (F"@#A"@$B >#A'E#A"@ >#A >=    < $K$K#J G"I"I(O#J	 	 $K$K#J G"I"I(O#J	  	  . A # m: :|?
F  ddd $d 	d
 $d $d Td $Td 'd "4d td d )$d /d $Td  ,U!d" 0#d d$ t%d& 'd( &t)d* (+d, '-d. &t/d0 (1d2 "43d4 (5d6 %d7d8 T9d: ;d< &t=d> +E?d@ )%AdB $TCdD 'Ed d dF (GdH "4IdJ &tKdL (MdN 1$OdP  QdR *:SdT +DUdV &tWdX #DYdZ *4[d\ $T]d^ t_d` "4adb *5cdd +Eedf tgd d dh  idj !$kdl %dmdn $Todp /qdr "5sdt +Dudv wdx !$ydz &t{d| +D}d~  d@ -dAdB dCdD $UEdF +DGdH "4Id d dJ tKdL #DMdN dOdP !$QdR  SdT '
UdV $UWdX !$YdZ ([d\ )%]d^ )$_d` tadb cdd Tedf tgdh "4idj #Dkd dl )-)-*/$( $$('+#!&#'  Gd d dG|?
P  -q  *+12     *+56./>?'(*+&',-$%12    23BC12./>?,-01;<	  	  ./*+   # 23=>34/0566701562378CD349:    $ 23=>34/05601239:	  	 ! +,+,)*45+,67*+'(?@,-78&'    " ./9:4534	    56;<45;<=>   Ek k` ,.$%! !
 :1#$ $ -q )1  '  4Q	 
 +A  .q  3C  :3  ;C  @  ,Q  "1  ,S  ,Q  4Q   #A! " 4Q# ( *-58:=-.	! !) : -069;>AD	    -0;>;>=@	! ! @  @#!$ $* & ('  +G  ,W	 
 /  $W  +G  /  )'  +G  ,W  6w  0  <W  =g   +G! & &.4;>E5<,3! ! +G 5   B $%)*(),-+,&'12)*,-78    -067&)3:4;25,/! ! '.18,37>	# # 0";   D & *G  /  )'	 
 +G  0  (  /  3G  -g  5g  +G  $W  .w  8   +G! " <W# $ +2.529+25<076=293:077     < +2)0<C%,,39@+207	! 	! 07=D" "
 .w#Y/ /d '(12   
 '(./! !	# 	# / 3Q  1!  <Q	 
 ?  Fq  .q  8  9!  1!  ;A  6q  21  8  +A   8! " 4Q# $ ?%   (!BA!Da! I!! G	!
 <Q! Fq! 1!! 9!! Ma! OPQ! QRS! .s! 4S! <S! ;C!  :3!!" 23#!$ 4S%! !* ;<@A   
 07:A5<@G	# #[3  3 l 295<29=D/6:A297>3:4;5<@G    ELFMHO/65<! ! 07:A5<@G	# #-! !> /6(/,3)04;.5&-18)0#*    '.4;#*)0	! ! '.18# #'   2 ' .  7  3G	 
 =g  (  '  8  *7  +G  0  ,W  1'  1'  -g   -g! " 8# ( *118+218,3! ! 4W  ("=! !F / :G  7  5g	 
 6w  -g  6w  A'  5g  8  >w  4W  :7  3G  :7   <W! & 29076=7>6=9@! !' < '.)0*1*19@4;)0    +29@)0! ! 8#   ( :A9@;B:A079@:A)018
  
  23*+67,-	    &',-89*+,-! ! uI I[w wQ|?
@  A|?
^  !z!v! ! 
	!
 ! y! z! ~! y! ,! =! z! i! y! !  '!!" y#!$ '-+! ! !_|?
L "$ $M|?
T #VU|?
Z "#+0$"& %  6:959X9 59 U	9
 59 U9 D9 T9 59 U9 59 W9 9 59 X9  F!9" h#9 9$ I%9& 5'9( e)9* 5+9, 5-9. k/90 Z192 F394 F59: Z;9< Z=9> 5?9@ 6A9B 5C9D 5E9H FI9J FK9 9N '"   !"")"!(%  '"q9 9 9v ""$"$!#"$&"! ! !        &"&$2+ (%(( *'(# # AAA! #.% #.%[r r[|?
@ #&*(,,0,0)-+/6:#'#'"&#(	( ( #($)#'/3$)+/26)$ $. r% '+!%$(%'*/& & ',#'$)*.	# # '+#'$)!$*/( ( $(&*#'$)!$%'$(,0*/	* 	*  #u= =~ y  &&+$($(%)- -$ $ r% ',%)& &
 %e( ',%)!%* *  #3# #> "#3 "#3 	  "#3 "#3 	 Oo oA|?
` Ya|?
f "&$"&!..w77!..w77 "..s33T5F5Fw5O5OP!..u55t7H7H7S7ST!..s33T5F5Fy5Q5QR!..s33T5F5Fy5Q5QR!..v668I8I)8T8TU!..t44d6G6G	6R6RS!..t44d6G6G	6R6RS!..u55t7H7H7S7ST!..u55t7H7H7S7ST!..v668I8I)8T8TU!..v668I8I)8T8TU!..v668I8I)8T8TU!..v668I8I)8T8TU!..w779J9J99U9UV!..w779J9J99U9UV!..w779J9J99U9UV!..w779J9J99U9UV#"( "..s33T5F5Fw5O5OP!..u55t7H7H7S7ST!..s33T5F5Fy5Q5QR!..s33T5F5Fy5Q5QR!..v668I8I)8T8TU!..t44d6G6G	6R6RS!..t44d6G6G	6R6RS!..u55t7H7H7S7ST!..u55t7H7H7S7ST!..v668I8I)8T8TU!..v668I8I)8T8TU!..v668I8I)8T8TU!..v668I8I)8T8TU!..w779J9J99U9UV!..w779J9J99U9UV!..w779J9J99U9UV!..w779J9J99U9UV#"+( (/ /b "&%"&!..u55!..x88 "..s33T5F5Fx5P5PQ!..u55t7H7H7T7TU!..s33T5F5Fz5R5RS!..s33T5F5Fz5R5RS!..v668I8I*8U8UV!..t44d6G6G
6S6ST!..t44d6G6G
6S6ST!..u55t7H7H7T7TU!..u55t7H7H7T7TU!..v668I8I*8U8UV!..v668I8I*8U8UV!..v668I8I*8U8UV!..v668I8I*8U8UV!..w779J9J:9V9VW!..w779J9J:9V9VW!..w779J9J:9V9VW!..w779J9J:9V9VW#"( "..s33T5F5Fy5Q5QR!..u55t7H7H7S7ST!..s33T5F5Fy5Q5QR!..s33T5F5Fy5Q5QR!..v668I8I)8T8TU!..t44d6G6G	6R6RS!..t44d6G6G	6R6RS!..u55t7H7H7S7ST!..u55t7H7H7S7ST!..v668I8I)8T8TU!..v668I8I)8T8TU!..v668I8I)8T8TU!..v668I8I)8T8TU!..w779J9J99U9UV!..w779J9J99U9UV!..w779J9J99U9UV!..w779J9J99U9UV#")' '. .c` `Fb):b&
b '
b +J	b
 -.?b ":b +Jb %jb )*b  b ,-@b *+>b "#6b #$7b  !1b  ()<!b" ./B#b b$ &':%b& %&6'b(  !1)b* ,]+b, )*:-b. //b0 -m1b2 1-3b4 12C5b6 (7b8 2=9b: ';b<  1=b> ,]?b@ ,-AAbB *=CbD 5mEb b bF (GbH '	IbJ ,YKbL +,DMbN &}ObP *=QbR #LSbT &|UbV *<WbX )*;YbZ +L[b\ 01B]b^ (_b` &|abb (cbd %mebf ,]gb b bh &}ibj $]kbl %mmbn .|obp &|qbr ():sbt ),ubv +Mwbx '(9ybz %&7{b| *=}b~ ))b@ *=AbB -.?CbD ,\EbF (GbH 'Ib b bJ &}KbL %mMbN ,]ObP .}QbR (SbT %lUbV &}WbX .}YbZ *=[b\ )-]b^ ),_b` %labb %lcbd -lebf *<gbh *+Cibj (kb bl .; 4$8 4/<*44@6B(2*4!-0<Cb b bH &|Ig gP "(w#|?
 |?
 |?
 | | |	    enablec                 l    t          t          |                               |           || j        d<   d S )Nr  )r  r?   set_sandbox_moderS   )r  r  r  s     r  r  zgate.set_sandbox_mode  s3    dD**6222&,]###r  c                 8   |                      | j        d          }|q	 |                     |          }|                     |di           }|                     |d          dk    | j        d<   n!# t
          $ r}d| j        d<   Y d}~nd}~ww xY w| j        d         S )a  
        :param dict [params]: extra parameters specific to the exchange API endpoint
        returns unifiedAccount so the user can check if the unified account is enabled

        https://www.gate.com/docs/developers/apiv4/#retrieve-user-account-information

        :returns boolean: True or False if the enabled unified account is enabled or not and sets the unifiedAccount option if it is None
        r  Nkeymode   F)	safe_boolrS   privateAccountGetDetail	safe_dictsafe_integer	Exception)r  paramsr  responseresultes         r  load_unified_statuszgate.load_unified_status  s     6FGG!7  77??%<<151B1B661R1RVW1W-.. 7 7 716-......7 |,--s   AA. .
B8
BBc                 ,    |                      |          S N)privateUnifiedPutUnifiedMode)r  r  s     r  upgrade_unified_trade_accountz"gate.upgrade_unified_trade_account  s    00888r  c                 X    |                      |          }|                     |d          S )a`  
        fetches the current integer timestamp in milliseconds from the exchange server

        https://www.gate.com/docs/developers/apiv4/#get-server-current-time

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        server_time)publicSpotGetTimer  r  r  r  s      r  
fetch_timezgate.fetch_time  s/     ))&11   =999r  symbolc                    d}|}|                     d          }|                     d          }|                     d          }d }|                     |d          }|                    d          dk    r|                     |d          }n |                     |d          }|dd	         }|                     |d          }	|                     |d
          }
|                     |          }|                     |          }i d|dz   |z   dz   dz   |z   dz   |	z   dz   |
z   d|dz   |z   dz   |z   dz   |z   dz   |	z   dz   |
z   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!k    rd"nd#|                     |	          |                     d           d d$d d d%d d d%d d d%d&d d'	S )(NUSDT-/_r   r   r        rB   20r  :r'  rM  settlebaseIdquoteIdsettleIdactiveFtyperk   r  r  rR   ri   rj   TrP   1Ccallr  amountpriceminr  )r  r  cost)	contractcontractSizeexpiryexpiryDatetime
optionTypestrike	precisionlimitsinfo)splitsafe_stringfindconvert_expire_date	parse8601r  )r  r  rM  r  optionParts
symbolBasemarketIdBaser'  r  r  r  datetime	timestamps                r  create_expired_option_marketz!gate.create_expired_option_market  s   ll3''\\#&&
||C((!!+q11;;sb  ##J22DD##L!44DAaC[F!!+q11%%k155
++F33NN8,,	+
$*u$s*T1F:S@6ICOR\\+
dSj5(3.7#=FLvUX[[^hh+
 D+
 U	+

 f+
 d+
 u+
 +
 e+
 H+
 d+
 t+
 E+
 E+
 e+
  d!+
" e#+
$  --c22&%/3%6%6&&U''//++C00    
   
     U+
 +
 +
 +	
r  NmarketIdmarket	delimiter
marketTypec                    |d uo1|                     d          dk    p|                     d          dk    }|r|| j        vr|                     |          S t          t          |                               ||||          S )Nz-Cr  z-P)r  markets_by_idr  r  r?   safe_market)r  r  r  r  r  isOptionr  s         r  r  zgate.safe_market  s    D(hd0C0Cb0H/ghmm\`NaNadfNf 	?X);;;44X>>>T4  ,,Xvy*UUUr  c                    | j         d         r|                                  |                     d          r|                                  g }|                     | j         d          }|                     |dg d          }t          dt          |                    D ]}||         }|dk    r)|                    | 	                    |                     9|dk    r)|                    | 
                    |                     h|d	k    r)|                    |                     |                     |d
k    r(|                    |                     |                     |}|                     |          S )ao  
        retrieves data on all markets for gate

        https://www.gate.com/docs/developers/apiv4/#query-all-supported-currency-pairs                                       # spot
        https://www.gate.com/docs/developers/apiv4/en/#list-all-supported-currency-pairs-supported-in-margin-trading         # margin
        https://www.gate.com/docs/developers/apiv4/en/#query-all-futures-contracts                                           # swap
        https://www.gate.com/docs/developers/apiv4/en/#query-all-futures-contracts-2                                         # future
        https://www.gate.com/docs/developers/apiv4/en/#list-all-contracts-for-specified-underlying-and-expiration-date       # option

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        r  Fr   r  r  r   rR   ri   rj   rk   )rS   load_time_differencecheck_required_credentialsr  r  	safe_listrangelenappendfetch_spot_marketsfetch_swap_marketsfetch_future_marketsfetch_option_marketsarrays_concat)r  r  rawPromisesfetchMarketsOptionsr  ir  resultss           r  fetch_marketszgate.fetch_markets  s    <12 	(%%'''**511 	'$$&&&"nnT\>JJ2G=a=a=abbq#e**%% 	F 	FAqJV## ""4#:#:6#B#BCCCCv%%""4#:#:6#B#BCCCCx''""4#<#<V#D#DEEEEx''""4#<#<V#D#DEEE!!'***r  c                 0   |                      |          }|                     |          }||g\  }}|                     |d          }g }t          dt	          |                    D ]}||         }	|                     |	d          }
|                     ||
          }|                     ||	          }|
                    d          \  }}| 	                    |          }| 	                    |          }|                     |d          }|                     |d|          }| 
                    |                     |                     |d                              }|                     |d          }|                     |d          }|d u}|                     |	d	d
          }|dk    r|nd }|                    i d|
d|dz   |z   d|d|dd d|d|dd ddddd|ddddddd|dk    dddd d | 
                    t          j        |d                    | 
                    t          j        |d                    d d d d d || 
                    |                     |                     |d                               d!| 
                    d"          |                     |dd#          d$|                     |	d%|          d d$d d d$|                     |d&          |r|                     |d'          nd d$d(||d)           |S )*NrB   r   r  r   maker_fee_rateamount_precisiontrade_statusr  	buy_startr  r  r  r'  rM  r  r  r  r  r  rR   TrP   ri   Frj   rk   r  tradabler  r  100r  r  r  r   r  min_base_amountmin_quote_amountmax_quote_amountr  r  r  r  r  r"  r!  r  r  r  r  r  r  r  createdr  )publicMarginGetCurrencyPairspublicSpotGetCurrencyPairsindex_byr  r  r  
safe_valuer  r  safe_currency_coder  parse_precisionsafe_numbersafe_integer_productr  r=   
string_div)r  r  marginPromisespotMarketsPromisemarginResponsespotMarketsResponsemarginMarketsr  r  
spotMarketrB   marginMarketr  r  r  r'  rM  takerPercentmakerPercentamountPrecisiontradeStatusr  rP   buyStart	createdTss                            r  r  zgate.fetch_spot_marketsB  s   99&AA!<<VDD/<>P.Q++nd;;L q#12233 C	 C	A,Q/J!!*d33B??="==L%%lJ??F hhsmmOFG**622D++G44E++FE::L++F4DlSSL"//0D0DTEUEUV\^pEqEq0r0rssO**6>BBK''
;;HT)F00[$OOH%-]]IMM 3b3$*u,3 3 	3
 $3 &3 73 D3 3 3 &3 3 %3 %3 ;*43  E!3" $#3$  **7+=lE+R+RSS**7+=lE+R+RSS $"&"-!..t/C/CDDTDTU[]hDiDi/j/jkk   $0055#//
AFF! !
  $//
<M__# 
  $# 
  $//8JKKOU_t//8JKKK[_  $ %e3 3 3 3 3 3 3h r  c                    g }|                      dd          }| j        d         rdg}t          dt          |                    D ]}||         }d|i}|                     |                     ||                    }t          dt          |                    D ]3}|                     ||         |          }	|                    |	           4|S )Nri   r   r  r  r   r  )get_settlement_currenciesrS   r  r  publicFuturesGetSettleContractsextendparse_contract_marketr  )
r  r  r  swapSettlementCurrenciescr  requestr  r  parsedMarkets
             r  r  zgate.fetch_swap_markets  s    #'#A#A&.#Y#Y <& 	0(.x$q#67788 	, 	,A/2H(G ;;DKKQW<X<XYYH1c(mm,, , ,#99(1+xPPl++++, r  c                    | j         d         rg S g }|                     dd          }t          dt          |                    D ]}||         }d|i}|                     |                     ||                    }t          dt          |                    D ]3}|                     ||         |          }	|                    |	           4|S )Nr  rj   r   r   r  )rS   r  r  r   publicDeliveryGetSettleContractsr  r   r  )
r  r  r  futureSettlementCurrenciesr"  r  r#  r  r  r$  s
             r  r  zgate.fetch_future_markets  s    <& 	I%)%C%CHn%]%]"q#899:: 	, 	,A1!4H(G <<T[[RX=Y=YZZH1c(mm,, , ,#99(1+xPPl++++, r  c                    |                      |d          }|                    d          }|                      |d          }|                      |d          }|                      |d          }|                     |          }|                     |          }	|                     |          }
|                     |d          }d}d}|+|d	z   |	z   d
z   |
z   dz   |                     |d          z   }d}n|d	z   |	z   d
z   |
z   }|                      |d          }|                      |d          }t          j        d|          }t          j        d|          }t          j        ||          }t          j        ||          }|	|
k    }|                      |d          }|dk    rd}i d|d|d|d|	d|
d|d|d|d|ddddd|dk    d|dk    d|dk    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/S )0NrC   r  r   r   r  expire_time ri   r  r  r  rj   order_price_deviate
mark_pricer  quanto_multiplierr  rB   r  r'  rM  r  r  r  r  r  rR   FrP   rk   r  Tr  r  r(  z0.0002order_price_roundr  leverage_minleverage_maxr  order_size_minorder_size_maxr  create_timer  r  )r  r  r
  safe_timestampyymmddr=   
string_sub
string_add
string_mulr  iso8601r  r  )r  r  r  rB   partsr  r  dater'  rM  r  r  r  r  priceDeviate	markPriceminMultipliermaxMultiplierminPricemaxPriceisLinearr  s                         r  r   zgate.parse_contract_market  s   t ff--!!%++""5!,,q))&&v..''00((22$$V];;
CZ%'#-6<t{{6SU?V?VVF!JJCZ%'#-6F''0EFF$$V\::	*3==*3==%mY??%mY??F?''0CDD3L2
"2
f2
 D2
 U	2

 f2
 f2
 w2
 2
 J2
 E2
 e2
 J&(2
 jH,2
 jH,2
 d2
  !2
" h#2
$ $|&&x00&&x00 --l;;"ll622++C00))&2EFF   ++FNCC++FNCC 
  ++F4DEE++F4DEE 
  ,,X66,,X66 
    $ 00MMc2
 2
 2
 2	
r  c                    g }|                                  }t          dt          |                    D ]<}||         }|                     i |          }||d<   |                     |          }t          dt          |                    D ]}||         }	|                     |	d          }
|                    d          }|                     |d          }|                     |d          }|                     |          }|                     |          }|dz   |z   }|                     |	d          }|                     |	d          }| 	                    |	d	          }|rd
nd}|rdnd}|dz   |z   dz   | 
                    |          z   dz   |z   dz   |z   }|                     |	d          }|                     |	d          }t          j        d|          }t          j        d|          }t          j        ||          }t          j        ||          }|                    i d|
d|d|d|d|d|d|d|ddddddd dd!ddd"d#d"d$d"d%d"d|                     d&          |                     d&          |                     d          ||                     |          |                     |          ||                     d          |                     |	d'          d(d d d)|                     |	d*          |                     |	d+          d)|                     |          |                     |          d)d d d)d,|                     |	d-          |	d.           >|S )/Nr   
underlyingrC   r  r   r  expiration_timestrike_priceis_callr  Pr  r  r  r  r+  r,  r  rB   r  r'  rM  r  r  r  r  r  rk   rR   FrP   ri   rj   Tr  r  r  z0.0003r.  r  r  r1  r2  r  r3  r  )fetch_option_underlyingsr  r  r  publicOptionsGetContractsr  r  r
  r4  r	  r5  r=   r6  r7  r8  r  r  r9  r  )r  r  r  r   r  rD  queryr  jr  rB   r:  r  r  r'  rM  r  r  r  isCalloptionLetterr  r<  r=  r>  r?  r@  rA  s                               r  r  zgate.fetch_option_markets|  sj   3355q#k**++ r	 r	A$QJKKF++E",E,55e<<HN 1c(mm,, G G!!%%ff55"((--))%33**5!44..v66//88e+,,V5FGG))&.AA;;&,5ss#'-8VV5
#-3dkk&6I6IICORXX[^^amm#//8MNN ,,V\BB	 ' 23 E E ' 23 E E"-mYGG"-mYGG 2"2f2 D2 U	2
 e2 f2 w2 2 H2 E2 e2 E2 e2 d2 d2  !2" d#2$  %!..x88!..x88$($5$5c$:$:$&*ll6&:&:"//77","&"3"3C"8"8!%!1!1&:M!N!N" " $(#'% %
 $(#3#3F<L#M#M#'#3#3F<L#M#M# #
 $(#4#4X#>#>#'#4#4X#>#>" "
 $(#'! ! $  $226=II"c2 2 2 2 2 2 2+GP r  c                     |                                  }g }t          dt          |                    D ]7}||         }|                     |d          }||                    |           8|S )Nr   rC   )publicOptionsGetUnderlyingsr  r  r  r  )r  underlyingsResponser   r  rD  rC   s         r  rI  zgate.fetch_option_underlyings  s}    ">>@@ q#12233 	) 	)A,Q/J##J77D""4(((r  c                    i }|3|d         r|d         |d<   |d         s|d         |d<   nT|d         |d<   nH|dk    }|d	k    }|s|r8|rd
nd}|                      |d|          }|                     |d          }||d<   ||gS )a  
 @ignore
        Fills request params contract, settle, currency_pair, market and account where applicable
        :param dict market: CCXT market, required when type is None
        :param str type: 'spot', 'swap', or 'future', required when market is None
        :param dict [params]: request parameters
        :returns: the api request object, and the new params object with non-needed parameters removed
        Nr  rB   rk   r  r  currency_pairri   rj   r  r  )safe_string_loweromit)	r  r  r  r  r#  ri   rj   defaultSettler  s	            r  prepare_requestzgate.prepare_request  s     j! 8&,Tl
#h' ;(.z(:GH%+1$<((6>DX%F +v +*. 9E//-PP6844$*!  r  Fc                     |                      ||          \  }}i }|s)|t          | j        dz             ||d<   |d         |d<   ||gS )  
 @ignore
        Fills request params currency_pair, market and account where applicable for spot order methods like fetchOpenOrders, cancelAllOrders
        :param dict market: CCXT market
        :param bool trigger: True if for a trigger order
        :param dict [params]: request parameters
        :returns: the api request object, and the new params object with non-needed parameters removed
        NzL spotOrderPrepareRequest() requires a market argument for non-trigger ordersrZ   rB   rS  )get_margin_moder2   rB   r  r  r  r  r  rK  r#  s          r  spot_order_prepare_requestzgate.spot_order_prepare_request#  sx     !00&AA
E 	4~'  3A  )A  B  B  B!+GI'-d|GO$r  c                 z    |                      ||          \  }}d|i}||r|d         |d<   n|d         |d<   ||gS )rY  rZ   NrB   r  rS  )rZ  r[  s          r   multi_order_spot_prepare_requestz%gate.multi_order_spot_prepare_request5  sd     !00&AA
Ez
  8$*4L!!+1$<(r  c                 f   |                      | j        ddd          }|                      |dd|          }|                     |ddg          }|dk    rd}n|dk    rd}n|d	k    rd}|r%|dk    rd
}|dk    rt          | j        dz             d}|                     |dd          \  }}|rd}||gS )ae  
 @ignore
        Gets the margin type for self api call
        :param bool trigger: True if for a trigger order
        :param dict [params]: Request params
        :returns: The marginMode and the updated request params with marginMode removed, marginMode value is the value that can be read by the "account" property specified in gates api docs
        defaultMarginModer  rR   rZ   r  r  r  rP   r*  normalzA getMarginMode() does not support trigger orders for cross marginFgetMarginModer  rX   )safe_string_lower_2rS   rU  r3   rB   handle_option_and_params)r  r  r  r`  r  isUnifiedAccounts         r  rZ  zgate.get_margin_modeJ  s     !44T\CVXdflmm--flIO`aa
6L)#<==  'JJ:%%!JJ2J 	pV##%
^++ +n!nooo #'#@#@Zj#k#k & 	#"JF##r  c                     |                      | j        |i           }|                      ||i           }|dk    rdgndg}|                      |d|          S )Nri   r  r  r  )r	  rS   )r  r  methodrS   fetchMarketsContractOptionsrV  s         r  r  zgate.get_settlement_currenciesg  s]    //$,b99&*oogvr&J&J#%)V^^5':<RTabbbr  c                    |                      | j        d          }|i S |                     |          }|                     |d          }i }t	          dt          |                    D ]}||         }|                     |d          }|                     |          }	|                     |d|          rdnd}
| 	                    |dg           }i }t	          dt          |                    D ]}||         }|                     |d	          }| 
                    |          }|||d|                     |d
           |                     |d           d|                     d          dddddddd	||<   |                     ||	|                     |d	          |
|                     |d           |                     |d
           |                     |d           d||                     d          |d          ||	<   |S )a-  
        fetches all available currencies on an exchange

        https://www.gate.com/docs/developers/apiv4/en/#query-all-currency-information

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        	apiBackupNcurrencyr   T	leveragedcryptochainsrC   deposit_disabledwithdraw_disabledz0.0001r  )depositr   )	r  rB   networkr  rq  r   r   r  r  delisted)rB   coderC   r  r  rq  r   r   r  r  r  )r	  rM   publicSpotGetCurrenciesr  r  r  r  r
  is_leveraged_currencyr  network_id_to_coder  r  safe_currency_structure)r  r  rj  r  indexedCurrenciesr  r  entry
currencyIdrt  r  rn  r  rL  chain	networkIdnetworkCodes                    r  fetch_currencieszgate.fetch_currenciesm  s]    OODI{;;	 I//77N !MM(J??q#h--(( ,	 ,	AQKE))%<<J**:66D"&"<"<ZO`"a"ao;;goD^^E8R88FH1c&kk**  q	 ,,UF;;	"55i@@!#*"#'>>%9K#L#LL$(NN5:M$N$N N!%!2!28!<!< $(#'$ $
 $(#'% %	 	) )%%(  77 ((77"nnUJ???#~~e5GHHH $u6I J JJ$!..x889 9  F4LL r  c                 B   |                                   |                     |          }|d         st          | j        dz             |                     |d|          \  }}|                     |                     ||                    }|                     |          S )av  
        fetch the current funding rate

        https://www.gate.com/docs/developers/apiv4/en/#query-single-contract-information

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `funding rate structure <https://docs.ccxt.com/?id=funding-rate-structure>`
        ri   z0 fetchFundingRate() supports swap contracts onlyN)load_marketsr  r4   rB   rW  'publicFuturesGetSettleContractsContractr  parse_funding_rate)r  r  r  r  r#  rK  r  s          r  fetch_funding_ratezgate.fetch_funding_rate  s     	V$$f~ 	ZDG&XXYYY--fdFCC??GUZ@[@[\\Z &&x000r  symbolsc                 d   |                                   |                     |          }d}|+|                     |d          }|                     |          }|                     |d|          \  }}|                     |                     ||                    }|                     ||          S )a  
        fetch the funding rate for multiple markets

        https://www.gate.com/docs/developers/apiv4/en/#query-all-futures-contracts

        :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 `funding rate structures <https://docs.ccxt.com/?id=funding-rates-structure>`, indexed by market symbols
        Nr   ri   )r  market_symbolsr  r  rW  r  r  parse_funding_rates)r  r  r  r  firstSymbolr#  rK  r  s           r  fetch_funding_rateszgate.fetch_funding_rates  s     	%%g..**7A66K[[--F--fffEE77GU8S8STTZ ''':::r  c                 v   |                      |d          }|                     ||dd          }|                     |d          }|                     |d          }|                     |d          }|                     |d          }|                     |d          }	|                     |d	          }
t	          j        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|                     |          iS )NrC   r  ri   r,  index_priceinterest_ratefunding_ratefunding_next_applyfunding_rate_indicative1000funding_intervalr  r  r=  
indexPriceinterestRateestimatedSettlePricer  r  fundingRatefundingTimestampfundingDatetimenextFundingRatenextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetimeinterval)r  safe_symbolr  r4  r=   r8  r9  parse_funding_interval)r  r  r  r  r  r=  r  r  r  fundingTimefundingRateIndicativefundingIntervals               r  r  zgate.parse_funding_rateP  s   V ##Hf55!!(FC@@$$X|<<	%%h>>
''/BB&&x@@))(4HII $ 0 0;T U U!,VT5E5EhPb5c5cdd
H
f
 
 *	

 L
 #D
 
 
 ;
 
 t||K88
 4
 #D
 "4
 "4
  '!
" &t#
$ 33ODD%
 
 	
r  c                 @    dddddd}|                      |||          S )NrT  rV  rW  16h24h)360000014400000288000005760000086400000r  )r  r  	intervalss      r  r  zgate.parse_funding_interval  s7    
 
	 	8X>>>r  rt  c                 `   |                                   |                     |          }d|d         i}|                     |                     ||                    }|                     |d          }|                     |d          }|                     |          }i }t          dt          |                    D ]p}	||	         }
| 	                    |
d          }|r#|                     |
d          }|                     |
d          }|                     |
d          }|
||||d	||<   q|S )
Nrk  rB   multichain_addressesr   obtain_failedr|  address
payment_id)r  rt  rk  r  tag)
r  rk  privateWalletGetDepositAddressr  r	  r  r
  r  r  r  )r  rt  r  rk  r#  r  	addressesr{  r  r  rz  obtainFailedrr  r  r  s                  r  fetch_network_deposit_addressz"gate.fetch_network_deposit_address  sJ   ==&&
 66t{{7F7S7STTOOH.DEE	%%h
;;
&&z22q#i..)) 	 	AaLE  ,,UODDL &&ug66G&&ui88G""5,77C " F7OO r  c                    |                                   |                     |          }d|d         i}|                     |                     ||                    }|                     |dg           }|                     |d          }|                     ||          }|                     |dd          }|                     |d          S )a  
        fetch a dictionary of addresses for a currency, indexed by network

        https://www.gate.com/docs/developers/apiv4/en/#generate-currency-deposit-address

        :param str code: unified currency code of the currency for the deposit address
        :param dict [params]: extra parameters specific to the api endpoint
        :returns dict: a dictionary of `address structures <https://docs.ccxt.com/?id=address-structure>` indexed by the network
        rk  rB   r  NFrr  )	r  rk  r  r  r	  r  safe_currencyparse_deposit_addressesr  )	r  rt  r  rk  r#  r  rn  r{  parseds	            r  "fetch_deposit_addresses_by_networkz'gate.fetch_deposit_addresses_by_network  s     	==&&
 66t{{7F7S7STT+A2FF%%h
;;
%%j(;;--fdEBB}}VY///r  c                     |                                   d}|                     |          \  }}|                     ||          }|                     |||          }||         S )a  
        fetch the deposit address for a currency associated with self account

        https://www.gate.com/docs/developers/apiv4/en/#generate-currency-deposit-address

        :param str code: unified currency code
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.network]: unified network code(not used directly by gate.com but used by ccxt to filter the response)
        :returns dict: an `address structure <https://docs.ccxt.com/?id=address-structure>`
        N)r  handle_network_code_and_paramsr  )select_network_code_from_unified_networks)r  rt  r  r~  chainsIndexedByIdselectedNetworkIdOrCodes         r  fetch_deposit_addresszgate.fetch_deposit_address  sp     	"AA&IIV CCD&QQ"&"P"PQUWbdu"v"v !899r  c           
         |                      |d          }|                     |           ||                      |d          ||                      |d          |                     |                      |d                    dS )Nr  rt  r  r|  )r  rk  r  r  rr  )r  check_addressrw  )r  depositAddressrk  r  s       r  parse_deposit_addresszgate.parse_deposit_address  s     "">9==7###"((6::##NLAA..t/?/?PW/X/XYY
 
 	
r  c                     |                                   |                     |          }d|d         i}|                     |                     ||                    }|                     ||          S )ac  
        fetch the trading fees for a market

        https://www.gate.com/docs/developers/apiv4/en/#query-personal-trading-fees

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `fee structure <https://docs.ccxt.com/?id=fee-structure>`
        rS  rB   )r  r  privateWalletGetFeer  parse_trading_feer  r  r  r  r#  r  s         r  fetch_trading_feezgate.fetch_trading_fee	  sr     	V$$VD\
 ++DKK,H,HII %%h777r  c                 ~    |                                   |                     |          }|                     |          S )ac  
        fetch the trading fees for multiple markets

        https://www.gate.com/docs/developers/apiv4/en/#query-personal-trading-fees

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `fee structures <https://docs.ccxt.com/?id=fee-structure>` indexed by market symbols
        )r  r  parse_trading_feesr  s      r  fetch_trading_feeszgate.fetch_trading_fees$	  s?     	++F33 &&x000r  c                     i }t          dt          | j                            D ]=}| j        |         }|                     |          }|                     ||          ||<   >|S Nr   )r  r  r  r  r  )r  r  r  r  r  r  s         r  r  zgate.parse_trading_fees?	  sh    q#dl++,, 	F 	FA\!_F[[((F!33HfEEF6NNr  c                    |                      |d          }|rdnd}|rdnd}|                      |d          }|rdn|}|rdn|}||                     |d	          |                     ||          |                     ||          d d d
S )Ngt_discountgt_taker_fee	taker_feegt_maker_fee	maker_feer  futures_taker_feefutures_maker_feer  )r  r  r!  r"  r%  r#  )r	  r  r  )	r  r  r  
gtDiscountr"  r!  r  takerKeymakerKeys	            r  r  zgate.parse_trading_feeG	  s     __T=99
",=+",=+??6:66*2=&&*2=&&&&vx88%%dH55%%dH55
 
 	
r  codesc                    |                                   |                     |          }i }i }t          dt          |                    D ]}i }||         }|                     |d          }|                     |          }	||                     |	|          sQ|                     |d          }
|
|                     |d          }n|t          |

                                          }t          dt          |                    D ]=}||         }|                     |          }|                     |
|                   ||<   >|d|d||	<   |S )a  
 @deprecated
        please use fetchDepositWithdrawFees instead

        https://www.gate.com/docs/developers/apiv4/en/#query-withdrawal-status

        :param str[]|None codes: list of unified currency codes
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a list of `fee structures <https://docs.ccxt.com/?id=fee-structure>`
        r   rk  Nwithdraw_fix_on_chainswithdraw_fix)r   rq  r  )r  privateWalletGetWithdrawStatusr  r  r  r
  in_arrayr	  r  listkeysrw  r  )r  r  r  r  r  withdrawFeesr  rz  r{  rt  withdrawFixOnChains
networkIdsrL  r}  r~  s                  r  fetch_transaction_feeszgate.fetch_transaction_feese	  ss    	66v>>$ q#h--(( 	 	ALQKE))%<<J**:66D!4==u+E+E!"&//%9Q"R"R"*#//~FF!"5":":"<"<==
q#j//22 b bA *1I"&"9"9)"D"DK040A0ABUV_B`0a0aL--( F4LL
 r  c                     |                                   |                     |          }|                     ||d          S )as  
        fetch deposit and withdraw fees

        https://www.gate.com/docs/developers/apiv4/en/#query-withdrawal-status

        :param str[]|None codes: list of unified currency codes
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a list of `fee structures <https://docs.ccxt.com/?id=fee-structure>`
        rk  )r  r  parse_deposit_withdraw_fees)r  r  r  r  s       r  fetch_deposit_withdraw_feesz gate.fetch_deposit_withdraw_fees	  sC     	66v>>( //%LLLr  rk  c                    |                      |d          }||                     |d          dd|                     |d          ddi d}|t          |                                          }t	          dt          |                    D ]a}||         }|                     ||                     |d                    }|                     ||                   ddd d dd	|d
         |<   b|S )Nr  r  F)r   r%  rq  )r  r   rq  r  r   rk  )r   rq  r  )	r	  r  r  r  r  r  rw  r  r  )	r  r   rk  r  r  	chainKeysr  chainKeyr~  s	            r  parse_deposit_withdraw_feezgate.parse_deposit_withdraw_fee	  s8   $ #ooc3KLL''^<<# 
 ''Y77#  
 
 *0557788I1c)nn--  $Q<"55h@P@PQTV`@a@abb  $001DX1NOO&+! !
  $&*   	3 	3z";// r  sincer  c                 H   |                                   d}||                     |          }|d         }|                     d||          \  }}|                     |||          \  }}	d|d<   ||                     |dz            |d<   |||d<   d}
|d	k    r*|                     |                     ||	                    }
nG|d
k    r*|                     |                     ||	                    }
nt          | j	        dz             | 
                    |
|||          S )a  
        fetch the history of funding payments paid and received on self account

        https://www.gate.com/docs/developers/apiv4/en/#query-futures-account-change-history
        https://www.gate.com/docs/developers/apiv4/en/#query-futures-account-change-history-2

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch funding history for
        :param int [limit]: the maximum number of funding history structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `funding history structure <https://docs.ccxt.com/?id=funding-history-structure>`
        Nr  r   fundr  r  fromr  ri   rj   z= fetchFundingHistory() only support swap & future market type)r  r  handle_market_type_and_paramsrW  parse_to_int"privateFuturesGetSettleAccountBookr  #privateDeliveryGetSettleAccountBookr9   rB   parse_funding_histories)r  r  r  r  r  r  r  rK  r#  requestParamsr  s              r  fetch_funding_historyzgate.fetch_funding_history	  sC    	[[((FH%F889NPVX^__e!%!5!5fdE!J!J "//==GFO$GG6>>>>t{{7Ta?b?bccHHX??GUb@c@cddHHtw)hhiii ++HfeUKKKr  c                    g }t          dt          |                    D ]4}||         }|                     |          }|                    |           5|                     |d          }	|                     |	|||          S )Nr   r  )r  r  parse_funding_historyr  sort_byfilter_by_symbol_since_limit)
r  r  r  r  r  r  r  rz  r  sorteds
             r  r  zgate.parse_funding_histories
  s    q#h--(( 	# 	#AQKE0077GMM'""""fk2200NNNr  c           
      <   |                      |d          }|                     |d          }|                     ||dd          }||                     |d          |                     |d          ||                     |          d |                     |d          dS )	Nr   textr  ri   r  r  change)r  r  rt  r  r  rB   r  )r4  r  r  r9  r  )r  r  r  r  r  s        r  r  zgate.parse_funding_history&
  s     ''f55	##D&11!!(FC@@&&vx88$$VX66"Y//&&tX66
 
 	
r  c           	         |                                   |                     |          }|                     ||d         |          \  }}|.|d         rt          |d          }nt          |d          }||d<   d|d<   d}|d         s|d	         r*|                     |                     ||                    }n|d
         r*|                     |                     ||                    }n{|d         r*|                     |                     ||                    }nI|d         r*|                     |                     ||                    }nt          | j
        dz             |                     |d          }|d         s|dz  }|d         rdnd}	|d         rdnd}
|                     |d          }|                     |||dd|	|
          }||d<   |S )a^  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://www.gate.com/docs/developers/apiv4/en/#get-market-depth-information
        https://www.gate.com/docs/developers/apiv4/en/#query-futures-market-depth-information
        https://www.gate.com/docs/developers/apiv4/en/#query-futures-market-depth-information-2
        https://www.gate.com/docs/developers/apiv4/en/#query-options-contract-order-book

        :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
        r  NrR   r  i,  r  Twith_idrP   ri   rj   rk   z. fetchOrderBook() not support self market typecurrentr   pr   srB   bidsasksnonce)r  r  rW  r  publicSpotGetOrderBookr  publicFuturesGetSettleOrderBook publicDeliveryGetSettleOrderBookpublicOptionsGetOrderBookr9   rB   r  parse_order_book)r  r  r  r  r  r#  rK  r  r  priceKey	amountKeyr
  r  s                r  fetch_order_bookzgate.fetch_order_book=
  s    	V$$ --ffVnfMMf~ (E4((E3$GG!	&> 		[VH- 		[224;;w3N3NOOHHF^ 	[;;DKKQV<W<WXXHHH 	[<<T[[RW=X=XYYHHH 	[55dkk'56Q6QRRHHtw)YYZZZB %%h	::	f~ 	)!D(Iv/11C0AAS	!!(D11&&xFFT\^ghhwr  c                    |                                   |                     |          }|                     |d|          \  }}d}|d         s|d         r*|                     |                     ||                    }n|d         r*|                     |                     ||                    }n|d         r*|                     |                     ||                    }n|d         r`|d         }|                    d          }|                     |d	          |d
<   | 	                    |                     ||                    }nt          | j        dz             d}	|d         r?t          d	t          |                    D ] }
||
         }|d         |d         k    r|}	 n!n|                     |d	          }	|                     |	|          S )a  
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://www.gate.com/docs/developers/apiv4/en/#get-currency-pair-ticker-information
        https://www.gate.com/docs/developers/apiv4/en/#get-all-futures-trading-statistics
        https://www.gate.com/docs/developers/apiv4/en/#get-all-futures-trading-statistics-2
        https://www.gate.com/docs/developers/apiv4/en/#query-options-market-ticker-information

        :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>`
        NrR   rP   ri   rj   rk   rB   r  r   rD  z+ fetchTicker() not support self market typerC   )r  r  rW  publicSpotGetTickersr  publicFuturesGetSettleTickerspublicDeliveryGetSettleTickersr  r  publicOptionsGetTickersr9   rB   r  r  r	  parse_ticker)r  r  r  r  r#  rK  r  r  r  tickerr  rz  s               r  fetch_tickerzgate.fetch_ticker
  s    	V$$--fdFCC&> 	XVH- 	X00We1L1LMMHHF^ 
	X99$++gu:U:UVVHHH 	X::4;;wPU;V;VWWHHH 	Xd|H"..--K$($4$4[!$D$DGL!33DKK4O4OPPHHtw)VVWWW( 	21c(mm,,   =F4L00"FE 1 __Xq11F  000r  r  c           
         |                      |g d          }d|v rdnd}|                     ||d|          }|                     |dd          }|                      |g d          }|                      |g d	          }|                     |d
          }	|                     |d          }
|                     |dd          }|                     |dd          }|                     |d          }|                     |dd          }|dk    rd}|                     |dd          }|dk    r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)|          S )*N)rS  r  rC   r,  r  rR   r  r  
last_price)
lowest_aska
ask1_price)highest_bidb
bid1_pricehigh_24hlow_24hB	bid1_sizeA	ask1_sizetbase_volumevolume_24h_basenanr  quote_volumevolume_24h_quotechange_percentager  r  r  highlowbid	bidVolumeask	askVolumevwapopenclosepreviousCloser  r%  averager  )
baseVolumequoteVolumer=  r  r  )safe_string_nr  safe_string_2r  r  safe_tickerr9  )r  r  r  r  r  r  r  r4  r2  r0  r1  r3  r5  r  r;  r<  r%  s                    r  r  zgate.parse_ticker
  s   J %%f.S.S.STT$0F$:$:ZZ
!!(FCDD!!&&,??  )J)J)JKK  )K)K)KLL
33vy11&&vsK@@	&&vsK@@	%%fc22	''?PQQ
J((ASTT%K%%f.ABB
 !
f!
!
 Y//!
 D	!

 3!
 3!
 !
 3!
 !
 D!
 D!
 T!
 D!
 T!
 d!
  *!!
" t#!
$ %&))&,??**6=AA-!
 !
 !
. /  	r  c                    |                                   |                     |          }|                     |d          }d}||                     |          }|                     d||          \  }}|                     d||          \  }}d}	d|d<   |dk    s|dk    r*|                     |                     ||                    }	n|dk    r*|                     |                     ||                    }	n|d	k    r*| 	                    |                     ||                    }	n|d
k    rw| 
                    d|d           |d         }
|
                    d          }|                     |d          |d<   |                     |                     ||                    }	nt          | j        dz             |                     |	|          S )aB  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market

        https://www.gate.com/docs/developers/apiv4/en/#get-currency-pair-ticker-information
        https://www.gate.com/docs/developers/apiv4/en/#get-all-futures-trading-statistics
        https://www.gate.com/docs/developers/apiv4/en/#get-all-futures-trading-statistics-2
        https://www.gate.com/docs/developers/apiv4/en/#query-options-market-ticker-information

        :param str[]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/?id=ticker-structure>`
        r   Nr   utc0timezonerR   rP   ri   rj   rk   r  rB   r  rD  z fetchTickers() not support self market type, provide symbols or set params["defaultType"] to one from spot/margin/swap/future/option)r  r  r  r  r  rW  r  r  r  r  check_required_argumentr  r  r9   rB   parse_tickers)r  r  r  firstr  r  rK  r#  r  r  r  r  s               r  fetch_tickerszgate.fetch_tickersK  s    	%%g..  !,,[[''F88QWXXe!%!5!5dD%!H!H$
6>>TX--00Wm1T1TUUHHV^^99$++g}:]:]^^HHX::4;;wP];^;^__HHX(()LLLd|H"..--K$($4$4[!$D$DGL!33DKK4W4WXXHHtw  *q   q  r  r  r!!(G444r  c                     |                                  }|                     |dd          |d<   |                     |d          |d<   |                     |d          |d<   d|v r|                     |d          |d<   |S )	Nfreezelockedused	availablefreetotalborroweddebt)rZ   r>  r  )r  rz  rZ   s      r  parse_balance_helperzgate.parse_balance_helperr  s    ,,..,,UHhGG**5+>>++E7;;"..ujAAGFOr  c                 	   |                                   |                                  |                     |d          }|                     |d          }d}|                     |dd          \  }}|                     dd|          \  }}|                     d||          \  }}|                     d|          \  }}	| |                     |          }
|
d         |d<   d}|r+| 	                    | 
                    ||                    }n|dk    r|dk    r+|                     | 
                    ||	                    }nO|d	k    r+|                     | 
                    ||	                    }n|d
k    r*|                     | 
                    ||	                    }nt          | j        dz             |dk    r*|                     | 
                    ||	                    }n|dk    r*|                     | 
                    ||	                    }nw|dk    r*|                     | 
                    ||	                    }nG|dk    r*|                     | 
                    ||	                    }nt          | j        dz             |dk    p|dk    p|dk    }|r|g}d|i}|d	k    o|dk    }|}d|v rg }|                     |dg           }t+          |                                          }t/          dt1          |                    D ],}||         }||         }||d<   |                    |           -|}t/          dt1          |                    D ]H}||         }|r|                     |d          }|                     |ddd	          }|                     |di           }|                     |di           }|                     |                     |d                    }|                     |                     |d                    }i }|                     |          ||<   |                     |          ||<   |                     |          ||<   |                     |                     |d                    }|                     |          ||<   J|r|n|                     |          }|S )a#  

        https://www.gate.com/docs/developers/apiv4/en/#get-unified-account-information
        https://www.gate.com/docs/developers/apiv4/en/#list-spot-trading-accounts
        https://www.gate.com/docs/developers/apiv4/en/#margin-account-list
        https://www.gate.com/docs/developers/apiv4/en/#funding-account-list
        https://www.gate.com/docs/developers/apiv4/en/#get-futures-account
        https://www.gate.com/docs/developers/apiv4/en/#get-futures-account-2
        https://www.gate.com/docs/developers/apiv4/en/#query-account-information

        :param dict [params]: exchange specific parameters
        :param str [params.type]: spot, margin, swap or future, if not provided self.options['defaultType'] is used
        :param str [params.settle]: 'btc' or 'usdt' - settle currency for perpetual swap and future - default="usdt" for swap and "btc" for future
        :param str [params.marginMode]: 'cross' or 'isolated' - marginMode for margin trading if not provided self.options['defaultMarginMode'] is used
        :param str [params.symbol]: margin only - unified ccxt symbol
        :param boolean [params.unifiedAccount]: default False, set to True for fetching the unified account balance
        :returns dict: a `balance structure <https://docs.ccxt.com/?id=balance-structure>`
        r  Fr   r  NrB   rS  rR   rP   r  z+ fetchBalance() not support self marginModer  ri   rj   rk   z, fetchBalance() not support self market typer  balancesr   rk  r  r'  rM  )r  r  r  rU  rd  r  rW  rZ  r  privateUnifiedGetAccountsr  privateSpotGetAccountsprivateMarginGetAccountsprivateMarginGetCrossAccountsr9   rB   privateMarginGetFundingAccountsprivateFuturesGetSettleAccounts privateDeliveryGetSettleAccountsprivateOptionsGetAccountsr	  r  r  r  r  r  r  r
  rP  safe_balance) r  r  r  re  r  rK  r#  r  r  requestQueryr  r  r  r  r  dataflatBalancesrR  r  r  r{  contentrz  r  symbolInnerr'  rM  baseCode	quoteCode	subResultrt  returnResults                                    r  fetch_balancezgate.fetch_balance{  s   & 	  """!!&(3368,, #'#@#@Yi#j#j &88vVVe!%!5!5dD%!H!H#'#7#7}#M#M 
L[[((F'-d|GO$ 	Y55dkk'66R6RSSHHV^^V##66t{{7L7Y7YZZx''88Wl9[9[\\~--==dkk'S_>`>`aa"47-Z#Z[[[Y;;DKKQ]<^<^__HHV^^;;DKKQ]<^<^__HHX<<T[[R^=_=_``HHX55dkk'<6X6XYYHHtw)WWXXXV^P)9Ptx?O 	" zHD H
 )<dfnLtZ<<H ((D1c$ii(( - -!!W
":.&0
###G,,,,Dq#d))$$ 	@ 	@AGE @++E?CC"..xsHMMufb99w;;2243C3CD*3U3UVV 33D4D4DUJ4W4WXX	"$	&*&?&?&E&E	(#'+'@'@'G'G	)$&*&7&7	&B&B{##..t/?/?z/R/RSS#88??t!)Hvvt/@/@/H/Hr  rP  	timeframec           	         |                                   |                     |          }d}|                     |dd          \  }}|r|                     d|||||d          S |d         r|                     |||||          S |                     |d          }i }	|                     |d|          \  }	}|                     | j        ||          |	d<   |d	         rd
nd}
||
nt          ||
          }| 	                    |d          }|.| 
                    |dz            }|                     |d          }||                     |          }| 
                    |dz            |	d<   |dz
  |z  }|                     |	d         |          }|                                 }t          ||          }|t          ||          |	d<   n||	d<   n|||	d<   ||	d<   d}|d	         r|dk    }|dk    }|s|r'|dz   |d         z   |	d	<   |                     |d          }|d         r*|                     |                     |	|                    }n[|d         r)|                     |                     |	|                    }n)|                     |                     |	|                    }|                     |||||          S )a0  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://www.gate.com/docs/developers/apiv4/en/#market-k-line-chart                       # spot
        https://www.gate.com/docs/developers/apiv4/en/#futures-market-k-line-chart               # swap
        https://www.gate.com/docs/developers/apiv4/en/#futures-market-k-line-chart-2             # future
        https://www.gate.com/docs/developers/apiv4/en/#options-contract-market-candlestick-chart  # option

        :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, limit is conflicted with since and params["until"], If either since and params["until"] is specified, request will be rejected
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.price]: "mark" or "index" for mark price and index price candles
        :param int [params.until]: timestamp in ms of the latest candle to fetch
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns int[][]: A list of candles ordered, open, high, low, close, volume(units in quote currency)
        Fr   paginater  rk   r  Nr  r  r  untilr  r   tor  r	  r
  r  rB   rj   ri   )r  r  rd  "fetch_paginated_call_deterministicfetch_option_ohlcvr  rW  rN  r  r  r  rU  parse_timeframesumseconds#publicDeliveryGetSettleCandlesticksr  "publicFuturesGetSettleCandlestickspublicSpotGetCandlesticksparse_ohlcvs)r  r  rf  r  r  r  r  rh  r  r#  maxLimitri  durationdistancetoTimestampcurrentTimestamprj  r  isMarkisIndexs                       r  fetch_ohlcvzgate.fetch_ohlcv  s   & 	V$$88zZZ& 	x::<QVX]_hjprvwww( 	T**69eUFSSS  11..vtVDD"..t	9UU
!*-7444"]UH1E1E!!&'22%%edl33EYYvw//F++I66H"//==GFO	X-H((76?H==K#||~~["233B  #B "  %$GG* 	TvoF'G 4 4&+ckF4L&@
#6733h aCCDKKPWY_D`D`aa aBB4;;wX^C_C_``55dkk'66R6RSSH  69eUKKKr  c                 N   |                                   |                     |          }i }|                     |d |          \  }}|                     | j        ||          |d<   |                     |                     ||                    }|                     |||||          S )Nr  )r  r  rW  r  rN  publicOptionsGetCandlesticksr  rs  )	r  r  rf  r  r  r  r  r#  r  s	            r  rl  zgate.fetch_option_ohlcv  s    V$$..vtVDD"..t	9UU
44T[[&5Q5QRR  69eUKKKr  c           
         |t          | j        dz             |                                  d}|                     |dd          \  }}|r|                     d|||d|          S |                     |          }|d         st          | j        dz             i }|                     |d|          \  }}|||d	<   ||                     |d
z            |d<   | 	                    |d          }|1| 
                    |d          }|                     |d
z            |d<   |                     |                     ||                    }	g }
t          dt          |	                    D ]b}|	|         }|                     |d          }|
                    |||                     |d          ||                     |          d           c|                     |
d          }|                     ||d         ||          S )a  
        fetches historical funding rate prices

        https://www.gate.com/docs/developers/apiv4/en/#get-all-futures-trading-statistics

        :param str symbol: unified symbol of the market to fetch the funding rate history for
        :param int [since]: timestamp in ms of the earliest funding rate to fetch
        :param int [limit]: the maximum amount of `funding rate structures <https://docs.ccxt.com/?id=funding-rate-history-structure>` to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest funding rate to fetch
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns dict[]: a list of `funding rate structures <https://docs.ccxt.com/?id=funding-rate-history-structure>`
        Nz5 fetchFundingRateHistory() requires a symbol argumentFr   rh  rW  ri   z7 fetchFundingRateHistory() supports swap contracts onlyr  r  r  ri  rj  r   r)  r)r  r  r  r  r  r  r  )r2   rB   r  rd  rk  r  r4   rW  r  r  rU  !publicFuturesGetSettleFundingRater  r  r  r4  r  r  r9  r  r  )r  r  r  r  r  rh  r  r#  ri  r  ratesr  rz  r  r  s                  r  fetch_funding_rate_historyzgate.fetch_funding_rate_history  s9    >#DG.e$efff88AZ\fgg& 	z::;TV\^cejlprxyyyV$$f~ 	aDG&__```..vtVDD$GG"//==GFO!!&'22YYvw//F --edl;;GDM99$++gv:V:VWW q#h--(( 		 		AQKE++E377ILL #//s;;& LL33      e[11009I5RWXXXr  c           	      ,   t          |t                    r|                     |d          |                     |d          |                     |d          |                     |d          |                     |d          |                     |d          gS |                     |d          |                     |d          |                     |d	          |                     |d
          |                     |d          |                     |d          gS )Nr      r     r     r)  ohlr"  v)
isinstancer  r4  r  )r  ohlcvr  s      r  parse_ohlcvzgate.parse_ohlcv  s   2 eT"" 	##E1--  **  **  **  **  **  ##E3//  ,,  ,,  ,,  ,,  ,, r  c                    |                                   d}|                     |dd          \  }}|r|                     d||||          S |                     |          }|                     |d|          \  }}|                     |dd          }	|	2|                     |dg          }|                     |	dz            |d<   |t          |d          |d<   |#|d	         r|                     |dz            |d
<   d}
|d         dk    s|d         dk    r*| 	                    | 
                    ||                    }
n|d         r*|                     | 
                    ||                    }
n|d         r*|                     | 
                    ||                    }
nM|d         dk    r*|                     | 
                    ||                    }
nt          | j        dz             |                     |
|||          S )ay  
        get the list of most recent trades for a particular symbol

        https://www.gate.com/docs/developers/apiv4/en/#query-market-transaction-records
        https://www.gate.com/docs/developers/apiv4/en/#futures-market-transaction-records
        https://www.gate.com/docs/developers/apiv4/en/#futures-market-transaction-records-2
        https://www.gate.com/docs/developers/apiv4/en/#market-trade-records

        :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
        :param int [params.until]: timestamp in ms of the latest trade to fetch
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/?id=public-trades>`
        Fr   rh  Nrj  ri  r  r  r  r  r  rR   rP   ri   rj   rk   z, fetchTrades() not support self market type.)r  rd  fetch_paginated_call_dynamicr  rW  safe_integer_2rU  r  r  publicSpotGetTradesr  publicFuturesGetSettleTradespublicDeliveryGetSettleTradespublicOptionsGetTradesr9   rB   parse_trades)r  r  r  r  r  rh  r  r#  rK  ri  r  s              r  fetch_tradeszgate.fetch_tradesH  s*   " 	88PZ[[& 	b44]FESXZ`aaaV$$, --fdFCC##FD'::YYvy11F --edl;;GDM"5$//GG&"4"//==GFO&>V##vf~'A'A//GU0K0KLLHHF^ 	Y88We9T9TUUHHH 	Y99$++gu:U:UVVHHF^x''224;;w3N3NOOHHtw)WWXXXR   65%@@@r  rB   c                     |t          | j        dz             |                                  |                     |||d|i          }|S )a@  
        fetch all the trades made from a single order

        https://www.gate.com/docs/developers/apiv4/en/#query-personal-trading-records
        https://www.gate.com/docs/developers/apiv4/en/#query-personal-trading-records-by-time-range
        https://www.gate.com/docs/developers/apiv4/en/#query-personal-trading-records-3
        https://www.gate.com/docs/developers/apiv4/en/#query-personal-trading-records-4

        :param str id: order id
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades 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>`
        Nz. fetchOrderTrades() requires a symbol argumentorder_id)r2   rB   r  fetch_my_trades)r  rB   r  r  r  r  r  s          r  fetch_order_tradeszgate.fetch_order_trades  sV      >#DG.^$^___( ''uz2>NOOr  c                    |                                   |                                  d}|                     |dd          \  }}|r|                     d||||          S d}d}i }||                     |          nd}	|                     |d          }
|                     |dg          }|                     d|	|          \  }}|dk    p|dk    p|dk    }|r7|                     |	||          \  }}|dk    r|                     |d	          }n+|	|	d
         |d<   | 	                    d|          \  }}||d<   |||d<   || 
                    |dz            |d<   |
| 
                    |
dz            |d<   d}|dk    s|dk    r*|                     |                     ||                    }n|dk    r*|                     |                     ||                    }nw|dk    r*|                     |                     ||                    }nG|dk    r*|                     |                     ||                    }nt!          | j        dz             |                     ||	||          S )ab  
        Fetch personal trading history

        https://www.gate.com/docs/developers/apiv4/en/#query-personal-trading-records
        https://www.gate.com/docs/developers/apiv4/en/#query-personal-trading-records-by-time-range
        https://www.gate.com/docs/developers/apiv4/en/#query-personal-trading-records-3
        https://www.gate.com/docs/developers/apiv4/en/#query-personal-trading-records-4

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :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 int [params.until]: The latest timestamp, in ms, that fetched trades were made
        :param int [params.page]: *spot only* Page number
        :param str [params.order_id]: *spot only* Filter trades with specified order ID. symbol is also required if self field is present
        :param str [params.order]: *contract only* Futures order ID, return related data only if specified
        :param int [params.offset]: *contract only* list offset, starting from 0
        :param str [params.last_id]: *contract only* specify list staring point using the id of last record in previous list-query results
        :param int [params.count_total]: *contract only* whether to return total number matched, default to 0(no return)
        :param bool [params.unifiedAccount]: set to True for fetching trades in a unified account
        :param bool [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/?id=trade-structure>`
        Fr   rh  Nri  ri   rj   rk   r  rB   rS  rZ   r  r  r  rj  rR   rP   z. fetchMyTrades() not support self market type.)r  r  rd  r  r  r  rU  r  rW  rZ  r  privateSpotGetMyTradesr  (privateFuturesGetSettleMyTradesTimerange privateDeliveryGetSettleMyTradesprivateOptionsGetMyTradesr9   rB   r  )r  r  r  r  r  rh  r  r  r#  r  ri  r  r  s                r  r  zgate.fetch_my_trades  s   4 	  """88R\]]& 	d44_feUZ\bccc
)/);V$$$$!!&'226G9--99/6SYZZfFNO(8Odh>N 	,"2264HHOGVx6:66!+1$<(!%!5!5eV!D!DJ!+GI$GG"//==GFO --edl;;GDM6>>TX--224;;w3O3OPPHHV^^DDT[[QXZ`EaEabbHHX<<T[[RX=Y=YZZHHX55dkk'66R6RSSHHtw)YYZZZB   65%@@@r  tradec                    |                      |dd          }d }|                     |d          }|5t          j        |d          }|dd         }|                     |          }n|                     |dd          }|                      |d	d
          }d
|v rd
nd}|                     ||d|          }|                      |dd          }|                     |d          }	t          j        |d          rdnd}
t          j        |          }|                      |dd|
          }|                     |d          }|                     |d          }| 	                    |                     |d                    }| 	                    |                     |d                    }g }|[|                     |d          }| 
                    |          }||                     |d          }|                    ||d           ||                    |dd           ||                    |dd           |                     |d          }|                     ||||                     |          |d         |d |||	|d d |d |          S )!NrB   trade_idcreate_time_msr  r      r   r3  rS  r  rR   r  r  sizer  r  sellbuysider  r  r   gt_fee	point_feefee_currencyr  )r  rk  GTrx  roler  )r  rB   r  r  r  orderr  r  takerOrMakerr  r  r  r   r  )r>  r  r=   r8  r  safe_timestamp_2r  	string_lt
string_abs	omit_zeror
  r  
safe_trader9  )r  r  r  rB   r  msStringr  r  amountStringpriceStringcontractSider  orderId	feeAmountgtFeepointFeer  feeCurrencyIdfeeCurrencyCoder  s                       r  parse_tradezgate.parse_trade_  s   L tZ88	##E+;<<)(F;;H"~H))(33II--eV]KKI%%e_jII$.%$7$7ZZf
!!(FCDD))%6BB&&ug66!(!2<!E!EPvv5),77!!%FF""5*55$$UE22	t//x@@AA>>$"2"25+"F"FGG  ,,UNCCM"55mDDO&"&"2"268"D"DKK!+     KK      KK '     ''v66"Y//X&( " 
  
   	r  c                    |                                   d}|                     |dd          \  }}|r|                     d||||          S i }d}| |                     |          }|d         |d<   |||d<   |6|                     |dz            }||d	<   |                     |d
          |d<   |                     d||d          \  }}|                     |                     ||                    }	| 	                    |	|          S )a6  
        fetch all deposits made to an account

        https://www.gate.com/docs/developers/apiv4/en/#get-deposit-records

        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch deposits for
        :param int [limit]: the maximum number of deposits structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: end time in ms
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/?id=transaction-structure>`
        Fr   rh  NrB   rk  r  r  r   ' rj  MbP?)
r  rd  r  rk  r  rn  handle_until_optionprivateWalletGetDepositsr  parse_transactions
r  rt  r  r  r  rh  r#  rk  startr  s
             r  fetch_depositszgate.fetch_deposits   s0    	88R\]]& 	b44_dESXZ`aaa}}T**H"*4.GJ$GG%%edl33E#GFO HHU,=>>GDM224&%PP00Wf1M1MNN&&x:::r  c                    |                                   d}|                     |dd          \  }}|r|                     d||||          S i }d}| |                     |          }|d         |d<   |||d<   |6|                     |dz            }||d	<   |                     |d
          |d<   |                     d||d          \  }}|                     |                     ||                    }	| 	                    |	|          S )aD  
        fetch all withdrawals made from an account

        https://www.gate.com/docs/developers/apiv4/en/#get-withdrawal-records

        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch withdrawals for
        :param int [limit]: the maximum number of withdrawals structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: end time in ms
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/?id=transaction-structure>`
        Fr   rh  NrB   rk  r  r  r  r  rj  r  )
r  rd  r  rk  r  rn  r  privateWalletGetWithdrawalsr  r  r  s
             r  fetch_withdrawalszgate.fetch_withdrawals"  s2    	88ASU_``& 	e445GuV[]cddd}}T**H"*4.GJ$GG%%edl33E#GFO HHU,=>>GDM224&%PP33DKK4P4PQQ&&x:::r  r  r  r  c                    |                      ||          \  }}|                     |           |                                  |                     |          }|d         ||                     ||          d}|||d<   d}|                     |          \  }}||                     |          |d<   |                     |                     ||                    }	| 	                    |	|          S )a  
        make a withdrawal

        https://www.gate.com/docs/developers/apiv4/en/#withdraw

        :param str code: unified currency code
        :param float amount: the amount to withdraw
        :param str address: the address to withdraw to
        :param str tag:
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `transaction structure <https://docs.ccxt.com/?id=transaction-structure>`
        rB   )rk  r  r  Nmemor|  )
handle_withdraw_tag_and_paramsr  r  rk  currency_to_precisionr  network_code_to_id!privateWithdrawalsPostWithdrawalsr  parse_transaction)
r  rt  r  r  r  r  rk  r#  r~  r  s
             r  r   zgate.withdrawD  s    99#vFFV7###==&& 00v>>
 

 ?!GFO"AA&IIV"#66{CCGG99$++gv:V:VWW %%h999r  statusc                 P    dddddddddddddd}|                      |||          S )Npendingcanceledfailedok)PENDREQUESTDMOVEMANUALVERIFYPROCESEXTPEND	SPLITPENDCANCELFAILINVALIDDONEBCODEr  r  r  statusess      r  parse_transaction_statuszgate.parse_transaction_statusl  sO      " 
 
 &&999r  c                 :    ddd}|                      |||          S )Nrq  
withdrawal)dwr  )r  r  r  s      r  parse_transaction_typezgate.parse_transaction_type~  s.    
 
 tT222r  transactionc                    |                      |d          }d }|                      |d          }|U|d         dk    r.t          j        |d          rdnd}t          j        |          }n|                     |d                   }|                     |dd	          }|dk    rt          j        ||          }|                     |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S )NrB   r  r   r!  r  rq  r  r   
fee_amountr|  rk  txidr  r  r  r  r  rr  	addressToaddressFromr  tagTotagFromr  r  updatedrk  r  )internalcommentr   )r  r=   	string_gtr  r  r>  r6  safe_string_upperr
  r  r4  r  rw  r9  )r  r  rk  rB   r  r  feeCostStringr}  r{  rt  r  	rawStatusr  r  r  r  s                   r  r  zgate.parse_transaction  s   z k400''X>>>!u||$+$5lC$H$HZyyl&1,??222a599**;|LL<"-lMJJL**;@@	%%k:>>
&&z22V44$$[(;;	..y99"";	::{F33''[AA	
K
"
 D
 	

 d''55
 t..y99
 w
 
 4
 3
 T
 t
 f
 D
 
  Y//!
" t#
$  ))-88 )
 
 
 	
r  r  r  r  c                 8   |                                   |                                  |                     |          }|                     |d          }|                     |dd          }	|                     |d|	          }
|                     |d          }|
du}|du}|p|}| o|du }|                     ||||||          }d}|d         s|d         r.|r|                     |          }n|                     |          }n|d	         r.|r|                     |          }na| 	                    |          }nK|d
         r.|r| 
                    |          }n+|                     |          }n|                     |          }|                     ||          S )a  
        Create an order on the exchange

        https://www.gate.com/docs/developers/apiv4/en/#create-an-order
        https://www.gate.com/docs/developers/apiv4/en/#create-price-triggered-order
        https://www.gate.com/docs/developers/apiv4/en/#place-futures-order
        https://www.gate.com/docs/developers/apiv4/en/#create-price-triggered-order-2
        https://www.gate.com/docs/developers/apiv4/en/#place-futures-order-2
        https://www.gate.com/docs/developers/apiv4/en/#create-price-triggered-order-3
        https://www.gate.com/docs/developers/apiv4/en/#create-an-options-order

        :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]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
        :param dict [params]:  extra parameters specific to the exchange API endpoint
        :param float [params.triggerPrice]: 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
        :param bool [params.unifiedAccount]: set to True for creating an order in the unified account
        :param str [params.clientOrderId]: the clientOrderId of the order
        :returns dict|None: `An order structure <https://docs.ccxt.com/?id=order-structure>`
        r  r  	stopPricer  r  NrR   rP   ri   rj   )r  r  r  r	  safe_value_2create_order_requestprivateSpotPostOrdersprivateSpotPostPriceOrdersprivateFuturesPostSettleOrders#privateFuturesPostSettlePriceOrdersprivateDeliveryPostSettleOrders$privateDeliveryPostSettlePriceOrdersprivateOptionsPostOrdersparse_order)r  r  r  r  r  r  r  r  r  r  r  r  isStopLossOrderisTakeProfitOrderisTpslnonTriggerOrderorderRequestr  s                     r  create_orderzgate.create_order  s   J 	  """V$$//&)44((MMNN//&2CDD't3+47 5$5$*:'T/00tVUTZ[[&> 	CVH- 	C I55lCC::<HHF^ 	C R>>|LLCCLQQH 	C S??MMDD\RR44\BBHB &111r  r  c           	         g }g }t          |          }|dk    rt          | j        dz             |dk    rt          | j        dz             t          dt          |                    D ] }||         }|                     |d          }|                    |           |                     |d          }	|                     |d          }
|                     |d          }|                     |d	          }|                     |d
i           }|                     ||          }|                     |g d          }|t          | j        dz             d|d<   | 
                    ||	|
|||          }|                    |           "|                     |d ddd          }|                     |d                   }|d         s|d         rt          | j        dz             |S )Nr   z+ createOrders() requires at least one orderr  z8 createOrders() accepts a maximum of 10 orders at a timer  r  r  r  r  r  )r  r  r  r  ze createOrders() does not support advanced order properties(stopPrice, takeProfitPrice, stopLossPrice)TtextIsRequiredFrj   rk   z; createOrders() does not support futures or options markets)r  r3   rB   r  r  r  r	  r  safe_value_nr9   r  r  r  )r  r  r  ordersRequestsorderSymbolsordersLengthr  rawOrderr  r  r  r  r  orderParamsextendedParamstriggerValuer  r  r  s                      r  create_orders_requestzgate.create_orders_requestw  s   6{{1TW'TTUUU"TW'aabbbq#f++&& 	0 	0AayH''(;;H)))##Hf55D##Hf55D__Xx88FOOHg66E//(HbAAK![[f==N,,[:{:{:{||L'"47  .U  $U  V  V  V/3N+,44XtT6SXZhiiL!!,////%%lD%tLLWQZ((( 	hvh/ 	htw)ffgggr  c                 h   |                                   |                                  |                     ||          }|d         }|                     |d                   }d}|d         r|                     |          }n|d         r|                     |          }|                     |          S )a(  
        create a list of trade orders

        https://www.gate.com/docs/developers/apiv4/en/#batch-place-orders
        https://www.gate.com/docs/developers/apiv4/en/#place-batch-futures-orders

        :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>`
        r   r  NrR   ri   )r  r  r  r  privateSpotPostBatchOrders#privateFuturesPostSettleBatchOrdersparse_orders)r  r  r  r  
firstOrderr  r  s          r  create_orderszgate.create_orders  s     	  """33FFCCAY
Z122&> 	P66~FFHHF^ 	P??OOH  ***r  c                    |                      |          }|d         }|                     |d          }	|                     |dd          }
|                     |d|
          }|                     |d          }|d u}|d u}|p|}|r|rt          | j        dz             |                     |d          }|                     |g d	          }d }|                     |d
k    |dk    |          \  }}|                     |          }|rd}|                     |dd          }| 	                    |g d          }|dk    }|d
k    }|r|t          | j        dz   |z   dz             |ri|dk    s|dk    rt          | j        dz             |@|                     | j        dd          }|                     | j        d         |d          }|}|rd}|r\|                     |d          }|rd}nA|                     ||          }|dk    rt          j        |          n|}t!          |          }d }| o|	d u }|rD|rW|d         |d}|d         s|d         |d<   |rd |d!<   n!|dk    rd n|                     ||          |d!<   |||d"<   |||d#<   n\d }|                     d$|          \  }}|d         |||d%}|r|d&k    rd }d'} |                     |d(d)d'          \  } }|                     |d*          }!| 	                    |d*          }|!|                     ||!          }n| ro|t-          | j        d+z             |                     |          }"|                     |          }#t          j        |"|#          }$|                     ||$          }n|                     ||          }||d,<   n|                     ||          |d,<   |r|                     ||          |d!<   |||d-<   |                     |d.d$          }%|Xt5          |          d/k    rt7          | j        d0z             | 	                    |d.          }|d         d1k    rd2|z   }||d<   n|%rd2|                                 z   |d<   nh|d         rt;          | j        d3z             |r/|d         |d|d         d4}|d
k    rd |d5         d!<   n'|dk    rd n|                     ||          |d5         d!<   |	d }&d }'|r!|d&k    rd6nd7}&|                     ||          }'n"|r |d&k    rd7nd6}&|                     ||          }'|                     |d8d          }(|(dk     s|(d7k    rt7          | j        d9z             | 	                    |d8g          }|(|                     ||'          |&d:|d<   |||d5         d"<   |||d5         d#<   |||d5         d<   n|                     | j        d(i           })d }|                     d'|          \  }}|d}|||                     ||          |                     ||          ||d;|d         d<}|	|                     |)d=          }*|                     |d=|*          }+d }&d }'|r!|d&k    rd>nd?}&|                     ||          }'n"|r |d&k    rd?nd>}&|                     ||          }'|                     ||'          |&|+d@|d<   |||d         d<   |                     ||          S )ANr  r  r  r  r  r  zG createOrder() stopLossPrice and takeProfitPrice cannot both be defined
reduceOnly)r  tiftime_in_forcer  r  r  clientOrderId)r  r  r  r  r"  r  postOnlyr%  r  z- createOrder() requires a price argument for  ordersr  zF createOrder() timeInForce for market order can only be "FOK" or "IOC"defaultTimeInForcer  r  r  r   r8  r  rB   )r  r  rk   r  r  r  r  reduce_onlyr#  F)rS  r  rZ   r  r  Trw   r  r  a	   createOrder() requires the price argument for market buy orders to calculate the total cost to spend(amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to False and pass the cost to spend(quote quantity) in the amount argumentr  r$  r     zF createOrder() clientOrderId or text param must be up to 28 charactersr)  t-z: createOrder() conditional option orders are not supported)initialr  r,  r   r  
price_typezT createOrder() price_type should be 0 latest deal price, 1 mark price, 2 index price)r-  r  rule)r  r  r  r  rZ   r$  )r  r  r  z>=z<=)r  r.  r  ) r  r	  r   r-   rB   safe_string_lower_nhandle_post_onlyhandle_time_in_forcer>  rU  r2   r  rS   amount_to_precisionr=   
string_negintprice_to_precisionrZ  rd  r  cost_to_precisionr6   number_to_stringr8  r  r  r3   uuid16r9   r  r  ),r  r  r  r  r  r  r  r  r  r  r  r  r  r
  r  r  r"  exchangeSpecificTimeInForcer&  r  r%  isLimitOrderisMarketOrder
defaultTifexchangeSpecificTifisCloseamountToPrecisionsignedAmountr#  r  r  quoteAmountr  r  r  r  costRequestr  r.  triggerOrderPrice	priceTyperS   defaultExpirationr  s,                                               r  r  zgate.create_order_request  sI	   V$$*%//&)44((MMNN//&2CDD't3+47 5$5 	u0 	u*s sttt__V\::
&*&>&>vGnGnGn&o&o#001AC^bgCgiopp&//77 	 K **66?KK6  $_  $_  $_  `  `) 	rEM#DG.]$]`d$dgp$pqqq 		u$$+*>*>#DG.v$vwww&!%!1!1$,@TV[!\!\J*.*:*:4<;VXbdi*j*j'"5K  	+oofg66G +$($<$<VV$L$L!IMQWw12CDDD^o\**$*:'T/ e	C =; !'t"	 	 h' ;(.z(:GH%  g'*GG$$/4zzss@W@WX^`e@f@fGG$)-7GM**%0GEN!
%)%9%9%%H%H"
F &,D\ ) 
 
 ! Qdemm"&K8<5@D@]@]^dfs  vY  [_  A`  A`=5v++FF;;D!YYvv66F'&*&<&<VT&J&J: 	M =".tw  :E  0E  #F  #F  F+/+@+@+H+HL*.*?*?*F*FK*1*<\;*W*WK*.*@*@*U*UKK&*&<&<VV&L&L(3GH%%(,(@(@(P(PGH% N'+'>'>vu'M'MGG$*/:GO,!^^F4DeLLN(
 }%%**$TW/w%wxxx6+;<< #s**$(=$8M"/! ;&*T[[]]&:GFOh k"47-i#ijjj SC %+4L &    %Z0  8##25GI&w//:?1**##4KbKbcikpKqKqGI&w/?D(,%& ] &*U]]qq,0,C,CFM,Z,Z))* ]%)U]]qq,0,C,CFO,\,\) $ 1 1&, J JI 1}}	A(  4J  *J  K  K  K!YYv~>>F '0!%!8!8AR!S!S $	* *GI& )8BGI&}5*0;GI&u- ,1>GI&v. //$,rJJ!
%)%9%9$%G%G"
F&"'K !% $!%!8!8!G!G"&":":66"J"J#-)4  %Tl
 
 ?(,(9(9'<(P(P%!%!2!26<IZ![![JD(,%& ] )-ttD,0,C,CFM,Z,Z))* ](,ttD,0,C,CFO,\,\)!%!8!8AR!S!S $&0* *GI&
 %05B	*62{{7F+++r  r  c                    |                                   |                                  |                     |          }|d         st          | j        dz             |                     |ddi          }|                     |dd|d|          S )aC  
        create a market buy order by providing the symbol and cost

        https://www.gate.com/docs/developers/apiv4/en/#create-an-order

        :param str symbol: unified symbol of the market to create an order in
        :param float cost: how much you want to trade in units of the quote currency
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param bool [params.unifiedAccount]: set to True for creating a unified account order
        :returns dict: an `order structure <https://docs.ccxt.com/?id=order-structure>`
        rR   z9 createMarketBuyOrderWithCost() supports spot orders onlyr  Fr  r  N)r  r  r  r9   rB   r  r  )r  r  r  r  r  s        r  !create_market_buy_order_with_costz&gate.create_market_buy_order_with_cost  s     	  """V$$f~ 	ftw)ddeeeV&I5%QRR  5$fMMMr  c                    |                      |          }d }	|                     d||          \  }	}|                     |	          }
d}|                     |dd          \  }}|rd}
|dk    }|
dk    r%|s#t	          | j        dz   |z   dz   |	z   d	z             t          |          |d
         |
d}||d         r|                     ||          |d<   nq|dk    r?|                     t          j
        |                     ||                              |d<   n,|                     |                     ||                    |d<   ||                     ||          |d<   |d         s|d         |d<   |                     ||          S )Nr   Fr  rX   r  rR   z editOrder() does not support z orders for  marketsrB   )r  rS  rZ   r  r  r  r  r  r  )r  r  convert_type_to_accountrd  r6   rB   strr2  parse_to_numericr=   r3  r5  r  )r  rB   r  r  r  r  r  r  r  r  rZ   re  r:  r#  s                 r  edit_order_requestzgate.edit_order_request  s   V$$
!??VU[\\
F..z:: #'#@#@Vf#g#g & 	 Gf A"47-M#MPT#TWe#ehr#ru#  A  A  AB#D\
 

 f~ f$($<$<VV$L$L!!6>>&*&;&;G<NtOgOghnpvOwOw<x<x&y&yGFOO&*&;&;D<T<TU[]c<d<d&e&eGFO#66vuEEGGf~ 	3 &z 2GH{{7F+++r  c           	      H   |                                   |                                  |                     |          }|                     |||||||          }	d}
|d         r|                     |	          }
n|                     |	          }
|                     |
|          S )a  
        edit a trade order, gate currently only supports the modification of the price or amount fields

        https://www.gate.com/docs/developers/apiv4/en/#amend-single-order
        https://www.gate.com/docs/developers/apiv4/en/#amend-single-order-2

        :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
        :param bool [params.unifiedAccount]: set to True for editing an order in a unified account
        :returns dict: an `order structure <https://docs.ccxt.com/?id=order-structure>`
        NrR   )r  r  r  rM  privateSpotPatchOrdersOrderId$privateFuturesPutSettleOrdersOrderIdr	  )r  rB   r  r  r  r  r  r  r  extendedRequestr  s              r  
edit_orderzgate.edit_order  s    " 	  """V$$11"fdD&RWY_``&> 	R99/JJHH@@QQH@ &111r  c                 L    dddddddddddd}|                      |||          S )Nr7  closedr  )r7  _newfilled	cancelled
liquidatedr  r  expiredfinishedfinish	succeededr  r  s      r  parse_order_statuszgate.parse_order_status  sI    #" ! !
 
 &&999r  r  c           
         |                      |dd          }|sB|                     |                     |d          |d|                     |d          d          S |                     |ddi           }|                     |d	i           }|                     |d
          }|                     |d          }|                     |dd          }|                     |dd          }	|                     |d          }
|                     |d          }|                     |d
|          }|                     |d|          }|                     |dd|          }|dk    rd}|dk    }|                     |dd|	          }	|                     |d|
          }
|                     |d|          }|                     |d          }|                     |d          }|                     |d          }|                     |dd          }|r|	}d}|r:t          j
        |d          o|dk    }|rdnd}t          j        |	d          rdnd}
|                     |g d          }|                     |d          }||                     |d d!          }|jt          |          d"k    s|                    d#          d$k    rt          j        |d%          }n(t          |          d&k    rt          j        |d%          }|                     |d'          }||                     |d(d)          }|jt          |          d"k    s|                    d#          d$k    rt          j        |d%          }n(t          |          d&k    rt          j        |d%          }d
}d*|v sd|v rd+}|                     |d*d|          }|                     ||d,|          }g }|                     |d-          }||                    d.|d/           |                     |d0          }|?|                    |                     |                     |d1                    |d/           |                     |d2          }|Q|                    |                     |                     |d3                    t          j        |          d/           t          |          }|d4k    }|                     |          }t          j        |          }|                     |d5          } | d+k    s| d6k    re|                     |d          }!|                     |!          }|dk    r4|
dk    r.t          j        ||!          }d }|	}t          j        |	|!          }	d }"d }#||                     |          }"||                     |          }#|                     |di           }$|                      |$d7          }%|                      |d7|%          }&|                     |d          }'|'Ad|v r|                     |d         d          }'n d	|v r|                     |d	         d          }'|                     i d|                     |d          d8|'d9|"d:|                     |"          d;|#d<|d=|d|d>|d?|d@|&d|
d|dA|dB|dt          j        |	          dCt          j        |          d ||rd n|                     |d$          |r|ng d |dD|          S )ENr\  Tr  rejectedrB   )r%  r  r  rB   r  r,  r  r  r  r$  r#  r  r  r  r  r  r  leftfilled_totalavg_deal_price
fill_pricer  r  r  r  r  r  )	finish_asr  r7  r  r3  ctimer  .r   r     update_time_msupdate_timefinish_timerS  rR   r  r  r  r  r   r  rebated_feerebated_fee_currencyr   rZ   rX   is_reduce_onlyr%  r  r  lastTradeTimestampr  r  r  r&  r"  r  r:  r  )rV  	remainingr   r  r   r  )r  
safe_orderr  r   r	  safe_string_upper_2r>  r  safe_number_2r=   string_equalsr  r=  r  r  r8  r  r  r  r
  r3  r]  r  r  r  r  r9  )(r  r  r  r\  r  r  r  r  r  r  r  r  r&  remainingStringr  r  r:  r;  r  timestampStrlastTradeTimestampStrr  exchangeSymbolr  r  r  r   rY   numFeeCurrenciesmultipleFeeCurrenciesr  ro  rZ   averageStringr  rn  r,  reduceOnlyInitialr"  r%  s(                                           r  r	  zgate.parse_order  s]   L NN5+t<<	 	??!%!1!1%!@!@$&&ud33	$ $    ui<<//%B77##C44V,,..sOUKK##C6::V,,  g..##E:x@@vt44..uoukZZ%K4'##E8VVDDvt44  77**5&99~66''99$$U,<lKK 	$OD 	G#1%==X;RWCWM,988'D#-fc::F55D&&u.M.M.MNN	''/?@@--e]GLLL'|$$**l.?.?.D.D.I.I#*#5lF#K#KLL&&",,#*#5lF#K#KL $ 0 08H I I ($($6$6um]$[$[!$0,--337L7Q7QRU7V7VZ[7[7[,3,>?TV\,],])).//255,3,>?TV\,],])
u$$(e*;*;J++E?HhWW!!.&#zJJ  11KK      ue,,?KK 33D4D4DUN4[4[\\     !!%77KK 33D4D4DULb4c4cdd*622     t99 01 4((33&77	""5)44v7i#7#7 ,,U4DEEM''66G  tu}}#.NN	 +FMBB	!#)),77I ,!%!2!23H!I!I..	266 NN74DEE^^E+;=NOO
((77 E!! $ 0 0y1A6 J Je## $ 0 0y1A6 J J  
$""5$// 
] 
  
 Y//	 

 !"4 
 f 
 f 
 D 
 ; 
  
 * 
 D 
 U 
 L 
 w 
  g(00! 
" G&t,,# 
$ "0N44doodA6N6N19DDr/ 
  
  
0 1  	r  c                    |d n|                      |          }|                     |g dd          }|                     |g d          }|                     |dd          }|}|+|                     |ddg          }|d         dk    rd|z   }|}|                     d	||          \  }}	|d
k    p|dk    p|dk    }
|
r|                     |||	          n|                     |||	          \  }}t          |          |d<   ||gS )Nr  is_stop_orderstopFr~  r  r  r  r%  r   r)  r+  r   ri   rj   rk   r  )r  safe_bool_nrU  r>  r  rW  r\  rK  )r  rB   r  r  r  r  r%  r  r  rK  r  r#  r  s                r  fetch_order_requestzgate.fetch_order_requestR  sS    .t{{6/B/B""6+O+O+OQVWW6#G#G#GHH**66?KK$YYv'@AAFQ3&& $} 4#G88vvVVeFNO(8Odh>NNV  "T!5!5fdE!J!J!J\`\{\{  }C  EL  NS  ]T  ]T!'ll
''r  c                 8   |                                   |                                  |dn|                     |          }|                     d||          }|                     |d          }|                     |g dd          }|                     |||          \  }}	d}
|dk    s|dk    rW|r+|                     |                     ||	                    }
n)| 	                    |                     ||	                    }
n|dk    rV|r*| 
                    |                     ||	                    }
n|                     |                     ||	                    }
n|d	k    rV|r*|                     |                     ||	                    }
nq|                     |                     ||	                    }
nG|d
k    r*|                     |                     ||	                    }
nt          | j        dz             |                     |
|          S )a(  
        Retrieves information on an order

        https://www.gate.com/docs/developers/apiv4/en/#query-single-order-details
        https://www.gate.com/docs/developers/apiv4/en/#query-single-auto-order-details
        https://www.gate.com/docs/developers/apiv4/en/#query-single-order-details-2
        https://www.gate.com/docs/developers/apiv4/en/#query-single-auto-order-details-2
        https://www.gate.com/docs/developers/apiv4/en/#query-single-order-details-3
        https://www.gate.com/docs/developers/apiv4/en/#query-single-auto-order-details-3
        https://www.gate.com/docs/developers/apiv4/en/#query-single-order-details-4

        :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
        :param bool [params.unifiedAccount]: set to True for fetching a unified account order
        :returns: An `order structure <https://docs.ccxt.com/?id=order-structure>`
        Nr   r   r}  FrR   rP   ri   rj   rk   z* fetchOrder() not support self market type)r  r  r  r  r  r  r   privateSpotGetPriceOrdersOrderIdr  privateSpotGetOrdersOrderId)privateFuturesGetSettlePriceOrdersOrderId$privateFuturesGetSettleOrdersOrderId*privateDeliveryGetSettlePriceOrdersOrderId%privateDeliveryGetSettleOrdersOrderIdprivateOptionsGetOrdersOrderIdr9   rB   r	  )r  rB   r  r  r  r  r  r  r#  r  r  s              r  fetch_orderzgate.fetch_orderc  s&   , 	  """ .t{{6/B/B33L&&QQ**""6+O+O+OQVWW!%!9!9"ff!M!M6>>TX-- a@@WVcAdAdee;;DKKQ^<_<_``V^^ jII$++V]_lJmJmnnDDT[[QXZgEhEhiiX kJJ4;;W^`mKnKnooEEdkkRY[hFiFijjX::4;;wP];^;^__HHtw)UUVVV&111r  c                 4    |                      d||||          S )a  
        fetch all unfilled currently open orders

        https://www.gate.com/docs/developers/apiv4/en/#list-all-open-orders

        :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
        :param bool [params.trigger]: True for fetching trigger orders
        :param str [params.type]: spot, margin, swap or future, if not provided self.options['defaultType'] is used
        :param str [params.marginMode]: 'cross' or 'isolated' - marginMode for type='margin', if not provided self.options['defaultMarginMode'] is used
        :param bool [params.unifiedAccount]: set to True for fetching unified account orders
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        r7  )fetch_orders_by_status)r  r  r  r  r  s        r  fetch_open_orderszgate.fetch_open_orders  s       **665%PPPr  c                 2   |                                   |                                  |                     |d          }d}||                     |          }|d         }|                     d||          }|                     |d          }d}	|                     |ddd          \  }	}|	s#|||dk    r|                     d	||||          S |                     |d
          }i }
| 	                    |||          \  }
}|| 
                    |dz            |
d<   |1|                     |d          }| 
                    |dz            |
d<   |||
d<   |                     |                     |
|                    }|                     ||||          S )a  
        fetches information on multiple closed orders made by the user

        https://www.gate.com/en-eu/docs/developers/apiv4/#list-orders
        https://www.gate.com/en-eu/docs/developers/apiv4/#retrieve-running-auto-order-list
        https://www.gate.com/docs/developers/apiv4/en/#query-futures-order-list
        https://www.gate.com/docs/developers/apiv4/en/#query-auto-order-list
        https://www.gate.com/docs/developers/apiv4/en/#query-futures-order-list-2
        https://www.gate.com/docs/developers/apiv4/en/#query-auto-order-list-2
        https://www.gate.com/docs/developers/apiv4/en/#list-options-orders
        https://www.gate.com/docs/developers/apiv4/en/#query-futures-order-list-by-time-range

        :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 bool [params.trigger]: True for fetching trigger orders
        :param str [params.type]: spot, swap or future, if not provided self.options['defaultType'] is used
        :param str [params.marginMode]: 'cross' or 'isolated' - marginMode for margin trading if not provided self.options['defaultMarginMode'] is used
        :param boolean [params.historical]: *swap only* True for using historical endpoint
        :param bool [params.unifiedAccount]: set to True for fetching unified account orders
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        ri  Nr  r   r   F
historicalri   rZ  r  r  r  rj  r  )r  r  r  r  r  r  rd  r  rU  rW  r  &privateFuturesGetSettleOrdersTimeranger  r  )r  r  r  r  r  ri  r  resr  useHistoricalr#  r  s               r  fetch_closed_orderszgate.fetch_closed_orders  s   0 	  """!!&'22[[((FH%F001DffUUQ'' $ = =fFY[gin o ov 	Y5=U]PV..z65%QWXXX66**..vtVDD"//==GFOYYvw//F --edl;;GDM$GG>>t{{7TZ?[?[\\  65%@@@r  c                    d }||                      |          }|d         }d }|                     |dd          \  }}d }|                     d||          \  }}|dk    p|dk    }	i }
|	r|                     |||          n|                     |||          \  }
}|	r|r|                     |
d          }
|dk    rd	}||
d
<   |||
d<   |	rf||                     |dz            |
d<   |                     |d          }|1|                     |d          }|                     |dz            |
d<   |                     |dd          \  }}|||
d<   |
|gS )Nr  r  r  fetchOrdersByStatusrR   rP   rZ   rT  rZ  r  r  r  r  ri  rj  lastIdlast_id)	r  handle_param_bool_2r  r^  rW  rU  r  r  handle_param_string_2)r  r  r  r  r  r  r  r  r  rR   r#  ri  r  finalParamss                 r   prepare_orders_by_status_requestz%gate.prepare_orders_by_status_request  s   [[((FH%F2269fMM99:OQWY_``f5DH$4\`  Q$??QWXXXfjfzfz  |B  DH  JP  gQ  gQ 	4G 	4ii33GXF"$GG 	@ "&"3"3EDL"A"A%%fg66E 6733 $ 1 1%$, ? ?"889UU!'GI%%r  c                    |                                   |                                  d }||                     |          }|d         }|                     |dd          }|                     d||          }|                     |d          }	|                     |||||          \  }
}|	dk    p|	dk    }|dk    }|o|o| }d }|r|sX|r+|                     |                     |
|                    }nT| 	                    |                     |
|                    }n)| 
                    |                     |
|                    }n|	d	k    rV|r*|                     |                     |
|                    }n|                     |                     |
|                    }n|	d
k    rV|r*|                     |                     |
|                    }nq|                     |                     |
|                    }nG|	dk    r*|                     |                     |
|                    }nt!          | j        dz             |}|rTg }t%          dt'          |                    D ]4}|                     ||         d          }|                     ||          }5|                     ||||          }|                     ||||          S )Nr  r  r  r  r   rR   rP   r7  ri   rj   rk   z+ fetchOrders() not support self market typer  )r  r  r  safe_bool_2r  r  r  privateSpotGetOpenOrdersr  privateSpotGetOrdersprivateSpotGetPriceOrders"privateFuturesGetSettlePriceOrdersprivateFuturesGetSettleOrders#privateDeliveryGetSettlePriceOrdersprivateDeliveryGetSettleOrdersprivateOptionsGetOrdersr9   rB   r  r  r	  array_concatr  r  )r  r  r  r  r  r  r  r  r  r  r#  r  rR   
openStatusopenSpotOrdersr  r  r  ordersInnerr  s                       r  r  zgate.fetch_orders_by_status  s     """[[((FH%F((FCC001FPVWWQ''!%!F!FvvW\^cek!l!l5DH$4&
<*<W 	X _ ^#<<T[[R_=`=`aaHH#88Wm9\9\]]HH99$++g}:]:]^^V^^ cBB4;;wXeCfCfgg==dkk'S`>a>abbX dCCDKKPWYfDgDghh>>t{{7Ta?b?bccX33DKK4W4WXXHHtw)VVWWWf  	@F1c(mm,, @ @"oohqk8DD**6;??""665%@@00NNNr  c                    |                                   |                                  |dn|                     |          }|                     |g dd          }|                     |g d          }|                     d||          \  }}|dk    s|dk    r|                     |||          n|                     |||          \  }}	||d<   d}
|dk    s|dk    rW|r+|                     | 	                    ||	                    }
n)| 
                    | 	                    ||	                    }
n|dk    rV|r*|                     | 	                    ||	                    }
n|                     | 	                    ||	                    }
n|d	k    rV|r*|                     | 	                    ||	                    }
nq|                     | 	                    ||	                    }
nG|d
k    r*|                     | 	                    ||	                    }
nt!          | j        dz             |                     |
|          S )a  
        Cancels an open order

        https://www.gate.com/docs/developers/apiv4/en/#cancel-single-order
        https://www.gate.com/docs/developers/apiv4/en/#cancel-single-auto-order
        https://www.gate.com/docs/developers/apiv4/en/#cancel-single-order-2
        https://www.gate.com/docs/developers/apiv4/en/#cancel-single-auto-order-2
        https://www.gate.com/docs/developers/apiv4/en/#cancel-single-order-3
        https://www.gate.com/docs/developers/apiv4/en/#cancel-single-auto-order-3
        https://www.gate.com/docs/developers/apiv4/en/#cancel-single-order-4

        :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
        :param bool [params.unifiedAccount]: set to True for canceling unified account orders
        :returns: An `order structure <https://docs.ccxt.com/?id=order-structure>`
        Nr  Frp   rR   rP   r  ri   rj   rk   z+ cancelOrder() not support self market type)r  r  r  r  rU  r  r\  rW  #privateSpotDeletePriceOrdersOrderIdr  privateSpotDeleteOrdersOrderId,privateFuturesDeleteSettlePriceOrdersOrderId'privateFuturesDeleteSettleOrdersOrderId-privateDeliveryDeleteSettlePriceOrdersOrderId(privateDeliveryDeleteSettleOrdersOrderId!privateOptionsDeleteOrdersOrderIdr9   rB   r	  )r  rB   r  r  r  r  r  rK  r#  r  r  s              r  cancel_orderzgate.cancel_order  s   & 	  """ .t{{6/B/B""6+O+O+OQVWW6#G#G#GHH88PVWWe]aek]k]koswoo!@!@RW!X!X!X  GK  G[  G[  \b  dh  jo  Gp  Gp 
6>>TX-- dCCDKKPWYfDgDghh>>t{{7Ta?b?bccV^^ mLLT[[Y`boMpMpqqGGT[]jHkHkllX nMMdkkZacpNqNqrrHHU\^kIlIlmmX==dkk'S`>a>abbHHtw)VVWWWd &111r  idsc                    |                                   |                                  d}||                     |          }d}|dn|d         }|                     |d|          }|                     d||          \  }}|dk    }|r|t          | j        dz             |rZg }	t          dt          |                    D ]$}
||
         }||d}|		                    |           %| 
                    |	|          S d|i}|g}t          dt          |                    D ]}
|	                    ||
                    |                     |          }|                     |          S )	ar  
        cancel multiple orders

        https://www.gate.com/docs/developers/apiv4/en/#cancel-batch-orders-by-specified-id-list
        https://www.gate.com/docs/developers/apiv4/en/#cancel-batch-orders-by-specified-id-list-2

        :param str[] ids: order ids
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param bool [params.unifiedAccount]: set to True for canceling unified account orders
        :returns dict: an list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        Nr  r  rq   rR   z9 cancelOrders requires a symbol argument for spot marketsr   )rB   r  )r  r  r  rT  r  r2   rB   r  r  r  cancel_orders_for_symbols)privateFuturesPostSettleBatchCancelOrdersr  )r  r  r  r  r  r  rV  r  isSpotr  r  rB   	orderItemr#  	finalListr  s                   r  cancel_orderszgate.cancel_orders<  s    	  """[[((F#)>x8H''-HH99.&RXYYf&. 	kv~#DG.i$ijjj 		JN1c#hh'' 1 1V$# #	 %%i000011.&IIIf
 I	q#c((## 	% 	%ASV$$$$AA)LL  ***r  c                    |                                   |                                  g }t          dt          |                    D ]}||         }|                     |d          }|                     |          }|d         st          | j        dz             |                     |d          }||d         d}	|                    |	           | 	                    |          }
| 
                    |
          S )a  
        cancel multiple orders for multiple symbols

        https://www.gate.com/en-eu/docs/developers/apiv4/#cancel-a-batch-of-orders-with-an-id-list

        :param CancellationRequest[] orders: list of order ids with symbol, example [{"id": "a", "symbol": "BTC/USDT"}, {"id": "b", "symbol": "ETH/USDT"}]
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str[] [params.clientOrderIds]: client order ids
        :param bool [params.unifiedAccount]: set to True for canceling unified account orders
        :returns dict: an list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        r   r  rR   z4 cancelOrdersForSymbols() supports only spot marketsrB   )rB   rS  )r  r  r  r  r  r  r9   rB   r   privateSpotPostCancelBatchOrdersr  )r  r  r  r  r  r  r  r  rB   r  r  s              r  r  zgate.cancel_orders_for_symbolsh  s    	  """q#f++&& 	- 	-A1IE%%eX66F[[((F&> e"47-c#cddd!!%..B!' I !!),,,,88HH   ***r  c                 x   |                                   |                                  |dn|                     |          }|                     |dd          }|                     |ddg          }|                     d||          \  }}|dk    r|                     |||          n|                     |||          \  }}d}	|dk    s|dk    rW|r+|                     | 	                    ||                    }	n)| 
                    | 	                    ||                    }	n|dk    rV|r*|                     | 	                    ||                    }	n|                     | 	                    ||                    }	n|dk    rV|r*|                     | 	                    ||                    }	nq|                     | 	                    ||                    }	nG|d	k    r*|                     | 	                    ||                    }	nt!          | j        d
z             |                     |	|          S )a)  
        cancel all open orders

        https://www.gate.com/docs/developers/apiv4/en/#cancel-all-open-orders-in-specified-currency-pair
        https://www.gate.com/docs/developers/apiv4/en/#cancel-all-auto-orders
        https://www.gate.com/docs/developers/apiv4/en/#cancel-all-orders-with-open-status
        https://www.gate.com/docs/developers/apiv4/en/#cancel-all-auto-orders-2
        https://www.gate.com/docs/developers/apiv4/en/#cancel-all-orders-with-open-status-2
        https://www.gate.com/docs/developers/apiv4/en/#cancel-all-auto-orders-3
        https://www.gate.com/docs/developers/apiv4/en/#cancel-all-orders-with-open-status-3

        :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 bool [params.unifiedAccount]: set to True for canceling unified account orders
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        Nr  r  ro   rR   rP   ri   rj   rk   z/ cancelAllOrders() not support self market type)r  r  r  r  rU  r  r^  rW  privateSpotDeletePriceOrdersr  privateSpotDeleteOrders%privateFuturesDeleteSettlePriceOrders privateFuturesDeleteSettleOrders&privateDeliveryDeleteSettlePriceOrders!privateDeliveryDeleteSettleOrdersprivateOptionsDeleteOrdersr9   rB   r  )
r  r  r  r  r  r  rK  r#  r  r  s
             r  cancel_all_orderszgate.cancel_all_orders  sh   " 	  """ .t{{6/B/B""669==6FI#677889JFTZ[[ecgkqcqcq!F!FvwX]!^!^!^x|  yM  yM  NT  VZ  \a  yb  yb6>>TX-- ]<<T[[R_=`=`aa77G]8[8[\\V^^ fEEdkkRY[hFiFijj@@WVcAdAdeeX gFFt{{SZ\iGjGjkkAA$++gWdBeBeffX66t{{7M7Z7Z[[HHtw)ZZ[[[:   6222r  fromAccount	toAccountc                    |                                   |                     |          }|                     |          }|                     |          }|                     ||          }	|d         |	d}
|| j        d         vrd|
d<   ||
d<   n||
d<   || j        d         vrd|
d<   ||
d<   n||
d<   |dk    s|dk    rf|                     |dd          }|t          | j        d
z             |                     |          }|d         |
d<   | 	                    |d          }|dk    s|dk    s|dk    s|dk    r|d         |
d<   | 
                    |                     |
|                    }|                     ||          S )a  
        transfer currency internally between wallets on the same account

        https://www.gate.com/docs/developers/apiv4/en/#transfer-between-trading-accounts

        :param str code: unified currency code for currency being transferred
        :param float amount: the amount of currency to transfer
        :param str fromAccount: the account to transfer currency from
        :param str toAccount: the account to transfer currency to
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.symbol]: Unified market symbol *required for type == margin*
        :returns: A `transfer structure <https://docs.ccxt.com/?id=transfer-structure>`
        rB   rk  r  r  rP   r  rS  rj  r  NzA transfer requires params["symbol"] for isolated margin transfersrO   rQ   r  )r  rk  rJ  r  rS   r>  r2   rB   r  rU  privateWalletPostTransfersr  parse_transfer)r  rt  r  r  r  r  rk  fromIdtoId	truncatedr#  r  r  r  s                 r  r   zgate.transfer  s    	==&&--k::++I66..tV<<	 
 
 $,'7888&GFO'-GO$$$GFO%5666$GDM'+GO$$ GDMX!1!1''/JJF~'2u(uvvv[[((F'-d|GO$YYvx00FI4:#5#56Y;N;NTZ^hThTh (GH224;;w3O3OPP ""8X666r  r   c           
      j    |                      |d          d d |                     d |          d d d d |d	S )Ntx_id)	rB   r  r  rk  r  r  r  r  r  )r  r
  )r  r   rk  s      r  r  zgate.parse_transfer  sN     ""8W55//h??

 

 
	
r  r  c                    |t          | j        dz             |dk     s|dk    rt          | j        dz             |                                  |                     |          }|                     |d|          \  }}|                     | j        dd          }|                     |d          }|                     |d|          }	| 	                    |          }
|d	}	|}
|	d	k    s|	d
k    r|
|d<   d|d<   n|
|d<   d}|d         r*| 
                    |                     ||                    }nI|d         r*|                     |                     ||                    }nt          | j        dz             |S )a  
        set the level of leverage for a market

        https://www.gate.com/docs/developers/apiv4/en/#update-position-leverage
        https://www.gate.com/docs/developers/apiv4/en/#update-position-leverage-2

        :param float leverage: the rate of leverage
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: response from the exchange
        Nz) setLeverage() requires a symbol argumentr   r  z3 setLeverage() leverage should be between 1 and 100r  r`  cross_leverage_limitr  r  r  r  ri   rj   z+ setLeverage() not support self market type)r2   rB   r3   r  r  rW  r>  rS   r  r7  1privateFuturesPostSettlePositionsContractLeverager  2privateDeliveryPostSettlePositionsContractLeverager9   )r  r  r  r  r  r#  rK  r`  crossLeverageLimitr  stringifiedMarginr  s               r  set_leveragezgate.set_leverage&  s    >#DG.Y$YZZZ qLLhnnTW'\\]]]V$$--fdFCC ..t|\K^__!--e5KLL%%e\;LMM
 11(;;) J 2  J.$@$@.?G*+"%GJ"3GJ&> 	XMMdkkZachNiNijjHHH 	XNNt{{[bdiOjOjkkHHtw)VVWWW8 r  positionc                 d   |                      |d          }|                     ||dd          }|                     |dd          }|                      |d          }|/t          j        |d          rd}nt          j        |d          rd}|                      |d	          }|                      |d
          }|                      |d          }d }	||dk    rd}	nd}	|                      |d          }
d }|
?d}t          j        ||          }
t          j        t          j        ||          |
          }| 	                    |dd          }|dk    rd }| 
                    i d|dd d|                      |d          d|d|                     |          d| 	                    |dd          d|                     |          d|                     t          j        ||                    d|                     t          j        ||                    d|                     |          d|                     |d           d!|                     |          d|                     |d          d"|                     |d#          d$|                     |d%d&          d'|                     t          j        |                    d(|                     |d(          d |                     |d)          |                     |d*          d |                     |d+          |	|d d d d,
          S )-Nr  r  r  
accum_sizer  r  longshortmaintenance_ratevaluer  r  r  pnl_feer  	open_timefirst_open_timer   r  rB   r  r  r  lastUpdateTimestampri  r   initialMargininitialMarginPercentagemaintenanceMarginmaintenanceMarginPercentage
entryPriceentry_pricenotionalunrealizedPnlunrealised_pnlrealizedPnlrealised_pnlpnlr   r  	liq_pricer,  rP   )
marginRatioliquidationPricer=  	lastPrice
collateralr  r  r%  r  r  )r  r  r>  r=   r  r  r8  r7  r  r  safe_positionr9  r  r  rr  r  )r  r  r  r  r  r  maintenanceRater  r  r  feePaidinitialMarginStringtakerFeer  s                 r  parse_positionzgate.parse_positionk  s   V ##Hj99!!(FCDD!!(FLAA&11< s++ "4-- **85GHH##Hg66##Hj99
3$

'
 ""8Y77"? H(8<<G")"4W5GRZ5[5[]d"e"e))(KARSS	>>I!! #
H#
$#
 d&&vx88#
 	#

 Y//#
 "4#8#8=RX#Y#Y#
 T../BCC#
 &t'8'89KL_ai9j9j'k'k#
  !2!273EoW_3`3`!a!a#
 *4+<+<_+M+M#
 $**8]CC#
 ))(33#
 ((:>>#
 T--h8HII#
 4--hNN#
  **7+=d+C+CDD!#
" D,,V^DD##
$   $ 0 0; G G))(LAA**8X>>$!#7#
 #
 #
   	r  c                    |                                   |                     |          }|d         st          | j        dz             i }|                     ||d         |          \  }}|                     ||          }d}|d         r|                     |          }n?|d         r|                     |          }n!|d         dk    r|                     |          }| 	                    ||          S )aK  
        fetch data on an open contract position

        https://www.gate.com/docs/developers/apiv4/en/#get-single-position-information
        https://www.gate.com/docs/developers/apiv4/en/#get-single-position-information-2
        https://www.gate.com/docs/developers/apiv4/en/#get-specified-contract-position

        :param str symbol: unified market symbol of the market the position is held in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `position structure <https://docs.ccxt.com/?id=position-structure>`
        r  z/ fetchPosition() supports contract markets onlyr  Nri   rj   rk   )
r  r  r3   rB   rW  r  (privateFuturesGetSettlePositionsContract)privateDeliveryGetSettlePositionsContract"privateOptionsGetPositionsContractr  )r  r  r  r  r#  rQ  r  s          r  fetch_positionzgate.fetch_position  s    	V$$j! 	ZTW'XXYYY..vvf~vNN++gv66&> 	PDD_UUHHH 	PEEoVVHHF^x''>>OOHr ""8V444r  c                    |                                   d}|                     |dddd          }|0t          |          }|dk    r|                     |d                   }d}i }|                     d||          \  }}||dk    rd}|dk    r9|6|d         }|                    d	          }|                     |d          |d
<   n|                     d||          \  }}d}	|dk    r*|                     | 	                    ||                    }	n_|dk    r*| 
                    | 	                    ||                    }	n/|dk    r)|                     | 	                    ||                    }	|                     |	|          S )a?  
        fetch all open positions

        https://www.gate.com/docs/developers/apiv4/en/#get-user-position-list
        https://www.gate.com/docs/developers/apiv4/en/#get-user-position-list-2
        https://www.gate.com/docs/developers/apiv4/en/#list-user-s-positions-of-specified-underlying

        :param str[]|None symbols: Not used by gate, but parsed internally by CCXT
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.settle]: 'btc' or 'usdt' - settle currency for perpetual swap and future - default="usdt" for swap and "btc" for future
        :param str [params.type]: swap, future or option, if not provided self.options['defaultType'] is used
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/?id=position-structure>`
        NTr   r   rR   ri   rk   rB   r  rD  rj   )r  r  r  r  r  r  r  rW   privateFuturesGetSettlePositionsr  !privateDeliveryGetSettlePositionsprivateOptionsGetPositionsparse_positions)
r  r  r  r  symbolsLengthr  r#  r  r  r  s
             r  fetch_positionszgate.fetch_positionsF  s    	%%gtT4FFLLMq  WQZ0099:JFTZ[[fLdfnnD8"!$<&nnS11(,(8(8a(H(H%"224vFFOGV6>><<T[[RX=Y=YZZHHX==dkk'SY>Z>Z[[HHX66t{{7F7S7STTHz ##Hg666r  c                    |                                   |                     dd|          \  }}|                     d||          \  }}|dk    r|dk    rt          | j        dz             d}|dk    r*|                     |                     ||                    }nG|dk    r*|                     |                     ||                    }nt          | j        dz             | 	                    ||d          S )aI  
        retrieve information on the maximum leverage, and maintenance margin for trades of varying trade sizes

        https://www.gate.com/docs/developers/apiv4/en/#query-all-futures-contracts
        https://www.gate.com/docs/developers/apiv4/en/#query-all-futures-contracts-2

        :param str[] [symbols]: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `leverage tiers structures <https://docs.ccxt.com/?id=leverage-tiers-structure>`, indexed by market symbols
        r   Nrj   ri   z1 fetchLeverageTiers only supports swap and futurez2 fetchLeverageTiers() not support self market typerC   )
r  r  rW  r3   rB   r  r  r&  r9   parse_leverage_tiers)r  r  r  r  rK  r#  r  r  s           r  fetch_leverage_tierszgate.fetch_leverage_tiers  s
    	889MtU[\\e!%!5!5dD%!H!H8TW'ZZ[[[6>>;;DKKQ^<_<_``HHX<<T[[R_=`=`aaHHtw)]]^^^z ((7FCCCr  c                    |                                   |                     |          }|                     d||          \  }}|                     |||          \  }}|dk    r|dk    rt	          | j        dz             d}|dk    r*|                     |                     ||                    }n)|                     |                     ||                    }| 	                    ||          S )a  
        retrieve information on the maximum leverage, and maintenance margin for trades of varying trade sizes for a single market

        https://www.gate.com/docs/developers/apiv4/en/#query-risk-limit-tiers
        https://www.gate.com/docs/developers/apiv4/en/#query-risk-limit-tiers-2

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `leverage tiers structure <https://docs.ccxt.com/?id=leverage-tiers-structure>`
        r   rj   ri   z7 fetchMarketLeverageTiers only supports swap and futureN)
r  r  r  rW  r3   rB   $publicFuturesGetSettleRiskLimitTiersr  %publicDeliveryGetSettleRiskLimitTiersparse_market_leverage_tiers)	r  r  r  r  r  rK  r#  r  r  s	            r  fetch_market_leverage_tiersz gate.fetch_market_leverage_tiers!  s     	V$$889SU[]cdde!%!5!5fdE!J!J8TW'``aaa6>> @@WVcAdAdeeHHAA$++gWdBeBeffH//&AAAr  c                    |                      |d          }|                      |d          }|                      |d          }|                      |d          }|                      |d          }t          j        d|          }|}	|}
d}g }t          j        ||          r$t          j        ||          }|                    |                     t          j        ||                    |                     ||d d          |                      |d	          |                     |          |                     |          |                     |	          |                     t          j        d|
                    |d
           t          j        |	|          }	t          j        |
|          }
|}t          j        ||          $|S )NrC   r  r0  risk_limit_steprisk_limit_maxr  r  r  r  tierr  rk  minNotionalmaxNotionalmaintenanceMarginRatemaxLeverager  )r  r=   r  r  r7  r  r  r  )r  r  r  r  maintenanceMarginUnitleverageMaxriskLimitStepriskLimitMaxinitialMarginUnitr  initialMarginRatiofloorr&  caps                 r  parse_emulated_leverage_tiersz"gate.parse_emulated_leverage_tiersD  s   ##D&11 $ 0 07I J J&&t^<<((/@AA''.>??#.sK@@ 5.|44 	$UM::CLL))'*<S-*P*PQQ**8VT:NN ,,VX>>#0077#0055)-):):;P)Q)Q#001CCI[1\1\]]	 	 	 	 	 %,$67LNc$d$d!!(!34FHY!Z!ZE |44 	 r  c                    t          |t                    s|                     ||          S d}g }t          dt	          |                    D ]}||         }|                     |d          }|                    |                     |d          |d         |d         |||                     |d          |                     |d          |d           |}|S )	Nr   
risk_limitr   r  r'  r  r0  r  )r  r  r   r  r  r  r  rn  )r  r  r  r  r&  r  itemr  s           r  r  z gate.parse_market_leverage_tiers`  s     $%% 	D55dFCCCq#d))$$ 	& 	&A7D**4>>KLLA *"6N**)-)9)9$@R)S)S#//nEE	 	 	 	 	 &KKr  c                 ~   |                                   |                     |          }|d                                         |                     ||          d}|                     |          }|d         |d<   d|d<   |                     |                     ||                    }|                     ||          S )a  
        repay borrowed margin and interest

        https://www.gate.com/docs/developers/apiv4/en/#borrow-or-repay-2

        :param str symbol: unified market symbol
        :param str code: unified currency code of the currency to repay
        :param float amount: the amount to repay
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.mode]: 'all' or 'partial' payment mode, extra parameter required for isolated margin
        :param str [params.id]: '34267567' loan id, extra parameter required for isolated margin
        :returns dict: a `margin loan structure <https://docs.ccxt.com/?id=margin-loan-structure>`
        rB   r  rS  repayr  r  rk  upperr  r  privateMarginPostUniLoansr  parse_margin_loan)	r  r  rt  r  r  rk  r#  r  r  s	            r  repay_isolated_marginzgate.repay_isolated_margin  s     	==&& ,,..00v>>
 
 V$$#)$< !11$++gv2N2NOO %%h999r  c                 &   |                                   |                                  |                     |          }|d                                         |                     ||          d}d}|                     |dd          \  }}d}|r/d|d<   |                     |                     ||                    }n?|                     |                     ||                    }| 	                    |d	          }| 
                    ||          S )
a  
        repay cross margin borrowed margin and interest

        https://www.gate.com/docs/developers/apiv4/en/#borrow-or-repay

        :param str code: unified currency code of the currency to repay
        :param float amount: the amount to repay
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.mode]: 'all' or 'partial' payment mode, extra parameter required for isolated margin
        :param str [params.id]: '34267567' loan id, extra parameter required for isolated margin
        :param boolean [params.unifiedAccount]: set to True for repaying in the unified account
        :returns dict: a `margin loan structure <https://docs.ccxt.com/?id=margin-loan-structure>`
        rB   r  Fr   r  Nr%  r  r   )r  r  rk  r'  r  rd  privateUnifiedPostLoansr   privateMarginPostCrossRepaymentsr  r)  r  rt  r  r  rk  r#  re  r  s           r  repay_cross_marginzgate.repay_cross_margin  s    	  """==&& ,,..00v>>
 
 !#'#@#@I[]m#n#n & 	3%GFO33DKK4P4PQQHH <<T[[RX=Y=YZZH~~h22H" %%h999r  c                    |                                   |                     |          }|d                                         |                     ||          d}d}|                     |          }|d         |d<   d|d<   |                     |                     ||                    }|                     ||          S )a`  
        create a loan to borrow margin

        https://www.gate.com/docs/developers/apiv4/en/#borrow-or-repay-2

        :param str symbol: unified market symbol, required for isolated margin
        :param str code: unified currency code of the currency to borrow
        :param float amount: the amount to borrow
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.rate]: '0.0002' or '0.002' extra parameter required for isolated margin
        :returns dict: a `margin loan structure <https://docs.ccxt.com/?id=margin-loan-structure>`
        rB   r  NrS  borrowr  r&  )	r  r  rt  r  r  rk  r#  r  r  s	            r  borrow_isolated_marginzgate.borrow_isolated_margin  s     	==&& ,,..00v>>
 
 V$$#)$< "11$++gv2N2NOO( %%h999r  c                    |                                   |                                  |                     |          }|d                                         |                     ||          d}d}|                     |dd          \  }}d}|r/d|d<   |                     |                     ||                    }n)|                     |                     ||                    }| 	                    ||          S )	a  
        create a loan to borrow margin

        https://www.gate.com/docs/developers/apiv4/en/#borrow-or-repay

        :param str code: unified currency code of the currency to borrow
        :param float amount: the amount to borrow
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.rate]: '0.0002' or '0.002' extra parameter required for isolated margin
        :param boolean [params.unifiedAccount]: default True(set to False to use deprecated privateMarginPostCrossLoans method)
        :returns dict: a `margin loan structure <https://docs.ccxt.com/?id=margin-loan-structure>`
        rB   r  Frm   r  Nr1  r  )
r  r  rk  r'  r  rd  r,  r  privateMarginPostCrossLoansr)  r.  s           r  borrow_cross_marginzgate.borrow_cross_margin  s    	  """==&& ,,..00v>>
 
 !#'#@#@I\^n#o#o & 	V&GFO33DKK4P4PQQHH 77GV8T8TUUH %%h999r  c           	         |                      | j        ddd          }|                     |d          }|dk    r|                     |d          }|                     |d          }|                     |d          }|                     |d          |                     ||          |                     |d	          |                     |d d
d          ||                     |          |dS )Nr`  r  r  r3  r  rk  rS  rB   r  r  rP   )rB   rk  r  r  r  r  r  )	r>  rS   r  r4  r  r
  r  r  r9  )r  r  rk  r  r  r{  r  s          r  r)  zgate.parse_margin_loan)  s    J ''6I<Y`aa
%%dM::	##++D-@@I%%dJ77
##D/::##D$////
HEE&&tX66&&xsHEE"Y//
 
 	
r  c                     |                                   |                                  d}|                     |dd          \  }}i }|                     d||          \  }}d}| |                     |          }|d         |d<   d}	||                     |          }	|||d<   |||d	<   d}
d}|                     d|d
          \  }}|r*|                     |                     ||                    }
nl|dk    r7|	|	d         |d<   | 	                    |                     ||                    }
n/|d
k    r)| 
                    |                     ||                    }
|                     |
|	          }|                     ||||          S )aw  
        fetch the interest owed by the user for borrowing currency for margin trading

        https://www.gate.com/docs/developers/apiv4/en/#query-interest-deduction-records
        https://www.gate.com/docs/developers/apiv4/en/#query-interest-deduction-records-2

        :param str [code]: unified currency code
        :param str [symbol]: unified market symbol when fetching interest in isolated markets
        :param int [since]: the earliest time in ms to fetch borrow interest for
        :param int [limit]: the maximum number of structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.unifiedAccount]: set to True for fetching borrow interest in the unified account
        :returns dict[]: a list of `borrow interest structures <https://docs.ccxt.com/?id=borrow-interest-structure>`
        Fr   r  rj  NrB   rk  r  r  r  r  rS  )r  r  rd  r  rk  r  handle_margin_mode_and_params privateUnifiedGetInterestRecordsr  "privateMarginGetUniInterestRecords$privateMarginGetCrossInterestRecordsparse_borrow_interestsfilter_by_currency_since_limit)r  rt  r  r  r  r  re  r#  rk  r  r  r  interests                r  fetch_borrow_interestzgate.fetch_borrow_interest^  s    	  """ #'#@#@I^`p#q#q &224&II}}T**H"*4.GJ[[((F#GFO$GG
!??@UW]_fgg
F 	_<<T[[RX=Y=YZZHH:%%!+1$<(>>t{{7TZ?[?[\\HH7""@@WV\A]A]^^H..x@@228T5%PPPr  r  c                    |                      |d          }|                     ||          }|dnd}|                     |d          }||                      |d          |                     |                      |d                    |                     |d          |                     |d          d |||                     |          d		S )
NrS  r  r  r3  r  rk  r>  actual_rate)	r  r  rk  r>  r  amountBorrowedr  r  r  )r  r  r  r
  r  r9  )r  r  r  r  r  r  s         r  parse_borrow_interestzgate.parse_borrow_interest  s    ##D/::!!(F33$,$8ZZw
%%dM::	&&vx88//0@0@z0R0RSS((z:: ,,T=AA"$"Y//

 

 
	
r  c                 F    |                                  | j        d         z
  S )Nr  )millisecondsrS   )r  s    r  r
  z
gate.nonce  s!      ""T\2B%CCCr  GETc                    |d         }|d         }|                      ||                     |                    }	|                    d          dk    }
|
r|                    d          rp|                     |d          }|                     ||          }g }|}t          dt          |                    D ]}|                    ||                    |}|}	nYt          |t                    r.|                     |di           }|                     ||          }n|                     ||          }|dk    rdnd|z   }d|z   |z   }|dk    s|d	k    r|}| j        d
         |         |         }|t          | j        dz   |z   dz             ||z  }|dk    r|	r|d|                     |	          z   z  }n|                                  d}d}d}|dk    s|dk    rd|dk    r^|                    d          }|                     |dd          }|                    d          dk    p|                    d          dk    }|dk    s|dk    s|s|dk    r|	rz|                     |	          }|                     |	          }|                    d          dk    r/|                    d          dk    r|                    dd          }|d|z   z  }|dk    r|                     |	          }na|                     |	di           }|r|                     |          }|d|z   z  }|                      |	d          }	|                     |	          }|dn|}|                     |                     |          d          }|                                 }|                     |dz            }t5          |          }d| j        z   |z   }|                                ||||g}d                    |          } |                     |                     |           |                     | j                  t@          j!                  }!| j"        ||!d d!}||||d"S )#Nr   r   r  r  batch_cancel_ordersr*  r  rW   rV   rd   z! does not have a testnet for the z market type.r]   ?FrO   rQ   POSTdualr;  rF  DELETEPATCHzcurrencies=z%2C,rK  sha512r  z/api/
zapplication/json)KEY	TimestampSIGNzContent-Type)r_   rg  bodyr  )#rU  extract_paramsr  endswithr  implode_paramsr  r  r  r  r  r	  rM   r9   rB   	urlencoder  r  r  	rawencodereplacejsonhashencoder
  r  rK  rI   r'  joinhmacr  hashlibrO  r  )"r  pathrd   rg  r  r  rT  authenticationr  rK  containsSettler  	newParams	anyParamsr  rE  endPart
entirePathr_   queryStringrawQueryStringrequiresURLEncoding	pathParts
secondParturlQueryParamsbodyPayloadbodySignaturer
  r  timestampStringsignaturePathpayloadArraypayload	signatures"                                     r  signz	gate.sign  s   Q1v		&$"5"5d";";<<8,,r1 	5dmm,ABB 	5 ^^FA..F&&tV44DII1c)nn-- , ,  ++++FEE%% 	5 OOFAr22E&&tU33DD&&tV44D""3:4Z')
M!!t}'<'< Ji~.t4;tw)LLtSVeefffzX%% 3sT^^E2222++---KN"'""
(:(:6AQAQ JJsOO	!--iB??
'1v'>'>!'C&kYdIeIeijIj#%Vx%7%7<O%7TZ^eTeTe -%)^^E%:%:N"&.."7"7K"''66!;;@P@PQV@W@W[\@\@\&1&9&9%&E&E3,,CW$$99U++D!%!D!D! -"&.."@"@K3,,C		%11yy''!%""DK IIdkk+&>&>IIMJJLLE))%$,77I!)nnO#dl2Z?M"LLNNM>=ZijLii--G		$++g"6"6DK8P8PRYR`aaI{,! 2	 G fdwOOOr  c                    |                                   |                     |          }|                     |d |          \  }}|                     |          |d<   d }|d         r*|                     |                     ||                    }nI|d         r*|                     |                     ||                    }nt          | j        dz             | 	                    ||          S )Nr  ri   rj   z2 modifyMarginHelper() not support self market type)
r  r  rW  r7  /privateFuturesPostSettlePositionsContractMarginr  0privateDeliveryPostSettlePositionsContractMarginr9   rB   parse_margin_modification)r  r  r  r  r  r#  rK  r  s           r  modify_margin_helperzgate.modify_margin_helper  s    V$$--fdFCC 11&99&> 	_KKDKKX_afLgLghhHHH 	_LLT[[Y`bgMhMhiiHHtw)]]^^^--h???r  r]  c                     |                      |d          }|                     ||dd          }|                     |d          }||d         d dd ||                     |d          dd d d
S )	Nr  r  rP   r  r  rM  r  )
r  r  r  r  r  rM  rt  r  r  r  )r  r  r  r	  )r  r]  r  r  rM  s        r  ry  zgate.parse_margin_modification   s    8 ##D*55!!(FCDD  x00X&$OOFG44
 
 	
r  c                 2    |                      || |          S )a  
        remove margin from a position

        https://www.gate.com/docs/developers/apiv4/en/#update-position-margin
        https://www.gate.com/docs/developers/apiv4/en/#update-position-margin-2

        :param str symbol: unified market symbol
        :param float amount: the amount of margin to remove
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `margin structure <https://docs.ccxt.com/?id=margin-structure>`
        rz  r  r  r  r  s       r  reduce_marginzgate.reduce_margin,  s     ((&&AAAr  c                 0    |                      |||          S )a  
        add margin

        https://www.gate.com/docs/developers/apiv4/en/#update-position-margin
        https://www.gate.com/docs/developers/apiv4/en/#update-position-margin-2

        :param str symbol: unified market symbol
        :param float amount: amount of margin to add
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `margin structure <https://docs.ccxt.com/?id=margin-structure>`
        r}  r~  s       r  
add_marginzgate.add_margin:  s     ((@@@r  rQ  c           	         |                                   d}|                     |ddd          \  }}|r|                     d|||||d          S |                     |          }|d         st	          | j        dz             |d         |d         |                     | j        ||          d	}|||d<   |||d<   |                     | 	                    ||                    }	| 
                    |	|||          S )a  
        Retrieves the open interest of a currency

        https://www.gate.com/docs/developers/apiv4/en/#futures-statistics

        :param str symbol: Unified CCXT market symbol
        :param str timeframe: "5m", "15m", "30m", "1h", "4h", "1d"
        :param int [since]: the time(ms) of the earliest record to retrieve unix timestamp
        :param int [limit]: default 30
        :param dict [params]: exchange specific parameters
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns dict} an open interest structure{@link https://docs.ccxt.com/?id=open-interest-structure:
        Fr   rh  r  ri   z/ fetchOpenInterest() supports swap markets onlyrB   r  )r  r  r  Nr  r  )r  rd  rk  r  r3   rB   r  rN  #publicFuturesGetSettleContractStatsr  parse_open_interests_history)
r  r  rf  r  r  r  rh  r  r#  r  s
             r  fetch_open_interest_historyz gate.fetch_open_interest_historyH  s>    	88A[]ginoo& 	E::;UW]_dfkmvx~  AD  E  E  EV$$f~ 	ZTW'XXYYYtZ((()YOO
 

 $GG#GFO;;DKKQW<X<XYY, 0065%PPPr  c                     |                      |d          }|                     |d          |                     |d          |                     |d          ||                     |          |dS )Nr   r  open_interestopen_interest_usd)r  openInterestAmountopenInterestValuer  r  r  )r4  r  r  r9  )r  r>  r  r  s       r  parse_open_interestzgate.parse_open_interest  sw    & ''&99	&&vx88"&"2"28_"M"M!%!1!1(<O!P!P"Y//
 
 	
r  c                 X   |t          | j        dz             |                                  |                     |          }d}|                     d||          \  }}|dk    rt          | j        dz             |d         }|                    d          }d|                     |d	          i}	|||	d
<   |||	d<   |                     | 	                    |	|                    }
| 
                    |
|          }|                     |d          }|                     ||||          S )a  
        fetches historical settlement records

        https://www.gate.com/docs/developers/apiv4/en/#list-settlement-history

        :param str symbol: unified market symbol of the settlement history, required on gate
        :param int [since]: timestamp in ms
        :param int [limit]: number of records
        :param dict [params]: exchange specific params
        :returns dict[]: a list of `settlement history objects <https://docs.ccxt.com/?id=settlement-history-structure>`
        Nz4 fetchSettlementHistory() requires a symbol argumentr   rk   z6 fetchSettlementHistory() supports option markets onlyrB   r  rD  r   r  r  r  )r2   rB   r  r  r  r9   r  r  publicOptionsGetSettlementsr  parse_settlementsr  r  )r  r  r  r  r  r  r  r  r  r#  r  r   r  s                r  fetch_settlement_historyzgate.fetch_settlement_history  sB    >#DG.d$deeeV$$99:RTZ\bccf8tw)aabbb$<nnS))$**;::
 #GFO$GG33DKK4P4PQQ ,,Xv>>k;7700NNNr  c                    |                                   d}||                     |          }|d         }d}|                     d||          \  }}|dk    }|dk    }|s|st          | j        dz             |                     |||          \  }	}
|||	d<   d}|r*|                     |                     |	|
                    }n|||	d<   |0|                     |d	          }|t          | j        d
z             n6|d         }|
                    d          }|                     |d          |	d	<   |                     |                     |	|                    }|                     |di           }|                     |dg           }|                     ||          }|                     |d          }|                     ||||          S )a
  
        fetches historical settlement records of the user

        https://www.gate.com/docs/developers/apiv4/en/#query-personal-settlement-records
        https://www.gate.com/docs/developers/apiv4/en/#query-settlement-records

        :param str symbol: unified market symbol of the settlement history
        :param int [since]: timestamp in ms
        :param int [limit]: number of records
        :param dict [params]: exchange specific params
        :returns dict[]: a list of [settlement history objects]
        Nr  r   rk   rj   zC fetchMySettlementHistory() supports option and future markets onlyr  r  rD  z[ fetchMySettlementHistory() requires a symbol argument or an underlying parameter in paramsrB   r  r   r  r  r  )r  r  r  r9   rB   rW  #privateDeliveryGetSettleSettlementsr  r  r2   r  privateOptionsGetMySettlementsr	  r  r  r  )r  r  r  r  r  r  r  r  isFuturer#  rK  r  rD  r  r  r  r]  r   r  s                      r  fetch_my_settlement_historyz gate.fetch_my_settlement_history  s    	[[((FH%F99:TV\^deef8#8# 	p 	ptw)nnooo--fdFCC$GG +	Y  ??GUZ@[@[\\HH "'~!--flCC
%+DG  7T  -T  U  U  U & "$<&nnS11(,(8(8a(H(H%  ::4;;wPV;W;WXXH8R88vvr22,,T6::k;7700NNNr  c                     |                      |d          }|                     |d          }||                     ||          |                     |d          ||                     |          dS )Nr   r  settle_price)r  r  r  r  r  )r4  r  r  r  r9  )r  
settlementr  r  r  s        r  parse_settlementzgate.parse_settlement  sy    P ''
F;;	##J
;;&&x88%%j.AA"Y//
 
 	
r  c                     g }t          dt          |                    D ]1}|                    |                     ||         |                     2|S r  )r  r  r  r  )r  r   r  r  r  s        r  r  zgate.parse_settlementsJ  sZ    > q#k**++ 	I 	IAMM$//AGGHHHHr  c                 &   |                                   d}|                     |dd          \  }}|r|                     d||||          S d}d}d}i }	|                     dd|          \  }}|dk    s|dk    r"| |                     |          }|d         |	d<   |d	k    s|d
k    r<|d	k    rdnd}
|                     |d|
          }|                     |d          }||	d<   |||	d<   |||	d<   |                     d|	|          \  }	}|dk    r*|                     | 	                    |	|                    }n|dk    r*| 
                    | 	                    |	|                    }n|d	k    r*|                     | 	                    |	|                    }n_|d
k    r*|                     | 	                    |	|                    }n/|dk    r)|                     | 	                    |	|                    }|                     ||||          S )a  
        fetch the history of changes, actions done by the user or operations that altered the balance of the user

        https://www.gate.com/docs/developers/apiv4/en/#query-spot-account-transaction-history
        https://www.gate.com/docs/developers/apiv4/en/#query-margin-account-balance-change-history
        https://www.gate.com/docs/developers/apiv4/en/#query-futures-account-change-history
        https://www.gate.com/docs/developers/apiv4/en/#query-futures-account-change-history-2
        https://www.gate.com/docs/developers/apiv4/en/#query-account-change-history

        :param str [code]: unified currency code
        :param int [since]: timestamp in ms of the earliest ledger entry
        :param int [limit]: max number of ledger entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: end time in ms
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns dict: a `ledger structure <https://docs.ccxt.com/?id=ledger-entry-structure>`
        Fr   rh  NrR   rP   rB   rk  ri   rj   r  r  r  r  r  rj  rk   )r  rd  r  r  rk  rT  rU  r  privateSpotGetAccountBookr  privateMarginGetAccountBookr  r  privateOptionsGetAccountBookparse_ledger)r  rt  r  r  r  rh  r  rk  r  r#  rV  r  s               r  fetch_ledgerzgate.fetch_ledgern  sW   $ 	88PZ[[& 	`44]D%QVX^___99-vVVfFNN 0 0==..&.tn
#FNN 0 0'+v~~FFEM++FHmLLFYYvx00F &GH#GFO$GG224&II6>>55dkk'66R6RSSHHX77GV8T8TUUHHV^^>>t{{7TZ?[?[\\HHX??GU[@\@\]]HHX88Wf9U9UVVHj   8UEBBBr  r#  c                    d }|                      |d          }t          j        |d          rd}t          j        |          }nd}|                      |d          }|                     ||          }|                      |d          }|                      |d          }d }t          |          dk    rt          |          }nt          |          d	z  }|                      |d
          }	|                      |d          }
|                     t          j        |	|
                    }| 	                    ||                      |d          |d d d | 
                    |          |                     ||          |                     |          ||                     |          ||                     |d
          d d d|          S )Nr  r  outinrk  r  r   r  r  balancerB   )r  rB   	directionrZ   referenceAccountreferenceIdr  rk  r  r  r  beforeafterr  r   )r  r=   r  r  r  r  r4  r  r6  safe_ledger_entryparse_ledger_entry_typer
  r9  r  )r  r#  rk  r  r  r{  r  rawTimestampr  balanceStringchangeStringr  s               r  parse_ledger_entryzgate.parse_ledger_entry  s   Z 	!!$11VS)) 	I'//FFI%%dJ77
%%j(;;f--''f55	|r!!L))IIL))D0I((y99''h77""7#5m\#R#RSS%%""4.." $0066//
HEE''//"Y//%%dI66'
 '
  !  	r  c                    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dddd)d+}|                      |||          S ),Nrq  r   r  sub_account_transferr   	margin_in
margin_outmargin_funding_inmargin_funding_outcross_margin_incross_margin_outcopy_trading_incopy_trading_outquant_in	quant_out
futures_infutures_outdelivery_indelivery_out	new_orderr  
order_fillreferral_feerY   	order_feer   r>  lendr[   redeemprofitflash_swap_buyflash_swap_sellunknownsetr  prem
point_refrr  	point_dnwzdeposit/withdrawr  )refrr   r  dnwr  )r  r  
ledgerTypes      r  r  zgate.parse_ledger_entry_type*  s   '
y'
'
 #J'
 	'

 *'
  '
 !*'
 z'
 
'
 z'
 
'
 
'
 '
 *'
 :'
  :!'
" J#'
 '
$ %'
& '''
( H)'
* +'
, 
-'
. F/'
0 f1'
2 j3'
4 g5'
6 w7'
8 y9'
: <;'
< G='
> (?'
@ A'
B +C'
D EE'
 '
F %M'
 '
 '

P 
D$777r  r  c                     ||                      |          nd}|                     |d|          \  }}||d<   |                     |                     ||                    S )aH  
        set dual/hedged mode to True or False for a swap market, make sure all positions are closed and no orders are open before setting dual mode

        https://www.gate.com/docs/developers/apiv4/en/#set-position-mode

        :param bool hedged: set to True to enable dual mode
        :param str|None symbol: if passed, dual mode is set for all markets with the same settle currency
        :param dict params: extra parameters specific to the exchange API endpoint
        :param str params['settle']: settle currency
        :returns dict: response from the exchange
        Nri   	dual_mode)r  rW   privateFuturesPostSettleDualModer  )r  r  r  r  r  r#  rK  s          r  set_position_modezgate.set_position_modeU  sf     *0);V$$$$--fffEE%44T[[%5P5PQQQr  c                    |                                   d}|                     dd|          \  }}||dk    rd}|dk    rt          | j        dz             |                     |          }g }t          dt          |                    D ]7}||         }|                     |d          }||                    |           8|S )a  
        fetches the market ids of underlying assets for a specific contract market type

        https://www.gate.com/docs/developers/apiv4/en/#list-all-underlying-assets

        :param dict [params]: exchange specific params
        :param str [params.type]: the contract market type, 'option', 'swap' or 'future', the default is 'option'
        :returns dict[]: a list of `underlying assets <https://docs.ccxt.com/?id=underlying-assets-structure>`
        Nr   rR   rk   z5 fetchUnderlyingAssets() supports option markets onlyr   rC   )	r  r  r9   rB   rP  r  r  r  r  )r  r  r  r  r   r  rD  rC   s           r  fetch_underlying_assetszgate.fetch_underlying_assetsf  s     	
!??@WY]_eff
FJ&$8$8!J!!tw)``aaa33F;; q#h--(( 	) 	)A!!J##J77D""4(((r  c                    |                                   |                     |          }|d         st          | j        dz             |d         |d         d}|||d<   |||d<   |                     d	||          \  }}|                     |                     ||                    }|                     ||||          S )
a  
        retrieves the public liquidations of a trading pair

        https://www.gate.com/docs/developers/apiv4/en/#query-liquidation-order-history

        :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 exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest liquidation
        :returns dict: an array of `liquidation structures <https://docs.ccxt.com/?id=liquidation-structure>`
        ri   z/ fetchLiquidations() supports swap markets onlyr  rB   )r  r  Nr  r  rj  )r  r  r9   rB   r  publicFuturesGetSettleLiqOrdersr  parse_liquidations)r  r  r  r  r  r  r#  r  s           r  fetch_liquidationszgate.fetch_liquidations  s     	V$$f~ 	\tw)ZZ[[[Z(t
 
 #GFO$GG224&II77GV8T8TUU &&xFFFr  c                    |t          | j        dz             |                                  |                     |          }d|d         i}d}|d         s|d         r|||d<   |d         |d	<   n>|d
         r6|d         }|                    d          }	|                     |	d          |d<   |d         r*|                     |                     ||                    }n|d         r*|                     |                     ||                    }nU|d
         r*| 	                    |                     ||                    }n#t          | j        dz   |d         z   dz             |                     ||||          S )a  
        retrieves the users liquidated positions

        https://www.gate.com/docs/developers/apiv4/en/#query-liquidation-history
        https://www.gate.com/docs/developers/apiv4/en/#query-liquidation-history-2
        https://www.gate.com/docs/developers/apiv4/en/#list-user-s-liquidation-history-of-specified-underlying

        :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 exchange API endpoint
        :returns dict: an array of `liquidation structures <https://docs.ccxt.com/?id=liquidation-structure>`
        Nz1 fetchMyLiquidations() requires a symbol argumentr  rB   ri   rj   r  r  r  rk   r  r   rD  z( fetchMyLiquidations() does not support r  r'  )r2   rB   r  r  r  r  !privateFuturesGetSettleLiquidatesr  "privateDeliveryGetSettleLiquidatesprivateOptionsGetPositionCloser9   r  )
r  r  r  r  r  r  r#  r  r  r  s
             r  fetch_my_liquidationszgate.fetch_my_liquidations  s    >#DG.a$abbbV$$t
 6N 	Ex 0 	E #(  &z 2GHH 	Ed|H"..--K$($4$4[!$D$DGL!&> 	r==dkk'SY>Z>Z[[HHH 	r>>t{{7TZ?[?[\\HHH 	r::4;;wPV;W;WXXHHtw)SSV\]cVddgppqqqD &&xFFFr  c                    |                      |d          }|                     |d          }|                     |dd          }|                      |dd          }t          j        t          j        ||                    }|                      |d          }|                     |dd	          }	t          j        ||          }
|                      |d
          }|t          j        |
|	          }|                     |d          }d }|dk    rd}n:|dk    rd}n1|/t          j        |d          rd}nt          j	        |d          rd}| 
                    ||                     ||          |                     |          |                     |          |                     |	          ||                     |
          |                     t          j        |                    ||                     |          d
          S )Nr  r   r  settle_sizer`  r  r  r  rc  r  r  r  r  r  r  )
r  r  r   r  r  r  	baseValue
quoteValuer  r  )r  r4  r>  r=   r  r6  r8  rT  r  r  safe_liquidationr  r  r9  )r  liquidationr  r  r  r  r`  contractsStringcontractSizeStringr  baseValueStringquoteValueStringoptPosr  s                 r  parse_liquidationzgate.parse_liquidation  s   R ##K<<''V<<	!!+v}EEVS99!,W-?d-K-KLL!--fnEE((k<PP!,_>PQQ++K??#&1/;OO ''V<<VDDwDD$T3// " DD&tS11 "!D$$&&x88**?;; --.@AA&&{33**?;;++G,>?O,P,PQQ"Y//&
 &
   	r  c                    |                                   |                     |          }d|d         d         i}|                     |                     ||                    }|d         }t	          dt          |                    D ]>}||         }|                     |d          }	|	|k    r|                     ||          c S ?dS )a  
        fetches an option contracts greeks, financial metrics used to measure the factors that affect the price of an options contract

        https://www.gate.com/docs/developers/apiv4/en/#query-options-market-ticker-information

        :param str symbol: unified symbol of the market to fetch greeks for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `greeks structure <https://docs.ccxt.com/?id=greeks-structure>`
        rD  r  rB   r   rC   N)r  r  r  r  r  r  r  parse_greeks)
r  r  r  r  r#  r  r  r  rz  entryMarketIds
             r  fetch_greekszgate.fetch_greeksJ  s     	V$$&.6
 //GV0L0LMM. $<q#h--(( 	8 	8AQKE ,,UF;;M((((77777 )tr  greeksc                    |                      |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         d                   |dS )NrC   r  r  r  deltagammathetavegarhobidSizer&  askSizer(  bidImpliedVolatilitybid_ivaskImpliedVolatilityask_ivmarkImpliedVolatilitymark_ivbidPricer"  askPricer  r=  r,  r  r  r  underlying_price)underlyingPricer  )r  r  r  r  )r  r  r  r  r  s        r  r  zgate.parse_greeksx  s   * ##FF33!!(F33
f

 
 T%%fg66	

 T%%fg66
 T%%fg66
 D$$VV44
 4
 t''<<
 t''<<
 #D$4$4VX$F$F
 #D$4$4VX$F$F
 $T%5%5fi%H%H
 ((>>
 ((>>
  ))&,??!
" ))&,??#
$  $00@R1STT'
 
 
 	
r  c                 r    ddi}|                      ||          }|d}|                     |d|dd|          S )a4  
        closes open positions for a market

        https://www.gate.com/docs/developers/apiv4/en/#place-futures-order
        https://www.gate.com/docs/developers/apiv4/en/#place-futures-order-2
        https://www.gate.com/docs/developers/apiv4/en/#create-an-options-order

        :param str symbol: Unified CCXT market symbol
        :param str side: 'buy' or 'sell'
        :param dict [params]: extra parameters specific to the okx api endpoint
        :returns dict[]: `A list of position structures <https://docs.ccxt.com/?id=position-structure>`
        r8  TNr*  r  r   )r  r  )r  r  r  r  r#  s        r  close_positionzgate.close_position  sM     T
 Wf--<D  4D&IIIr  c                 X   |                                   d}||                     |          }i }d}|                     |d          }|                     |d          }|d         ra|d         |d<   |r*|                     |                     ||                    }ny|                     |                     ||                    }nO|r*|                     |                     ||                    }n#t          | j	        dz   |d         z   dz             | 
                    ||          S )	a2  
        fetch the set leverage for a market

        https://www.gate.com/docs/developers/apiv4/en/#get-unified-account-information
        https://www.gate.com/docs/developers/apiv4/en/#get-lending-market-details

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.unified]: default False, set to True for fetching the unified accounts leverage
        :returns dict: a `leverage structure <https://docs.ccxt.com/?id=leverage-structure>`
        NrX   rR   rB   rS  z" fetchLeverage() does not support r  rI  )r  r  r  rU  +publicMarginGetUniCurrencyPairsCurrencyPairr  (publicMarginGetCurrencyPairsCurrencyPairrS  r9   rB   parse_leverage)r  r  r  r  r#  r  	isUnifieds          r  fetch_leveragezgate.fetch_leverage  sB    	[[((FNN6955	69--&> O	m'-d|GO$ gKKDKKX_agLhLhii  HHU\^dIeIeff  5	m55dkk'66R6RSSHHh tw)MMPVW]P^^akklll""8V444r  c                 B   |                                   |                     |          }d}|                     |d          }|                     |d          }d}|rd}|                     |          }n|                     |          }|                     |||d          S )a  
        fetch the set leverage for all leverage markets, only spot margin is supported on gate

        https://www.gate.com/docs/developers/apiv4/en/#list-lending-markets

        :param str[] symbols: a list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.unified]: default False, set to True for fetching unified account leverages
        :returns dict: a list of `leverage structures <https://docs.ccxt.com/?id=leverage-structure>`
        NrX   rB   rS  rR   )r  r  r  rU  publicMarginGetUniCurrencyPairsr  parse_leverages)r  r  r  r  r  marketIdRequests         r  fetch_leverageszgate.fetch_leverages!  s     	%%g..NN6955	69-- 	A-O;;FCCHH 88@@H ##HgOOOr  c                     |                      |dd          }|                     |d          }||                     ||dd          d ||dS )NrS  rB   r  r  rR   )r  r  r  longLeverageshortLeverage)r>  r  r  )r  r  r  r  leverageValues        r  r  zgate.parse_leverageQ  s`    %%hFF))(J??&&xfEE)*
 
 	
r  c                     |                                   |                     |          }d|d         i}|                     |                     ||                    }|                     |d|          S )a  
        fetches option data that is commonly found in an option chain

        https://www.gate.com/docs/developers/apiv4/en/#query-specified-contract-details

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `option chain structure <https://docs.ccxt.com/?id=option-chain-structure>`
        r  rB   N)r  r  !publicOptionsGetContractsContractr  parse_optionr  s         r  fetch_optionzgate.fetch_option\  su     	V$$t
 99$++gv:V:VWWR   4888r  c                     |                                   |                     |          }d|d         dz   i}|                     |                     ||                    }|                     |dd          S )a  
        fetches data for an underlying asset that is commonly found in an option chain

        https://www.gate.com/docs/developers/apiv4/en/#list-all-contracts-for-specified-underlying-and-expiration-date

        :param str code: base currency to fetch an option chain for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.underlying]: the underlying asset, can be obtained from fetchUnderlyingAssets()
        :param int [params.expiration]: unix timestamp of the expiration time
        :returns dict: a list of `option chain structures <https://docs.ccxt.com/?id=option-chain-structure>`
        rD  rt  _USDTNrC   )r  rk  rJ  r  parse_option_chain)r  rt  r  rk  r#  r  s         r  fetch_option_chainzgate.fetch_option_chain  s{     	==&&(6*W4
 11$++gv2N2NOOV &&xv>>>r  r|  c                    |                      |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 S )NrC   r3  r  rk  r  r  r  impliedVolatilityopenInterestr  r"  r  r  midPricer=  r,  r  r  r  r   r  r%  r;  r<  )r  r  r4  r9  r  )r  r|  rk  r  r  r  s         r  r  zgate.parse_option  sx   R ##E622!!(F33''}==	
E

 fX&
 	

 Y//
  
 D
 ((==
 ((==
 
 ))%>>
 ))%>>
 t//7IJJ
 d
 $
  $!
" 4#
 	
r  c                    |                                   d}|0t          |          }|dk    r|                     |d                   }d}|                     d||d          \  }}|                     |d          }|                     |d          }i }	|                     |||          \  }	}|||	d<   ||                     |dz            |	d	<   ||                     |dz            |	d
<   d}
|dk    r*|                     | 	                    |	|                    }
nJ|dk    r*| 
                    | 	                    |	|                    }
nt          | j        dz   |z             |                     |
||          S )a  
        fetches historical positions

        https://www.gate.com/docs/developers/apiv4/#query-position-close-history
        https://www.gate.com/docs/developers/apiv4/#query-position-close-history-2

        :param str[] symbols: unified conract symbols, must all have the same settle currency and the same market type
        :param int [since]: the earliest time in ms to fetch positions for
        :param int [limit]: the maximum amount of records to fetch, default=1000
        :param dict params: extra parameters specific to the exchange api endpoint
        :param int [params.until]: the latest time in ms to fetch positions for

 EXCHANGE SPECIFIC PARAMETERS
        :param int [params.offset]: list offset, starting from 0
        :param str [params.side]: long or short
        :param str [params.pnl]: query profit or loss
        :returns dict[]: a list of `position structures <https://docs.ccxt.com/?id=position-structure>`
        Nr   r   r   ri   ri  r  r  r  rj  rj   z: fetchPositionsHistory() does not support markets of type )r  r  r  r  r  rU  rW  r  $privateFuturesGetSettlePositionCloser  %privateDeliveryGetSettlePositionCloser9   rB   r  )r  r  r  r  r  r  r  r  ri  r#  r  s              r  fetch_positions_historyzgate.fetch_positions_history  s   & 	LLM!!WQZ00
!??@WY_agiopp
F!!&'2267++..vz6JJ$GG"//==GFO --edl;;GDM@@WV\A]A]^^HH8##AA$++gW]B^B^__HHtw)eehrrsss* ##Hgv>>>r  reasonr_   rg  r  rT  c
                     |d S |                      |d          }
|
>| j        dz   |z   }|                     | j        d         |
|           t	          |          d S )Nlabel r  )r  rB   throw_exactly_matched_exceptionr  r-   )r  rt  r#  r_   rg  r  rT  r  requestHeadersrequestBodyr%  feedbacks               r  handle_errorszgate.handle_errorsV  sm    4   733w}t+H001I5RZ[[[)))tr  )NNNNr  )NN)__name__
__module____qualname__r   r  boolr  r  r  r   r  rK  r  r    r   r*   r  r,   r  r  r  r  r   r  rI  rW  r\  r^  rZ  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  dictr  r#   rF  rP  r   re  r  r{  rl  r  r  r&   r  r  r  r  r)   r  r  floatr   r  r  r  r   r   r   r  r   r  r   r  rG  rM  rR  r]  r   r	  r  r  r  r  r  r  r  r  r   r  r  r+   r   r  r4  r  r  r  r   r  r   r	  r   r  r   r  r*  r/  r2  r5  r)  r   r?  rC  r
  ru  rz  r   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+  __classcell__)r  s   @r  r?   r?      s       }# } } } } } }~#-t - - - - - - *, . . . .B 46 9 9 9 9 !# : :s : : : :"=
3 =
 =
 =
 =
~V VC V VRU Vjm V  zI V V V V V V $& "+ "+$v, "+ "+ "+ "+H )+ o o o ob )+      +-     g
 g
 g
R +- v v v vp  & &*R ! ! ! !8 15eB        $ 7;ERT        *$ $ $:c c c ') c cZ c c c cJ 68 <1 <1 <1K <1 <1 <1 <1| 6:" >; >;7 >; >; >; >; >;@G
 G
6 G
[ G
 G
 G
 G
R? ? ? ?A # ## # # # #J DF 0 0s 0$~J^ 0 0 0 0, 79 : :# :^ : : : :$
 
 
 
( 57 8 8 8;N 8 8 8 8@ )+ 1 1{ 1 1 1 16  
 
f 
 
 
 
< 7;2 5 5G 5 5 5 5n <@ M M M M M MB. . . . . .` 37TX\eg .L .LC .Ls .LRU .L .L .L .L`OnI] O O O O
 
& 
 
 
 
. :>b s ss s3 sY s s s sj 02 '1 '13 '1f '1 '1 '1 '1Rn n4 n n6 n n n n` 04B %5 %5W %57 %5 %5 %5 %5N   $& Z Z( Z Z Z Zx 9=4^bkm AL AL# AL# ALS ALX[ ALrvw{r| AL AL AL ALF 9=4^bkm L L LS LX[ L L L L 8<$]ajl 5Y 5Y 5YC 5YWZ 5Y 5Y 5Y 5Yn+ + +4 + + + +Z 6:UW hA hA3 hAs hA# hA\`af\g hA hA hA hAT 9=4^bkm ' 'S '# 'S 'X[ ' ' ' 'R -1tRV_a BA BAc BA BAC BA BA BA BAH_ _ _v _ _ _ _ _B *.Dt\^  ;  ;3  ;c  ;  ;cghsct  ;  ;  ;  ;D -1tRV_a  ;  ;c  ;  ;C  ;fjkvfw  ;  ;  ;  ;D KOWY &: &:S &:% &:# &:C &:^i &: &: &: &:P:s : : : :$3 3 3k
 k
T k
X k
Q\ k
 k
 k
 k
Z gksu C2 C23 C2i C2y C2RW C2`c C2 C2 C2 C2J HJ  D,>    < @B + +D$6 + + + +. os{} U, U,3 U,i U,y U,Z_ U,hk U, U, U, U,n RT N N N5 N N N N( hlz~  HJ , ,S ,# ,Y ,i ,ad ,tw , , , ,B `drv  @B 92 92S 92# 92Y 92i 92Y\ 92lo 92 92 92 92v: : : : : M M Mv M M M M M^
 :>b ( (c (3 ( ( ( (" 26b 12 12c 123 12 12 12 12f /3TXac Q Q Q3 Qc Qhlmrhs Q Q Q Q$ 154VZce 0A 0A# 0AS 0APS 0Ajnotju 0A 0A 0A 0Ad FJX\koxz & &s &RU &eh & & & &> <@daenp O OS O O[^ O O O OB 37r @2 @2s @2C @2 @2 @2 @2D ;?r *+ *+c *+C *+ *+ *+ *+X SU $+ $+5H0I $+ $+ $+ $+L /32 H3 H3 H3 H3 H3 H3T [] 67 67S 67% 67c 67c 67an 67 67 67 67p
 
t 
x 
= 
 
 
 
, 9=R C CS C# C C C CJE Et EV E E E EN 24 R5 R5S R5 R5 R5 R5h 26b d7 d7w d7T(^ d7 d7 d7 d7L 7;2 sD sDG sD- sD sD sD sDj ?A !B !B# !BT,EW !B !B !B !BF $|BT    8  $|J\    @ LN : :C :s : : : :: <> /: /:s /: /: /: /:b TV +: +:S +: +:U +: +: +: +:Z DF ,: ,: ,:U ,: ,: ,: ,:\3
 3
 3
 3
 3
 3
j 15DW[jnwy -Q -Q# -Qc -QQT -Qdg -Q  C  DR  S -Q -Q -Q -Q^
 
$ 
 
. 
 
 
 
"D D D  b$T OP OP OP OPb @B @ @3 @ @ @ @*
 *
d *
F *
N` *
 *
 *
 *
X @B B BC B BFX B B B B =? A A Ae ACU A A A A BFTXgktv 5Q 5Q# 5Qc 5Qad 5Q 5Q 5Q 5Qn
 
F 
 
 
 
: 6:[_hj ,O ,Os ,O# ,OUX ,O ,O ,O ,O\ 9=4^bkm LO LO# LOS LOX[ LO LO LO LO\0
 0
 0
d" " "H (,$TZ\ hC hC hCC hCs hCaefqar hC hC hC hCTP Pt Px P; P P P Pd)8 )8 )8V =A R R Rc R R R R" .0 ! ! ! !F <@d[] 'G 'G 'GS 'G 'G 'G 'G 'GR 37TX\eg GG GGC GGs GGRU GG GG GG GGRM MV M M M M^ 02 , ,3 ,f , , , ,\+
 +
4 +
 +
6 +
 +
 +
 +
Z =A J JS J	 JPU J J J J* 24 e5 e5S e5 e5 e5 e5 e5N 26b .P .Pw .PY .P .P .P .P`	
 	
t 	
V 	
x 	
 	
 	
 	
 02 89 893 89f 89 89 89 89t 46 <? <?s <?+ <? <? <? <?|>
 >
$ >
( >
6 >
]c >
 >
 >
 >
@ :>D_cln @? @?w @?c @?Y\ @?sw  yA  tB @? @? @? @?D# s  c TX `c        r  r?   )Dccxt.base.exchanger   ccxt.abstract.gater   r`  ccxt.base.typesr   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'   r(   r)   r*   r+   typingr,   ccxt.base.errorsr-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   ccxt.base.decimal_to_precisionr<   ccxt.base.preciser=   r?    r  r  <module>r;     s   ( ' ' ' ' ' * * * * * *  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]       * * * * * * 0 0 0 0 0 0 - - - - - - . . . . . . - - - - - - . . . . . . ' ' ' ' ' ' & & & & & & . . . . . . ) ) ) ) ) ) * * * * * * 5 5 5 5 5 5 ) ) ) ) ) ) . . . . . . 1 1 1 1 1 1 4 4 4 4 4 4 % % % % % %H} H} H} H} H}8[ H} H} H} H} H}r  