
    ei)J                       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(dS )    )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dUd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dee         f
dZdUd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!dUde	dede fdZ"i fdefdZ#dUdefdZ$dddi fde%dedefd Z&dUd!e	dede'fd"Z(d#e%fd$Z)d%e%fd&Z*d'e%fd(Z+dVd)e%ded*e%d+e%de,f
 fd,Z-d-efd.Z.defd/Z/d0 Z0d1 Z1di fded'e2d2e3d3e4d4e5f
d5Z6i fd6ed3e4d7ed8ede7f
d9Z8dUd:e	d;e9de7fd<Z:di fde%de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dAZ>dddi fde%dededee'         fdBZ?dddi fd>ede%dedefdCZ@dddi fde%dedefdDZAdddi fde%dedefdEZBdUdefdFZCdi fdGeDde%fdHZEdi fdedeeF         fdIZGdUdJe	defdKZHdLdMi ddfdNZId6eDdOedPedQedRe	dSefdTZJ xZKS )Wapexreturnc                 &   |                      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i deddfddgddhddiddjddkddlddmddnddoddpddqddrddsddtddudvdwdxdydzd{d|d}d~ddddddddddddddddddddddddddddddidddddddddddddddddddddddddt          idddt
          dt          t          t          dddd|                     d          |                     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borrowMargincancelAllOrderscancelAllOrdersAftercancelOrdercancelOrderscancelOrdersForSymbolscloseAllPositionsclosePositioncreateMarketBuyOrderWithCostcreateMarketOrderWithCostcreateMarketSellOrderWithCostcreateOrdercreateOrderscreatePostOnlyOrdercreateReduceOnlyOrdercreateStopOrdercreateTriggerOrder	editOrderfetchAccountsfetchAllGreeksfetchBalancefetchBorrowInterestfetchBorrowRatefetchBorrowRateHistoriesfetchBorrowRateHistoryfetchBorrowRatesfetchBorrowRatesPerSymbolfetchCanceledAndClosedOrdersfetchCanceledOrdersfetchClosedOrdersfetchCrossBorrowRatefetchCrossBorrowRatesfetchCurrenciesfetchDepositAddressfetchDepositAddressesfetchDepositsfetchDepositWithdrawFeefetchDepositWithdrawFeesfetchFundingHistoryfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchGreeksfetchIndexOHLCVfetchIsolatedBorrowRatefetchIsolatedBorrowRatesfetchLedgerfetchLeveragefetchLeverageTiersfetchLiquidationsfetchMarginModefetchMarketLeverageTiersfetchMarketsfetchMarkOHLCVfetchMyLiquidationsfetchMyTrades
fetchOHLCVfetchOpenInterestfetchOpenInterestHistoryfetchOpenInterestsfetchOpenOrdersfetchOptionfetchOptionChain
fetchOrderfetchOrderBookfetchOrdersfetchOrderTradesfetchPositionfetchPositionModefetchPositionsfetchPositionsRiskfetchPremiumIndexOHLCVfetchTickerfetchTickers	fetchTimefetchTradesfetchTradingFeefetchTradingFeesfetchTransferfetchTransfersfetchVolatilityHistory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   rF   rG   rr   rz   rw   r|   rX   rs   extendsdefault)linearinverse)r   r5   )precisionModecommonCurrenciesoptionsfeatures)	deep_extendsuperr#   describer   r   r   parse_numberr    )self	__class__s    U/var/www/html/volatility/venv/lib/python3.11/site-packages/ccxt/async_support/apex.pyr   zapex.describe   s	   dD 1 1 : : < < `?
&`?
F`?
 `?
 t	`?

 `?
 `?
 4`?
 4`?
  fff %f 	f
 %f %f Uf $Uf 'f f "4f 'f tf f )%f  $U!f"  #f f$ /%f& ,U'f( 0)f* t+f, -f. &t/f0 (1f2 "43f4 %d5f6 U7f8  9f: !%;f< =f> &u?f@ "5AfB +ECfD )%Ef f fF #EGfH ,UIfJ /KfL &uMfN $UOfP 'QfR (SfT "4UfV &uWfX (YfZ  [f\ *5]f^ +E_f` &tafb #Ecfd *4eff $Ugf f fh uifj "5kfl *5mfn +Eofp uqfr  sft %eufv $Uwfx "5yfz +E{f| }f~ !%f@ &uAfB  CfD dEfF $TGfH +EIf f fJ %eKfL "4MfN uOfP #EQfR dSfT !$UfV tWfX #DYfZ  [f\ $U]f^ !$_f` %eafb )%cfd teff gfh Tifj tkf f fl "5mfn #Eofp  qfr !$sft )%ufv "5wfx #Eyfz {f| #E}f~ &uf@ 4AfB tCfD  EfF "5GfH EIfJ EKf f`?
`  a`?
| ,}`?
~ i67 
 GG  0;z> `?
