
    !:hD                       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 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'  G d dee      Z(y)    )Exchange)ImplicitAPIN)AccountAnyBalances
CurrenciesCurrencyIntMarketNumOrder	OrderBook	OrderSide	OrderTypePositionStrStringsTickerTickersTradeMarketInterfaceTransferEntry)List)ExchangeError)ArgumentsRequired)
BadRequest)InvalidOrder)RateLimitExceeded)TRUNCATE)	TICK_SIZE)Precisec                       e Zd Zdef fdZi fdZdefdZi fdefdZde	de
fdZi fde
fdZi fdefd	Zi fdee   fd
Zde	defdZdTde	dedefdZi fdedefdZdi fdedefdZdddi fdedededee   fdZdTdedefdZdi fdededefdZddi fdedededee    fdZ!dTde	dede fdZ"i fdefdZ#dTdefdZ$dddi fde%dedefdZ&dTd e	dede'fd!Z(d"e%fd#Z)d$e%fd%Z*d&e%fd'Z+dUd(e%ded)e%d*e%de,f
 fd+Z-d,efd-Z.defd.Z/d/ Z0d0 Z1di fded&e2d1e3d2e4d3e5f
d4Z6i fd5ed2e4d6ed7ede7f
d8Z8dTd9e	d:e9de7fd;Z:di fde%fd<Z;di fd=ede%fd>Z<di fd=ede%fd?Z=d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e'   fdAZ?dddi fd=ede%dedefdBZ@dddi fde%dedefdCZAdddi fde%dedefdDZBdTdefdEZCdi fdFede%fdGZDdi fdedeeE   fdHZFdTdIe	defdJZGdKdLi ddfdMZHd5eIdNedOedPedQe	dRefdSZJ xZKS )Vapexreturnc                    | j                  t        t        |          i dddddg 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d"dd#dd$dd%dd&dd'dd(dd)dd*dd+dd,dd-dd.dd/dd0dd1di d2dd3dd4dd5dd6dd7dd8dd9dd:d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i dTddUddVddWddXddYddZdd[dd\dd]dd^dd_dd`ddaddbddcddddddddddddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdxdydzdzdyd{d|d}d~ddddddddddddidddddddddddddddddddddddyddt        idddt
        dt        t        t        dddd| j                  d      | j                  d      didddddddt        i dddddddd dddd dddddddddddddd ddddddddddddd ddddddddddddd ddid	ddid ddd      S )Nidr#   nameApex	countriesversionv3	rateLimit   	certifiedFproTdexhasCORSspotmarginswapfutureoption	addMarginborrowCrossMarginborrowIsolatedMargincancelAllOrderscancelAllOrdersAftercancelOrdercancelOrderscancelOrdersForSymbolscloseAllPositionsclosePositioncreateMarketBuyOrderWithCostcreateMarketOrderWithCostcreateMarketSellOrderWithCostcreateOrdercreateOrderscreatePostOnlyOrdercreateReduceOnlyOrdercreateStopOrdercreateTriggerOrder	editOrderfetchAccountsfetchBalancefetchBorrowInterestfetchBorrowRateHistoriesfetchBorrowRateHistoryfetchCanceledAndClosedOrdersfetchCanceledOrdersfetchClosedOrdersfetchCrossBorrowRatefetchCrossBorrowRatesfetchCurrenciesfetchDepositAddressfetchDepositAddressesfetchDepositsfetchDepositWithdrawFeefetchDepositWithdrawFeesfetchFundingHistoryfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchIndexOHLCVfetchIsolatedBorrowRatefetchIsolatedBorrowRatesfetchLedgerfetchLeveragefetchLeverageTiersfetchLiquidationsfetchMarginModefetchMarketLeverageTiersfetchMarketsfetchMarkOHLCVfetchMyLiquidationsfetchMyTrades
fetchOHLCVfetchOpenInterestfetchOpenInterestHistoryfetchOpenInterestsfetchOpenOrders
fetchOrderfetchOrderBookfetchOrdersfetchOrderTradesfetchPositionfetchPositionModefetchPositionsfetchPositionsRiskfetchPremiumIndexOHLCVfetchTickerfetchTickers	fetchTimefetchTradesfetchTradingFeefetchTradingFeesfetchTransferfetchTransfersfetchWithdrawalfetchWithdrawalsreduceMarginrepayCrossMargin)repayIsolatedMarginsandboxsetLeveragesetMarginModesetPositionModetransferwithdraw
timeframes15153060120240360720DWM)1m5m15m30m1h2h4h6h12h1d1w1Mhostnamezomni.apex.exchangeurlszOhttps://github.com/user-attachments/assets/fef8f2f7-4265-46aa-965e-33a91881cb00zhttps://{hostname}/api)publicprivatez&https://testnet.omni.apex.exchange/apizhttps://apex.exchange/z"https://api-docs.pro.apex.exchangez`https://apex-pro.gitbook.io/apex-pro/apex-omni-live-now/trading-perpetual-contracts/trading-feesz https://omni.apex.exchange/trade)logoapitestwwwdocfeesreferralr   get   )z
v3/symbolszv3/history-fundingz	v3/tickerz	v3/klinesz	v3/tradeszv3/depthzv3/timezv3/data/all-ticker-info)z
v3/accountzv3/account-balancezv3/fillszv3/order-fillsv3/orderzv3/history-orderszv3/order-by-client-order-idz
v3/fundingzv3/historical-pnlzv3/open-orderszv3/transferszv3/transfer)zv3/delete-open-orderszv3/delete-client-order-idzv3/delete-orderr   zv3/set-initial-margin-ratezv3/transfer-outzv3/contract-transfer-out)r   posthttpExceptions403
exceptionszapikey sign errorzrequest para error)200062001610001)ORDER_PRICE_MUST_GREETER_ZERO)ORDER_POSSIBLE_LEAD_TO_ACCOUNT_LIQUIDATED1ORDER_WITH_THIS_PRICE_CANNOT_REDUCE_POSITION_ONLY)exactbroadr   0.00050.0002)takermakerrequiredCredentials)apiKeysecretwalletAddress
privateKeypasswordg?6956)defaultTypedefaultSlippagebrokerId)IOCFOKPOGTD)
marginModetriggerPricetriggerPriceTypetriggerDirectionstopLossPricetakeProfitPriceattachedStopLossTakeProfittimeInForcehedgedselfTradePreventiontrailingleveragemarketBuyByCostmarketBuyRequiresPriceiceberg  i )r   limitdaysBack	untilDayssymbolRequired)r   triggerr   r   )r   r   r   r   r   d   )r   r   r   r   r   r   r   r      )	r   rE   rF   rl   rr   rq   rt   rS   rm   extendsdefault)linearinverse)r   r5   )precisionModecommonCurrenciesoptionsfeatures)	deep_extendsuperr#   describer   r   r   parse_numberr    )self	__class__s    Q/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/async_support/apex.pyr   zapex.describe   s   dD : < W?
&W?
FW?
 W?
 t	W?

 W?
 W?
 4W?
 4W?
  ]]] %] 	]
 %] %] U] $U] '] "4] '] t] ] )%] $U]   !]" /#]$ ,U%]& 0']( t)]* +], &t-]. (/]0 "41]2 %d3]4 U5]6  7]8 9]: &u;]< +E=]> )%?]@ /A]B &uC]D $UE]F 'G]H (I]J "4K]L &uM]N (O]P  Q]R *5S]T +EU]V &tW]X #EY]Z *4[]\ $U]]^ "5_]` *5a]b +Ec]d ue]f  g]h %ei]j $Uk]l "5m]n +Eo]p q]r !%s]t &uu]v  w]x dy]z $T{]| +E}]~ %e]@ "4A]B dC]D !$E]F tG]H #DI]J  K]L $UM]N !$O]P %eQ]R )%S]T tU]V W]X TY]Z t[]\ "5]]^ #E_]`  a]b !$c]d "5e]f #Eg]h i]j #Ek]l (-#!&#(!!y]W?
