
    !:hNc                       d dl mZ d dlmZ d dlZd dlZd dlmZmZm	Z	m
Z
mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z- d dl.m/Z/ d dl0m1Z1 d dl0m2Z2 d dl0m3Z3 d d	l0m4Z4 d d
l0m5Z5 d dl0m6Z6 d dl0m7Z7 d dl0m8Z8 d dl0m9Z9 d dl0m:Z: d dl0m;Z; d dl0m<Z< d dl0m=Z= d dl0m>Z> d dl0m?Z? d dl@mAZA d dlBmCZC  G d dee      ZDy)    )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    Q/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/async_support/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                 P  K   | j                  | j                  d      }|O	 | j                  |       d{   }| j                  |di       }| j	                  |d      dk(  | j                  d<   | j                  d   S 7 H# t
        $ r}d| j                  d<   Y d}~.d}~ww xY w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_statusA  s      6FG!7 "&!=!=f!EE%<151B1B661RVW1W-. ||,-- F  716-.7s>   B&B A?9B 0B&?B 	B#
BB&B##B&c                 @   K   | j                  |       d {   S 7 wN)privateUnifiedPutUnifiedMode)r}  r  s     r  upgrade_unified_trade_accountz"gate.upgrade_unified_trade_accountb  s     66v>>>>s   c                 d   K   | j                  |       d{   }| j                  |d      S 7 w)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
        Nserver_time)publicSpotGetTimer  r}  r  r  s      r  
fetch_timezgate.fetch_timee  s5      //77   =99 8s   0.0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_marketv  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                   K   | j                   d   r| j                          d{    | j                  | j                   dd      }| j                  |      | j	                  |      g}|s$| j                  |      g}| j                  ||      }t        j                  |  d{   }| j                  |dg       }| j                  |dg       }| j                  |dg       }| j                  ||      }	| j                  |	|      S 7 7 cw)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  Nr  Fr   r   r  )
rR   load_time_differencer  fetch_contract_marketsfetch_option_marketsfetch_spot_marketsarray_concatasynciogather
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 55ooh26//(Ar:!R8##KA  -88 . 6s#   #D
DA>D
$D%A"D
D
c                 D  K   | j                  |      }| j                  |      }t        j                  ||g  d {   \  }}| 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 7 aw)(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publicSpotGetCurrencyPairsr  r  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  sj    99&A!<<VD4;NN]TfDg4h.h++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 M /is   :J JI!J c                   K   g }| j                  dd      }| j                  dd      }t        dt        |            D ]t  }||   }d|i}| j                  | j	                  ||             d {   }t        dt        |            D ](  }	| j                  ||	   |      }
|j                  |
       * v t        dt        |            D ]t  }||   }d|i}| j                  | j	                  ||             d {   }t        dt        |            D ](  }	| j                  ||	   |      }
|j                  |
       * v |S 7 7 Jw)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_marketsF  se    #'#A#A&.#Y %)%C%CHn%]"q#678 	,A/2H(G "AA$++gW]B^__H1c(m, ,#99(1+xPl+,	, q#89: 	,A1!4H(G "BB4;;wX^C_``H1c(m, ,#99(1+xPl+,	,  ` as&   A,E.E/BE:E;A	EE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                   K   g }| j                          d {   }t        dt        |            D ]  }||   }| j                  i |      }||d<   | j	                  |       d {   }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 7 .7 w)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     99;;q#k*+ t	A$QJKKF+E",E,!;;EBBHN 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 m <
 Cs#   MMAM&M	'K M	Mc                    K   | j                          d {   }g }t        dt        |            D ]-  }||   }| j                  |d      }||j	                  |       / |S 7 Mw)Nr   rC   )publicOptionsGetUnderlyingsr  r  r  r  )r}  underlyingsResponser   r  r,  rC   s         r  r2  zgate.fetch_option_underlyings  sy     $($D$D$FF q#123 	)A,Q/J##J7D""4(		)
 ! Gs   A&A$7A&A&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  r4  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 )rB  rY   rB   r  r<  )rC  rD  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  rI  r  isUnifiedAccounts         r  rC  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                   K   | j                  | j                  d      }|y| j                  d      r| j                          d{    | j	                  |       d{   }| 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 7 7 w)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  ra  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  rS  r  indexedCurrenciesr  r  entry
currencyIdr"  	partFirstcurrencyNamewithdrawDisableddepositDisabledtradeDisabledr  rd  isLeveragedTokenrealCurrencyIdr  	networkIdnetworkCodenetworkEntryr  s                           r  fetch_currencieszgate.fetch_currencies  s     OODII{;	 **51**,,,55f== !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 [ -=s%   AIIII G&IIc                 >  K   | j                          d{    | j                  |      }|d   st        | j                  dz         | j	                  |d|      \  }}| j                  | j                  ||             d{   }| j                  |      S 7 7 w)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>`
        Nrg   z0 fetchFundingRate() supports swap contracts only)load_marketsr  r4   rB   r@  'publicFuturesGetSettleContractsContractr  parse_funding_rate)r}  r  r  r  r  r4  r  s          r  fetch_funding_ratezgate.fetch_funding_rateX  s      !!!V$f~DGG&XXYY--fdFCEEdkkRY[`FabbZ &&x00e 	"
 cs"   BBA,BBBBsymbolsc                 T  K   | j                          d{    | j                  |      }d}|#| j                  |d      }| j                  |      }| j	                  |d|      \  }}| j                  | j                  ||             d{   }| j                  ||      S 7 7 w)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   )r{  market_symbolsr  r  r@  r  r  parse_funding_rates)r}  r  r  r  firstSymbolr  r4  r  s           r  fetch_funding_rateszgate.fetch_funding_rates  s      !!!%%g.**7A6K[[-F--fffE==dkk'SX>YZZZ '''::i 	" [s"   B(B$A6B(B&B(&B(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  rd  c                    K   | j                          d {    | j                  |      }d|d   i}| j                  | j                  ||             d {   }| j	                  |d      }| j                  |d      }| j                  |      }i }t        dt        |            D ]]  }	||	   }
| j                  |
d      }|r| j                  |
d      }| j                  |
d      }| j                  |
d      }|
||||d	||<   _ |S 7 7 w)
NrT  rB   multichain_addressesr   obtain_failedr`  address
payment_id)r  rd  rT  r  tag)
r{  rT  privateWalletGetDepositAddressr  r  r  r  r  r  r  )r}  rd  r  rT  r  r  	addressesrn  r  r  rm  obtainFailedrb  r  r  s                  r  fetch_network_deposit_addressz"gate.fetch_network_deposit_address)  s0    !!!==&
 <<T[[RX=YZZOOH.DE	%%h
;
&&z2q#i.) 	AaLE  ,,UODL&&ug6G&&ui8G""5,7C "F7O#	0 E 	"
 [s#   DD
A DDB3DDc                   K   | j                          d{    | j                  |      }d|d   i}| j                  | j                  ||             d{   }| j	                  |dg       }| j                  |d      }| j                  ||      }| j                  ||d   gdd|d   i      }| j                  |d      S 7 7 lw)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
        NrT  rB   r  rd  Frb  )	r{  rT  r  r  r  r  safe_currencyparse_deposit_addressesr  )	r}  rd  r  rT  r  r  chainsrn  parseds	            r  "fetch_deposit_addresses_by_networkz'gate.fetch_deposit_addresses_by_networkN  s      !!!==&
 <<T[[RX=YZZ+A2F%%h
;
%%j(;--fx7G6H%R
  }}VY// 	"
 [s#   CCA CCA+CCc                    K   | j                          d{    d}| j                  |      \  }}| j                  ||       d{   }| j                  |||      }||   S 7 L7 w)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)r{  handle_network_code_and_paramsr  )select_network_code_from_unified_networks)r}  rd  r  rw  chainsIndexedByIdselectedNetworkIds         r  fetch_deposit_addresszgate.fetch_deposit_addressc  sz      !!!"AA&IV"&"I"I$PV"WW JJ4Q\^op !233 	" Xs!   A'A#/A'A%A'%A'c           
          | j                  |d      }| j                  |       || j                  |d      || j                  |d      | j                  | j                  |d            dS )Nr  rd  r  r`  )r  rT  r  r  rb  )r  check_addressrh  )r}  depositAddressrT  r  s       r  parse_deposit_addresszgate.parse_deposit_addressu  sp     "">9=7#"((6:##NLA..t/?/?PW/XY
 	