\ &'./%&%&%&$%#$34	 	 '(./$%*+$%-.78&'-.*+()'(  2356+,$%67+,45  & &]`?
j (k`?
p  11'  6BAMIU  q`?
R !..x88!..x88 S`?
^ "!&# $ $_`?
l ' "%#'"   $&+(,,0,1).+06:#'#'"&#'	( ( #(/4$($)+027#()$ $, %)&+!$$*%+*/& & ',#($)*/	# # ',!%#($)*/( ( ',!$$*%+#($)*/$ $ *.#o: :z "9  $	 yB B{`?
 `?
 `?
 ` ` `	    c                    K   |                      |           d{V }|                     |di           }|                     |d          S )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_time;  sZ       --f55555555~~h33   v...r  c                     |                                  }|||                     |          d}d}|                                 }|                     |d          |d<   |                     |d          |d<   |||<   |                     |          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_balanceN  s     %%''	"Y//
 

 ,,..**85GHH++H6HIIt  (((r  c                    K   |                                   d{V  |                     |           d{V }|                     |di           }|                     |          S )a?  
        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_balancej  sz       !!!!!!!!!88@@@@@@@@~~h33!!$'''r  r  c                 >    |                      |dd          }|d d |dS )Nr&   0)r&   typer  r  r  )r   r  	accountIds      r  parse_accountzapex.parse_accountx  s4    $$WdC88		
 
 	
r  c                    K   |                                   d{V  |                     |           d{V }|                     |di           }|                     |          S )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_account  sz       !!!!!!!!!11&99999999~~h33!!$'''r  c                   K   |                      |           d{V }|                     |di           }|                     |di           }|                     |di           }|                     |dg           }|                     |dg           }i }t          dt	          |                    D ]%}	||	         }
|                     |
d          }|                     |          }|                     |
d	          }i }t          dt	          |                    D ]J}||         }|                     |d
g           }t          dt	          |                    D ]	}||         }|                     |d          }||k    r|                     |d          }|                     |          }|||d|                     |d           |                     |d          | 	                    |d          | 
                    |                     |                     |d                              | 	                    |d          dd| 	                    |d          dddd	||<   Lt          |                                          }t	          |          }|dk    }|rdnd}|                     |
||d|d||dddddddddddd|d          ||<   '|S )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activer=  r   fee	precisionlimitsFcrypto)amountr   r=  )r  r  r&   r$  r'   r?  r=  r   r@  rA  rB  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'   rE  jchainr2  fr0  	tokenName	networkIdnetworkCodenetworkKeysnetworksLengthemptyChainsvalueForEmptys                              r  fetch_currencieszapex.fetch_currencies  s_      0088888888~~h33^^D,;;
^^JbAA
t ~~j(B77
Hb99q#d))$$ A	 A	AAwH))(G<<J**:66D##Hm<<DH1c&kk**  q	x<<q#f++..  A"1IE $ 0 0 @ @I J..$($4$4UI$F$F	&*&=&=i&H&H$)"+'2&*+/>>%AQ+R+R'R(,u>N(O(O#'#3#3E8#D#D)-):):4;O;OPTP`P`afhrPsPs;t;t)u)u ,0+;+;E=+Q+Q+/-" -"
 ,0+;+;E<+P+P+/," ,"	' 	'1 1-4 x}}//K --N(A-K%0:EEdM77   ()!  $# 
  $#! !
  $#     %39 9  F4LL6 r  c                    K   |                      |           d{V }|                     |di           }|                     |di           }|                     |dg           }|                     |          S )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)rF  r  rG  parse_markets)r   r
  r  r  rb  rc  s         r  fetch_marketszapex.fetch_markets<  s       0088888888~~h33.>CC NN>;NPRSSn !!"3444r  marketc                 0   |                      |d          }|                      |d          }|                      |d          }|                      |d          }|                      |d          }|                     |          }|                      |d          }|                     |          }	|dz   |z   dz   |	z   }
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k    rd n||dk    rd n|                     |          d d |                     |d          |                     |d           d!|                     |d"          |                     |d#          d$|                     |d          |                     |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   r?  enableTradecontractminOrderSizestepSizetickSize)rD  pricedisplayMinLeveragedisplayMaxLeverager9  maxOrderSize)r   rD  r{  cost)r   r   r   r   contractSizeexpiryexpiryDatetimestrike
optionTyperA  rB  createdr  )r  rJ  r   safe_market_structurerL  rM  r  )r   rf  r&   ro  rt  rs  rq  rp  ru  rr  rh  r  takerFeemakerFees                 r  parse_marketzapex.parse_market  s
   fh//v'899""6:66!!&-88  99&&v..##FO<<((2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%{{dd'-{{ddf9M9M**6:>>))&*==   ++F4HII++F4HII 
  ++FNCC++FNCC 
   
    $ e3+
 3+
 3+
 3 3 3	r  Ntickerc           
         |                                  }|                     |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|          S )Nrh  	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  rf  r  marketIdrh  r  r  r  r  r  r  s               r  parse_tickerzapex.parse_ticker  s   & %%''	##FH55!!(F33!!(F3344%%fn==
&&v}==%%fk::
77v}55 !
f!
!
 Y//!
 D	!

 3!
 4!
 !
 4!
 !
 D!
 D!
 T!
 D!
 T!
 d!
  *!!
" t#!
$ %&))&+>>**6<@@-!
 !
 !
. /  	r  rh  c                 ^  K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     |dg           }|                     |di           }|                     ||          S )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>`
        Nrh  ro  r  r   )r  rf  publicGetV3TickerextendrG  r  r  r   rh  r
  rf  requestr  tickers	rawTickers           r  fetch_tickerzapex.fetch_ticker  s       !!!!!!!!!V$$fUm
 //GV0L0LMMMMMMMM..6266NN7Ar22	  F333r  symbolsc                    K   |                                   d{V  |                     |           d{V }|                     |dg           }|                     ||          S )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  publicGetV3DataAllTickerInforG  parse_tickers)r   r  r
  r  r  s        r  fetch_tickerszapex.fetch_tickers  s|       !!!!!!!!!::6BBBBBBBB..6266!!'7333r  r   	timeframesincer   c                 @  K   |                                   d{V  |                     |          }|                     | j        ||          |d         d}|d}||d<   |                     d||d          \  }}|'t          t          j        |dz                      |d	<   |                     | 	                    ||                     d{V }| 
                    |d