N OW?
j ,kW?
l i67
 GG 0;z>mW?
J &'./%&%&%&$%#$34	 '(./$%*+$%-.78&'-.*+()'( 2356+,$%67+,45&KW?
X (YW?
^  11' 6BAMIU_W?
@ !..x8!..x8AW?
L "!&# $MW?
Z ' "%#'"  $&+(,,0,1).+06:#'#'"&#'	( #(/4$($)+027#()$, %)&+!$$*%+*/& ',#($)*/	# ',!%#($)*/( ',!$$*%+#($)*/$ *.#o:z "9  $	yBiW?
 W W	    c                    K   | j                  |       d{   }| j                  |di       }| j                  |d      S 7 )w)ai  
        fetches the current integer timestamp in milliseconds from the exchange server

        https://api-docs.pro.apex.exchange/#publicapi-v3-for-omni-get-system-time-v3

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        Ndatatime)publicGetV3Time	safe_dictsafe_integerr   paramsresponser   s       r   
fetch_timezapex.fetch_time2  sG      --f55~~h3   v.. 6s   AA*Ac                     | j                         }||| j                  |      d}d}| j                         }| j                  |d      |d<   | j                  |d      |d<   |||<   | j	                  |      S )N)info	timestampdatetimeUSDTavailableBalancefreetotalEquityValuetotal)millisecondsiso8601accountsafe_stringsafe_balance)r   r  r  resultcoder  s         r   parse_balancezapex.parse_balanceE  s     %%'	"Y/

 ,,.**85GH++H6HIt  ((r   c                    K   | j                          d{    | j                  |       d{   }| j                  |di       }| j                  |      S 7 A7 *w)aA  
        query for account info

        https://api-docs.pro.apex.exchange/#privateapi-v3-for-omni-get-retrieve-user-account-balance

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        Nr   )load_marketsprivateGetV3AccountBalancer   r  r   s       r   fetch_balancezapex.fetch_balancea  sY      !!!88@@~~h3!!$'' 	"@   AAAA)AAr  c                 6    | j                  |dd      }|d d |dS )Nr&   0)r&   typer  r  r  )r   r  	accountIds      r   parse_accountzapex.parse_accounto  s,    $$WdC8		
 	
r   c                    K   | j                          d{    | j                  |       d{   }| j                  |di       }| j                  |      S 7 A7 *w)a  
        query for balance and get the amount of funds available for trading or funds locked in orders

        https://api-docs.pro.apex.exchange/#privateapi-v3-for-omni-get-retrieve-user-account-data

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        Nr   )r  privateGetV3Accountr   r  r   s       r   fetch_accountzapex.fetch_accountx  sY      !!!11&99~~h3!!$'' 	"9r  c                   K   | j                  |       d{   }| j                  |di       }| j                  |di       }| j                  |di       }| j                  |dg       }| j                  |dg       }i }t        dt	        |            D ]  }	||	   }
| j                  |
d      }| j                  |      }| j                  |
d	      }i }t        dt	        |            D ]  }||   }| j                  |d
g       }t        dt	        |            D ]  }||   }| j                  |d      }||k(  s | j                  |d      }| j                  |      }|||d| j                  |d       | j                  |d      | j                  |d      | j                  | j                  | j                  |d                  | j                  |d      dd| j                  |d      dddd	||<     t        |j                               }t	        |      }|dk(  }|rdnd}| j                  |
||d|d||dddddddddddd|d      ||<    |S 7 Bw)a0  
        fetches all available currencies on an exchange

        https://api-docs.pro.apex.exchange/#publicapi-v3-for-omni-get-all-config-data-v3

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        Nr   
spotConfig
multiChainassetschainsr   tokendisplayNametokenschainIddepositDisablewithdrawEnableminFeedecimalsminWithdrawminmax
minDeposit)r   deposit)	r  r&   networkactiver5  r   fee	precisionlimitsFcrypto)amountr   r5  )r  r  r&   r  r'   r7  r5  r   r8  r9  r:  networks)publicGetV3Symbolsr   	safe_listrangelenr  safe_currency_codenetwork_id_to_code	safe_boolsafe_numberr   parse_precisionlistkeyssafe_currency_structure)r   r  r  r   r$  r%  rowsr'  r  icurrency
currencyIdr  r'   r=  jchainr*  fr(  	tokenName	networkIdnetworkCodenetworkKeysnetworksLengthemptyChainsvalueForEmptys                              r   fetch_currencieszapex.fetch_currencies  s     0088~~h3^^D,;
^^JbA
t ~~j(B7
Hb9q#d)$ A	AAwH))(G<J**:6D##Hm<DH1c&k* q	x<q#f+. A"1IE $ 0 0 @I J.$($4$4UI$F	&*&=&=i&H$)"+'2&*+/>>%AQ+R'R(,u>N(O#'#3#3E8#D)-):):4;O;OPTP`P`afhrPs;t)u ,0+;+;E=+Q+/-"
 ,0+;+;E<+P+/,"	'1-: x}}/K -N(A-K%0EdM77   ()!  $#
  $#!
  $#  %39 F4LOA	D E 9s   IIDI8D"Ic                    K   | j                  |       d{   }| j                  |di       }| j                  |di       }| j                  |dg       }| j                  |      S 7 Nw)a.  
        retrieves data on all markets for apex

        https://api-docs.pro.apex.exchange/#publicapi-v3-for-omni-get-all-config-data-v3

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        Nr   contractConfigperpetualContract)r>  r   r?  parse_markets)r   r  r  r   rZ  r[  s         r   fetch_marketszapex.fetch_markets3  sp      0088~~h3.>C NN>;NPRSn !!"344u 9s   A(A&AA(marketc                    | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |      }| j                  |d      }| j                  |      }	|dz   |z   dz   |	z   }
d}| j                  d	      }| j                  d
      }| j                  i d|d|d|
