
    E#iiH                       S SK Jr  S SKJr  S SKrS SKrS SKJrJrJ	r	J
r
JrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJr  S SKJr  S SKJr  S SKJr  S SKJ r   S S	KJ!r!  S S
KJ"r"  S SK#J$r$  S SK#J%r%  S SK&J'r'   " S S\\5      r(g)    )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                     ^  \ rS rSrS\4U 4S jjr0 4S jrS\4S jr0 4S\4S jjr	S\
S\4S jr0 4S\4S	 jjr0 4S\4S
 jjr0 4S\\   4S jjrS\
S\4S jrSWS\
S\S\4S jjr0 4S\S\4S jjrS0 4S\S\4S jjrSSS0 4S\S\S\S\S\\   4
S jjrSWS\S\4S jjrS0 4S\S\S\4S jjr SS0 4S\S\S\S\\!   4S jjr"SWS\
S\S\!4S jjr#0 4S\4S jjr$SWS\4S  jjr%SSS0 4S\&S\S\4S! jjr'SWS"\
S\S\(4S# jjr)S$\&4S% jr*S&\&4S' jr+S(\&4S) jr,SXS*\&S\S+\&S,\&S\-4
U 4S- jjjr.S.\4S/ jr/S\4S0 jr0S1 r1S2 r2S0 4S\S(\3S3\4S4\5S5\64
S6 jjr70 4S7\S4\5S8\S9\S\84
S: jjr9SWS;\
S<\:S\84S= jjr;S0 4S\&S\\(   4S> jjr<S0 4S?\S\&4S@ jjr=S0 4S?\S\&4SA jjr>SSS0 4S\&S\S\S\\(   4SB jjr?SSS0 4S\&S\S\S\\(   4SC jjr@SSS0 4S?\S\&S\S\4SD jjrASSS0 4S\&S\S\4SE jjrBSSS0 4S\&S\S\4SF jjrCSWS\4SG jjrDS0 4SH\ES\&4SI jjrFS0 4S\S\\G   4SJ jjrHSWSK\
S\4SL jjrISMSN0 SS4SO jrJS7\ESP\SQ\SR\SS\
ST\4SU jrKSVrLU =rM$ )Yapex   returnc                   > U R                  [        [        U ]  5       0 SS_SS_S/ _SS_SS	_S
S_SS_SS_S0 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_0 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_S0S_S1S_E0 S2S_S3S_S4S_S5S_S6S_S7S_S8S_S9S_S:S_S;S_S<S_S=S_S>S_S?S_S@S_SAS_SBS_E0 SCS_SDS_SES_SFS_SGS_SHS_SIS_SJS_SKS_SLS_SMS_SNS_SOS_SPS_SQS_SRS_SSS_E0 STS_SUS_SVS_SWS_SXS_SYS_SZS_S[S_S\S_S]S_S^S_S_S_S`S_SaS_SbS_ScS_SdS_E0 SeS_SfS_SgS_ShS_SiS_SjS_SkS_SlS_SmS_SnS_SoS_SpS_SqS_SrS_SsS_StS_E_SuSvSwSxSySzS{S|S}S~SSSS._SS_SSSSS.SSS.SSSSS._SSSSSSSSSSS.0SSSSSSSSSSSSS.SSSSSSSS.S.S._SS[        0_SSS[
        S.[        [        [        S.S._SSU R                  S5      U R                  S5      S.0_SSSSSSS._[        0 SSSS.SSSS SSSS SSSSS.SSSSSSSS.S SSSSSS.SSSSS.SS SSSS.SSSSSSSS.S SS0S.	SS0S S.S.S.E5      $ )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   rG   rH   rs   r{   rx   r}   rY   rt   extendsdefault)linearinverse)r   r6   )precisionModecommonCurrenciesoptionsfeatures)	deep_extendsuperr#   describer   r   r   parse_numberr    )self	__class__s    C/home/james-whalen/.local/lib/python3.13/site-packages/ccxt/apex.pyr   apex.describe   s   dD : < `?
&`?
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& ,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 #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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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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`?
` a`?
| ,}`?
~ i67
 GG 0;z>`?
\ &'./%&%&%&$%#$34	 '(./$%*+$%-.78&'-.*+()'( 2356+,$%67+,45&]`?
j (k`?
p  11' 6BAMIUq`?
R !..x8!..x8S`?
^ "!&# $_`?
l ' "%#'"  $&+(,,0,1).+06:#'#'"&#'	( #(/4$($)+027#()$, %)&+!$$*%+*/& ',#($)*/	# ',!%#($)*/( ',!$$*%+#($)*/$ *.#o:z "9  $	yB{`?
 ` `	    c                 n    U R                  U5      nU R                  US0 5      nU R                  US5      $ )aA  
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
datatime)publicGetV3Time	safe_dictsafe_integerr   paramsresponser  s       r  
fetch_timeapex.fetch_time;  s;     ''/~~h3   v..r  c                     U R                  5       nUUU R                  U5      S.nSnU R                  5       nU R                  US5      US'   U R                  US5      US'   XSU'   U R	                  U5      $ )N)info	timestampdatetimeUSDTavailableBalancefreetotalEquityValuetotal)millisecondsiso8601accountsafe_stringsafe_balance)r   r  r  resultcoder  s         r  parse_balanceapex.parse_balanceN  s     %%'	"Y/

 ,,.**85GH++H6HIt  ((r  c                     U R                  5         U R                  U5      nU R                  US0 5      nU R                  U5      $ )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>`
r  )load_marketsprivateGetV3AccountBalancer	  r   r  s       r  fetch_balanceapex.fetch_balancej  sC     	226:~~h3!!$''r  r  c                 6    U R                  USS5      nUS S US.$ )Nr'   0)r'   typer  r  r  )r   r  	accountIds      r  parse_accountapex.parse_accountx  s,    $$WdC8		
 	
r  c                     U R                  5         U R                  U5      nU R                  US0 5      nU R                  U5      $ )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>`
r  )r#  privateGetV3Accountr	  r,  r  s       r  fetch_accountapex.fetch_account  sC     	++F3~~h3!!$''r  c                    U R                  U5      nU R                  US0 5      nU R                  US0 5      nU R                  US0 5      nU R                  US/ 5      nU R                  US/ 5      n0 n[        S[	        U5      5       GH  n	Xi   n
U R                  U
S5      nU R                  U5      nU R                  U
S5      n0 n[        S[	        U5      5       GH  nX   nU R                  US	/ 5      n[        S[	        U5      5       H  nUU   nU R                  US5      nUU:X  d  M"  U R                  US
5      nU R                  U5      nUUUSU R                  US5      (       + U R                  US5      U R                  US5      U R                  U R                  U R                  US5      5      5      U R                  US5      SS.U R                  US5      SS.S.S.	UU'   M     GM     [        UR                  5       5      n[	        U5      nUS:H  nU(       a  SOSnU R                  U
UUSUSUUSSSSS.SSS.SSS.S.US.5      X'   GM     U$ )a  
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
r  
spotConfig
multiChainassetschainsr   tokendisplayNametokenschainIdNdepositDisablewithdrawEnableminFeedecimalsminWithdrawminmax
minDeposit)r   deposit)	r  r'   networkactiverD  r   fee	precisionlimitsFcrypto)amountr   rD  )r  r  r'   r)  r(   rF  rD  r   rG  rH  rI  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  r3  r4  rowsr6  r  icurrency
currencyIdr  r(   rL  jchainr9  fr7  	tokenName	networkIdnetworkCodenetworkKeysnetworksLengthemptyChainsvalueForEmptys                              r  fetch_currenciesapex.fetch_currencies  s    **62~~h3^^D,;
^^JbA
t ~~j(B7
Hb9q#d)$AwH))(G<J**:6D##Hm<DH1c&k*	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 FLO %D r  c                     U R                  U5      nU R                  US0 5      nU R                  US0 5      nU R                  US/ 5      nU R                  U5      $ )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
r  contractConfigperpetualContract)rM  r	  rN  parse_markets)r   r  r  r  rj  rk  s         r  fetch_marketsapex.fetch_markets<  sc     **62~~h3.>C NN>;NPRSn !!"344r  marketc                    U R                  US5      nU R                  US5      nU R                  US5      nU R                  US5      nU R                  US5      nU R                  U5      nU R                  US5      nU R                  U5      n	US-   U-   S-   U	-   n
SnU R                  S	5      nU R                  S
5      nU R                  0 SU_SU_SU
_SU_SU_SU	_SU_SU_SU_SS_SS_SS _SS_SS_SS_SU R	                  US5      _SS_SSUUU R                  US5      US:X  a  S OUUS:X  a  S OU R                  U5      S S U R                  US5      U R                  US 5      S!.U R                  US"5      U R                  US#5      S$.U R                  US5      U R                  US%5      S$.S S S$.S S S$.S&.S US'.E5      $ )(NsymbolcrossSymbolNamel2PairIdbaseTokenIdsettleAssetId/:r   r   r   r'   id2basequotesettlebaseIdquoteIdsettleIdr)  r6   r4   Fr5   Tr7   r8   rF  enableTradecontractminOrderSizestepSizetickSize)rK  pricedisplayMinLeveragedisplayMaxLeverager@  maxOrderSize)r   rK  r  cost)r   r   r   r   contractSizeexpiryexpiryDatetimestrike
optionTyperH  rI  createdr  )r  rQ  r   safe_market_structurerS  rT  r  )r   ro  r'   rx  r}  r|  rz  ry  r~  r{  rq  r  takerFeemakerFees                 r  parse_marketapex.parse_market  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           
      Z   U R                  5       nU R                  US5      nU R                  XB5      nU R                  XB5      nU R                  US5      nU R                  US5      nU R                  US5      nU R                  US5      n	U R                  US5      n
U R                  US5      nU R	                  0 SU_SU_S	U R                  U5      _S
U
_SU_SS _SS _SS _SS _SS _SS _SU_SU_SS _SS _SU_SS _U	UU R                  US5      U R                  US5      US.EU5      $ )Nrq  	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  ro  r  marketIdrq  r  r  r  r  r  r  s               r  parse_tickerapex.parse_ticker  s   & %%'	##FH5!!(3!!(34%%fn=
&&v}=%%fk:
7v}5 !
f!
!
 Y/!
 D	!

 3!
 4!
 !
 4!
 !
 D!
 D!
 T!
 D!
 T!
 d!
  *!!
" t#!
$ %&))&+>**6<@-!
. / 	r  rq  c                     U R                  5         U R                  U5      nSUS   0nU R                  U R                  XB5      5      nU R	                  US/ 5      nU R                  US0 5      nU R                  Xs5      $ )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>`
rq  rx  r  r   )r#  ro  publicGetV3TickerextendrN  r	  r  r   rq  r  ro  requestr  tickers	rawTickers           r  fetch_tickerapex.fetch_ticker  s~     	V$fUm
 ))$++g*FG..626NN7Ar2	  33r  symbolsc                     U R                  5         U R                  U5      nU R                  US/ 5      nU R                  XA5      $ )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>`