i           }	|                     |	|d         g           }
|                     |
||||          S )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
        Nro  )intervalrh  r   r   endgMbP?  startr  )r  rf  r  r   handle_until_optionintmathfloorpublicGetV3Klinesr  r  rG  parse_ohlcvs)r   rh  r  r  r   r
  rf  r  r  r  OHLCVss              r  fetch_ohlcvzapex.fetch_ohlcv  s=      !!!!!!!!!V$$(()YOOUm
 
 =E 225'65QQ"4:edl#;#;<<GG//GV0L0LMMMMMMMM~~h33fUmR88  E5IIIr  c           
         |                      |ddg          |                     |ddg          |                     |ddg          |                     |ddg          |                     |d	d
g          |                     |ddg          gS )Nr  tr  or  hr  lr  cvolumev)safe_integer_nsafe_number_n)r   ohlcvrf  s      r  parse_ohlcvzapex.parse_ohlcv;  s     ~66uvsm44uvsm44uucl33uwn55uxo66
 	
r  c                   K   |                                   d{V  |                     |          }d|d         i}|d}||d<   |                     |                     ||                     d{V }|                     |di           }|                                 }|                     ||d         |dd          }	|                     |d	          |	d
<   |	S )aI  
        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
        Nrh  ro  r   r   r  baunonce)r  rf  publicGetV3Depthr  r  r  parse_order_bookr  )
r   rh  r   r
  rf  r  r  r  r  	orderbooks
             r  fetch_order_bookzapex.fetch_order_bookR  s       !!!!!!!!!V$$fUm
 =E ..t{{7F/K/KLLLLLLLL6 ~~h33%%''	))$x0@)SRUVV	!..tS99	'r  c                 F  K   |                                   d{V  |                     |          }d|d         i}|d}||d<   |                     |                     ||                     d{V }|                     |dg           }|                     ||||          S )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>`
        Nrh  ro  r   r   r  )r  rf  publicGetV3Tradesr  rG  parse_trades)	r   rh  r  r   r
  rf  r  r  tradess	            r  fetch_tradeszapex.fetch_trades  s       !!!!!!!!!V$$fUm
 =E //GV0L0LMMMMMMMM* &"55  >>>r  tradec                 $   |                      |ddg          }|                     ||          }|                      |ddg          }|                     |g d          }|                      |ddg          }|                      |dd	g          }|                     |d
dg          }|                      |dg          }	|                      |dg          }
|                     ||d ||                     |          |d         |	d |||d |
d|          S )Nsrh  rS  r&   )r  T	createdAtpr{  r  sizeSsider$  r@  )r  r&   orderr  r  rh  r$  takerOrMakerr  r{  rD  r  r@  )safe_string_nr  r  safe_string_lower_n
safe_trader  )r   r  rf  r  r&   r  priceStringamountStringr  r$  r@  s              r  parse_tradezapex.parse_trade  s=    %%ec8_==!!(F33T{33''/F/F/FGG	((g??))%#v??''V}==!!%&22  00"Y//X&  " 
  
   	r  c                 ^  K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     |dg           }|                     |di           }|                     ||          S )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:
        Nrh  ro  r  r   )r  rf  r  r  rG  r  parse_open_interestr  s           r  fetch_open_interestzapex.fetch_open_interest  s       !!!!!!!!!V$$fUm
 //GV0L0LMMMMMMMM..6266NN7Ar22	''	6:::r  c           	      6   |                                  }|                     |d          }|                     ||          }|                     ||          }|                     ||                     |d          d ||                     |          |d|          S )Nrh  openInterest)rh  openInterestAmountopenInterestValuer  r  r  )r  r  r  r  safe_open_interestr  )r   interestrf  r  r  rh  s         r  r  zapex.parse_open_interest  s    & %%''	##Hh77!!(F33!!(F33&&"&"2"28^"L"L!%"Y//(
 (
   	r  c           
        K   |t          | j        dz             |                                  d{V  i }|                     |          }|d         |d<   |||d<   |||d<   |                     |d          }|||d<   |                     |g d          }|||d	<   |                     |                     ||                     d{V }	g }
