
    !:h[                       d dl mZ d dlmZ d dlZd dlmZmZmZm	Z	m
Z
mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z, d dl-m.Z. d dl/m0Z0 d dl/m1Z1 d dl/m2Z2 d d	l/m3Z3 d d
l/m4Z4 d dl/m5Z5 d dl/m6Z6 d dl/m7Z7 d dl/m8Z8 d dl/m9Z9 d dl/m:Z: d dl/m;Z; d dl/m<Z< d dl/m=Z= d dl/m>Z> d dl?m@Z@ d dlAmBZB  G d dee      ZCy)    )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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) Z/ddefd*Z0d
i fd+e!fd,Z1d
i fd+e!fd-Z2dd.e3fd/Z4d
d
d
i fded0e	d1e	fd2Z5dee6   fd3Z7ddefd4Z8d
i fded1e	de9fd5Z:i fdede;fd6Z<dd7e=dede;fd8Z>d
i fde!de?fd9Z@d: ZAi fdeBfd;ZCd<d
d
i fded0e	d1e	deeD   fd=ZEd<d
d
i fded0e	d1e	fd>ZFd
d
d
i fded0e	d1e	fd?ZGddedeDfd@ZHd
d
i fded0e	d1e	deeI   fdAZJd
d
d
i fdBeded0e	d1e	fdCZKd
d
d
i fded0e	d1e	fdDZLddEe=dedeIfdFZMd
d
d
i fd"ed0e	d1e	deeN   fdGZOd
d
d
i fd"ed0e	d1e	deeN   fdHZPd
i fd"edIeQdJedeNfdKZRdLefdMZSdN ZTddOe=d.e3deNfdPZUd
i fdedQeVdReWdIeQdSeXf
dTZYi fdUeeZ   fdVZ[i fdUeeZ   fdWZ\d
i fdedQeVdReWdIeQdSeXf
dXZ]i fdedYeQfdZZ^d
d
i fdBededQeVdReWdIeXdSeXfd[Z_d
d
i fdBededQeVdReWdIeXdSeXfd\Z`dLefd]Zadd^e=dedebfd_Zcd
i fdBedefd`Zdd
i fdBedefdaZed
d
d
i fded0e	d1e	deeb   fdbZfd
d
d
i fded0e	d1e	deeb   fdcZgd
d
d
i fded0e	d1e	fddZhd
d
d
i fded0e	d1e	fdeZid
i fdBedefdfZjd
i fdgee   defdhZki fdUeel   fdiZmd
i fdefdjZni fd"edIeQdkedledeof
dmZpddne=d.e3deofdoZqd
i fdpe	defdqZrddre=defdsZsi fdefdtZtd
i fde!deeu   fduZvd
i fde!dewfdvZxi fdedeey   fdwZzddeey   fdxZ{ddedeey   fdyZ|i fded"efdzZ}i fd"efd{Z~i fded"edIeQfd|Zi fd"edIeQfd}Zdd.e3fd~Zd
d
d
d
i fd"eded0e	d1e	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dIeQdefdZi fdedIeQdefdZdd
d
i fded0e	d1e	fdZddefdZd
d
d
i fded0e	d1e	fdZd
d
d
i fded0e	d1e	fdZd Zd Zd
d
d
i fd"ed0e	d1e	dee   fdZdde=d.e3defdZd Zd
i fdedefdZi fdZd
d
i fded0e	d1e	fdZd
d
d
i fded0e	d1e	fdZddefdZi fdedefdZdde=dedefdZd
i fdedReWdebfdZi fdedefdZd
i fde!defdZddpe=dedefdZi fdedefdZi fd"edefdZdde=d.e3dedefdZd
d
d
i fde!d0e	d1e	deeu   fdZd"edededede=defdZ xZS )gatereturnc                 %   | j                  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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dvdxdxdxdxdxdxdxdxdxdy	idvdxdxdxdxdxdxdxdzidvd{dxiidvdxdxdxdxdxdxdxdxdxdxdxdxdxd|idvdxdxdxdxdxdxdxd}idvdxdxdxdxdxdxdxdxdxdxdxdxd~idvdxdxdidddxdddxidi ddxddxddxddxddxddxddddddddddxddxddddxddxddxddddxddddddddddddddiddiddddddddddddddddddddd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ddddddddddddddddddddddiddxdxdxdxddxdxddi ddxddxddxddxddxddxddxddxddxddxddxddxddxddxddxddxddxdxdxdxdxdxdxdxddddddќddxidddddҜddddddddddddddӜddddddԜdddddҜd՜ddddddddddd֜
dddddלddd؜d՜ddddddddٜddiddiddidܜi dddddddddddddddddddddddddddddddddddddddddddddddddddid՜dvdddidddddddddddddddd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&d'ddd(d)d*d+id,d-d-d-d d.d/idi d0d0d1d2d3d3d4d3d5d5d6d5d7d8d9d8d:d:d;d:d<d<d=d>d?d>d@dAdBdAdCdCdDdEi dFdFdGdHdIdJdKdKdLdMdMdMdNdNdOdPdQdRdSdSdTdTdUdVdWdXdYdYdZd[d\d\d]d]i d^d^d_d_d`d`dadadbdbdcdcdddddededfdfdgdhdidjdkdldmdndodpdqdrdsdtdAd@idudvdwdwdxdyddddzdzdd{d|d{d|d,d,d}dYd~ddgiidYd~dg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| j                  d      | j                  d      | j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      gg| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      ggddddd| j                  d«      | j                  dë      | j                  d      | j                  dī      g| j                  d      | j                  dū      g| j                  d      | j                  dū      g| j                  d      | j                  dū      g| j                  d      | j                  dū      g| j                  d      | j                  dū      g| j                  d      | j                  dū      g| j                  d      | j                  dū      g| j                  d      | j                  dū      g| j                  d      | j                  dū      g| j                  d      | j                  dū      g| j                  d      | j                  dƫ      g| j                  d      | j                  dǫ      g| j                  d      | j                  dȫ      g| j                  d      | j                  dɫ      g| j                  d      | j                  dʫ      g| j                  d      | j                  d˫      gg| j                  d      | j                  d̫      g| j                  d      | j                  dͫ      g| j                  d      | j                  dΫ      g| j                  d      | j                  dϫ      g| j                  d      | j                  dЫ      g| j                  d      | j                  dѫ      g| j                  d      | j                  dҫ      g| j                  d      | j                  dӫ      g| j                  d      | j                  dԫ      g| j                  d      | j                  dի      g| j                  d      | j                  d֫      g| j                  d      | j                  d֫      g| j                  d      | j                  d֫      g| j                  d      | j                  d֫      g| j                  d      | j                  d֫      g| j                  d      | j                  d֫      g| j                  d      | j                  d֫      ggdddלi dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        i dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        i dt        dt         dt         dt"        dt$        dt$        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        d)t        d*t        d+t        d,t"        t        t        t        t        t        t        t        t        t        t        t        d-i d.d/      S (0  Nidr?   namezGate.io	countriesKR	rateLimit2   versionv4	certifiedTprourlszOhttps://github.com/user-attachments/assets/64f988c5-07b6-4652-b5c1-679a6bf67c85z-https://www.gate.io/docs/developers/apiv4/en/zhttps://gate.io/zhttps://api.gateio.ws/api/v4)walletfuturesmargindeliveryspotoptionssub_accountsearn)withdrawalsrM   rN   rO   rP   rQ   rR   subAccountsunifiedrebaterT   accountloan)publicprivatez'https://fx-api-testnet.gateio.ws/api/v4)rN   rP   rR   z"https://www.gate.io/signup/2436035g?)urldiscount)logodocwwwapitestreferralhasCORSrQ   rO   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withdrawrb   getcurrency_chains   )	
currencieszcurrencies/{currency}currency_pairscurrency_pairs/{currency_pair}tickers
order_booktradescandlestickstime)r   r   funding_bookzcross/currencieszcross/currencies/{currency}zuni/currency_pairsz"uni/currency_pairs/{currency_pair}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   )underlyingsexpirations	contractszcontracts/{contract}settlementszsettlements/{contract}r   r   zunderlying/tickers/{underlying}r   zunderlying/candlesticksr   )uni/currenciesuni/currencies/{currency})rM   rQ   rO   
flash_swaprN   rP   rR   rT      )rU   pushzwithdrawals/{withdrawal_id})postdeletedeposit_addressrU   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   )	transfersr   sub_account_to_sub_accountr   )r   r   )rS   zsub_accounts/{user_id}sub_accounts/{user_id}/keys!sub_accounts/{user_id}/keys/{key})rS   r   zsub_accounts/{user_id}/lockzsub_accounts/{user_id}/unlockr   )r   r   putr   gUUUUUU?)accountsaccount_mode
borrowabletransferableloansloan_recordsinterest_recordsestimate_ratecurrency_discount_tiers
risk_unitsunified_modeloan_margin_tierszleverage/user_currency_configleverage/user_currency_settingg*@)r   r   portfolio_calculatorr  r  )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   r	  funding_accounts
auto_repayr   r   loans/{loan_id}loans/{loan_id}/repaymentr   loan_records/{loan_record_id}r   zcross/accountszcross/account_bookcross/loanszcross/loans/{loan_id}cross/repaymentszcross/interest_records)zcross/transferablezcross/estimate_ratezcross/borrowablezuni/estimate_rate	uni/loanszuni/loan_recordsuni/interest_recordszuni/borrowable)r  r   merged_loansr  r  r  r  )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}/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}/feer   {settle}/price_orders {settle}/price_orders/{order_id})${settle}/positions/{contract}/margin&{settle}/positions/{contract}/leverage({settle}/positions/{contract}/risk_limitz{settle}/dual_modez.{settle}/dual_comp/positions/{contract}/marginz0{settle}/dual_comp/positions/{contract}/leveragez2{settle}/dual_comp/positions/{contract}/risk_limitr$  z{settle}/batch_ordersz{settle}/countdown_cancel_allz{settle}/batch_cancel_ordersr)  )r$  r%  r)  r*  )r   r!  r"  r#  r$  r%  r&  r'  r(  z{settle}/settlementsr)  r*  )r+  r,  r-  r$  r)  )r   r   r   )
my_settlementsr   r	  	positionszpositions/{contract}position_closer  r  r  mmp)r  r  r1  z	mmp/reset)r  r  )r   r   	uni/lendszuni/lend_recordszuni/interests/{currency}r  zuni/interest_status/{currency}r2  zuni/interest_reinvest)r   r   r   r  collateral/orderszcollateral/orders/{order_id}zcollateral/repay_recordscollateral/collateralszcollateral/total_amountzcollateral/ltvzcollateral/currenciesmulti_collateral/ordersz"multi_collateral/orders/{order_id}multi_collateral/repaymulti_collateral/mortgagezmulti_collateral/currency_quotazmulti_collateral/currencieszmulti_collateral/ltvzmulti_collateral/fixed_ratezmulti_collateral/current_rate)r3  zcollateral/repayr4  r5  r6  r7  )detail
rate_limit
stp_groupsstp_groups/{stp_id}/userszstp_groups/debit_fee)r:  r;  r;  )zagency/transaction_historyzagency/commission_history)rU   rM   rV   rW   rQ   rO   r   rN   rP   rR   rT   rZ   rY   rX   
timeframes10s1m5m15m30m1h2h4h8h1d7d)r=  r>  r?  r@  rA  rB  rC  rD  rE  rF  rG  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ccxtrR   r   
expirationiQ BTCBRC20BTCBRCETHERC20TRXTRC20HECOHTHRC20BSCBEP20SOLPOLYGONPOLMATICOPOPETHOPTIMISM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AURORA	AURORAEVMKONKONET	GATECHAINGTEVMKUSAMAKSMSMOKCOKTPOLKADOTDOTSMLUNALUNCgtciocpocfok)rZ  IOCPOPOCFOKcross_marginrN   rP   )fundingrQ   rO   r  crossisolatedrg   rh   rN   rP   ri   rR   settlementCurrenciesusdtbtc)timeDifferenceadjustForTimeDifferencesandboxModeunifiedAccountru   !createMarketBuyOrderRequiresPricenetworksnetworksByIdtimeInForceaccountsByTyperg   rh   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   ru   rv   r   r   r   fetchOrdersr   r   extendsdefault)lastmarkindex)r  r  
   )r  r  r  )r  r  r    )r  ru   rv   r   r   r   r   forDerivatives)linearinverse)r  rQ   r  rg   rh   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.0z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)tradingrg   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	NO_CHANGE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)exactbroad)fees
exceptions)deep_extendsuperr?   describer<   parse_numberr3   r2   r-   r.   r/   r1   r5   r:   r;   r6   r4   r8   r7   r0   )self	__class__s    C/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/gate.pyr{  zgate.describe    s!   dD : < Y?
&Y?
IY?
 $Y?
 	Y?

 tY?
 Y?
 4Y?
 iF) #A#A"@$B >#A(F >	 (F"@#A"@$B >#A'E#A"@ >#A > : $M$M#L $M$M#L  @ #W/Y?
p  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$ 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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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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l )-)-*/$( $$('+#!&#'  GdqY?
z  -q  *+56./>?'(*+&',-$%
  ./>?,-01;<23BC 
 (! # 23=>34/0566701562378CD349:  $ 23=>34/0560123 
! +,+,)*45+,67*+'(?@,-78&'  " ./9: aVv ,.$%!
 :1#$ -q )1  '  4Q	 
 +A  .q  3C  :3  ;C  @  ,Q  "1  ,S  ,Q  4Q   #A! & *-58:=-.	!'8 -069;>AD	  -0;>;>=@	! @  @#!$, )0,3*1,3%,,307-47>*1,318=D>E " -4%-4;>E	! +G / < $%)*(),-+,&'12)*,-78  -067&)3:4;25,/! '.18,37>	# 0"; D & *G  /  )'	 
 +G  $W  .w  8  +G  <W  )'  -g  1'  *7  4W   /! " 5g# $ 3:3:0718)0074;.53 8 +2%,,39@+207)0! 07=D"
 .w#S,^ +,./&'12	  '(./!# / 3Q  1!  <Q	 
 Fq  .q  8  9!  1!  ;A  6q  21  8  +A  8   4Q! " ?# ( EFFGHI23NOPQRS/258=@<?58! 9!  07:A5<@G	#K+ \ 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#' 4 /69@)0078?4;>E  (! 4W  ("!* / :G  7  5g	 
 6w  -g  4W  6w  A'  5g  8  >w  :7  3G  :7   <W! & 29076=7>6=9@!'< '.*1*19@4;  +29@!
 8# " :A9@ _
