
    i                       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" d dl#m$Z$ d dl%m&Z& d dl%m'Z' d dl%m(Z( d d	l%m)Z) d d
l%m*Z* d dl%m+Z+ d dl%m,Z, d dl%m-Z- d dl%m.Z. d dl%m/Z/ d dl%m0Z0 d dl%m1Z1 d dl%m2Z2 d dl%m3Z3 d dl%m4Z4 d dl%m5Z5 d dl6m7Z7 d dl8m9Z9  G d dee          Z:dS )    )Exchange)ImplicitAPIN)Balances
CurrenciesCurrencyFundingHistoryGreeksIntLeverage	LeveragesMarginModificationMarketMarketInterfaceNumOptionOptionChainOrder	OrderBookOrderRequest	OrderSide	OrderTypeStrStringsTickerTickersTradeTradingFeeInterfaceTradingFeesTransactionTransferEntry)List)ExchangeError)AuthenticationError)PermissionDenied)AccountNotEnabled)AccountSuspended)ArgumentsRequired)
BadRequest)	BadSymbol)BadResponse)InsufficientFunds)InvalidOrder)OrderNotFound)OrderImmediatelyFillable)NotSupported)RateLimitExceeded)ExchangeNotAvailable)	TICK_SIZE)Precisec                       e Zd Z fdZdef 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fdZdi fdefdZdde	fdZi fdefdZi fdefd Zi fdede fd!Z!i fde"fd"Z#d# Z$dde	fd$Z%di fd%ee         fd&Z&di fd%efd'Z'dd(e(fd)Z)dddi fded*e*d+e*fd,Z+dee,         fd-Z-dde	fd.Z.di fded+e*de/fd/Z0i fdede1fd0Z2dde	de1fd1Z3di fdede4fd2Z5d3 Z6i fde7fd4Z8d5ddi fded*e*d+e*dee9         fd6Z:d5ddi fded*e*d+e*fd7Z;dddi fded*e*d+e*fd8Z<dde	de9fd9Z=ddi fded*e*d+e*dee>         fd:Z?dddi fd;eded*e*d+e*fd<Z@dddi fded*e*d+e*fd=ZAdde	de>fd>ZBdddi fded*e*d+e*deeC         fd?ZDdddi fded*e*d+e*deeC         fd@ZEdi fdedAeFfdBZGdC ZHdD ZIdd(e(deCfdEZJdi fdedFeKdGeLdAeFdHeMf
dIZNi fdJeeO         fdKZPdi fdedFeKdGeLdAeFdHeMf
dLZQi fdedMeFfdNZRddi fd;ededFeKdGeLdAeMdHeMfdOZSdP ZTdde	deUfdQZVdi fd;edefdRZWdddi fded*e*d+e*deeU         fdSZXdddi fded*e*d+e*deeU         fdTZYdddi fded*e*d+e*fdUZZdi fd;edefdVZ[di fdefdWZ\i fdedAeFdXedYede]f
dZZ^dd(e(fd[Z_di fd\e*defd]Z`dde	fd^Zai fdefd_Zbdi fdefd`Zcdi fdefdaZdi fdefdbZeddcZfdde	fddZgi fdedefdeZhi fdefdfZii fdededAeFfdgZji fdedAeFfdhZkdd(e(fdiZlg dji ddfdkZmi fdefdlZndde	deofdmZpi fdedeofdnZqi fdedeofdoZrdpddi fded*e*d+e*fdqZsdde	fdrZtdddi fded*e*d+e*fdsZudddi fded*e*d+e*fdtZvdu Zwdv Zxdddi fded*e*d+e*fdwZydd(e(fdxZzdy Z{di fdzedefd{Z|i fd|Z}ddi fded*e*d+e*fd}Z~dddi fded*e*d+e*fd~Zdde	fdZi fdedefdZdde	fdZdi fdedGeLdeUfdZi fdedefdZdi fdee         defdZddefdZi fdedefdZi fdedefdZdd(e(de	fdZd Z xZS )gatec           !      &   |                      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dAdBdCddDddEddFddGd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dhddid+djddkddlddmddnddod+dpddqddrddsddd+dd+dddtdudvdwdxiidvdxdxdxdxdxdxdxdxdxdy	idvdxdxdxdxdxdxdxdzidvd{dxiidvdxdxdxdxdxdxdxdxdxdxdxdxd|idvdxdxdxdxdxdxdxd}idvdxdxdxdxdxdxdxdxdxdxdxdxd~idvdxdxdidddiddxiddxdxdxdxdxdddddxdxddxdxdddddxddddddddddddddiddiddddddddddd	ddd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ĜddddddddddŜ	ddidddǜdĜddddddddȜddiddiddid˜dddddddddddddddd̜ddddddd͜dddddΜdddϜddidĜdvdddќidҜdddddddddddddddߜdi ddddddddddddddddddddddddddddddddd dddidddddddi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dTd"d#d$giidTd"d#giid%d&t          d'ddvd|                     d(          |                     d(          |                     d)          |                     d(          g|                     d*          |                     d+          g|                     d,          |                     d-          g|                     d.          |                     d/          g|                     d0          |                     d1          g|                     d2          |                     d3          g|                     d4          |                     d5          g|                     d6          |                     d7          g|                     d8          |                     d9          g|                     d:          |                     d;          g|                     d<          |                     d=          g|                     d>          |                     d?          g|                     d@          |                     dA          g|                     dB          |                     dC          g|                     dD          |                     dE          g|                     dF          |                     dE          g|                     dG          |                     dE          gg|                     d)          |                     d(          g|                     d*          |                     dH          g|                     d,          |                     d+          g|                     d.          |                     d-          g|                     d0          |                     d/          g|                     d2          |                     d1          g|                     d4          |                     d3          g|                     d6          |                     d5          g|                     d8          |                     d7          g|                     d:          |                     d9          g|                     d<          |                     d;          g|                     d>          |                     d=          g|                     d@          |                     d?          g|                     dB          |                     dA          g|                     dD          |                     dC          g|                     dF          |                     dC          g|                     dG          |                     dC          ggdIdJddKd|                     dL          |                     dM          |                     d)          |                     dN          g|                     d*          |                     dO          g|                     d,          |                     dO          g|                     d.          |                     dO          g|                     d0          |                     dO          g|                     d2          |                     dO          g|                     d4          |                     dO          g|                     d6          |                     dO          g|                     d8          |                     dO          g|                     d:          |                     dO          g|                     d<          |                     dO          g|                     d>          |                     dP          g|                     d@          |                     dQ          g|                     dB          |                     dR          g|                     dD          |                     dS          g|                     dF          |                     dT          g|                     dG          |                     dU          gg|                     d)          |                     dV          g|                     d*          |                     dW          g|                     d,          |                     dX          g|                     d.          |                     dY          g|                     d0          |                     dZ          g|                     d2          |                     d[          g|                     d4          |                     d\          g|                     d6          |                     d]          g|                     d8          |                     d^          g|                     d:          |                     d_          g|                     d<          |                     d`          g|                     d>          |                     d`          g|                     d@          |                     d`          g|                     dB          |                     d`          g|                     dD          |                     d`          g|                     dF          |                     d`          g|                     dG          |                     d`          ggdIdJdadbi dct          ddt          det          dft          dgt          dht          dit          djt          dkt          dlt          dmt          dnt          dot          dpt          dqt          drt          dst          i dtt          dut          dvt          dwt          dxt          dyt          dzt          d{t          d|t          d}t          d~t          dt          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          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          t          t          t          t          t          t          t          t          t          t          d
i di          S (  Nidr5   namezGate.io	countriesKR	rateLimit2   versionv4	certifiedTprourlszchttps://user-images.githubusercontent.com/1294454/31784029-0313c702-b509-11e7-9ccc-bc0da6a0e435.jpgz-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)withdrawalsrB   rC   rD   rE   rF   rG   subAccountsunifiedrebaterI   accountloan)publicprivatez'https://fx-api-testnet.gateio.ws/api/v4)rC   rE   rG   z"https://www.gate.io/signup/2436035g?)urldiscount)logodocwwwapitestreferralhasCORSrF   rD   swapfutureoption	addMarginborrowCrossMarginborrowIsolatedMargincancelAllOrderscancelOrdercreateMarketBuyOrderWithCostcreateMarketOrdercreateMarketOrderWithCostFcreateMarketSellOrderWithCostcreateOrdercreateOrderscreatePostOnlyOrdercreateReduceOnlyOrdercreateStopLimitOrdercreateStopLossOrdercreateStopMarketOrdercreateStopOrdercreateTakeProfitOrdercreateTriggerOrder	editOrderfetchBalancefetchBorrowRateHistoriesfetchBorrowRateHistoryfetchClosedOrdersfetchCrossBorrowRatefetchCrossBorrowRatesfetchCurrenciesfetchDepositAddress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fetchPositionModefetchPositionsfetchPremiumIndexOHLCVfetchSettlementHistoryfetchTickerfetchTickers	fetchTimefetchTradesfetchTradingFeefetchTradingFeesfetchTransactionFeesfetchUnderlyingAssetsfetchVolatilityHistoryfetchWithdrawalsreduceMarginrepayCrossMarginrepayIsolatedMargin)setLeveragesetMarginModesetPositionModesignIntransferwithdrawrW   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)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})rB   rF   rD   
flash_swaprC   rE   rG   rI   rJ      zwithdrawals/{withdrawal_id})postdeleteg      @)deposit_addressrJ   depositssub_account_transferswithdraw_statussub_account_balancessub_account_margin_balancessub_account_futures_balances!sub_account_cross_margin_balancessaved_addressfeetotal_balancesmall_balancesmall_balance_history)	transfersr   sub_account_to_sub_accountr   )r   r   )rH   zsub_accounts/{user_id}sub_accounts/{user_id}/keys!sub_accounts/{user_id}/keys/{key})rH   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_tiersg*@)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}/feez{settle}/risk_limit_tiers{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   r   )r   r   )r   r   	uni/lendszuni/lend_recordszuni/interests/{currency}r  zuni/interest_status/{currency}r  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_rate)r  zcollateral/repayr  r  r  r  )detail
stp_groupsstp_groups/{stp_id}/users)r  r  r  )zagency/transaction_historyzagency/commission_history)rJ   rB   rK   rL   rF   rD   r   rC   rE   rG   rI   rO   rN   rM   
timeframes10s1m5m15m30m1h2h4h8h1d7d)r   r!  r"  r#  r$  r%  r&  r'  r(  r)  r*  1wcommonCurrencies88MPHMPHAXISz	Axis DeFiBIFIzBitcoin FileBOXDefiBoxBYNBeyondFiEGGzGoose FinanceGTCzGame.comGTC_HTzGame.com HTGTC_BSCzGame.com BSCHITHitChainMMMillionMorpherPOINT	GatePointRAIzRai Reflex IndexSBTCzSuper BitcoinTNCzTrinity Network CreditVAIVAIOTTRACTRACOrequiredCredentials)apiKeysecretheaderszX-Gate-Channel-IdccxtrG   
expirationiQ AVAX_CBSCEOSETHGTEVMHTKSMSMNEAROKTOPETHDOTSMTRX)AVAXCBEP20rO  ERC20	GATECHAINHRC20KUSAMArT  OKCOPTIMISMPOLKADOTTRC20gtciocpocfok)r6  IOCPOPOCFOKcross_marginrC   rE   )fundingrF   rD   rk  crossisolatedr\   r]   rC   rE   r^   rG   settlementCurrenciesusdtbtc)sandboxModerh   networkstimeInForceaccountsByTypedefaultTyper\   r]   precisionModefeesz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)tradingr\   
exceptions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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)deep_extendsuperr5   describer2   parse_numberr(   r'   r"   r#   r$   r&   r+   r0   r1   r,   r)   r.   r-   r%   )self	__class__s    ]/var/www/html/crypto-bot/backend/venv/lib/python3.11/site-packages/ccxt/async_support/gate.pyr  zgate.describe"   s   dD 1 1 : : < < T?
&T?
IT?
 $T?
 	T?

 tT?
 T?
 4T?
 }F) #A#A"@$B >#A(F >	 	 (F"@#A"@$B >#A'E#A"@ >#A >    : $M$M#L  $M$M#L     @ # W/ /T?
p  \\\ $\ 	\
 $\ $\ T\ $T\ '\ "4\ t\ /\ $T\ ,U\ 0\  t!\" #\ \$ &t%\& ('\( ')\* &t+\, (-\. "4/\0 (1\2 %d3\4 T5\6 7\8 +E9\: )%;\< $T=\> '?\@ (A\B "4C\D &tE\ \ \F  G\H *:I\J +DK\L &tM\N #DO\P *4Q\R $TS\T tU\V "4W\X *5Y\Z +E[\\ t]\^  _\` !$a\b %dc\d $Te\f /g\ \ \h "5i\j +Dk\l m\n !$o\p &tq\r +Ds\t  u\v -dw\x dy\z $U{\| +D}\~ "4\@ tA\B #DC\D dE\F !$G\H  I\ \ \J $UK\L !$M\N )%O\P )$Q\R tS\T U\V UW\X tY\Z "4[\\ #D]\^ '_\` (a\b )%c\d #De\f g\h #Di\j &tk\ \l  $!&#'  w\ \ \qT?
j  -q  *+56./>?'(*+&',-$%
  
  ./>?,-01;<23BC   
 (! # 23=>34/0566701562378CD34    " 23=>34/0560123   
! +,+,)*45+,67*+'(?@,-78&'    " ./9:   _U Ut *2! :1#	$ $ 01+,()56/047;><?AD-.#$-0-.56   " *-58:=-.	! !# 4 -069;>AD	    -0;>;>=@	! ! @  @#!$ $, )0,3*1,3%,,307-47>
  
  -4%-! !   ( $%)*(),-+,&'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
  
  %g! '.18# #   , /69@)0078?4;>E    (! 4W  ("! , 29<C8?6=7>.55<7>BI6=9@?F;B4;;B   $ 29076=7>6=9@! !% : '.*19@    +29@! !
 8#    :A9@   w	A AoY YkT?
^  _T?
|  !!! ! y	!
 z! ! z! -! >! z! i! y! ! )! !  /!!" w#!$ %! !}T?
d "$ $eT?
l #VmT?
r $ %  &" "!(!%"  ' '"  !        &"&$2+ (%(( *'(# #  &".% #.%]3 3sT?
Z Y[T?
\ !%$"&!..w77!..w77 "..s33T5F5Fw5O5OP!..u55t7H7H7S7ST!..s33T5F5Fy5Q5QR!..s33T5F5Fy5Q5QR!..v668I8I)8T8TU!..t44d6G6G	6R6RS!..t44d6G6G	6R6RS!..u55t7H7H7S7ST!..u55t7H7H7S7ST!..v668I8I)8T8TU!..v668I8I)8T8TU!..v668I8I)8T8TU!..v668I8I)8T8TU!..w779J9J99U9UV!..w779J9J99U9UV!..w779J9J99U9UV!..w779J9J99U9UV#"( "..s33T5F5Fw5O5OP!..u55t7H7H7S7ST!..s33T5F5Fy5Q5QR!..s33T5F5Fy5Q5QR!..v668I8I)8T8TU!..t44d6G6G	6R6RS!..t44d6G6G	6R6RS!..u55t7H7H7S7ST!..u55t7H7H7S7ST!..v668I8I)8T8TU!..v668I8I)8T8TU!..v668I8I)8T8TU!..v668I8I)8T8TU!..w779J9J99U9UV!..w779J9J99U9UV!..w779J9J99U9UV!..w779J9J99U9UV#"+( (/ /b "&%"&!..u55!..x88 "..s33T5F5Fx5P5PQ!..u55t7H7H7T7TU!..s33T5F5Fz5R5RS!..s33T5F5Fz5R5RS!..v668I8I*8U8UV!..t44d6G6G
6S6ST!..t44d6G6G
6S6ST!..u55t7H7H7T7TU!..u55t7H7H7T7TU!..v668I8I*8U8UV!..v668I8I*8U8UV!..v668I8I*8U8UV!..v668I8I*8U8UV!..w779J9J:9V9VW!..w779J9J:9V9VW!..w779J9J:9V9VW!..w779J9J:9V9VW#"( "..s33T5F5Fy5Q5QR!..u55t7H7H7S7ST!..s33T5F5Fy5Q5QR!..s33T5F5Fy5Q5QR!..v668I8I)8T8TU!..t44d6G6G	6R6RS!..t44d6G6G	6R6RS!..u55t7H7H7S7ST!..u55t7H7H7S7ST!..v668I8I)8T8TU!..v668I8I)8T8TU!..v668I8I)8T8TU!..v668I8I)8T8TU!..w779J9J99U9UV!..w779J9J99U9UV!..w779J9J99U9UV!..w779J9J99U9UV#")' '. .c` `]T?
` `):`&
` '
` +J	`
 -.?` ":` +J` %j` )*`  ` *+>` "#6` #$7`  !1` ()<`  ./B!`" &':#` `$ %&6%`&  !1'`( ,])`* )*:+`, /-`. -m/`0 1-1`2 12C3`4 (5`6 2=7`8 '9`:  1;`< ,]=`> ,-A?`@ *=A`B 5mC`D (E` ` `F '	G`H ,YI`J +,DK`L &}M`N *=O`P #LQ`R &|S`T *<U`V )*;W`X +LY`Z 01B[`\ (]`^ &|_`` (a`b %mc`d ,]e`f &}g` ` `h $]i`j  k`l %mm`n .|o`p &|q`r ():s`t ),u`v +Mw`x '(9y`z %&7{`| *=}`~ ))`@ *=A`B -.?C`D ,\E`F (G`H 'I` ` `J &}K`L %mM`N ,]O`P .}Q`R (S`T %lU`V &}W`X .}Y`Z *=[`\ )-]`^ ),_`` %la`b %lc`d -le`f *<g`h *+Ci`j (k` `l .; 4$8 4/<*44@6B(2*4` ` `B Ec caT?
 T?
 T T T	    enablec                 l    t          t          |                               |           || j        d<   d S )Nrr  )r  r5   set_sandbox_moderG   )r  r  r  s     r  r  zgate.set_sandbox_modey  s3    dD**6222&,]###r  symbolc                    d}|}|                     d          }|                     d          }|                     d          }d }|                     |d          }|                    d          dk    r|                     |d          }n |                     |d          }|dd	         }|                     |d          }	|                     |d
          }