|                     |	d
i           }| 	                    |dg           }t          dt          |                    D ]}||         }|                     |d          }|                     |d          }|
                    ||                     ||          |                     |d          ||                     |          d           |                     |
d          }|                     ||||          S )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&   rh  beginTimeInclusiver   pageendTimeendTimeExclusiveuntilr  r  historyFundsr   fundingTimestamprate)r  rh  fundingRater  r  r  )r   r&   r  rf  r  r  publicGetV3HistoryFundingr  r  rG  rH  rI  r  appendr  rM  r  sort_byfilter_by_symbol_since_limit)r   rh  r  r   r
  r  rf  r  r  r  ratesr  
resultListrS  entryr  r  sorteds                     r  fetch_funding_rate_historyzapex.fetch_funding_rate_history  s$      >#DG.e$efff!!!!!!!!!V$$"4L,1G()$GG  00"GFO..v7_7_7_``'*:G&'77GV8T8TUUUUUUUU ~~h33^^D."==
q#j//** 
	 
	AqME))%1CDDI''x88HLL**8V<<#//v>>& LL33      e[1100NNNr  r  c                 b   |                      |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|          S )Nr  r&   clientIdrh  r{  r  r$  statusr  remainingSizeupdatedTimeclientOrderIdr  r  lastTradeTimestamplastUpdateTimestampr   postOnly
reduceOnlyr   r   r   r@  ru  )r  rT  )r  rD  filled	remainingr  r  r@  r  )r  r  r  safe_string_lower	omit_zero
safe_orderr  parse_order_statusparse_order_typeparse_time_in_forcerL  )r   r  rf  r  orderIdr  r  rh  r{  rD  	orderTyper  r  r  r  s                  r  parse_orderzapex.parse_orderL  s   n %%e[99	""5$//((
;;##E844!!(F33!  00!!%00$$UF33	!!%22%%eV44NN4#3#3E?#K#KLL	"//}EE  
' 
] 
  
 Y//	 

 !$ 
 "#6 
 d--f55 
 f 
 D)))44 
 433D4D4DUM4Z4Z[[ 
 uj99 
 $..== 
 D 
 U 
 D,,UNCC 
  t! 
" T# 
$ "((66":.  9 
  
  
: ;  	r  r   c                 >    ddddd}|                      ||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  s4    0*#8$	
 
 k4@@@r  r  c                 J    | ddddddd}|                      |||          S |S )Nr  r  canceled)PENDINGOPENFILLED	CANCELINGCANCELEDUNTRIGGEREDr%  )r   r  statusess      r  r  zapex.parse_order_status  sE    !"'&% H ##Hff===r  r$  c                 B    ddddddd}|                      |||          S )Nr   rf  )LIMITMARKET
STOP_LIMITSTOP_MARKETTAKE_PROFIT_LIMITTAKE_PROFIT_MARKETr%  )r   r$  typess      r  r  zapex.parse_order_type  s:    !#!("*
 
 tT222r  r  	delimiter
marketTypec                    |||| j         v r| j         |         }n|| j        v r| j        |         }np|                     |          }|| j        v rR| j        |         }t          |          }|dk    r0| j        |         d         d         |k    r| j        |         d         }t	          t
          |                               ||||          S )Nr   ro  )marketsmarkets_by_idadd_hyphen_before_usdtrI  r   r#   r  )	r   r  rf  r9  r:  newMarketIdr<  
numMarketsr   s	           r  r  zapex.safe_market  s    >h24<''h/T///+H5"99(CC$"444"0=G!$WJ!A~~-k:1=eDPP%)%7%DQ%GFT4  ,,Xvy*UUUr  
_accountIdc                     |p!t          |                     d                    }d|z   dz   t          |                                           z   dz   t          |                     d                    z   S )N   z	apexomni--   )strrand_numberr  )r   rA  r&  s      r  generate_random_client_id_omniz#apex.generate_random_client_id_omni  sn    ;#d&6&6r&:&:";";	Y&,s43D3D3F3F/G/GG#MPSTXTdTdefTgTgPhPhhhr  c                     |                                 }|                    d          }|                     ||dz
            }|dk    r|dk    r|d|         dz   ||d          z   S |S )Nr  r   r   rD  )upperfindr  )r   rh  uppercaseSymbolindex