Uqn{Y?
X YY?
v  !z!v! ! 
	!
 ! y! z! ~! y! ,! =! z! i! y! !  '!!" y#!$ '-+!wY?
d "$eY?
l #VmY?
r "#+0$"& %  6:;5;X; 5; U	;
 5; U; D; T; 5; U; 5; u; U; '; ;  5!;" X#;$ F%;& h';( I);* 5+;, e-;. 5/;0 51;2 k3;4 Z5;6 F7;8 F9;> Z?;@ ZA;B 5C;D 6E;F 5G;H 5I;L FM;N FO;R hS;T FU;V 5W;X 5Y;` 5a;b Fc;d Fe;f kg;j 7k;l  m;n go;p 5q;r s;t Fu;z T! !      &"&$2+ (%(( *'(# #.% #.%EgsY?
B #&*(,,0,0)-+/6:#'#'"&#(	( #($)#'/3$)+/26)$. r% '+!%$(%'*/& ',#'$)*.	# '+#'$)!$*/( $(&*#'$)!$%'$(,0*/	*  #u=~ y  &&+$($(%)-$ r% ',%)&
 %e( ',%)!%*  #3#> "#3 "#3 	 "#3 "#3 	OoCY?
b YcY?
h "&$"&!..w7!..w7 "..s3T5F5Fw5OP!..u5t7H7H7ST!..s3T5F5Fy5QR!..s3T5F5Fy5QR!..v68I8I)8TU!..t4d6G6G	6RS!..t4d6G6G	6RS!..u5t7H7H7ST!..u5t7H7H7ST!..v68I8I)8TU!..v68I8I)8TU!..v68I8I)8TU!..v68I8I)8TU!..w79J9J99UV!..w79J9J99UV!..w79J9J99UV!..w79J9J99UV#"( "..s3T5F5Fw5OP!..u5t7H7H7ST!..s3T5F5Fy5QR!..s3T5F5Fy5QR!..v68I8I)8TU!..t4d6G6G	6RS!..t4d6G6G	6RS!..u5t7H7H7ST!..u5t7H7H7ST!..v68I8I)8TU!..v68I8I)8TU!..v68I8I)8TU!..v68I8I)8TU!..w79J9J99UV!..w79J9J99UV!..w79J9J99UV!..w79J9J99UV#"+(/b "&%"&!..u5!..x8 "..s3T5F5Fx5PQ!..u5t7H7H7TU!..s3T5F5Fz5RS!..s3T5F5Fz5RS!..v68I8I*8UV!..t4d6G6G
6ST!..t4d6G6G
6ST!..u5t7H7H7TU!..u5t7H7H7TU!..v68I8I*8UV!..v68I8I*8UV!..v68I8I*8UV!..v68I8I*8UV!..w79J9J:9VW!..w79J9J:9VW!..w79J9J:9VW!..w79J9J:9VW#"( "..s3T5F5Fy5QR!..u5t7H7H7ST!..s3T5F5Fy5QR!..s3T5F5Fy5QR!..v68I8I)8TU!..t4d6G6G	6RS!..t4d6G6G	6RS!..u5t7H7H7ST!..u5t7H7H7ST!..v68I8I)8TU!..v68I8I)8TU!..v68I8I)8TU!..v68I8I)8TU!..w79J9J99UV!..w79J9J99UV!..w79J9J99UV!..w79J9J99UV#")'.c`Fa):a&
a '
a +J	a
 -.?a ":a +Ja %ja )*a  a ,-@a *+>a "#6a #$7a  !1a  ()<!a" ./B#a$ &':%a& %&6'a(  !1)a* ,]+a, )*:-a. //a0 -m1a2 1-3a4 12C5a6 (7a8 2=9a: ';a<  1=a> ,]?a@ ,-AAaB *=CaD 5mEaF (GaH '	IaJ ,YKaL +,DMaN &}OaP *=QaR #LSaT &|UaV *<WaX )*;YaZ +L[a\ 01B]a^ (_a` &|aab (cad %meaf ,]gah &}iaj $]kal  man %moap .|qar &|sat ():uav ),wax +Myaz '(9{a| %&7}a~ *=a@ ))AaB *=CaD -.?EaF ,\GaH (IaJ 'KaL &}MaN %mOaP ,]QaR .}SaT (UaV %lWaX &}YaZ .}[a\ *=]a^ )-_a` ),aab %lcad %leaf -lgah *<iaj *+Ckal *6-: 4$8 4/<*44@6B(2*4AaD GdiY?
 Y Y	    enablec                 J    t         t        |   |       || j                  d<   y )Nr  )rz  r?   set_sandbox_moderR   )r}  r  r~  s     r  r  zgate.set_sandbox_mode<  s     dD*62&,]#r  c                 4   | j                  | j                  d      }|G	 | j                  |      }| j                  |di       }| j	                  |d      dk(  | j                  d<   | j                  d   S # t
        $ r}d| j                  d<   Y d}~,d}~ww xY w)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.io/docs/developers/apiv4/#get-account-detail

        :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_boolrR   privateAccountGetDetail	safe_dictsafe_integer	Exception)r}  paramsr  responseresultes         r  load_unified_statuszgate.load_unified_status@  s     6FG!7  77?%<151B1B661RVW1W-. ||,--  716-.7s   AA5 5	B>BBc                 $    | j                  |      S N)privateUnifiedPutUnifiedMode)r}  r  s     r  upgrade_unified_trade_accountz"gate.upgrade_unified_trade_accounta  s    0088r  c                 H    | j                  |      }| j                  |d      S )ab  
        fetches the current integer timestamp in milliseconds from the exchange server

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

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        server_time)publicSpotGetTimer  r}  r  r  s      r  
fetch_timezgate.fetch_timed  s)     ))&1   =99r  symbolc                    d}|}|j                  d      }|j                  d      }|j                  d      }d }| j                  |d      }|j                  d      dkD  r| j                  |d      }n| j                  |d      }|dd	 }| j                  |d      }	| j                  |d
      }
| j                  |      }| j	                  |      }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| j                  d       |||
d!k(  rd"nd#| j                  |	      | j                  d       d d$d d d%d d d%d d d%d&d d'	S )(NUSDT-/_r   r   r        rB   20r  :r  quotesettlebaseIdquoteIdsettleIdactiveFtyperi   r  r  rQ   rg   rh   TrO   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  r  r  optionParts
symbolBasemarketIdBaser  r  r  r  datetime	timestamps                r  create_expired_option_marketz!gate.create_expired_option_marketu  s   ll3'\\#&
||C(!!+q1;;sb ##J2D##L!4DAa[F!!+q1%%k15
++F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&%/3%6&U''/++C0  
  
   U+
 +	
r  NmarketIdmarket	delimiter
marketTypec                     |d uxr* |j                  d      dkD  xs |j                  d      dkD  }|r|| j                  vr| j                  |      S t        t        |   ||||      S )Nz-Cr  z-P)r  markets_by_idr  rz  r?   safe_market)r}  r  r  r  r  isOptionr~  s         r  r  zgate.safe_market  sn    D(hd0Cb0H/ghmm\`NadfNfX););;44X>>T4,Xvy*UUr  c                    | j                   d   r| j                          | j                  | j                   dd      }| j                  |      | j	                  |      g}|s$| j                  |      g}| j                  ||      }|}| j                  |dg       }| j                  |dg       }| j                  |dg       }| j                  ||      }	| j                  |	|      S )aj  
        retrieves data on all markets for gate

        https://www.gate.io/docs/developers/apiv4/en/#list-all-currency-pairs-supported                                     # spot
        https://www.gate.io/docs/developers/apiv4/en/#list-all-supported-currency-pairs-supported-in-margin-trading         # margin
        https://www.gate.io/docs/developers/apiv4/en/#list-all-futures-contracts                                            # swap
        https://www.gate.io/docs/developers/apiv4/en/#list-all-futures-contracts-2                                          # future
        https://www.gate.io/docs/developers/apiv4/en/#list-all-the-contracts-with-specified-underlying-and-expiration-time  # option

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        r  r  Fr   r   r  )rR   load_time_differencer  fetch_contract_marketsfetch_option_marketsfetch_spot_marketsarray_concat
safe_value)
r}  r  r  rawPromisesmainnetOnlypromisesspotMarketscontractMarketsoptionMarketsmarketss
             r  fetch_marketszgate.fetch_markets  s     <<12%%'nnT\\=%H''/%%f-
 226:;K++KEKooh26//(Ar:!R8##KA  -88r  c                    | j                  |      }| j                  |      }||g\  }}| j                  |d      }g }t        dt	        |            D ]*  }||   }	| j                  |	d      }
| j                  ||
      }| j                  ||	      }|
j                  d      \  }}| j                  |      }| j                  |      }| j                  |d      }| j                  |d|      }| j                  | j                  | j                  |d                  }| j                  |d      }| j                  |d      }|d u}|j                  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 | j                  t        j                  |d            | j                  t        j                  |d            d d d d d || j                  | j                  | j                  |d                  d| j                  d       | j                  |dd!      d"| j                  |	d#|      d d"d d d"| j                  |d$      |r| j                  |d%      nd d"d&d |d'       - |S )(NrB   r   r  r   maker_fee_rateamount_precisiontrade_statusr  r  r  r  r  r  r  r  r  r  rQ   TrO   rg   Frh   ri   r  tradabler  r  100r  r  r  r   r  min_base_amountmin_quote_amountmax_quote_amountr  r  r  r  r  r  r  r  r  r  r  r  r  r  createdr  )publicMarginGetCurrencyPairspublicSpotGetCurrencyPairsindex_byrangelenr  r  ry  r  safe_currency_coder|  parse_precisionsafe_numberappendr=   
string_div)r}  r  marginPromisespotMarketsPromisemarginResponsespotMarketsResponsemarginMarketsr  i
spotMarketrB   marginMarketr  r  r  r  r  takerPercentmakerPercentamountPrecisiontradeStatusr  rO   s                          r  r  zgate.fetch_spot_markets  sS   99&A!<<VD/<>P.Q++nd;D q#123 A	A,Q/J!!*d3B??="=L%%lJ?F hhsmOFG**62D++G4E++FE:L++F4DlSL"//0D0DTEUEUV\^pEq0rsO**6>BK''
;HT)F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S**7+=+=lE+RS $"&"-!..t/C/CDDTDTU[]hDi/jk  $005#//
AF!
  $//
<M_#
  $#
  $//8JKOUt//8JK[_$  e3 3A	D r  c                 b   g }| j                  dd      }| j                  dd      }t        dt        |            D ]l  }||   }d|i}| j                  | j	                  ||            }t        dt        |            D ](  }	| j                  ||	   |      }
|j                  |
       * n t        dt        |            D ]l  }||   }d|i}| j                  | j	                  ||            }t        dt        |            D ](  }	| j                  ||	   |      }
|j                  |
       * n |S )Nrg   r   rh   r   r  )get_settlement_currenciesr  r  publicFuturesGetSettleContractsextendparse_contract_marketr   publicDeliveryGetSettleContracts)r}  r  r  swapSettlementCurrenciesfutureSettlementCurrenciescr  requestr  r  parsedMarkets              r  r  zgate.fetch_contract_marketsE  sN   #'#A#A&.#Y %)%C%CHn%]"q#678 	,A/2H(G ;;DKKQW<XYH1c(m, ,#99(1+xPl+,	, q#89: 	,A1!4H(G <<T[[RX=YZH1c(m, ,#99(1+xPl+,	, r  c                    | j                  |d      }|j                  d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |      }| j                  |      }	| j                  |      }
| j                  |d      }d}d}|'|d	z   |	z   d
z   |
z   dz   | j	                  |d      z   }d}n|d	z   |	z   d
z   |
z   }| j                  |d      }| j                  |d      }t        j                  d|      }t        j                  d|      }t        j                  ||      }t        j                  ||      }| j                  |d      }| j                  |d|      }|	|
k(  }| j                  |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$|| | j                  t        j                  |d%            | j                  t        j                  |d%            | j                  |      || j                  |      d d | j                  d      | j                  |d&      d'| j                  |d(      | j                  |d)      d*| j                  |d+      | j                  |d,      d*| j                  |      | j                  |      d*d d d*d-d |d.S )/NrC   r  r   r   r  expire_time rg   r  r  r  rh   order_price_deviate
mark_pricer  taker_fee_rater  quanto_multiplierr  rB   r  r  r  r  r  r  r  r  rQ   FrO   ri   r  Tr  r  r  order_price_roundr  leverage_minleverage_maxr  order_size_minorder_size_maxr  r  )r  r  r  safe_timestampyymmddr=   
string_sub
string_add
string_mulr|  r  iso8601r  )r}  r  r  rB   partsr  r  dater  r  r  r  r  r  priceDeviate	markPriceminMultipliermaxMultiplierminPricemaxPricer  r   isLinearr  s                           r  r  zgate.parse_contract_market]  s   r ff-!!%+""5!,q)&&v.''0((2$$V];
CZ%'#-6<t{{6SU?VVF!JCZ%'#-6F''0EF$$V\:	**3=**3=%%mY?%%mY?''0@A''0@,OF?''0C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
$ $|&&w'9'9,'NO&&w'9'9,'NO --l;"ll62++C0))&2EF  ++FNC++FNC
  ++F4DE++F4DE
  ,,X6,,X6
  $ c2
 2	
r  c                 h   g }| j                         }t        dt        |            D ]  }||   }| j                  i |      }||d<   | j	                  |      }t        dt        |            D ]  }||   }	| j                  |	d      }
|j                  d      }| j                  |d      }| j                  |d      }| j                  |      }| j                  |      }|dz   |z   }| j                  |	d      }| j                  |	d      }| j                  |	d	      }|rd
nd}|rdnd}|dz   |z   dz   | j                  |      z   dz   |z   dz   |z   }| j                  |	d      }| j                  |	d      }t        j                  d|      }t        j                  d|      }t        j                  ||      }t        j                  ||      }| j                  |	d      }| j                  |	d|      }|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 | j!                  t        j"                  |d(            | j!                  t        j"                  |d(            | j!                  d      || j%                  |      ||| j!                  d      | j'                  |	d)      d*d d d+| j'                  |	d,      | j'                  |	d-      d+| j!                  |      | j!                  |      d+d d d+d.| j                  |	d/      |	d0        	 |S )1Nr   
underlyingrC   r  r   r  expiration_timestrike_priceis_callr  Pr  r   r  r  r  r  r  r  r  rB   r  r  r  r  r  r  r  r  ri   rQ   FrO   rg   rh   Tr  r  r  r  r  r  r  r  r  r  create_timer  )fetch_option_underlyingsr  r  r  publicOptionsGetContractsr  r  r  r  r  r  r=   r  r  r  r  r|  r  r  r  )r}  r  r  r   r  r*  queryr  jr  rB   r   r  r  r  r  r  r  r  isCalloptionLetterr  r"  r#  r$  r%  r&  r'  r  r   s                                 r  r  zgate.fetch_option_markets  s   335q#k*+ t	A$QJKKF+E",E,55e<HN 1c(m, I!!%%ff5"((-))%3**5!4..v6//8e+,,V5FG))&.A;&,s#'-V5
#-3dkk&6IICORXX[^^amm#//8MN ,,V\B	 ' 2 23 E ' 2 23 E"--mYG"--mYG#//8HI#//8H,W 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$  %!..w/A/A,PU/VW!..w/A/A,PU/VW$($5$5c$:$&*ll6&:$","&"3"3C"8!%!1!1&:M!N" $(#'%
 $(#3#3F<L#M#'#3#3F<L#M#
 $(#4#4X#>#'#4#4X#>"
 $(#'!$  $226=I"c2 2/IWt	j r  c                     | j                         }g }t        dt        |            D ]-  }||   }| j                  |d      }||j	                  |       / |S )Nr   rC   )publicOptionsGetUnderlyingsr  r  r  r  )r}  underlyingsResponser   r  r*  rC   s         r  r0  zgate.fetch_option_underlyings  sl    ">>@ q#123 	)A,Q/J##J7D""4(		)
 r  c                     i }|*|d   r|d   |d<   |d   s|d   |d<   ||gS |d   |d<   ||gS |dk(  }|dk(  }|s|r0|rd	nd
}| j                  |d|      }| j                  |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
        r  rB   ri   r  r  currency_pairrg   rh   r  r  )safe_string_loweromit)	r}  r  r  r  r  rg   rh   defaultSettler  s	            r  prepare_requestzgate.prepare_request  s     j!&,Tl
#h'(.z(:GH%    ,2$<(    6>DX%Fv*.E//-P684$*!  r  Fc                     | j                  ||      \  }}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
        zL spotOrderPrepareRequest() requires a market argument for non-trigger ordersrY   rB   r:  )get_margin_moder2   rB   r}  r  r  r  r  r2  r  s          r  spot_order_prepare_requestzgate.spot_order_prepare_request  sl     !00&A
E~'  3A  )A  B  B!+GI'-d|GO$r  c                 l    | j                  ||      \  }}d|i}||r|d   |d<   ||gS |d   |d<   ||gS )r@  rY   rB   r  r:  )rA  rB  s          r   multi_order_spot_prepare_requestz%gate.multi_order_spot_prepare_request  sh     !00&A
Ez
 $*4L!  ,2$<(r  c                 H   | j                  | j                  ddd      }| j                  |dd|      }| j                  |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}| j                  |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  rQ   rY   r  r  r  rO   r  normalzA getMarginMode() does not support trigger orders for cross marginFgetMarginModer  rW   )safe_string_lower_2rR   r<  r3   rB   handle_option_and_params)r}  r  r  rG  r  isUnifiedAccounts         r  rA  zgate.get_margin_mode  s     !44T\\CVXdflm--flIO`a
6L)#<= 'J:%!J2JV#%
^+ +n!noo #'#@#@Zj#k &"JF##r  c                     | j                  | j                  |i       }| j                  ||i       }|dk(  rdgndg}| j                  |d|      S )Nrg   r  r  r  )r  rR   )r}  r  methodrR   fetchMarketsContractOptionsr=  s         r  r  zgate.get_settlement_currencies  sR    //$,,b9&*oogvr&J#%)V^5':<RTabbr  c                 f   | j                  | j                  d      }|y| j                  d      r| j                          | j	                  |      }| j                  |d      }i }t        dt        |            D ]  }||   }| j                  |d      }|j                  d      }	| j                  |	d      }
|j                  d      r|n|
}| j                  |dd      }| j                  |d	d      }| j                  |d
d      }| j                  d      }| j                  |      }d}|j                  d      s3|j                  d      s"|j                  d      s|j                  d      r|dd }||v rd}|rdnd}| j                  |d|      }| j                  ||      }|||ddddddd| | | d|d	}||vr||j                         |||di g d||<   |||   d   |<   | j!                  ||   dg       }|j#                  |       |||   d<   | j%                  ||         ||<    |S )a)  
        fetches all available currencies on an exchange

        https://www.gate.io/docs/developers/apiv4/en/#list-all-currencies-details

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        	apiBackupNFcurrencyr   r  _OLDwithdraw_disableddeposit_disabledtrade_disabledz0.00013S3L5S5LT	leveragedcryptochainr  )depositr   )	r  rB   networkr  r  r_  r   r   r  )rB   lowerCaseIdcoder  r  r  r  r  r  r  )r  rL   check_required_credentialsr  publicSpotGetCurrenciesr  r  r  r  r  endswithr  r|  r  network_id_to_codelower	safe_listr  safe_currency_structure)r}  r  rQ  r  indexedCurrenciesr  r  entry
currencyIdr   	partFirstcurrencyNamewithdrawDisableddepositDisabledtradeDisabledr  rb  isLeveragedTokenrealCurrencyIdr  	networkIdnetworkCodenetworkEntryr  s                           r  fetch_currencieszgate.fetch_currencies  s    OODII{;	 **51$$&//7 !MM(J?q#h-( :	FAQKE))%<J$$S)E((2I)3)<)<V)D:)L#~~e5H%P"nnU4FNO NN52BEJM))(3I**<8D$""4(J,?,?,EI\I\]aIbfpfyfyz~f!+Ab!1!%66'+$"2;D((DI11)TBK&  $# 
  $#!	 ,+.. 00&%L* FN&#/#5#5#7  !*" "	 t 5AF4L$[1>>&,;DKK#'F4L 77tEF4Lu:	Fv r  c                    | j                          | j                  |      }|d   st        | j                  dz         | j	                  |d|      \  }}| j                  | j                  ||            }| j                  |      S )ak  
        fetch the current funding rate

        https://www.gate.io/docs/developers/apiv4/en/#get-a-single-contract

        :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>`
        rg   z0 fetchFundingRate() supports swap contracts onlyN)load_marketsr  r4   rB   r>  'publicFuturesGetSettleContractsContractr  parse_funding_rate)r}  r  r  r  r  r2  r  s          r  fetch_funding_ratezgate.fetch_funding_rateW  s     	V$f~DGG&XXYY--fdFC??GUZ@[\Z &&x00r  symbolsc                 $   | j                          | j                  |      }d}|#| j                  |d      }| j                  |      }| j	                  |d|      \  }}| j                  | j                  ||            }| j                  ||      S )a  
        fetch the funding rate for multiple markets

        https://www.gate.io/docs/developers/apiv4/en/#list-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   rg   )ry  market_symbolsr  r  r>  r  r  parse_funding_rates)r}  r}  r  r  firstSymbolr  r2  r  s           r  fetch_funding_rateszgate.fetch_funding_rates  s     	%%g.**7A6K[[-F--fffE77GU8STZ '''::r  c                     | j                  |d      }| j                  ||dd      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }	| j                  |d	      }
t	        j
                  d
| j                  |d            }i d|d|d|d|d|dd dd dd d|d|	d| j                  |	      d|
dd dd dd dd dd d| j                  |      iS )NrC   r  rg   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  r  r=   r  r  parse_funding_interval)r}  r  r  r  r  r#  r  r  r  fundingTimefundingRateIndicativefundingIntervals               r  r{  zgate.parse_funding_rate  s   V ##Hf5!!(FC@$$X|<	%%h>
''/B&&x@))(4HI $ 0 0;T U!,,VT5E5EhPb5cd
H
f
 
 *	

 L
 #D
 
 
 ;
 
 t||K8
 4
 #D
 "4
 "4
  '!
" &t#
$ 33OD%
 	
r  c                 8    dddddd}| j                  |||      S )NrB  rD  rE  16h24h)360000014400000288000005760000086400000r  )r}  r  	intervalss      r  r  zgate.parse_funding_interval  s/    
	 	8X>>r  rb  c                    | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |d      }| j                  |d      }| j                  |      }i }t        dt        |            D ]]  }	||	   }
| j                  |
d      }|r| j                  |
d      }| j                  |
d      }| j                  |
d      }|
||||d	||<   _ |S )
NrR  rB   multichain_addressesr   obtain_failedr^  address
payment_id)r  rb  rR  r  tag)
ry  rR  privateWalletGetDepositAddressr  r  r  r  r  r  r  )r}  rb  r  rR  r  r  	addressesrl  r  r  rk  obtainFailedr`  r  r  s                  r  fetch_network_deposit_addressz"gate.fetch_network_deposit_address(  s   ==&
 66t{{7F7STOOH.DE	%%h
;
&&z2q#i.) 	AaLE  ,,UODL&&ug6G&&ui8G""5,7C "F7O#	0 r  c                 `   | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |dg       }| j                  |d      }| j                  ||      }| j                  ||d   gdd|d   i      }| j                  |d      S )az  
        fetch a dictionary of addresses for a currency, indexed by network
        :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
        rR  rB   r  rb  Fr`  )	ry  rR  r  r  r  r  safe_currencyparse_deposit_addressesr  )	r}  rb  r  rR  r  r  chainsrl  parseds	            r  "fetch_deposit_addresses_by_networkz'gate.fetch_deposit_addresses_by_networkM  s     	==&
 66t{{7F7ST+A2F%%h
;
%%j(;--fx7G6H%R
  }}VY//r  c                     | j                          d}| j                  |      \  }}| j                  ||      }| j                  |||      }||   S )a  
        fetch the deposit address for a currency associated with self account

        https://www.gate.io/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.io but used by ccxt to filter the response)
        :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
        N)ry  handle_network_code_and_paramsr  )select_network_code_from_unified_networks)r}  rb  r  ru  chainsIndexedByIdselectedNetworkIds         r  fetch_deposit_addresszgate.fetch_deposit_addressb  s`     	"AA&IV CCD&Q JJ4Q\^op !233r  c           
          | j                  |d      }| j                  |       || j                  |d      || j                  |d      | j                  | j                  |d            dS )Nr  rb  r  r^  )r  rR  r  r  r`  )r  check_addressrf  )r}  depositAddressrR  r  s       r  parse_deposit_addresszgate.parse_deposit_addresst  sp     "">9=7#"((6:##NLA..t/?/?PW/XY
 	
r  c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  ||      S )af  
        fetch the trading fees for a market

        https://www.gate.io/docs/developers/apiv4/en/#retrieve-personal-trading-fee

        :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>`
        r:  rB   )ry  r  privateWalletGetFeer  parse_trading_feer}  r  r  r  r  r  s         r  fetch_trading_feezgate.fetch_trading_fee  s`     	V$VD\
 ++DKK,HI %%h77r  c                 f    | j                          | j                  |      }| j                  |      S )af  
        fetch the trading fees for multiple markets

        https://www.gate.io/docs/developers/apiv4/en/#retrieve-personal-trading-fee

        :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
        )ry  r  parse_trading_feesr  s      r  fetch_trading_feeszgate.fetch_trading_fees  s3     	++F3 &&x00r  c                     i }t        dt        | j                              D ]7  }| j                  |   }| j                  |      }| j	                  ||      ||<   9 |S Nr   )r  r  r}  r  r  )r}  r  r  r  r  r  s         r  r  zgate.parse_trading_fees  s`    q#dll+, 	FA\\!_F[[(F!33HfEF6N	F r  c                     | j                  |d      }|rdnd}|rdnd}| j                  |d      }|rdn|}|rdn|}|| j                  |d	      | j                  ||      | j                  ||      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_fee  s     __T=9