r  c                    K   | j                          d{    | j                  |      }d|d   i}| j                  | j                  ||             d{   }| j	                  ||      S 7 W7 w)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>`
        Nr<  rB   )r{  r  privateWalletGetFeer  parse_trading_feer}  r  r  r  r  r  s         r  fetch_trading_feezgate.fetch_trading_fee  sy      !!!V$VD\
 11$++gv2NOO %%h77) 	"
 Ps"   A2A.A A2A0A20A2c                    K   | j                          d{    | j                  |       d{   }| j                  |      S 7 .7 w)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
        N)r{  r  parse_trading_feesr  s      r  fetch_trading_feeszgate.fetch_trading_fees  sI      !!!11&99 &&x00! 	"9s   A	AA	AA	A	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                 0  K   | j                          d{    | j                  |       d{   }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 7 7 w)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>`
        Nr   rT  withdraw_fix_on_chainswithdraw_fix)r   ra  r  )r{  privateWalletGetWithdrawStatusr  r  r  r  in_arrayr  r  listkeysr|  )r}  r  r  r  r  withdrawFeesr  rm  rn  rd  withdrawFixOnChains	chainKeysr5  chainKeys                 r  fetch_transaction_feeszgate.fetch_transaction_fees  s?     !!!<<VDD$ 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	( S 	"Ds    DDDDC#DDc                    K   | j                          d{    | j                  |       d{   }| j                  ||d      S 7 07 w)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>`
        NrT  )r{  r  parse_deposit_withdraw_fees)r}  r  r  r  s       r  fetch_deposit_withdraw_feesz gate.fetch_deposit_withdraw_fees 	  sM      !!!<<VDD( //%LL+ 	"Ds   AAAA	A	ArT  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  ra  )r  r   ra  r  r   rT  )r   ra  r  )	r  r  r  r  r  r  rh  r  r|  )	r}  r   rT  r  r  r  r  r  rw  s	            r  parse_deposit_withdraw_feezgate.parse_deposit_withdraw_feeA	  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                 4  K   | j                          d{    d}|| j                  |      }|d   }| j                  d||      \  }}| j                  |||      \  }}	d|d<   || j	                  |dz        |d<   |||d<   d}
|d	k(  r*| j                  | j                  ||	             d{   }
nG|d
k(  r*| j                  | j                  ||	             d{   }
nt        | j                  dz         | j                  |
|||      S 7 7 b7 5w)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)r{  r  handle_market_type_and_paramsr@  parse_to_int"privateFuturesGetSettleAccountBookr  #privateDeliveryGetSettleAccountBookr9   rB   parse_funding_histories)r}  r  r  r  r  r  r  r4  r  requestParamsr  s              r  fetch_funding_historyzgate.fetch_funding_historyq	  s;     !!![[(FH%F889NPVX^_e!%!5!5fdE!J "//=GFO$GG6>!DDT[[QXZgEhiiHX!EEdkkRY[hFijjHtww)hhii ++HfeUKKC 	"  jjs4   DDBD1D2.D D!2DDD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  rm  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  rd  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           	      0  K   | j                          d{    | j                  |      }| j                  ||d   |      \  }}|||d<   d|d<   d}|d   s|d   r*| j                  | j	                  ||             d{   }n|d   r*| j                  | j	                  ||             d{   }nv|d	   r*| j                  | j	                  ||             d{   }nG|d
   r*| j                  | j	                  ||             d{   }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 7 t7 7 7 7 w)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
        Nr  r  Twith_idrQ   rO   rg   rh   ri   z. fetchOrderBook() not support self market typecurrentr  r   pr   srB   bidsasksnonce)r{  r  r@  publicSpotGetOrderBookr  publicFuturesGetSettleOrderBook publicDeliveryGetSettleOrderBookpublicOptionsGetOrderBookr9   rB   r  parse_order_book)r}  r  r  r  r  r  r4  r  r  priceKey	amountKeyr  r  s                r  fetch_order_bookzgate.fetch_order_book	  s     !!!V$ --ffVnfM$GG!	&>VH-!88We9TUUHF^!AA$++gW\B]^^HH!BB4;;wX]C^__HH!;;DKKQV<WXXHtww)YYZZB %%h	:	f~!D(Iv1CAS	!!(D1&&xFFT\^ghwC 	"  V^_XsY   FF
A*FF.F0F1.FF .FFA<FFFFFc                 b  K   | j                          d{    | j                  |      }| j                  |d|      \  }}d}|d   s|d   r*| j                  | j	                  ||             d{   }n|d   r*| j                  | j	                  ||             d{   }n|d   r*| j                  | j	                  ||             d{   }nr|d   rU|d   }|j                  d      }| j                  |d	      |d
<   | j                  | j	                  ||             d{   }nt        | j                  dz         d}	|d   r/t        d	t        |            D ]  }
||
   }|d   |d   k(  s|}	 n n| j                  |d	      }	| j                  |	|      S 7 7 37 7 7 w)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   )r{  r  r@  publicSpotGetTickersr  publicFuturesGetSettleTickerspublicDeliveryGetSettleTickersr  r  publicOptionsGetTickersr9   rB   r  r  r  parse_ticker)r}  r  r  r  r  r4  r  r  r  tickerr  rm  s               r  fetch_tickerzgate.fetch_ticker2
  s     !!!V$--fdFC&>VH-!66t{{7E7RSSHF^!??GUZ@[\\HH!@@WV[A\]]HHd|H"..-K$($4$4[!$DGL!!99$++gu:UVVHtww)VVWW(1c(m,  =F4L0"F	 __Xq1F  005 	"
 T\]
 Ws`   F/F"AF/2F%3.F/!F(".F/F+AF/*F-+AF/8+F/%F/(F/+F/-F/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  r5  r6  r  s                    r  r  zgate.parse_ticker[
  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                 x  K   | j                          d{    | j                  |      }| j                  |d      }d}|| j                  |      }| j	                  d||      \  }}| j                  d||      \  }}d}	d|d<   |dk(  s|dk(  r*| j                  | j                  ||             d{   }	n|dk(  r*| j                  | j                  ||             d{   }	n|d	k(  r*| j                  | j                  ||             d{   }	n|d
k(  rh| j                  d|d       |d   }
|
j                  d      }| j                  |d      |d<   | j                  | j                  ||             d{   }	nt        | j                  dz         | j                  |	|      S 7 7 7 7 7 8w)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>`
        Nr   r   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)r{  r  r  r  r  r@  r  r  r  r  check_required_argumentr  r  r9   rB   parse_tickers)r}  r  r  firstr  r  r4  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-!66t{{7M7Z[[HV^!??GUb@cddHX!@@WVcAdeeHX(()Ld|H"..-K$($4$4[!$DGL!!99$++g}:]^^Htww  *q   q  r  r!!(G441 	" \de _sY   F:F/BF:4F25.F:#F4$.F:F6A,F:?F8 0F:2F:4F:6F:8F: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   r8  r  )r}  rm  rY   s      r  parse_balance_helperzgate.parse_balance_helper
  su    ,,.,,UHhG**5+>++E7;"..ujAGFOr  c                   K   | j                          d{    | j                          d{    | j                  |d      }| j                  |d      }d}| j	                  |dd      \  }}| j                  dd|      \  }}| j                  d||      \  }}| j                  d|      \  }}	|| j                  |      }
|
d   |d<   d}|r+| j                  | j                  ||             d{   }n|dk(  r|dk(  r+| j                  | j                  ||	             d{   }nK|d	k(  r+| j                  | j                  ||	             d{   }n|d
k(  r*| j                  | j                  ||	             d{   }nt        | j                  dz         |dk(  r*| j!                  | j                  ||	             d{   }n|dk(  r*| j#                  | j                  ||	             d{   }nv|dk(  r*| j%                  | j                  ||	             d{   }nG|dk(  r*| j'                  | j                  ||	             d{   }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 7 37 7 \7 *7 7 7 7 `7 47 w)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>`
        Nr  Fr   r  rB   r<  rQ   rO   r  z+ fetchBalance() not support self marginModer  rg   rh   ri   z, fetchBalance() not support self market typer  balancesr   rT  r  r  r  )r{  r  r  r>  rM  r  r@  rC  r  privateUnifiedGetAccountsr  privateSpotGetAccountsprivateMarginGetAccountsprivateMarginGetCrossAccountsr9   rB   privateMarginGetFundingAccountsprivateFuturesGetSettleAccounts privateDeliveryGetSettleAccountsprivateOptionsGetAccountsr  r  r  r  r  r  r  r  rJ  safe_balance) r}  r  r  rN  r  r4  r  r  r  requestQueryr  r  r  r  r  dataflatBalancesrL  r  r  rn  contentrm  r  symbolInnerr  r  baseCode	quoteCode	subResultrd  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$!;;DKKQW<XYYHV^V#!%!<!<T[[R^=_!``x'!%!>!>t{{7T`?a!bb~-!%!C!CDKKPWYeDf!gg"477-Z#Z[[Y!AA$++gWcBdeeHV^!AA$++gWcBdeeHX!BB4;;wXdCeffHX!;;DKKQ]<^__H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O 	"( Z abg fef_s   Q'Q	Q'QCQ'3Q44Q'(Q)/Q'Q/Q'Q	AQ'Q.Q'>Q?.Q'-Q!..Q'Q$G-Q'Q'Q'Q'Q'Q'Q'Q'!Q'$Q'r>  c           	        K   | j                          d{    | j                  |      }d}| j                  |dd      \  }}|r| j                  d|||||d       d{   S |d   r| j	                  |||||       d{   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!                  |	|             d{   }nX|d   rS| j#                  | j!                  |	|             d{   }n)| j%                  | j!                  |	|             d{   }| j'                  |||||      S 7 f7 7  7 {7 N7 &w)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)
        NFr   paginater  ri   r  r  r  r  untilr  r   tor  r  r  r  rB   rh   rg   )r{  r  rM  "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  ra  r  r  maxLimitrb  durationdistancetoTimestampcurrentTimestamprc  r  isMarkisIndexs                       r  fetch_ohlcvzgate.fetch_ohlcv  s    & !!!V$88zZ&@@vW\^cenpvx|}}}(00E5RXYYY  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!%!I!I$++V]_eJf!gg!%!H!HU\^dIe!ff!;;DKKQW<XYYH  69eUKK] 	"
 ~YD hfYsk   JI<A	J I?!!JJFJ	J
.J8J9)J"J	#J?JJJJ	Jc                 P  K   | j                          d {    | j                  |      }i }| j                  |d |      \  }}| j                  | j                  ||      |d<   | j                  | j                  ||             d {   }| j                  |||||      S 7 7 w)Nr  )r{  r  r@  r  r<  publicOptionsGetCandlesticksr  rl  )	r}  r  rm  r  r  r  r  r  r  s	            r  re  zgate.fetch_option_ohlcvQ  s     !!!V$..vtVD"..t	9U
::4;;wPV;WXX  69eUKK 	"
 Ys"   B&B"A1B&B$	B&$B&c           
        K   |t        | j                  dz         | j                          d{    d}| j                  |dd      \  }}|r| j	                  d|||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                  ||             d{   }	g }
t        dt        |	            D ]O  }|	|   }| j                  |d      }|
j!                  ||| j#                  |d      || j%                  |      d       Q | j'                  |
d      }| j)                  ||d   ||      S 7 7 f7 w)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   ra  rE  rg   z7 fetchFundingRateHistory() supports swap contracts onlyr  r  r  rb  rc  r   r#  r)r  r  r  r  r  r  r  )r2   rB   r{  rM  rd  r  r4   r@  r  r  r>  !publicFuturesGetSettleFundingRater  r  r  r  r  r  r!  r  r  )r}  r  r  r  r  ra  r  r  rb  r  ratesr  rm  r  r  s                  r  fetch_funding_rate_historyzgate.fetch_funding_rate_history[  s     >#DGG.e$eff!!!88AZ\fg&@@AZ\bdikprvx~V$f~DGG&__``..vtVD$GG"//=GFO!!&'2YYvw/F --edl;GDM??GU[@\]] q#h-( 		AQKE++E37ILL #//s;& LL3 		 e[1009I5RWXXK 	" @ ^s5   .GG7G(G)CG4G5BGGG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                   K   | j                          d{    d}| j                  |dd      \  }}|r| j                  d||||       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                  ||             d{   }
n|d   r*| j                  | j                  ||             d{   }
ny|d   r*| j                  | j                  ||             d{   }
nJ|d   dk(  r*| j                  | j                  ||             d{   }
nt        | j                  dz         | j!                  |
|||      S 7 7 7 7 7 m7 =w)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>`
        NFr   ra  rc  rb  r  r  r  r  r  rQ   rO   rg   rh   ri   z, fetchTrades() not support self market type.)r{  rM  fetch_paginated_call_dynamicr  r@  safe_integer_2r>  r  r  publicSpotGetTradesr  publicFuturesGetSettleTradespublicDeliveryGetSettleTradespublicOptionsGetTradesr9   rB   parse_trades)r}  r  r  r  r  ra  r  r  r4  rb  r  s              r  fetch_tradeszgate.fetch_trades  s    " !!!88PZ[&::=&RWY^`fgggV$, --fdFC##FD':YYvy1F --edl;GDM"5$/GG&"4"//=GFO&>V#vf~'A!55dkk'56QRRHF^!>>t{{7TY?Z[[HH!??GUZ@[\\HF^x'!88We9TUUHtww)WWXXR   65%@@o 	" hD S[\Usj   G-G6G-G"CG-G%.G-G'.G-;G)<1G--G+.2G-"G-%G-'G-)G-+G-rB   c                    K   |t        | j                  dz         | j                          d{    | j                  |||d|i       d{   }|S 7 $7 w)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>`
        Nz. fetchOrderTrades() requires a symbol argumentorder_id)r2   rB   r{  fetch_my_trades)r}  rB   r  r  r  r  r  s          r  fetch_order_tradeszgate.fetch_order_trades)  sf       >#DGG.^$^__!!!( --feUZQSDTUU+ 	"( Vs!   .AAAAAAc                   K   | j                          d{    | j                          d{    d}| j                  |dd      \  }}|r| j                  d||||       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                  ||             d{   }n|dk(  r*| j                  | j                  ||             d{   }nv|dk(  r*| j                  | j                  ||             d{   }nG|dk(  r*| j                  | j                  ||             d{   }nt!        | j"                  dz         | j%                  ||	||      S 7 97 $7 7 7 7 m7 @w)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>`
        NFr   ra  rb  rg   rh   ri   r  rB   r<  rY   r  r  r  rc  rQ   rO   z. fetchMyTrades() not support self market type.)r{  r  rM  r  r  r  r>  r  r@  rC  r  privateSpotGetMyTradesr  (privateFuturesGetSettleMyTradesTimerange privateDeliveryGetSettleMyTradesprivateOptionsGetMyTradesr9   rB   r  )r}  r  r  r  r  ra  r  r  r  r  rb  r  r  s                r  r  zgate.fetch_my_tradesR  s    4 !!!&&(((88R\]&::?FTY[`bhiii
)/);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-!88Wf9UVVHV^!JJ4;;W^`fKghhHX!BB4;;wX^C_``HX!;;DKKQW<XYYHtww)YYZZB   65%@@Q 	"( j4 Wh`Ysz   I II I6I %I&D*I I.I ?I .I .I/.I I2I I I I I I I 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   r1  r<  r  rQ   r  r  sizer  r  sellbuysider  r  r   gt_fee	point_feefee_currencyr  )r  rT  GT	GatePointroler  )r  rB   r  r  r  orderr  r  takerOrMakerr  r  r  r   rw  )r8  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                   K   | j                          d{    d}| j                  |dd      \  }}|r| j                  d||||       d{   S i }d}|| j                  |      }|d   |d<   |||d<   |.| j	                  |dz        }||d	<   | j                  |d
      |d<   | j                  d||      \  }}| j                  | j                  ||             d{   }	| j                  |	|      S 7 7 7 w)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>`
        NFr   ra  rB   rT  r  r  r   ' rc  )
r{  rM  r  rT  r  rg  handle_until_optionprivateWalletGetDepositsr  parse_transactions
r}  rd  r  r  r  ra  r  rT  startr  s
             r  fetch_depositszgate.fetch_depositsw  s+     !!!88R\]&::?DRWY^`fggg}}T*H"*4.GJ$GG%%edl3E#GFO HHU,=>GDM224&I66t{{7F7STT&&x::% 	" h U4   C?C96C?C;BC?"C=#C?;C?=C?c                   K   | j                          d{    d}| j                  |dd      \  }}|r| j                  d||||       d{   S i }d}|| j                  |      }|d   |d<   |||d<   |.| j	                  |dz        }||d	<   | j                  |d
      |d<   | j                  d||      \  }}| j                  | j                  ||             d{   }	| j                  |	|      S 7 7 7 w)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>`
        NFr   ra  rB   rT  r  r  r  r  rc  )
r{  rM  r  rT  r  rg  r  privateWalletGetWithdrawalsr  r  r  s
             r  fetch_withdrawalszgate.fetch_withdrawals  s-     !!!88ASU_`&::;MtUZ\acijjj}}T*H"*4.GJ$GG%%edl3E#GFO HHU,=>GDM224&I99$++gv:VWW&&x::% 	" k Xr  r  r  c                   K   | j                  ||      \  }}| j                  |       | j                          d{    | j                  |      }|d   || j	                  ||      d}|||d<   d}| j                  |      \  }}|| j                  |      |d<   | j                  | j                  ||             d{   }	| j                  |	|      S 7 7 w)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>`
        NrB   )rT  r  r  memor`  )