symbolChars        r  r>  zapex.add_hyphen_before_usdt  ss     ,,..$$V,,%%feai88
199s**!E'?S(6%&&>99r  c                 n    |                      | 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   rP  s     r  	get_seedszapex.get_seeds  sH      w77=#DG  /O  %O  P  P  Pr  c                    K   |                      | j        dd          }|dk    r9|                                  d {V }|                      |dd          | j        d<   | j        d         S )Nr&  r#  r&   )r  r   r*  )r   r&  accountDatas      r  get_account_idzapex.get_account_id  sx      $$T\;DD	 $ 2 2 4 4444444K(,(8(8dC(P(PDL%|K((r  r  rD  r{  c                   K   |                                   d{V  |                     |          }|                                }|                                }	|                     ||          }
d}||                     ||          }|                     | j        di           }|                     |dd          }|                     |dd          }|                     t          j
        t          j        t          j        ||
          |          |                     |d         d	                             t          |d         d	         | j        | j                  }|                                 }|                     |d
          }|                     |d          }|                     |d          }||dk    rdnd}|}n||dk    rdnd}|}|dk    }|r|t#          | j        dz             |                     |d          }|                     |d|          }|d}|s|rd}n|dk    rd}|                     |d          }|                     |d          }|                     |g d          }|                                  d{V }||                     |          }|                     |g d          }||||d         |
||	||d	}||                     ||          |d
<   |                     |                     |                                           |           d{V }|d         |	||
||t9          t;          j        |dz  dz                       |||                     | j        d d!          d"
}||                     ||          |d
<   ||d#<   |                      | !                    ||                     d{V }|                     |d$i           }| "                    ||          S )%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 float [params.stopLossPrice]: The price a stop loss order is triggered at
        :param float [params.takeProfitPrice]: The price a take profit 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   r   r   r   rA  r{  r   r   r   r3  r5  r4  r7  r6  z: createOrder() requires a price argument for market ordersr   r#  r&  iocr%  r  r  r  client_order_id)r  r  rX  r   r   r   rt  )	r&  slotIdr  pairIdr  r{  	directionmakerFeeRatetakerFeeRater&   r  i ' r   r   )
rh  r  r$  r  r{  limitFee
expirationr   r  r   	signaturer  )#r  rf  rJ  amount_to_precisionprice_to_precisionr  r   r  decimal_to_precisionr!   
string_add
string_mulnumber_to_stringr   r   paddingModer  r   r&   safe_string_upperis_post_onlyomitr  rT  rH  get_zk_contract_signature_objremove0x_prefixrQ  r  r  r  r   privatePostV3Orderr  r!  )r   rh  r$  r  rD  r{  r
  rf  r   	orderSide	orderSize
orderPricer   r   r   r^  timeNowr   r   r   isMarketr   r  r  r&  orderToSignr`  r  r  r  s                                 r  create_orderzapex.create_order  s     * !!!!!!!!!V$$JJLL	JJLL	,,VV<<	
00??J~~di44  w99  w99,,W-?@RSZSefpr{S|S|  D  AE  AE  GK  G\  G\  ]c  do  ]p  qx  ]y  Gz  Gz  .{  .{  }E  GM  NY  GZ  [b  Gc  ei  ew  y}  yI  J  J##%%''??((AA**63DEE$*3x*?*?lI(LL(1:h1F1F,,M`I*L( 	l#DG.j$jkkk,,V]CC$$XtV<<+K 	4 4)%%36=116:..**63c3c3cdd--////////	  ??	JJM6  $H  $H  $H  I  I"#"Y'"!!

 

 #*.*A*A&,*W*WK'<<T=Q=QRVR`R`RbRb=c=cepqqqqqqqq	Tl dj4:K)KLLMM&%((z6JJ
 
 #&*&=&=fl&S&SGN#(00Wf1M1MNNNNNNNN~~h33f---r  r  fromAccount	toAccountc                   K   |                                   d{V  |                     |           d{V }|                     |di           }|                     |di           }|                     |dg           }	|                     |di           }
|                     |
dg           }|                     |
di           }|                     |dd          }|                     |d	d          }|                     |d
d          }|                     |dd          }|                     |           d{V }|                     |di           }|                     |di           }|                     |dd          }|                     |dd          }|                     |dg           }d}t          |          dk    r|                     |d         dd          }|                     |dd          }|                     |dd          }i }g }||                                dk    r|	}n|}t          dt          |                    D ]+}|                     ||         dd          |k    r||         },|                     |dd          }| 	                    |t          j        d|                     |dd                    z            }| 	                    |                                 dz            }|                     |g d          } | .|                     |                     | j        d                    } |                     |g d          }|\|                                dk    rCd}!t%          j        ||!          }"|dz   }#|"||||t)          |          d| |#dd 
}$|                     |                     |                                           |$           d{V }%||#| |%||d!}&|                     |                     |&|                     d{V }'|                     |'di           }(|                                 })|                     |                     |(|                     |                    |)|                     |)          |                     |          dd"d#          S |||||t)          |          d||d$	}$|                     |                     |                                           |$           d{V }%t)          |          || |%||d|||||||d%}&|                     |                     |&|                     d{V }'|                     |'di           }(|                                 })|                     |                     |(|                     |                    |)|                     |)          |                     |          d"dd#          S )&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  rb  r.  r,  globalcontractAssetPoolEthAddress contractAssetPoolZkAccountIdcontractAssetPoolSubAccountcontractAssetPoolAccountIdspotAccountzkAccountIddefaultSubAccountIdr#  subAccountsr   r  ethereumAddressr&   rw  r0  tokenId
   r7  r  rW  r&  