",+",+??6:6*2&*2&&&vx8%%dH5%%dH5
 	
r  codesc                     | j                          | j                  |      }i }i }t        dt        |            D ]  }i }||   }| j	                  |d      }| j                  |      }	|| j                  |	|      sB| j                  |d      }
|
| j                  |d      }nOt        |
j                               }t        dt        |            D ]  }||   }| j                  |
|         ||<     |d|d||	<    |S )a  
 @deprecated
        please use fetchDepositWithdrawFees instead

        https://www.gate.io/docs/developers/apiv4/en/#retrieve-withdrawal-status

        :param str[]|None codes: list of unified currency codes
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a list of `fee structures <https://docs.ccxt.com/#/?id=fee-structure>`
        r   rR  Nwithdraw_fix_on_chainswithdraw_fix)r   r_  r  )ry  privateWalletGetWithdrawStatusr  r  r  r  in_arrayr  r  listkeysr|  )r}  r  r  r  r  withdrawFeesr  rk  rl  rb  withdrawFixOnChains	chainKeysr3  chainKeys                 r  fetch_transaction_feeszgate.fetch_transaction_fees  s(    	66v>$ q#h-( 	ALQKE))%<J**:6D!4==u+E"&//%9Q"R"*#//~F !4!9!9!;<	q#i.1 ^A(|H-1->->?RS[?\-]L*^ )F4L	( r  c                 j    | j                          | j                  |      }| j                  ||d      S )aw  
        fetch deposit and withdraw fees

        https://www.gate.io/docs/developers/apiv4/en/#retrieve-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>`
        rR  )ry  r  parse_deposit_withdraw_fees)r}  r  r  r  s       r  fetch_deposit_withdraw_feesz gate.fetch_deposit_withdraw_fees	  s7     	66v>( //%LLr  rR  c                    | j                  |d      }|| j                  |d      dd| j                  |d      ddi d}|}t        |j                               }t	        dt        |            D ]L  }||   }| j                  || j                  |d            }| j                  ||         ddd d dd	|d
   |<   N |S )Nr  r  F)r   r  r_  )r  r   r_  r  r   rR  )r   r_  r  )	r  r  r  r  r  r  rf  r  r|  )	r}  r   rR  r  r  r  r  r  ru  s	            r  parse_deposit_withdraw_feezgate.parse_deposit_withdraw_fee@	  s    $ #ooc3KL''^<#
 ''Y7# 
 *05578I1c)n- $Q<"55h@P@PQTV`@ab  $001DX1NO&+!
  $&* 	3z";/ r  sincer  c                    | j                          d}|| j                  |      }|d   }| j                  d||      \  }}| j                  |||      \  }}	d|d<   || j	                  |dz        |d<   |||d<   d}
|d	k(  r"| j                  | j                  ||	            }
n?|d
k(  r"| j                  | j                  ||	            }
nt        | j                  dz         | j                  |
|||      S )a  
        fetch the history of funding payments paid and received on self account

        https://www.gate.io/docs/developers/apiv4/en/#query-account-book-2
        https://www.gate.io/docs/developers/apiv4/en/#query-account-book-3

        :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  rg   rh   z= fetchFundingHistory() only support swap & future market type)ry  r  handle_market_type_and_paramsr>  parse_to_int"privateFuturesGetSettleAccountBookr  #privateDeliveryGetSettleAccountBookr9   rB   parse_funding_histories)r}  r  r  r  r  r  r  r2  r  requestParamsr  s              r  fetch_funding_historyzgate.fetch_funding_historyp	  s    	[[(FH%F889NPVX^_e!%!5!5fdE!J "//=GFO$GG6>>>t{{7Ta?bcHX??GUb@cdHtww)hhii ++HfeUKKr  c                     g }t        dt        |            D ])  }||   }| j                  |      }|j                  |       + | j	                  |d      }	| j                  |	|||      S )Nr   r  )r  r  parse_funding_historyr  sort_byfilter_by_symbol_since_limit)
r}  r  r  r  r  r  r  rk  r  sorteds
             r  r  zgate.parse_funding_histories	  so    q#h-( 	#AQKE007GMM'"	# fk200NNr  c           
         | j                  |d      }| j                  |d      }| j                  ||dd      }|| j                  |d      | j                  |d      || j                  |      d | j	                  |d      dS )	Nr   textr  rg   r  r  change)r  r  rb  r  r  rB   r  )r  r  r  r  r  )r}  r  r  r  r  s        r  r  zgate.parse_funding_history	  s     ''f5	##D&1!!(FC@&&vx8$$VX6"Y/&&tX6
 	
r  c           	         | j                          | j                  |      }| j                  ||d   |      \  }}|||d<   d|d<   d}|d   s|d   r"| j                  | j	                  ||            }n|d   r"| j                  | j	                  ||            }nf|d	   r"| j                  | j	                  ||            }n?|d
   r"| j                  | j	                  ||            }nt        | j                  dz         | j                  |d      }|d   s|dz  }|d   rdnd}	|d   rdnd}