|                     |          }|                     |          }i d|dz   |z   dz   dz   |z   dz   |	z   dz   |
z   d|dz   |z   dz   |z   dz   |z   dz   |	z   dz   |
z   d|d|d|d|d|d|dddddd dd ddddddddddd|                     d           |||
d!k    rd"nd#|                     |	          |                     d           d d$d d d%d d d%d d d%d&d d'	S )(NUSDT-/_r   r            r7   20r  :r  quotesettlebaseIdquoteIdsettleIdactiveFtyper^   linearinverserF   r\   r]   TrD   1Ccallr   amountpriceminmax)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_market}  s   ll3''\\#&&
||C((!!+q11;;sb  ##J22DD##L!44DAaC[F!!+q11%%k155
++F33NN8,,	+
$*u$s*T1F:S@6ICOR\\+
dSj5(3.7#=FLvUX[[^hh+
 D+
 U	+

 f+
 d+
 u+
 +
 e+
 H+
 d+
 t+
 E+
 E+
 e+
  d!+
" e#+
$  --c22&%/3%6%6&&U''//++C00    
   
     U+
 +
 +
 +	
r  NmarketIdmarket	delimiter
marketTypereturnc                    |d uo1|                     d          dk    p|                     d          dk    }|r|| j        vr|                     |          S t          t          |                               ||||          S )Nz-Cr  z-P)r(  markets_by_idr0  r  r5   safe_market)r  r1  r2  r3  r4  isOptionr  s         r  r8  zgate.safe_market  s    D(hd0C0Cb0H/ghmm\`NaNadfNf 	?X);;;44X>>>T4  ,,Xvy*UUUr  c                   K   |                      | j        dd          }|                     |          |                     |          g}|s,|                     |          g}|                     ||          }t          j        |  d{V }|                     |dg           }|                     |dg           }|                     |dg           }|                     ||          }	|                     |	|          S )a  
        retrieves data on all markets for gate
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-all-currency-pairs-supported                                     # spot
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-all-supported-currency-pairs-supported-in-margin-trading         # margin
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-all-futures-contracts                                            # swap
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-all-futures-contracts-2                                          # future
        :see: 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
        rr  FNr   r   r  )		safe_boolrG   fetch_contract_marketsfetch_option_marketsfetch_spot_marketsarray_concatasynciogather
safe_value)
r  paramsrr  rawPromisesmainnetOnlypromisesspotMarketscontractMarketsoptionMarketsmarketss
             r  fetch_marketszgate.fetch_markets  s      nnT\=%HH''//%%f--
  	F226::;K++KEEK 5555555ooh266//(Ar::!R88##KAA  -888r  c                   K   |                      |           d {V }|                     |           d {V }|                     |d          }g }t          dt	          |                    D ]}||         }|                     |d          }|                     ||          }	|                     |	|          }
|                    d          \  }}| 	                    |          }| 	                    |          }|                     |
d          }|                     |
d|          }| 
                    |                     |                     |
d                              }|                     |
d          }|                     |
d          }|d u}|                    i d|d	|d
z   |z   d|d|dd d|d|dd ddddd|ddddddd|dk    dddd d | 
                    t          j        |d                    | 
                    t          j        |d                    d d d d d || 
                    |                     |                     |
d                              d| 
                    d           |                     |
dd!          d"|                     |d#|          d d"d d d"|                     |
d$          |r|                     |
d%          nd d"d&d |
d'           |S )(Nr7   r   r  r   maker_fee_rateamount_precisiontrade_statusleverager  r  r  r
  r  r  r  r  r  rF   TrD   r\   Fr]   r^   r  tradabler  r  100r#  r  r  r   r  min_base_amountmin_quote_amountmax_quote_amountrP  r  r  r  r  r  r  r  r  r   r"  r!  r#  r$  createdr%  )publicMarginGetCurrencyPairspublicSpotGetCurrencyPairsindex_byrangelenr'  rB  r  r&  safe_currency_coder  parse_precisionsafe_numberappendr3   
string_div)r  rC  marginResponsespotMarketsResponsemarginMarketsresulti
spotMarketr7   marginMarketr2  r  r  r  r
  takerPercentmakerPercentamountPrecisiontradeStatusrP  rD   s                        r  r>  zgate.fetch_spot_markets  s     #@@HHHHHHHH$($C$CF$K$KKKKKKKnd;;D q#12233 A	 A	A,Q/J!!*d33B??="==L%%lJ??F hhsmmOFG**622D++G44E++FE::L++F4DlSSL"//0D0DTEUEUV\^pEqEq0r0rssO**6>BBK''
;;HT)FMM 3b3$*u,3 3 	3
 $3 &3 73 D3 3 3 &3 3 %3 %3 ;*43  E!3" $#3$  **7+=lE+R+RSS**7+=lE+R+RSS $"&"-!..t/C/CDDTDTU[]hDiDi/j/jkk   $0055#//
AFF! !
  $//
<M__# 
  $# 
  $//8JKKOU_t//8JKKK[_  $  e3 3 3 3 3 3 3h r  c                   K   g }|                      dd          }|                      dd          }t          dt          |                    D ]}||         }d|i}|                     |                     ||                     d {V }t          dt          |                    D ]3}	|                     ||	         |          }
|                    |
           4t          dt          |                    D ]}||         }d|i}|                     |                     ||                     d {V }t          dt          |                    D ]3}	|                     ||	         |          }
|                    |
           4|S )Nr\   r   r]   r   r  )get_settlement_currenciesr\  r]  publicFuturesGetSettleContractsextendparse_contract_marketra   publicDeliveryGetSettleContracts)r  rC  rf  swapSettlementCurrenciesfutureSettlementCurrenciescr  requestresponserg  parsedMarkets              r  r<  zgate.fetch_contract_marketsH  s     #'#A#A&.#Y#Y %)%C%CHn%]%]"q#67788 	, 	,A/2H(G "AA$++gW]B^B^________H1c(mm,, , ,#99(1+xPPl++++, q#899:: 	, 	,A1!4H(G "BB4;;wX^C_C_````````H1c(mm,, , ,#99(1+xPPl++++, r  c                 T   |                      |d          }|                    d          }|                      |d          }|                      |d          }|                      |d          }|                     |          }|                     |          }	|                     |          }
|                     |d          }d}d}|+|d	z   |	z   d
z   |
z   dz   |                     |d          z   }d}n|d	z   |	z   d
z   |
z   }|                      |d          }|                      |d          }t          j        d|          }t          j        d|          }t          j        ||          }t          j        ||          }|                      |d          }|                      |d|          }|	|
k    }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"|| | 	                    t          j
        |d#                    | 	                    t          j
        |d#                    |                     |d$          ||                     |          d d | 	                    d          |                     |d%          d&|                     |d'          |                     |d(          d)|                     |d*          |                     |d+          d)| 	                    |          | 	                    |          d)d d d)d,d |d-S ).Nr8   r  r   r   r  expire_time r\   r  r	  r  r]   order_price_deviate
mark_pricer  taker_fee_raterM  r7   r  r  r
  r  r  r  r  r  rF   FrD   r^   r  Tr  r  rR  quanto_multiplierorder_price_roundr  leverage_minleverage_maxr  order_size_minorder_size_maxrV  rW  )r'  r&  r^  safe_timestampyymmddr3   
string_sub
string_add
string_mulr  rb  r`  iso8601)r  r2  r  r7   partsr  r  dater  r
  r  r  r  r4  priceDeviate	markPriceminMultipliermaxMultiplierminPricemaxPricerj  rk  isLinears                          r  rr  zgate.parse_contract_market`  s   r ff--!!%++""5!,,q))&&v..''00((22$$V];;
CZ%'#-6<t{{6SU?V?VVF!JJCZ%'#-6F''0EFF$$V\::	*3==*3==%mY??%mY??''0@AA''0@,OOF?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,'N'NOO&&w'9,'N'NOO ,,V5HII"ll622++C00))&2EFF   ++FNCC++FNCC 
  ++F4DEE++F4DEE 
  ,,X66,,X66 
    $ c2
 2
 2
 2	
r  c                   K   g }|                                   d {V }t          dt          |                    D ]}||         }|                     i |          }||d<   |                     |           d {V }t          dt          |                    D ]"}||         }	|                     |	d          }
|                    d          }|                     |d          }|                     |d          }|                     |          }|                     |          }|dz   |z   }|                     |	d          }|                     |	d          }| 	                    |	d	          }|rd
nd}|rdnd}|dz   |z   dz   | 
                    |          z   dz   |z   dz   |z   }|                     |	d          }|                     |	d          }t          j        d|          }t          j        d|          }t          j        ||          }t          j        ||          }|                     |	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 |                     t          j        |d(                    |                     t          j        |d(                    |                     d          ||                     |          |||                     d          |                     |	d)          d*d d d+|                     |	d,          |                     |	d-          d+|                     |          |                     |          d+d d d+d.|                     |	d/          |	d0           $|S )1Nr   
underlyingr8   r  r   r  expiration_timestrike_priceis_callr  Pr  r   r	  r  r}  r~  r  r  rM  r7   r  r  r
  r  r  r  r  r  r^   rF   FrD   r\   r]   Tr  r  r  rR  r  r  r  r  r  rV  create_timerW  )fetch_option_underlyingsr\  r]  rq  publicOptionsGetContractsr'  r&  r^  r  rB  r  r3   r  r  r  ra  r  rb  r  r`  )r  rC  rf  r   rg  r  queryrx  jr2  r7   r  r  r  r  r
  r  r  r"  isCalloptionLetterr!  r  r  r  r  r  r  rj  rk  s                                 r  r=  zgate.fetch_option_markets  s      99;;;;;;;;q#k**++ t	 t	A$QJKKF++E",E,!;;EBBBBBBBBHN 1c(mm,, I I!!%%ff55"((--))%33**5!44..v66//88e+,,V5FGG))&.AA;;&,5ss#'-8VV5
#-3dkk&6I6IICORXX[^^amm#//8MNN ,,V\BB	 ' 23 E E ' 23 E E"-mYGG"-mYGG#//8HII#//8H,W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,PU/V/VWW!..w/A,PU/V/VWW$($5$5c$:$:$&*ll6&:&:$","&"3"3C"8"8!%!1!1&:M!N!N" " $(#'% %
 $(#3#3F<L#M#M#'#3#3F<L#M#M# #
 $(#4#4X#>#>#'#4#4X#>#>" "
 $(#'! ! $  $226=II"c2 2 2 2 2 2 2/IT r  c                    K   |                                   d {V }g }t          dt          |                    D ]7}||         }|                     |d          }||                    |           8|S )Nr   r8   )publicOptionsGetUnderlyingsr\  r]  r'  ra  )r  underlyingsResponser   rg  r  r8   s         r  r  zgate.fetch_option_underlyings  s      $($D$D$F$FFFFFFF q#12233 	) 	)A,Q/J##J77D""4(((r  c                    i }|3|d         r|d         |d<   |d         s|d         |d<   nT|d         |d<   nH|dk    }|d	k    }|s|r8|rd
nd}|                      |d|          }|                     |d          }||d<   ||gS )a  
         * @ignore
        Fills request params contract, settle, currency_pair, market and account where applicable
        :param dict market: CCXT market, required when type is None
        :param str type: 'spot', 'swap', or 'future', required when market is None
        :param dict [params]: request parameters
        :returns: the api request object, and the new params object with non-needed parameters removed
        Nr  r7   r^   r  r  currency_pairr\   r]   rp  rq  )safe_string_loweromit)	r  r2  r  rC  rw  r\   r]   defaultSettler  s	            r  prepare_requestzgate.prepare_request  s     j! 8&,Tl
#h' ;(.z(:GH%+1$<((6>DX%F +v +*. 9E//-PP6844$*!  r  Fc                     |                      ||          \  }}i }|s)|t          | j        dz             ||d<   |d         |d<   ||gS )  
         * @ignore
        Fills request params currency_pair, market and account where applicable for spot order methods like fetchOpenOrders, cancelAllOrders
        :param dict market: CCXT market
        :param bool stop: True if for a stop order
        :param dict [params]: request parameters
        :returns: the api request object, and the new params object with non-needed parameters removed
        NzI spotOrderPrepareRequest() requires a market argument for non-stop ordersrN   r7   r  )get_margin_moder'   r7   r  r2  stoprC  
marginModer  rw  s          r  spot_order_prepare_requestzgate.spot_order_prepare_request  si     !00v>>
E 	4~'2}(}~~~!+GI'-d|GO$r  c                 z    |                      ||          \  }}d|i}||r|d         |d<   n|d         |d<   ||gS )r  rN   Nr7   r2  r  )r  r  s          r   multi_order_spot_prepare_requestz%gate.multi_order_spot_prepare_request  sd     !00v>>
Ez
  8$*4L!!+1$<(r  c                 &   |                      | j        ddd          }|                      |dd|          }|                     |ddg          }|dk    rd}n|dk    rd}n|d	k    rd}|r%|dk    rd
}|dk    rt          | j        dz             ||gS )ai  
         * @ignore
        Gets the margin type for self api call
        :param bool stop: True if for a stop 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  rF   rN   rm  rk  rn  rD   r|  normalz> getMarginMode() does not support stop orders for cross margin)safe_string_lower_2rG   r  r(   r7   )r  r  rC  r  r  s        r  r  zgate.get_margin_mode  s     !44T\CVXdflmm--flIO`aa
6L)#<==  'JJ:%%!JJ2J 	mV##%
^++ +k!klllF##r  c                     |                      | j        |i           }|                      ||i           }|dk    rdgndg}|                      |d|          S )Nr\   rp  rq  ro  )rB  rG   )r  r  methodrG   fetchMarketsContractOptionsr  s         r  ro  zgate.get_settlement_currencies  s]    //$,b99&*oogvr&J&J#%)V^^5':<RTabbbr  c                 r  K   |                      | j        d          }|dS |                     |           d{V }i }t          dt	          |                    D ]Y}||         }|                     |d          }|                     |d          }|                    d          }	|	d         }
|                     |
          }|                     |d          }d}|| 	                    ||          }|                      |d          }| 
                    |dd	          }| 
                    |d
d	          }| 
                    |dd	          }| }| }| }| }|o|o|o|}|                      ||          <|                                |dd|||dg |                     d          | j        i d||<   |                      ||         d          }|r|n|}|                      ||         d          }|r|n|}|                      ||         di           }|1||||||||d|                     d          ddddddddddd||<   |||         d<   |                      ||         dg           }|                    |           |||         d<   |o|||         d<   |||         d<   |||         d<   [|S )a-  
        fetches all available currencies on an exchange
        :see: 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
        	apiBackupNr   currencyr  chaindelistedwithdraw_disabledFdeposit_disabledtrade_disabledz1e-4)r7   coder%  r8   r  depositr   r   rx  r#  r$  rs  r  r   rs  r  )r  r   r  )r%  r7   network
currencyIdlowerCaseCurrencyIdr  r   r  r   r#  r$  r%  r  )rB  rA   publicSpotGetCurrenciesr\  r]  r'  r  r&  r^  network_id_to_coder;  lowerr  r$  ra  )r  rC  r  rx  rf  rg  entryr  currencyIdLowerr  r  r  	networkIdnetworkCoder  withdrawDisableddepositDisabledtradeDisabledwithdrawEnableddepositEnabledtradeEnabledlistedr  depositAvailablewithdrawAvailablers  r%  s                              r  fetch_currencieszgate.fetch_currencies  sd      OODI{;;	 455f========* q#h--(( I	9 I	9AQKE))%<<J"44UJGGO$$S))EQxH**844D((88IK$"55iFFuj99H#~~e5H%PP"nnU4FNNO NN52BEJJM"22O!00N,,L!\FSSS^Fvt,,4**,,   $- /!%!2!26!:!:"k "   t  $vd|YGG2@W~~GW $tj I I4C [J[vd|ZDDH&!#*",+:- /$!%!2!26!:!: $(#'# #
 $(#'% %
 $(#'$ $ ) )%4 (0F4L$??6$<<<DKK#'F4L %5%K:KF4L"&6F4L#'8F4L$$r  c                 ^  K   |                                   d{V  |                     |          }|d         st          | j        dz             |                     |d|          \  }}|                     |                     ||                     d{V }|                     |          S )ao  
        fetch the current funding rate
        :see: 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>`
        Nr\   z0 fetchFundingRate() supports swap contracts only)load_marketsr2  r)   r7   r  'publicFuturesGetSettleContractsContractrq  parse_funding_rate)r  r  rC  r2  rw  r  rx  s          r  fetch_funding_ratezgate.fetch_funding_rateb  s       !!!!!!!!!V$$f~ 	ZDG&XXYYY--fdFCCEEdkkRY[`FaFabbbbbbbbZ &&x000r  symbolsc                 N  K   |                                   d{V  |                     |          }|                     dd|          \  }}|                     |                     ||                     d{V }|                     |          }|                     |d|          S )a  
        fetch the funding rate for multiple markets
        :see: 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 dictionary of `funding rates structures <https://docs.ccxt.com/#/?id=funding-rates-structure>`, indexe by market symbols
        Nr\   r  )r  market_symbolsr  rp  rq  parse_funding_ratesfilter_by_array)r  r  rC  rw  r  rx  rf  s          r  fetch_funding_rateszgate.fetch_funding_rates  s       !!!!!!!!!%%g..--dFFCC==dkk'SX>Y>YZZZZZZZZZ ))(33##FHg>>>r  c                    |                      |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 S )Nr8   r  r\   r~  index_priceinterest_ratefunding_ratefunding_next_applyfunding_rate_indicativer%  r  r  