d|d|d|	d|d|d|dddddd ddddddd| j	                  |d      dddd||| j                  |d      |dk(  rd n||dk(  rd n| j                  |      d d | j                  |d      | j                  |d       d!| j                  |d"      | j                  |d#      d$| j                  |d      | j                  |d%      d$d d d$d d d$d&d |d'      S )(NsymbolcrossSymbolNamel2PairIdbaseTokenIdsettleAssetId/:r   r   r   r&   id2basequotesettlebaseIdquoteIdsettleIdr  r5   r3   Fr4   Tr6   r7   r7  enableTradecontractminOrderSizestepSizetickSize)r<  pricedisplayMinLeveragedisplayMaxLeverager1  maxOrderSize)r   r<  rs  cost)r   r   r   r   contractSizeexpiryexpiryDatetimestrike
optionTyper9  r:  createdr  )r  rB  r   safe_market_structurerD  rE  r  )r   r^  r&   rg  rl  rk  ri  rh  rm  rj  r`  ry  takerFeemakerFees                 r   parse_marketzapex.parse_marketx  s   fh/v'89""6:6!!&-8  9&&v.##FO<((2#%+f4$$X.$$X.)) 3+
"3+
33+
 f3+
 D	3+

 U3+
 f3+
 f3+
 w3+
 3+
 F3+
 E3+
 d3+
 D3+
 e3+
 e3+
  dnnV];!3+
" #3+
$  ,,V^D%{d'-{df9M**6:>))&*=  ++F4HI++F4HI
  ++FNC++FNC
  
  $ e3+
 3 3	r   Ntickerc           
      ^   | j                         }| j                  |d      }| j                  ||      }| j                  ||      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }	| j                  |d      }
| j                  |d      }| j	                  i d|d|d	| j                  |      d
|
d|dd dd dd dd dd dd d|d|dd dd d|dd |	|| j                  |d      | j                  |d      |d|      S )Nr`  	lastPriceprice24hPcntturnover24h	volume24hhighPrice24hlowPrice24hr  r  highlowbid	bidVolumeask	askVolumevwapopencloselastpreviousClosechange
percentageaverage	markPrice
indexPrice)
baseVolumequoteVolumer  r  r  )r  r  safe_marketsafe_symbolsafe_tickerr  )r   r  r^  r  marketIdr`  r  r  r  r  r  r  s               r   parse_tickerzapex.parse_ticker  s   & %%'	##FH5!!(F3!!(F34%%fn=
&&v}=%%fk:
7v}5 !
f!
!
 Y/!
 D	!

 3!
 4!
 !
 4!
 !
 D!
 D!
 T!
 D!
 T!
 d!
  *!!
" t#!
$ %&))&+>**6<@-!
. / 	r   r`  c                 4  K   | j                          d{    | j                  |      }d|d   i}| j                  | j                  ||             d{   }| j	                  |dg       }| j                  |di       }| j                  ||      S 7 }7 >w)a  
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://api-docs.pro.apex.exchange/#publicapi-v3-for-omni-get-ticker-data-v3

        :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>`
        Nr`  rg  r   r   )r  r^  publicGetV3Tickerextendr?  r   r  r   r`  r  r^  requestr  tickers	rawTickers           r   fetch_tickerzapex.fetch_ticker  s      !!!V$fUm
 //GV0LMM..626NN7Ar2	  F33 	"
 N"   BBA BB=BBsymbolsc                    K   | j                          d{    | j                  |       d{   }| j                  |dg       }| j                  ||      S 7 B7 +w)a  
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://api-docs.pro.apex.exchange/#publicapi-v3-for-omni-get-ticker-data-v3

        :param str symbols: 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>`
        Nr   )r  publicGetV3DataAllTickerInfor?  parse_tickers)r   r  r  r  r  s        r   fetch_tickerszapex.fetch_tickers  s[      !!!::6BB..626!!'733 	"Bs   AAAA*AAr   sincer   c                   K   | j                          d{    | j                  |      }| j                  | j                  ||      |d   d}|d}||d<   | j	                  d||      \  }}|||d<   | j                  | j                  ||             d{   }| j                  |di       }	| j                  |	|d   g       }
| j                  |
||||      S 7 7 Dw)	a  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://api-docs.pro.apex.exchange/#publicapi-v3-for-omni-get-candlestick-chart-data-v3

        :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
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest candle to fetch
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        Nrg  )intervalr`  r   r   endstartr   )
r  r^  r  r   handle_until_optionpublicGetV3Klinesr  r   r?  parse_ohlcvs)r   r`  	timeframer  r   r  r^  r  r  r   OHLCVss              r   fetch_ohlcvzapex.fetch_ohlcv  s      !!!V$(()YOUm
 =E 225'6J$GG//GV0LMM~~h3fUmR8  E5II 	" Ns#   C CBC CAC C c           
          | j                  |ddg      | j                  |ddg      | j                  |ddg      | j                  |ddg      | j                  |d	d
g      | j                  |ddg      gS )Nr  tr  or  hr  lr  cvolumev)safe_integer_nsafe_number_n)r   ohlcvr^  s      r   parse_ohlcvzapex.parse_ohlcv2  s     ~6uvsm4uvsm4uucl3uwn5uxo6
 	