| j                  |d      }| j                  |||dd|	|
      }||d<   |S )a  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://www.gate.io/docs/developers/apiv4/en/#retrieve-order-book
        https://www.gate.io/docs/developers/apiv4/en/#futures-order-book
        https://www.gate.io/docs/developers/apiv4/en/#futures-order-book-2
        https://www.gate.io/docs/developers/apiv4/en/#options-order-book

        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        r  Nr  Twith_idrQ   rO   rg   rh   ri   z. fetchOrderBook() not support self market typecurrentr  r   pr   srB   bidsasksnonce)ry  r  r>  publicSpotGetOrderBookr  publicFuturesGetSettleOrderBook publicDeliveryGetSettleOrderBookpublicOptionsGetOrderBookr9   rB   r  parse_order_book)r}  r  r  r  r  r  r2  r  r  priceKey	amountKeyr  r  s                r  fetch_order_bookzgate.fetch_order_book	  s    	V$ --ffVnfM$GG!	&>VH-224;;w3NOHF^;;DKKQV<WXHH<<T[[RW=XYHH55dkk'56QRHtww)YYZZB %%h	:	f~!D(Iv1CAS	!!(D1&&xFFT\^ghwr  c                    | j                          | j                  |      }| j                  |d|      \  }}d}|d   s|d   r"| j                  | j	                  ||            }n|d   r"| j                  | j	                  ||            }n|d   r"| j                  | j	                  ||            }nj|d   rM|d   }|j                  d      }| j                  |d	      |d
<   | j                  | j	                  ||            }nt        | j                  dz         d}	|d   r/t        d	t        |            D ]  }
||
   }|d   |d   k(  s|}	 n n| j                  |d	      }	| j                  |	|      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.io/docs/developers/apiv4/en/#get-details-of-a-specifc-order
        https://www.gate.io/docs/developers/apiv4/en/#list-futures-tickers
        https://www.gate.io/docs/developers/apiv4/en/#list-futures-tickers-2
        https://www.gate.io/docs/developers/apiv4/en/#list-tickers-of-options-contracts

        :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>`
        NrQ   rO   rg   rh   ri   rB   r  r   r*  z+ fetchTicker() not support self market typerC   )ry  r  r>  publicSpotGetTickersr  publicFuturesGetSettleTickerspublicDeliveryGetSettleTickersr  r  publicOptionsGetTickersr9   rB   r  r  r  parse_ticker)r}  r  r  r  r  r2  r  r  r  tickerr  rk  s               r  fetch_tickerzgate.fetch_ticker1
  s}    	V$--fdFC&>VH-00We1LMHF^99$++gu:UVHH::4;;wPU;VWHHd|H"..-K$($4$4[!$DGL!33DKK4OPHtww)VVWW(1c(m,  =F4L0"F	 __Xq1F  00r  r  c           
         | j                  |g d      }d|v rdnd}| j                  ||d|      }| j                  |dd      }| j                  |g d      }| j                  |g d	      }| j                  |d
      }	| j                  |d      }
| j                  |dd      }| j                  |dd      }| j	                  |d      }| j                  |dd      }|dk(  rd}| j                  |dd      }|dk(  rd}| j                  |d      }| j                  i d|d|d| j                  |      d|	d|
d|d|d|d |d!d d"d d#|d|d$d d%d d&|d'd ||| j                  |d      | j                  |d(      |d)|      S )*N)r:  r  rC   r  r  rQ   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  r,  r*  r(  r)  r+  r-  r  r3  r4  r  s                    r  r  zgate.parse_tickerZ
  sI   J %%f.ST$0F$:Z
!!(FCD!!&&,?  )JK  )KL
3vy1&&vsK@	&&vsK@	%%fc2	''?PQ
J((AST%K%%f.AB
 !
f!
!
 Y/!
 D	!

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

        https://www.gate.io/docs/developers/apiv4/en/#get-details-of-a-specifc-order
        https://www.gate.io/docs/developers/apiv4/en/#list-futures-tickers
        https://www.gate.io/docs/developers/apiv4/en/#list-futures-tickers-2
        https://www.gate.io/docs/developers/apiv4/en/#list-tickers-of-options-contracts

        :param str[]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        r   Nr   utc0timezonerQ   rO   rg   rh   ri   r}  rB   r  r*  z fetchTickers() not support self market type, provide symbols or set params["defaultType"] to one from spot/margin/swap/future/option)ry  r  r  r  r  r>  r  r  r  r  check_required_argumentr  r  r9   rB   parse_tickers)r}  r}  r  firstr  r  r2  r  r  r  r  r  s               r  fetch_tickerszgate.fetch_tickers
  s    	%%g.  !,[['F88QWXe!%!5!5dD%!H$
6>TX-00Wm1TUHV^99$++g}:]^HX::4;;wP];^_HX(()Ld|H"..-K$($4$4[!$DGL!33DKK4WXHtww  *q   q  r  r!!(G44r  c                     | j                         }| j                  |dd      |d<   | j                  |d      |d<   | j                  |d      |d<   d|v r| j                  |d      |d<   |S )	Nfreezelockedused	availablefreetotalborroweddebt)rY   r6  r  )r}  rk  rY   s      r  parse_balance_helperzgate.parse_balance_helper
  su    ,,.,,UHhG**5+>++E7;"..ujAGFOr  c                    | j                          | j                          | j                  |d      }| j                  |d      }d}| j	                  |dd      \  }}| j                  dd|      \  }}| j                  d||      \  }}| j                  d|      \  }}	|| j                  |      }
|
d   |d<   d}|r#| j                  | j                  ||            }nG|dk(  r|dk(  r#| j                  | j                  ||	            }n|d	k(  r"| j                  | j                  ||	            }n|d
k(  r"| j                  | j                  ||	            }nt        | j                  dz         |dk(  r"| j!                  | j                  ||	            }n|dk(  r"| j#                  | j                  ||	            }nf|dk(  r"| j%                  | j                  ||	            }n?|dk(  r"| j'                  | j                  ||	            }nt        | j                  dz         |dk(  xs |dk(  xs |dk(  }|r|g}d|i}|d	k(  }|}d|v rjg }| j)                  |dg       }t+        |j-                               }t/        dt1        |            D ]"  }||   }||   }||d<   |j3                  |       $ |}t/        dt1        |            D ]  }||   }|r| j                  |d      }| j5                  |ddd	      }| j)                  |di       }| j)                  |di       }| j7                  | j                  |d            }| j7                  | j                  |d            }i }| j9                  |      ||<   | j9                  |      ||<   | j;                  |      ||<   | j7                  | j                  |d            }| j9                  |      ||<    |r|}|S | j;                  |      }|S )a  
        :param dict [params]: exchange specific parameters
        :param str [params.type]: spot, margin, swap or future, if not provided self.options['defaultType'] is used
        :param str [params.settle]: 'btc' or 'usdt' - settle currency for perpetual swap and future - default="usdt" for swap and "btc" for future
        :param str [params.marginMode]: 'cross' or 'isolated' - marginMode for margin trading if not provided self.options['defaultMarginMode'] is used
        :param str [params.symbol]: margin only - unified ccxt symbol
        :param boolean [params.unifiedAccount]: default False, set to True for fetching the unified account balance
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        r  Fr   r  NrB   r:  rQ   rO   r  z+ fetchBalance() not support self marginModer  rg   rh   ri   z, fetchBalance() not support self market typer  balancesr   rR  r  r  r  )ry  r  r  r<  rK  r  r>  rA  r  privateUnifiedGetAccountsr  privateSpotGetAccountsprivateMarginGetAccountsprivateMarginGetCrossAccountsr9   rB   privateMarginGetFundingAccountsprivateFuturesGetSettleAccounts privateDeliveryGetSettleAccountsprivateOptionsGetAccountsr  r  r  r  r  r  r  r  rH  safe_balance) r}  r  r  rL  r  r2  r  r  r  requestQueryr  r  r  r  r  dataflatBalancesrJ  r  r  rl  contentrk  r  symbolInnerr  r  baseCode	quoteCode	subResultrb  returnResults                                    r  fetch_balancezgate.fetch_balance
  s#    	  "!!&(368, #'#@#@Yi#j &88vVe!%!5!5dD%!H#'#7#7}#M 
L[[(F'-d|GO$55dkk'66RSHV^V#66t{{7L7YZx'88Wl9[\~-==dkk'S_>`a"477-Z#Z[[Y;;DKKQ]<^_HV^;;DKKQ]<^_HX<<T[[R^=_`HX55dkk'<6XYHtww)WWXXV^P)9Ptx?O zHD H
 )LtZ<H (D1c$i( -!!W
":.&0
###G,	-
  Dq#d)$ 	@AGE++E?C"..xsHMufb9w;2243C3CD*3UV 33D4D4DUJ4WX	"$	&*&?&?&E	(#'+'@'@'G	)$&*&7&7	&B{#..t/?/?z/RS#88?t	@  "*v 04/@/@/Hr  r>  c           	         | j                          | j                  |      }d}| j                  |dd      \  }}|r| j                  d|||||d      S |d   r| j	                  |||||      S | j                  |d      }i }	| j                  |d|      \  }	}| j                  | j                  ||      |	d<   |d	   rd
nd}
||
nt        ||
      }| j                  |d      }|&| j                  |dz        }| j                  |d      }|y| j                  |      }| j                  |dz        |	d<   |dz
  |z  }| j                  |	d   |      }| j                         }t        ||      }|t        ||      |	d<   n||	d<   n|||	d<   ||	d<   d}|d	   r||dk(  }|dk(  }|s|r |dz   |d   z   |	d	<   | j                  |d      }|d   r"| j                  | j!                  |	|            }nH|d   rC| j#                  | j!                  |	|            }n!| j%                  | j!                  |	|            }| j'                  |||||      S )a  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://www.gate.io/docs/developers/apiv4/en/#market-candlesticks       # spot
        https://www.gate.io/docs/developers/apiv4/en/#get-futures-candlesticks  # swap
        https://www.gate.io/docs/developers/apiv4/en/#market-candlesticks       # future
        https://www.gate.io/docs/developers/apiv4/en/#get-options-candlesticks  # option

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

        https://www.gate.io/docs/developers/apiv4/en/#funding-rate-history

        :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   r_  rE  rg   z7 fetchFundingRateHistory() supports swap contracts onlyr  r  r  r`  ra  r   r!  r)r  r  r  r  r  r  r  )r2   rB   ry  rK  rb  r  r4   r>  r  r  r<  !publicFuturesGetSettleFundingRater  r  r  r  r  r  r  r  r  )r}  r  r  r  r  r_  r  r  r`  r  ratesr  rk  r  r  s                  r  fetch_funding_rate_historyzgate.fetch_funding_rate_historyZ  s    >#DGG.e$eff88AZ\fg&::;TV\^cejlprxyyV$f~DGG&__``..vtVD$GG"//=GFO!!&'2YYvw/F --edl;GDM99$++gv:VW q#h-( 		AQKE++E37ILL #//s;& LL3 		 e[1009I5RWXXr  c           	         t        |t              rh| j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      gS | j                  |d      | j                  |d      | j                  |d	      | j                  |d
      | j                  |d      | j                  |d      gS )Nr      r     r     r!  ohlr  v)
isinstancer  r  r  )r}  ohlcvr  s      r  parse_ohlcvzgate.parse_ohlcv  s    2 eT"##E1-  *  *  *  *  *  ##E3/  ,  ,  ,  ,  , r  c                 Z   | j                          d}| j                  |dd      \  }}|r| j                  d||||      S | j                  |      }| j	                  |d|      \  }}| j                  |dd      }	|	*| j                  |dg      }| j                  |	dz        |d<   |t        |d      |d<   ||d	   r| j                  |dz        |d
<   d}
|d   dk(  s|d   dk(  r"| j                  | j                  ||            }
n|d   r"| j                  | j                  ||            }
ni|d   r"| j                  | j                  ||            }
nB|d   dk(  r"| j                  | j                  ||            }
nt        | j                  dz         | j!                  |
|||      S )aX  
        get the list of most recent trades for a particular symbol

        https://www.gate.io/docs/developers/apiv4/en/#retrieve-market-trades
        https://www.gate.io/docs/developers/apiv4/en/#futures-trading-history
        https://www.gate.io/docs/developers/apiv4/en/#futures-trading-history-2
        https://www.gate.io/docs/developers/apiv4/en/#options-trade-history

        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest trade to fetch
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        Fr   r_  Nra  r`  r  r  r  r  r  rQ   rO   rg   rh   ri   z, fetchTrades() not support self market type.)ry  rK  fetch_paginated_call_dynamicr  r>  safe_integer_2r<  r  r  publicSpotGetTradesr  publicFuturesGetSettleTradespublicDeliveryGetSettleTradespublicOptionsGetTradesr9   rB   parse_trades)r}  r  r  r  r  r_  r  r  r2  r`  r  s              r  fetch_tradeszgate.fetch_trades  s   " 	88PZ[&44]FESXZ`aaV$, --fdFC##FD':YYvy1F --edl;GDM"5$/GG&"4"//=GFO&>V#vf~'A//GU0KLHF^88We9TUHH99$++gu:UVHF^x'224;;w3NOHtww)WWXXR   65%@@r  rB   c                     |t        | j                  dz         | j                          | j                  |||d|i      }|S )a.  
        fetch all the trades made from a single order

        https://www.gate.io/docs/developers/apiv4/en/#list-personal-trading-history
        https://www.gate.io/docs/developers/apiv4/en/#list-personal-trading-history-2
        https://www.gate.io/docs/developers/apiv4/en/#list-personal-trading-history-3
        https://www.gate.io/docs/developers/apiv4/en/#list-personal-trading-history-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>`
        z. fetchOrderTrades() requires a symbol argumentorder_id)r2   rB   ry  fetch_my_trades)r}  rB   r  r  r  r  r  s          r  fetch_order_tradeszgate.fetch_order_trades(  sL      >#DGG.^$^__( ''uz2>NOr  c                 *   | j                          | j                          d}| j                  |dd      \  }}|r| j                  d||||      S d}d}i }|| j	                  |      nd}	| j                  |d      }
| j                  |dg      }| j                  d|	|      \  }}|dk(  xs |dk(  xs |dk(  }|r.| j                  |	||      \  }}|dk(  r7| j                  |d	      }n$|	|	d
   |d<   | j                  d|      \  }}||d<   |||d<   || j                  |dz        |d<   |
| j                  |
dz        |d<   d}|dk(  s|dk(  r"| j                  | j                  ||            }n|dk(  r"| j                  | j                  ||            }nf|dk(  r"| j                  | j                  ||            }n?|dk(  r"| j                  | j                  ||            }nt!        | j"                  dz         | j%                  ||	||      S )aP  
        Fetch personal trading history

        https://www.gate.io/docs/developers/apiv4/en/#list-personal-trading-history
        https://www.gate.io/docs/developers/apiv4/en/#list-personal-trading-history-2
        https://www.gate.io/docs/developers/apiv4/en/#list-personal-trading-history-3
        https://www.gate.io/docs/developers/apiv4/en/#list-personal-trading-history-4

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.marginMode]: 'cross' or 'isolated' - marginMode for margin trading if not provided self.options['defaultMarginMode'] is used
        :param str [params.type]: 'spot', 'swap', or 'future', if not provided self.options['defaultMarginMode'] is used
        :param int [params.until]: The latest timestamp, in ms, that fetched trades were made
        :param int [params.page]: *spot only* Page number
        :param str [params.order_id]: *spot only* Filter trades with specified order ID. symbol is also required if self field is present
        :param str [params.order]: *contract only* Futures order ID, return related data only if specified
        :param int [params.offset]: *contract only* list offset, starting from 0
        :param str [params.last_id]: *contract only* specify list staring point using the id of last record in previous list-query results
        :param int [params.count_total]: *contract only* whether to return total number matched, default to 0(no return)
        :param bool [params.unifiedAccount]: set to True for fetching trades in a unified account
        :param bool [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        Fr   r_  Nr`  rg   rh   ri   r  rB   r:  rY   r  r  r  ra  rQ   rO   z. fetchMyTrades() not support self market type.)ry  r  rK  r  r  r  r<  r  r>  rA  r  privateSpotGetMyTradesr  (privateFuturesGetSettleMyTradesTimerange privateDeliveryGetSettleMyTradesprivateOptionsGetMyTradesr9   rB   r  )r}  r  r  r  r  r_  r  r  r  r  r`  r  r  s                r  r  zgate.fetch_my_tradesQ  sS   4 	  "88R\]&44_feUZ\bcc
)/);V$$!!&'26G9-99/6SYZfFNO(8Odh>N"2264HOGVx6:6!+1$<(!%!5!5eV!DJ!+GI$GG"//=GFO --edl;GDM6>TX-224;;w3OPHV^DDT[[QXZ`EabHX<<T[[RX=YZHX55dkk'66RSHtww)YYZZB   65%@@r  tradec                 N   | j                  |dd      }d }| j                  |d      }|-t        j                  |d      }|dd }| j	                  |      }n| j                  |dd      }| j                  |d	d
      }d
|v rd
nd}| j                  ||d|      }| j                  |dd      }| j                  |d      }	t        j                  |d      rdnd}
t        j                  |      }| j                  |dd|
      }| j                  |d      }| j                  |d      }| j                  | j                  |d            }| j                  | j                  |d            }g }|K| j                  |d      }| j                  |      }|| j                  |d      }|j                  ||d       ||j                  |dd       ||j                  |dd       | j                  |d      }| j                  |||| j                  |      |d   |d |||	|d d |d |      S )!NrB   trade_idcreate_time_msr  r      r   r/  r:  r  rQ   r  r  sizer  r  sellbuysider  r  r   gt_fee	point_feefee_currencyr  )r  rR  GT	GatePointroler  )r  rB   r  r  r  orderr  r  takerOrMakerr  r  r  r   rw  )r6  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pointFeerw  feeCurrencyIdfeeCurrencyCoder  s                       r  parse_tradezgate.parse_trade  sm   L tZ8	##E+;<))(F;H"~H))(3I--eV]KI%%e_jI$.%$7Zf
!!(FCD))%6B&&ug6!(!2!2<!Ev5)),7!!%F""5*5$$UE2	t//x@A>>$"2"25+"FG  ,,UNCM"55mDO&"&"2"268"DKK!+  KK   KK '  ''v6"Y/X&( " 
  	r  c                    | j                          d}| j                  |dd      \  }}|r| j                  d||||      S i }d}|| j                  |      }|d   |d<   |||d<   |.| j	                  |dz        }||d	<   | j                  |d
      |d<   | j                  d||      \  }}| j                  | j                  ||            }	| j                  |	|      S )a<  
        fetch all deposits made to an account

        https://www.gate.io/docs/developers/apiv4/en/#retrieve-deposit-records

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

        https://www.gate.io/docs/developers/apiv4/en/#retrieve-withdrawal-records

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

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

        :param str code: unified currency code
        :param float amount: the amount to withdraw
        :param str address: the address to withdraw to
        :param str tag:
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        rB   )rR  r  r  Nmemor^  )
handle_withdraw_tag_and_paramsr  ry  rR  currency_to_precisionr  network_code_to_id!privateWithdrawalsPostWithdrawalsr  parse_transaction)
r}  rb  r  r  r  r  rR  r  ru  r  s
             r  r   zgate.withdraw  s     99#vFV7#==& 00v>

 ?!GFO"AA&IV"#66{CGG99$++gv:VW %%h99r  statusc                 H    dddddddddddddd}| j                  |||      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_status  sG      " 
 &&99r  c                 2    ddd}| j                  |||      S )Nr_  
