
    eiE                       d dl mZ d dlmZ d dl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l0m1Z1 d dl0m2Z2 d dl0m3Z3 d d	l0m4Z4 d d
l0m5Z5 d dl0m6Z6 d dl0m7Z7 d dl0m8Z8 d dl0m9Z9 d dl0m:Z: d dl0m;Z; d dl0m<Z< d dl0m=Z= d dl0m>Z> d dl0m?Z? d dl@mAZA d dlBmCZC  G d dee          ZDd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    U/var/www/html/volatility/venv/lib/python3.11/site-packages/ccxt/async_support/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                 H  K   |                      | j        d          }|w	 |                     |           d{V }|                     |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 "&!=!=f!E!EEEEEEE%<<151B1B661R1RVW1W-.. 7 7 716-......7 |,--s   AA6 6
B 
BBc                 <   K   |                      |           d {V S N)privateUnifiedPutUnifiedMode)r  r  s     r  upgrade_unified_trade_accountz"gate.upgrade_unified_trade_account  s,      66v>>>>>>>>>r  c                 h   K   |                      |           d{V }|                     |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
        Nserver_time)publicSpotGetTimer  r  r  r  s      r  
fetch_timezgate.fetch_time  sE       //77777777   =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                 6  K   | j         d         r|                                  d{V  |                     d          r|                                  d{V  g }|                     | j         d          }|                     |dg d          }t          dt          |                    D ]}||         }|dk    r)|                    | 	                    |                     9|d	k    r)|                    | 
                    |                     h|d
k    r)|                    |                     |                     |dk    r(|                    |                     |                     t          j        |  d{V }|                     |          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  NFr   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asynciogather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4444444!!'***r  c                 X  K   |                      |          }|                     |          }t          j        ||g  d {V \  }}|                     |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publicSpotGetCurrencyPairsr  r  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_marketsC  s(     99&AA!<<VDD4;N]TfDg4h.h.h.h.h.h.h++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                   K   g }|                      dd          }| j        d         rdg}t          dt          |                    D ]}||         }d|i}|                     |                     ||                     d {V }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 "AA$++gW]B^B^________H1c(mm,, , ,#99(1+xPPl++++, r  c                   K   | j         d         rg S g }|                     dd          }t          dt          |                    D ]}||         }d|i}|                     |                     ||                     d {V }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 "BB4;;wX^C_C_````````H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                   K   g }|                                   d {V }t          dt          |                    D ]B}||         }|                     i |          }||d<   |                     |           d {V }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.           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.0003r0  r  r  r3  r4  r  r5  r  )fetch_option_underlyingsr  r  r!  publicOptionsGetContractsr  r  r  r6  r  r7  r=   r8  r9  r:  r  r  r;  r  )r  r  r  r   r  rF  queryr  jr  rB   r<  r  r  r'  rM  r  r  r  isCalloptionLetterr  r>  r?  r@  rA  rB  rC  s                               r  r  zgate.fetch_option_markets}  s      99;;;;;;;;q#k**++ r	 r	A$QJKKF++E",E,!;;EBBBBBBBBHN 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                    K   |                                   d {V }g }t          dt          |                    D ]7}||         }|                     |d          }||                    |           8|S )Nr   rC   )publicOptionsGetUnderlyingsr  r  r  r  )r  underlyingsResponser   r  rF  rC   s         r  rK  zgate.fetch_option_underlyings  s      $($D$D$F$FFFFFFF 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   rU  )get_margin_moder2   rB   r  r  r  r  r  rM  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 )r[  rZ   NrB   r  rU  )r\  r]  s          r   multi_order_spot_prepare_requestz%gate.multi_order_spot_prepare_request6  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   rW  r3   rB   handle_option_and_params)r  r  r  rb  r  isUnifiedAccounts         r  r\  zgate.get_margin_modeK  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   fetchMarketsContractOptionsrX  s         r  r  zgate.get_settlement_currenciesh  s]    //$,b99&*oogvr&J&J#%)V^^5':<RTabbbr  c                 $  K   |                      | j        d          }|i S |                     |           d{V }|                     |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  rs  r   r   r  r  delisted)rB   coderC   r  r  rs  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  rl  r  indexedCurrenciesr  r  entry
currencyIdrv  r  rp  r  rN  chain	networkIdnetworkCodes                    r  fetch_currencieszgate.fetch_currenciesn  ss      OODI{;;	 I55f========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                 ^  K   |                                   d{V  |                     |          }|d         st          | j        dz             |                     |d|          \  }}|                     |                     ||                     d{V }|                     |          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>`
        Nri   z0 fetchFundingRate() supports swap contracts only)load_marketsr  r4   rB   rY  'publicFuturesGetSettleContractsContractr!  parse_funding_rate)r  r  r  r  r%  rM  r  s          r  fetch_funding_ratezgate.fetch_funding_rate  s       !!!!!!!!!V$$f~ 	ZDG&XXYYY--fdFCCEEdkkRY[`FaFabbbbbbbbZ &&x000r  symbolsc                   K   |                                   d{V  |                     |          }d}|+|                     |d          }|                     |          }|                     |d|          \  }}|                     |                     ||                     d{V }|                     ||          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  rY  r   r!  parse_funding_rates)r  r  r  r  firstSymbolr%  rM  r  s           r  fetch_funding_rateszgate.fetch_funding_rates  s       !!!!!!!!!%%g..**7A66K[[--F--fffEE==dkk'SX>Y>YZZZZZZZZ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  r6  r=   r:  r;  parse_funding_interval)r  r  r  r  r  r?  r  r  r  fundingTimefundingRateIndicativefundingIntervals               r  r  zgate.parse_funding_rateQ  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  rv  c                 |  K   |                                   d {V  |                     |          }d|d         i}|                     |                     ||                     d {V }|                     |d          }|                     |d          }|                     |          }i }t          dt          |                    D ]p}	||	         }
| 	                    |
d          }|r#|                     |
d          }|                     |
d          }|                     |
d          }|
||||d	||<   q|S )
Nrm  rB   multichain_addressesr   obtain_failedr~  address
payment_id)r  rv  rm  r  tag)
r  rm  privateWalletGetDepositAddressr!  r  r  r  r  r  r  )r  rv  r  rm  r%  r  	addressesr}  r  r  r|  obtainFailedrt  r  r  s                  r  fetch_network_deposit_addressz"gate.fetch_network_deposit_address  ss     !!!!!!!!!==&&
 <<T[[RX=Y=YZZZZZZZZ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                   K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     |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
        Nrm  rB   r  Frt  )	r  rm  r  r!  r  r  safe_currencyparse_deposit_addressesr
  )	r  rv  r  rm  r%  r  rp  r}  parseds	            r  "fetch_deposit_addresses_by_networkz'gate.fetch_deposit_addresses_by_network  s       !!!!!!!!!==&&
 <<T[[RX=Y=YZZZZZZZZ+A2FF%%h
;;
%%j(;;--fdEBB}}VY///r  c                    K   |                                   d{V  d}|                     |          \  }}|                     ||           d{V }|                     |||          }||         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  rv  r  r  chainsIndexedByIdselectedNetworkIdOrCodes         r  fetch_deposit_addresszgate.fetch_deposit_address  s       !!!!!!!!!"AA&IIV"&"I"I$PV"W"WWWWWWW"&"P"PQUWbdu"v"v !899r  c           
         |                      |d          }|                     |           ||                      |d          ||                      |d          |                     |                      |d                    dS )Nr  rv  r  r~  )r  rm  r  r  rt  )r  check_addressry  )r  depositAddressrm  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                   K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     ||          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>`
        NrU  rB   )r  r  privateWalletGetFeer!  parse_trading_feer  r  r  r  r%  r  s         r  fetch_trading_feezgate.fetch_trading_fee	  s       !!!!!!!!!V$$VD\
 11$++gv2N2NOOOOOOOO %%h777r  c                    K   |                                   d{V  |                     |           d{V }|                     |          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
        N)r  r  parse_trading_feesr  s      r  fetch_trading_feeszgate.fetch_trading_fees%	  sg       !!!!!!!!!11&99999999 &&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_feeH	  s     __T=99
",=+",=+??6:66*2=&&*2=&&&&vx88%%dH55%%dH55
 
 	
r  codesc                   K   |                                   d{V  |                     |           d{V }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>`
        Nr   rm  withdraw_fix_on_chainswithdraw_fix)r   rs  r  )r  privateWalletGetWithdrawStatusr  r  r  r  in_arrayr  r  listkeysry  r  )r  r  r  r  r  withdrawFeesr  r|  r}  rv  withdrawFixOnChains