handle_withdraw_tag_and_paramsr  r{  rT  currency_to_precisionr  network_code_to_id!privateWithdrawalsPostWithdrawalsr  parse_transaction)
r}  rd  r  r  r  r  rT  r  rw  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??GU[@\]] %%h99/ 	" ^s"   :CCBCCCC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 )Nra  
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  ra  r  r   
fee_amountr`  rT  txidr  r  r  r  r  rb  	addressToaddressFromr  tagTotagFromr  r  updatedrT  r  )internalcommentr   )r  r=   	string_gtr  r  r8  r  safe_string_upperr  r  r  r|  rh  r!  )r}  r  rT  rB   r  r  feeCostStringrv  rn  rd  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                 h  K   | j                          d{    | j                          d{    | 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   r6|r| j                  |       d{   }n| j                  |       d{   }n|d	   r6|r| j                  |       d{   }nn| j                  |       d{   }nT|d
   r6|r| j                  |       d{   }n3| j                  |       d{   }n| j                  |       d{   }| j                  ||      S 7 7 s7 7 7 7 w7 X7 @7 (w)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>`
        Nr  r  	stopPricer  r  rQ   rO   rg   rh   )r{  r  r  r  safe_value_2create_order_requestprivateSpotPostOrdersprivateSpotPostPriceOrdersprivateFuturesPostSettleOrders#privateFuturesPostSettlePriceOrdersprivateDeliveryPostSettleOrders$privateDeliveryPostSettlePriceOrdersprivateOptionsPostOrdersparse_order)r}  r  r  r  r  r  r  r  r  r  r  r  isStopLossOrderisTakeProfitOrderisTpslnonTriggerOrderorderRequestr  s                     r  create_orderzgate.create_orderi  s    H !!!&&(((V$//&)4((MN//&2CD't3+47 5$5$*:'T/00tVUTZ[&>VH-!%!;!;L!II!%!@!@!NNF^!%!D!D\!RR!%!I!I,!WWH!%!E!El!SS!%!J!J<!XX!::<HHHB &11} 	"( JN SW TXHs   F2FF2F!B.F2F$F27F&8 F2F(F22F*3 F2F,F2-F..F2F0F2!F2$F2&F2(F2*F2,F2.F20F2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                 p  K   | j                          d{    | j                          d{    | j                  ||      }|d   }| j                  |d         }d}|d   r| j	                  |       d{   }n|d   r| j                  |       d{   }| j                  |      S 7 7 7 87 w)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>`
        Nr   r  rQ   rg   )r{  r  r  r  privateSpotPostBatchOrders#privateFuturesPostSettleBatchOrdersparse_orders)r}  r  r  r  
firstOrderr  r  s          r  create_orderszgate.create_orders  s      !!!&&(((33FFCAY
Z12&>!<<^LLHF^!EEnUUH  ** 	"( MUsD   B6B.B6B0A
B69B2:B6B4B60B62B64B6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   r2  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_precisionrC  rM  r  cost_to_precisionr6   number_to_stringr   r8  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                   K   | j                          d{    | j                          d{    | j                  |      }|d   st        | j                  dz         d|d<   | j                  |dd|d|       d{   S 7 m7 W7 w)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>`
        NrQ   z9 createMarketBuyOrderWithCost() supports spot orders onlyFr  r  r  )r{  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  s      !!!&&(((V$f~tww)ddee6;23&&vxdFSSS 	"(
 Ts2   B
BB
BAB
?B B
B
B
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_accountrM  r6   rB   strr.  parse_to_numericr=   r/  r1  r  )r}  rB   r  r  r  r  r  r  r  r  rY   rN  r6  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           	      b  K   | j                          d{    | j                          d{    | j                  |      }| j                  |||||||      }	d}
|d   r| j	                  |	       d{   }
n| j                  |	       d{   }
| j                  |
|      S 7 7 z7 47 w)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   )r{  r  r  rI  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_`&>!??PPH!FFWWH@ &11Q 	"(
 QWsD   B/B'B/B)AB/6B+7B/B-B/)B/+B/-B/c                 D    dddddddddddd}| j                  |||      S )Nr1  closedr  )r1  _newfilled	cancelled
liquidatedr  r  expiredfinishedfinish	succeededr  r  s      r  parse_order_statuszgate.parse_order_statusf  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 )@NrX  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  r1  r  r1  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  r4  r  r   )rR  	remainingr   rw  r   r  )r  
safe_orderr  r  r  safe_string_upper_2r8  r  safe_number_2r=   string_equalsr  r7  r  r  r  r  r  r/  r  rY  r  r|  r  r!  )"r}  r  r  rX  r   r  r  r  r  r  r  r  r!  remainingStringr  r  r4  r7  r  r  rg  r  exchangeSymbolr  rw  r  r   rX   numFeeCurrenciesmultipleFeeCurrenciesr  ri  rY   averageStrings"                                     r  r  zgate.parse_orderv  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ru  rv  r  r  r%  r   r#  r'  r   rg   rh   ri   r  )r  safe_bool_nr>  r8  r  r@  rE  rG  )r}  rB   r  r  r  r  r%  r  r  r4  r  r  r  s                r  fetch_order_requestzgate.fetch_order_requests  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                 D  K   | j                          d{    | j                          d{    |dn| j                  |      }| j                  d||      }| j	                  |d      }| j                  |g dd      }| j                  |||      \  }}	d}
|dk(  s|dk(  rW|r+| j                  | j                  ||	             d{   }
n'| j                  | j                  ||	             d{   }
n|dk(  rV|r*| j                  | j                  ||	             d{   }
n| j                  | j                  ||	             d{   }
n|d	k(  rV|r*| j                  | j                  ||	             d{   }
nq| j                  | j                  ||	             d{   }
nG|d
k(  r*| j                  | j                  ||	             d{   }
nt        | j                   dz         | j#                  |
|      S 7 7 7 F7 7 7 7 7 p7 Cw)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   rt  FrQ   rO   rg   rh   ri   z* fetchOrder() not support self market type)r{  r  r  r  r  rx  ry   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-!%!F!Ft{{SZ\iGj!kk!%!A!A$++gWdBe!ffV^!%!O!OPTP[P[\cerPs!tt!%!J!J4;;W^`mKn!ooX!%!P!PQUQ\Q\]dfsQt!uu!%!K!KDKKX_anLo!ppX!@@WVcAdeeHtww)UUVV&117 	"( lf uo vpes   H H
H HBH 
H*H 5H60H &H')H H0H H)H +H,.H H0H H H H H H H H H c                 H   K   | j                  d||||       d{   S 7 w)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>`
        r1  N)fetch_orders_by_status)r}  r  r  r  r  s        r  fetch_open_orderszgate.fetch_open_orders  s'     " 00vVVVVs   " "c                   K   | j                          d{    | j                          d{    | j                  |d      }d}|| j                  |      }|d   }| j	                  d||      }| j                  |d      }d}	| j                  |ddd      \  }	}|	s&|||dk7  r| j                  d	||||       d{   S | j                  |d
      }i }
| j                  |||      \  }
}|| j                  |dz        |
d<   |)| j                  |d      }| j                  |dz        |
d<   |||
d<   | j                  | j                  |
|             d{   }| j                  ||||      S 7 a7 L7 7  w)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>`
        Nrb  r  r   r   F
historicalrg   rV  r  r  r  rc  r  )r{  r  r  r  r  r  rM  r  r>  r@  r  &privateFuturesGetSettleOrdersTimeranger  r  )r}  r  r  r  r  rb  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44ZPUW]^^^66*..vtVD"//=GFOYYvw/F --edl;GDM$GGDDT[[QXZ`Eabb  65%@@1 	"( _ csE   FE7FE:BF E=BFE?F:F=F?F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  rv  fetchOrdersByStatusrQ   rO   rY   rP  rV  r  r  r  r  rb  rc  lastIdlast_id)	r  handle_param_bool_2r  rG  r@  r>  r  r  handle_param_string_2)r}  r  r  r  r  r  r  r  r  rQ   r  rb  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                   K   | j                          d {    | j                          d {    d }|| j                  |      }|d   }| j                  |dd      }| j	                  d||      }| j                  |d      }	| j                  |||||      \  }
}|	dk(  xs |	dk(  }|dk(  }|xr |xr | }d }|r|sX|r+| j                  | j                  |
|             d {   }nR| j                  | j                  |
|             d {   }n'| j                  | j                  |
|             d {   }n|	d	k(  rV|r*| j                  | j                  |
|             d {   }n| j                  | j                  |
|             d {   }n|	d
k(  rV|r*| j                  | j                  |
|             d {   }nq| j                  | j                  |
|             d {   }nG|	dk(  r*| j                  | j                  |
|             d {   }nt!        | j"                  dz         |}|rCg }t%        dt'        |            D ])  }| j)                  ||   d      }| j+                  ||      }+ | j-                  ||||      }| j/                  ||||      S 7 7 7 7 7 ~7 P7 )7 7 7 w)Nr  r  rv  r  r   rQ   rO   r1  rg   rh   ri   z+ fetchOrders() not support self market typer  )r{  r  r  safe_bool_2r  r  r  privateSpotGetOpenOrdersr  privateSpotGetOrdersprivateSpotGetPriceOrders"privateFuturesGetSettlePriceOrdersprivateFuturesGetSettleOrders#privateDeliveryGetSettlePriceOrdersprivateDeliveryGetSettleOrdersprivateOptionsGetOrdersr9   rB   r  r  r  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  s    !!!&&((([[(FH%F((FC001FPVWQ'!%!F!FvvW\^cek!l5DH$4&
<*<W%)%B%B4;;wXeCf%ggH%)%>%>t{{7Ta?b%ccH!%!?!?GUb@c!ddV^!%!H!HU\^kIl!mm!%!C!CDKKPWYfDg!hhX!%!I!I$++V]_lJm!nn!%!D!DT[[QXZgEh!iiX!99$++g}:]^^Htww)VVWWf F1c(m, @"oohqk8D**6;?@ ""665%@00NN} 	"("  hcd nh oi^s   KJ-KJ0B6K%J3&*KJ6*K;J9<0K,J<-)KJ?0KK)K1K2.K K!BK0K3K6K9K<K?KKKKc                   K   | j                          d{    | j                          d{    |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(  rW|r+| j                  | j                  ||	             d{   }
n'| j                  | j                  ||	             d{   }
n|dk(  rV|r*| j                  | j                  ||	             d{   }
n| j                  | j                  ||	             d{   }
n|d	k(  rV|r*| j                  | j                  ||	             d{   }
nq| j                  | j                  ||	             d{   }
nG|d
k(  r*| j                  | j                  ||	             d{   }
nt!        | j"                  dz         | j%                  |
|      S 7 7 7 F7 7 7 7 7 p7 Cw)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>`
        Nrw  Frn   rQ   rO   r  rg   rh   ri   z+ cancelOrder() not support self market type)r{  r  r  rx  r>  r  rE  r@  #privateSpotDeletePriceOrdersOrderIdr  privateSpotDeleteOrdersOrderId,privateFuturesDeleteSettlePriceOrdersOrderId'privateFuturesDeleteSettleOrdersOrderId-privateDeliveryDeleteSettlePriceOrdersOrderId(privateDeliveryDeleteSettleOrdersOrderId!privateOptionsDeleteOrdersOrderIdr9   rB   r  )r}  rB   r  r  r  r  r  r4  r  r  r  s              r  cancel_orderzgate.cancel_order  sY      !!!&&((( .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-!%!I!I$++V]_lJm!nn!%!D!DT[[QXZgEh!iiV^!%!R!RSWS^S^_fhuSv!ww!%!M!MdkkZacpNq!rrX!%!S!STXT_T_`givTw!xx!%!N!Nt{{[bdqOr!ssX!CCDKKPWYfDghhHtww)VVWWd &11[ 	"( oi xr yshs   IH1IH4CI1H72*IH:0IH=)I7H?80I(I))II.II0I4I7I:I=I?IIIIidsc                   K   | j                          d{    | j                          d{    d}|| j                  |      }d}|dn|d   }| j                  |d|      }| j	                  d||      \  }}|dk(  }|r|t        | j                  dz         |rQg }	t        dt        |            D ]  }
||
   }||d}|	j                  |        | j                  |	|       d{   S d|i}|g}t        dt        |            D ]  }
|j                  ||
           | j                  |       d{   }| j                  |      S 7 97 $7 i7 w)	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  )r{  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_ordersX  s     !!!&&((([[(F#)>x8H''-H99.&RXYf&.v~#DGG.i$ijjN1c#h' 1V$#	 %%i01 77OOOf
 I	q#c(# 	%ASV$	%GG	RR  **; 	"(( P SsE   EEEEB<E+E,AE9E:EEEEc                   K   | j                          d{    | j                          d{    g }t        dt        |            D ]r  }||   }| j	                  |d      }| j                  |      }|d   st        | j                  dz         | j	                  |d      }||d   d}	|j                  |	       t | j                  |       d{   }
| j                  |
      S 7 7 7 w)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>`
        Nr   r  rQ   z4 cancelOrdersForSymbols() supports only spot marketsrB   )rB   r<  )r{  r  r  r  r  r  r9   rB   r   privateSpotPostCancelBatchOrdersr  )r}  r  r  r  r  r  r  r  rB   r  r  s              r  r  zgate.cancel_orders_for_symbols  s      !!!&&(((q#f+& 	-A1IE%%eX6F[[(F&>"477-c#cdd!!%.B!'I !!),	- >>~NN   **1 	"( Os2   C/C)C/C+B$C/C-C/+C/-C/c                 z  K   | j                          d{    | j                          d{    |dn| j                  |      }| j                  |dd      }| j	                  |ddg      }| j                  d||      \  }}|dk(  r| j                  |||      n| j                  |||      \  }}d}	|dk(  s|dk(  rW|r+| j                  | j                  ||             d{   }	n'| j                  | j                  ||             d{   }	n|dk(  rV|r*| j                  | j                  ||             d{   }	n| j                  | j                  ||             d{   }	n|dk(  rV|r*| j                  | j                  ||             d{   }	nq| j                  | j                  ||             d{   }	nG|d	k(  r*| j                  | j                  ||             d{   }	nt!        | j"                  d
z         | j%                  |	|      S 7 7 7 F7 7 7 7 7 p7 Cw)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>`
        Nrv  r  rm   rQ   rO   rg   rh   ri   z/ cancelAllOrders() not support self market type)r{  r  r  r  r>  r  rG  r@  privateSpotDeletePriceOrdersr  privateSpotDeleteOrders%privateFuturesDeleteSettlePriceOrders privateFuturesDeleteSettleOrders&privateDeliveryDeleteSettlePriceOrders!privateDeliveryDeleteSettleOrdersprivateOptionsDeleteOrdersr9   rB   r  )
r}  r  r  r  r  r  r4  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-!%!B!B4;;wXeCf!gg!%!=!=dkk'S`>a!bbV^!%!K!KDKKX_anLo!pp!%!F!Ft{{SZ\iGj!kkX!%!L!LT[[Y`boMp!qq!%!G!GT[]jHk!llX!<<T[[R_=`aaHtww)ZZ[[:   622o 	"( hb qk rlas   H;H%H;H(B6H;%H+&*H;H.0H;H1)H;+H3,0H;H5)H;H7.H;5H960H;(H;+H;.H;1H;3H;5H;7H;9H;fromAccount	toAccountc                   K   | j                          d{    | 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                  |
|             d{   }| j                  ||      S 7 M7 w)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>`
        NrB   rT  r  r  rO   r  r<  rc  r  zA transfer requires params["symbol"] for isolated margin transfersrN   rP   r  )r{  rT  rF  r  rR   r8  r2   rB   r  r>  privateWalletPostTransfersr  parse_transfer)r}  rd  r  r  r  r  rT  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88Wf9UVV ""8X66Q 	"8 Ws"   E(E#D5E(E&E(&E(r   c           
      Z    | j                  |d      d d | j                  d |      d d d d |d	S )Ntx_id)	rB   r  r  rT  r  r  r  r  r  )r  r  )r}  r   rT  s      r  r  zgate.parse_transfer)  sC     ""8W5//h?

 
	
r  r  c                   K   |t        | j                  dz         |dk  s|dkD  rt        | j                  dz         | j                          d{    | 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                  ||             d{   }|S |d   r+| j                  | j                  ||             d{   }|S t        | j                  dz         7 7 Q7 #w)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  rI  cross_leverage_limitr  r  r  r  rg   rh   z+ setLeverage() not support self market type)r2   rB   r3   r{  r  r@  r8  rR   r  r3  1privateFuturesPostSettlePositionsContractLeverager  2privateDeliveryPostSettlePositionsContractLeverager9   )r}  r  r  r  r  r  r4  rI  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&>!SSTXT_T_`ginToppH@ ? H!TTUYU`U`ahjoUpqqH< 9 tww)VVWW+ 	"" qqs7   AE2E+C	E2E./E2E0E2.E20E2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  lastUpdateTimestamprc  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  r8  r=   r  r  r   r  r  r  safe_positionr!  r|  r  rl  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                   K   | j                          d{    | j                  |      }|d   st        | j                  dz         i }| j	                  ||d   |      \  }}| j                  ||      }d}|d   r| j                  |       d{   }n@|d   r| j                  |       d{   }n!|d   dk(  r| j                  |       d{   }| j                  ||      S 7 7 Y7 <7 w)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>`
        Nr  z/ fetchPosition() supports contract markets onlyr  rg   rh   ri   )
r{  r  r3   rB   r@  r  (privateFuturesGetSettlePositionsContract)privateDeliveryGetSettlePositionsContract"privateOptionsGetPositionsContractr  )r}  r  r  r  r  rM  r  s          r  fetch_positionzgate.fetch_position  s      !!!V$j!TWW'XXYY..vvf~vN++gv6&>!JJ?[[HH!KKO\\HF^x'!DD_UUHr ""8V44M 	" \\UsF   C1C)A:C1C+C10C-1!C1C/C1+C1-C1/C1c                   K   | j                          d{    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                  ||             d{   }	n]|dk(  r*| j                  | j                  ||             d{   }	n.|dk(  r)| j                  | j                  ||             d{   }	| j                  |	|      S 7 N7 w7 J7 w)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   )r{  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_  s     !!!%%gtT4FLMq WQZ099:JFTZ[fLdfnD8"!$<&nnS1(,(8(8a(H%"224vFOGV6>!BB4;;wX^C_``HX!CCDKKPWY_D`aaHX!<<T[[RX=YZZHz ##Hg66m 	"* aaZsF   E-E$CE-/E'0.E-E).E-E+E-'E-)E-+E-c                   K   | j                          d{    | j                  dd|      \  }}| j                  d||      \  }}|dk7  r|dk7  rt        | j                  dz         d}|dk(  r*| j                  | j                  ||             d{   }nG|dk(  r*| j                  | j                  ||             d{   }nt        | j                  dz         | j                  ||d      S 7 7 a7 4w)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
        Nr   rh   rg   z1 fetchLeverageTiers only supports swap and futurez2 fetchLeverageTiers() not support self market typerC   )
r{  r  r@  r3   rB   r  r  r
  r9   parse_leverage_tiers)r}  r  r  r  r4  r  r  r  s           r  fetch_leverage_tierszgate.fetch_leverage_tiers  s      !!!889MtU[\e!%!5!5dD%!H8TWW'ZZ[[6>!AA$++gWdBeffHX!BB4;;wXeCfggHtww)]]^^z ((7FCCQ 	" ggs4   C:C4A=C:C6.C:C81C:6C:8C:c                 v  K   | j                          d{    | j                  |      }| j                  d||      \  }}| j                  |||      \  }}|dk7  r|dk7  rt	        | j
                  dz         | j                  | j                  ||             d{   }| j                  ||      S 7 7 w)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>`
        Nr   rh   rg   z7 fetchMarketLeverageTiers only supports swap and future)	r{  r  r  r@  r3   rB   %privateFuturesGetSettleRiskLimitTiersr  parse_market_leverage_tiers)	r}  r  r  r  r  r4  r  r  r  s	            r  fetch_market_leverage_tiersz gate.fetch_market_leverage_tiers:  s      !!!V$889SU[]cde!%!5!5fdE!J8TWW'``aaCCDKKPWYfDghh //&AA% 	" is"   B9B5BB9B7B97B9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  rT  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_tiersX  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  rg  )r}  r  r  r	  r  r  itemr
  s           r  r  z gate.parse_market_leverage_tierst  s     $%55dFCCq#d)$ 	&A7D**4>KLLA *"6N**)-)9)9$@R)S#//nE	 	 &K	& r  c                 b  K   | j                          d{    | j                  |      }|d   j                         | j                  ||      d}| j	                  |      }|d   |d<   d|d<   | j                  | j                  ||             d{   }| j                  ||      S 7 7 w)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>`
        NrB   r  r<  repayr  r{  rT  upperr  r  privateMarginPostUniLoansr  parse_margin_loan)	r}  r  rd  r  r  rT  r  r  r  s	            r  repay_isolated_marginzgate.repay_isolated_margin  s      !!!==& ,,.00v>
 V$#)$< !77GV8TUU %%h99 	" Vs"   B/B+A=B/B-B/-B/c                   K   | j                          d{    | j                          d{    | j                  |      }|d   j                         | j	                  ||      d}d}| j                  |dd      \  }}d}|r/d|d<   | j                  | j                  ||             d{   }n;| j                  | j                  ||             d{   }| j                  |d	      }| j                  ||      S 7 7 7 V7 .w)
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>`
        NrB   r  Fr   r  r  r  r   )r{  r  rT  r  r  rM  privateUnifiedPostLoansr   privateMarginPostCrossRepaymentsr  r  r}  rd  r  r  rT  r  rN  r  s           r  repay_cross_marginzgate.repay_cross_margin  s     !!!&&(((==& ,,.00v>
 !#'#@#@I[]m#n &%GFO!99$++gv:VWWH!BB4;;wX^C_``H~~h2H" %%h99A 	"( X`sD   D