withdrawal)dwr  )r}  r  typess      r  parse_transaction_typezgate.parse_transaction_type  s&    
 tT22r  transactionc                 z   | j                  |d      }d }| j                  |d      }|L|d   dk(  r0t        j                  |d      rdnd}t        j                  |      }n| j	                  |d         }| j                  |dd	      }|dk(  rt        j                  ||      }| j                  |d
      }| j                  |d      }| j                  |      }	| j                  |d      }
| j                  |d      }| j                  |      }| j                  |d      }| j                  |d      }| j                  |d      }i d|d|d|
d|	d| j                  |      d| j                  |      d|dd dd d|dd dd d|d|d|d| j                  |      dd d d |	| j                  |      ddS )NrB   r  r   r  r  r_  r  r   
fee_amountr^  rR  txidr  r  r  r  r  r`  	addressToaddressFromr  tagTotagFromr  r  updatedrR  r  )internalcommentr   )r  r=   	string_gtr  r  r6  r  safe_string_upperr  r  r  r|  rf  r  )r}  r  rR  rB   r  r  feeCostStringrt  rl  rb  r  	rawStatusr  r  r  r  s                   r  r  zgate.parse_transaction  sX   z k40''X>>!u|$+$5$5lC$Hyl&11,?222a59**;|L<"--lMJL**;@	%%k:>
&&z2V4$$[(;	..y9"";	:{F3''[A	
K
"
 D
 	

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

        https://www.gate.io/docs/developers/apiv4/en/#create-an-order
        https://www.gate.io/docs/developers/apiv4/en/#create-a-price-triggered-order
        https://www.gate.io/docs/developers/apiv4/en/#create-a-futures-order
        https://www.gate.io/docs/developers/apiv4/en/#create-a-price-triggered-order-2
        https://www.gate.io/docs/developers/apiv4/en/#create-a-futures-order-2
        https://www.gate.io/docs/developers/apiv4/en/#create-a-price-triggered-order-3
        https://www.gate.io/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
        :returns dict|None: `An order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r  r  	stopPricer  r  NrQ   rO   rg   rh   )ry  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_orderh  sn   H 	  "V$//&)4((MN//&2CD't3+47 5$5$*:'T/00tVUTZ[&>VH-55lC::<HF^>>|LCCLQH??MDD\R44\BHB &11r  r  c           	      @   g }g }t        |      }|dk(  rt        | j                  dz         |dkD  rt        | j                  dz         t        dt        |            D ]  }||   }| j	                  |d      }|j                  |       | j	                  |d      }	| j	                  |d      }
| j                  |d      }| j                  |d	      }| j                  |d
i       }| j                  ||      }| j                  |g d      }|t        | j                  dz         d|d<   | j                  ||	|
|||      }|j                  |        | j                  |d ddd      }| j                  |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textIsRequiredFrh   ri   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_request  s   6{1TWW'TTUU"TWW'aabbq#f+& 	0AayH''(;H)##Hf5D##Hf5D__Xx8FOOHg6E//(HbAK![[f=N,,[:{|L'"477  .U  $U  V  V/3N+,44XtT6SXZhiL!!,/	0  %%lD%tLWQZ((vh/tww)ffggr  c                    | j                          | j                          | j                  ||      }|d   }| j                  |d         }d}|d   r| j	                  |      }n|d   r| j                  |      }| j                  |      S )a  
        create a list of trade orders

        https://www.gate.io/docs/developers/apiv4/en/#get-a-single-order-2
        https://www.gate.io/docs/developers/apiv4/en/#create-a-batch-of-orders
        https://www.gate.io/docs/developers/apiv4/en/#create-a-batch-of-futures-orders

        :param Array orders: list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r   r  NrQ   rg   )ry  r  r  r  privateSpotPostBatchOrders#privateFuturesPostSettleBatchOrdersparse_orders)r}  r  r  r  
firstOrderr  r  s          r  create_orderszgate.create_orders
  s     	  "33FFCAY
Z12&>66~FHF^??OH  **r  c                    | j                  |      }|d   }| j                  |d      }	| j                  |dd      }
| j                  |d|
      }| j                  |d      }|d u}|d u}|xs |}|r|rt        | j                  dz         | j                  |d      }| j                  |g d	      }d }| j                  |d
k(  |dk(  |      \  }}| j                  |      }|rd}| j                  |g d      }|dk(  }|d
k(  }|r |t        | j                  dz   |z   dz         |rg|dk(  s|dk(  rt        | j                  dz         |?| j                  | j                  dd      }| j                  | j                  d   |d      }|}|rd}|rP| j                  |d      }|rd}n9| j                  ||      }|dk(  rt        j                  |      n|}t        |      }d }| xr |	d u }|r|rJ|d   |d}|d   s|d   |d<   |rd|d<   n|dk(  rdn| j!                  ||      |d<   |||d <   |5||d!<   n.d }| j#                  d"|      \  }}|d   |||d#}|r|d$k(  rd }d%}| j%                  |d&d'd%      \  }}| j'                  |d(      } | j                  |d(      }| | j)                  ||       }ny|re|t+        | j                  d)z         | j-                  |      }!| j-                  |      }"t        j.                  |!|"      }#| j)                  ||#      }n| j)                  ||      }||d*<   n| j                  ||      |d*<   |r| j!                  ||      |d<   |||d+<   | j1                  |d,d-      }$| j3                  |d.d"      }%|$Nt5        |$      d/kD  rt7        | j                  d0z         | j                  |g d1      }|$d   d2k7  rd3|$z   }$|$|d,<   n|%rd3| j9                         z   |d,<   n|d   rt;        | j                  d4z         |r|d   |d|d   d5}|d
k(  r	d|d6   d<   n|dk(  rdn| j!                  ||      |d6   d<   |	d }&d }'|r|d$k(  rd7nd8}&| j!                  ||      }'n|r|d$k(  rd8nd7}&| j!                  ||      }'| j=                  |d9d      }(|(dk  s|(d8kD  rt7        | j                  d:z         | j                  |d9g      }|(| j!                  ||'      |&d;|d<   |||d6   d <   |||d6   d!<   n| j                  | j                  d&i       })d }| j#                  d%|      \  }}|d}||| j!                  ||      | j                  ||      ||d<|d   d=}|	}| j=                  |)d>      }*| j=                  |d>|*      }+d }&d }'|r|d$k(  rd?nd@}&| j!                  ||      }'n|r|d$k(  rd@nd?}&| j!                  ||      }'| j!                  ||'      |&|+dA|d<   | j?                  ||      S )BNr  r  r  r  r  r  zG createOrder() stopLossPrice and takeProfitPrice cannot both be defined
reduceOnly)r  tiftime_in_forcer  r  )r  r  r  r  r  r  postOnlyr  z- createOrder() requires a price argument for  ordersr  zF createOrder() timeInForce for market order can only be "FOK" or "IOC"defaultTimeInForcer  r  r  r   r0  r  rB   )r  r  ri   r  r  r  r  reduce_onlyr  F)r:  r  rY   r  r  Tru   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  clientOrderIdr
     zF createOrder() clientOrderId or text param must be up to 28 characters)r  r"  r
  r!  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  rY   r  )r   r  rx  z>=z<=)r  r'  rx  ) r  r  r  r-   rB   safe_string_lower_nhandle_post_onlyhandle_time_in_forcer<  r2   r  rR   amount_to_precisionr=   
string_negintprice_to_precisionrA  rK  r  cost_to_precisionr6   number_to_stringr  r6  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  isLimitOrderisMarketOrder
defaultTifexchangeSpecificTifisCloseamountToPrecisionsignedAmountr  r  r  quoteAmountr  r  r  r  costRequestr"  r
  r'  triggerOrderPrice	priceTyperR   defaultExpirationrx  s,                                               r  r  zgate.create_order_request"  s~   V$*%//&)4((MN//&2CD't3+47 5$50*s stt__V\:
&*&>&>vGn&o#001AC^bgCgiop&//7K 6  $N  O)EM#DGG.]$]`d$dgp$pqqu$+*>#DGG.v$vww&!%!1!1$,,@TV[!\J*.*:*:4<<;VXbdi*j'"5Koofg6G$($<$<VV$L!IMQWw112CD^o\*$*:'T/ !'t"	 h'(.z(:GH% '*GG$/4zs@W@WX^`e@fGG$)-7GM**%0GEN!
%)%9%9%%H"
F &,D\ ) 
 !dem"&K8<5@D@]@]^dfs  vY  [_  A`=5v++FF;D!YYvv6F'&*&<&<VT&J: =".tww  :E  0E  #F  F+/+@+@+HL*.*?*?*FK*1*<*<\;*WK*.*@*@*UK&*&<&<VV&L(3GH%(,(@(@(PGH%'+'>'>vu'MGG$*/:GO, ..vvOM!^^F4DeLN(
 }%*$TWW/w%wxx6+VW #s*$(=$8M"/!&*T[[]&:GFOh"477-i#ijj %+4L &  %Z0 8#25GI&w/:?1*#4KbKbcikpKqGI&w/?D(,%& &*U]q,0,C,CFM,Z)*%)U]q,0,C,CFO,\) $ 1 1&, JI 1}	A(  4J  *J  K  K!YYv~>F '0!%!8!8AR!S $	*GI& )8BGI&}5*0;GI&u- //$,,rJ!
%)%9%9$%G"
F&"'K !% $!%!8!8!G"&":":66"J#-)4 %Tl
 ?(,(9(9'<(P%!%!2!26<IZ![JD(,%& )-tD,0,C,CFM,Z)*(,tD,0,C,CFO,\)!%!8!8AR!S $&0*GI&
 {{7F++r  r  c                     | j                          | j                          | j                  |      }|d   st        | j                  dz         d|d<   | j                  |dd|d|      S )aD  
        create a market buy order by providing the symbol and cost

        https://www.gate.io/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>`
        rQ   z9 createMarketBuyOrderWithCost() supports spot orders onlyFr  r  r  N)ry  r  r  r9   rB   r  )r}  r  r  r  r  s        r  !create_market_buy_order_with_costz&gate.create_market_buy_order_with_cost  sl     	  "V$f~tww)ddee6;23  5$fMMr  c                    | j                  |      }d }	| j                  d||      \  }	}| j                  |	      }
d}| j                  |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| j                  ||      |d<   na|dk(  r8| j                  t        j                  | j                  ||                  |d<   n$| j                  | j                  ||            |d<   || j                  ||      |d<   |d   s|d   |d<   | j                  ||      S )Nr   Fr  rW   r  rQ   z editOrder() does not support z orders for  marketsrB   )r  r:  rY   r  r  r  r  r  r  )r  r  convert_type_to_accountrK  r6   rB   strr+  parse_to_numericr=   r,  r.  r  )r}  rB   r  r  r  r  r  r  r  r  rY   rL  r3  r  s                 r  edit_order_requestzgate.edit_order_request	  s   V$
!??VU[\
F..z: #'#@#@Vf#g &Gf"477-M#MPT#TWe#ehr#ru#  A  AB#D\

 f~$($<$<VV$L!6>&*&;&;G<N<NtOgOghnpvOw<x&yGFO&*&;&;D<T<TU[]c<d&eGFO#66vuEGGf~ &z 2GH{{7F++r  c           	      
   | j                          | j                          | j                  |      }| j                  |||||||      }	d}