indexPriceinterestRateestimatedSettlePricer/  r.  fundingRatefundingTimestampfundingDatetimenextFundingRatenextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetime)r'  safe_symbolr`  r  r  )r  r  r2  r1  r  r  r  r  r  fundingTimefundingRateIndicatives              r  r  zgate.parse_funding_rate  s   V ##Hf55!!(FC@@$$X|<<	%%h>>
''/BB&&x@@))(4HII $ 0 0;T U U
H
f
 
 *	

 L
 #D
 
 
 ;
 
 t||K88
 4
 #D
 "4
 "4
  '!
" &t#
 	
r  r  c                 |  K   |                                   d {V  |                     |          }d|d         i}|                     |                     ||                     d {V }|                     |d          }|                     |d          }|                     |          }i }t          dt          |                    D ]p}	||	         }
| 	                    |
d          }|r#|                     |
d          }|                     |
d          }|                     |
d          }|
||||d	||<   q|S )
Nr  r7   multichain_addressesr   obtain_failedr  address
payment_id)r%  r  r  r  tag)
r  r  privateWalletGetDepositAddressrq  rB  r'  r^  r\  r]  safe_integer)r  r  rC  r  rw  rx  	addressesr  rf  rg  r  obtainFailedr  r  r  s                  r  fetch_network_deposit_addressz"gate.fetch_network_deposit_address   ss     !!!!!!!!!==&&
 <<T[[RX=Y=YZZZZZZZZOOH.DEE	%%h
;;
&&z22q#i..)) 	 	AaLE  ,,UODDL &&ug66G&&ui88G""5,77C " F7OO r  c                   K   |                                   d{V  |                     |          }|                     |d          }|                     |d          }d|d         i}|                     |                     ||                     d{V }|                     |d          }|                     |          }|                     ||          }d}	d}
d}|| 	                    |d          }t          dt          |                    D ]}||         }|                     |d          }||k    r^|                     |d          }|r nE|                     |d	          }|                     |d
          }
|                     ||          }	 nn|                     |d	          }|t|                    d          dk    rt          | j        dz   dz             |                    d          dk    r&|                    d          }|d         }|d         }
n|}|                     |           |||||
|	dS )a  
        fetch the deposit address for a currency associated with self account
        :see: 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>`
        Nr  r  r7   r  r   r  r  r  r  z3New address is being generated for you, please wait zcNew address is being generated for you, please wait a few seconds and try again to get the address.r   )r%  r  r  r  r  r  )r  r  safe_string_upperr  r  rq  r'  r^  network_code_to_idrB  r\  r]  r   r  r(  r*   r7   r&  check_address)r  r  rC  r  
rawNetworkrw  rx  r  r  r  r  r  r  rg  r  entryNetworkr  addressFieldsplitteds                      r  fetch_deposit_addresszgate.fetch_deposit_addressE  s      !!!!!!!!!==&&++FI>>
69--
 <<T[[RX=Y=YZZZZZZZZ  %%h
;;
&&z22++J==	 2HIII1c)nn-- 
 
!!#//w??,,#'#4#4UO#L#LL# "..ui@@G**5,??C"55iFFGE -  ++Hi@@L'$$%Z[[_```%dgm  7\  '\  ]  ]  ]$$S))Q..+11#66H&qkG"1+CC*G7###
 
 	
r  c                   K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     ||          S )aj  
        fetch the trading fees for a market
        :see: 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  r7   )r  r2  privateWalletGetFeerq  parse_trading_feer  r  rC  r2  rw  rx  s         r  fetch_trading_feezgate.fetch_trading_fee  s       !!!!!!!!!V$$VD\
 11$++gv2N2NOOOOOOOO %%h777r  c                    K   |                                   d{V  |                     |           d{V }|                     |          S )aj  
        fetch the trading fees for multiple markets
        :see: 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_fees)r  rC  rx  s      r  fetch_trading_feeszgate.fetch_trading_fees  sg       !!!!!!!!!11&99999999 &&x000r  c                     i }t          dt          | j                            D ]=}| j        |         }|                     |          }|                     ||          ||<   >|S Nr   )r\  r]  r  r2  r  )r  rx  rf  rg  r  r2  s         r  r  zgate.parse_trading_fees  sh    q#dl++,, 	F 	FA\!_F[[((F!33HfEEF6NNr  c                    |                      |d          }|rdnd}|rdnd}|                      |d          }|rdn|}|rdn|}||                     |d	          |                     ||          |                     ||          d d d
S )Ngt_discountgt_taker_fee	taker_feegt_maker_fee	maker_feer  futures_taker_feefutures_maker_feer  )r%  r  r  r  r  r  )rB  r'  r`  )	r  r%  r2  
gtDiscountr  r  r  takerKeymakerKeys	            r  r  zgate.parse_trading_fee  s     __T=99
",=+",=+??6:66*2=&&*2=&&&&vx88%%dH55%%dH55
 
 	
r  codesc                   K   |                                   d{V  |                     |           d{V }i }i }t          dt          |                    D ]}i }||         }|                     |d          }|                     |          }	||                     |	|          sP|                     |d          }
|
|                     |d          }ngt          |

                                          }t          dt          |                    D ](}||         }|                     |
|                   ||<   )|d|d||	<   |S )a  
         * @deprecated
        please use fetchDepositWithdrawFees instead
        :see: 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   r  withdraw_fix_on_chainswithdraw_fix)r   r  r%  )r  privateWalletGetWithdrawStatusr\  r]  r'  r^  in_arrayrB  r`  listkeysr  )r  r#  rC  rx  rf  withdrawFeesrg  r  r  r  withdrawFixOnChains	chainKeysr  chainKeys                 r  fetch_transaction_feeszgate.fetch_transaction_fees  s      !!!!!!!!!<<VDDDDDDDD$ q#h--(( 	 	ALQKE))%<<J**:66D!4==u+E+E!"&//%9Q"R"R"*#//~FF !4!9!9!;!;<<	q#i..11 ^ ^A(|H-1->->?RS[?\-]-]L**( F4LL
 r  c                    K   |                                   d{V  |                     |           d{V }|                     ||d          S )a{  
        fetch deposit and withdraw fees
        :see: 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  )r  r'  parse_deposit_withdraw_fees)r  r#  rC  rx  s       r  fetch_deposit_withdraw_feesz gate.fetch_deposit_withdraw_fees  sk       !!!!!!!!!<<VDDDDDDDD( //%LLLr  r  c                    |                      |d          }||                     |d          dd|                     |d          ddi d}|vt          |                                          }t	          dt          |                    D ]7}||         }|                     ||                   ddd d dd|d	         |<   8|S )
Nr%  r&  F)r   r  r  )r%  r   r  rs  r   )r   r  rs  )rB  r`  r)  r*  r\  r]  r  )r  r   r  r,  rf  r-  rg  r.  s           r  parse_deposit_withdraw_feezgate.parse_deposit_withdraw_fee=  s   $ #ooc3KLL''^<<# 
 ''Y77#  
 
 *0557788I1c)nn--  $Q<  $001DX1NOO&+! !
  $&*   	0 	0z"8,, r  sincelimitc                 p  K   |                                   d{V  d}||                     |          }|d         }|                     d||          \  }}|                     |||          \  }}	d|d<   ||                     |dz            |d<   |||d<   d}
|d	k    r0|                     |                     ||	                     d{V }
nM|d
k    r0|                     |                     ||	                     d{V }
nt          | j	        dz             | 
                    |
|||          S )a  
        fetch the history of funding payments paid and received on self account
        :see: https://www.gate.io/docs/developers/apiv4/en/#query-account-book-2
        :see: 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    fromr6  r\   r]   z= fetchFundingHistory() only support swap & future market type)r  r2  handle_market_type_and_paramsr  parse_to_int"privateFuturesGetSettleAccountBookrq  #privateDeliveryGetSettleAccountBookr/   r7   parse_funding_histories)r  r  r5  r6  rC  r2  r  r  rw  requestParamsrx  s              r  fetch_funding_historyzgate.fetch_funding_historyl  s      !!!!!!!!![[((FH%F889NPVX^__e!%!5!5fdE!J!J "//==GFO$GG6>>!DDT[[QXZgEhEhiiiiiiiiHHX!EEdkkRY[hFiFijjjjjjjjHHtw)hhiii ++HfeUKKKr  c                    g }t          dt          |                    D ]4}||         }|                     |          }|                    |           5|                     |d          }	|                     |	|||          S )Nr   r/  )r\  r]  parse_funding_historyra  sort_byfilter_by_symbol_since_limit)
r  rx  r  r5  r6  rf  rg  r  rl  sorteds
             r  r?  zgate.parse_funding_histories  s    q#h--(( 	# 	#AQKE0077GMM'""""fk2200NNNr  c           
      <   |                      |d          }|                     |d          }|                     ||dd          }||                     |d          |                     |d          ||                     |          d |                     |d          dS )	Nr   textr  r\   r  r  change)r%  r  r  r/  r.  r7   r  )r  r'  r8  r  r`  )r  r%  r2  r/  r1  s        r  rC  zgate.parse_funding_history  s     ''f55	##D&11!!(FC@@&&vx88$$VX66"Y//&&tX66
 
 	
r  c           	        K   |                                   d{V  |                     |          }|                     ||d         |          \  }}|||d<   d|d<   d}|d         s|d         r0|                     |                     ||                     d{V }n|d         r0|                     |                     ||                     d{V }n|d	         r0|                     |                     ||                     d{V }nO|d
         r0|                     |                     ||                     d{V }nt          | j	        dz             | 
                    |d          }|d         s|dz  }|d         rdnd}	|d         rdnd}
| 
                    |d          }|                     |||dd|	|
          }||d<   |S )a2  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :see: https://www.gate.io/docs/developers/apiv4/en/#retrieve-order-book
        :see: https://www.gate.io/docs/developers/apiv4/en/#futures-order-book
        :see: https://www.gate.io/docs/developers/apiv4/en/#futures-order-book-2
        :see: 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  r6  Twith_idrF   rD   r\   r]   r^   z. fetchOrderBook() not support self market typecurrentr9  r   pr   sr7   bidsasksnonce)r  r2  r  publicSpotGetOrderBookrq  publicFuturesGetSettleOrderBook publicDeliveryGetSettleOrderBookpublicOptionsGetOrderBookr/   r7   r   parse_order_book)r  r  r6  rC  r2  rw  r  rx  r/  priceKey	amountKeyrQ  rf  s                r  fetch_order_bookzgate.fetch_order_book  sC      !!!!!!!!!V$$ --ffVnfMM$GG!	&> 		[VH- 		[!88We9T9TUUUUUUUUHHF^ 	[!AA$++gW\B]B]^^^^^^^^HHH 	[!BB4;;wX]C^C^________HHH 	[!;;DKKQV<W<WXXXXXXXXHHtw)YYZZZB %%h	::	f~ 	)!D(Iv/11C0AAS	!!(D11&&xFFT\^ghhwr  c                   K   |                                   d{V  |                     |          }|                     |d|          \  }}d}|d         s|d         r0|                     |                     ||                     d{V }n|d         r0|                     |                     ||                     d{V }n|d         r0|                     |                     ||                     d{V }n|d         rf|d         }|                    d          }|                     |d	          |d
<   | 	                    |                     ||                     d{V }nt          | j        dz             d}	|d         r?t          d	t          |                    D ] }
||
         }|d         |d         k    r|}	 n!n|                     |d	          }	|                     |	|          S )a  
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
        :see: https://www.gate.io/docs/developers/apiv4/en/#get-details-of-a-specifc-order
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-futures-tickers
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-futures-tickers-2
        :see: 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>`
        NrF   rD   r\   r]   r^   r7   r  r   r  z+ fetchTicker() not support self market typer8   )r  r2  r  publicSpotGetTickersrq  publicFuturesGetSettleTickerspublicDeliveryGetSettleTickersr&  r'  publicOptionsGetTickersr/   r7   r\  r]  rB  parse_ticker)r  r  rC  r2  rw  r  rx  r1  r+  tickerrg  r  s               r  fetch_tickerzgate.fetch_ticker)	  sH      !!!!!!!!!V$$--fdFCC&> 	XVH- 	X!66t{{7E7R7RSSSSSSSSHHF^ 
	X!??GUZ@[@[\\\\\\\\HHH 	X!@@WV[A\A\]]]]]]]]HHH 	Xd|H"..--K$($4$4[!$D$DGL!!99$++gu:U:UVVVVVVVVHHtw)VVWWW( 	21c(mm,,   =F4L00"FE 1 __Xq11F  000r  c                 L   |                      |g d          }d|v rdnd}|                     ||d|          }|                     |dd          }|                      |g d          }|                      |g d	          }|                     |d
          }	|                     |d          }
|                     |dd          }|                     |dd          }|                     |d          }|                     |dd          }|dk    rd}|                     |dd          }|dk    rd}|                     |d          }|                     i d|d|d|                     |          d|	d|
d|d|d|d |d!d d"d d#|d|d$d d%d d&|d'd |||d(|          S ))N)r  r  r8   r~  r  rF   r  last
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nanry  quote_volumevolume_24h_quotechange_percentager  r/  r.  highlowbid	bidVolumeask	askVolumevwapopenclosepreviousCloserI  r  average)
baseVolumequoteVolumer%  )safe_string_nr  safe_string_2r'  r   safe_tickerr  )r  r`  r2  r1  r4  r  rc  r|  rz  rx  ry  r{  r}  r/  r  r  r  s                    r  r_  zgate.parse_tickerP	  s   J %%f.S.S.STT$0F$:$:ZZ
!!(FCDD!!&&,??  )J)J)JKK  )K)K)KLL
33vy11&&vsK@@	&&vsK@@	%%fc22	''?PQQ
J((ASTT%K%%f.ABB
 !
f!
!
 Y//!
 D	!

 3!
 3!
 !
 3!
 !
 D!
 D!
 T!
 D!
 T!
 d!
  *!!
" t#!
$ %&)!
 !
 !
* +  	r  c                   K   |                                   d{V  |                     |          }|                     |d          }d}||                     |          }|                     d||          \  }}|                     d||          \  }}d}	d|d<   |dk    s|dk    r1|                     |                     ||                     d{V }	n|dk    r0|                     |                     ||                     d{V }	n|d	k    r0| 	                    |                     ||                     d{V }	n|d
k    r}| 
                    d|d           |d         }
|
                    d          }|                     |d          |d<   |                     |                     ||                     d{V }	nt          | j        dz             |                     |	|          S )a.  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
        :see: https://www.gate.io/docs/developers/apiv4/en/#get-details-of-a-specifc-order
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-futures-tickers
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-futures-tickers-2
        :see: 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timezonerF   rD   r\   r]   r^   r  r7   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'  r2  r;  r  r[  rq  r\  r]  check_required_argumentr&  r^  r/   r7   parse_tickers)r  r  rC  firstr2  r  r  rw  r@  rx  r1  r+  s               r  fetch_tickerszgate.fetch_tickers	  sF      !!!!!!!!!%%g..  !,,[[''F88QWXXe!%!5!5dD%!H!H$
6>>TX--!66t{{7M7Z7Z[[[[[[[[HHV^^!??GUb@c@cddddddddHHX!@@WVcAdAdeeeeeeeeHHX(()LLLd|H"..--K$($4$4[!$D$DGL!!99$++g}:]:]^^^^^^^^HHtw  *q   q  r  r  r!!(G444r  c                     |                                  }|                     |dd          |d<   |                     |d          |d<   |                     |d          |d<   d|v r|                     |d          |d<   |S )	Nfreezelockedused	availablefreetotalborroweddebt)rN   r  r'  )r  r  rN   s      r  parse_balance_helperzgate.parse_balance_helper	  s    ,,..,,UHhGG**5+>>++E7;;"..ujAAGFOr  c                 4	  K   |                                   d{V  |                     |d          }|                     |d          }|                     dd|          \  }}|                     d||          \  }}|                     d|          \  }}| |                     |          }	|	d         |d<   d}
|dk    r|dk    r1|                     |                     ||                     d{V }
nt|dk    r1| 	                    |                     ||                     d{V }
n=|d	k    r1| 
                    |                     ||                     d{V }
nt          | j        d
z             |dk    r0|                     |                     ||                     d{V }
n|dk    r0|                     |                     ||                     d{V }
n|dk    r0|                     |                     ||                     d{V }
nM|dk    r0|                     |                     ||                     d{V }
nt          | j        dz             |dk    p|dk    p|dk    }|r|
g}
d|
i}|dk    }|
}d|v rg }|                     |dg           }t%          |                                          }t)          dt+          |                    D ],}||         }||         }||d<   |                    |           -|}t)          dt+          |                    D ]H}||         }|r|                     |d          }|                     |ddd          }|                     |di           }|                     |di           }|                     |                     |d                    }|                     |                     |d                    }i }|                     |          ||<   |                     |          ||<   |                     |          ||<   |                     |                     |d                    }|                     |          ||<   J|r|n|                     |          }|S )a)  
        :param dict [params]: exchange specific parameters
        :param str [params.type]: spot, margin, swap or future, if not provided self.options['defaultType'] is used
        :param str [params.settle]: 'btc' or 'usdt' - settle currency for perpetual swap and future - default="usdt" for swap and "btc" for future
        :param str [params.marginMode]: 'cross' or 'isolated' - marginMode for margin trading if not provided self.options['defaultMarginMode'] is used
        :param str [params.symbol]: margin only - unified ccxt symbol
        Nr  rs   Fr7   r  rF   rD   rk  z+ fetchBalance() not support self marginModerl  r\   r]   r^   z, fetchBalance() not support self market typer%  balancesr   r  r  r  r
  )r  r'  r  r;  r  r  r2  privateSpotGetAccountsrq  privateMarginGetAccountsprivateMarginGetCrossAccountsr/   r7   privateMarginGetFundingAccountsprivateFuturesGetSettleAccounts privateDeliveryGetSettleAccountsprivateOptionsGetAccountsrB  r)  r*  r\  r]  ra  r  r^  r  safe_balance)r  rC  r  r  r  rw  r@  r  requestQueryr2  rx  r  rf  rn  dataflatBalancesr  r*  rg  r  contentr  r1  symbolInnerr  r
  baseCode	quoteCode	subResultr  returnResults                                  r  fetch_balancezgate.fetch_balance	  s)      !!!!!!!!!!!&(3368,,88vVVe!%!5!5dD%!H!H#'#7#7}#M#M 
L[[((F'-d|GO$6>>V##!%!<!<T[[R^=_=_!`!```````x''!%!>!>t{{7T`?a?a!b!bbbbbbb~--!%!C!CDKKPWYeDfDf!g!ggggggg"47-Z#Z[[[Y!AA$++gWcBdBdeeeeeeeeHHV^^!AA$++gWcBdBdeeeeeeeeHHX!BB4;;wXdCeCeffffffffHHX!;;DKKQ]<^<^________HHtw)WWXXXV^P)9Ptx?O 	" zH^ H
 )LtZ<<H ((D1c$ii(( - -!!W
":.&0
###G,,,,Dq#d))$$ 	@ 	@AGE @++E?CC"..xsHMMufb99w;;2243C3CD*3U3UVV 33D4D4DUJ4W4WXX		&*&?&?&E&E	(#'+'@'@'G'G	)$&*&7&7	&B&B{##..t/?/?z/R/RSS#88??t!)Hvvt/@/@/H/Hr  r!  c           	        K   |                                   d{V  |                     |          }d}|                     |dd          \  }}|r!|                     d|||||d           d{V S |d         r|                     |||||           d{V S |                     |d          }i }	|                     |d|          \  }	}|                     | j        ||          |	d<   |d	         rd
nd}
||
nt          ||
          }| 	                    |d          }|.| 
                    |dz            }|                     |d          }||                     |          }| 
                    |dz            |	d<   |dz
  |z  }|                     |	d         |          }|                                 }t          ||          }|t          ||          |	d<   n||	d<   n|||	d<   ||	d<   d}|d	         rd
}
|dk    }|dk    }|s|r'|dz   |d         z   |	d	<   |                     |d          }|d         r0|                     |                     |	|                     d{V }ng|d         r/|                     |                     |	|                     d{V }n/|                     |                     |	|                     d{V }|                     |||||          S )a  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :see: https://www.gate.io/docs/developers/apiv4/en/#market-candlesticks       # spot
        :see: https://www.gate.io/docs/developers/apiv4/en/#get-futures-candlesticks  # swap
        :see: https://www.gate.io/docs/developers/apiv4/en/#market-candlesticks       # future
        :see: 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   paginater9  r^   r  intervalr  i  untilr:  r   tor6  markindexr  r7   r]   r\   )r  r2  handle_option_and_params"fetch_paginated_call_deterministicfetch_option_ohlcvr'  r  r  r  r   r<  r  parse_timeframesumseconds#publicDeliveryGetSettleCandlesticksrq  "publicFuturesGetSettleCandlestickspublicSpotGetCandlesticksparse_ohlcvs)r  r  	timeframer5  r6  rC  r2  r  r  rw  maxLimitr  durationdistancetoTimestampcurrentTimestampr  rx  isMarkisIndexs                       r  fetch_ohlcvzgate.fetch_ohlcv
  s     " !!!!!!!!!V$$88zZZ& 	~@@vW\^cenpvx|}}}}}}}}}( 	Z00E5RXYYYYYYYYY  11..vtVDD"..t	9UU