r   c                 z  K   | j                          d{    | j                  |      }d|d   i}|d}||d<   | j                  | j                  ||             d{   }| j	                  |di       }| j                         }| j                  ||d   |dd      }	| j                  |d	      |	d
<   |	S 7 7 Xw)aK  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://api-docs.pro.apex.exchange/#publicapi-v3-for-omni-get-market-depth-v3

        :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`  rg  r   r   r   baunonce)r  r^  publicGetV3Depthr  r   r  parse_order_bookr   )
r   r`  r   r  r^  r  r  r   r  	orderbooks
             r   fetch_order_bookzapex.fetch_order_bookI  s      !!!V$fUm
 =E ..t{{7F/KLL6 ~~h3%%'	))$x0@)SRUV	!..tS9	'O 	" Ms#   B;B7A	B; B9!AB;9B;c                 $  K   | j                          d{    | j                  |      }d|d   i}|d}||d<   | j                  | j                  ||             d{   }| j	                  |dg       }| j                  ||||      S 7 u7 -w)a  
        get the list of most recent trades for a particular symbol

        https://api-docs.pro.apex.exchange/#publicapi-v3-for-omni-get-newest-trading-data-v3

        :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]: the latest time in ms to fetch trades for
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        Nr`  rg  r   r   r   )r  r^  publicGetV3Tradesr  r?  parse_trades)	r   r`  r  r   r  r^  r  r  tradess	            r   fetch_tradeszapex.fetch_trades}  s      !!!V$fUm
 =E //GV0LMM* &"5  >>= 	" Ns"   BBA	B B!,BBtradec                    | j                  |ddg      }| j                  ||      }| j                  |ddg      }| j                  |g d      }| j                  |ddg      }| j                  |dd	g      }| j                  |d
dg      }| j                  |dg      }	| j                  |dg      }
| j	                  ||d || j                  |      |d   |	d |||d |
d|      S )Nsr`  rK  r&   )r  T	createdAtprs  r  sizeSsider  r8  )r  r&   orderr  r  r`  r  takerOrMakerr  rs  r<  rw  r8  )safe_string_nr  r  safe_string_lower_n
safe_trader  )r   r  r^  r  r&   r  priceStringamountStringr  r  r8  s              r   parse_tradezapex.parse_trade  s    %%ec8_=!!(F3T{3''/FG	((g?))%#v?''V}=!!%&2  0"Y/X&  " 
  	r   c                 4  K   | j                          d{    | j                  |      }d|d   i}| j                  | j                  ||             d{   }| j	                  |dg       }| j                  |di       }| j                  ||      S 7 }7 >w)a}  
        retrieves the open interest of a contract trading pair

        https://api-docs.pro.apex.exchange/#publicapi-v3-for-omni-get-ticker-data-v3

        :param str symbol: unified CCXT market symbol
        :param dict [params]: exchange specific parameters
        :returns dict} an open interest structure{@link https://docs.ccxt.com/#/?id=open-interest-structure:
        Nr`  rg  r   r   )r  r^  r  r  r?  r   parse_open_interestr  s           r   fetch_open_interestzapex.fetch_open_interest  s      !!!V$fUm
 //GV0LMM..626NN7Ar2	''	6:: 	"
 Nr  c           	          | j                         }| j                  |d      }| j                  ||      }| j                  ||      }| j	                  || j                  |d      d || j                  |      |d|      S )Nr`  openInterest)r`  openInterestAmountopenInterestValuer  r  r  )r  r  r  r  safe_open_interestr  )r   interestr^  r  r  r`  s         r   r  zapex.parse_open_interest  s    & %%'	##Hh7!!(F3!!(F3&&"&"2"28^"L!%"Y/(
  	r   c           
      2  K   |t        | j                  dz         | j                          d{    i }| j                  |      }|d   |d<   |||d<   |||d<   | j	                  |d      }|||d<   | j                  |g d      }|||d	<   | j                  | j                  ||             d{   }	g }
| j                  |	d
i       }| j                  |dg       }t        dt        |            D ]q  }||   }| j	                  |d      }| j                  |d      }|
j                  || j                  ||      | j                  |d      || j!                  |      d       s | j#                  |
d      }| j%                  ||||      S 7 b7 ޭw)a  
        fetches historical funding rate prices

        https://api-docs.pro.apex.exchange/#publicapi-v3-for-omni-get-funding-rate-history-v3

        :param str symbol: unified symbol of the market to fetch the funding rate history for
        :param int [since]: timestamp in ms of the earliest funding rate to fetch
        :param int [limit]: the maximum amount of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>` to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest funding rate
        :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 `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>`
        Nz5 fetchFundingRateHistory() requires a symbol argumentr&   r`  beginTimeInclusiver   pageendTimeendTimeExclusiveuntilr  r   historyFundsr   fundingTimestamprate)r  r`  fundingRater  r  r  )r   r&   r  r^  r   r  publicGetV3HistoryFundingr  r   r?  r@  rA  r  appendr  rE  r  sort_byfilter_by_symbol_since_limit)r   r`  r  r   r  r  r^  r  r  r  ratesr   
resultListrK  entryr  r  sorteds                     r   fetch_funding_rate_historyzapex.fetch_funding_rate_history  s     >#DGG.e$eff!!!V$"4L,1G()$GG  0"GFO..v7_`'*:G&'77GV8TUU ~~h3^^D."=
q#j/* 
	AqME))%1CDI''x8HLL**8V<#//v>& LL3 	
	 e[100NNY 	" Vs#   .FFBF6F7CFFr  c                    | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  ||      }|d   }| j                  |d      }| j                  |d      }	| j                  |d      }
| j                  |d      }| j                  |d	      }| j	                  | j                  |d
            }| j                  |d      }| j                  i d|d|d|d| j                  |      dd d|d| j                  |      d|d| j                  |
      d| j                  | j                  |d            d| j                  |d      d| j                  |d      d	|d|d| j                  |d      dd dd d |	d |d d | j                  |d      |d   d|d|      S )Nr  r&   clientIdr`  rs  r  r  statusr  remainingSizeupdatedTimeclientOrderIdr  r  lastTradeTimestamplastUpdateTimestampr   postOnly
reduceOnlyr   r   r   r8  rm  )rw  rL  )r  r<  filled	remainingrw  r  r8  r  )r   r  r  safe_string_lower	omit_zero
safe_orderr  parse_order_statusparse_order_typeparse_time_in_forcerD  )r   r  r^  r  orderIdr  r  r`  rs  r<  	orderTyper  r  r  r	  s                  r   parse_orderzapex.parse_orderC  sj   n %%e[9	""5$/((
;##E84!!(F3!  0!!%0$$UF3	!!%2%%eV4NN4#3#3E?#KL	"//}E  
' 
] 
  
 Y/	 

 !$ 
 "#6 
 d--f5 
 f 
 D)))4 
 433D4D4DUM4Z[ 
 uj9 
 $..= 
 D 
 U 
 D,,UNC 
  t! 
" T# 
$ "((6":. 9 
: ; 	r   r   c                 6    ddddd}| j                  ||d       S )NGOOD_TIL_CANCELFILL_OR_KILLIMMEDIATE_OR_CANCEL	POST_ONLY)r  r  r  r  r  )r   r   timeInForcess      r   r  zapex.parse_time_in_force  s,    0*#8$	
 k4@@r   r  c                 B    |ddddddd}| j                  |||      S |S )Nr  r  canceled)PENDINGOPENFILLED	CANCELINGCANCELEDUNTRIGGEREDr  )r   r  statusess      r   r  zapex.parse_order_status  s=    !"'&%H ##Hff==r   r  c                 :    ddddddd}| j                  |||      S )NLIMITMARKET