|d   r| j	                  |	      }
n| j                  |	      }
| j                  |
|      S )a  
        edit a trade order, gate currently only supports the modification of the price or amount fields

        https://www.gate.io/docs/developers/apiv4/en/#amend-an-order
        https://www.gate.io/docs/developers/apiv4/en/#amend-an-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>`
        NrQ   )ry  r  r  rF  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_`&>99/JH@@QH@ &11r  c                 D    dddddddddddd}| j                  |||      S )Nr/  closedr  )r/  _newfilled	cancelled
liquidatedr  r  expiredfinishedfinish	succeededr  r  s      r  parse_order_statuszgate.parse_order_statuse  sA    #" ! !
 &&99r  r  c           
      	   | j                  |dd      }|s6| j                  | j                  |d      |d| j                  |d      d      S | j                  |ddi       }| j	                  |d	i       }| j                  |d
      }| j                  |d      }| j                  |dd      }| j                  |dd      }	| j                  |d      }
| j                  |d      }| j                  |d
|      }| j                  |d|      }| j                  |dd|      }|dk(  rd}|dk(  }| j                  |dd|	      }	| j                  |d|
      }
| j                  |d|      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |dd      }|r|	}d}|r=t        j                  |d      xr |dk(  }|rdnd}t        j                  |	d      rdnd}
| j                  |g d      }| j                  |d      }|| j                  |d d!      }| j                  |d"      }|| j                  |d#d$      }d
}d%|v sd|v rd&}| j                  |d%d|      }| j                  ||d'|      }g }| j                  |d(      }||j!                  d)|d*       | j                  |d+      }|3|j!                  | j#                  | j                  |d,            |d*       | j                  |d-      }|F|j!                  | j#                  | j                  |d.            t        j$                  |      d*       t'        |      }|d/kD  }| j)                  |      }t        j*                  |      }| j                  |d0      } | d&k(  r]| j                  |d      }!| j-                  |!      }|dk(  r5|
dk(  r0t        j.                  ||!      }d }|	}t        j.                  |	|!      }	| j                  i d| j                  |d      d1| j                  |d      d2|d3| j1                  |      d4|d5|d6|d|d7|d8|d9| j	                  |d:      d|
d|d;|d<|dt        j*                  |	      d=t        j*                  |      d ||rd n| j	                  |d>      |r|ng d |d?|      S )@NrU  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  r/  r  r/  ctimeupdate_time_msupdate_timefinish_timer:  rQ   r  r  r  r  r   r  rebated_feerebated_fee_currencyr   rY   r"  r  r  lastTradeTimestampr  r  r  r  r  is_reduce_onlyr  r2  r  r   )rO  	remainingr   rw  r   r  )r  
safe_orderr  r  r  safe_string_upper_2r6  r  safe_number_2r=   string_equalsr  r5  r  r  r  r  r  r,  r  rV  r  r|  r  r  )"r}  r  r  rU  r   r  r  r  r  r  r  r  r  remainingStringr  r  r2  r4  r  r  rd  r  exchangeSymbolr  rw  r  r   rX   numFeeCurrenciesmultipleFeeCurrenciesr  rf  rY   averageStrings"                                     r  r  zgate.parse_orderu  s   ` NN5+t<	??!%!1!1%!@$&&ud3	$   ui<//%B7##C4V,..sOUK##C6:V,  g.##E:x@vt4..uoukZ%K4'##E8VVDvt4  7**5&9~6''9$$U,<lK$OD#11%=X;RWCWM,8'D#--fc:5D&&u.MN	%%e-=>	--e]GLI!..u6FG%!%!6!6um]![
u$(e*;J++E?HhW!!.&#zJ  1KK   ue,?KK 33D4D4DUN4[\  !!%7KK 33D4D4DULb4cd**62  t9 01 4((3&&7	""5)4f ,,U4DEM''6G tu}#..N	 ++FMB  
$""5$/ 
T--eV< 
  
 Y/	 

 !"4 
 f 
 f 
 D 
 ; 
  
 $//%1AB 
 D 
 U 
 L 
 w 
  g((0! 
" G&&t,# 
$ "04doodA6N1Dr/ 
0 1 	r  c                    |d n| j                  |      }| j                  |g dd      }| j                  |g d      }| j                  |dd      }|}|#| j                  |ddg      }|d   dk7  rd|z   }|}| j	                  d	||      \  }}	|d
k(  xs |dk(  xs |dk(  }
|
r| j                  |||	      n| j                  |||	      \  }}t        |      |d<   ||gS )Nr  is_stop_orderstopFrr  rs  r  r  r"  r   r!  r$  r   rg   rh   ri   r  )r  safe_bool_nr<  r6  r  r>  rC  rD  )r}  rB   r  r  r  r  r"  r  r  r2  r  r  r  s                r  fetch_order_requestzgate.fetch_order_requestr  s    .t{{6/B""6+OQVW6#GH**66?K$YYv'@AFQ3& $} 4#G88vvVeFNO(8Odh>NNV!5!5fdE!J\`\{\{  }C  EL  NS  ]T!'l
''r  c                 ~   | j                          | j                          |dn| j                  |      }| j                  d||      }| j	                  |d      }| j                  |g dd      }| j                  |||      \  }}	d}
|dk(  s|dk(  rF|r"| j                  | j                  ||	            }
n| j                  | j                  ||	            }
n|dk(  rF|r"| j                  | j                  ||	            }
n| j                  | j                  ||	            }
n|d	k(  rF|r"| j                  | j                  ||	            }
na| j                  | j                  ||	            }
n?|d
k(  r"| j                  | j                  ||	            }
nt        | j                   dz         | j#                  |
|      S )a  
        Retrieves information on an order

        https://www.gate.io/docs/developers/apiv4/en/#get-a-single-order
        https://www.gate.io/docs/developers/apiv4/en/#get-a-single-order-2
        https://www.gate.io/docs/developers/apiv4/en/#get-a-single-order-3
        https://www.gate.io/docs/developers/apiv4/en/#get-a-single-order-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   rq  FrQ   rO   rg   rh   ri   z* fetchOrder() not support self market type)ry  r  r  r  r  ru  rv   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_order  s   & 	  " .t{{6/B33L&&Q*""6+OQVW!%!9!9"ff!M6>TX-@@WVcAde;;DKKQ^<_`V^II$++V]_lJmnDDT[[QXZgEhiXJJ4;;W^`mKnoEEdkkRY[hFijX::4;;wP];^_Htww)UUVV&11r  c                 ,    | j                  d||||      S )a  
        fetch all unfilled currently open orders

        https://www.gate.io/docs/developers/apiv4/en/#list-all-open-orders
        https://www.gate.io/docs/developers/apiv4/en/#retrieve-running-auto-order-list

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch open orders for
        :param int [limit]: the maximum number of  open orders structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :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>`
        r/  )fetch_orders_by_status)r}  r  r  r  r  s        r  fetch_open_orderszgate.fetch_open_orders  s    " **665%PPr  c                    | j                          | j                          | j                  |d      }d}|| j                  |      }|d   }| j	                  d||      }| j                  |d      }d}	| j                  |ddd      \  }	}|	s|||dk7  r| j                  d	||||      S | j                  |d
      }i }
| j                  |||      \  }
}|| j                  |dz        |
d<   |)| j                  |d      }| j                  |dz        |
d<   |||
d<   | j                  | j                  |
|            }| j                  ||||      S )ab  
        fetches information on multiple closed orders made by the user

        https://www.gate.io/docs/developers/apiv4/en/#list-orders
        https://www.gate.io/docs/developers/apiv4/en/#retrieve-running-auto-order-list
        https://www.gate.io/docs/developers/apiv4/en/#list-futures-orders
        https://www.gate.io/docs/developers/apiv4/en/#list-all-auto-orders
        https://www.gate.io/docs/developers/apiv4/en/#list-futures-orders-2
        https://www.gate.io/docs/developers/apiv4/en/#list-all-auto-orders-2
        https://www.gate.io/docs/developers/apiv4/en/#list-options-orders
        https://www.gate.io/docs/developers/apiv4/en/#list-futures-orders-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>`
        r`  Nr  r   r   F
historicalrg   rS  r  r  r  ra  r  )ry  r  r  r  r  r  rK  r  r<  r>  r  &privateFuturesGetSettleOrdersTimeranger  r  )r}  r  r  r  r  r`  r  resr  useHistoricalr  r  s               r  fetch_closed_orderszgate.fetch_closed_orders  s   0 	  "!!&'2[[(FH%F001DffUQ' $ = =fFY[gin ov5=U]PV..z65%QWXX66*..vtVD"//=GFOYYvw/F --edl;GDM$GG>>t{{7TZ?[\  65%@@r  c                 L   d }|| j                  |      }|d   }d }| j                  |dd      \  }}d }| j                  d||      \  }}|dk(  xs |dk(  }	i }
|	r| j                  |||      n| j	                  |||      \  }
}|	r|r| j                  |
d      }
|dk(  rd	}||
d
<   |||
d<   |	rV|| j                  |dz        |
d<   | j                  |d      }|)| j                  |d      }| j                  |dz        |
d<   | j                  |dd      \  }}|||
d<   |
|gS )Nr  r  rs  fetchOrdersByStatusrQ   rO   rY   rM  rS  r  r  r  r  r`  ra  lastIdlast_id)	r  handle_param_bool_2r  rE  r>  r<  r  r  handle_param_string_2)r}  r  r  r  r  r  r  r  r  rQ   r  r`  r  finalParamss                 r   prepare_orders_by_status_requestz%gate.prepare_orders_by_status_request  s   [[(FH%F2269fM99:OQWY_`f5DH$4\`$??QWXfjfzfz  |B  DH  JP  gQGii3GXF"$GG "&"3"3EDL"A%%fg6E 673 $ 1 1%$, ?"889U!'GI%%r  c                    | j                          | j                          d }|| j                  |      }|d   }| j                  |dd      }| j	                  d||      }| j                  |d      }	| j                  |||||      \  }
}|	dk(  xs |	dk(  }|dk(  }|xr |xr | }d }|rk|sG|r#| j                  | j                  |
|            }n| j                  | j                  |
|            }n| j                  | j                  |
|            }n|	d	k(  rF|r"| j                  | j                  |
|            }n| j                  | j                  |
|            }n|	d
k(  rF|r"| j                  | j                  |
|            }na| j                  | j                  |
|            }n?|	dk(  r"| j                  | j                  |
|            }nt!        | j"                  dz         |}|rCg }t%        dt'        |            D ])  }| j)                  ||   d      }| j+                  ||      }+ | j-                  ||||      }| j/                  ||||      S )Nr  r  rs  r  r   rQ   rO   r/  rg   rh   ri   z+ fetchOrders() not support self market typer  )ry  r  r  safe_bool_2r  r  r  privateSpotGetOpenOrdersr  privateSpotGetOrdersprivateSpotGetPriceOrders"privateFuturesGetSettlePriceOrdersprivateFuturesGetSettleOrders#privateDeliveryGetSettlePriceOrdersprivateDeliveryGetSettleOrdersprivateOptionsGetOrdersr9   rB   r  r  r  r  r  r  )r}  r  r  r  r  r  r  r  r  r  r  r  rQ   
openStatusopenSpotOrdersr  r  r  ordersInnerr  s                       r  r  zgate.fetch_orders_by_status  sf     "[[(FH%F((FC001FPVWQ'!%!F!FvvW\^cek!l5DH$4&
<*<W#<<T[[R_=`aH#88Wm9\]H99$++g}:]^V^BB4;;wXeCfg==dkk'S`>abXCCDKKPWYfDgh>>t{{7Ta?bcX33DKK4WXHtww)VVWWf F1c(m, @"oohqk8D**6;?@ ""665%@00NNr  c                    | j                          | j                          |dn| j                  |      }| j                  |g dd      }| j	                  |g d      }| j                  d||      \  }}|dk(  s|dk(  r| j                  |||      n| j                  |||      \  }}	||d<   d}
|dk(  s|dk(  rF|r"| j                  | j                  ||	            }
n| j                  | j                  ||	            }
n|dk(  rF|r"| j                  | j                  ||	            }
n| j                  | j                  ||	            }
n|d	k(  rF|r"| j                  | j                  ||	            }
na| j                  | j                  ||	            }
n?|d
k(  r"| j                  | j                  ||	            }
nt!        | j"                  dz         | j%                  |
|      S )a  
        Cancels an open order

        https://www.gate.io/docs/developers/apiv4/en/#cancel-a-single-order
        https://www.gate.io/docs/developers/apiv4/en/#cancel-a-single-order-2
        https://www.gate.io/docs/developers/apiv4/en/#cancel-a-single-order-3
        https://www.gate.io/docs/developers/apiv4/en/#cancel-a-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>`
        Nrt  Frn   rQ   rO   r  rg   rh   ri   z+ cancelOrder() not support self market type)ry  r  r  ru  r<  r  rC  r>  #privateSpotDeletePriceOrdersOrderIdr  privateSpotDeleteOrdersOrderId,privateFuturesDeleteSettlePriceOrdersOrderId'privateFuturesDeleteSettleOrdersOrderId-privateDeliveryDeleteSettlePriceOrdersOrderId(privateDeliveryDeleteSettleOrdersOrderId!privateOptionsDeleteOrdersOrderIdr9   rB   r  )r}  rB   r  r  r  r  r  r2  r  r  r  s              r  cancel_orderzgate.cancel_order  s     	  " .t{{6/B""6+OQVW6#GH88PVWe]aek]koswo!@!@RW!X  GK  G[  G[  \b  dh  jo  Gp 
6>TX-CCDKKPWYfDgh>>t{{7Ta?bcV^LLT[[Y`boMpqGGT[]jHklXMMdkkZacpNqrHHU\^kIlmX==dkk'S`>abHtww)VVWWd &11r  idsc                 Z   | j                          | j                          d}|| j                  |      }d}|dn|d   }| j                  |d|      }| j	                  d||      \  }}|dk(  }|r|t        | j                  dz         |rIg }	t        dt        |            D ]  }
||
   }||d}|	j                  |        | j                  |	|      S d|i}|g}t        dt        |            D ]  }
|j                  ||
           | j                  |      }| j                  |      S )	ar  
        cancel multiple orders

        https://www.gate.io/docs/developers/apiv4/en/#cancel-a-batch-of-orders-with-an-id-list
        https://www.gate.io/docs/developers/apiv4/en/#cancel-a-batch-of-orders-with-an-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  ro   rQ   z9 cancelOrders requires a symbol argument for spot marketsr   )rB   r  )ry  r  r  r;  r  r2   rB   r  r  r  cancel_orders_for_symbols)privateFuturesPostSettleBatchCancelOrdersr  )r}  r  r  r  r  r  r=  r  isSpotr  r  rB   	orderItemr  	finalListr  s                   r  cancel_orderszgate.cancel_ordersW  s[    	  "[[(F#)>x8H''-H99.&RXYf&.v~#DGG.i$ijjN1c#h' 1V$#	 %%i01 11.&IIf
 I	q#c(# 	%ASV$	%AA)L  **r  c                    | j                          | j                          g }t        dt        |            D ]r  }||   }| j	                  |d      }| j                  |      }|d   st        | j                  dz         | j	                  |d      }||d   d}	|j                  |	       t | j                  |      }
| j                  |
      S )a  
        cancel multiple orders for multiple symbols

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

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

        https://www.gate.io/docs/developers/apiv4/en/#cancel-all-open-orders-in-specified-currency-pair
        https://www.gate.io/docs/developers/apiv4/en/#cancel-all-open-orders-matched
        https://www.gate.io/docs/developers/apiv4/en/#cancel-all-open-orders-matched-2
        https://www.gate.io/docs/developers/apiv4/en/#cancel-all-open-orders-matched-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>`
        Nrs  r  rm   rQ   rO   rg   rh   ri   z/ cancelAllOrders() not support self market type)ry  r  r  r  r<  r  rE  r>  privateSpotDeletePriceOrdersr  privateSpotDeleteOrders%privateFuturesDeleteSettlePriceOrders privateFuturesDeleteSettleOrders&privateDeliveryDeleteSettlePriceOrders!privateDeliveryDeleteSettleOrdersprivateOptionsDeleteOrdersr9   rB   r  )
r}  r  r  r  r  r  r2  r  r  r  s
             r  cancel_all_orderszgate.cancel_all_orders  s    	  " .t{{6/B""669=6FI#67889JFTZ[ecgkqcq!F!FvwX]!^x|  yM  yM  NT  VZ  \a  yb6>TX-<<T[[R_=`a77G]8[\V^EEdkkRY[hFij@@WVcAdeXFFt{{SZ\iGjkAA$++gWdBefX66t{{7M7Z[Htww)ZZ[[:   622r  fromAccount	toAccountc                    | j                          | j                  |      }| j                  |      }| j                  |      }| j                  ||      }	|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(  rX| j                  |dd      }|t        | j                  d	z         | j                  |      }|d   |
d<   | j                  |d      }|d
k(  s|dk(  s
|d
k(  s|dk(  r|d   |
d<   | j                  | j                  |
|            }| j                  ||      S )a  
        transfer currency internally between wallets on the same account

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

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

        https://www.gate.io/docs/developers/apiv4/en/#update-position-leverage
        https://www.gate.io/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  rG  cross_leverage_limitr  r  r  r  rg   rh   z+ setLeverage() not support self market type)r2   rB   r3   ry  r  r>  r6  rR   r  r0  1privateFuturesPostSettlePositionsContractLeverager  2privateDeliveryPostSettlePositionsContractLeverager9   )r}  r  r  r  r  r  r2  rG  crossLeverageLimitr  stringifiedMarginr  s               r  set_leveragezgate.set_leverage>  s}    >#DGG.Y$YZZ qLhnTWW'\\]]V$--fdFC ..t||\K^_!--e5KL%%e\;LM
 11(;) J 2 J.$@.?G*+"%GJ"3GJ&>MMdkkZachNijH@ ? HNNt{{[bdiOjkH< 9 tww)VVWWr  positionc                    | j                  |d      }| j                  ||dd      }| j                  |dd      }| j                  |d      }|1t        j                  |d      rd}nt        j
                  |d      rd}| j                  |d	      }| j                  |d
      }| j                  |d      }d }	|
|dk(  rd}	nd}	| j                  |d      }
d }|
Bd}t        j                  ||      }
t        j                  t        j                  ||      |
      }| j                  |dd      }|dk(  rd }| j                  i d|dd d| j                  |d      d|d| j                  |      d| j                  |dd      d| j                  |      d| j                  t        j                  ||            d| j                  t        j                  ||            d| j                  |      d| j                  |d       d!| j                  |      d| j                  |d      d"| j                  |d#      d$| j                  |d%d&      d'| j                  t        j                  |            d(| j                  |d(      d | j                  |d)      | j                  |d*      d | j                  |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  lastUpdateTimestampr`  r   initialMargininitialMarginPercentagemaintenanceMarginmaintenanceMarginPercentage
entryPriceentry_pricenotionalunrealizedPnlunrealised_pnlrealizedPnlrealised_pnlpnlr   r  	liq_pricer  rO   )
marginRatioliquidationPricer#  	lastPrice
collateralr  r  r  r  r  )r  r  r6  r=   r  r  r  r  r  r  safe_positionr  r|  r  ri  r  )r}  r  r  r  r  r  maintenanceRater  r  r  feePaidinitialMarginStringtakerFeer  s                 r  parse_positionzgate.parse_position  sO   V ##Hj9!!(FCD!!(FLA&1<  s+""4-**85GH##Hg6##Hj9
3$
'
 ""8Y7"? H((8<G")"4"4W5G5GRZ5[]d"e))(KARS	>I!! #
H#
$#
 d&&vx8#
 	#

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

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

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

        https://www.gate.io/docs/developers/apiv4/en/#list-all-positions-of-a-user
        https://www.gate.io/docs/developers/apiv4/en/#list-all-positions-of-a-user-2
        https://www.gate.io/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   rQ   rg   ri   rB   r  r*  rh   )ry  r  r  r  r  r  r  r>   privateFuturesGetSettlePositionsr  !privateDeliveryGetSettlePositionsprivateOptionsGetPositionsparse_positions)