!*-7444"]UH1E1E!!&'22%%edl33EYYvw//F++I66H"//==GFO	X-H((76?H==K#||~~["233B  #B "  %$GG* 	ZHvoF'G 4 4&+ckF4L&@
#6733h g!%!I!I$++V]_eJfJf!g!ggggggg g!%!H!HU\^dIeIe!f!fffffff!;;DKKQW<X<XYYYYYYYYH  69eUKKKr  c                 j  K   |                                   d {V  |                     |          }i }|                     |d |          \  }}|                     | j        ||          |d<   |                     |                     ||                     d {V }|                     |||||          S )Nr  )r  r2  r  r'  r  publicOptionsGetCandlesticksrq  r  )	r  r  r  r5  r6  rC  r2  rw  rx  s	            r  r  zgate.fetch_option_ohlcv  s      !!!!!!!!!V$$..vtVDD"..t	9UU
::4;;wPV;W;WXXXXXXXX  69eUKKKr  c           
        K   |t          | j        dz             |                                  d{V  |                     |          }|d         st	          | j        dz             |                     |d|          \  }}|||d<   |                     |                     ||                     d{V }g }	t          dt          |                    D ]b}
||
         }| 
                    |d          }|	                    |||                     |d          ||                     |          d	           c|                     |	d
          }|                     ||d         ||          S )a  
        fetches historical funding rate prices
        :see: 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
        :returns dict[]: a list of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>`
        Nz5 fetchFundingRateHistory() requires a symbol argumentr\   z7 fetchFundingRateHistory() supports swap contracts onlyr6  r   rq  r)r%  r  r  r/  r.  r/  r  )r'   r7   r  r2  r)   r  !publicFuturesGetSettleFundingRaterq  r\  r]  r  ra  r`  r  rD  rE  )r  r  r5  r6  rC  r2  rw  r  rx  ratesrg  r  r/  rF  s                 r  fetch_funding_rate_historyzgate.fetch_funding_rate_history  s      >#DG.e$efff!!!!!!!!!V$$f~ 	aDG&__```--fdFCC$GG??GUZ@[@[\\\\\\\\ q#h--(( 		 		AQKE++E377ILL #//s;;& LL33      e[11009I5RWXXXr  c           	      ,   t          |t                    r|                     |d          |                     |d          |                     |d          |                     |d          |                     |d          |                     |d          gS |                     |d          |                     |d          |                     |d	          |                     |d
          |                     |d          |                     |d          gS )Nr      r     r     rq  ohlrv  v)
isinstancer)  r  r`  )r  ohlcvr2  s      r  parse_ohlcvzgate.parse_ohlcv9  s   2 eT"" 	##E1--  **  **  **  **  **  ##E3//  ,,  ,,  ,,  ,,  ,, r  c                 f  K   |                                   d{V  d}|                     |dd          \  }}|r|                     d||||           d{V S |                     |          }|                     |d|          \  }}|                     |dd          }	|	2|                     |dg          }|                     |	dz            |d<   |t          |d          |d<   |#|d	         r|                     |dz            |d
<   d}
|d         dk    s|d         dk    r0| 	                    | 
                    ||                     d{V }
n|d         r0|                     | 
                    ||                     d{V }
n|d         r0|                     | 
                    ||                     d{V }
nS|d         dk    r0|                     | 
                    ||                     d{V }
nt          | j        dz             |                     |
|||          S )an  
        get the list of most recent trades for a particular symbol
        :see: https://www.gate.io/docs/developers/apiv4/en/#retrieve-market-trades
        :see: https://www.gate.io/docs/developers/apiv4/en/#futures-trading-history
        :see: https://www.gate.io/docs/developers/apiv4/en/#futures-trading-history-2
        :see: 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   r  r  r  r9  r6  r  r:  r  rF   rD   r\   r]   r^   z, fetchTrades() not support self market type.)r  r  fetch_paginated_call_dynamicr2  r  safe_integer_2r  r<  r  publicSpotGetTradesrq  publicFuturesGetSettleTradespublicDeliveryGetSettleTradespublicOptionsGetTradesr/   r7   parse_trades)r  r  r5  r6  rC  r  r2  rw  r  r  rx  s              r  fetch_tradeszgate.fetch_tradesf  s      !!!!!!!!!88PZ[[& 	h::=&RWY^`fgggggggggV$$, --fdFCC##FD'::YYvy11F --edl;;GDM"5$//GG&"4"//==GFO&>V##vf~'A'A!55dkk'56Q6QRRRRRRRRHHF^ 	Y!>>t{{7TY?Z?Z[[[[[[[[HHH 	Y!??GUZ@[@[\\\\\\\\HHF^x''!88We9T9TUUUUUUUUHHtw)WWXXXR   65%@@@r  r7   c                    K   |t          | j        dz             |                                  d{V  |                     |||d|i           d{V }|S )aD  
        fetch all the trades made from a single order
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-personal-trading-history
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-personal-trading-history-2
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-personal-trading-history-3
        :see: 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)r'   r7   r  fetch_my_trades)r  r7   r  r5  r6  rC  rx  s          r  fetch_order_tradeszgate.fetch_order_trades  s       >#DG.^$^___!!!!!!!!!( --feUZQSDTUUUUUUUUr  c                   K   |                                   d{V  d}|                     |dd          \  }}|r|                     d||||           d{V S d}d}i }||                     |          nd}	|                     |dd          }
|                     |ddg          }|                     d|	|          \  }}|dk    p|dk    p|d	k    }|r7|                     |	||          \  }}|d	k    r|                     |d
          }n+|	|	d         |d<   |                     d|          \  }}||d<   |||d<   || 	                    |dz            |d<   |
| 	                    |
dz            |d<   d}|dk    s|dk    r0| 
                    |                     ||                     d{V }n|dk    r0|                     |                     ||                     d{V }n|dk    r0|                     |                     ||                     d{V }nM|d	k    r0|                     |                     ||                     d{V }nt          | j        dz             |                     ||	||          S )a  
        Fetch personal trading history
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-personal-trading-history
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-personal-trading-history-2
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-personal-trading-history-3
        :see: 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 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=trade-structure>`
        NFr   r  r  tillr\   r]   r^   r  r7   r  rN   r6  r9  r:  r  rF   rD   z. fetchMyTrades() not support self market type.)r  r  r  r2  r  r  r;  r  r  r<  privateSpotGetMyTradesrq  (privateFuturesGetSettleMyTradesTimerange privateDeliveryGetSettleMyTradesprivateOptionsGetMyTradesr/   r7   r  )r  r  r5  r6  rC  r  r  r  rw  r2  r  r  rx  s                r  r  zgate.fetch_my_trades  s(     . !!!!!!!!!88R\]]& 	j::?FTY[`bhiiiiiiiii
)/);V$$$$##FGV<<6GV#45599/6SYZZfFNO(8Odh>N 	,"2264HHOGVx6:66!+1$<(!%!5!5eV!D!DJ!+GI$GG"//==GFO --edl;;GDM6>>TX--!88Wf9U9UVVVVVVVVHHV^^!JJ4;;W^`fKgKghhhhhhhhHHX!BB4;;wX^C_C_````````HHX!;;DKKQW<X<XYYYYYYYYHHtw)YYZZZB   65%@@@r  c                 \   |                      |dd          }|                     |dd          }|                     |d|          }|                      |dd          }d|v rdnd}|                     ||d	|          }|                      |d
d          }|                     |d          }t          j        |d          rdnd}	t          j        |          }|                      |dd|	          }
|                     |d          }|                     |d          }|                     |d          }|                     |d          }g }|[|                     |d          }|                     |          }||                     |d          }|	                    ||d           ||	                    |dd           ||	                    |dd           |                     |d          }| 
                    ||||                     |          |d         |d |
|||d d |d|          S )Nr7   trade_idr   r  create_time_msr  r  rF   r  r  sizer  ry  sellbuysider  r  r   gt_fee	point_feefee_currencyr  )r  r  GTr?  roler  )r%  r7   r/  r.  r  orderr  r  takerOrMakerr  r  r  r   rx  )r  safe_timestamp_2r   r8  r'  r3   	string_lt
string_absr^  ra  
safe_trader  )r  trader2  r7   r/  r1  r4  amountStringpriceStringcontractSider  orderId	feeAmountgtFeepointFeerx  feeCurrencyIdfeeCurrencyCoder  s                      r  parse_tradezgate.parse_tradeu  s   r tZ88))%GG	%%e-=yII	%%e_jII$.%$7$7ZZf
!!(FCDD))%6BB&&ug66!(!2<!E!EPvv5),77!!%FF""5*55$$UE22	  11##E;77  ,,UNCCM"55mDDO&"&"2"268"D"DKK!+     KK      KK '     ''v66"Y//X&( " 
  
   	r  c                 <  K   |                                   d{V  d}|                     |dd          \  }}|r|                     d||||           d{V S i }d}| |                     |          }|d         |d<   |||d<   |6|                     |dz            }||d	<   |                     |d
          |d<   |                     d||          \  }}|                     |                     ||                     d{V }	| 	                    |	|          S )a@  
        fetch all deposits made to an account
        :see: 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 int [params.until]: end time in ms
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :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{   r  r7   r  r6  r9  r:   ' r  )
r  r  r  r  r<  r  handle_until_optionprivateWalletGetDepositsrq  parse_transactions
r  r  r5  r6  rC  r  rw  r  startrx  s
             r  fetch_depositszgate.fetch_deposits  si      !!!!!!!!!88R\]]& 	h::?DRWY^`fggggggggg}}T**H"*4.GJ$GG%%edl33E#GFO HHU,=>>GDM224&II66t{{7F7S7STTTTTTTT&&x:::r  c                 <  K   |                                   d{V  d}|                     |dd          \  }}|r|                     d||||           d{V S i }d}| |                     |          }|d         |d<   |||d<   |6|                     |dz            }||d	<   |                     |d
          |d<   |                     d||          \  }}|                     |                     ||                     d{V }	| 	                    |	|          S )aN  
        fetch all withdrawals made from an account
        :see: 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   r  r7   r  r6  r9  r:  r
  r  )
r  r  r  r  r<  r  r  privateWalletGetWithdrawalsrq  r  r  s
             r  fetch_withdrawalszgate.fetch_withdrawals#  sk      !!!!!!!!!88ASU_``& 	k::;MtUZ\acijjjjjjjjj}}T**H"*4.GJ$GG%%edl33E#GFO HHU,=>>GDM224&II99$++gv:V:VWWWWWWWW&&x:::r  r  c                 |  K   |                      ||          \  }}|                     |           |                                  d{V  |                     |          }|d         ||                     ||          d}|||d<   |                     | j        di           }|                     |d          }	|                     ||	|	          }	|	|	|d<   | 	                    |d          }n|d         |d<   | 
                    |                     ||                     d{V }
|                     |
|          S )a  
        make a withdrawal
        :see: 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>`
        Nr7   )r  r  r  memors  r  r  )handle_withdraw_tag_and_paramsr  r  r  currency_to_precisionrB  rG   r  r  r  !privateWithdrawalsPostWithdrawalsrq  parse_transaction)r  r  r  r  r  rC  r  rw  rs  r  rx  s              r  r   zgate.withdrawC  se      99#vFFV7###!!!!!!!!!==&& 00v>>
 

 ?!GFO??4<R@@((;;((7GDD&GGYYvy11FF'~GG??GU[@\@\]]]]]]]] %%h999r  c                 P    dddddddddddddd}|                      |||          S )Npendingcanceledfailedok)PENDREQUESTDMOVEMANUALVERIFYPROCESEXTPEND	SPLITPENDCANCELFAILINVALIDDONEBCODEr'  r  statusstatusess      r  parse_transaction_statuszgate.parse_transaction_statusm  sO      " 
 
 &&999r  c                 :    ddd}|                      |||          S )Nr  
withdrawal)dwr,  )r  r  typess      r  parse_transaction_typezgate.parse_transaction_type  s.    
 
 tT222r  c                 
   |                      |d          }d }|                      |d          }|U|d         dk    r.t          j        |d          rdnd}t          j        |          }n|                     |d                   }|                      |d          }|dk    rt          j        ||          }|                     |d	          }|                      |d
          }|                     |          }	|                      |d          }
|                      |d          }|                     |          }|                      |d          }|                      |d          }| 	                    |d          }i d|d|d|
d
|	d| 
                    |          d|                     |          d|dd dd d|dd dd d|d|d|d|                     |          dd d d |	| 
                    |          ddS )Nr7   r  r   ri  ry  r  r2  r   r  r  txidr.  r  r  r/  r%  r  	addressToaddressFromr  tagTotagFromr  r.  updatedr  r  )internalcommentr   )r'  r3   	string_gtr  r6  r  r  r^  r0  r  r  r  r  )r  transactionr  r7   r  r  feeCostStringr  r  r  r8  	rawStatusr.  r  r  r/  s                   r  r  zgate.parse_transaction  s   @ k400''X>>>!u||$+$5lC$H$HZyyl&1,??222a599((e<<<"-lMJJL**;@@	%%k:>>