r  )r#  publicGetV3DataAllTickerInforN  parse_tickers)r   r  r  r  r  s        r  fetch_tickersapex.fetch_tickers  sC     	44V<..626!!'33r  r   	timeframesincer   c                    U R                  5         U R                  U5      nU R                  U R                  X"5      US   S.nUc  SnXGS'   U R	                  SXuS5      u  puUb%  [        [        R                  " US-  5      5      US'   U R                  U R                  Xu5      5      nU R                  US	0 5      n	U R                  XS   / 5      n
U R                  XX#U5      $ )
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
rx  )intervalrq  r   r   endgMbP?  startr  )r#  ro  r  r   handle_until_optionintmathfloorpublicGetV3Klinesr  r	  rN  parse_ohlcvs)r   rq  r  r  r   r  ro  r  r  r  OHLCVss              r  fetch_ohlcvapex.fetch_ohlcv  s     	V$(()OUm
 =E 225'5Q"4::edl#;<GG))$++g*FG~~h3UmR8  5IIr  c           
          U R                  USS/5      U R                  USS/5      U R                  USS/5      U R                  USS/5      U R                  US	S
/5      U R                  USS/5      /$ )Nr  tr  or  hr  lr  cvolumev)safe_integer_nsafe_number_n)r   ohlcvro  s      r  parse_ohlcvapex.parse_ohlcv;  s     ~6uvsm4uvsm4uucl3uwn5uxo6
 	