DD
DB D
/D0)D
D)D
D
D
D
c                 f  K   | j                          d{    | j                  |      }|d   j                         | j                  ||      d}d}| j	                  |      }|d   |d<   d|d<   | j                  | j                  ||             d{   }| j                  ||      S 7 7 w)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>`
        NrB   r  r<  borrowr  r  )	r}  r  rd  r  r  rT  r  r  r  s	            r  borrow_isolated_marginzgate.borrow_isolated_margin  s      !!!==& ,,.00v>
 V$#)$< "77GV8TUU( %%h99= 	" Vs"   B1B-A?B1B/B1/B1c                   K   | j                          d{    | j                          d{    | j                  |      }|d   j                         | j	                  ||      d}d}| j                  |dd      \  }}d}|r/d|d<   | j                  | j                  ||             d{   }n)| j                  | j                  ||             d{   }| j                  ||      S 7 7 7 D7 w)	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>`
        NrB   r  Frk   r  r&  r  )
r{  r  rT  r  r  rM  r!  r  privateMarginPostCrossLoansr  r#  s           r  borrow_cross_marginzgate.borrow_cross_margin  s      !!!&&(((==& ,,.00v>
 !#'#@#@I\^n#o &&GFO!99$++gv:VWWH!==dkk'SY>Z[[H %%h99; 	"( X[sD   C8C0C8C2B C8/C40)C8C6C82C84C86C8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 )NrI  r  r  r1  r  rT  r<  rB   r  r  rO   )rB   rT  r  r  r  r  r  )	r8  rR   r  r  r  r  r  r  r!  )r}  r  rT  r  r  rn  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                   K   | j                          d{    | j                          d{    d}| j                  |dd      \  }}i }| j                  d||      \  }}d}|| j	                  |      }|d   |d<   d}	|| j                  |      }	|||d<   |||d	<   d}
d}| j                  d|d
      \  }}|r*| j                  | j                  ||             d{   }