&&z22V44$$[(;;	..y99"";	::{F33''[AA	
K
"
 D
 	

 d''55
 t..y99
 w
 
 4
 3
 T
 t
 f
 D
 
  Y//!
" t#
$  ))-88 )
 
 
 	
r  r  r  r  c                 t  K   |                                   d{V  |                     |          }|                     |d          }|                     |dd          }	|                     |d|	          }
|                     |d          }|
du}|du}|p|}| o|du }|                     ||||||          }d}|d         s|d         r:|r|                     |           d{V }n|                     |           d{V }n|d	         r:|r|                     |           d{V }ny|                     |           d{V }n]|d
         r:|r| 	                    |           d{V }n7| 
                    |           d{V }n|                     |           d{V }|                     ||          S )a[  
        Create an order on the exchange
        :see: https://www.gate.io/docs/developers/apiv4/en/#create-an-order
        :see: https://www.gate.io/docs/developers/apiv4/en/#create-a-price-triggered-order
        :see: https://www.gate.io/docs/developers/apiv4/en/#create-a-futures-order
        :see: https://www.gate.io/docs/developers/apiv4/en/#create-a-price-triggered-order-2
        :see: https://www.gate.io/docs/developers/apiv4/en/#create-a-futures-order-2
        :see: https://www.gate.io/docs/developers/apiv4/en/#create-a-price-triggered-order-3
        :see: 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]: *ignored in "market" orders* the price at which the order is to be fullfilled at in units of the quote currency
        :param dict [params]:  extra parameters specific to the exchange API endpoint
        :param float [params.stopPrice]: The price at which a trigger order is triggered at
        :param str [params.timeInForce]: "GTC", "IOC", or "PO"
        :param float [params.stopLossPrice]: The price at which a stop loss order is triggered at
        :param float [params.takeProfitPrice]: The price at which a take profit order is triggered at
        :param str [params.marginMode]: 'cross' or 'isolated' - marginMode for margin trading if not provided self.options['defaultMarginMode'] is used
        :param int [params.iceberg]: Amount to display for the iceberg order, Null or 0 for normal orders, Set to -1 to hide the order completely
        :param str [params.text]: User defined information
        :param str [params.account]: *spot and margin only* "spot", "margin" or "cross_margin"
        :param bool [params.auto_borrow]: *margin only* Used in margin or cross margin trading to allow automatic loan of insufficient amount if balance is not enough
        :param str [params.settle]: *contract only* Unified Currency Code for settle currency
        :param bool [params.reduceOnly]: *contract only* Indicates if self order is to reduce the size of a position
        :param bool [params.close]: *contract only* Set to close the position, with size set to 0
        :param bool [params.auto_size]: *contract only* Set side to close dual-mode position, close_long closes the long side, while close_short the short one, size also needs to be set to 0
        :param int [params.price_type]: *contract only* 0 latest deal price, 1 mark price, 2 index price
        :param float [params.cost]: *spot market buy only* the quote quantity that can be used alternative for the amount
        :returns dict|None: `An order structure <https://docs.ccxt.com/#/?id=order-structure>`
        NtriggertriggerPrice	stopPricestopLossPricetakeProfitPricerF   rD   r\   r]   )r  r2  rB  safe_value_2create_order_requestprivateSpotPostOrdersprivateSpotPostPriceOrdersprivateFuturesPostSettleOrders#privateFuturesPostSettlePriceOrdersprivateDeliveryPostSettleOrders$privateDeliveryPostSettlePriceOrdersprivateOptionsPostOrdersparse_order)r  r  r  r  r  r  rC  r2  rF  rG  rI  rJ  isStopLossOrderisTakeProfitOrderisStopOrdernonTriggerOrderorderRequestrx  s                     r  create_orderzgate.create_order  s\     B !!!!!!!!!V$$//&)44((MMNN//&2CDD't3+47%:):)/?w$00tVUTZ[[&> 	IVH- 	I O!%!;!;L!I!IIIIIII!%!@!@!N!NNNNNNNF^ 	I X!%!D!D\!R!RRRRRRR!%!I!I,!W!WWWWWWWH 	I Y!%!E!El!S!SSSSSSS!%!J!J<!X!XXXXXXX!::<HHHHHHHHHB &111r  r   c           	      2  K   |                                   d{V  g }g }t          dt          |                    D ] }||         }|                     |d          }|                    |           |                     |d          }|                     |d          }	|                     |d          }
|                     |d          }|                     |di           }|                     ||          }|                     |g d	          }|t          | j	        d
z             d|d<   | 
                    |||	|
||          }|                    |           "|                     |dddd          }|                     |d                   }|d         s|d         rt          | j	        dz             d}|d         r|                     |           d{V }n#|d         r|                     |           d{V }|                     |          S )a  
        create a list of trade orders
        :see: https://www.gate.io/docs/developers/apiv4/en/#get-a-single-order-2
        :see: https://www.gate.io/docs/developers/apiv4/en/#create-a-batch-of-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
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr   r  r  r  r  r  rC  )rG  rH  rJ  rI  ze createOrders() does not support advanced order properties(stopPrice, takeProfitPrice, stopLossPrice)TtextIsRequiredFr]   r^   z; createOrders() does not support futures or options marketsrF   r\   )r  r\  r]  r'  ra  rB  rq  safe_value_nr/   r7   rL  r  r2  privateSpotPostBatchOrders#privateFuturesPostSettleBatchOrdersparse_orders)r  r   rC  ordersRequestsorderSymbolsrg  rawOrderr1  r  r  r  r  orderParamsextendedParamstriggerValuerY  r  r2  rx  s                      r  create_orderszgate.create_ordersV  sg      !!!!!!!!!q#f++&& 	0 	0AayH''(;;H)))##Hf55D##Hf55D__Xx88FOOHg66E//(HbAAK![[f==N,,[:{:{:{||L'"47  .U  $U  V  V  V/3N+,44XtT6SXZhiiL!!,////%%lD%tLLWQZ((( 	hvh/ 	htw)ffggg&> 	V!<<^LLLLLLLLHHF^ 	V!EEnUUUUUUUUH  ***r  c                 p   |                      |          }|d         }|                     |d          }	|                     |dd          }
|                     |d|
          }|                     |d          }|d u}|d u}|p|}|r|rt          | j        dz             |                     |d          }|                     |g d	          }d }|                     |d
k    |dk    |          \  }}|                     |          }|rd}|                     |g d          }|dk    }|d
k    }|r|t          | j        dz   |z   dz             |ri|dk    s|dk    rt          | j        dz             |@| 
                    | j        dd          }| 
                    | j        d         |d          }|}|rd}|r\|                     |d          }|rd}nA|                     ||          }|dk    rt          j        |          n|}t          |          }d }| o|	d u }|rU|rO|d         |d}|d         s|d         |d<   |r||d<   n|                     ||          |d<   |||d<   |||d <   n\d }|                     d!|          \  }}|d         |||d"}|r|d#k    rd }d$}|                     |d%d&d$          \  }}|                     |d'          } |                     |d'          }| |                     ||           }n|ro|t+          | j        d(z             |                     |          }!|                     |          }"t          j        |!|"          }#|                     ||#          }n|                     ||          }||d)<   n|                     ||          |d)<   |r|                     ||          |d<   |||d*<   |                     |d+d,          }$|                     |d-d!          }%|$Zt5          |$          d.k    rt7          | j        d/z             |                     |g d0          }|$d         d1k    rd2|$z   }$|$|d+<   nG|%rd2|                                 z   |d+<   n)|d         rt;          | j        d3z             |r|d         ||                     ||          d4|d         d5}|	d }&d }'|r!|d#k    rd6nd7}&|                     ||          }'n"|r |d#k    rd7nd6}&|                     ||          }'|                     |d8d          }(|(dk     s|(d7k    rt7          | j        d9z             |                     |d8g          }|(|                     ||'          |&d:|d<   |||d;         d<   |||d;         d <   n
|                     | j        d%i           })d }|                     d$|          \  }}|d}|||                     ||          |                     ||          ||d<|d         d=}|	|                     |)d>          }*|                     |d>|*          }+d }&d }'|r!|d#k    rd?nd@}&|                     ||          }'n"|r |d#k    rd@nd?}&|                     ||          }'|                     ||'          |&|+dA|d<   |                     ||          S )BNr  rF  rG  rH  rI  rJ  zG createOrder() stopLossPrice and takeProfitPrice cannot both be defined
reduceOnly)rt  tiftime_in_forcer2  re  )rH  rG  rI  rJ  ri  rt  postOnlyr6  z- createOrder() requires a price argument for  ordersrc  zF createOrder() timeInForce for market order can only be "FOK" or "IOC"defaultTimeInForcerg  rt  rd  r   r  r  r7   )r  r  r^   r  r  r  reduce_onlyrj  F)r  r  rN   r  r  Trh   !createMarketBuyOrderRequiresPricer  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  rk  rH  clientOrderIdr\     zF createOrder() clientOrderId or text param must be up to 28 characters)rH  rq  r\  rq  t-z: createOrder() conditional option orders are not supported)r  r  r  )initialr  r   r  
price_typezT createOrder() price_type should be 0 latest deal price, 1 mark price, 2 index price)ru  r  rulert  )r  r  r  r  rN   rk  )r   r2  rL  z>=z<=)r  rv  rL  ) r2  rB  rK  r"   r7   safe_string_lower_nhandle_post_onlyhandle_time_in_forcer  r'   r'  rG   amount_to_precisionr3   
string_negintprice_to_precisionr  r  r`  cost_to_precisionr,   number_to_stringr  r  r;  r]  r(   uuid16r/   r   rq  ),r  r  r  r  r  r  rC  r2  r  rF  rG  rI  rJ  rU  rV  rW  ri  exchangeSpecificTimeInForcerl  rt  isLimitOrderisMarketOrder
defaultTifexchangeSpecificTifisCloseamountToPrecisionsignedAmountrw  rX  r  quoteAmountrp  r  r  r   costRequestrq  r\  rv  triggerOrderPrice	priceTyperG   defaultExpirationrL  s,                                               r  rL  zgate.create_order_request|  s   V$$*%//&)44((MMNN//&2CDD't3+47%:): 	u0 	u*s sttt__V\::
&*&>&>vGnGnGn&o&o#001AC^bgCgiopp&//77 	 K 6  $N  $N  $N  O  O) 	rEM#DG.]$]`d$dgp$pqqq 		u$$+*>*>#DG.v$vwww&!%!1!1$,@TV[!\!\J*.*:*:4<;VXbdi*j*j'"5K  	+oofg66G +$($<$<VV$L$L!IMQWw12CDDD^o\**)/?w$ ^	 =; !'t"	 	 h' ;(.z(:GH%  N',GG$$'+'>'>vu'M'MGG$)-7GM**%0GEN!
%)%9%9%%H%H"
F &,D\ ) 
 
 ! Qdemm"&K8<5@D@]@]^dfs  vY  [_  A`  A`=5v++FF;;D!YYvv66F'&*&<&<VT&J&J: 	M =".tw  :E  0E  #F  #F  F+/+@+@+H+HL*.*?*?*F*FK*1*<\;*W*WK*.*@*@*U*UKK&*&<&<VV&L&L(3GH%%(,(@(@(P(PGH% N'+'>'>vu'M'MGG$*/:GO, ..vvOOM!^^F4DeLLN(
 }%%**$TW/w%wxxx6+V+V+VWW #s**$(=$8M"/! ;&*T[[]]&:GFOh k"47-i#ijjj K %+4L &!%!8!8!G!G    %Z0  ?D(,%& ] &*U]]qq,0,C,CFM,Z,Z))* ]%)U]]qq,0,C,CFO,\,\) $ 1 1&, J JI 1}}	A(  4J  *J  K  K  K!YYv~>>F '0!%!8!8AR!S!S $	* *GI& )8BGI&}5*0;GI&u- //$,rJJ!
%)%9%9$%G%G"
F&"'K !% $!%!8!8!G!G"&":":66"J"J#-)4  %Tl
 
 ?(,(9(9'<(P(P%!%!2!26<IZ![![JD(,%& ] )-ttD,0,C,CFM,Z,Z))* ](,ttD,0,C,CFO,\,\)!%!8!8AR!S!S $&0* *GI&
 {{7F+++r  r  c                    K   |                                   d{V  |                     |          }|d         st          | j        dz             d|d<   |                     |dd|d|           d{V S )a  
        create a market buy order by providing the symbol and cost
        :see: 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
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        NrF   z9 createMarketBuyOrderWithCost() supports spot orders onlyFrp  r2  r  )r  r2  r/   r7   rZ  )r  r  r  rC  r2  s        r  !create_market_buy_order_with_costz&gate.create_market_buy_order_with_costK  s       !!!!!!!!!V$$f~ 	ftw)ddeee6;23&&vxdFSSSSSSSSSr  c                 d  K   |                                   d{V  |                     |          }|                     d||          \  }	}
|                     |	          }|dk    }|dk    r%|s#t	          | j        dz   |z   dz   |	z   dz             ||d         |d	}|m|d         r|                     ||          |d
<   nK|dk    r,t          j        |                     ||                    |d<   n|                     ||          |d<   || 	                    ||          |d<   d}|d         r0| 
                    |                     ||
                     d{V }n:|d         |d<   |                     |                     ||
                     d{V }|                     ||          S )aj  
        edit a trade order, gate currently only supports the modification of the price or amount fields
        :see: https://www.gate.io/docs/developers/apiv4/en/#amend-an-order
        :see: 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 fullfilled, in units of the base currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nrr   r6  rF   z editOrder() does not support z orders for  marketsr7   )r  r  rN   r  r  r  r  r  r  )r  r2  r;  convert_type_to_accountr,   r7   rz  r3   r{  r}  privateSpotPatchOrdersOrderIdrq  $privateFuturesPutSettleOrdersOrderIdrT  )r  r7   r  r  r  r  r  rC  r2  r4  r  rN   r  rw  rx  s                  r  
edit_orderzgate.edit_order[  s      !!!!!!!!!V$$ >>{FTZ[[
E..z::f A"47-M#MPT#TWe#ehr#ru#  A  A  A#D\
 

 f~ O$($<$<VV$L$L!!6>>&-&89Q9QRXZ`9a9a&b&bGFOO&*&>&>vv&N&NGFO#66vuEEGG&> 	d!??GUZ@[@[\\\\\\\\HH &z 2GH!FFt{{SZ\aGbGbccccccccH@ &111r  c                 L    dddddddddddd}|                      |||          S )Nr  closedr  )r  _newfilled	cancelled
liquidatedrd  r  expiredfinishedfinish	succeededr,  r-  s      r  parse_order_statuszgate.parse_order_status  sI    #" ! !
 
 &&999r  c                 
   |                      |dd          }|s-|                     |                     |d          |dd          S |                     |ddi           }|                     |di           }|                     |d	          }|                     |d
          }|                     |dd          }|                     |dd          }	|                     |d          }
|                     |d          }|                     |d	|          }|                     |d
|          }|                     |dd|          }|dk    rd}|dk    }|                     |dd|	          }	|                     |d|
          }
|                     |d|          }|                     |d          }|                     |d          }|                     |d          }|                     |dd          }|r|	}d}|r:t          j
        |d          o|dk    }|rdnd}t          j        |	d          rdnd}
|                     |g d          }|                     |d          }||                     |dd           }|                     |d!          }||                     |d"d#          }d	}d$|v sd|v rd%}|                     |d$d|          }|                     ||d&|          }g }|                     |d'          }|r|                    d(|d)           |                     |d*          }|r?|                    |                     |                     |d+                    |d)           |                     |d,          }|rQ|                    |                     |                     |d-                    t          j        |          d)           t'          |          }|d.k    }|                     |          }t          j        |          }|                     |d/          } | d%k    re|                     |d          }!|                     |!          }|dk    r4|
dk    r.t          j        ||!          }d }|	}t          j        |	|!          }	|                     i d0|                     |d0          d1|                     |d          d2|d3|                     |          d4|d5|d6|d
|d7|d8|d9|                     |d:          d|
d|d;|d<|d=|dt          j        |	          t          j        |          d ||rd n|                     |d>          |r|ng d |d?|          S )@Nr  TrH  rejected)rq  r%  r.  r   rt  rF  r  r  rk  rj  r  r  r  r  ri  rh  leftfilled_totalavg_deal_price
fill_pricery  rg  r2  r6  r  r  )	finish_asr.  r  r  r  ctimeupdate_time_msupdate_timefinish_timer  rF   r  r  r  r>  r   r  rebated_feerebated_fee_currencyr   rN   r7   rq  r/  r.  lastTradeTimestampr.  r  rt  rl  ri  is_reduce_onlyrH  rG  r  r   )r  r  	remainingr   rx  r   r%  )r;  
safe_orderr'  rK  rB  safe_string_upper_2r  r`  safe_number_2r3   string_equalsrA  r  r   r  r  ra  r^  r{  r]  r  r  r  rb  r  )"r  r  r2  r  r   rF  r  r  rt  r  r  r  rl  remainingStringr  rG  r  r  rD  r/  r  r4  exchangeSymbolr  rx  r  r   rM   numFeeCurrenciesmultipleFeeCurrenciesr.  r  rN   averageStrings"                                     r  rT  zgate.parse_order  s   \ NN5+t<<	 	??!%!1!1%!@!@$$ $   
 ui<<//%B77##C44V,,..sOUKK##C6::V,,  g..##E:x@@vt44..uoukZZ%K4'##E8VVDDvt44  77**5&99~66''99$$U,<lKK 	$OD 	G#1%==X;RWCWM,988'D#-fc::F55D&&u.M.M.MNN	%%e-=>>	--e]GLLI!..u6FGG%!%!6!6um]![![
u$$(e*;*;J++E?HhWW!!.&#zJJ  11 	KK      ue,, 	KK 33D4D4DUN4[4[\\     !!%77 	KK 33D4D4DULb4c4cdd*622     t99 01 4((33&77	""5)44f ,,U4DEEM''66G  tu}}#.NN	 +FMBB  
$""5$// 
T--eV<< 
  
 Y//	 

 !"4 
 f 
 f 
 D 
 ; 
  
 $//%1ABB 
 D 
 U 
  
 L 
  w! 
" g(00# 
$ &t,,"0N44doodA6N6N19DDr1 
  
  
2 3  	r  c                 j  K   |                                   d{V  |                     |ddd          }|                     |ddg          }|                     |dd          }|}|+|                     |ddg          }|d         dk    rd	|z   }|}|dn|                     |          }|                     d
||          \  }}	|dk    p|dk    p|dk    }
|
r|                     |||	          n|                     |||	          \  }}||d<   d}|dk    s|dk    rd|r1|                     | 	                    ||                     d{V }nN| 
                    | 	                    ||                     d{V }n|dk    rb|r0|                     | 	                    ||                     d{V }n|                     | 	                    ||                     d{V }n|dk    rb|r0|                     | 	                    ||                     d{V }n}|                     | 	                    ||                     d{V }nM|dk    r0|                     | 	                    ||                     d{V }nt!          | j        dz             |                     ||          S )a  
        Retrieves information on an order
        :see: https://www.gate.io/docs/developers/apiv4/en/#get-a-single-order
        :see: https://www.gate.io/docs/developers/apiv4/en/#get-a-single-order-2
        :see: https://www.gate.io/docs/developers/apiv4/en/#get-a-single-order-3
        :see: 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.stop]: True if the order being fetched is a trigger order
        :param str [params.marginMode]: 'cross' or 'isolated' - marginMode for margin trading if not provided self.options['defaultMarginMode'] is used
        :param str [params.type]: 'spot', 'swap', or 'future', if not provided self.options['defaultMarginMode'] is used
        :param str [params.settle]: 'btc' or 'usdt' - settle currency for perpetual swap and future - market settle currency is used if symbol is not None, default="usdt" for swap and "btc" for future
        :returns: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nis_stop_orderr  FrH  rq  r   rq  rs  r   r\   r]   r^   r  rF   rD   z* fetchOrder() not support self market type)r  rK  r  r  r2  r;  r  r   privateSpotGetPriceOrdersOrderIdrq  privateSpotGetOrdersOrderId)privateFuturesGetSettlePriceOrdersOrderId$privateFuturesGetSettleOrdersOrderId*privateDeliveryGetSettlePriceOrdersOrderId%privateDeliveryGetSettleOrdersOrderIdprivateOptionsGetOrdersOrderIdr/   r7   rT  )r  r7   r  rC  r  rq  r  r2  r  r  r  rw  r@  rx  s                 r  fetch_orderzgate.fetch_order  sg       !!!!!!!!!  &%HH6OV#<==**66?KK$YYv'@AAFQ3&& $} 4#G .t{{6/B/B88vvVVeFNO(8Odh>NNV  "Q!5!5fdE!J!J!J\`\{\{  }C  EI  KP  ]Q  ]Q%