r  c                 F   U R                  5         U R                  U5      nSUS   0nUc  SnX%S'   U R                  U R                  XS5      5      nU R	                  US0 5      nU R                  5       nU R                  XtS   USS5      n	U R                  US5      U	S	'   U	$ )
a  
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
rq  rx  r   r   r  baunonce)r#  ro  publicGetV3Depthr  r	  r  parse_order_bookr
  )
r   rq  r   r  ro  r  r  r  r  	orderbooks
             r  fetch_order_bookapex.fetch_order_bookR  s     	V$fUm
 =E ((W)EF6 ~~h3%%'	))$x0@)SRUV	!..tS9	'r  c                     U R                  5         U R                  U5      nSUS   0nUc  SnX6S'   U R                  U R                  Xd5      5      nU R	                  US/ 5      nU R                  XX#5      $ )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>`
rq  rx  r   r   r  )r#  ro  publicGetV3Tradesr  rN  parse_trades)	r   rq  r  r   r  ro  r  r  tradess	            r  fetch_tradesapex.fetch_trades  s     	V$fUm
 =E ))$++g*FG* &"5  >>r  tradec                    U R                  USS/5      nU R                  X25      nU R                  USS/5      nU R                  U/ SQ5      nU R                  USS/5      nU R                  USS	/5      nU R                  US