STOP_LIMITSTOP_MARKETTAKE_PROFIT_LIMITTAKE_PROFIT_MARKET)r'  r(  r)  r*  r+  r,  )safe_string_upper)r   r  typess      r   r  zapex.parse_order_type  s2    &(!4"6
 %%eT488r   r  	delimiter
marketTypec                    |||| j                   v r| j                   |   }n|| j                  v r| j                  |   }nh| j                  |      }|| j                  v rI| j                  |   }t        |      }|dkD  r*| j                  |   d   d   |k(  r| j                  |   d   }t        t
        |   ||||      S )Nr   rg  )marketsmarkets_by_idadd_hyphen_before_usdtrA  r   r#   r  )	r   r  r^  r/  r0  newMarketIdr2  
numMarketsr   s	           r   r  zapex.safe_market  s    >h24<<'h/T///++H5"99(C$"4"44"00=G!$WJ!A~--k:1=eDP%)%7%7%DQ%GFT4,Xvy*UUr   
_accountIdc                     |xs t        | j                  d            }d|z   dz   t        | j                               z   dz   t        | j                  d            z   S )N   z	apexomni--   )strrand_numberr  )r   r7  r  s      r   generate_random_client_id_omniz#apex.generate_random_client_id_omni  s\    ;#d&6&6r&:";	Y&,s43D3D3F/GG#MPSTXTdTdefTgPhhhr   c                     |j                         }|j                  d      }| j                  ||dz
        }|dkD  r|dk7  r|d| dz   ||d  z   S |S )Nr  r   r   r:  )upperfindr  )r   r`  uppercaseSymbolindex
symbolChars        r   r4  zapex.add_hyphen_before_usdt  sb     ,,.$$V,%%feai8
19s*!E?S(6%&>99r   c                 r    | j                  | j                  d      }|t        | j                  dz         |S )Nseedsz the "seeds" key is required in the options to access private endpoints. You can find it in API Management > Omni Key, and then set it.options["seeds"] = XXXX)r  r   r   r&   )r   rF  s     r   	get_seedszapex.get_seeds  sC      w7=#DGG  /O  %O  P  Pr   c                    K   | j                  | j                  dd      }|dk(  r8| j                          d {   }| j                  |dd      | j                  d<   | j                  d   S 7 3w)Nr  r  r&   )r  r   r"  )r   r  accountDatas      r   get_account_idzapex.get_account_id  sh     $$T\\;D	 $ 2 2 44K(,(8(8dC(PDLL%||K(( 5s   6A.A,4A.r  r<  rs  c                 B  K   | j                          d{    | j                  |      }|j                         }|j                         }	| j                  ||      }
d}|| j	                  ||      }| j                  | j                  di       }| j                  |dd      }| j                  |dd      }| j                  t        j                  t        j                  t        j                  ||
      t        |            t        |d   d	               t        |d   d	   | j                  | j                        }| j!                         }|d
k(  }|r|t#        | j$                  dz         | j'                  |d      }| j)                  |d|      }|d}|s|rd}n|dk(  rd}| j+                  |d      }| j+                  |d      }| j-                  |g d      }| j/                          d{   }|| j1                  |      }| j+                  |g d      }||||d   |
||	t        |      t        |      d	}| j3                  | j5                  | j7                               |       d{   }|d   |	||
||t9        t;        j<                  |dz  dz               ||| j?                  | j@                  dd      d
}||d<   | jC                  | jE                  ||             d{   }| j                  |di       }| jG                  ||      S 7 7 '7 7 1w)a<  
        create a trade order

        https://api-docs.pro.apex.exchange/#privateapi-v3-for-omni-post-creating-orders

        :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 currency you want to trade in units of base currency
        :param float [price]: the price at which the order is to be fullfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param float [params.triggerPrice]: The price a trigger order is triggered at
        :param str [params.timeInForce]: "GTC", "IOC", or "POST_ONLY"
        :param bool [params.postOnly]: True or False
        :param bool [params.reduceOnly]: Ensures that the executed order does not flip the opened position.
        :param str [params.clientOrderId]: a unique id for the order
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr  r5   r   gMb@?r   g-C6*?r9  rs  r(  z: createOrder() requires a price argument for market ordersr   r  r  iocr  r
  r  r  client_order_idrl  )	r  slotIdr  pairIdr  rs  	directionmakerFeeRatetakerFeeRater&     i ' r   r   )
r`  r  r  r  rs  limitFee
expirationr   r  r   	signaturer   )$r  r^  r@  amount_to_precisionprice_to_precisionr   r   rE  decimal_to_precisionr!   
string_add
string_mulr<  r   r   paddingModer  r   r&   r-  is_post_onlyomitr  rJ  r>  get_zk_contract_signature_objremove0x_prefixrG  intmathfloorr  r   privatePostV3Orderr  r  )r   r`  r  r  r<  rs  r  r^  r  	orderSide	orderSize
orderPricer   r   r   rU  timeNowisMarketr   r
  r  r  orderToSignrW  r  r  r   s                              r   create_orderzapex.create_order  s    & !!!V$JJL	JJL	,,VV<	
00?J~~dii4  w7  w7,,W-?-?@R@RSZSeSefpr{S|  B  CH  I  AJ  LO  PV  Wb  Pc  dk  Pl  Lm  .n  px  z@  AL  zM  NU  zV  X\  Xj  Xj  lp  l|  l|  }##%(#DGG.j$jkk,,V]C$$XtV<+K)%36=16:.**63cd--//	  ??	JM6#ST"#"Y'"JJ

 <<T=Q=QRVR`R`Rb=cepqq	Tl djj4:K)KLM&%((z6J
  )00Wf1MNN~~h3f--y 	": 0 r OsH   LLGL1L2A>L0L1A:L+L,*LLLLr  fromAccount	toAccountc                 .
  K   | j                          d{    | j                  |       d{   }| j                  |di       }| j                  |di       }| j                  |dg       }	| j                  |di       }
| j                  |
dg       }| j                  |
di       }| j	                  |dd      }| j	                  |d	d      }| j	                  |d
d      }| j	                  |dd      }| j                  |       d{   }| j                  |di       }| j                  |di       }| j	                  |dd      }| j	                  |dd      }| j                  |dg       }d}t        |      dkD  r| j	                  |d   dd      }| j	                  |dd      }| j	                  |dd      }i }g }||j                         dk(  r|	}n|}t        dt        |            D ]!  }| j	                  ||   dd      |k(  s||   }# | j	                  |dd      }| j                  |t        j                  d| j                  |dd            z        }| j                  | j                         dz        }| j                  |g d      } | +| j                  | j	                  | j                   d            } | j#                  |g d      }|(|j                         dk(  rd}!t%        j&                  ||!      }"|dz   }#|"||||t)        |      d| |#dd 
}$| j+                  | j-                  | j/                               |$       d{   }%||#| |%||d!}&| j1                  | j3                  |&|             d{   }'| j                  |'di       }(| j                         })| j3                  | j5                  |(| j7                  |            |)| j9                  |)      | j;                  |      dd"d#      S |||||t)        |      d||d$	}$| j+                  | j-                  | j/                               |$       d{   }%t)        |      || |%||d|||||||d%}&| j=                  | j3                  |&|             d{   }'| j                  |'di       }(| j                         })| j3                  | j5                  |(| j7                  |            |)| j9                  |)      | j;                  |      d"dd#      S 7 7 7 7 7 7 7 w)&a%  
        transfer currency internally between wallets on the same account
        :param str code: unified currency code
        :param float amount: amount to transfer
        :param str fromAccount: account to transfer from
        :param str toAccount: account to transfer to
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.transferId]: UUID, which is unique across the platform
        :returns dict: a `transfer structure <https://docs.ccxt.com/#/?id=transfer-structure>`
        Nr   rZ  r&  r$  globalcontractAssetPoolEthAddress contractAssetPoolZkAccountIdcontractAssetPoolSubAccountcontractAssetPoolAccountIdspotAccountzkAccountIddefaultSubAccountIdr  subAccountsr   r  ethereumAddressr&   ro  r(  tokenId
   r/  rT  rM  r  
4294967295i $ T)
rw  receiverAddresssubAccountIdreceiverSubAccountIdr{  r<  r8  r  timestampSeconds
isContract)r<  
expireTimeclientWithdrawIdrW  r(  
ethAddressr3   )r  r  r<  rm  rn  )	rw  r~  r  r  r{  r<  r8  r  r  )r<  r  clientTransferIdrW  rw  r  r8  r(  r{  receiverAccountIdreceiverZkAccountIdr  r~  r  )r  r>  r   r?  r  r!  rA  lowerr@  parse_to_intrc  powrE  r  r  r>  r   r_  r!   
string_modr<  get_zk_transfer_signature_objra  rG   privatePostV3ContractTransferOutr  parse_transferrL  r  r   privatePostV3TransferOut)*r   r  r<  rm  rn  r  configResponse
configDatarZ  contractAssetsr$  
spotAssetsglobalConfigr~  r  r  r  accountResponserI  rv  rw  r  ry  r  r  r  rL  r&  rK  r{  amountNumberr  r  formattedUint32zkSignAccountIdr  rk  rW  r  r  r   currentTimes*                                             r   r   zapex.transferB  s^     !!!#66v>>^^NFB?

4DbI"E^^JbA
^^J"=
~~j(B?**<9VXZ["..|=[]_`#//>[]_` ,,\;WY[\ $ 8 8 @@nn_fbAnn[-D&&{M2F''5JCPnn[-D{a$$[^WcBE%%k3DbI
$$[$;	"{'8'8':j'H#FFq#f+& 	%Aq	7B74?!!9	% ""8Y;((488B@P@PQY[egh@i3j)kl,,T->->-@4-GH**63cd  ??@P@PQUQ]Q]_j@klM6#ST"{'8'8':j'H*O%00OLO)N:J.#- ,(4"l+&$."K #@@AUAUVZVdVdVfAgituuI ($1&(G "BB4;;wX^C_``H>>(FB7D++-K;;t224t9LM( LL5++F3)#P    +#2 ,(<"l+$4
K #@@AUAUVZVdVdVfAgituuIf+-$1&* ,"%6':(<#2G  "::4;;wPV;WXXH>>(FB7D++-K;;t224t9LM( LL5++F3%'P  U 	"> AV v a, v" Ys   TTTTCTTC>TETT1T>T?CTTATTA=TTTTTTTr   rL  c                 L   | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }|| j                  |ddg      || j                  |      | j	                  ||      | j                  |d      ||| j                  |d      d		S )
Ncoinr  rm  rn  
transferIdr&   r<  r  )	r  r&   r  r  rL  r<  rm  rn  r  )r  r   r  r  rB  rE  )r   r   rL  rM  r  rm  rn  s          r   r  zapex.parse_transfer  s    %%h7
%%h<	&&x?$$X{;	$$Xd/CD"Y///
HE&&x:&"&&x:

 
	
r   c                    K   | j                          d{    d}i }|| j                  |      }|d   |d<   | j                  | j                  ||             d{   }| j	                  |di       }|S 7 a7 w)a  
        cancel all open orders in a market

        https://api-docs.pro.apex.exchange/#privateapi-v3-for-omni-post-cancel-all-open-orders

        :param str symbol: unified market symbol of the market to cancel orders in
        :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&   r`  r   )r  r^  privatePostV3DeleteOpenOrdersr  r   )r   r`  r  r^  r  r  r   s          r   cancel_all_orderszapex.cancel_all_orders  s      !!![[(F &tGH;;DKKQW<XYY~~h3 	" Zs"   A<A8AA<A:A<:A<r&   c                 R  K   i }| j                  |g d      }d}|C||d<   | j                  |g d      }| j                  | j                  ||             d{   }n.||d<   | j	                  | j                  ||             d{   }| j                  |di       }|S 7 H7 w)a\  
        cancels an open order

        https://api-docs.pro.apex.exchange/#privateapi-v3-for-omni-post-cancel-order

        :param str id: order id
 @param symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        rM  Nr&   r   )r  r_   privatePostV3DeleteClientOrderIdr  privatePostV3DeleteOrderr   r   r&   r`  r  r  r  r  r   s           r   cancel_orderzapex.cancel_order  s      **63cd$)GDMYYv'WXF!BB4;;wX^C_``HGDM!::4;;wPV;WXXH~~h3 a Ys$   AB'B#.B'	B%
B'%B'c                   K   | j                          d{    i }| j                  |g d      }d}|C||d<   | j                  |g d      }| j                  | j	                  ||             d{   }n.||d<   | j                  | j	                  ||             d{   }| j                  |di       }| j                  |      S 7 7 Y7 ,w)aX  
        fetches information on an order made by the user

        https://api-docs.pro.apex.exchange/#privateapi-v3-for-omni-get-order-id
        https://api-docs.pro.apex.exchange/#privateapi-v3-for-omni-get-order-by-clientorderid

        :param str id: the order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.clientOrderId]: a unique id for the order
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        NrM  r&   r   )r  r  r_   privateGetV3OrderByClientOrderIdr  privateGetV3Orderr   r  r  s           r   fetch_orderzapex.fetch_order  s      !!!**63cd$)GDMYYv'WXF!BB4;;wX^C_``HGDM!33DKK4PQQH~~h3%% 	" a Rs4   CC
AC2C3.C!C")CCCc                    K   | j                          d{    | j                  |       d{   }| j                  |dg       }| j                  |d||      S 7 D7 -w)aB  
        fetches information on multiple orders made by the user

        https://api-docs.pro.apex.exchange/#privateapi-v3-for-omni-get-open-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
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr   )r  privateGetV3OpenOrdersr?  parse_orders)r   r`  r  r   r  r  orderss          r   fetch_open_orderszapex.fetch_open_orders  s_      !!!44V<<&"5  ue<< 	"<s   AAAA,AAc                   K   | j                          d{    i }d}|| j                  |      }|d   |d<   |||d<   |||d<   | j                  |g d      }|||d<   | j                  |g d      }| j	                  | j                  ||             d{   }| j                  |di       }	| j                  |	d	g       }
| j                  |
|||      S 7 7 @w)
a:  
        fetches information on multiple orders made by the user *classic accounts only*

        https://api-docs.pro.apex.exchange/#privateapi-v3-for-omni-get-all-order-history

        :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, default 100
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param dict [params.until]: end time, ms
        :param boolean [params.status]: "PENDING", "OPEN", "FILLED", "CANCELED", "EXPIRED", "UNTRIGGERED"
        :param boolean [params.side]: BUY or SELL
        :param str [params.type]: "LIMIT", "MARKET","STOP_LIMIT", "STOP_MARKET", "TAKE_PROFIT_LIMIT","TAKE_PROFIT_MARKET"
        :param str [params.orderType]: "ACTIVE","CONDITION","HISTORY"
        :param boolean [params.page]: Page numbers start from 0
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr&   r`  r  r   r  r  r   r  )	r  r^  r  r_  privateGetV3HistoryOrdersr  r   r?  r  r   r`  r  r   r  r  r^  r  r  r   r  s              r   fetch_orderszapex.fetch_orders(  s    $ !!![[(F &tGH,1G()$GG..v7_`'*:G&'YYv'OPF77GV8TUU~~h3h3  >># 	" V"   CCBCC?CCc                 t  K   | j                          d{    i }| j                  |dd      }|||d<   n||d<   | j                  |ddg      }| j                  | j	                  ||             d{   }| j                  |di       }	| j                  |	dg       }
| j                  |
d||      S 7 7 @w)a-  
        fetch all the trades made from a single order

        https://api-docs.pro.apex.exchange/#privateapi-v3-for-omni-get-trade-history

        :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>`
        Nr  r  r  r   r  )r  safe_string_2r_  privateGetV3OrderFillsr  r   r?  r  )r   r&   r`  r  r   r  r  r  r  r   r  s              r   fetch_order_tradeszapex.fetch_order_tradesM  s      !!!**6?JO$'4GO$!#GI6OZ#@A44T[[&5QRR~~h3h3  ue<< 	" Ss"   B8B4AB85B66?B86B8c                   K   | j                          d{    i }d}|| j                  |      }|d   |d<   |||d<   |||d<   | j                  |g d      }|||d<   | j                  |g d      }| j	                  | j                  ||             d{   }| j                  |di       }	| j                  |	d	g       }
| j                  |
|||      S 7 7 @w)
a  
        fetches information on multiple orders made by the user *classic accounts only*

        https://api-docs.pro.apex.exchange/#privateapi-v3-for-omni-get-trade-history

        :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, default 100
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param dict [params.until]: end time
        :param boolean [params.side]: BUY or SELL
        :param str [params.orderType]: "LIMIT", "MARKET","STOP_LIMIT", "STOP_MARKET", "TAKE_PROFIT_LIMIT","TAKE_PROFIT_MARKET"
        :param boolean [params.page]: Page numbers start from 0
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        Nr&   r`  r  r   r  r  r   r  )	r  r^  r  r_  privateGetV3Fillsr  r   r?  r  r  s              r   fetch_my_tradeszapex.fetch_my_tradesg  s      !!![[(F &tGH,1G()$GG..v7_`'*:G&'YYv'OPF//GV0LMM~~h3h3  >># 	" Nr  c                   K   | j                          d{    i }d}|| j                  |      }|d   |d<   |||d<   |||d<   | j                  |g d      }|| j                  |g d      }||d<   | j	                  | j                  ||             d{   }| j                  |di       }	| j                  |	d	g       }
| j                  |
|||      S 7 7 @w)
a  
        fetches information on multiple orders made by the user *classic accounts only*

        https://api-docs.pro.apex.exchange/#privateapi-v3-for-omni-get-funding-rate

        :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, default 100
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param dict [params.until]: end time, ms
        :param boolean [params.side]: BUY or SELL
        :param boolean [params.page]: Page numbers start from 0
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=funding-history-structure>`
        Nr&   r`  r  r   r  r  r   fundingValues)	r  r^  r  r_  privateGetV3Fundingr  r   r?  parse_incomes)r   r`  r  r   r  r  r^  r  r  r   r  s              r   fetch_funding_historyzapex.fetch_funding_history  s     !!![[(F &tGH,1G()$GG..v7_`'YYv'OPF*:G&'11$++gv2NOO~~h3t_bA!!-FF# 	" Pr  c                 *   | j                  |d      }| j                  ||d d      }d}| j                  |d      }|| j                  ||      ||| j	                  |      | j                  |d      | j                  |d      | j                  |d      dS )	Nr`  ro  r  fundingTimer&   fundingValuer  )r  r`  r  r  r  r&   r<  r  )r  r  r   r  r  rE  )r   incomer^  r  r  r  s         r   parse_incomezapex.parse_income  s     ##FH5!!(FD*E%%fm<	&&x8"Y/""640&&v~>$$VV4	
 		
r   r   c                 t  K   |t        | j                  dz         | j                          d{    | j                  |      }| j	                  |      }t        j                  d|d      }|d   |d}| j                  | j                  ||             d{   }| j                  |di       }	|	S 7 7 w)a  
        set the level of leverage for a market

        https://api-docs.pro.apex.exchange/#privateapi-v3-for-omni-post-sets-the-initial-margin-rate-of-a-contract

        :param float leverage: the rate of leverage
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: response from the exchange
        Nz) setLeverage() requires a symbol argumentr      r&   )r`  initialMarginRater   )
r   r&   r  r^  number_to_stringr!   
string_div!privatePostV3SetInitialMarginRater  r   )
r   r   r`  r  r^  leverageStringr  r  r  r   s
             r   set_leveragezapex.set_leverage  s      >#DGG.Y$YZZ!!!V$..x8#..sNAFTl!2
 ??GU[@\]]~~h3 	" ^s"   .B8B4A)B8B6B86B8c                    K   | j                          d{    | j                  |       d{   }| j                  |di       }| j                  |dg       }| j	                  ||      S 7 U7 >w)a  
        fetch all open positions

        https://api-docs.pro.apex.exchange/#privateapi-v3-for-omni-get-retrieve-user-account-data

        :param str[] [symbols]: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        Nr   	positions)r  r!  r   r?  parse_positions)r   r  r  r  r   r  s         r   fetch_positionszapex.fetch_positions  sm      !!!11&99~~h3NN4b9	##Iw77	 	"9s   A0A,A0A.=A0.A0positionc           
      x   | j                  |d      }| j                  ||      }|d   }| j                  |d      }| j                  |d      }| j                  |d      }d}| j	                  |ddgd      }	| j                  |	      d	k7  r&| j                  t        j                  d
|	d            }| j                  i d|d| j                  |d      d|d| j                  |d      dd dd dd dd d|d| j                  |      dd d|d| j                  |      dd dd dd dd d |d d d d d      S )Nr`  r  r  r  r-   customInitialMarginRate	customImrr  r   r   r  r  r&   
entryPricer  notional
collateralunrealizedPnl	contractsrx  r  r  r   maintenanceMarginmaintenanceMarginPercentageinitialMargin)initialMarginPercentager   liquidationPricemarginRatior   r  )r  r  r  r   r  precision_from_stringr  r!   r  safe_positionr   r  )
r   r  r^  r  r`  r  quantityr  r   r  s
             r   parse_positionzapex.parse_position  s     ##Hh7!!(F3!%%h7##Hf5%%h>	"&"4"4X@Y[f?gil"m%%&=>!C((););CAXZ[)\]H!! #
H#
$""8T2#
 f#
 $**8\B	#

 #
 #
 $#
 T#
 D#
 **84#
 D#
 #
 Y/#
 d#
  #
  *4!#
" T##
$ (,  $/#
  	r   r   GETc                    | j                  | j                  d   |         dz   |z   }dddd}d|z   }|}	|j                         dk7  r1|rQ|d	| j                  |      z   z  }|d	| j                  |      z   z  }n"| j	                  |      }
| j                  |
      }	|d
k(  r| j                          t        | j                               }||j                         z   |z   }|	||	z   }| j                  | j                  |      | j                  | j                  | j                              t        j                  d      }||d<   | j                  |d<   ||d<   | j                  |d<   |||	|dS )Nr   re  z	apex-CCXTzapplication/jsonz!application/x-www-form-urlencoded)z
User-AgentAcceptzContent-Typez/api/POST?r   base64zAPEX-SIGNATUREzAPEX-API-KEYzAPEX-TIMESTAMPzAPEX-PASSPHRASE)urlmethodbodyheaders)implode_hostnamer   r@  	rawencodekeysortcheck_required_credentialsr<  r  hmacencodestring_to_base64r   hashlibsha256r   r   )r   pathr   r  r  r  r  r  signPathsignBodysortedQueryr  messageStringrW  s                 r   signz	apex.sign'  s|   ##DIIe$4S$9:S@4G%(?

 T><<>V#C$.."888sT^^F333,,v.K~~k2H)++-D--/0I%6AM# - 8		$++m"<dkk$J_J_`d`k`kJl>movo}o}  @H  II(1G$%&*kkGN#(1G$%)-G%&fh7SSr   reasonr  r  r  r  c
                 2   |y | j                  |d      }