r}  r}  r  r  symbolsLengthr  r  r  r  r  s
             r  fetch_positionszgate.fetch_positions^  sc    	%%gtT4FLMq WQZ099:JFTZ[fLdfnD8"!$<&nnS1(,(8(8a(H%"224vFOGV6><<T[[RX=YZHX==dkk'SY>Z[HX66t{{7F7STHz ##Hg66r  c                    | j                          | j                  dd|      \  }}| j                  d||      \  }}|dk7  r|dk7  rt        | j                  dz         d}|dk(  r"| j                  | j                  ||            }n?|dk(  r"| j                  | j                  ||            }nt        | j                  dz         | j                  ||d      S )aG  
        retrieve information on the maximum leverage, and maintenance margin for trades of varying trade sizes

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

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

        https://www.gate.io/docs/developers/apiv4/en/#list-risk-limit-tiers

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `leverage tiers structure <https://docs.ccxt.com/#/?id=leverage-tiers-structure>`
        r   rh   rg   z7 fetchMarketLeverageTiers only supports swap and future)	ry  r  r  r>  r3   rB   %privateFuturesGetSettleRiskLimitTiersr  parse_market_leverage_tiers)	r}  r  r  r  r  r2  r  r  r  s	            r  fetch_market_leverage_tiersz gate.fetch_market_leverage_tiers9  s     	V$889SU[]cde!%!5!5fdE!J8TWW'``aa==dkk'S`>ab //&AAr  c                 :   | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }t        j                  d|      }|}	|}
d}g }t        j                  ||      rt        j                  ||      }|j                  | j                  t        j                  ||            | j                  ||d d      | j                  |d	      | j                  |      | j                  |      | j                  |	      | j                  t        j                  d|
            |d
       t        j                  |	|      }	t        j                  |
|      }
|}t        j                  ||      r|S )NrC   r  r  risk_limit_steprisk_limit_maxr  r  r  r  tierr  rR  minNotionalmaxNotionalmaintenanceMarginRatemaxLeverager  )r  r=   r  r  r  r  r|  r  )r}  r  r  r  maintenanceMarginUnitleverageMaxriskLimitStepriskLimitMaxinitialMarginUnitr  initialMarginRatiofloorr  caps                 r  parse_emulated_leverage_tiersz"gate.parse_emulated_leverage_tiersW  s   ##D&1 $ 0 07I J&&t^<((/@A''.>?#..sK@ 5.|4$$UM:CLL))'*<*<S-*PQ**8VT:N ,,VX>#007#005)-):):;P)Q#001C1CCI[1\]	 	 %,$6$67LNc$d!!(!3!34FHY!ZE |4 r  c                 X   t        |t              s| j                  ||      S d}g }t        dt	        |            D ]k  }||   }| j                  |d      }|j                  | j                  |d      |d   |d   ||| j                  |d      | j                  |d      |d       |}m |S )	Nr   
risk_limitr   r  r  r  r  r  )r  r  r  r  r  r  r  re  )r}  r  r  r  r  r  itemr  s           r  r  z gate.parse_market_leverage_tierss  s     $%55dFCCq#d)$ 	&A7D**4>KLLA *"6N**)-)9)9$@R)S#//nE	 	 &K	& r  c                 2   | j                          | j                  |      }|d   j                         | j                  ||      d}| j	                  |      }|d   |d<   d|d<   | j                  | j                  ||            }| j                  ||      S )a  
        repay borrowed margin and interest

        https://www.gate.io/docs/apiv4/en/#repay-a-loan

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

        https://www.gate.io/docs/developers/apiv4/en/#cross-margin-repayments
        https://www.gate.io/docs/developers/apiv4/en/#borrow-or-repay

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

        https://www.gate.io/docs/developers/apiv4/en/#marginuni

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

        https://www.gate.io/docs/apiv4/en/#create-a-cross-margin-borrow-loan
        https://www.gate.io/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]: set to True for borrowing in the unified account
        :returns dict: a `margin loan structure <https://docs.ccxt.com/#/?id=margin-loan-structure>`
        rB   r  Frk   r  Nr#  r  )
ry  r  rR  r  r  rK  r  r  privateMarginPostCrossLoansr  r   s           r  borrow_cross_marginzgate.borrow_cross_margin  s     	  "==& ,,.00v>
 !#'#@#@I\^n#o &&GFO33DKK4PQH77GV8TUH %%h99r  c           	         | j                  | j                  ddd      }| j                  |d      }|dk(  r| j                  |d      }| j	                  |d      }| j	                  |d      }| j                  |d      | j                  ||      | j                  |d	      | j                  |d d
d      || j                  |      |dS )NrG  r  r  r/  r  rR  r:  rB   r  r  rO   )rB   rR  r  r  r  r  r  )	r6  rR   r  r  r  r  r  r  r  )r}  r  rR  r  r  rl  r  s          r  r  zgate.parse_margin_loan;  s    J ''6I<Y`a
%%dM:	#++D-@I%%dJ7
##D/:##D$///
HE&&tX6&&xsHE"Y/
 	
r  c                    | j                          | j                          d}| j                  |dd      \  }}i }| j                  d||      \  }}d}|| j	                  |      }|d   |d<   d}	|| j                  |      }	|||d<   |||d	<   d}
d}| j                  d|d
      \  }}|r"| j                  | j                  ||            }
nW|dk(  r,|	|	d   |d<   | j                  | j                  ||            }
n&|d
k(  r!| j                  | j                  ||            }
| j                  |
|	      }| j                  ||||      S )a  
        fetch the interest owed by the user for borrowing currency for margin trading

        https://www.gate.io/docs/developers/apiv4/en/#list-interest-records
        https://www.gate.io/docs/developers/apiv4/en/#interest-records-for-the-cross-margin-account
        https://www.gate.io/docs/developers/apiv4/en/#list-interest-records-2

        :param str [code]: unified currency code
        :param str [symbol]: unified market symbol when fetching interest in isolated markets
        :param int [since]: the earliest time in ms to fetch borrow interest for
        :param int [limit]: the maximum number of structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.unifiedAccount]: set to True for fetching borrow interest in the unified account
        :returns dict[]: a list of `borrow interest structures <https://docs.ccxt.com/#/?id=borrow-interest-structure>`
        Fr   r  ra  NrB   rR  r  r  r  r  r:  )ry  r  rK  r  rR  r  handle_margin_mode_and_params privateUnifiedGetInterestRecordsr  "privateMarginGetUniInterestRecords$privateMarginGetCrossInterestRecordsparse_borrow_interestsfilter_by_currency_since_limit)r}  rb  r  r  r  r  rL  r  rR  r  r  r  interests                r  fetch_borrow_interestzgate.fetch_borrow_interestp  s     	  " #'#@#@I^`p#q &224&I}}T*H"*4.GJ[[(F#GFO$GG
!??@UW]_fg
F<<T[[RX=YZH:%!+1$<(>>t{{7TZ?[\H7"@@WV\A]^H..x@228T5%PPr  r  c                 N   | j                  |d      }| j                  ||      }|dnd}| j                  |d      }|| j                  |d      | j                  | j                  |d            | j	                  |d      | j	                  |d      d ||| j                  |      d		S )
Nr:  r  r  r/  r  rR  r0  actual_rate)	r  r  rR  r0  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$,$8Zw
%%dM:	&&vx8//0@0@z0RS((z: ,,T=A"$"Y/

 
	
r  c                 B    | j                         | j                  d   z
  S )Nr  )millisecondsrR   )r}  s    r  r  z
gate.nonce  s       "T\\2B%CCCr  GETc                 >   |d   }|d   }| j                  || j                  |            }	|j                  d      dkD  }
|
rl|j                  d      r[| j	                  |d      }| j                  ||      }g }|}t        dt        |            D ]  }|j                  ||           |}|}	nHt        |t              r&| j                  |di       }| j                  ||      }n| j                  ||      }|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| j                  |	      z   z  }n'| j!                          d}d}|dk(  s|dk(  rS|dk(  rN|j#                  d      }| j%                  |dd      }|j                  d      dk\  xs |j                  d      dk\  }|dk(  s|dk(  s|s|dk(  rl|	rS| j                  |	      }|j                  d      dk\  r&|j                  d      dk\  r|j'                  dd      }|d|z   z  }|dk(  rc| j)                  |	      }nQ| j                  |	di       }|r| j                  |      }|d|z   z  }| j                  |	d      }	| j)                  |	      }|dn|}| j+                  | j-                  |      d      }| j/                         }| j1                  |dz        }t3        |      }d| j4                  z   |z   }|j7                         ||||g}dj9                  |      }| j;                  | j-                  |      | j-                  | j<                        t>        j@                        } | jB                  || d d!}||||d"S )#Nr   r   r  r  batch_cancel_ordersr  r  rV   rU   rb   z! does not have a testnet for the z market type.r[   ?FrN   rP   POSTdualr/  r8  DELETEPATCHzcurrencies=z%2C,r2  sha512r  z/api/
zapplication/json)KEY	TimestampSIGNzContent-Type)r]   rN  bodyrv  )"r<  extract_paramsr  re  r  implode_paramsr  r  r  r  r  r  rL   r9   rB   	urlencoderc  r  r  replacejsonhashencoder  r  rD  rH   r  joinhmacru  hashlibrA  rt  )!r}  pathrb   rN  r  rv  rF  authenticationr  r2  containsSettler  	newParams	anyParamsr  r=  endPart
entirePathr]   queryStringrequiresURLEncoding	pathParts
secondParturlQueryParamsbodyPayloadbodySignaturer  r  timestampStringsignaturePathpayloadArraypayload	signatures!                                    r  signz	gate.sign  s   Q1v		&$"5"5d";<8,r1dmm,AB ^^FA.F&&tV4DII1c)n- ,  +,FE% OOFAr2E&&tU3D&&tV4D"3:4Z')
M!t}'< Jii~.t4;tww)LLtSVeeffzX%sT^^E222++-K"'"
(:6AQ JJsO	!--iB?
'1v'>!'C&kYdIeijIj#%Vx%7<OTZ^eTe"&.."7K"''6!;@P@PQV@W[\@\&1&9&9%&E3,,CW$99U+D!%!D!"&.."@K3,,C		%1yy'!%"DK IIdkk+&>IMJJLE))%$,7I!)nO#dll2Z?M"LLNM;WfgLii-G		$++g"6DKK8PRYR`R`aI{{,! 2	G fdwOOr  c                    | j                          | j                  |      }| j                  |d |      \  }}| j                  |      |d<   d }|d   r"| j	                  | j                  ||            }n?|d   r"| j                  | j                  ||            }nt        | j                  dz         | j                  ||      S )Nr  rg   rh   z2 modifyMarginHelper() not support self market type)
ry  r  r>  r0  /privateFuturesPostSettlePositionsContractMarginr  0privateDeliveryPostSettlePositionsContractMarginr9   rB   parse_margin_modification)r}  r  r  r  r  r  r2  r  s           r  modify_margin_helperzgate.modify_margin_helper  s    V$--fdFC 11&9&>KKDKKX_afLghHHLLT[[Y`bgMhiHtww)]]^^--h??r  rU  c                     | j                  |d      }| j                  ||dd      }| j                  |d      }||d   d dd || j                  |d      dd d d
S )	Nr  r  rO   r  r  r  r  )
r  r  r  r  r  rE  rb  r  r  r  )r  r  r  r  )r}  rU  r  r  rE  s        r  rh  zgate.parse_margin_modification  sv    8 ##D*5!!(FCD  x0X&$OOFG4
 	
r  c                 *    | j                  || |      S )a  
        remove margin from a position

        https://www.gate.io/docs/developers/apiv4/en/#update-position-margin
        https://www.gate.io/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=reduce-margin-structure>`
        ri  r}  r  r  r  s       r  reduce_marginzgate.reduce_margin;  s     ((&&AAr  c                 (    | j                  |||      S )a  
        add margin

        https://www.gate.io/docs/developers/apiv4/en/#update-position-margin
        https://www.gate.io/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=add-margin-structure>`
        rl  rm  s       r  
add_marginzgate.add_marginI  s     ((@@r  r?  c           	         | j                          d}| j                  |ddd      \  }}|r| j                  d|||||d      S | j                  |      }|d   st	        | j
                  dz         |d   |d   | j                  | j                  ||      d	}|||d
<   |||d<   | j                  | j                  ||            }	| j                  |	|||      S )a  
        Retrieves the open interest of a currency

        https://www.gate.io/docs/developers/apiv4/en/#futures-stats

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

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

        :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   ri   z6 fetchSettlementHistory() supports option markets onlyrB   r  r*  r   r  r  r  )r2   rB   ry  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  s    >#DGG.d$deeV$99:RTZ\bcf8tww)aabb$<nnS)$**;:
 #GFO$GG33DKK4PQ ,,Xv>k;700NNr  c                 X   |t        | j                  dz         | j                          | j                  |      }d}| j	                  d||      \  }}|dk7  rt        | j                  dz         |d   }|j                  d      }| j                  |d      |d	}	|||	d
<   |||	d<   | j                  | j                  |	|            }
| j                  |
di       }| j                  |dg       }| j                  ||      }| j                  |d      }| j                  ||d   ||      S )a  
        fetches historical settlement records of the user

        https://www.gate.io/docs/developers/apiv4/en/#list-my-options-settlements

        :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]
        Nz6 fetchMySettlementHistory() requires a symbol argumentr   ri   z8 fetchMySettlementHistory() supports option markets onlyrB   r  r   )r*  r  r  r  r  r  r  r  )r2   rB   ry  r  r  r9   r  r  privateOptionsGetMySettlementsr  r  r}  r  r  )r}  r  r  r  r  r  r  r  r  r  r  r  rU  r   r  s                  r  fetch_my_settlement_historyz gate.fetch_my_settlement_history  sG    >#DGG.f$fggV$99:TV\^def8tww)ccdd$<nnS)**;: 
 #GFO$GG66t{{7F7ST  8R8vvr2,,T6:k;7009I5RWXXr  c                     | j                  |d      }| j                  |d      }|| j                  ||      | j                  |d      || j	                  |      dS )Nr   r  settle_price)r  r  r  r  r  )r  r  r  r  r  )r}  
settlementr  r  r  s        r  parse_settlementzgate.parse_settlement  sd    6 ''
F;	##J
;&&x8%%j.A"Y/
 	
r  c                     g }t        dt        |            D ]&  }|j                  | j                  ||   |             ( |S r  )r  r  r  r  )r}  r   r  r  r  s        r  r}  zgate.parse_settlements2  sH    > q#k*+ 	IAMM$//AGH	Ir  c                 t   | j                          d}| j                  |dd      \  }}|r| j                  d||||      S d}d}d}i }	| j                  dd|      \  }}|dk(  s|dk(  r|| j	                  |      }|d   |	d<   |d	k(  s|d
k(  r3|d	k(  rdnd}
| j                  |d|
      }| j                  |d      }||	d<   |||	d<   |||	d<   | j                  d|	|      \  }	}|dk(  r"| j                  | j                  |	|            }n|dk(  r"| j                  | j                  |	|            }nt|d	k(  r"| j                  | j                  |	|            }nM|d
k(  r"| j                  | j                  |	|            }n&|dk(  r!| j                  | j                  |	|            }| j                  ||||      S )a  
        fetch the history of changes, actions done by the user or operations that altered the balance of the user

        https://www.gate.io/docs/developers/apiv4/en/#query-account-book
        https://www.gate.io/docs/developers/apiv4/en/#list-margin-account-balance-change-history
        https://www.gate.io/docs/developers/apiv4/en/#query-account-book-2
        https://www.gate.io/docs/developers/apiv4/en/#query-account-book-3
        https://www.gate.io/docs/developers/apiv4/en/#list-account-changing-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>`
        Fr   r_  NrQ   rO   rB   rR  rg   rh   r  r  r  r  r  ra  ri   )ry  rK  r  r  rR  r;  r<  r  privateSpotGetAccountBookr  privateMarginGetAccountBookr  r  privateOptionsGetAccountBookparse_ledger)r}  rb  r  r  r  r_  r  rR  r  r  r=  r  s               r  fetch_ledgerzgate.fetch_ledgerV  s   $ 	88PZ[&44]D%QVX^__99-vVfFN 0==.&.tn