S/5      nU R                  US/5      n	U R                  US/5      n
U R	                  UUS UU R                  U5      US   U	S UUUS U
S.U5      $ )Nsrq  rZ  r'   )r  T	createdAtpr  r  sizeSsider)  rG  )r  r'   orderr  r  rq  r)  takerOrMakerr  r  rK  r  rG  )safe_string_nr  r  safe_string_lower_n
safe_trader  )r   r  ro  r  r'   r  priceStringamountStringr  r)  rG  s              r  parse_tradeapex.parse_trade  s    %%ec8_=!!(3T{3''/FG	((g?))%#v?''V}=!!%&2  0"Y/X&  " 
  	r  c                     U R                  5         U R                  U5      nSUS   0nU R                  U R                  XB5      5      nU R	                  US/ 5      nU R                  US0 5      nU R                  Xs5      $ )aM  
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:
rq  rx  r  r   )r#  ro  r  r  rN  r	  parse_open_interestr  s           r  fetch_open_interestapex.fetch_open_interest  s~     	V$fUm
 ))$++g*FG..626NN7Ar2	''	::r  c           	          U R                  5       nU R                  US5      nU R                  XB5      nU R                  XB5      nU R	                  UU R                  US5      S UU R                  U5      US.U5      $ )Nrq  openInterest)rq  openInterestAmountopenInterestValuer  r  r  )r  r  r  r  safe_open_interestr  )r   interestro  r  r  rq  s         r  r  apex.parse_open_interest  s    & %%'	##Hh7!!(3!!(3&&"&"2"28^"L!%"Y/(
  	r  c           
          Uc  [        U R                  S-   5      eU R                  5         0 nU R                  U5      nUS   US'   Ub  X%S'   Ub  X5S'   U R	                  US5      nUb  XuS'   U R                  U/ SQ5      nUb  XS'   U R                  U R                  XT5      5      n	/ n
U R                  U	S	0 5      nU R                  US
/ 5      n[        S[        U5      5       Hq  nX   nU R	                  US5      nU R                  US5      nU
R                  UU R                  UU5      U R                  US5      UU R!                  U5      S.5        Ms     U R#                  U
S5      nU R%                  UXU5      $ )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>`
z5 fetchFundingRateHistory() requires a symbol argumentr'   rq  beginTimeInclusiver   pageendTimeendTimeExclusiveuntilr  r  historyFundsr   fundingTimestamprate)r  rq  fundingRater  r  r  )r   r'   r#  ro  r
  r  publicGetV3HistoryFundingr  r	  rN  rO  rP  r  appendr  rT  r  sort_byfilter_by_symbol_since_limit)r   rq  r  r   r  r  ro  r  r  r  ratesr  
resultListrZ  entryr  r  sorteds                     r  fetch_funding_rate_historyapex.fetch_funding_rate_history  s    >#DGG.e$effV$"4L,1()$G  0"FO..v7_`'*:&'11$++g2NO ~~h3^^D."=
q#j/*AME))%1CDI''x8HLL**8V<#//v>& LL3 	 + e[100NNr  r  c                    U R                  US5      nU R                  US5      nU R                  US5      nU R                  US5      nU R                  Xb5      nUS   nU R                  US5      nU R                  US5      n	U R                  US5      n
U R                  US5      nU R                  US	5      nU R	                  U R                  US
5      5      nU R                  US5      nU R                  0 SU_SU_SU_SU R                  U5      _SS _SU_SU R                  U5      _SU_SU R                  U
5      _SU R                  U R                  US5      5      _SU R                  US5      _SU R                  US5      _S	U_SU_SU R                  US5      _SS _SS _S U	S US S U R                  US5      US   S.US.EU5      $ )Nr  r'   clientIdrq  r  r  r)  statusr  remainingSizeupdatedTimeclientOrderIdr  r  lastTradeTimestamplastUpdateTimestampr   postOnly
reduceOnlyr   r   r   rG  r~  )r  r[  )r  rK  filled	remainingr  r  rG  r  )r
  r  r  safe_string_lower	omit_zero
safe_orderr  parse_order_statusparse_order_typeparse_time_in_forcerS  )r   r  ro  r  orderIdr'  r  rq  r  rK  	orderTyper$  r  r-  r)  s                  r  parse_orderapex.parse_orderL  sh   n %%e[9	""5$/((
;##E84!!(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                 4    SSSSS.nU R                  X!S 5      $ )NGOOD_TIL_CANCELFILL_OR_KILLIMMEDIATE_OR_CANCEL	POST_ONLY)r9  r:  r;  r<  r*  )r   r   timeInForcess      r  r3  apex.parse_time_in_force  s*    0*#8$	
 4@@r  r$  c                 B    Ub  SSSSSSS.nU R                  X!U5      $ U$ )Nr  r,  canceled)PENDINGOPENFILLED	CANCELINGCANCELEDUNTRIGGEREDr*  )r   r$  statusess      r  r1  apex.parse_order_status  s;    !"'&%H ##Hf==r  r)  c                 8    SSSSSSS.nU R                  X!U5      $ )Nr   ro  )LIMITMARKET
STOP_LIMITSTOP_MARKETTAKE_PROFIT_LIMITTAKE_PROFIT_MARKETr*  )r   r)  typess      r  r2  apex.parse_order_type  s0    !#!("*
 T22r  r  	delimiter
marketTypec                   > Uc  Ub  XR                   ;   a  U R                   U   nOXR                  ;   a  U R                  U   nOkU R                  U5      nXPR                  ;   aK  U R                  U   n[        U5      nUS:  a+  U R                  U   S   S   U:X  a  U R                  U   S   n[        [
        U ]  XX45      $ )Nr   rx  )marketsmarkets_by_idadd_hyphen_before_usdtrP  r   r#   r  )	r   r  ro  rR  rS  newMarketIdrU  