networkIdsrN  r  r  s                  r  fetch_transaction_feeszgate.fetch_transaction_feesf	  s      !!!!!!!!!<<VDDDDDDDD$ 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                    K   |                                   d{V  |                     |           d{V }|                     ||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>`
        Nrm  )r  r  parse_deposit_withdraw_fees)r  r  r  r  s       r  fetch_deposit_withdraw_feesz gate.fetch_deposit_withdraw_fees	  sk       !!!!!!!!!<<VDDDDDDDD( //%LLLr  rm  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%  rs  )r  r   rs  r  r   rm  )r   rs  r  )	r  r  r  r  r  r  ry  r  r  )	r  r   rm  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                 p  K   |                                   d{V  d}||                     |          }|d         }|                     d||          \  }}|                     |||          \  }}	d|d<   ||                     |dz            |d<   |||d<   d}
|d	k    r0|                     |                     ||	                     d{V }
nM|d
k    r0|                     |                     ||	                     d{V }
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_paramsrY  parse_to_int"privateFuturesGetSettleAccountBookr!  #privateDeliveryGetSettleAccountBookr9   rB   parse_funding_histories)r  r  r  r  r  r  r  rM  r%  requestParamsr  s              r  fetch_funding_historyzgate.fetch_funding_history	  s      !!!!!!!!![[((FH%F889NPVX^__e!%!5!5fdE!J!J "//==GFO$GG6>>!DDT[[QXZgEhEhiiiiiiiiHHX!EEdkkRY[hFiFijjjjjjjjHH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  r|  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  rv  r  r  rB   r  )r6  r  r  r;  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           	        K   |                                   d{V  |                     |          }|                     ||d         |          \  }}|.|d         rt          |d          }nt          |d          }||d<   d|d<   d}|d         s|d	         r0|                     |                     ||                     d{V }n|d
         r0|                     |                     ||                     d{V }n|d         r0|                     |                     ||                     d{V }nO|d         r0|                     |                     ||                     d{V }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
        Nr  rR   r  i,  r  Twith_idrP   ri   rj   rk   z. fetchOrderBook() not support self market typecurrentr   pr   srB   bidsasksnonce)r  r  rY  r  publicSpotGetOrderBookr!  publicFuturesGetSettleOrderBook publicDeliveryGetSettleOrderBookpublicOptionsGetOrderBookr9   rB   r  parse_order_book)r  r  r  r  r  r%  rM  r  r  priceKey	amountKeyr  r  s                r  fetch_order_bookzgate.fetch_order_book>
  sm      !!!!!!!!!V$$ --ffVnfMMf~ (E4((E3$GG!	&> 		[VH- 		[!88We9T9TUUUUUUUUHHF^ 	[!AA$++gW\B]B]^^^^^^^^HHH 	[!BB4;;wX]C^C^________HHH 	[!;;DKKQV<W<WXXXXXXXXHHtw)YYZZZB %%h	::	f~ 	)!D(Iv/11C0AAS	!!(D11&&xFFT\^ghhwr  c                   K   |                                   d{V  |                     |          }|                     |d|          \  }}d}|d         s|d         r0|                     |                     ||                     d{V }n|d         r0|                     |                     ||                     d{V }n|d         r0|                     |                     ||                     d{V }n|d         rf|d         }|                    d          }|                     |d	          |d
<   | 	                    |                     ||                     d{V }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   rF  z+ fetchTicker() not support self market typerC   )r  r  rY  publicSpotGetTickersr!  publicFuturesGetSettleTickerspublicDeliveryGetSettleTickersr  r  publicOptionsGetTickersr9   rB   r  r  r  parse_ticker)r  r  r  r  r%  rM  r  r  r  tickerr  r|  s               r  fetch_tickerzgate.fetch_ticker
  sH      !!!!!!!!!V$$--fdFCC&> 	XVH- 	X!66t{{7E7R7RSSSSSSSSHHF^ 
	X!??GUZ@[@[\\\\\\\\HHH 	X!@@WV[A\A\]]]]]]]]HHH 	Xd|H"..--K$($4$4[!$D$DGL!!99$++gu:U:UVVVVVVVVHH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)rU  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_tickerr;  )r  r  r  r  r  r  r  r6  r4  r2  r3  r5  r7  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                   K   |                                   d{V  |                     |          }|                     |d          }d}||                     |          }|                     d||          \  }}|                     d||          \  }}d}	d|d<   |dk    s|dk    r1|                     |                     ||                     d{V }	n|dk    r0|                     |                     ||                     d{V }	n|d	k    r0| 	                    |                     ||                     d{V }	n|d
k    r}| 
                    d|d           |d         }
|
                    d          }|                     |d          |d<   |                     |                     ||                     d{V }	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>`
        Nr   r   utc0timezonerR   rP   ri   rj   rk   r  rB   r  rF  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  rY  r  r!  r  r  check_required_argumentr  r  r9   rB   parse_tickers)r  r  r  firstr  r  rM  r%  r  r  r  r  s               r  fetch_tickerszgate.fetch_tickersL  sF      !!!!!!!!!%%g..  !,,[[''F88QWXXe!%!5!5dD%!H!H$
6>>TX--!66t{{7M7Z7Z[[[[[[[[HHV^^!??GUb@c@cddddddddHHX!@@WVcAdAdeeeeeeeeHHX(()LLLd|H"..--K$($4$4[!$D$DGL!!99$++g}:]:]^^^^^^^^HH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  r|  rZ   s      r  parse_balance_helperzgate.parse_balance_helpers  s    ,,..,,UHhGG**5+>>++E7;;"..ujAAGFOr  c                 
  K   |                                   d{V  |                                  d{V  |                     |d          }|                     |d          }d}|                     |dd          \  }}|                     dd|          \  }}|                     d||          \  }}|                     d|          \  }}	| |                     |          }
|
d         |d<   d}|r1| 	                    | 
                    ||                     d{V }n|dk    r|dk    r1|                     | 
                    ||	                     d{V }nt|d	k    r1|                     | 
                    ||	                     d{V }n=|d
k    r1|                     | 
                    ||	                     d{V }nt          | j        dz             |dk    r0|                     | 
                    ||	                     d{V }n|dk    r0|                     | 
                    ||	                     d{V }n|dk    r0|                     | 
                    ||	                     d{V }nM|dk    r0|                     | 
                    ||	                     d{V }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>`
        Nr  Fr   r  rB   rU  rR   rP   r  z+ fetchBalance() not support self marginModer  ri   rj   rk   z, fetchBalance() not support self market typer  balancesr   rm  r  r'  rM  )r  r  r  rW  rf  r  rY  r\  r  privateUnifiedGetAccountsr!  privateSpotGetAccountsprivateMarginGetAccountsprivateMarginGetCrossAccountsr9   rB   privateMarginGetFundingAccountsprivateFuturesGetSettleAccounts privateDeliveryGetSettleAccountsprivateOptionsGetAccountsr  r  r  r  r  r  r  r  rR  safe_balance) r  r  r  rg  r  rM  r%  r  r  requestQueryr  r  r  r  r  dataflatBalancesrT  r  r  r}  contentr|  r  symbolInnerr'  rM  baseCode	quoteCode	subResultrv  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!;;DKKQW<X<XYYYYYYYYHHV^^V##!%!<!<T[[R^=_=_!`!```````x''!%!>!>t{{7T`?a?a!b!bbbbbbb~--!%!C!CDKKPWYeDfDf!g!ggggggg"47-Z#Z[[[Y!AA$++gWcBdBdeeeeeeeeHHV^^!AA$++gWcBdBdeeeeeeeeHHX!BB4;;wXdCeCeffffffffHHX!;;DKKQ]<^<^________HH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           	        K   |                                   d{V  |                     |          }d}|                     |dd          \  }}|r!|                     d|||||d           d{V S |d         r|                     |||||           d{V 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         r0|                     |                     |	|                     d{V }ng|d         r/|                     |                     |	|                     d{V }n/|                     |                     |	|                     d{V }|                     |||||          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)
        NFr   paginater  rk   r  r  r  r  untilr  r   tor  r	  r
  r  rB   rj   ri   )r  r  rf  "fetch_paginated_call_deterministicfetch_option_ohlcvr  rY  rN  r  r  r  rW  parse_timeframesumseconds#publicDeliveryGetSettleCandlesticksr!  "publicFuturesGetSettleCandlestickspublicSpotGetCandlesticksparse_ohlcvs)r  r  rh  r  r  r  r  rj  r  r%  maxLimitrk  durationdistancetoTimestampcurrentTimestamprl  r  isMarkisIndexs                       r  fetch_ohlcvzgate.fetch_ohlcv  s     & !!!!!!!!!V$$88zZZ& 	~@@vW\^cenpvx|}}}}}}}}}( 	Z00E5RXYYYYYYYYY  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* 	ZvoF'G 4 4&+ckF4L&@
#6733h g!%!I!I$++V]_eJfJf!g!ggggggg g!%!H!HU\^dIeIe!f!fffffff!;;DKKQW<X<XYYYYYYYYH  69eUKKKr  c                 j  K   |                                   d {V  |                     |          }i }|                     |d |          \  }}|                     | j        ||          |d<   |                     |                     ||                     d {V }|                     |||||          S )Nr  )r  r  rY  r  rN  publicOptionsGetCandlesticksr!  ru  )	r  r  rh  r  r  r  r  r%  r  s	            r  rn  zgate.fetch_option_ohlcv  s      !!!!!!!!!V$$..vtVDD"..t	9UU
::4;;wPV;W;WXXXXXXXX  69eUKKKr  c           
      ,  K   |t          | j        dz             |                                  d{V  d}|                     |dd          \  }}|r |                     d|||d|           d{V S |                     |          }|d         st          | j        dz             i }|                     |d|          \  }}|||d	<   ||                     |d