#FN 0'+v~FEM++FHmLFYYvx0F &GH#GFO$GG224&I6>55dkk'66RSHX77GV8TUHV^>>t{{7TZ?[\HX??GU[@\]HX88Wf9UVHj   8UEBBr  r  c                    d }| j                  |d      }t        j                  |d      rd}t        j                  |      }nd}| j                  |d      }| j	                  ||      }| j                  |d      }| j                  |d      }d }t        |      dkD  rt        |      }nt        |      d	z  }| j                  |d
      }	| j                  |d      }
| j                  t        j                  |	|
            }| j                  || j                  |d      |d d d | j                  |      | j                  ||      | j                  |      || j                  |      || j                  |d
      d d d|      S )Nr  r  outinrR  r  r   r  r  balancerB   )r  rB   	directionrY   referenceAccountreferenceIdr  rR  r  r  r  beforeafterr  r   )r  r=   r  r  r  r  r-  r|  r  safe_ledger_entryparse_ledger_entry_typer  r  r  )r}  r  rR  r  r  rl  r  rawTimestampr  balanceStringchangeStringr  s               r  parse_ledger_entryzgate.parse_ledger_entry  s   Z 	!!$1VS)I''/FI%%dJ7
%%j(;f-''f5	|r!L)IL)D0I((y9''h7""7#5#5m\#RS%%""4." $006//
HE''/"Y/%%dI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+}| j                  |||      S ),Nr_  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_feerX   	order_feer   r0  lendrZ   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7r  r  c                     || j                  |      nd}| j                  |d|      \  }}||d<   | j                  | j                  ||            S )aQ  
        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.io/docs/developers/apiv4/en/#enable-or-disable-dual-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
        Nrg   	dual_mode)r  r>   privateFuturesPostSettleDualModer  )r}  r  r  r  r  r  r2  s          r  set_position_modezgate.set_position_mode=  sW     *0);V$$--fffE%44T[[%5PQQr  c                 R   | j                          d}| j                  dd|      \  }}||dk(  rd}|dk7  rt        | j                  dz         | j	                  |      }g }t        dt        |            D ]-  }||   }| j                  |d      }||j                  |       / |S )a  
        fetches the market ids of underlying assets for a specific contract market type

        https://www.gate.io/docs/developers/apiv4/en/#list-all-underlyings

        :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   rQ   ri   z5 fetchUnderlyingAssets() supports option markets onlyr   rC   )	ry  r  r9   rB   r7  r  r  r  r  )r}  r  r  r  r   r  r*  rC   s           r  fetch_underlying_assetszgate.fetch_underlying_assetsN  s     	
!??@WY]_ef
FJ&$8!J!tww)``aa33F; q#h-( 	)A!!J##J7D""4(		)
 r  c                 F   | j                          | j                  |      }|d   st        | j                  dz         |d   |d   d}|||d<   |||d<   | j	                  d||      \  }}| j                  | j                  ||            }| j                  ||||      S )	a  
        retrieves the public liquidations of a trading pair

        https://www.gate.io/docs/developers/apiv4/en/#retrieve-liquidation-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>`
        rg   z/ fetchLiquidations() supports swap markets onlyr  rB   )r  r  r  r  ra  )ry  r  r9   rB   r  publicFuturesGetSettleLiqOrdersr  parse_liquidations)r}  r  r  r  r  r  r  r  s           r  fetch_liquidationszgate.fetch_liquidationsq  s     	V$f~tww)ZZ[[Z(t
 #GFO$GG224&I77GV8TU &&xFFr  c                 r   |t        | j                  dz         | j                          | j                  |      }d|d   i}d}|d   s|d   r|||d<   |d   |d	<   n0|d
   r+|d   }|j	                  d      }	| j                  |	d      |d<   |d   r"| j                  | j                  ||            }no|d   r"| j                  | j                  ||            }nH|d
   r"| j                  | j                  ||            }n!t        | j                  dz   |d   z   dz         | j                  ||||      S )a  
        retrieves the users liquidated positions

        https://www.gate.io/docs/developers/apiv4/en/#list-liquidation-history
        https://www.gate.io/docs/developers/apiv4/en/#list-liquidation-history-2
        https://www.gate.io/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   rg   rh   r  r  r  ri   r  r   r*  z( fetchMyLiquidations() does not support r  r  )r2   rB   ry  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^    >#DGG.a$abbV$t
 6Nx 0 #(  &z 2GHHd|H"..-K$($4$4[!$DGL!&>==dkk'SY>Z[HH>>t{{7TZ?[\HH::4;;wPV;WXHtww)SSV\]cVddgppqqD &&xFFr  c                    | j                  |d      }| j                  |d      }| j                  |dd      }| j                  |dd      }t        j                  t        j
                  ||            }| j                  |d      }| j                  |dd	      }	t        j                  ||      }
| j                  |d
      }|t        j                  |
|	      }| j                  || j                  ||      | j                  |      | j                  |      | j                  |	      | j                  |
      | j                  t        j                  |            || j                  |      d	      S )Nr  r   r  settle_sizerY  r  r  r  r\  r  )	r  r  r   r  r  	baseValue
quoteValuer  r  )r  r  r6  r=   r  r  r  safe_liquidationr  r|  r  )r}  liquidationr  r  r  r  rY  contractsStringcontractSizeStringr  baseValueStringquoteValueStrings               r  parse_liquidationzgate.parse_liquidation  sa   R ##K<''V<	!!+v}EVS9!,,W-?-?d-KL!--fnE((k<P!,,_>PQ++K?#&11/;O$$&&x8**?; --.@A&&{3**?;++G,>,>?O,PQ"Y/
&
 
 
	r  c                 :   | j                          | j                  |      }d|d   d   i}| j                  | j                  ||            }|d   }t	        dt        |            D ]2  }||   }| j                  |d      }	|	|k(  s | j                  ||      c S  y)a  
        fetches an option contracts greeks, financial metrics used to measure the factors that affect the price of an options contract

        https://www.gate.io/docs/developers/apiv4/en/#list-tickers-of-options-contracts

        :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>`
        r*  r  rB   r   rC   N)ry  r  r  r  r  r  r  parse_greeks)
r}  r  r  r  r  r  r  r  rk  entryMarketIds
             r  fetch_greekszgate.fetch_greeks#  s     	V$&.6
 //GV0LM. $<q#h-( 	8AQKE ,,UF;M(((77		8
 r  greeksc                    | j                  |d      }| j                  ||      }i d|dd dd d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      d	d d
| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      | j                  |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_greeksQ  s   * ##FF3!!(F3
f

 
 T%%fg6	

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

        https://www.gate.io/docs/developers/apiv4/en/#create-a-futures-order
        https://www.gate.io/docs/developers/apiv4/en/#create-a-futures-order-2
        https://www.gate.io/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>`
        r0  TNr  r  r   )r  r  )r}  r  r  r  r  s        r  close_positionzgate.close_position~  sG     T
 Wf-<D  4D&IIr  c                    | j                          d}|| j                  |      }i }d}| j                  |d      }| j                  |d      }|d   rN|d   |d<   |r"| j	                  | j                  ||            }ng| j                  | j                  ||            }nE|r"| j                  | j                  ||            }n!t        | j                  dz   |d   z   dz         | j                  ||      S )	a  
        fetch the set leverage for a market

        https://www.gate.io/docs/developers/apiv4/en/#get-unified-account-information
        https://www.gate.io/docs/developers/apiv4/en/#get-detail-of-lending-market
        https://www.gate.io/docs/developers/apiv4/en/#query-one-single-margin-currency-pair-deprecated

        :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>`
        NrW   rQ   rB   r:  z" fetchLeverage() does not support r  rB  )ry  r  r  r<  +publicMarginGetUniCurrencyPairsCurrencyPairr  (publicMarginGetCurrencyPairsCurrencyPairrK  r9   rB   parse_leverage)r}  r  r  r  r  r  	isUnifieds          r  fetch_leveragezgate.fetch_leverage  s    	[[(FNN695	69-&>'-d|GO$KKDKKX_agLhi  HHU\^dIef 55dkk'66RSHh tww)MMPVW]P^^akkll""8V44r  c                 
   | j                          | j                  |      }d}| j                  |d      }| j                  |d      }d}|rd}| j	                  |      }n| j                  |      }| j                  |||d      S )a  
        fetch the set leverage for all leverage markets, only spot margin is supported on gate

        https://www.gate.io/docs/developers/apiv4/en/#list-lending-markets
        https://www.gate.io/docs/developers/apiv4/en/#list-all-supported-currency-pairs-supported-in-margin-trading-deprecated

        :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>`
        NrW   rB   r:  rQ   )ry  r  r  r<  publicMarginGetUniCurrencyPairsr  parse_leverages)r}  r}  r  r  r  marketIdRequests         r  fetch_leverageszgate.fetch_leverages  s     	%%g.NN695	69--O;;FCH 88@H ##HgOOr  c                     | j                  |dd      }| j                  |d      }|| j                  ||dd      d ||dS )Nr:  rB   r  r  rQ   )r  r  r  longLeverageshortLeverage)r6  r  r  )r}  r  r  r  leverageValues        r  r  zgate.parse_leverage,  sR    %%hF))(J?&&xfE)*
 	
r  c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |d|      S )a  
        fetches option data that is commonly found in an option chain

        https://www.gate.io/docs/developers/apiv4/en/#query-specified-contract-detail

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

        https://www.gate.io/docs/developers/apiv4/en/#list-all-the-contracts-with-specified-underlying-and-expiration-time

        :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>`
        r*  rb  _USDTNrC   )ry  rR  r1  r  parse_option_chain)r}  rb  r  rR  r  r  s         r  fetch_option_chainzgate.fetch_option_chainq  si     	==&(6*W4
 11$++gv2NOV &&xv>>r  r^  c                    | j                  |d      }| j                  ||      }| j                  |d      }i d|dd d|d   d|d| j                  |      dd d	d d
| j	                  |d      d| j	                  |d      dd d| j	                  |d      d| j	                  |d      d| j	                  |d      dd dd dd dd S )NrC   r/  r  rR  r  r  r  impliedVolatilityopenInterestr  r  r  r  midPricer#  r  r  r  r  r  r  r  r3  r4  )r  r  r  r  r  )r}  r^  rR  r  r  r  s         r  r  zgate.parse_option  s]   R ##E62!!(F3''}=	
E

 fX&
 	

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

        https://www.gate.io/docs/developers/apiv4/#list-position-close-history
        https://www.gate.io/docs/developers/apiv4/#list-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   rg   r`  r  r  r  ra  rh   z: fetchPositionsHistory() does not support markets of type )ry  r  r  r  r  r<  r>  r  $privateFuturesGetSettlePositionCloser  %privateDeliveryGetSettlePositionCloser9   rB   r  )r}  r}  r  r  r  r  r  r  r`  r  r  s              r  fetch_positions_historyzgate.fetch_positions_history  sl   & 	LM!WQZ0
!??@WY_agiop
F!!&'267+..vz6J$GG"//=GFO --edl;GDM@@WV\A]^H8#AA$++gW]B^_Htww)eehrrss* ##Hgv>>r  reasonr]   rN  rv  rF  c
                     |y | j                  |d      }
|
=| j                  dz   |z   }| j                  | j                  d   |
|       t	        |      y )Nlabel ru  )r  rB   throw_exactly_matched_exceptionrx  r-   )r}  rb  r  r]   rN  rv  rF  r  requestHeadersrequestBodyr  feedbacks               r  handle_errorszgate.handle_errors1  sa       73ww}t+H001I5RZ[))r  )NNNNr  )NN)__name__
__module____qualname__r   r{  boolr  r  r  r   r  rD  r  r    r   r*   r  r,   r  r  r  r  r  r0  r>  rC  rE  rA  r  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  dictr  r#   r>  rH  r   r]  r  rs  rc  rz  r  r&   r  r  r  r  r)   r  r  floatr   r  r  r  r   r   r   r  r   r  r  r  r@  rF  rK  rV  r   r  rv  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   r1  r5  r  rd  ri  r   rh  rn  rp  rt  rz  r~  r  r  r}  r   r  r  r  r  r  r  r  r  r   r  r  r  r   r  r   r  r  r   r  r   r  r  r  r-  r  __classcell__)r~  s   @r  r?   r?      s   Z# Zx -t - *, .B 46 9 !# :s :"=
3 =
~VC V VRU Vjm V  zI V $& 9$v, 9> )+ iV -/ 0h
T +- xt& &*R !8 15eB  $ 7;ERT  *$:c ') [Z [z 68 <1 <1K <1| 6:" >;7 >; >;@G
6 G
[ G
R? ?A ## #J DF 0s 0$~J^ 0* 79 4# 4^ 4$
( 57 8 8;N 8@ )+ 1{ 16
f 
< 7;2 4G 4l <@ M MB. .` 37TX\eg .LC .Ls .LRU .L`OnI] O
& 
. :>b os o3 oY ob 02 '13 '1f '1Rn4 n n6 n` 04B %5W %57 %5N $& Q( Qf 26DW[df AL# ALc ALQT ALkoptku ALF 9=4^bkm L LS LX[ L 8<$]ajl 5Y 5YC 5YWZ 5Yn+ +4 +Z 6:UW hA3 hAs hA# hA\`af\g hAT 9=4^bkm 'S '# 'S 'X[ 'R -1tRV_a BAc BA BAC BAH_ _v _ _B *.Dt\^  ;3  ;c  ;  ;cghsct  ;D -1tRV_a  ;c  ;  ;C  ;fjkvfw  ;D DHPR &:S &:% &:# &:Wb &:P:s :$3k
T k
X k
Q\ k
Z gksu B23 B2i B2y B2RW B2`c B2H HJ D,> < @B +D$6 +0 os{} Q,3 Q,i Q,y Q,Z_ Q,hk Q,f RT N N5 N( hlz~  HJ ,S ,# ,Y ,i ,ad ,tw ,B `drv  @B 92S 92# 92Y 92i 92Y\ 92lo 92v: : { {v { {z :>b (c (3 (" 26b .2c .23 .2` /3TXac Q Q3 Qc Qhlmrhs Q& 154VZce 0A# 0AS 0APS 0Ajnotju 0Ad FJX\koxz &s &RU &eh &> <@daenp OS O O[^ OB 37r }2s }2C }2~ ;?r *+c *+C *+X SU $+5H0I $+L /32 E3 E3N [] 67S 67% 67c 67c 67an 67p
t 
x 
= 
, 9=R CS C# CJEt EV EN 24 R5S R5h 26b d7w d7T(^ d7L 7;2 sDG sD- sDj ?A B# BT,EW B<$|BT 8 $|J\ @ LN :C :s :: <> /:s /:b TV +:S +: +:U +:Z DF +: +:U +:Z3
 3
j 15DW[jnwy -Q# -Qc -QQT -Qdg -Q  C  DR  S -Q^
$ 
 
. 
"D  b$T LP\ @B @3 @*
d *
F *
N` *
X @B BC B BFX B =? A Ae ACU A BFTXgktv 5Q# 5Qc 5Qad 5Qn
F 
: 6:[_hj ,Os ,O# ,OUX ,O\ 9=4^bkm 2Y# 2YS 2YX[ 2Yh#
J"H (,$TZ\ hC hCC hCs hCaefqar hCTPt Px P; Pd)8V =A R Rc R" .0 !F <@d[] 'G 'GS 'G 'GR 37TX\eg GGC GGs GGRU GGR>V >@ 02 ,3 ,f ,\+
4 +
 +
6 +
Z =A JS J	 JPU J* 24 f5S f5 f5P 26b /Pw /PY /Pb	
t 	
V 	
x 	
 02 893 89f 89t 46 <?s <?+ <?|>
$ >
( >
6 >
]c >
@ :>D_cln @?w @?c @?Y\ @?sw  yA  tB @?D# s  c TX `c r  r?   )Dccxt.base.exchanger   ccxt.abstract.gater   rP  ccxt.base.typesr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   typingr,   ccxt.base.errorsr-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   ccxt.base.decimal_to_precisionr<   ccxt.base.preciser=   r?    r  r  <module>r'     s    ( *  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  * 0 - . - . ' & . ) * 5 ) . 1 4 %cx8[ cxr  