ng|dk(  r4|	|	d   |d<   | j                  | j                  ||             d{   }
n.|d
k(  r)| j                  | j                  ||             d{   }
| j                  |
|	      }| j                  ||||      S 7 `7 K7 7 a7 4w)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>`
        NFr   r  rc  rB   rT  r  r  r  r  r<  )r{  r  rM  r  rT  r  handle_margin_mode_and_params privateUnifiedGetInterestRecordsr  "privateMarginGetUniInterestRecords$privateMarginGetCrossInterestRecordsparse_borrow_interestsfilter_by_currency_since_limit)r}  rd  r  r  r  r  rN  r  rT  r  r  r  interests                r  fetch_borrow_interestzgate.fetch_borrow_interestq  s      !!!&&((( #'#@#@I^`p#q &224&I}}T*H"*4.GJ[[(F#GFO$GG
!??@UW]_fg
F!BB4;;wX^C_``H:%!+1$<(!DDT[[QXZ`EabbH7"!FFt{{SZ\bGcddH..x@228T5%PP; 	"(( a cdsV   FE6FE9B4F#E<$8FE>.FF +F9F<F>F F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  r1  r  rT  r3  actual_rate)	r  r  rT  r3  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/  r;  DELETEPATCHzcurrencies=z%2C,r4  sha512r  z/api/
zapplication/json)KEY	TimestampSIGNzContent-Type)r]   rP  bodyrv  )"r>  extract_paramsr  rg  r  implode_paramsr  r  r  r  r  r  rL   r9   rB   	urlencodere  r  r  replacejsonhashencoder  r  rG  rH   r  joinhmacru  hashlibrD  rt  )!r}  pathrb   rP  r  rv  rI  authenticationr  r4  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                   K   | j                          d {    | j                  |      }| j                  |d |      \  }}| j                  |      |d<   d }|d   r*| j	                  | j                  ||             d {   }nG|d   r*| j                  | j                  ||             d {   }nt        | j                  dz         | j                  ||      S 7 7 `7 3w)Nr  rg   rh   z2 modifyMarginHelper() not support self market type)
r{  r  r@  r3  /privateFuturesPostSettlePositionsContractMarginr  0privateDeliveryPostSettlePositionsContractMarginr9   rB   parse_margin_modification)r}  r  r  r  r  r  r4  r  s           r  modify_margin_helperzgate.modify_margin_helper  s     !!!V$--fdFC 11&9&>!QQRVR]R]^eglRmnnHH!RRSWS^S^_fhmSnooHtww)]]^^--h?? 	" oos4   C&C A*C&C".C&0C$10C&"C&$C&rW  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  rG  rd  r  r  r  )r  r  r  r  )r}  rW  r  r  rG  s        r  rk  zgate.parse_margin_modification  sv    8 ##D*5!!(FCD  x0X&$OOFG4
 	