|
|
dk7  r{| j                  dz   |z   }| j                  |dd      }| j                  | j                  d   ||       t        |      }| j                  | j                  d   ||       t        |      y )Nr  r    keymsgr   r   )r   r&   r  throw_broadly_matched_exceptionr   r<  throw_exactly_matched_exceptionr   )r   r  r  r  r  r  r  r  requestHeadersrequestBody	errorCodefeedbackmessager  s                 r   handle_errorszapex.handle_errorsD  s    
 %%h7	 Y!^ww}t+H((5%@G001I7T\]YF001I6S[\))r   )N)NNNN)L__name__
__module____qualname__r   r   r  r   r  r  dictr   r  r"  r   rX  r   r   r]  r  r   r  r<  r  r   r   r  r
   rG  r  r  r   r  r   r  r  r  r  r   r  r   r  r  r  r  r   r  r>  r4  rG  rJ  r   r   floatr   rl  r   r   r	   r  r  r  r  r  r  r  r  r  r  r  r   r  r  r  rb  r	  __classcell__)r   s   @r   r#   r#      s    X# Xt ') /&) )8 *, ( (
T 
g 
 *, ( ( -/ k: kZ *, C5V C5J@4 @F @D44 4 46 4l 68 4 4F 4( 6:" 47 4 4 8<$]ajl J JC JWZ Jquvzq{ J>
 
4 
. @DB 2S 2 2S\ 2h <@d[] ,? ,?S ,? ,?bfglbm ,?\$ $v $ $L =? ; ;(F @ >BPTcgpr <Os <O# <O]` <O|b bv b bHAs A 	9S 	9VC V VRU Vjm V  zI V i iS ) mqy{ O. O.I O.Y O.X] O.fi O.b ac {3 { {C {TW {gt {z
t 
x 
= 
" 59 c ( 9=R S # 0 8<B &C & &6 59tZ^gi =c = =TW =nrsxny =" 04$UYbd #? #?C #?s #?imnsit #?J ?CQUdhqs =3 = =3 =^a =4 37TX\eg !?C !?s !?RU !?F 9=4^bkm  G#  GS  GX[  GD
6 
< ?C2 3  2 8<B 8W 84PX> 8 2t 2V 2h &eBSW T:# s  c TX `c r   r#   )) ccxt.async_support.base.exchanger   ccxt.abstract.apexr   r  rc  ccxt.base.typesr   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   ccxt.base.decimal_to_precisionr   r    ccxt.base.preciser!   r#    r   r   <module>r     sb    6 *   S  S  S  S  S  S  * . ' ) . 3 4 %}8[ }r   