z            |d<   | 	                    |d          }|1| 
                    |d          }|                     |d
z            |d<   |                     |                     ||                     d{V }	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   rj  rW  ri   z7 fetchFundingRateHistory() supports swap contracts onlyr  r  r  rk  rl  r   r+  r)r  r  r  r  r  r  r  )r2   rB   r  rf  rm  r  r4   rY  r  r  rW  !publicFuturesGetSettleFundingRater!  r  r  r6  r  r  r;  r  r   )r  r  r  r  r  rj  r  r%  rk  r  ratesr  r|  r  r  s                  r  fetch_funding_rate_historyzgate.fetch_funding_rate_history  st      >#DG.e$efff!!!!!!!!!88AZ\fgg& 	@@@AZ\bdikprvx~V$$f~ 	aDG&__```..vtVDD$GG"//==GFO!!&'22YYvw//F --edl;;GDM??GU[@\@\]]]]]]]] 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  r6  r  )r  ohlcvr  s      r  parse_ohlcvzgate.parse_ohlcv  s   2 eT"" 	##E1--  **  **  **  **  **  ##E3//  ,,  ,,  ,,  ,,  ,, r  c                 f  K   |                                   d{V  d}|                     |dd          \  }}|r|                     d||||           d{V 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    r0| 	                    | 
                    ||                     d{V }
n|d         r0|                     | 
                    ||                     d{V }
n|d         r0|                     | 
                    ||                     d{V }
nS|d         dk    r0|                     | 
                    ||                     d{V }
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>`
        NFr   rj  rl  rk  r  r  r  r  r  rR   rP   ri   rj   rk   z, fetchTrades() not support self market type.)r  rf  fetch_paginated_call_dynamicr  rY  safe_integer_2rW  r  r  publicSpotGetTradesr!  publicFuturesGetSettleTradespublicDeliveryGetSettleTradespublicOptionsGetTradesr9   rB   parse_trades)r  r  r  r  r  rj  r  r%  rM  rk  r  s              r  fetch_tradeszgate.fetch_tradesI  s     " !!!!!!!!!88PZ[[& 	h::=&RWY^`fgggggggggV$$, --fdFCC##FD'::YYvy11F --edl;;GDM"5$//GG&"4"//==GFO&>V##vf~'A'A!55dkk'56Q6QRRRRRRRRHHF^ 	Y!>>t{{7TY?Z?Z[[[[[[[[HHH 	Y!??GUZ@[@[\\\\\\\\HHF^x''!88We9T9TUUUUUUUUHHtw)WWXXXR   65%@@@r  rB   c                    K   |t          | j        dz             |                                  d{V  |                     |||d|i           d{V }|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  s        >#DG.^$^___!!!!!!!!!( --feUZQSDTUUUUUUUUr  c                 @  K   |                                   d{V  |                                  d{V  d}|                     |dd          \  }}|r|                     d||||           d{V 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    r0|                     |                     ||                     d{V }n|dk    r0|                     |                     ||                     d{V }n|dk    r0|                     |                     ||                     d{V }nM|dk    r0|                     |                     ||                     d{V }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>`
        NFr   rj  rk  ri   rj   rk   r  rB   rU  rZ   r  r  r  rl  rR   rP   z. fetchMyTrades() not support self market type.)r  r  rf  r  r  r  rW  r  rY  r\  r  privateSpotGetMyTradesr!  (privateFuturesGetSettleMyTradesTimerange privateDeliveryGetSettleMyTradesprivateOptionsGetMyTradesr9   rB   r  )r  r  r  r  r  rj  r  r  r%  r  rk  r  r  s                r  r  zgate.fetch_my_trades  sG     4 !!!!!!!!!&&(((((((((88R\]]& 	j::?FTY[`bhiiiiiiiii
)/);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--!88Wf9U9UVVVVVVVVHHV^^!JJ4;;W^`fKgKghhhhhhhhHHX!BB4;;wX^C_C_````````HHX!;;DKKQW<X<XYYYYYYYYHH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   r5  rU  r  rR   r  r  sizer  r  sellbuysider  r  r   gt_fee	point_feefee_currencyr  )r  rm  GTrx  roler  )r  rB   r  r  r  orderr  r  takerOrMakerr  r  r  r   r  )r@  r  r=   r:  r  safe_timestamp_2r  	string_lt
string_abs	omit_zeror  r  
safe_trader;  )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                 >  K   |                                   d{V  d}|                     |dd          \  }}|r|                     d||||           d{V S i }d}| |                     |          }|d         |d<   |||d<   |6|                     |dz            }||d	<   |                     |d
          |d<   |                     d||d          \  }}|                     |                     ||                     d{V }	| 	                    |	|          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>`
        NFr   rj  rB   rm  r  r  r   ' rl  MbP?)
r  rf  r  rm  r  rp  handle_until_optionprivateWalletGetDepositsr!  parse_transactions
r  rv  r  r  r  rj  r%  rm  startr  s
             r  fetch_depositszgate.fetch_deposits  sk      !!!!!!!!!88R\]]& 	h::?DRWY^`fggggggggg}}T**H"*4.GJ$GG%%edl33E#GFO HHU,=>>GDM224&%PP66t{{7F7S7STTTTTTTT&&x:::r  c                 >  K   |                                   d{V  d}|                     |dd          \  }}|r|                     d||||           d{V S i }d}| |                     |          }|d         |d<   |||d<   |6|                     |dz            }||d	<   |                     |d
          |d<   |                     d||d          \  }}|                     |                     ||                     d{V }	| 	                    |	|          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>`
        NFr   rj  rB   rm  r  r  r  r  rl  r  )
r  rf  r  rm  r  rp  r  privateWalletGetWithdrawalsr!  r  r  s
             r  fetch_withdrawalszgate.fetch_withdrawals#  sm      !!!!!!!!!88ASU_``& 	k::;MtUZ\acijjjjjjjjj}}T**H"*4.GJ$GG%%edl33E#GFO HHU,=>>GDM224&%PP99$++gv:V:VWWWWWWWW&&x:::r  r  r  r  c                    K   |                      ||          \  }}|                     |           |                                  d{V  |                     |          }|d         ||                     ||          d}|||d<   d}|                     |          \  }}||                     |          |d<   |                     |                     ||                     d{V }	| 	                    |	|          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>`
        NrB   )rm  r  r  memor~  )