r  c                 F   K   | j                  || |       d{   S 7 w)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>`
        Nrl  r}  r  r  r  s       r  reduce_marginzgate.reduce_margin<  s%      ..vwGGGGs   !!c                 D   K   | j                  |||       d{   S 7 w)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>`
        Nro  rp  s       r  
add_marginzgate.add_marginJ  s#      ..vvvFFFFs     r?  c           	        K   | j                          d{    d}| j                  |ddd      \  }}|r| j                  d|||||d       d{   S | j                  |      }|d   st	        | j
                  dz         |d   |d	   | j                  | j                  ||      d
}|||d<   |||d<   | j                  | j                  ||             d{   }	| j                  |	|||      S 7 7 7 w)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:
        NFr   ra  r  rg   z/ fetchOpenInterest() supports swap markets onlyrB   r  )r  r  r  r  r  )r{  rM  rd  r  r3   rB   r  r<  #publicFuturesGetSettleContractStatsr  parse_open_interests_history)
r}  r  rm  r  r  r  ra  r  r  r  s
             r  fetch_open_interest_historyz gate.fetch_open_interest_historyX  s;     !!!88A[]gino&@@A[]cejlqs|  E  GJ  K  K  KV$f~TWW'XXYYtZ((()YO

 $GG#GFOAA$++gW]B^__, 0065%PPO 	" K `s4   C;C59C;C7BC;C9C;7C;9C;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}  r3  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                 4  K   |t        | j                  dz         | j                          d{    | j                  |      }d}| j	                  d||      \  }}|dk7  rt        | j                  dz         |d   }|j                  d      }d| j                  |d	      i}	|||	d