numMarketsr  s	           r  r  apex.safe_market  s    >h2<<'h////++H5"99(C"4"44"00=G!$WJ!A~--k:1=eDP%)%7%7%DQ%GFT4,XyUUr  
_accountIdc                     U=(       d    [        U R                  S5      5      nSU-   S-   [        U R                  5       5      -   S-   [        U R                  S5      5      -   $ )N   z	apexomni--   )strrand_numberr  )r   r[  r+  s      r  generate_random_client_id_omni#apex.generate_random_client_id_omni  s\    ;#d&6&6r&:";	Y&,s43D3D3F/GG#MPSTXTdTdefTgPhhhr  c                     UR                  5       nUR                  S5      nU R                  XS-
  5      nUS:  a  US:w  a  USU S-   XS  -   $ U$ )Nr  r   r   r^  )upperfindr  )r   rq  uppercaseSymbolindex
symbolChars        r  rW  apex.add_hyphen_before_usdt  s^     ,,.$$V,%%fai8
19s*!E?S(6&>99r  c                 t    U R                  U R                  S5      nUc  [        U R                  S-   5      eU$ )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   rl  s     r  	get_seedsapex.get_seeds  sC      w7=#DGG  /O  %O  P  Pr  c                     U R                  U R                  SS5      nUS:X  a0  U R                  5       nU R                  USS5      U R                  S'   U R                  S   $ )Nr+  r(  r'   )r  r   r0  )r   r+  accountDatas      r  get_account_idapex.get_account_id  s\    $$T\\;D	,,.K(,(8(8dC(PDLL%||K((r  r  rK  r  c                    U R                  5         U R                  U5      nUR                  5       nUR                  5       n	U R                  X5      n
SnUb  U R	                  X5      nU R                  U R                  S0 5      nU R                  USS5      nU R                  USS5      nU R                  [        R                  " [        R                  " [        R                  " X5      U5      U R                  US   S	   5      5      [        US   S	   U R                  U R                  5      nU R!                  5       nU R                  US
5      nU R                  US5      nU R                  US5      nUb  US:X  a  SOSnUnOUb  US:X  a  SOSnUnUS:H  nU(       a  Uc  [#        U R$                  S-   5      eU R'                  US5      nU R)                  USU5      nUc  SnU(       d  U(       a  SnOUS:X  a  SnU R+                  US5      nU R+                  US5      nU R-                  U/ SQ5      nU R/                  5       nUc  U R1                  U5      nU R+                  U/ SQ5      nUUUUS   U
UU	UUS.	nUb  U R	                  UU5      US
'   U R3                  U R5                  U R7                  5       5      U5      nUS   U	UU
UU[9        [:        R<                  " US-  S-   5      5      UUU R                  U R>                  S S!5      S".
nUb  U R	                  UU5      US
'   UUS#'   U RA                  U RC                  UU5      5      nU R                  US$0 5      nU RE                  UU5      $ )%aj  
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>`
r(  Nr6   r   r   r   r   rH  r  r   r   r   rK  rM  rL  rO  rN  z: createOrder() requires a price argument for market ordersr   r9  r<  iocr;  r*  r#  r'  client_order_id)r#  r'  rv  r   r   r   r}  )	r+  slotIdr  pairIdr  r  	directionmakerFeeRatetakerFeeRater'   r  i ' r   r   )
rq  r  r)  r  r  limitFee
expirationr   r#  r   	signaturer  )#r#  ro  re  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  rq  rb  get_zk_contract_signature_objremove0x_prefixrm  r  r  r  r   privatePostV3Orderr  r6  )r   rq  r)  r  rK  r  r  ro  r5  	orderSide	orderSize
orderPricer   r   r   r|  timeNowr   r   r   isMarketr   r*  r'  r+  orderToSignr~  r  r  r  s                                 r  create_orderapex.create_order  s   * 	V$JJL	JJL	,,V<	
00?J~~dii4  w9  w9,,W-?-?@R@RSZSeSefpS|  D  AE  GK  G\  G\  ]c  do  ]p  qx  ]y  Gz  .{  }E  GM  NY  GZ  [b  Gc  ei  ew  ew  y}  yI  yI  J##%''?((A**63DE$*3x*?lI(L(1:h1F,M`I*L(#DGG.j$jkk,,V]C$$XtV<+K)%36=16:.**63cd'')	  ??	JM6  $H  I"#"Y'"!!

 #*.*A*A&,*WK'66t7K7KDNNL\7]_jk	Tl djj4:K)KLM&%((z6J
 #&*&=&=fl&SGN#(**4;;w+GH~~h3f--r  r  fromAccount	toAccountc                 	   U R                  5         U R                  U5      nU R                  US0 5      nU R                  US0 5      nU R                  US/ 5      n	U R                  US0 5      n
U R                  U
S/ 5      nU R                  U
S0 5      nU R	                  USS5      nU R	                  USS5      nU R	                  US	S5      nU R	                  US
S5      nU R                  U5      nU R                  US0 5      nU R                  US0 5      nU R	                  USS5      nU R	                  USS5      nU R                  US/ 5      nSn[        U5      S:  a  U R	                  US   SS5      nU R	                  USS5      nU R	                  USS5      n0 n/ nUb  UR                  5       S:X  a  U	nOUn[        S[        U5      5       H$  nU R	                  UU   SS5      U:X  d  M  UU   nM&     U R	                  USS5      nU R                  U[        R                  " SU R                  USS5      5      -  5      nU R                  U R                  5       S-  5      nU R                  U/ SQ5      n U c+  U R                  U R	                  U R                   S5      5      n U R#                  U/ SQ5      nUGb  UR                  5       S:X  Ga  Sn![$        R&                  " UU!5      n"US-   n#U"UUUU[)        U5      SU U#SS.
n$U R+                  U R-                  U R/                  5       5      U$5      n%UU#U U%UUS .n&U R1                  U R3                  U&U5      5      n'U R                  U'S0 5      n(U R                  5       n)U R3                  U R5                  U(U R7                  U5      5      U)U R9                  U)5      U R;                  U5      SS!S".5      $ UUUUU[)        U5      SUUS#.	n$U R+                  U R-                  U R/                  5       5      U$5      n%[)        U5      UU U%UUSUUUUUUUS$.n&U R=                  U R3                  U&U5      5      n'U R                  U'S0 5      n(U R                  5       n)U R3                  U R5                  U(U R7                  U5      5      U)U R9                  U)5      U R;                  U5      S!SS".5      $ )%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>`
r  rj  r5  r3  globalcontractAssetPoolEthAddress contractAssetPoolZkAccountIdcontractAssetPoolSubAccountcontractAssetPoolAccountIdspotAccountzkAccountIddefaultSubAccountIdr(  subAccountsr   r  ethereumAddressr'   r  r7  tokenId
   r>  r  ru  r+  
4294967295i $ T)
r  receiverAddresssubAccountIdreceiverSubAccountIdr  rK  rG  r  timestampSeconds
isContract)rK  
expireTimeclientWithdrawIdr~  r7  
ethAddressr4   )r  r  rK  r  r  )	r  r  r  r  r  rK  rG  r  r  )rK  r  clientTransferIdr~  r  r  rG  r7  r  receiverAccountIdreceiverZkAccountIdr  r  r  )r#  rM  r	  rN  r  r/  rP  lowerrO  parse_to_intr  powrT  r  r  rb  r   r  r!   
string_modr`  get_zk_transfer_signature_objr  rm   privatePostV3ContractTransferOutr  parse_transferr[  r  r   privatePostV3TransferOut)*r   r  rK  r  r  r  configResponse
configDatarj  contractAssetsr3  
spotAssetsglobalConfigr  r  r  r  accountResponserp  r  r  r  r  r  r  r+  r[  r5  rZ  r  amountNumberr  r'  formattedUint32zkSignAccountIdr  r  r~  r  r  r  currentTimes*                                             r  r   apex.transferY  s    	008^^NFB?

4DbI"E^^JbA
^^J"=
~~j(B?**<9VXZ["..|=[]_`#//>[]_` ,,\;WY[\226: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 ::4;O;OPTP^P^P`;acnoI ($1&(G <<T[[RX=YZH>>(FB7D++-K;;t224t9LM( LL5++F3)#P    +#2 ,(<"l+$4
K ::4;O;OPTP^P^P`;acnoIf+-$1&* ,"%6':(<#2G  44T[[&5QRH>>(FB7D++-K;;t224t9LM( LL5++F3%'P  r  r   r[  c                 J   U R                  US5      nU R                  US5      nU R                  US5      nU R                  US5      nUU R                  USS/5      UU R                  U5      U R	                  X25      U R                  US5      UUU R                  US5      S	.	$ )
Ncoinr  r  r  
transferIdr'   rK  r$  )	r  r'   r  r  r[  rK  r  r  r$  )r  r
  r  r  rQ  rT  )r   r   r[  r\  r  r  r  s          r  r  apex.parse_transfer  s    %%h7
%%h<	&&x?$$X{;	$$Xd/CD"Y///
E&&x:&"&&x:

 
	
r  c                     U R                  5         Sn0 nUb  U R                  U5      nUS   US'   U R                  U R                  XB5      5      nU R	                  US0 5      nU R                  Xc5      /$ )aq  
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'   rq  r  )r#  ro  privatePostV3DeleteOpenOrdersr  r	  r6  )r   rq  r  ro  r  r  r  s          r  cancel_all_ordersapex.cancel_all_orders  s{     	[[(F &tGH55dkk'6RS~~h3  .//r  r'   c                 :   0 nU R                  U/ SQ5      nSnUb9  XTS'   U R                  U/ SQ5      nU R                  U R                  XC5      5      nO$XS'   U R	                  U R                  XC5      5      nU R                  US0 5      nU R                  U5      $ )aU  
       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>`
       ru  Nr'   r  )r  r   privatePostV3DeleteClientOrderIdr  privatePostV3DeleteOrderr	  r0  r   r'   rq  r  r  r'  r  r  s           r  cancel_orderapex.cancel_order  s     **63cd$)DMYYv'WXF<<T[[=YZHDM44T[[5QRH~~h3t$$r  c                 Z   U R                  5         0 nU R                  U/ SQ5      nSnUb9  XTS'   U R                  U/ SQ5      nU R                  U R	                  XC5      5      nO$XS'   U R                  U R	                  XC5      5      nU R                  US0 5      nU R                  U5      $ )a  
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>`
ru  Nr'   r  )r#  r  r   privateGetV3OrderByClientOrderIdr  privateGetV3Orderr	  r6  r  s           r  fetch_orderapex.fetch_order  s     	**63cd$)DMYYv'WXF<<T[[=YZHDM--dkk'.JKH~~h3%%r  c                     U R                  5         U R                  U5      nU R                  US/ 5      nU R                  USX#5      $ )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>`
r  N)r#  privateGetV3OpenOrdersrN  parse_orders)r   rq  r  r   r  r  orderss          r  fetch_open_ordersapex.fetch_open_orders.  sG     	..v6&"5  u<<r  c                    U R                  5         0 nSnUb  U R                  U5      nUS   US'   Ub  X%S'   Ub  X5S'   U R                  U/ SQ5      nUb  XuS'   U R                  U/ SQ5      nU R	                  U R                  XT5      5      nU R                  US0 5      n	U R                  U	S	/ 5      n
U R                  XX#5      $ )
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'   rq  r  r   r  r  r  r  )	r#  ro  r  r  privateGetV3HistoryOrdersr  r	  rN  r  r   rq  r  r   r  r  ro  r  r  r  r  s              r  fetch_ordersapex.fetch_orders?  s    $ 	[[(F &tGH,1()$G..v7_`'*:&'YYv'OPF11$++g2NO~~h3h3  >>r  c                 >   U R                  5         0 nU R                  USS5      nUb  XvS'   OXS'   U R                  USS/5      nU R                  U R	                  Xe5      5      nU R                  US0 5      n	U R                  U	S/ 5      n
U R                  U
SX45      $ )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>`
r'  r#  Nr4  r  r  )r#  safe_string_2r  privateGetV3OrderFillsr  r	  rN  r  )r   r'   rq  r  r   r  r  r'  r  r  r  s              r  fetch_order_tradesapex.fetch_order_tradesd  s     	**6?JO$'4O$!#I6OZ#@A..t{{7/KL~~h3h3  u<<r  c                    U R                  5         0 nSnUb  U R                  U5      nUS   US'   Ub  X%S'   Ub  X5S'   U R                  U/ SQ5      nUb  XuS'   U R                  U/ SQ5      nU R	                  U R                  XT5      5      nU R                  US0 5      n	U R                  U	S	/ 5      n
U R                  XX#5      $ )
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'   rq  r  r   r  r  r  r  )	r#  ro  r  r  privateGetV3Fillsr  r	  rN  r  r  s              r  fetch_my_tradesapex.fetch_my_trades~  s      	[[(F &tGH,1()$G..v7_`'*:&'YYv'OPF))$++g*FG~~h3h3  >>r  c                    U R                  5         0 nSnUb  U R                  U5      nUS   US'   Ub  X%S'   Ub  X5S'   U R                  U/ SQ5      nUb  U R                  U/ SQ5      nXuS'   U R	                  U R                  XT5      5      nU R                  US0 5      n	U R                  U	S	/ 5      n
U R                  XX#5      $ )
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'   rq  r  r   r  r  r  fundingValues)	r#  ro  r  r  privateGetV3Fundingr  r	  rN  parse_incomes)r   rq  r  r   r  r  ro  r  r  r  r  s              r  fetch_funding_historyapex.fetch_funding_history  s     	[[(F &tGH,1()$G..v7_`'YYv'OPF*:&'++DKK,HI~~h3t_bA!!-FFr  c                 &   U R                  US5      nU R                  X2S S5      nSnU R                  US5      nUU R                  X25      UUU R	                  U5      U R                  US5      U R                  US5      U R                  US5      S.$ )	Nrq  r  r  fundingTimer'   fundingValuer  )r  rq  r  r  r  r'   rK  r  )r  r  r
  r  r  rT  )r   incomero  r  r  r  s         r  parse_incomeapex.parse_income  s     ##FH5!!(D*E%%fm<	&&x8"Y/""640&&v~>$$VV4	
 		
r  r   c                 F   Uc  [        U R                  S-   5      eU R                  5         U R                  U5      nU R	                  U5      n[
        R                  " SUS5      nUS   US.nU R                  U R                  Xs5      5      nU R                  US0 5      n	U	$ )aa  
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
z) setLeverage() requires a symbol argumentr      r'   )rq  initialMarginRater  )
r   r'   r#  ro  r  r!   
string_div!privatePostV3SetInitialMarginRater  r	  )
r   r   rq  r  ro  leverageStringr  r  r  r  s
             r  set_leverageapex.set_leverage  s     >#DGG.Y$YZZV$..x8#..sNAFTl!2
 99$++g:VW~~h3r  c                     U R                  5         U R                  U5      nU R                  US0 5      nU R                  US/ 5      nU R	                  XQ5      $ )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>`
r  	positions)r#  r/  r	  rN  parse_positions)r   r  r  r  r  r  s         r  fetch_positionsapex.fetch_positions  sU     	++F3~~h3NN4b9	##I77r  positionc           
      z   U R                  US5      nU R                  X25      nUS   nU R                  US5      nU R                  US5      nU R                  US5      nSnU R	                  USS/S5      n	U R                  U	5      S	:w  a'  U R                  [        R                  " S
U	S5      5      nU R                  0 SU_SU R                  US5      _SU_SU R                  US5      _SS _SS _SS _SS _SU_SU R                  U5      _SS _SU_SU R                  U5      _SS _SS _SS _SS _S US S S S S.E5      $ )Nrq  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  ro  r  rq  r  quantityr  r   r  s
             r  parse_positionapex.parse_position
  s     ##Hh7!!(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                    U R                  U R                  S   U   5      S-   U-   nSSSS.nSU-   nUn	UR                  5       S:w  a6  U(       a.  US	U R                  U5      -   -  nUS	U R                  U5      -   -  nO"U R	                  U5      n
U R                  U
5      n	US
:X  a  U R                  5         [        U R                  5       5      nXR                  5       -   U-   nU	b  X-   nU R                  U R                  U5      U R                  U R                  U R                  5      5      [        R                  S5      nXS'   U R                  US'   XS'   U R                  US'   XsXS.$ )Nr   rv  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   re  	rawencodekeysortcheck_required_credentialsr`  r  hmacencodestring_to_base64r   hashlibsha256r   r   )r   pathr   r  r  r   r  r  signPathsignBodysortedQueryr  messageStringr~  s                 r  sign	apex.sign>  sq   ##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(1$%&*kkGN#(1$%)-G%&hSSr  reasonr  r  r   r  c
                 4   Uc  g U R                  US5      n
U
b  U
S:w  ay  U R                  S-   U-   nU R                  USS5      nU R                  U R                  S   X5        [        U5      nU R                  U R                  S   X5        [        U5      eg )Nr  r    keymsgr   r   )r
  r'   r  throw_broadly_matched_exceptionr   r`  throw_exactly_matched_exceptionr   )r   r  r1  r  r  r   r  r  requestHeadersrequestBody	errorCodefeedbackmessager$  s                 r  handle_errorsapex.handle_errors[  s    
 %%h7	 Y!^ww}t+H((5%@G001I7]YF001I6\))r   )N)NNNN)N__name__