6>>TX-- g!%!F!Ft{{SZ\iGjGj!k!kkkkkkk!%!A!A$++gWdBeBe!f!fffffffV^^ p!%!O!OPTP[P[\cerPsPs!t!ttttttt!%!J!J4;;W^`mKnKn!o!oooooooX q!%!P!PQUQ\Q\]dfsQtQt!u!uuuuuuu!%!K!KDKKX_anLoLo!p!pppppppX!@@WVcAdAdeeeeeeeeHHtw)UUVVV&111r  c                 D   K   |                      d||||           d{V S )af  
        fetch all unfilled currently open orders
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-all-open-orders
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch open orders for
        :param int [limit]: the maximum number of  open orders structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param bool [params.stop]: True for fetching stop 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
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        r  Nfetch_orders_by_statusr  r  r5  r6  rC  s        r  fetch_open_orderszgate.fetch_open_orders  s6       00vVVVVVVVVVr  c                 D   K   |                      d||||           d{V S )at  
        fetches information on multiple closed orders made by the user
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-orders
        :see: https://www.gate.io/docs/developers/apiv4/en/#retrieve-running-auto-order-list
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-futures-orders
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-all-auto-orders
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-futures-orders-2
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-all-auto-orders-2
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-options-orders
        :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.stop]: True for fetching stop 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
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        r  Nr  r  s        r  fetch_closed_orderszgate.fetch_closed_orders  s7      & 00VUESYZZZZZZZZZr  c                   K   |                                   d {V  d }||                     |          }|d         }|                     |d          }|                     |d          }|                     d||          \  }}	|dk    p|dk    }
|
r|                     |||	          n|                     |||	          \  }}|dk    rd}||d<   |||d	<   ||
r|                     |d
z            |d<   |
o|dk    o| }d }|dk    s|dk    r|r1|                     | 	                    ||                     d {V }n|r1| 
                    | 	                    ||                     d {V }nN|                     | 	                    ||                     d {V }n|dk    rb|r0|                     | 	                    ||                     d {V }n|                     | 	                    ||                     d {V }n|dk    rb|r0|                     | 	                    ||                     d {V }n}|                     | 	                    ||                     d {V }nM|dk    r0|                     | 	                    ||                     d {V }nt#          | j        dz             |}|rTg }t'          dt)          |                    D ]4}|                     ||         d          }|                     ||          }5|                     ||||          }|                     ||||          S )Nr  r  fetchOrdersByStatusrF   rD   r  r  r.  r6  r9  r:  r  r\   r]   r^   z+ fetchOrders() not support self market typer   r   )r  r2  rB  r  r;  r  r  r<  privateSpotGetOpenOrdersrq  privateSpotGetPriceOrdersprivateSpotGetOrders"privateFuturesGetSettlePriceOrdersprivateFuturesGetSettleOrders#privateDeliveryGetSettlePriceOrdersprivateDeliveryGetSettleOrdersprivateOptionsGetOrdersr/   r7   r\  r]  r?  r`  rE  )r  r.  r  r5  r6  rC  r2  r  r  r  rF   rw  r@  openSpotOrdersrx  rf  rg  ordersInnerr   s                      r  r  zgate.fetch_orders_by_status  s     !!!!!!!!![[((FH%Fvv..66**889NPVX^__e5DH$4_c  "S!F!FvtUZ![![![imi}i}  E  GK  MR  jS  jSXF"$GG"//==GFOA6V#3AT6>>TX-- `!%!>!>t{{7Ta?b?b!c!ccccccc `!%!?!?GUb@c@c!d!ddddddd!%!:!:4;;wP];^;^!_!_______V^^ i!%!H!HU\^kIlIl!m!mmmmmmm!%!C!CDKKPWYfDgDg!h!hhhhhhhX j!%!I!I$++V]_lJmJm!n!nnnnnnn!%!D!DT[[QXZgEhEh!i!iiiiiiiX!99$++g}:]:]^^^^^^^^HHtw)VVWWWf  	@F1c(mm,, @ @"oohqk8DD**6;??""665%@@00NNNr  c                   K   |                                   d{V  |dn|                     |          }|                     |ddd          }|                     |ddg          }|                     d||          \  }}|dk    s|dk    r|                     |||          n|                     |||          \  }}	||d<   d}
|dk    s|dk    rd|r1|                     |                     ||	                     d{V }
nN| 	                    |                     ||	                     d{V }
n|d	k    rb|r0| 
                    |                     ||	                     d{V }
n|                     |                     ||	                     d{V }
n|d
k    rb|r0|                     |                     ||	                     d{V }
n}|                     |                     ||	                     d{V }
nM|dk    r0|                     |                     ||	                     d{V }
nt          | j        dz             |                     |
|          S )a  
        Cancels an open order
        :see: https://www.gate.io/docs/developers/apiv4/en/#cancel-a-single-order
        :see: https://www.gate.io/docs/developers/apiv4/en/#cancel-a-single-order-2
        :see: https://www.gate.io/docs/developers/apiv4/en/#cancel-a-single-order-3
        :see: 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.stop]: True if the order to be cancelled is a trigger order
        :returns: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr  r  Frc   rF   rD   r  r\   r]   r^   z+ cancelOrder() not support self market type)r  r2  rK  r  r;  r  r  #privateSpotDeletePriceOrdersOrderIdrq  privateSpotDeleteOrdersOrderId,privateFuturesDeleteSettlePriceOrdersOrderId'privateFuturesDeleteSettleOrdersOrderId-privateDeliveryDeleteSettlePriceOrdersOrderId(privateDeliveryDeleteSettleOrdersOrderId!privateOptionsDeleteOrdersOrderIdr/   r7   rT  )r  r7   r  rC  r2  r  r  r  rw  r@  rx  s              r  cancel_orderzgate.cancel_order  s      !!!!!!!!! .t{{6/B/B  &%HH6OV#<==88PVWWeZ^bhZhZhlpt|l|l|!@!@u!U!U!U  DH  DX  DX  Y_  ae  gl  Dm  Dm 
6>>TX-- j!%!I!I$++V]_lJmJm!n!nnnnnnn!%!D!DT[[QXZgEhEh!i!iiiiiiiV^^ s!%!R!RSWS^S^_fhuSvSv!w!wwwwwww!%!M!MdkkZacpNqNq!r!rrrrrrrX t!%!S!STXT_T_`givTwTw!x!xxxxxxx!%!N!Nt{{[bdqOrOr!s!sssssssX!CCDKKPWYfDgDghhhhhhhhHHtw)VVWWWd &111r  c                   K   |                                   d{V  |dn|                     |          }|                     |dd          }|                     |ddg          }|                     d||          \  }}|dk    r|                     |||          n|                     |||          \  }}d}	|dk    s|dk    rd|r1|                     |                     ||                     d{V }	nN| 	                    |                     ||                     d{V }	n|dk    rb|r0| 
                    |                     ||                     d{V }	n|                     |                     ||                     d{V }	n|dk    rb|r0|                     |                     ||                     d{V }	n}|                     |                     ||                     d{V }	nM|d	k    r0|                     |                     ||                     d{V }	nt          | j        d
z             |                     |	|          S )a  
        cancel all open orders
        :see: https://www.gate.io/docs/developers/apiv4/en/#cancel-all-open-orders-in-specified-currency-pair
        :see: https://www.gate.io/docs/developers/apiv4/en/#cancel-all-open-orders-matched
        :see: https://www.gate.io/docs/developers/apiv4/en/#cancel-all-open-orders-matched-2
        :see: 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
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr  rF  rb   rF   rD   r\   r]   r^   z/ cancelAllOrders() not support self market type)r  r2  safe_bool_2r  r;  r  r  privateSpotDeletePriceOrdersrq  privateSpotDeleteOrders%privateFuturesDeleteSettlePriceOrders privateFuturesDeleteSettleOrders&privateDeliveryDeleteSettlePriceOrders!privateDeliveryDeleteSettleOrdersprivateOptionsDeleteOrdersr/   r7   r`  )
r  r  rC  r2  r  r  r  rw  r@  rx  s
             r  cancel_all_orderszgate.cancel_all_ordersK  s      !!!!!!!!! .t{{6/B/B	::6FI#677889JFTZ[[e`dhn`n`n!F!FvtUZ![![![uy  vJ  vJ  KQ  SW  Y^  v_  v_6>>TX-- c!%!B!B4;;wXeCfCf!g!ggggggg!%!=!=dkk'S`>a>a!b!bbbbbbbV^^ l!%!K!KDKKX_anLoLo!p!ppppppp!%!F!Ft{{SZ\iGjGj!k!kkkkkkkX m!%!L!LT[[Y`boMpMp!q!qqqqqqq!%!G!GT[]jHkHk!l!lllllllX!<<T[[R_=`=`aaaaaaaaHHtw)ZZ[[[:   6222r  fromAccount	toAccountc                 *  K   |                                   d{V  |                     |          }|                     |          }|                     |          }|                     ||          }	|d         |	d}
|| j        d         vrd|
d<   ||
d<   n||
d<   || j        d         vrd|
d<   ||
d<   n||
d<   |dk    s|dk    rf|                     |d	d          }|t          | j        d
z             |                     |          }|d         |
d<   | 	                    |d	          }|dk    s|dk    s|dk    s|dk    r|d         |
d<   | 
                    |                     |
|                     d{V }|                     ||          S )a  
        transfer currency internally between wallets on the same account
        :see: 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>`
        Nr7   r  r  ru  rD   r:  r  r  r  zA transfer requires params["symbol"] for isolated margin transfersrC   rE   r  )r  r  r  r  rG   r  r'   r7   r2  r  privateWalletPostTransfersrq  parse_transfer)r  r  r  r  r  rC  r  fromIdtoId	truncatedrw  r  r2  rx  s                 r  r   zgate.transfer  s      !!!!!!!!!==&&--k::++I66..tV<<	 
 
 $,'7888&GFO'-GO$$$GFO%5666$GDM'+GO$$ GDMX!1!1''/JJF~'2u(uvvv[[((F'-d|GO$YYvx00FI4:#5#56Y;N;NTZ^hThTh (GH88Wf9U9UVVVVVVVV ""8X666r  c           
      j    |                      |d          d d |                     d |          d d d d |d	S )Ntx_id)	r7   r/  r.  r  r  r  r  r.  r%  )r'  r^  )r  r   r  s      r  r  zgate.parse_transfer  sN     ""8W55//h??

 

 
	
r  rP  c                 &  K   |t          | j        dz             |dk     s|dk    rt          | j        dz             |                                  d{V  |                     |          }|                     |d|          \  }}|                     | j        dd          }|                     |d          }|                     |d|          }	| 	                    |          }
|d	}	|}
|	d	k    s|	d
k    r|
|d<   d|d<   n|
|d<   d}|d         r0| 
                    |                     ||                     d{V }nO|d         r0|                     |                     ||                     d{V }nt          | j        dz             |S )a  
        set the level of leverage for a market
        :see: https://www.gate.io/docs/developers/apiv4/en/#update-position-leverage
        :see: 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   d   z3 setLeverage() leverage should be between 1 and 100r  r  cross_leverage_limitrm  rk  ry  rP  r\   r]   z+ setLeverage() not support self market type)r'   r7   r(   r  r2  r  r  rG   r'  r  1privateFuturesPostSettlePositionsContractLeveragerq  2privateDeliveryPostSettlePositionsContractLeverager/   )r  rP  r  rC  r2  rw  r  r  crossLeverageLimitr  stringifiedMarginrx  s               r  set_leveragezgate.set_leverage  s      >#DG.Y$YZZZ qLLhnnTW'\\]]]!!!!!!!!!V$$--fdFCC ..t|\K^__!--e5KLL%%e\;LMM
 11(;;) J 2  J.$@$@.?G*+"%GJ"3GJ&> 	X!SSTXT_T_`ginToToppppppppHHH 	X!TTUYU`U`ahjoUpUpqqqqqqqqHHtw)VVWWW8 r  c                    |                      |d          }|                     ||dd          }|                      |d          }d }t          j        |d          rd}nt          j        |d          rd}|                      |d          }|                      |d          }|                      |d	          }d }	|dk    rd
}	nd}	|                      |d          }
d}t          j        ||          }t          j        t          j        ||          |          }|                     |d          }| 	                    i d|dd d|                      |d          d|d| 
                    |          d|                     |d          d|                     |          d|                     t          j        ||                    d|                     t          j        ||                    d|                     |          d|                     |d          d|                     |          d	|                     |d	          d|                     |
          d|                     |d          d |                     t          j        |                    d!|                     |d!          d |                     |d"          |                     |d#          d |                     |d$          |	|d d d d%
          S )&Nr  r  r  ry  longshortmaintenance_ratevaluerP  rm  rn  unrealised_pnlr  	open_timer%  r7   r  r/  r.  lastUpdateTimestampr  initialMargininitialMarginPercentagemaintenanceMarginmaintenanceMarginPercentage
entryPriceentry_pricenotionalunrealizedPnlrealizedPnlrealised_pnlr   r  	liq_pricer~  rD   )
marginRatioliquidationPricer  	lastPrice
collateralr  r  r  rI  rJ  )r'  r8  r3   rA  r  r  r  rb  r  safe_positionr  r  r`  r  )r  positionr2  r  r  r  maintenanceRater  rP  r  unrealisedPnltakerFeefeePaidinitialMarginStringr/  s                  r  parse_positionzgate.parse_position  s}   r ##Hj99!!(FCDD&11T3'' 	DDtS)) 	D**85GHH##Hg66##Hj99
s?? JJ#J((3CDD $Xx88%01CHh1W1WY`aa''+>>	!! #
H#
$#
 d&&vx88#
 	#

 Y//#
 "4#6#6x#O#O#
 T../BCC#
 &t'8'89KL_ai9j9j'k'k#
  !2!273EoW_3`3`!a!a#
 *4+<+<_+M+M#
 $**8]CC#
 ))(33#
 ((:>>#
 T..}==#
 4++HnEE#
  **7+=d+C+CDD!#
" D,,V^DD##
&   $ 0 0; G G))(LAA**8X>>$!#9#
 #
 #
   	r  c                    K   |                                   d{V  |                     |          }|d         st          | j        dz             i }|                     ||d         |          \  }}|                     ||          }d}|d         r|                     |           d{V }nK|d         r|                     |           d{V }n'|d         dk    r|                     |           d{V }| 	                    ||          S )aB  
        fetch data on an open contract position
        :see: https://www.gate.io/docs/developers/apiv4/en/#get-single-position
        :see: https://www.gate.io/docs/developers/apiv4/en/#get-single-position-2
        :see: 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  r\   r]   r^   )
r  r2  r(   r7   r  rq  (privateFuturesGetSettlePositionsContract)privateDeliveryGetSettlePositionsContract"privateOptionsGetPositionsContractr  )r  r  rC  r2  rw  extendedRequestrx  s          r  fetch_positionzgate.fetch_position  sS      !!!!!!!!!V$$j! 	ZTW'XXYYY..vvf~vNN++gv66&> 	V!JJ?[[[[[[[[HHH 	V!KKO\\\\\\\\HHF^x''!DD_UUUUUUUUHr ""8V444r  c                 H  K   |                                   d{V  d}|                     |dddd          }|0t          |          }|dk    r|                     |d                   }d}i }|                     d||          \  }}||dk    rd}|dk    r9|6|d         }|                    d	          }|                     |d          |d
<   n|                     d||          \  }}d}	|dk    r0|                     | 	                    ||                     d{V }	nk|dk    r0| 
                    | 	                    ||                     d{V }	n5|dk    r/|                     | 	                    ||                     d{V }	|                     |	|          S )aZ  
        fetch all open positions
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-all-positions-of-a-user
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-all-positions-of-a-user-2
        :see: 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   rF   r\   r^   r7   r  r  r]   )r  r  r]  r2  r;  r&  r'  r   privateFuturesGetSettlePositionsrq  !privateDeliveryGetSettlePositionsprivateOptionsGetPositionsparse_positions)
r  r  rC  r2  symbolsLengthr  rw  r1  r+  rx  s
             r  fetch_positionszgate.fetch_positions  s      !!!!!!!!!%%gtT4FFLLMq  WQZ0099:JFTZ[[fLdfnnD8"!$<&nnS11(,(8(8a(H(H%"224vFFOGV6>>!BB4;;wX^C_C_````````HHX!CCDKKPWY_D`D`aaaaaaaaHHX!<<T[[RX=Y=YZZZZZZZZHz ##Hg666r  c                    K   |                                   d{V  |                     dd|          \  }}|                     d||          \  }}|dk    r|dk    rt          | j        dz             d}|dk    r0|                     |                     ||                     d{V }nM|dk    r0|                     |                     ||                     d{V }nt          | j        dz             | 	                    ||d          S )aQ  
        retrieve information on the maximum leverage, and maintenance margin for trades of varying trade sizes
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-all-futures-contracts
        :see: 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   r]   r\   z1 fetchLeverageTiers only supports swap and futurez2 fetchLeverageTiers() not support self market typer8   )
r  r;  r  r(   r7   rp  rq  rs  r/   parse_leverage_tiers)r  r  rC  r  r  rw  r@  rx  s           r  fetch_leverage_tierszgate.fetch_leverage_tiersC  sD      !!!!!!!!!889MtU[\\e!%!5!5dD%!H!H8TW'ZZ[[[6>>!AA$++gWdBeBeffffffffHHX!BB4;;wXeCfCfggggggggHHtw)]]^^^z ((7FCCCr  c                   K   |                                   d{V  |                     |          }|                     d||          \  }}|                     |||          \  }}|dk    r|dk    rt	          | j        dz             |                     |                     ||                     d{V }|                     ||          S )a  
        retrieve information on the maximum leverage, and maintenance margin for trades of varying trade sizes for a single market
        :see: 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   r]   r\   z7 fetchMarketLeverageTiers only supports swap and future)	r  r2  r;  r  r(   r7   %privateFuturesGetSettleRiskLimitTiersrq  parse_market_leverage_tiers)	r  r  rC  r2  r  r  rw  r@  rx  s	            r  fetch_market_leverage_tiersz gate.fetch_market_leverage_tiers  s       !!!!!!!!!V$$889SU[]cdde!%!5!5fdE!J!J8TW'``aaaCCDKKPWYfDgDghhhhhhhh //&AAAr  c                 6   |                      |d          }|                      |d          }|                      |d          }|                      |d          }t          j        d|          }|}|}	d}
g }t          j        |
|          rt          j        |
|          }|                    |                     t          j        ||                    |                      |d          |                     |
          |                     |          |                     |          |                     t          j        d|	                    |d           t          j        ||          }t          j        |	|          }	|}