handle_withdraw_tag_and_paramsr  r  rm  currency_to_precisionr  network_code_to_id!privateWithdrawalsPostWithdrawalsr!  parse_transaction)
r  rv  r  r  r  r  rm  r%  r  r  s
             r  r   zgate.withdrawE  s*      99#vFFV7###!!!!!!!!!==&& 00v>>
 

 ?!GFO"AA&IIV"#66{CCGG??GU[@\@\]]]]]]]] %%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_statusm  sO      " 
 
 &&999r  c                 :    ddd}|                      |||          S )Nrs  
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  rs  r  r   
fee_amountr~  rm  txidr  r  r  r  r  rt  	addressToaddressFromr  tagTotagFromr  r  updatedrm  r  )internalcommentr   )r  r=   	string_gtr  r  r@  r8  safe_string_upperr  r  r6  r  ry  r;  )r  r  rm  rB   r  r  feeCostStringr  r}  rv  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                   K   |                                   d{V  |                                  d{V  |                     |          }|                     |d          }|                     |dd          }	|                     |d|	          }
|                     |d          }|
du}|du}|p|}| o|du }|                     ||||||          }d}|d         s|d         r:|r|                     |           d{V }n|                     |           d{V }n|d	         r:|r|                     |           d{V }ny| 	                    |           d{V }n]|d
         r:|r| 
                    |           d{V }n7|                     |           d{V }n|                     |           d{V }|                     ||          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>`
        Nr  r  	stopPricer  r  rR   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[[&> 	IVH- 	I O!%!;!;L!I!IIIIIII!%!@!@!N!NNNNNNNF^ 	I X!%!D!D\!R!RRRRRRR!%!I!I,!W!WWWWWWWH 	I Y!%!E!El!S!SSSSSSS!%!J!J<!X!XXXXXXX!::<HHHHHHHHHB &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_requestx  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                   K   |                                   d{V  |                                  d{V  |                     ||          }|d         }|                     |d                   }d}|d         r|                     |           d{V }n#|d         r|                     |           d{V }|                     |          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>`
        Nr   r  rR   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&> 	V!<<^LLLLLLLLHHF^ 	V!EEnUUUUUUUUH  ***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   r:  r  rB   )r  r  rk   r  r  r  r  reduce_onlyr%  F)rU  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  r0  r  ) r  r  r  r-   rB   safe_string_lower_nhandle_post_onlyhandle_time_in_forcer@  rW  r2   r  rS   amount_to_precisionr=   
string_negintprice_to_precisionr\  rf  r  cost_to_precisionr6   number_to_stringr:  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  r0  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                 F  K   |                                   d{V  |                                  d{V  |                     |          }|d         st          | j        dz             |                     |ddi          }|                     |dd|d|           d{V 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>`
        NrR   z9 createMarketBuyOrderWithCost() supports spot orders onlyr  Fr  r  )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&&vxdFSSSSSSSSSr  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  rU  rZ   r  r  r  r  r  r  )r  r  convert_type_to_accountrf  r6   rB   strr4  parse_to_numericr=   r5  r7  r!  )r  rB   r  r  r  r  r  r  r  r  rZ   rg  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           	      |  K   |                                   d{V  |                                  d{V  |                     |          }|                     |||||||          }	d}
|d         r|                     |	           d{V }
n|                     |	           d{V }
|                     |
|          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  rO  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_``&> 	X!??PPPPPPPPHH!FFWWWWWWWWH@ &111r  c                 L    dddddddddddd}|                      |||          S )Nr9  closedr  )r9  _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  r9  r  r5  ctimer  .r   r     update_time_msupdate_timefinish_timerU  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  )rX  	remainingr   r  r   r  )r  
safe_orderr  r  r  safe_string_upper_2r@  r  safe_number_2r=   string_equalsr  r?  r  r  r:  r  r  r  r  r5  r_  r  r  r  r  r;  )(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  rq  rZ   averageStringr  rp  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_nrW  r@  r  rY  r^  rM  )r  rB   r  r  r  r  r'  r  r  rM  r  r%  r  s                r  fetch_order_requestzgate.fetch_order_requestS  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                   K   |                                   d{V  |                                  d{V  |dn|                     |          }|                     d||          }|                     |d          }|                     |g dd          }|                     |||          \  }}	d}
|dk    s|dk    rd|r1|                     |                     ||	                     d{V }
nN| 	                    |                     ||	                     d{V }
n|dk    rb|r0| 
                    |                     ||	                     d{V }
n|                     |                     ||	                     d{V }
n|d	k    rb|r0|                     |                     ||	                     d{V }
n}|                     |                     ||	                     d{V }
nM|d
k    r0|                     |                     ||	                     d{V }
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_orderd  s     , !!!!!!!!!&&((((((((( .t{{6/B/B33L&&QQ**""6+O+O+OQVWW!%!9!9"ff!M!M6>>TX-- g!%!F!Ft{{SZ\iGjGj!k!kkkkkkk!%!A!A$++gWdBeBe!f!fffffffV^^ p!%!O!OPTP[P[\cerPsPs!t!ttttttt!%!J!J4;;W^`mKnKn!o!oooooooX q!%!P!PQUQ\Q\]dfsQtQt!u!uuuuuuu!%!K!KDKKX_anLoLo!p!pppppppX!@@WVcAdAdeeeeeeeeHHtw)UUVVV&111r  c                 D   K   |                      d||||           d{V 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>`
        r9  N)fetch_orders_by_status)r  r  r  r  r  s        r  fetch_open_orderszgate.fetch_open_orders  s6        00vVVVVVVVVVr  c                 f  K   |                                   d{V  |                                  d{V  |                     |d          }d}||                     |          }|d         }|                     d||          }|                     |d          }d}	|                     |ddd          \  }	}|	s)|||dk    r|                     d	||||           d{V S |                     |d
          }i }
| 	                    |||          \  }
}|| 
                    |dz            |
d<   |1|                     |d          }| 
                    |dz            |
d<   |||
d<   |                     |                     |
|                     d{V }|                     ||||          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>`
        Nrk  r  r   r   F
historicalri   r\  r  r  r  rl  r  )r  r  r  r  r  r  rf  r  rW  rY  r  &privateFuturesGetSettleOrdersTimeranger!  r   )r  r  r  r  r  rk  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 	_5=U]PV44ZPUW]^^^^^^^^^66**..vtVDD"//==GFOYYvw//F --edl;;GDM$GGDDT[[QXZ`EaEabbbbbbbb  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   rV  r\  r  r  r  r  rk  rl  lastIdlast_id)	r  handle_param_bool_2r  r`  rY  rW  r  r  handle_param_string_2)r  r  r  r  r  r  r  r  r  rR   r%  rk  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                 "  K   |                                   d {V  |                                  d {V  d }||                     |          }|d         }|                     |dd          }|                     d||          }|                     |d          }	|                     |||||          \  }
}|	dk    p|	dk    }|dk    }|o|o| }d }|r|sd|r1|                     |                     |
|                     d {V }n| 	                    |                     |
|                     d {V }nN| 
                    |                     |
|                     d {V }n|	d	k    rb|r0|                     |                     |
|                     d {V }n|                     |                     |
|                     d {V }n|	d
k    rb|r0|                     |                     |
|                     d {V }n}|                     |                     |
|                     d {V }nM|	dk    r0|                     |                     |
|                     d {V }nt!          | j        dz             |}|rTg }t%          dt'          |                    D ]4}|                     ||         d          }|                     ||          }5|                     ||||          }|                     ||||          S )Nr  r  r  r  r   rR   rP   r9  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 e d%)%B%B4;;wXeCfCf%g%gggggggHH%)%>%>t{{7Ta?b?b%c%cccccccHH!%!?!?GUb@c@c!d!dddddddV^^ i!%!H!HU\^kIlIl!m!mmmmmmm!%!C!CDKKPWYfDgDg!h!hhhhhhhX j!%!I!I$++V]_lJmJm!n!nnnnnnn!%!D!DT[[QXZgEhEh!i!iiiiiiiX!99$++g}:]:]^^^^^^^^HHtw)VVWWWf  	@F1c(mm,, @ @"oohqk8DD**6;??""665%@@00NNNr  c                   K   |                                   d{V  |                                  d{V  |dn|                     |          }|                     |g dd          }|                     |g d          }|                     d||          \  }}|dk    s|dk    r|                     |||          n|                     |||          \  }}	||d<   d}
|dk    s|dk    rd|r1|                     | 	                    ||	                     d{V }
nN| 
                    | 	                    ||	                     d{V }
n|dk    rb|r0|                     | 	                    ||	                     d{V }
n|                     | 	                    ||	                     d{V }
n|d	k    rb|r0|                     | 	                    ||	                     d{V }
n}|                     | 	                    ||	                     d{V }
nM|d
k    r0|                     | 	                    ||	                     d{V }
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  rW  r  r^  rY  #privateSpotDeletePriceOrdersOrderIdr!  privateSpotDeleteOrdersOrderId,privateFuturesDeleteSettlePriceOrdersOrderId'privateFuturesDeleteSettleOrdersOrderId-privateDeliveryDeleteSettlePriceOrdersOrderId(privateDeliveryDeleteSettleOrdersOrderId!privateOptionsDeleteOrdersOrderIdr9   rB   r  )r  rB   r  r  r  r  r  rM  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-- j!%!I!I$++V]_lJmJm!n!nnnnnnn!%!D!DT[[QXZgEhEh!i!iiiiiiiV^^ s!%!R!RSWS^S^_fhuSvSv!w!wwwwwww!%!M!MdkkZacpNqNq!r!rrrrrrrX t!%!S!STXT_T_`givTwTw!x!xxxxxxx!%!N!Nt{{[bdqOrOr!s!sssssssX!CCDKKPWYfDgDghhhhhhhhHHtw)VVWWWd &111r  idsc                   K   |                                   d{V  |                                  d{V  d}||                     |          }d}|dn|d         }|                     |d|          }|                     d||          \  }}|dk    }|r|t          | j        dz             |r`g }	t          dt          |                    D ]$}
||
         }||d}|		                    |           %| 
                    |	|           d{V S d|i}|g}t          dt          |                    D ]}