__module____qualname____firstlineno__r   r   r  r   r   r%  dictr   r,  r0  r   rg  r   r   rm  r  r   r  r`  r  r   r   r  r
   rV  r  r  r   r  r   r  r   r  r  r   r   r   r6  r3  r1  r2  r   r  rb  rW  rm  rq  r   r   floatr   r  r   r   r	   r  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r/  r=  __static_attributes____classcell__)r  s   @r  r#   r#      s   a# aF	 !# /&) )8 $& (( (
T 
g 
 $& (' ( ') kZ kZ $& C5$v, C5J@4 @F @D44 4 46 4l 02 43 4f 4( 04B 4W 47 4 9=4^bkm J# J# JS JX[ Jrvw{r| J>
 
4 
. :>b 2s 23 2Y 2h 6:UW ,?3 ,?s ,?# ,?\`af\g ,?\$ $v $ $L 79 ;# ;(F @ 8<$]ajl <O <OC <OWZ <O|b bv b bHAs A 	3S 	3VC V VRU Vjm V  zI V V i iS ) gksu ].3 ].i ].y ].RW ].`c ].~ [] {S {% {c {c {an {z
t 
x 
= 
" /32 0 0$u+ 0( 37r %s %C %0 26b &c &3 &6 /3TXac = =3 =c =hlmrhs =" *.Dt\^ #?3 #?c #? #?cghmcn #?J 9=4^bkm =S =# =S =X[ =4 -1tRV_a !?c !? !?C !?F 37TX\eg  GC  Gs  GRU  GD
6 
< 9=R S # 2 26b 8w 8T(^ 8 2t 2V 2h &eBSW T:# s  c TX `c  r  r#   ))ccxt.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  r  <module>rO     sb    ( *   S  S  S  S  S  S  * . ' ) . 3 4 %T8[ Tr  