t          j        |
|          |S )	Nr   r  risk_limit_steprisk_limit_maxr  ry  r  tierr  minNotionalmaxNotionalmaintenanceMarginRatemaxLeverager%  )r'  r3   rb  r  r  ra  r  )r  r%  r2  maintenanceMarginUnitleverageMaxriskLimitStepriskLimitMaxinitialMarginUnitr7  initialMarginRatiofloorr  caps                r  parse_emulated_leverage_tiersz"gate.parse_emulated_leverage_tiers  s    $ 0 07I J J&&t^<<((/@AA''.>??#.sK@@ 5.|44 	$UM::CLL))'*<S-*P*PQQ ,,VX>>#0077#0055)-):):;P)Q)Q#001CCI[1\1\]]     %,$67LNc$d$d!!(!34FHY!Z!ZE |44 	 r  c                    t          |t                    s|                     ||          S d}g }t          dt	          |                    D ]}||         }|                     |d          }|                    |                     |d          |d         |||                     |d          |                     |d          |d           |}|S )Nr   
risk_limitr   r  r   r  r3  )r  r)  rA  r\  r]  r`  ra  r  )r  r%  r2  r5  r  rg  itemr6  s           r  r.  z gate.parse_market_leverage_tiers  s     $%% 	D55dFCCCq#d))$$ 	& 	&A7D**4>>KLLA"6N**)-)9)9$@R)S)S#//nEE     &KKr  c                   K   |                                   d{V  |                     |          }|d                                         |                     ||          d}|                     |          }|d         |d<   d|d<   |                     |                     ||                     d{V }|                     ||          S )a  
        repay borrowed margin and interest
        :see: 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>`
        Nr7   r  r  repayr  r  r  upperr  r2  privateMarginPostUniLoansrq  parse_margin_loan)	r  r  r  r  rC  r  rw  r2  rx  s	            r  repay_isolated_marginzgate.repay_isolated_margin  s       !!!!!!!!!==&& ,,..00v>>
 
 V$$#)$< !77GV8T8TUUUUUUUU %%h999r  c                 |  K   |                                   d{V  |                     |          }|d                                         |                     ||          d}|                     |                     ||                     d{V }|                     |d          }|                     ||          S )a  
        repay cross margin borrowed margin and interest
        :see: https://www.gate.io/docs/developers/apiv4/en/#cross-margin-repayments
        :param str code: unified currency code of the currency to repay
        :param float amount: the amount to repay
        :param str symbol: unified market symbol, required for isolated margin
        :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>`
        Nr7   r  r   )r  r  rH  r   privateMarginPostCrossRepaymentsrq  rB  rJ  r  r  r  rC  r  rw  rx  s          r  repay_cross_marginzgate.repay_cross_margin&  s       !!!!!!!!!==&& ,,..00v>>
 
 >>t{{7TZ?[?[\\\\\\\\" ??8Q//%%h999r  c                   K   |                                   d{V  |                     |          }|d                                         |                     ||          d}d}|                     |          }|d         |d<   d|d<   |                     |                     ||                     d{V }|                     ||          S )a]  
        create a loan to borrow margin
        :see: https://www.gate.io/docs/developers/apiv4/en/#marginuni
        :param str code: unified currency code of the currency to borrow
        :param float amount: the amount to borrow
        :param str symbol: unified market symbol, required for isolated margin
        :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>`
        Nr7   r  r  borrowr  rG  )	r  r  r  r  rC  r  rw  rx  r2  s	            r  borrow_isolated_marginzgate.borrow_isolated_marginL  s       !!!!!!!!!==&& ,,..00v>>
 
 V$$#)$< "77GV8T8TUUUUUUUU( %%h999r  c                 P  K   |                                   d{V  |                     |          }|d                                         |                     ||          d}|                     |                     ||                     d{V }|                     ||          S )aj  
        create a loan to borrow margin
        :see: https://www.gate.io/docs/apiv4/en/#create-a-cross-margin-borrow-loan
        :param str code: unified currency code of the currency to borrow
        :param float amount: the amount to borrow
        :param str symbol: unified market symbol, required for isolated margin
        :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>`
        Nr7   r  )r  r  rH  r  privateMarginPostCrossLoansrq  rJ  rN  s          r  borrow_cross_marginzgate.borrow_cross_marginw  s       !!!!!!!!!==&& ,,..00v>>
 
 99$++gv:V:VWWWWWWWW %%h999r  c           	         |                      | j        ddd          }|                     |d          }|dk    r|                     |d          }|                     |d          }|                     |d          }|                     |d          |                     ||          |                     |d	          |                     |d d
d          ||                     |          |dS )Nr  r  rm  r  rn  r  r  r7   r  r  rD   )r7   r  r  r  r/  r.  r%  )	r  rG   r   r  r'  r^  r`  r  r  )r  r%  r  r  r/  r  r1  s          r  rJ  zgate.parse_margin_loan  s    J ''6I<Y`aa
%%dM::	##++D-@@I%%dJ77
##D/::##D$////
HEE&&tX66&&xsHEE"Y//
 
 	
r  GETc                 x   |d         }|d         }|                      ||                     |                    }	t          |t                    r.|                     |di           }
|                     ||
          }n|                     ||          }|dk    rdnd|z   }d|z   |z   }|dk    s|dk    r|}| j        d         |         |         }|t          | j        dz   |z   d	z             ||z  }|d
k    r|	r|d| 	                    |	          z   z  }n| 
                                 d}d}|dk    s|dk    rd|dk    r^|                    d          }|                     |dd          }|                    d          dk    p|                    d          dk    }|dk    s|dk    s|s|dk    r;|	r| 	                    |	          }|d|z   z  }|dk    r|                     |	          }na|                     |	di           }|r| 	                    |          }|d|z   z  }|                      |	d          }	|                     |	          }|dn|}|                     |                     |          d          }|                                 }t%          |          }d| j        z   |z   }|                                ||||g}d                    |          }|                     |                     |          |                     | j                  t0          j                  }| j        ||dd}||||dS )Nr   r   r|  r  rK   rJ   rW   z! does not have a testnet for the z market type.rP   ?FrC   rE   POSTdualr  rW  DELETEPATCHr  sha512z/api/
zapplication/json)KEY	TimestampSIGNzContent-Type)rR   r  bodyrJ  )r  extract_paramsr  r)  rB  implode_paramsrA   r/   r7   	urlencodecheck_required_credentialsr&  r'  r(  jsonhashencoder  strr=   rH  joinhmacrI  hashlibr^  rH  )r  pathrW   r  rC  rJ  rc  authenticationr  r  r  endPart
entirePathrR   queryStringrequiresURLEncoding	pathParts
secondParturlQueryParamsbodyPayloadbodySignaturer/  timestampStringsignaturePathpayloadArraypayload	signatures                              r  signz	gate.sign  sx   Q1v		&$"5"5d";";<<fd## 	5 OOFAr22E&&tU33DD&&tV44D""3:4Z')
M!!t}'<'< Ji~.t4;tw)LLtSVeefffzX%% 3sT^^E2222++---K"'""
(:(:6AQAQ JJsOO	!--iB??
'1v'>'>!'C&kYdIeIeijIj#%Vx%7%7<O%7TZ^eTeTe -"&.."7"7K3,,CW$$99U++D!%!D!D! -"&.."@"@K3,,C		%11yy''!%""DK IIdkk+&>&>IIMI!)nnO#dl2Z?M"LLNNM;WfgLii--G		$++g"6"6DK8P8PRYR`aaI{,! 2	 G fdwOOOr  c                   K   |                                   d {V  |                     |          }|                     |d |          \  }}|                     |          |d<   d }|d         r0|                     |                     ||                     d {V }nO|d         r0|                     |                     ||                     d {V }nt          | j        dz             | 	                    ||          S )NrI  r\   r]   z2 modifyMarginHelper() not support self market type)
r  r2  r  r  /privateFuturesPostSettlePositionsContractMarginrq  0privateDeliveryPostSettlePositionsContractMarginr/   r7   parse_margin_modification)r  r  r  rC  r2  rw  r  rx  s           r  modify_margin_helperzgate.modify_margin_helper  s.     !!!!!!!!!V$$--fdFCC 11&99&> 	_!QQRVR]R]^eglRmRmnnnnnnnnHHH 	_!RRSWS^S^_fhmSnSnooooooooHHtw)]]^^^--h???r  c                     |                      |d          }|                     ||dd          }|                     |d          }||d         d dd ||                     |d          dd d d
S )	Nr  r  rD   r  rn  r
  r  )
r%  r  r  r  r  r  r  r.  r/  r.  )r'  r8  r`  rB  )r  r  r2  r  r  s        r  r  zgate.parse_margin_modification  s    8 ##D*55!!(FCDD  x00X&$OOFG44
 
 	
r  c                 B   K   |                      || |           d{V S )a  
        remove margin from a position
        :see: https://www.gate.io/docs/developers/apiv4/en/#update-position-margin
        :see: 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r  r  r  r  rC  s       r  reduce_marginzgate.reduce_marginE  s4       ..vwGGGGGGGGGr  c                 @   K   |                      |||           d{V S )a  
        add margin
        :see: https://www.gate.io/docs/developers/apiv4/en/#update-position-margin
        :see: 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>`
        Nr  r  s       r  
add_marginzgate.add_marginQ  s2       ..vvvFFFFFFFFFr  r"  c           	      $  K   |                                   d{V  d}|                     |ddd          \  }}|r!|                     d|||||d           d{V S |                     |          }|d         st	          | j        dz             |d         |d	         |                     | j        ||          d
}|||d<   |||d<   |                     | 	                    ||                     d{V }	| 
                    |	|||          S )a  
        Retrieves the open interest of a currency
        :see: 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   r  r  r\   z/ fetchOpenInterest() supports swap markets onlyr7   r  )r  r  r  r6  r:  )r  r  r  r2  r(   r7   r'  r  #publicFuturesGetSettleContractStatsrq  parse_open_interests)
r  r  r  r5  r6  rC  r  r2  rw  rx  s
             r  fetch_open_interest_historyz gate.fetch_open_interest_history]  s      !!!!!!!!!88A[]ginoo& 	K@@A[]cejlqs|  E  GJ  K  K  K  K  K  K  K  K  KV$$f~ 	ZTW'XXYYYtZ((()YOO
 

 $GG#GFOAA$++gW]B^B^________, ((65%HHHr  c                     |                      |d          }|                     |d          |                     |d          |                     |d          ||                     |          |dS )Nr   r  open_interestopen_interest_usd)r  openInterestAmountopenInterestValuer/  r.  r%  )r  r'  r`  r  )r  interestr2  r/  s       r  parse_open_interestzgate.parse_open_interest  sw    & ''&99	&&vx88"&"2"28_"M"M!%!1!1(<O!P!P"Y//
 
 	
r  c                 t  K   |t          | j        dz             |                                  d{V  |                     |          }d}|                     d||          \  }}|dk    rt          | j        dz             |d         }|                    d          }d|                     |d	          i}	|||	d
<   |||	d<   |                     | 	                    |	|                     d{V }
| 
                    |
|          }|                     |d          }|                     ||||          S )a  
        fetches historical settlement records
        :see: 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   r^   z6 fetchSettlementHistory() supports option markets onlyr7   r  r  r   r:  r6  r/  )r'   r7   r  r2  r;  r/   r&  r'  publicOptionsGetSettlementsrq  parse_settlementsrD  rE  )r  r  r5  r6  rC  r2  r  r1  r+  rw  rx  r   rF  s                r  fetch_settlement_historyzgate.fetch_settlement_history  sj      >#DG.d$deee!!!!!!!!!V$$99:RTZ\bccf8tw)aabbb$<nnS))$**;::
 #GFO$GG99$++gv:V:VWWWWWWWW ,,Xv>>k;7700NNNr  c                   K   |t          | j        dz             |                                  d{V  |                     |          }d}|                     d||          \  }}|dk    rt          | j        dz             |d         }|                    d          }|                     |d          |d	}	|||	d
<   |||	d<   |                     | 	                    |	|                     d{V }
| 
                    |
di           }| 
                    |dg           }|                     ||          }|                     |d          }|                     ||d         ||          S )a  
        fetches historical settlement records of the user
        :see: 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   r^   z8 fetchMySettlementHistory() supports option markets onlyr7   r  r   )r  r  r:  r6  rf  r)  r/  r  )r'   r7   r  r2  r;  r/   r&  r'  privateOptionsGetMySettlementsrq  rB  r  rD  rE  )r  r  r5  r6  rC  r2  r  r1  r+  rw  rx  rf  r  r   rF  s                  r  fetch_my_settlement_historyz gate.fetch_my_settlement_history  s      >#DG.f$fggg!!!!!!!!!V$$99:TV\^deef8tw)ccddd$<nnS))**;:: 
 
 #GFO$GG<<T[[RX=Y=YZZZZZZZZ  8R88vvr22,,T6::k;77009I5RWXXXr  c                     |                      |d          }|                     |d          }||                     ||          |                     |d          ||                     |          dS )Nr   r  settle_price)r%  r  r  r/  r.  )r  r'  r  r`  r  )r  
settlementr2  r/  r1  s        r  parse_settlementzgate.parse_settlement  sx    6 ''
F;;	##J
;;&&x88%%j.AA"Y//
 
 	
r  c                     g }t          dt          |                    D ]1}|                    |                     ||         |                     2|S r  )r\  r]  ra  r  )r  r   r2  rf  rg  s        r  r  zgate.parse_settlements2  sZ    > q#k**++ 	I 	IAMM$//AGGHHHHr  c                 ~  K   |                                   d{V  d}|                     |dd          \  }}|r|                     d||||           d{V S d}d}d}i }	|                     dd|          \  }}|dk    s|dk    r"| |                     |          }|d         |	d<   |d	k    s|d
k    r<|d	k    rdnd}
|                     |d|
          }|                     |d          }||	d<   |||	d<   |||	d<   |                     d|	|          \  }	}|dk    r0|                     | 	                    |	|                     d{V }n|dk    r0| 
                    | 	                    |	|                     d{V }n|d	k    r0|                     | 	                    |	|                     d{V }nk|d
k    r0|                     | 	                    |	|                     d{V }n5|dk    r/|                     | 	                    |	|                     d{V }|                     ||||          S )a  
        fetch the history of changes, actions done by the user or operations that altered the balance of the user
        :see: https://www.gate.io/docs/developers/apiv4/en/#query-account-book
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-margin-account-balance-change-history
        :see: https://www.gate.io/docs/developers/apiv4/en/#query-account-book-2
        :see: https://www.gate.io/docs/developers/apiv4/en/#query-account-book-3
        :see: 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 [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns dict: a `ledger structure <https://docs.ccxt.com/#/?id=ledger-structure>`
        NFr   r  rF   rD   r7   r  r\   r]   rp  rq  r  r:  r6  r  r^   )r  r  r  r;  r  r  r  r  privateSpotGetAccountBookrq  privateMarginGetAccountBookr=  r>  privateOptionsGetAccountBookparse_ledger)r  r  r5  r6  rC  r  r  r  rx  rw  r  r  s               r  fetch_ledgerzgate.fetch_ledgerV  s       !!!!!!!!!88PZ[[& 	f::=$PUW\^deeeeeeeee99-vVVfFNN 0 0==..&.tn
#FNN 0 0'+v~~FFEM++FHmLLFYYvx00F &GH#GFO$GG224&II6>>!;;DKKQW<X<XYYYYYYYYHHX!==dkk'SY>Z>Z[[[[[[[[HHV^^!DDT[[QXZ`EaEabbbbbbbbHHX!EEdkkRY[aFbFbccccccccHHX!>>t{{7TZ?[?[\\\\\\\\Hj   8UEBBBr  c                 6   d }|                      |d          }t          j        |d          rd}t          j        |          }nd}|                      |d          }|                      |d          }|                      |d          }d }t	          |          dk    rt          |          }nt          |          d	z  }|                      |d
          }	|                      |d          }
|                     t          j        |	|
                    }|                      |d          |d d d |                     |          | 	                    ||          |                     |          || 
                    |          ||                     |d
          d d |dS )NrI  ry  outinr  r  r   
   r9  balancer7   )r7   	directionrN   referenceAccountreferenceIdr  r  r  r/  r.  beforeafterr.  r   r%  )r'  r3   r  r  r]  r|  r  r  parse_ledger_entry_typer^  r  r`  )r  rD  r  r  r  r  r  rawTimestampr/  balanceStringchangeStringr  s               r  parse_ledger_entryzgate.parse_ledger_entry  s   Z 	!!$11VS)) 	I'//FFI%%dJ77