|	                    ||
                    |                     |           d{V }|                     |          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  rV  r  r2   rB   r  r  r  cancel_orders_for_symbols)privateFuturesPostSettleBatchCancelOrdersr   )r  r  r  r  r  r  rX  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 		PN1c#hh'' 1 1V$# #	 %%i000077OOOOOOOOOf
 I	q#c((## 	% 	%ASV$$$$GG	RRRRRRRR  ***r  c                 "  K   |                                   d{V  |                                  d{V  g }t          dt          |                    D ]}||         }|                     |d          }|                     |          }|d         st          | j        dz             |                     |d          }||d         d}	|                    |	           | 	                    |           d{V }
| 
                    |
          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>`
        Nr   r  rR   z4 cancelOrdersForSymbols() supports only spot marketsrB   )rB   rU  )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_symbolsi  sE      !!!!!!!!!&&(((((((((q#f++&& 	- 	-A1IE%%eX66F[[((F&> e"47-c#cddd!!%..B!' I !!),,,,>>~NNNNNNNN   ***r  c                   K   |                                   d{V  |                                  d{V  |dn|                     |          }|                     |dd          }|                     |ddg          }|                     d||          \  }}|dk    r|                     |||          n|                     |||          \  }}d}	|dk    s|dk    rd|r1|                     | 	                    ||                     d{V }	nN| 
                    | 	                    ||                     d{V }	n|dk    rb|r0|                     | 	                    ||                     d{V }	n|                     | 	                    ||                     d{V }	n|dk    rb|r0|                     | 	                    ||                     d{V }	n}|                     | 	                    ||                     d{V }	nM|d	k    r0|                     | 	                    ||                     d{V }	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  rW  r  r`  rY  privateSpotDeletePriceOrdersr!  privateSpotDeleteOrders%privateFuturesDeleteSettlePriceOrders privateFuturesDeleteSettleOrders&privateDeliveryDeleteSettlePriceOrders!privateDeliveryDeleteSettleOrdersprivateOptionsDeleteOrdersr9   rB   r   )
r  r  r  r  r  r  rM  r%  r  r  s
             r  cancel_all_orderszgate.cancel_all_orders  s     " !!!!!!!!!&&((((((((( .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-- c!%!B!B4;;wXeCfCf!g!ggggggg!%!=!=dkk'S`>a>a!b!bbbbbbbV^^ l!%!K!KDKKX_anLoLo!p!ppppppp!%!F!Ft{{SZ\iGjGj!k!kkkkkkkX m!%!L!LT[[Y`boMpMp!q!qqqqqqq!%!G!GT[]jHkHk!l!lllllllX!<<T[[R_=`=`aaaaaaaaHHtw)ZZ[[[:   6222r  fromAccount	toAccountc                 *  K   |                                   d{V  |                     |          }|                     |          }|                     |          }|                     ||          }	|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<   | 
                    |                     |
|                     d{V }|                     ||          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>`
        NrB   rm  r  r  rP   r  rU  rl  r  zA transfer requires params["symbol"] for isolated margin transfersrO   rQ   r  )r  rm  rL  r  rS   r@  r2   rB   r  rW  privateWalletPostTransfersr!  parse_transfer)r  rv  r  r  r  r  rm  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88Wf9U9UVVVVVVVV ""8X666r  r   c           
      j    |                      |d          d d |                     d |          d d d d |d	S )Ntx_id)	rB   r  r  rm  r  r  r  r  r  )r  r  )r  r   rm  s      r  r  zgate.parse_transfer  sN     ""8W55//h??

 

 
	
r  r  c                 &  K   |t          | j        dz             |dk     s|dk    rt          | j        dz             |                                  d{V  |                     |          }|                     |d|          \  }}|                     | j        dd          }|                     |d          }|                     |d|          }	| 	                    |          }
|d	}	|}
|	d	k    s|	d
k    r|
|d<   d|d<   n|
|d<   d}|d         r0| 
                    |                     ||                     d{V }nO|d         r0|                     |                     ||                     d{V }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  rb  cross_leverage_limitr  r  r  r  ri   rj   z+ setLeverage() not support self market type)r2   rB   r3   r  r  rY  r@  rS   r  r9  1privateFuturesPostSettlePositionsContractLeverager!  2privateDeliveryPostSettlePositionsContractLeverager9   )r  r  r  r  r  r%  rM  rb  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!SSTXT_T_`ginToToppppppppHHH 	X!TTUYU`U`ahjoUpUpqqqqqqqqHH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  lastUpdateTimestamprk  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  r:  r9  r  r  safe_positionr;  r  r  rt  r  )r  r  r  r  r  r  maintenanceRater  r  r  feePaidinitialMarginStringtakerFeer  s                 r  parse_positionzgate.parse_positionl  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                    K   |                                   d{V  |                     |          }|d         st          | j        dz             i }|                     ||d         |          \  }}|                     ||          }d}|d         r|                     |           d{V }nK|d         r|                     |           d{V }n'|d         dk    r|                     |           d{V }| 	                    ||          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>`
        Nr  z/ fetchPosition() supports contract markets onlyr  ri   rj   rk   )
r  r  r3   rB   rY  r!  (privateFuturesGetSettlePositionsContract)privateDeliveryGetSettlePositionsContract"privateOptionsGetPositionsContractr  )r  r  r  r  r%  rS  r  s          r  fetch_positionzgate.fetch_position  sS      !!!!!!!!!V$$j! 	ZTW'XXYYY..vvf~vNN++gv66&> 	V!JJ?[[[[[[[[HHH 	V!KKO\\\\\\\\HHF^x''!DD_UUUUUUUUHr ""8V444r  c                 H  K   |                                   d{V  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    r0|                     | 	                    ||                     d{V }	nk|dk    r0| 
                    | 	                    ||                     d{V }	n5|dk    r/|                     | 	                    ||                     d{V }	|                     |	|          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  rF  rj   )r  r  r  r  r  r  r  rY   privateFuturesGetSettlePositionsr!  !privateDeliveryGetSettlePositionsprivateOptionsGetPositionsparse_positions)