4294967295i $ T)
r  receiverAddresssubAccountIdreceiverSubAccountIdr  rD  r@  r  timestampSeconds
isContract)rD  
expireTimeclientWithdrawIdr`  r0  
ethAddressr3   )r  r  rD  ru  rv  )	r  r  r  r  r  rD  r@  r  r  )rD  r  clientTransferIdr`  r  r  r@  r0  r  receiverAccountIdreceiverZkAccountIdr  r  r  )r  rF  r  rG  r  r)  rI  lowerrH  parse_to_intr  powrM  r  r  rH  r   rj  r!   
string_modrF  get_zk_transfer_signature_objrl  rQ   privatePostV3ContractTransferOutr  parse_transferrT  r  r   privatePostV3TransferOut)*r   r  rD  ru  rv  r
  configResponse
configDatarb  contractAssetsr,  
spotAssetsglobalConfigr  r  r  r  accountResponserS  r~  r  r  r  r  r  r&  rT  r.  rS  r  amountNumberr  r  formattedUint32zkSignAccountIdr  rs  r`  r  r  r  currentTimes*                                             r  r   zapex.transferY  s      !!!!!!!!!#66v>>>>>>>>^^NFB??

4DbII"EE^^JbAA
^^J"==
~~j(B??**<9VXZ[["..|=[]_``#//>[]_`` ,,\;WY[\\ $ 8 8 @ @@@@@@@nn_fbAAnn[-DD&&{M2FF''5JCPPnn[-DD{a$$[^WcBBE%%k3DbII
$$[$;;	"{'8'8':':j'H'H#FFFq#f++&& 	% 	%Aq	7B774??!!9""8Y;;((48B@P@PQY[egh@i@i3j3j)kll,,T->->-@-@4-GHH**63c3c3cdd  ??@P@PQUQ]_j@k@kllM6#S#S#STT"{'8'8':':j'H'H*O%0OLLO)N:J.#- ,(4"l++&$." K #@@AUAUVZVdVdVfVfAgAgituuuuuuuuI ($1&( G "BB4;;wX^C_C_````````H>>(FB77D++--K;;t224t9L9LMM( LL55++F33)#P P     +#2 ,(<"l++$4
 
K #@@AUAUVZVdVdVfVfAgAgituuuuuuuuIf++-$1&* ,"%6':(<#2 G  "::4;;wPV;W;WXXXXXXXXH>>(FB77D++--K;;t224t9L9LMM( LL55++F33%'P P   r  r   rT  c                    |                      |d          }|                     |d          }|                      |d          }|                      |d          }||                     |ddg          ||                     |          |                     ||          |                     |d          |||                      |d          d		S )
Ncoinr  ru  rv  
transferIdr&   rD  r  )	r  r&   r  r  rT  rD  ru  rv  r  )r  r  r  r  rJ  rM  )r   r   rT  rU  r  ru  rv  s          r  r  zapex.parse_transfer  s    %%h77
%%h<<	&&x??$$X{;;	$$Xd/CDD"Y////
HEE&&x::&"&&x::

 

 
	
r  c                 @  K   |                                   d{V  d}i }| |                     |          }|d         |d<   |                     |                     ||                     d{V }|                     |di           }|                     ||          gS )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&   rh  r  )r  rf  privatePostV3DeleteOpenOrdersr  r  r!  )r   rh  r
  rf  r  r  r  s          r  cancel_all_orderszapex.cancel_all_orders  s       !!!!!!!!![[((F &tGH;;DKKQW<X<XYYYYYYYY~~h33  v..//r  r&   c                   K   i }|                      |g d          }d}|M||d<   |                     |g d          }|                     |                     ||                     d{V }n4||d<   |                     |                     ||                     d{V }|                     |di           }|                     |          S )aZ  
        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>`
        rW  Nr&   r  )r  rj   privatePostV3DeleteClientOrderIdr  privatePostV3DeleteOrderr  r  r   r&   rh  r
  r  r  r  r  s           r  cancel_orderzapex.cancel_order  s       **63c3c3cdd$)GDMYYv'W'W'WXXF!BB4;;wX^C_C_````````HHGDM!::4;;wPV;W;WXXXXXXXXH~~h33t$$$r  c                   K   |                                   d{V  i }|                     |g d          }d}|M||d<   |                     |g d          }|                     |                     ||                     d{V }n4||d<   |                     |                     ||                     d{V }|                     |di           }|                     |          S )aV  
        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>`
        NrW  r&   r  )r  r  rj   privateGetV3OrderByClientOrderIdr  privateGetV3Orderr  r!  r  s           r  fetch_orderzapex.fetch_order  s      !!!!!!!!!**63c3c3cdd$)GDMYYv'W'W'WXXF!BB4;;wX^C_C_````````HHGDM!33DKK4P4PQQQQQQQQH~~h33%%%r  c                    K   |                                   d{V  |                     |           d{V }|                     |dg           }|                     |d||          S )a@  
        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  privateGetV3OpenOrdersrG  parse_orders)r   rh  r  r   r
  r  orderss          r  fetch_open_orderszapex.fetch_open_orders.  s       !!!!!!!!!44V<<<<<<<<&"55  ue<<<r  c                   K   |                                   d{V  i }d}| |                     |          }|d         |d<   |||d<   |||d<   |                     |g d          }|||d<   |                     |g d          }|                     |                     ||                     d{V }|                     |di           }	|                     |	d	g           }
|                     |
|||          S )
a8  
        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&   rh  r  r   r  r  r  r  )	r  rf  r  rj  privateGetV3HistoryOrdersr  r  rG  r  r   rh  r  r   r
  r  rf  r  r  r  r  s              r  fetch_orderszapex.fetch_orders?  s;     $ !!!!!!!!![[((F &tGH,1G()$GG..v7_7_7_``'*:G&'YYv'O'O'OPPF77GV8T8TUUUUUUUU~~h33h33  >>>r  c                   K   |                                   d{V  i }|                     |dd          }|||d<   n||d<   |                     |ddg          }|                     |                     ||                     d{V }|                     |di           }	|                     |	dg           }
|                     |
d||          S )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_2rj  privateGetV3OrderFillsr  r  rG  r  )r   r&   rh  r  r   r
  r  r  r  r  r  s              r  fetch_order_tradeszapex.fetch_order_tradesd  s       !!!!!!!!!**6?JOO$'4GO$$!#GI6OZ#@AA44T[[&5Q5QRRRRRRRR~~h33h33  ue<<<r  c                   K   |                                   d{V  i }d}| |                     |          }|d         |d<   |||d<   |||d<   |                     |g d          }|||d<   |                     |g d          }|                     |                     ||                     d{V }|                     |di           }	|                     |	d	g           }
|                     |
|||          S )
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&   rh  r  r   r  r  r  r  )	r  rf  r  rj  privateGetV3Fillsr  r  rG  r  r  s              r  fetch_my_tradeszapex.fetch_my_trades~  s;       !!!!!!!!![[((F &tGH,1G()$GG..v7_7_7_``'*:G&'YYv'O'O'OPPF//GV0L0LMMMMMMMM~~h33h33  >>>r  c                   K   |                                   d{V  i }d}| |                     |          }|d         |d<   |||d<   |||d<   |                     |g d          }||                     |g d          }||d<   |                     |                     ||                     d{V }|                     |di           }	|                     |	d	g           }
|                     |
|||          S )
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&   rh  r  r   r  r  r  fundingValues)	r  rf  r  rj  privateGetV3Fundingr  r  rG  parse_incomes)r   rh  r  r   r
  r  rf  r  r  r  r  s              r  fetch_funding_historyzapex.fetch_funding_history  s;      !!!!!!!!![[((F &tGH,1G()$GG..v7_7_7_``'YYv'O'O'OPPF*:G&'11$++gv2N2NOOOOOOOO~~h33t_bAA!!-FFFr  c                 j   |                      |d          }|                     ||d d          }d}|                     |d          }||                     ||          |||                     |          |                      |d          |                     |d          |                     |d          dS )	Nrh  rw  r  fundingTimer&   fundingValuer  )r  rh  r  r  r  r&   rD  r  )r  r  r  r  r  rM  )r   incomerf  r  r  r  s         r  parse_incomezapex.parse_income  s     ##FH55!!(FD*EE%%fm<<	&&x88"Y//""6400&&v~>>$$VV44	
 	
 		
r  r   c                   K   |t          | j        dz             |                                  d{V  |                     |          }|                     |          }t          j        d|d          }|d         |d}|                     |                     ||                     d{V }| 	                    |di           }	|	S )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&   )rh  initialMarginRater  )
r   r&   r  rf  rf  r!   
string_div!privatePostV3SetInitialMarginRater  r  )
r   r   rh  r
  rf  leverageStringr  r  r  r  s
             r  set_leveragezapex.set_leverage  s       >#DG.Y$YZZZ!!!!!!!!!V$$..x88#.sNAFFTl!2
 
 ??GU[@\@\]]]]]]]]~~h33r  c                    K   |                                   d{V  |                     |           d{V }|                     |di           }|                     |dg           }|                     ||          S )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  rG  parse_positions)r   r  r
  r  r  r  s         r  fetch_positionszapex.fetch_positions  s       !!!!!!!!!11&99999999~~h33NN4b99	##Iw777r  positionc           
         |                      |d          }|                     ||          }|d         }|                     |d          }|                      |d          }|                     |d          }d}|                     |ddgd          }	|                     |	          d	k    r)|                     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d d |d d d d d          S )Nrh  r  r  r  r-   customInitialMarginRate	customImrr#  r   r   r  r  r&   
entryPricer  notional
collateralunrealizedPnl	contractsr  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  rf  r  rh  r  quantityr  r   r  s
             r  parse_positionzapex.parse_position
  s     ##Hh77!!(F33!%%h77##Hf55%%h>>	"&"4"4X@Y[f?gil"m"m%%&=>>!CC(();CAXZ[)\)\]]H!! #
H#
$""8T22#
 f#
 $**8\BB	#

 #
 #
 $#
 T#
 D#
 **844#
 D#
 #
 Y//#
 d#
  #
  *4!#
" T##
$ (,  $/#
 #
 #
   	r  r   GETc                 ,   |                      | j        d         |                   dz   |z   }dddd}d|z   }|}	|                                dk    r9|r6|d	|                     |          z   z  }|d	|                     |          z   z  }n*|                     |          }
|                     |
          }	|d
k    r|                                  t          |                                           }||                                z   |z   }|	||	z   }|                     | 	                    |          | 	                    | 
                    | j                            t          j        d          }||d<   | j        |d<   ||d<   | j        |d<   |||	|dS )Nr   rm  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   rJ  	rawencodekeysortcheck_required_credentialsrF  r  hmacencodestring_to_base64r   hashlibsha256r   r   )r   pathr   r  r
  r  r  r  signPathsignBodysortedQueryr  messageStringr`  s                 r  signz	apex.sign>  s   ##DIe$4S$9::S@4G%(?
 

 T><<>>V## 4C$.."8"888sT^^F3333,,v..K~~k22H)++---D--//00I%6AM# - 8		$++m"<"<dkk$J_J_`d`kJlJl>m>movo}  @H  I  II(1G$%&*kGN#(1G$%)-G%&fh7SSSr  reasonr  r  r  r  c
                 V   |d S |                      |d          }