<   |||	d<   | j                  | j                  |	|             d{   }
| j                  |
|      }| j                  |d      }| j                  ||||      S 7 7 >w)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   r{  r  r  r9   r  r  publicOptionsGetSettlementsr  parse_settlementsr  r  )r}  r  r  r  r  r  r  r  r  r  r  r   r  s                r  fetch_settlement_historyzgate.fetch_settlement_history  s5     >#DGG.d$dee!!!V$99:RTZ\bcf8tww)aabb$<nnS)$**;:
 #GFO$GG99$++gv:VWW ,,Xv>k;700NN= 	" Xs"   .DDB&DD=DDc                   K   |t        | j                  dz         | j                          d{    | j                  |      }d}| j	                  d||      \  }}|dk7  rt        | j                  dz         |d   }|j                  d      }| j                  |d      |d	}	|||	d
<   |||	d<   | j                  | j                  |	|             d{   }
| j                  |
di       }| j                  |dg       }| j                  ||      }| j                  |d      }| j                  ||d   ||      S 7 7 hw)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   r{  r  r  r9   r  r  privateOptionsGetMySettlementsr  r  r  r  r  )r}  r  r  r  r  r  r  r  r  r  r  r  rW  r   r  s                  r  fetch_my_settlement_historyz gate.fetch_my_settlement_history  sb     >#DGG.f$fgg!!!V$99:TV\^def8tww)ccdd$<nnS)**;: 
 #GFO$GG<<T[[RX=YZZ  8R8vvr2,,T6:k;7009I5RWXXI 	"  [s#   .ED>B'EEA&EE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_settlements3  sH    > q#k*+ 	IAMM$//AGH	Ir  c                   K   | j                          d{    d}| j                  |dd      \  }}|r| j                  d||||       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                  |	|             d{   }n|dk(  r*| j                  | j                  |	|             d{   }n|d	k(  r*| j                  | j                  |	|             d{   }n]|d
k(  r*| j                  | j                  |	|             d{   }n.|dk(  r)| j                  | j                  |	|             d{   }| j                  ||||      S 7 7 7 7 7 7 S7 &w)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>`
        NFr   ra  rQ   rO   rB   rT  rg   rh   r  r  r  r  r  rc  ri   )r{  rM  r  r  rT  r=  r>  r  privateSpotGetAccountBookr  privateMarginGetAccountBookr  r  privateOptionsGetAccountBookparse_ledger)r}  rd  r  r  r  ra  r  rT  r  r  r?  r  s               r  fetch_ledgerzgate.fetch_ledgerW  s8    $ !!!88PZ[&::=$PUW\^deee99-vVfFN 0==.&.tn
#FN 0'+v~FEM++FHmLFYYvx0F &GH#GFO$GG224&I6>!;;DKKQW<XYYHX!==dkk'SY>Z[[HV^!DDT[[QXZ`EabbHX!EEdkkRY[aFbccHX!>>t{{7TZ?[\\Hj   8UEBBm 	" f* Z[bc\s|   HG46HG7CHG: .HG<.H=G>>.H,H -.HHH7H:H<H>H HH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inrT  r  r   r  r  balancerB   )r  rB   	directionrY   referenceAccountreferenceIdr  rT  r  r  r  beforeafterr  r   )r  r=   r  r  r  r  r0  r|  r  safe_ledger_entryparse_ledger_entry_typer  r!  r  )r}  r  rT  r  r  rn  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 ),Nra  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   r3  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                    K   || j                  |      nd}| j                  |d|      \  }}||d<   | j                  | j                  ||             d{   S 7 w)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  r4  s          r  set_position_modezgate.set_position_mode>  sb      *0);V$$--fffE%::4;;wPU;VWWWWs   AAAAc                   K   | j                          d{    d}| j                  dd|      \  }}||dk(  rd}|dk7  rt        | j                  dz         | j	                  |       d{   }g }t        dt        |            D ]-  }||   }| j                  |d      }||j                  |       / |S 7 7 Ow)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   )	r{  r  r9   rB   r9  r  r  r  r  )r}  r  r  r  r   r  r,  rC   s           r  fetch_underlying_assetszgate.fetch_underlying_assetsO  s      !!!
!??@WY]_ef
FJ&$8!J!tww)``aa99&AA q#h-( 	)A!!J##J7D""4(		)
 / 	" Bs(   B?B;AB?-B=.7B?&B?=B?c                 v  K   | j                          d{    | j                  |      }|d   st        | j                  dz         |d   |d   d}|||d<   |||d<   | j	                  d	||      \  }}| j                  | j                  ||             d{   }| j                  ||||      S 7 7 w)
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>`
        Nrg   z/ fetchLiquidations() supports swap markets onlyr  rB   )r  r  r  r  rc  )r{  r  r9   rB   r  publicFuturesGetSettleLiqOrdersr  parse_liquidations)r}  r  r  r  r  r  r  r  s           r  fetch_liquidationszgate.fetch_liquidationsr  s      !!!V$f~tww)ZZ[[Z(t
 #GFO$GG224&I==dkk'SY>Z[[ &&xFF5 	" \s"   B9B5BB9B7B97B9c                   K   |t        | j                  dz         | j                          d{    | 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                  ||             d{   }n|d   r*| j                  | j                  ||             d{   }nP|d
   r*| j                  | j                  ||             d{   }n!t        | j                  dz   |d   z   dz         | j                  ||||      S 7 +7 7 n7 Aw)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   r{  r  r  r  !privateFuturesGetSettleLiquidatesr  "privateDeliveryGetSettleLiquidatesprivateOptionsGetPositionCloser9   r  )
r}  r  r  r  r  r  r  r  r  r  s
             r  fetch_my_liquidationszgate.fetch_my_liquidations  s     >#DGG.a$abb!!!V$t
 6Nx 0 #(  &z 2GHHd|H"..-K$($4$4[!$DGL!&>!CCDKKPWY_D`aaHH!DDT[[QXZ`EabbHH!@@WV\A]^^Htww)SSV\]cVddgppqqD &&xFFo 	" bb^sF   .E$EBE$E.E$1E 2.E$ E"!;E$E$ E$"E$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_sizer\  r  r  r  r_  r  )	r  r  r   r  r  	baseValue
quoteValuer  r  )r  r  r8  r=   r  r  r   safe_liquidationr  r|  r!  )r}  liquidationr  r  r  r  r\  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  K   | j                          d{    | j                  |      }d|d   d   i}| j                  | j                  ||             d{   }|d   }t	        dt        |            D ]2  }||   }| j                  |d      }	|	|k(  s | j                  ||      c S  y7 7 Vw)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>`
        Nr,  r  rB   r   rC   )r{  r  r  r  r  r  r  parse_greeks)
r}  r  r  r  r  r  r  r  rm  entryMarketIds
             r  fetch_greekszgate.fetch_greeks$  s      !!!V$&.6
 55dkk'66RSS. $<q#h-( 	8AQKE ,,UF;M(((77		8
 E 	"
 Ts(   B3B/AB3B1=B3B31B3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_greeksR  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                 ~   K   ddi}| j                  ||      }|d}| j                  |d|dd|       d{   S 7 w)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>`
        r2  TNr  r  r   )r  r  )r}  r  r  r  r  s        r  close_positionzgate.close_position  sQ      T
 Wf-<D&&vxq$OOOOs   4=;=c                 J  K   | j                          d{    d}|| j                  |      }i }d}| j                  |d      }| j                  |d      }|d   r^|d   |d<   |r*| j	                  | j                  ||             d{   }nw| j                  | j                  ||             d{   }nM|r*| j                  | j                  ||             d{   }n!t        | j                  dz   |d   z   dz         | j                  ||      S 7 7 7 i7 ?w)	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  rE  )r{  r  r  r>  +publicMarginGetUniCurrencyPairsCurrencyPairr  (publicMarginGetCurrencyPairsCurrencyPairrM  r9   rB   parse_leverage)r}  r  r  r  r  r  	isUnifieds          r  fetch_leveragezgate.fetch_leverage  s6     !!![[(FNN695	69-&>'-d|GO$!%!Q!QRVR]R]^egmRn!oo "&!N!Nt{{[bdjOk!ll !;;DKKQW<XYYHh tww)MMPVW]P^^akkll""8V44s 	" p m ZsF   D#DA4D#D)D#5D6+D#!D!"9D#D#D#!D#c                 N  K   | j                          d{    | j                  |      }d}| j                  |d      }| j                  |d      }d}|rd}| j	                  |       d{   }n| j                  |       d{   }| j                  |||d      S 7 7 47 w)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   )r{  r  r  r>  publicMarginGetUniCurrencyPairsr  parse_leverages)r}  r  r  r  r  marketIdRequests         r  fetch_leverageszgate.fetch_leverages  s      !!!%%g.NN695	69--O!AA&IIH ">>vFFH ##HgOOG 	" J Gs4   B%BAB%,B!-B%B#B%!B%#B%c                     | j                  |dd      }| j                  |d      }|| j                  ||dd      d ||dS )Nr<  rB   r  r  rQ   )r  r  r  longLeverageshortLeverage)r8  r  r  )r}  r  r  r  leverageValues        r  r  zgate.parse_leverage-  sR    %%hF))(J?&&xfE)*
 	
r  c                    K   | j                          d{    | j                  |      }d|d   i}| j                  | j                  ||             d{   }| j	                  |d|      S 7 X7 w)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>`
        Nr  rB   )r{  r  !publicOptionsGetContractsContractr  parse_optionr  s         r  fetch_optionzgate.fetch_option8  s~      !!!V$t
 ??GU[@\]]R   488] 	"
 ^s"   A3A/A A3A1A31A3c                    K   | j                          d{    | j                  |      }d|d   dz   i}| j                  | j                  ||             d{   }| j	                  |dd      S 7 [7 w)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>`
        Nr,  rd  _USDTrC   )r{  rT  r3  r  parse_option_chain)r}  rd  r  rT  r  r  s         r  fetch_option_chainzgate.fetch_option_chainr  s      !!!==&(6*W4
 77GV8TUUV &&xv>>a 	"
 Vs"   A6A2AA6A4A64A6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   r1  r  rT  r  r  r  impliedVolatilityopenInterestr  r  r  r  midPricer%  r  r  r  r  r  r  r  r5  r6  )r  r  r  r!  r  )r}  r`  rT  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                   K   | j                          d{    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                  |	|             d{   }
nJ|dk(  r*| j                  | j                  |	|             d{   }
nt        | j                  dz   |z         | j                  |
||      S 7 I7 e7 8w)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   rb  r  r  r  rc  rh   z: fetchPositionsHistory() does not support markets of type )r{  r  r  r  r  r>  r@  r  $privateFuturesGetSettlePositionCloser  %privateDeliveryGetSettlePositionCloser9   rB   r  )r}  r  r  r  r  r  r  r  rb  r  r  s              r  fetch_positions_historyzgate.fetch_positions_history  s    & !!!LM!WQZ0
!??@WY_agiop
F!!&'267+..vz6J$GG"//=GFO --edl;GDM!FFt{{SZ\bGcddH8#!GGT[]cHdeeHtww)eehrrss* ##Hgv>>[ 	"( ees4   E&EC%E&<E"=.E&+E$,4E&"E&$E&reasonr]   rP  rv  rI  c
                     |y | j                  |d      }