r  r  r  r  symbolsLengthr  r%  r  r  r  s
             r  fetch_positionszgate.fetch_positionsG  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>>!BB4;;wX^C_C_````````HHX!CCDKKPWY_D`D`aaaaaaaaHHX!<<T[[RX=Y=YZZZZZZZZHz ##Hg666r  c                    K   |                                   d{V  |                     dd|          \  }}|                     d||          \  }}|dk    r|dk    rt          | j        dz             d}|dk    r0|                     |                     ||                     d{V }nM|dk    r0|                     |                     ||                     d{V }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
        Nr   rj   ri   z1 fetchLeverageTiers only supports swap and futurez2 fetchLeverageTiers() not support self market typerC   )
r  r  rY  r3   rB   r   r!  r(  r9   parse_leverage_tiers)r  r  r  r  rM  r%  r  r  s           r  fetch_leverage_tierszgate.fetch_leverage_tiers  sD      !!!!!!!!!889MtU[\\e!%!5!5dD%!H!H8TW'ZZ[[[6>>!AA$++gWdBeBeffffffffHHX!BB4;;wXeCfCfggggggggHHtw)]]^^^z ((7FCCCr  c                   K   |                                   d{V  |                     |          }|                     d||          \  }}|                     |||          \  }}|dk    r|dk    rt	          | j        dz             d}|dk    r0|                     |                     ||                     d{V }n/|                     |                     ||                     d{V }| 	                    ||          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>`
        Nr   rj   ri   z7 fetchMarketLeverageTiers only supports swap and future)
r  r  r  rY  r3   rB   $publicFuturesGetSettleRiskLimitTiersr!  %publicDeliveryGetSettleRiskLimitTiersparse_market_leverage_tiers)	r  r  r  r  r  rM  r%  r  r  s	            r  fetch_market_leverage_tiersz gate.fetch_market_leverage_tiers"  s2      !!!!!!!!!V$$889SU[]cdde!%!5!5fdE!J!J8TW'``aaa6>> "FFt{{SZ\iGjGjkkkkkkkkHH!GGT[]jHkHkllllllllH//&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  r2  risk_limit_steprisk_limit_maxr  r  r  r  tierr  rm  minNotionalmaxNotionalmaintenanceMarginRatemaxLeverager  )r  r=   r  r  r9  r  r  r  )r  r  r  r  maintenanceMarginUnitleverageMaxriskLimitStepriskLimitMaxinitialMarginUnitr  initialMarginRatiofloorr&  caps                 r  parse_emulated_leverage_tiersz"gate.parse_emulated_leverage_tiersE  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  r2  r  )r  r  r"  r  r  r  r  rp  )r  r  r  r  r&  r  itemr  s           r  r  z gate.parse_market_leverage_tiersa  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                   K   |                                   d{V  |                     |          }|d                                         |                     ||          d}|                     |          }|d         |d<   d|d<   |                     |                     ||                     d{V }|                     ||          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>`
        NrB   r  rU  repayr  r  rm  upperr  r  privateMarginPostUniLoansr!  parse_margin_loan)	r  r  rv  r  r  rm  r%  r  r  s	            r  repay_isolated_marginzgate.repay_isolated_margin  s       !!!!!!!!!==&& ,,..00v>>
 
 V$$#)$< !77GV8T8TUUUUUUUU %%h999r  c                 Z  K   |                                   d{V  |                                  d{V  |                     |          }|d                                         |                     ||          d}d}|                     |dd          \  }}d}|r5d|d<   |                     |                     ||                     d{V }nE|                     |                     ||                     d{V }| 	                    |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>`
        NrB   r  Fr   r  r'  r  r   )r  r  rm  r)  r  rf  privateUnifiedPostLoansr!   privateMarginPostCrossRepaymentsr  r+  r  rv  r  r  rm  r%  rg  r  s           r  repay_cross_marginzgate.repay_cross_margin  sf      !!!!!!!!!&&(((((((((==&& ,,..00v>>
 
 !#'#@#@I[]m#n#n & 	3%GFO!99$++gv:V:VWWWWWWWWHH "BB4;;wX^C_C_````````H~~h22H" %%h999r  c                   K   |                                   d{V  |                     |          }|d                                         |                     ||          d}d}|                     |          }|d         |d<   d|d<   |                     |                     ||                     d{V }|                     ||          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>`
        NrB   r  rU  borrowr  r(  )	r  r  rv  r  r  rm  r%  r  r  s	            r  borrow_isolated_marginzgate.borrow_isolated_margin  s       !!!!!!!!!==&& ,,..00v>>
 
 V$$#)$< "77GV8T8TUUUUUUUU( %%h999r  c                 .  K   |                                   d{V  |                                  d{V  |                     |          }|d                                         |                     ||          d}d}|                     |dd          \  }}d}|r5d|d<   |                     |                     ||                     d{V }n/|                     |                     ||                     d{V }| 	                    ||          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>`
        NrB   r  Frm   r  r3  r  )
r  r  rm  r)  r  rf  r.  r!  privateMarginPostCrossLoansr+  r0  s           r  borrow_cross_marginzgate.borrow_cross_margin  sT      !!!!!!!!!&&(((((((((==&& ,,..00v>>
 
 !#'#@#@I\^n#o#o & 	\&GFO!99$++gv:V:VWWWWWWWWHH "==dkk'SY>Z>Z[[[[[[[[H %%h999r  c           	         |                      | j        ddd          }|                     |d          }|dk    r|                     |d          }|                     |d          }|                     |d          }|                     |d          |                     ||          |                     |d	          |                     |d d
d          ||                     |          |dS )Nrb  r  r  r5  r  rm  rU  rB   r  r  rP   )rB   rm  r  r  r  r  r  )	r@  rS   r  r6  r  r  r  r  r;  )r  r  rm  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                 `  K   |                                   d{V  |                                  d{V  d}|                     |dd          \  }}i }|                     d||          \  }}d}| |                     |          }|d         |d<   d}	||                     |          }	|||d<   |||d	<   d}
d}|                     d|d
          \  }}|r0|                     |                     ||                     d{V }
nx|dk    r=|	|	d         |d<   | 	                    |                     ||                     d{V }
n5|d
k    r/| 
                    |                     ||                     d{V }
|                     |
|	          }|                     ||||          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>`
        NFr   r  rl  rB   rm  r  r  r  r  rU  )r  r  rf  r  rm  r  handle_margin_mode_and_params privateUnifiedGetInterestRecordsr!  "privateMarginGetUniInterestRecords$privateMarginGetCrossInterestRecordsparse_borrow_interestsfilter_by_currency_since_limit)r  rv  r  r  r  r  rg  r%  rm  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 	e!BB4;;wX^C_C_````````HH:%%!+1$<(!DDT[[QXZ`EaEabbbbbbbbHH7""!FFt{{SZ\bGcGcddddddddH..x@@228T5%PPPr  r  c                    |                      |d          }|                     ||          }|dnd}|                     |d          }||                      |d          |                     |                      |d                    |                     |d          |                     |d          d |||                     |          d		S )
NrU  r  r  r5  r  rm  r@  actual_rate)	r  r  rm  r@  r  amountBorrowedr  r  r  )r  r  r  r  r  r;  )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;  rH  DELETEPATCHzcurrencies=z%2C,rM  sha512r  z/api/
zapplication/json)KEY	TimestampSIGNzContent-Type)r_   ri  bodyr  )#rW  extract_paramsr  endswithr  implode_paramsr  r  r  r  r  r  rM   r9   rB   	urlencoder  r  r  	rawencodereplacejsonhashencoder  r  rM  rI   r)  joinhmacr  hashlibrQ  r  )"r  pathrd   ri  r  r  rV  authenticationr  rM  containsSettler  	newParams	anyParamsr  rG  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                   K   |                                   d {V  |                     |          }|                     |d |          \  }}|                     |          |d<   d }|d         r0|                     |                     ||                     d {V }nO|d         r0|                     |                     ||                     d {V }nt          | j        dz             | 	                    ||          S )Nr  ri   rj   z2 modifyMarginHelper() not support self market type)
r  r  rY  r9  /privateFuturesPostSettlePositionsContractMarginr!  0privateDeliveryPostSettlePositionsContractMarginr9   rB   parse_margin_modification)r  r  r  r  r  r%  rM  r  s           r  modify_margin_helperzgate.modify_margin_helper  s.     !!!!!!!!!V$$--fdFCC 11&99&> 	_!QQRVR]R]^eglRmRmnnnnnnnnHHH 	_!RRSWS^S^_fhmSnSnooooooooHH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  rO  rv  r  r  r  )r  r  r  r  )r  r_  r  r  rO  s        r  r{  zgate.parse_margin_modification  s    8 ##D*55!!(FCDD  x00X&$OOFG44
 
 	
r  c                 B   K   |                      || |           d{V 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>`
        Nr|  r  r  r  r  s       r  reduce_marginzgate.reduce_margin-  s4       ..vwGGGGGGGGGr  c                 @   K   |                      |||           d{V 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>`
        Nr  r  s       r  
add_marginzgate.add_margin;  s2       ..vvvFFFFFFFFFr  rQ  c           	      $  K   |                                   d{V  d}|                     |ddd          \  }}|r!|                     d|||||d           d{V S |                     |          }|d         st	          | j        dz             |d         |d	         |                     | j        ||          d
}|||d<   |||d<   |                     | 	                    ||                     d{V }	| 
                    |	|||          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:
        NFr   rj  r  ri   z/ fetchOpenInterest() supports swap markets onlyrB   r  )r  r  r  r  r  )r  rf  rm  r  r3   rB   r  rN  #publicFuturesGetSettleContractStatsr!  parse_open_interests_history)
r  r  rh  r  r  r  rj  r  r%  r  s
             r  fetch_open_interest_historyz gate.fetch_open_interest_historyI  s      !!!!!!!!!88A[]ginoo& 	K@@A[]cejlqs|  E  GJ  K  K  K  K  K  K  K  K  KV$$f~ 	ZTW'XXYYYtZ((()YOO
 

 $GG#GFOAA$++gW]B^B^________, 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  )r6  r  r  r;  )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                 t  K   |t          | j        dz             |                                  d{V  |                     |          }d}|                     d||          \  }}|dk    rt          | j        dz             |d         }|                    d          }d|                     |d	          i}	|||	d