|
|
dk    r| j        dz   |z   }|                     |dd          }|                     | j        d         ||           t          |          }|                     | j        d         ||           t          |          d S )Nr  r    keymsgr   r   )r  r&   r  throw_broadly_matched_exceptionr   rF  throw_exactly_matched_exceptionr   )r   r  r  r  r  r  r  r  requestHeadersrequestBody	errorCodefeedbackmessager  s                 r  handle_errorszapex.handle_errors[  s    
 4%%h77	 Y!^^w}t+H((5%@@G001I7T\]]]YYF001I6S[\\\)))tr  )N)NNNN)L__name__
__module____qualname__r   r   r  r   r  r!  dictr   r'  r*  r   r`  r   r   re  r  r   r  rF  r  r   r   r  r
   rO  r  r  r   r  r   r  r  r  r  r   r  r   r!  r  r  r  r   r  rH  r>  rQ  rT  r   r   floatr   rt  r   r   r	   r  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  __classcell__)r   s   @r  r#   r#      s       a# a a a a a aF	 ') / / / /&) ) ) ) )8 *, ( ( ( ( ( (
T 
g 
 
 
 
 *, ( ( ( ( ( ( -/ k k: k k k kZ *, C5 C5V C5 C5 C5 C5J@4 @F @ @ @ @D4 44 4 46 4 4 4 4l 68 4 4 4F 4 4 4 4( 6:" 4 47 4 4 4 4 4 ?CQUdhqs J J J J3 J^a Jx|  ~B  yC J J J J>
 
 
4 
 
 
 
. @DB 2 2S 2 2S\ 2 2 2 2h <@d[] ,? ,? ,?S ,? ,?bfglbm ,? ,? ,? ,?\$ $ $v $ $ $ $ $L =? ; ; ; ; ; ;( F    @ >BPTcgpr <O <Os <O# <O]` <O <O <O <O|b b bv b b b b bHAs A A A A    	3S 	3 	3 	3 	3V VC V VRU Vjm V  zI V V V V V V i i i i iS      ) ) ) mqy{ ]. ]. ].I ].Y ].X] ].fi ]. ]. ]. ].~ ac { {3 { {C {TW {gt { { { {z
 
t 
x 
= 
 
 
 
" 59 0 0c 0U 0 0 0 0( 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#  GS  GX[  G  G  G  GD
 
6 
 
 
 
< ?C2  3     2 8<B 8 8W 84PX> 8 8 8 8 2 2t 2V 2 2 2 2h &eBSW T T T T:# s  c TX `c        r  r#   )) ccxt.async_support.base.exchanger   ccxt.abstract.apexr   r  r  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     s'   6 5 5 5 5 5 * * * * * *   S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S       * * * * * * . . . . . . ' ' ' ' ' ' ) ) ) ) ) ) . . . . . . 3 3 3 3 3 3 4 4 4 4 4 4 % % % % % %T T T T T8[ T T T T Tr  