f--''f55	|r!!L))IIL))D0I((y99''h77""7#5m\#R#RSS""4.." $0066//
HEE''//"Y//%%dI66
 
 	
r  c                    i ddddddddddddd	dd
dddddddddddddddddddi ddddddddddddddddd dd!dd"d"d#d$d%dd&dd'dd(d)d*ddddd)d+}|                      |||          S ),Nr  r   r2  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_feerM   	order_feer   r  lendrO   redeemprofitflash_swap_buyflash_swap_sellunknownsetr  prem
point_refrr  	point_dnwzdeposit/withdrawr8  )refrr   pnldnwr,  )r  r  
ledgerTypes      r  r  zgate.parse_ledger_entry_type  s   '
y'
'
 #J'
 	'

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

P 
D$777r  hedgedc                    K   ||                      |          nd}|                     |d|          \  }}||d<   |                     |                     ||                     d{V S )aU  
        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
        :see: 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
        Nr\   	dual_mode)r2  r   privateFuturesPostSettleDualModerq  )r  r  r  rC  r2  rw  r  s          r  set_position_modezgate.set_position_mode:  s}       *0);V$$$$--fffEE%::4;;wPU;V;VWWWWWWWWWr  c                   K   |                                   d{V  d}|                     dd|          \  }}||dk    rd}|dk    rt          | j        dz             |                     |           d{V }g }t          dt          |                    D ]7}||         }|                     |d          }||                    |           8|S )a  
        fetches the market ids of underlying assets for a specific contract market type
        :see: 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   rF   r^   z5 fetchUnderlyingAssets() supports option markets onlyr   r8   )	r  r;  r/   r7   r  r\  r]  r'  ra  )r  rC  r4  rx  r   rg  r  r8   s           r  fetch_underlying_assetszgate.fetch_underlying_assetsI  s      !!!!!!!!!
!??@WY]_eff
FJ&$8$8!J!!tw)``aaa99&AAAAAAAA q#h--(( 	) 	)A!!J##J77D""4(((r  c                   K   |                                   d{V  |                     |          }|d         st          | j        dz             |d         |d         d}|||d<   |||d<   |                     d	||          \  }}|                     |                     ||                     d{V }|                     ||||          S )
a  
        retrieves the public liquidations of a trading pair
        :see: 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>`
        Nr\   z/ fetchLiquidations() supports swap markets onlyr  r7   )r  r  r:  r6  r  )r  r2  r/   r7   r  publicFuturesGetSettleLiqOrdersrq  parse_liquidations)r  r  r5  r6  rC  r2  rw  rx  s           r  fetch_liquidationszgate.fetch_liquidationsj  s      !!!!!!!!!V$$f~ 	\tw)ZZ[[[Z(t
 
 #GFO$GG224&II==dkk'SY>Z>Z[[[[[[[[ &&xFFFr  c                 6  K   |t          | j        dz             |                                  d{V  |                     |          }d|d         i}d}|d         s|d         r|||d<   |d         |d	<   n>|d
         r6|d         }|                    d          }	|                     |	d          |d<   |d         r0|                     |                     ||                     d{V }n|d         r0|                     |                     ||                     d{V }n[|d
         r0| 	                    |                     ||                     d{V }n#t          | j        dz   |d         z   dz             |                     ||||          S )a  
        retrieves the users liquidated positions
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-liquidation-history
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-liquidation-history-2
        :see: 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  r7   r\   r]   r6  r  r  r^   r  r   r  z( fetchMyLiquidations() does not support r  rm  )r'   r7   r  r2  r&  r'  !privateFuturesGetSettleLiquidatesrq  "privateDeliveryGetSettleLiquidatesprivateOptionsGetPositionCloser/   r  )
r  r  r5  r6  rC  r2  rw  rx  r1  r+  s
             r  fetch_my_liquidationszgate.fetch_my_liquidations  s      >#DG.a$abbb!!!!!!!!!V$$t
 6N 	Ex 0 	E #(  &z 2GHH 	Ed|H"..--K$($4$4[!$D$DGL!&> 	r!CCDKKPWY_D`D`aaaaaaaaHHH 	r!DDT[[QXZ`EaEabbbbbbbbHHH 	r!@@WV\A]A]^^^^^^^^HHtw)SSV\]cVddgppqqqD &&xFFFr  c                 P   |                      |d          }|                     |d          }|                     |dd          }|                      |dd          }t          j        t          j        ||                    }|                      |d          }|                     |dd	          }	t          j        ||          }
|                      |d
          }|t          j        |
|	          }|                     ||                     ||          | 	                    |          | 	                    |          | 	                    |	          | 	                    |
          | 	                    t          j        |                    || 
                    |          d	          S )Nr  r   r  settle_sizer  ry  r  r  r  r  )	r%  r  r   r  r  	baseValue
quoteValuer/  r.  )r'  r  r  r3   r  r  r  safe_liquidationr  r  r  )r  liquidationr2  r1  r/  r  r  contractsStringcontractSizeStringr   baseValueStringquoteValueStrings               r  parse_liquidationzgate.parse_liquidation  s   R ##K<<''V<<	!!+v}EEVS99!,W-?d-K-KLL!--fnEE((k<PP!,_>PQQ++K??#&1/;OO$$&&x88**?;; --.@AA&&{33**?;;++G,>?O,P,PQQ"Y//
&
 
&
 
 
 
	r  c                   K   |                                   d{V  |                     |          }d|d         d         i}|                     |                     ||                     d{V }|d         }t	          dt          |                    D ]>}||         }|                     |d          }	|	|k    r|                     ||          c S ?dS )a  
        fetches an option contracts greeks, financial metrics used to measure the factors that affect the price of an options contract
        :see: 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%  r7   r   r8   )r  r2  r^  rq  r\  r]  r'  parse_greeks)
r  r  rC  r2  rw  rx  r1  rg  r  entryMarketIds
             r  fetch_greekszgate.fetch_greeks  s       !!!!!!!!!V$$&.6
 55dkk'66R6RSSSSSSSS. $<q#h--(( 	8 	8AQKE ,,UF;;M((((77777 )tr  c                    |                      |d          }|                     ||          }i d|dd dd d|                     |d          d|                     |d          d|                     |d          d|                     |d          d	d d
|                     |d          d|                     |d          d|                     |d          d|                     |d          d|                     |d          d|                     |d          d|                     |d          d|                     |d          d|                     |d          |                     |d         d                   |dS )Nr8   r  r/  r.  deltagammathetavegarhobidSizern  askSizerp  bidImpliedVolatilitybid_ivaskImpliedVolatilityask_ivmarkImpliedVolatilitymark_ivbidPricerj  askPricerg  r  r~  r  rd  r%  underlying_price)underlyingPricer%  )r'  r  r`  r  )r  greeksr2  r1  r  s        r  r  zgate.parse_greeksD  s   * ##FF33!!(F33
f

 
 T%%fg66	

 T%%fg66
 T%%fg66
 D$$VV44
 4
 t''<<
 t''<<
 #D$4$4VX$F$F
 #D$4$4VX$F$F
 $T%5%5fi%H%H
 ((>>
 ((>>
  ))&,??!
" ))&,??#
$  $00@R1STT'
 
 
 	
r  c                    K   ddi}|                      ||          }|d}|                     |d|dd|           d{V S )aI  
        closes open positions for a market
        :see: https://www.gate.io/docs/developers/apiv4/en/#create-a-futures-order
        :see: https://www.gate.io/docs/developers/apiv4/en/#create-a-futures-order-2
        :see: 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>`
        r  TNr|  r2  r   )rq  rZ  )r  r  r  rC  rw  s        r  close_positionzgate.close_positionq  sc       T
 Wf--<D&&vxq$OOOOOOOOOr  c                   K   |                                   d{V  d}||                     |          }i }d}|                     |d          }|                     |d          }|d         rm|d         |d<   |r0|                     |                     ||                     d{V }n|                     |                     ||                     d{V }nU|r0|                     |                     ||                     d{V }n#t          | j	        dz   |d         z   dz             | 
                    ||          S )	a  
        fetch the set leverage for a market
        :see: https://www.gate.io/docs/developers/apiv4/en/#get-unified-account-information
        :see: https://www.gate.io/docs/developers/apiv4/en/#get-detail-of-lending-market
        :see: 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>`
        NrL   rF   r7   r  z" fetchLeverage() does not support r  r  )r  r2  r;  r  +publicMarginGetUniCurrencyPairsCurrencyPairrq  (publicMarginGetCurrencyPairsCurrencyPairprivateUnifiedGetAccountsr/   r7   parse_leverage)r  r  rC  r2  rw  rx  	isUnifieds          r  fetch_leveragezgate.fetch_leverage  s      !!!!!!!!![[((FNN6955	69--&> O	m'-d|GO$ m!%!Q!QRVR]R]^egmRnRn!o!ooooooo "&!N!Nt{{[bdjOkOk!l!lllllll  5	m!;;DKKQW<X<XYYYYYYYYHHh tw)MMPVW]P^^akklll""8V444r  c                 j  K   |                                   d{V  |                     |          }d}|                     |d          }|                     |d          }d}|rd}|                     |           d{V }n|                     |           d{V }|                     |||d          S )a  
        fetch the set leverage for all leverage markets, only spot margin is supported on gate
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-lending-markets
        :see: 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>`
        NrL   r7   r  rF   )r  r  r;  r  publicMarginGetUniCurrencyPairsrY  parse_leverages)r  r  rC  rx  r  marketIdRequests         r  fetch_leverageszgate.fetch_leverages  s       !!!!!!!!!%%g..NN6955	69-- 	G-O!AA&IIIIIIIIHH ">>vFFFFFFFFH ##HgOOOr  c                     |                      |dd          }|                     |d          }||                     ||dd          d ||dS )Nr  r7   rP  r  rF   )r%  r  r  longLeverageshortLeverage)r  r   r  )r  rP  r2  r1  leverageValues        r  r  zgate.parse_leverage  s`    %%hFF))(J??&&xfEE)*
 
 	
r  c                   K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     |d|          S )a  
        fetches option data that is commonly found in an option chain
        :see: 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  r7   )r  r2  !publicOptionsGetContractsContractrq  parse_optionr  s         r  fetch_optionzgate.fetch_option$  s       !!!!!!!!!V$$t
 ??GU[@\@\]]]]]]]]R   4888r  c                 
  K   |                                   d{V  |                     |          }d|d         dz   i}|                     |                     ||                     d{V }|                     |dd          S )a  
        fetches data for an underlying asset that is commonly found in an option chain
        :see: https://www.gate.io/docs/developers/apiv4/en/#list-all-the-contracts-with-specified-underlying-and-expiration-time
        :param str currency: 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  r  _USDTr8   )r  r  r  rq  parse_option_chain)r  r  rC  r  rw  rx  s         r  fetch_option_chainzgate.fetch_option_chain\  s       !!!!!!!!!==&&(6*W4
 77GV8T8TUUUUUUUUV &&xv>>>r  c                    |                      |d          }|                     ||          }|                     |d          }i d|dd d|d         d|d|                     |          dd d	d d
|                     |d          d|                     |d          dd d|                     |d          d|                     |d          d|                     |d          dd dd dd dd S )Nr8   r  r%  r  r  r/  r.  impliedVolatilityopenInterestr  rj  r  rg  midPricer  r~  r  rd  r
  r	  rI  r  r  r  )r'  r8  r  r  r`  )r  r  r  r2  r1  r/  s         r  r   zgate.parse_option  sx   R ##E622!!(F33''}==	
E

 fX&
 	

 Y//
  
 D
 ((==
 ((==
 
 ))%>>
 ))%>>
 t//7IJJ
 d
 $
  $!
" 4#
 	
r  c
                     |d S |                      |d          }
|
>| j        dz   |z   }|                     | j        d         |
|           t	          |          d S )Nlabelr  r  )r'  r7   throw_exactly_matched_exceptionr  r"   )r  r  reasonrR   r  rJ  rc  rx  requestHeadersrequestBodyr+  feedbacks               r  handle_errorszgate.handle_errors  sm    4   733w}t+H001I5RZ[[[)))tr  )NNNN)N)NN)__name__
__module____qualname__r  boolr  rk  r0  r   r   r   r8  r!   rK  r>  r<  rr  r=  r  r  r  r  r  ro  r   r  r  r   r  r  r  r  r   r  r   r  r  r  r/  r2  r   r4  r
   rA  r   r?  rC  r   rY  r   ra  r_  r   r  r  r   r  r)  r  r  r  r  r   r  r  r  r  r   r  r  floatr   r0  r6  r  r   r   r   rZ  r   rg  rL  r  r  r  r   rT  r  r  r  r  r  r  r    r   r  r  r  r!  r(  r+  r/  rA  r.  rK  rO  rR  rU  rJ  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   r1  __classcell__)r  s   @r  r5   r5       s       U U U U Un-t - - - - - -=
3 =
 =
 =
 =
~V VC V VRU Vjm V  zI V V V V V V *, 9 9V 9 9 9 96 /1 h h h hT 35    0d
 d
 d
L 13 x x x xt  & &*R ! ! ! !8 155        $ 7;r        *$ $ $2c c c -/ k k: k k k kZ <> :1 :1s :1 :1 :1 :1x <@ 9? 9? 9? 9? 9? 9?vE
 E
6 E
 E
 E
 E
N EG # # # # # #J =? F
 F
 F
 F
 F
 F
P ;= 8 8c 8AT 8 8 8 8< /1 1 1[ 1 1 1 12  
 
f 
 
 
 
< ?C2 2 2$s) 2 2 2 2h BFb M Mw M M M M>- - - - - -^ 9=4^bkm ,L ,L# ,LS ,LX[ ,L ,L ,L ,L\OnI] O O O O
 
& 
 
 
 
. @DB m mS m mS\ m m m m^ 68 %1 %1 %1F %1 %1 %1 %1Nl l6 lV l l l l\ 6:" #5 #57 #5 #5 #5 #5 #5J   *, W W W W W Wr 8<$]ajl @L @L @LC @LWZ @Lquvzq{ @L @L @L @LD ?CQUdhqs L Ls L3 L^a L L L L >BPTcgpr &Y &Ys &Y# &Y]` &Y &Y &Y &YP+ + +4 + + + +Z <@d[] fA fA fAS fA fAbfglbm fA fA fA fAP ?CQUdhqs % %3 % %3 %^a % % % %N 37TX\eg ~A ~AC ~As ~ARU ~A ~A ~A ~A@L L L5 L L L L\ 04$UYbd ; ; ;C ;s ;imnyiz ; ; ; ;@ 37TX\eg ; ;C ;s ;RU ;lpq|l} ; ; ; ;@ EIQS (: (:3 (: (: (: (: (:T: : :$3 3 3N
 N
x N
; N
 N
 N
 N
` mqy{ ~2 ~2 ~2I ~2Y ~2X] ~2fi ~2 ~2 ~2 ~2@ FH $+ $+$|*< $+ $+ $+ $+L os{} M, M,3 M,i M,y M,Z_ M,hk M, M, M, M,^ XZ T Tc T T T T T  fjx|  FH K2 K23 K2 K29 K2I K2_b K2ru K2 K2 K2 K2Z: : : y y y5 y y y yv 8<B 32 32C 32 32 32 32 32j 59tZ^gi W Wc W WTW Wnrsxny W W W W 7;\`ik [ [ [3 [VY [ptuzp{ [ [ [ [* BFTXgktv BO BO3 BOc BOad BO BO BO BOH 9=R y2 y2S y2# y2 y2 y2 y2v 59 A3 A3c A3 A3 A3 A3F ac 47 473 47 47C 47TW 47gt 47 47 47 47l
 
 
 
 
 
, ?C2 A A3 A A A A AFn nv n n n n` 8: P5 P53 P5 P5 P5 P5d 8<B b7 b7W b7 b7 b7 b7H =A qD qD' qD qD qD qDf EG B B B B B B8   4     > RT : :# :S : : : :6 BD $: $:S $: $: $: $:L Z\ ): ):3 ):c ):5 ): ): ): ):V JL  :  :c  :5  :  :  :  :D3
 3
 3
 3
 3
 3
j  b$T ;P ;P ;P ;Pz FH @ @ @ @ @ @*
 *
f *
HZ *
 *
 *
 *
X ?A 
H 
H# 
HEW 
H 
H 
H 
H <> 
G 
Gs 
GBT 
G 
G 
G 
G HLZ^mqz| 3I 3I 3ITW 3Igj 3I 3I 3I 3Ij
 
F 
 
 
 
: <@daenp *O *OS *O *O[^ *O *O *O *OX ?CQUdhqs 0Y 0Y 0Y3 0Y^a 0Y 0Y 0Y 0Yd#
 #
 #
J" " "H .2SW`b fC fCs fC# fCS fC fC fC fCPO
 O
 O
 O
 O
 O
b)8 )8 )8V CGr X Xd XC X X X X 46    B BFTXac %G %Gs %G3 %Gc %G %G %G %GN 9=4^bkm EG EG# EGS EGX[ EG EG EG EGN> >V > > > >@ 68 * * *F * * * *X+
 +
6 +
 +
 +
 +
Z CGr P P3 Pi PV[ P P P P& 8: d5 d53 d5h d5 d5 d5 d5L :>b -P -PT#Y -PY -P -P -P -P^	
 	
x 	
 	
 	
 	
 68 69 69 69F 69 69 69 69p :< :? :?S :? :? :? :? :?x>
 >
H >
V >
 >
 >
 >
@      r  r5   ); ccxt.async_support.base.exchanger   ccxt.abstract.gater   r@  rn  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    typingr!   ccxt.base.errorsr"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   ccxt.base.decimal_to_precisionr2   ccxt.base.preciser3   r5    r  r  <module>r@     sE   6 5 5 5 5 5 * * * * * *   N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N       * * * * * * 0 0 0 0 0 0 - - - - - - . . . . . . - - - - - - . . . . . . ' ' ' ' ' ' & & & & & & ( ( ( ( ( ( . . . . . . ) ) ) ) ) ) * * * * * * 5 5 5 5 5 5 ) ) ) ) ) ) . . . . . . 1 1 1 1 1 1 4 4 4 4 4 4 % % % % % %Gk Gk Gk Gk Gk8[ Gk Gk Gk Gk Gkr  