<   |||	d<   |                     | 	                    |	|                     d{V }
| 
                    |
|          }|                     |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  rF  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  sj      >#DG.d$deee!!!!!!!!!V$$99:RTZ\bccf8tw)aabbb$<nnS))$**;::
 #GFO$GG99$++gv:V:VWWWWWWWW ,,Xv>>k;7700NNNr  c                   K   |                                   d{V  d}||                     |          }|d         }d}|                     d||          \  }}|dk    }|dk    }|s|st          | j        dz             |                     |||          \  }	}
|||	d<   d}|r0|                     |                     |	|
                     d{V }n|||	d<   |0|                     |d	          }|t          | j        d
z             n6|d         }|
                    d          }|                     |d          |	d	<   |                     |                     |	|                     d{V }|                     |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  rF  z[ fetchMySettlementHistory() requires a symbol argument or an underlying parameter in paramsrB   r  r   r  r  r  )r  r  r  r9   rB   rY  #privateDeliveryGetSettleSettlementsr!  r  r2   r  privateOptionsGetMySettlementsr  r  r  r   )r  r  r  r  r  r  r  r  isFuturer%  rM  r  rF  r  r  r  r_  r   r  s                      r  fetch_my_settlement_historyz gate.fetch_my_settlement_history  sS      !!!!!!!!![[((FH%F99:TV\^deef8#8# 	p 	ptw)nnooo--fdFCC$GG +	_  "EEdkkRY[`FaFabbbbbbbbHH "'~!--flCC
%+DG  7T  -T  U  U  U & "$<&nnS11(,(8(8a(H(H%  "@@WV\A]A]^^^^^^^^H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  )r6  r  r  r  r;  )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_settlementsK  sZ    > q#k**++ 	I 	IAMM$//AGGHHHHr  c                 ~  K   |                                   d{V  d}|                     |dd          \  }}|r|                     d||||           d{V 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    r0|                     | 	                    |	|                     d{V }n|dk    r0| 
                    | 	                    |	|                     d{V }n|d	k    r0|                     | 	                    |	|                     d{V }nk|d
k    r0|                     | 	                    |	|                     d{V }n5|dk    r/|                     | 	                    |	|                     d{V }|                     ||||          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>`
        NFr   rj  rR   rP   rB   rm  ri   rj   r  r  r  r  r  rl  rk   )r  rf  r  r  rm  rV  rW  r  privateSpotGetAccountBookr!  privateMarginGetAccountBookr  r  privateOptionsGetAccountBookparse_ledger)r  rv  r  r  r  rj  r  rm  r  r%  rX  r  s               r  fetch_ledgerzgate.fetch_ledgero  s     $ !!!!!!!!!88PZ[[& 	f::=$PUW\^deeeeeeeee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>>!;;DKKQW<X<XYYYYYYYYHHX!==dkk'SY>Z>Z[[[[[[[[HHV^^!DDT[[QXZ`EaEabbbbbbbbHHX!EEdkkRY[aFbFbccccccccHHX!>>t{{7TZ?[?[\\\\\\\\Hj   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inrm  r  r   r  r  balancerB   )r  rB   	directionrZ   referenceAccountreferenceIdr  rm  r  r  r  beforeafterr  r   )r  r=   r  r  r  r  r6  r  r8  safe_ledger_entryparse_ledger_entry_typer  r;  r  )r  r%  rm  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 ),Nrs  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                    K   ||                      |          nd}|                     |d|          \  }}||d<   |                     |                     ||                     d{V 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  rY   privateFuturesPostSettleDualModer!  )r  r  r  r  r  r%  rM  s          r  set_position_modezgate.set_position_modeV  s}       *0);V$$$$--fffEE%::4;;wPU;V;VWWWWWWWWWr  c                   K   |                                   d{V  d}|                     dd|          \  }}||dk    rd}|dk    rt          | j        dz             |                     |           d{V }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   rR  r  r  r  r  )r  r  r  r  r   r  rF  rC   s           r  fetch_underlying_assetszgate.fetch_underlying_assetsg  s      !!!!!!!!!
!??@WY]_eff
FJ&$8$8!J!!tw)``aaa99&AAAAAAAA q#h--(( 	) 	)A!!J##J77D""4(((r  c                   K   |                                   d{V  |                     |          }|d         st          | j        dz             |d         |d         d}|||d<   |||d<   |                     d	||          \  }}|                     |                     ||                     d{V }|                     ||||          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>`
        Nri   z/ fetchLiquidations() supports swap markets onlyr  rB   )r  r  r  r  rl  )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==dkk'SY>Z>Z[[[[[[[[ &&xFFFr  c                 6  K   |t          | j        dz             |                                  d{V  |                     |          }d|d         i}d}|d         s|d         r|||d<   |d         |d	<   n>|d
         r6|d         }|                    d          }	|                     |	d          |d<   |d         r0|                     |                     ||                     d{V }n|d         r0|                     |                     ||                     d{V }n[|d
         r0| 	                    |                     ||                     d{V }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   rF  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!CCDKKPWY_D`D`aaaaaaaaHHH 	r!DDT[[QXZ`EaEabbbbbbbbHHH 	r!@@WV\A]A]^^^^^^^^HH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_sizerb  r  r  r  re  r  r  r  r  r  r  )
r  r  r   r  r  r  	baseValue
quoteValuer  r  )r  r6  r@  r=   r  r8  r:  rV  r  r  safe_liquidationr  r  r;  )r  liquidationr  r  r  r  rb  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                   K   |                                   d{V  |                     |          }d|d         d         i}|                     |                     ||                     d{V }|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>`
        NrF  r  rB   r   rC   )r  r  r  r!  r  r  r  parse_greeks)
r  r  r  r  r%  r  r  r  r|  entryMarketIds
             r  fetch_greekszgate.fetch_greeksK  s       !!!!!!!!!V$$&.6
 55dkk'66R6RSSSSSSSS. $<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_greeksy  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                    K   ddi}|                      ||          }|d}|                     |d|dd|           d{V 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>`
        r:  TNr,  r  r   )r!  r  )r  r  r  r  r%  s        r  close_positionzgate.close_position  sc       T
 Wf--<D&&vxq$OOOOOOOOOr  c                   K   |                                   d{V  d}||                     |          }i }d}|                     |d          }|                     |d          }|d         rm|d         |d<   |r0|                     |                     ||                     d{V }n|                     |                     ||                     d{V }nU|r0|                     |                     ||                     d{V }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   rU  z" fetchLeverage() does not support r  rK  )r  r  r  rW  +publicMarginGetUniCurrencyPairsCurrencyPairr!  (publicMarginGetCurrencyPairsCurrencyPairrU  r9   rB   parse_leverage)r  r  r  r  r%  r  	isUnifieds          r  fetch_leveragezgate.fetch_leverage  s      !!!!!!!!![[((FNN6955	69--&> O	m'-d|GO$ m!%!Q!QRVR]R]^egmRnRn!o!ooooooo "&!N!Nt{{[bdjOkOk!l!lllllll  5	m!;;DKKQW<X<XYYYYYYYYHHh tw)MMPVW]P^^akklll""8V444r  c                 j  K   |                                   d{V  |                     |          }d}|                     |d          }|                     |d          }d}|rd}|                     |           d{V }n|                     |           d{V }|                     |||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   rU  rR   )r  r  r  rW  publicMarginGetUniCurrencyPairsr  parse_leverages)r  r  r  r  r
  marketIdRequests         r  fetch_leverageszgate.fetch_leverages"  s       !!!!!!!!!%%g..NN6955	69-- 	G-O!AA&IIIIIIIIHH ">>vFFFFFFFFH ##HgOOOr  c                     |                      |dd          }|                     |d          }||                     ||dd          d ||dS )NrU  rB   r  r  rR   )r  r  r  longLeverageshortLeverage)r@  r  r  )r  r  r  r  leverageValues        r  r	  zgate.parse_leverageR  s`    %%hFF))(J??&&xfEE)*
 
 	