|
=| j                  dz   |z   }| j                  | j                  d   |
|       t	        |      y )Nlabel ru  )r  rB   throw_exactly_matched_exceptionrx  r-   )r}  rd  r  r]   rP  rv  rI  r  requestHeadersrequestBodyr  feedbacks               r  handle_errorszgate.handle_errors2  sa       73ww}t+H001I5RZ[))r  )NNNNr  )NN)__name__
__module____qualname__r   r{  boolr  r  r  r   r  rG  r  r    r   r*   r  r,   r  r  r  r	  r  r2  r@  rE  rG  rC  r  r	   ry  r$   r~  r!   r%   r  r}  r  r  r   r  r  r  r'   r  r(   r  r  r  r  r  r
   r  r  r   r  r  r   r  r"   r  dictr  r#   r@  rJ  r   r_  r  ru  re  r|  r  r&   r  r  r  r  r)   r  r  floatr   r  r  r  r   r   r   r  r   r  r  r  rC  rI  rN  rY  r   r  ry  r  r  r  r  r  r  r  r   r  r  r+   r   r  r  r  r  r   r  r   r  r   r  r  r  r  r$  r'  r*  r  r   r4  r8  r  rg  rl  r   rk  rq  rs  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  r0  r  __classcell__)r~  s   @r  r?   r?      s   Z# Zx -t - 02 .B :< ? ') :S :"=
3 =
~VC V VRU Vjm V  zI V *, 9V 9> /1 iV 35 0h
T 13 xt& &*R !8 15eB  $ 7;ERT  *$:c -/ [: [z <> <1s <1+ <1| <@ >; >;| >;@G
6 G
[ G
R? EG # #J JL 0S 0PTUcPd 0* =? 4 4> 4$
( ;= 8c 8AT 8@ /1 1[ 16
f 
< =A 4' 4l BFb Mw MB. .` 9=4^bkm .L# .LS .LX[ .L`OnI] O
& 
. @DB oS o oS\ ob 68 '1 '1F '1Rn4 n n6 n` 6:" %57 %5 %5N *, Q Qf 8<$]ajl AL ALC ALWZ ALquvzq{ ALF ?CQUdhqs Ls L3 L^a L >BPTcgpr 5Ys 5Y# 5Y]` 5Yn+ +4 +Z <@d[] hA hAS hA hAbfglbm hAT ?CQUdhqs '3 ' '3 '^a 'R 37TX\eg BAC BAs BARU BAH_ _v _ _B 04$UYbd  ;  ;C  ;s  ;imnyiz  ;D 37TX\eg  ;C  ;s  ;RU  ;lpq|l}  ;D JNVX &:3 &: &: &:]h &:P:s :$3k
T k
X k
Q\ k
Z mqy{ B2 B2I B2Y B2X] B2fi B2H HJ D,> < FH +$|*< +0 os{} Q,3 Q,i Q,y Q,Z_ Q,hk Q,f XZ Tc T T( hlz~  HJ ,S ,# ,Y ,i ,ad ,tw ,B fjx|  FH 923 92 929 92I 92_b 92ru 92v: : { {v { {z :>b (c (3 (" 8<B .2C .2 .2` 59tZ^gi Wc W WTW Wnrsxny W& 7;\`ik 0A 0A3 0AVY 0Aptuzp{ 0Ad FJX\koxz &s &RU &eh &> BFTXgktv O3 Oc Oad OB 9=R }2S }2# }2~ AER *+tCy *+# *+X Y[ $+d;N6O $+L 59 E3c E3N ac 673 67 67C 67TW 67gt 67p
t 
x 
= 
, ?C2 C3 C CJEt EV EN 8: R53 R5h 8<B d7W d74PX> d7L =A sD' sDP] sDj EG B B4P\K] B<$|BT 8 $|J\ @ RT :# :S :: BD /:S /:b Z\ +:3 +:c +:5 +:Z JL +:c +:5 +:Z3
 3
j 7;$]apt} -Q -QC -QWZ -Qjm -Q  EI  JX  EY -Q^
$ 
 
. 
"D  b$T LP\ FH @ @*
d *
F *
N` *
X FH H# Hu HL^ H CE Gs GE GI[ G HLZ^mqz| 5Q 5QTW 5Qgj 5Qn
F 
: <@daenp ,OS ,O ,O[^ ,O\ ?CQUdhqs 2Y 2Y3 2Y^a 2Yh#
J"H .2SW`b hCs hC# hCS hCgklwgx hCTPt Px P; Pd)8V CGr Xd XC X" 46 !F BFTXac 'Gs 'G3 'Gc 'GR 9=4^bkm GG# GGS GGX[ GGR>V >@ 68 , ,F ,\+
4 +
 +
6 +
Z CGr P3 Pi PV[ P* 8: f53 f5h f5P 8<B /PW /P9 /Pb	
t 	
V 	
x 	
 68 89 89F 89t :< <?S <? <?|>
$ >
( >
6 >
]c >
@ @DRVeirt @?W @?C @?_b @?y}  G  zH @?D# s  c TX `c r  r?   )E ccxt.async_support.base.exchanger   ccxt.abstract.gater   r  rS  ccxt.base.typesr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   typingr,   ccxt.base.errorsr-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   ccxt.base.decimal_to_precisionr<   ccxt.base.preciser=   r?    r  r  <module>r*     s    6 *   ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  ]  * 0 - . - . ' & . ) * 5 ) . 1 4 %cx8[ cxr  