r  c                   K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     |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>`
        Nr  rB   )r  r  !publicOptionsGetContractsContractr!  parse_optionr  s         r  fetch_optionzgate.fetch_option]  s       !!!!!!!!!V$$t
 ??GU[@\@\]]]]]]]]R   4888r  c                 
  K   |                                   d{V  |                     |          }d|d         dz   i}|                     |                     ||                     d{V }|                     |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>`
        NrF  rv  _USDTrC   )r  rm  rL  r!  parse_option_chain)r  rv  r  rm  r%  r  s         r  fetch_option_chainzgate.fetch_option_chain  s       !!!!!!!!!==&&(6*W4
 77GV8T8TUUUUUUUU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   r5  r  rm  r  r  r  impliedVolatilityopenInterestr   r$  r  r!  midPricer?  r.  r  r  r  r  r  r%  r=  r>  )r  r  r6  r;  r  )r  r~  rm  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                 ,  K   |                                   d{V  d}|0t          |          }|dk    r|                     |d                   }d}|                     d||d          \  }}|                     |d          }|                     |d          }i }	|                     |||          \  }	}|||	d<   ||                     |dz            |	d	<   ||                     |dz            |	d
<   d}
|dk    r0|                     | 	                    |	|                     d{V }
nP|dk    r0| 
                    | 	                    |	|                     d{V }
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   rk  r  r  r  rl  rj   z: fetchPositionsHistory() does not support markets of type )r  r  r  r  r  rW  rY  r  $privateFuturesGetSettlePositionCloser!  %privateDeliveryGetSettlePositionCloser9   rB   r  )r  r  r  r  r  r  r  r  rk  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!FFt{{SZ\bGcGcddddddddHH8##!GGT[]cHdHdeeeeeeeeHHtw)eehrrsss* ##Hgv>>>r  reasonr_   ri  r  rV  c
                     |d S |                      |d          }
|
>| j        dz   |z   }|                     | j        d         |
|           t	          |          d S )Nlabel r  )r  rB   throw_exactly_matched_exceptionr  r-   )r  rv  r%  r_   ri  r  rV  r  requestHeadersrequestBodyr'  feedbacks               r  handle_errorszgate.handle_errorsW  sm    4   733w}t+H001I5RZ[[[)))tr  )NNNNr  )NN)__name__
__module____qualname__r   r  boolr  r  r  r   r  rM  r  r    r   r*   r  r,   r  r  r  r  r"  r  rK  rY  r^  r`  r\  r  r	   r  r$   r  r!   r%   r  r  r  r  r   r  r  r  r'   r  r(   r  r  r  r  r  r
   r  r  r   r  r  r   r  r"   r  dictr  r#   rH  rR  r   rg  r  r}  rn  r  r  r&   r  r  r  r  r)   r  r  floatr   r  r  r  r   r   r   r  r   r  r"  r  rI  rO  rT  r_  r   r  r  r  r  r  r  r  r  r  r   r  r  r+   r   r  r6  r  r  r  r   r  r   r  r   r  r"  r  r,  r1  r4  r7  r+  r   rA  rE  r  rw  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-  __classcell__)r  s   @r  r?   r?      sG       }# } } } } } }~#-t - - - - - - 02 . . . .B :< ? ? ? ? ') : :S : : : :"=
3 =
 =
 =
 =
~V VC V VRU Vjm V  zI V V V V V V *, "+ "+V "+ "+ "+ "+H /1 o o o ob /1      13     g
 g
 g
R 13 v v v vp  & &*R ! ! ! !8 15eB        $ 7;ERT        *$ $ $:c c c -/ c c: c c c cJ <> <1 <1s <1+ <1 <1 <1 <1| <@ >; >; >;| >; >; >; >;@G
 G
6 G
[ G
 G
 G
 G
R? ? ? EG # # # # # #J JL 0 0S 0PTUcPd 0 0 0 0, =? : : :> : : : :$
 
 
 
( ;= 8 8c 8AT 8 8 8 8@ /1 1 1[ 1 1 1 16  
 
f 
 
 
 
< =A 5 5' 5 5 5 5n BFb M Mw M M M MB. . . . . .` 9=4^bkm .L .L# .LS .LX[ .L .L .L .L`OnI] O O O O
 
& 
 
 
 
. @DB s sS s sS\ s s s sj 68 '1 '1 '1F '1 '1 '1 '1Rn n4 n n6 n n n n` 6:" %5 %57 %5 %5 %5 %5 %5N   *, Z Z Z Z Z Zx ?CQUdhqs AL AL AL AL3 AL^a ALx|  ~B  yC AL AL AL ALF ?CQUdhqs L Ls L3 L^a L L L L >BPTcgpr 5Y 5Ys 5Y# 5Y]` 5Y 5Y 5Y 5Yn+ + +4 + + + +Z <@d[] hA hA hAS hA hAbfglbm hA hA hA hAT ?CQUdhqs ' '3 ' '3 '^a ' ' ' 'R 37TX\eg BA BAC BAs BARU BA BA BA BAH_ _ _v _ _ _ _ _B 04$UYbd  ;  ;  ;C  ;s  ;imnyiz  ;  ;  ;  ;D 37TX\eg  ;  ;C  ;s  ;RU  ;lpq|l}  ;  ;  ;  ;D QU]_ &: &:3 &: &: &:# &:do &: &: &: &:P:s : : : :$3 3 3k
 k
T k
X k
Q\ k
 k
 k
 k
Z mqy{ C2 C2 C2I C2Y C2X] C2fi C2 C2 C2 C2J HJ  D,>    < FH + +$|*< + + + +. os{} U, U,3 U,i U,y U,Z_ U,hk U, U, U, U,n XZ T Tc T T T T T( hlz~  HJ , ,S ,# ,Y ,i ,ad ,tw , , , ,B fjx|  FH 92 923 92 929 92I 92_b 92ru 92 92 92 92v: : : : : M M Mv M M M M M^
 :>b ( (c (3 ( ( ( (" 8<B 12 12C 12 12 12 12 12f 59tZ^gi W Wc W WTW Wnrsxny W W W W$ 7;\`ik 0A 0A 0A3 0AVY 0Aptuzp{ 0A 0A 0A 0Ad FJX\koxz & &s &RU &eh & & & &> BFTXgktv O O3 Oc Oad O O O OB 9=R @2 @2S @2# @2 @2 @2 @2D AER *+ *+tCy *+# *+ *+ *+ *+X Y[ $+ $+d;N6O $+ $+ $+ $+L 59 H3 H3c H3 H3 H3 H3T ac 67 673 67 67C 67TW 67gt 67 67 67 67p
 
t 
x 
= 
 
 
 
, ?C2 C C3 C C C C CJE Et EV E E E EN 8: R5 R53 R5 R5 R5 R5h 8<B d7 d7W d74PX> d7 d7 d7 d7L =A sD sD' sDP] sD sD sD sDj EG !B !B !B4P\K] !B !B !B !BF $|BT    8  $|J\    @ RT : :# :S : : : :: BD /: /:S /: /: /: /:b Z\ +: +:3 +:c +:5 +: +: +: +:Z JL ,: ,:c ,:5 ,: ,: ,: ,:\3
 3
 3
 3
 3
 3
j 7;$]apt} -Q -Q -QC -QWZ -Qjm -Q  EI  JX  EY -Q -Q -Q -Q^
 
$ 
 
. 
 
 
 
"D D D  b$T OP OP OP OPb FH @ @ @ @ @ @*
 *
d *
F *
N` *
 *
 *
 *
X FH H H# Hu HL^ H H H H CE G Gs GE GI[ G G G G HLZ^mqz| 5Q 5Q 5QTW 5Qgj 5Q 5Q 5Q 5Qn
 
F 
 
 
 
: <@daenp ,O ,OS ,O ,O[^ ,O ,O ,O ,O\ ?CQUdhqs LO LO LO3 LO^a LO LO LO LO\0
 0
 0
d" " "H .2SW`b hC hCs hC# hCS hCgklwgx hC hC hC hCTP Pt Px P; P P P Pd)8 )8 )8V CGr X Xd XC X X X X" 46 ! ! ! !F BFTXac 'G 'Gs 'G3 'Gc 'G 'G 'G 'GR 9=4^bkm GG GG# GGS GGX[ GG GG GG GGRM MV M M M M^ 68 , , ,F , , , ,\+
 +
4 +
 +
6 +
 +
 +
 +
Z CGr P P3 Pi PV[ P P P P* 8: e5 e53 e5h e5 e5 e5 e5N 8<B .P .PW .P9 .P .P .P .P`	
 	
t 	
V 	
x 	
 	
 	
 	
 68 89 89 89F 89 89 89 89t :< <? <?S <? <? <? <? <?|>
 >
$ >
( >
6 >
]c >
 >
 >
 >
@ @DRVeirt @? @?W @?C @?_b @?y}  G  zH @? @? @? @?D# s  c TX `c        r  r?   )E ccxt.async_support.base.exchanger   ccxt.abstract.gater   r  rb  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   6 5 5 5 5 5 * * * * * *   ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]       * * * * * * 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  