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

 W?
 W?
 4W?
 4W?
  ]]] %] 	]
 %] %] U] $U] '] "4] '] t] ] )%] $U]   !]" /#]$ ,U%]& 0']( t)]* +], &t-]. (/]0 "41]2 %d3]4 U5]6  7]8 9]: &u;]< +E=]> )%?]@ /A]B &uC]D $UE]F 'G]H (I]J "4K]L &uM]N (O]P  Q]R *5S]T +EU]V &tW]X #EY]Z *4[]\ $U]]^ "5_]` *5a]b +Ec]d ue]f  g]h %ei]j $Uk]l "5m]n +Eo]p q]r !%s]t &uu]v  w]x dy]z $T{]| +E}]~ %e]@ "4A]B dC]D !$E]F tG]H #DI]J  K]L $UM]N !$O]P %eQ]R )%S]T tU]V W]X TY]Z t[]\ "5]]^ #E_]`  a]b !$c]d "5e]f #Eg]h i]j #Ek]l (-#!&#(!!y]W?
N OW?
j ,kW?
l i67
 GG 0;z>mW?
J &'./%&%&%&$%#$34	 '(./$%*+$%-.78&'-.*+()'( 2356+,$%67+,45&KW?
X (YW?
^  11' 6BAMIU_W?
@ !..x8!..x8AW?
L "!&# $MW?
Z ' "%#'"  $&+(,,0,1).+06:#'#'"&#'	( #(/4$($)+027#()$, %)&+!$$*%+*/& ',#($)*/	# ',!%#($)*/( ',!$$*%+#($)*/$ *.#o:z "9  $	yBiW?
 W W	    c                 n    | j                  |      }| j                  |di       }| j                  |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
        datatime)publicGetV3Time	safe_dictsafe_integerr   paramsresponser   s       r   
fetch_timezapex.fetch_time2  s;     ''/~~h3   v..r   c                     | j                         }||| j                  |      d}d}| j                         }| j                  |d      |d<   | j                  |d      |d<   |||<   | j	                  |      S )N)info	timestampdatetimeUSDTavailableBalancefreetotalEquityValuetotal)millisecondsiso8601accountsafe_stringsafe_balance)r   r  r  resultcoder  s         r   parse_balancezapex.parse_balanceE  s     %%'	"Y/

 ,,.**85GH++H6HIt  ((r   c                     | j                          | j                  |      }| j                  |di       }| j                  |      S )aA  
        query for account info

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

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        r   )load_marketsprivateGetV3AccountBalancer   r  r   s       r   fetch_balancezapex.fetch_balancea  sC     	226:~~h3!!$''r   r  c                 6    | j                  |dd      }|d d |dS )Nr&   0)r&   typer  r  r  )r   r  	accountIds      r   parse_accountzapex.parse_accounto  s,    $$WdC8		
 	
r   c                     | j                          | j                  |      }| j                  |di       }| j                  |      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>`
        r   )r  privateGetV3Accountr   r  r   s       r   fetch_accountzapex.fetch_accountx  sC     	++F3~~h3!!$''r   c                    | j                  |      }| j                  |di       }| j                  |di       }| j                  |di       }| j                  |dg       }| j                  |dg       }i }t        dt	        |            D ]  }	||	   }
| j                  |
d      }| j                  |      }| j                  |
d      }i }t        dt	        |            D ]  }||   }| j                  |d	g       }t        dt	        |            D ]  }||   }| j                  |d      }||k(  s | j                  |d
      }| j                  |      }|||d| j                  |d       | j                  |d      | j                  |d      | j                  | j                  | j                  |d                  | j                  |d      dd| j                  |d      dddd	||<     t        |j                               }t	        |      }|dk(  }|rdnd}| j                  |
||d|d||dddddddddddd|d      ||<    |S )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
        r   
spotConfig
multiChainassetschainsr   tokendisplayNametokenschainIdNdepositDisablewithdrawEnableminFeedecimalsminWithdrawminmax
minDeposit)r   deposit)	r  r&   networkactiver4  r   fee	precisionlimitsFcrypto)amountr   r4  )r  r  r&   r  r'   r6  r4  r   r7  r8  r9  networks)publicGetV3Symbolsr   	safe_listrangelenr  safe_currency_codenetwork_id_to_code	safe_boolsafe_numberr   parse_precisionlistkeyssafe_currency_structure)r   r  r  r   r#  r$  rowsr&  r  icurrency
currencyIdr  r'   r<  jchainr)  fr'  	tokenName	networkIdnetworkCodenetworkKeysnetworksLengthemptyChainsvalueForEmptys                              r   fetch_currencieszapex.fetch_currencies  s    **62~~h3^^D,;
^^JbA
t ~~j(B7
Hb9q#d)$ A	AAwH))(G<J**:6D##Hm<DH1c&k* q	x<q#f+. A"1IE $ 0 0 @I J.$($4$4UI$F	&*&=&=i&H$)"+'2&*+/>>%AQ+R'R(,u>N(O#'#3#3E8#D)-):):4;O;OPTP`P`afhrPs;t)u ,0+;+;E=+Q+/-"
 ,0+;+;E<+P+/,"	'1-: x}}/K -N(A-K%0EdM77   ()!  $#
  $#!
  $#  %39 F4LOA	D r   c                     | j                  |      }| j                  |di       }| j                  |di       }| j                  |dg       }| j                  |      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
        r   contractConfigperpetualContract)r=  r   r>  parse_markets)r   r  r  r   rY  rZ  s         r   fetch_marketszapex.fetch_markets3  sc     **62~~h3.>C NN>;NPRSn !!"344r   marketc                    | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |      }| j                  |d      }| j                  |      }	|dz   |z   dz   |	z   }
d}| j                  d	      }| j                  d
      }| j                  i d|d|d|
d|d|d|	d|d|d|dddddd ddddddd| j	                  |d      dddd||| j                  |d      |dk(  rd n||dk(  rd n| j                  |      d d | j                  |d      | j                  |d       d!| j                  |d"      | j                  |d#      d$| j                  |d      | j                  |d%      d$d d d$d d d$d&d |d'      S )(NsymbolcrossSymbolNamel2PairIdbaseTokenIdsettleAssetId/:r   r   r   r&   id2basequotesettlebaseIdquoteIdsettleIdr  r5   r3   Fr4   Tr6   r7   r6  enableTradecontractminOrderSizestepSizetickSize)r;  pricedisplayMinLeveragedisplayMaxLeverager0  maxOrderSize)r   r;  rr  cost)r   r   r   r   contractSizeexpiryexpiryDatetimestrike
optionTyper8  r9  createdr  )r  rA  r   safe_market_structurerC  rD  r  )r   r]  r&   rf  rk  rj  rh  rg  rl  ri  r_  rx  takerFeemakerFees                 r   parse_marketzapex.parse_marketx  s   fh/v'89""6:6!!&-8  9&&v.##FO<((2#%+f4$$X.$$X.)) 3+
"3+
33+
 f3+
 D	3+

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

 3!
 4!
 !
 4!
 !
 D!
 D!
 T!
 D!
 T!
 d!
  *!!
" t#!
$ %&))&+>**6<@-!
. / 	r   r_  c                    | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |dg       }| j                  |di       }| j                  ||      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>`
        r_  rf  r   r   )r  r]  publicGetV3Tickerextendr>  r   r  r   r_  r  r]  requestr  tickers	rawTickers           r   fetch_tickerzapex.fetch_ticker  s     	V$fUm
 ))$++gv*FG..626NN7Ar2	  F33r   symbolsc                     | j                          | j                  |      }| j                  |dg       }| j                  ||      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>`
        r   )r  publicGetV3DataAllTickerInfor>  parse_tickers)r   r  r  r  r  s        r   fetch_tickerszapex.fetch_tickers  sE     	44V<..626!!'733r   r   sincer   c                    | j                          | j                  |      }| j                  | j                  ||      |d   d}|d}||d<   | j	                  d||      \  }}|||d<   | j                  | j                  ||            }| j                  |di       }	| j                  |	|d   g       }
| j                  |
||||      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
        rf  )intervalr_  r   r   endstartr   )
r  r]  r  r   handle_until_optionpublicGetV3Klinesr  r   r>  parse_ohlcvs)r   r_  	timeframer  r   r  r]  r  r  r   OHLCVss              r   fetch_ohlcvzapex.fetch_ohlcv  s     	V$(()YOUm
 =E 225'6J$GG))$++gv*FG~~h3fUmR8  E5IIr   c           
          | j                  |ddg      | j                  |ddg      | j                  |ddg      | j                  |ddg      | j                  |d	d
g      | j                  |ddg      gS )Nr  tr  or  hr  lr  cvolumev)safe_integer_nsafe_number_n)r   ohlcvr]  s      r   parse_ohlcvzapex.parse_ohlcv2  s     ~6uvsm4uvsm4uucl3uwn5uxo6
 	
r   c                 J   | j                          | j                  |      }d|d   i}|d}||d<   | j                  | j                  ||            }| j	                  |di       }| j                         }| j                  ||d   |dd      }	| j                  |d      |	d	<   |	S )
aK  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

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

        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        r_  rf  r   r   r   baunonce)r  r]  publicGetV3Depthr  r   r  parse_order_bookr   )
r   r_  r   r  r]  r  r  r   r  	orderbooks
             r   fetch_order_bookzapex.fetch_order_bookI  s     	V$fUm
 =E ((Wf)EF6 ~~h3%%'	))$x0@)SRUV	!..tS9	'r   c                     | j                          | j                  |      }d|d   i}|d}||d<   | j                  | j                  ||            }| j	                  |dg       }| j                  ||||      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>`
        r_  rf  r   r   r   )r  r]  publicGetV3Tradesr  r>  parse_trades)	r   r_  r  r   r  r]  r  r  tradess	            r   fetch_tradeszapex.fetch_trades}  s     	V$fUm
 =E ))$++gv*FG* &"5  >>r   tradec                    | j                  |ddg      }| j                  ||      }| j                  |ddg      }| j                  |g d      }| j                  |ddg      }| j                  |dd	g      }| j                  |d
dg      }| j                  |dg      }	| j                  |dg      }
| j	                  ||d || j                  |      |d   |	d |||d |
d|      S )Nsr_  rJ  r&   )r  T	createdAtprr  r  sizeSsider  r7  )r  r&   orderr  r  r_  r  takerOrMakerr  rr  r;  rv  r7  )safe_string_nr  r  safe_string_lower_n
safe_trader  )r   r  r]  r  r&   r  priceStringamountStringr  r  r7  s              r   parse_tradezapex.parse_trade  s    %%ec8_=!!(F3T{3''/FG	((g?))%#v?''V}=!!%&2  0"Y/X&  " 
  	r   c                    | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |dg       }| j                  |di       }| j                  ||      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:
        r_  rf  r   r   )r  r]  r  r  r>  r   parse_open_interestr  s           r   fetch_open_interestzapex.fetch_open_interest  s     	V$fUm
 ))$++gv*FG..626NN7Ar2	''	6::r   c           	          | j                         }| j                  |d      }| j                  ||      }| j                  ||      }| j	                  || j                  |d      d || j                  |      |d|      S )Nr_  openInterest)r_  openInterestAmountopenInterestValuer  r  r  )r  r  r  r  safe_open_interestr  )r   interestr]  r  r  r_  s         r   r  zapex.parse_open_interest  s    & %%'	##Hh7!!(F3!!(F3&&"&"2"28^"L!%"Y/(
  	r   c           
          |t        | j                  dz         | j                          i }| j                  |      }|d   |d<   |||d<   |||d<   | j	                  |d      }|||d<   | j                  |g d      }|||d<   | j                  | j                  ||            }	g }
| j                  |	d	i       }| j                  |d
g       }t        dt        |            D ]q  }||   }| j	                  |d      }| j                  |d      }|
j                  || j                  ||      | j                  |d      || j!                  |      d       s | j#                  |
d      }| j%                  ||||      S )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&   r_  beginTimeInclusiver   pageendTimeendTimeExclusiveuntilr  r   historyFundsr   fundingTimestamprate)r  r_  fundingRater  r  r  )r   r&   r  r]  r   r  publicGetV3HistoryFundingr  r   r>  r?  r@  r  appendr  rD  r  sort_byfilter_by_symbol_since_limit)r   r_  r  r   r  r  r]  r  r  r  ratesr   
resultListrJ  entryr  r  sorteds                     r   fetch_funding_rate_historyzapex.fetch_funding_rate_history  s    >#DGG.e$effV$"4L,1G()$GG  0"GFO..v7_`'*:G&'11$++gv2NO ~~h3^^D."=
q#j/* 
	AqME))%1CDI''x8HLL**8V<#//v>& LL3 	
	 e[100NNr   r  c                    | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  ||      }|d   }| j                  |d      }| j                  |d      }	| j                  |d      }
| j                  |d      }| j                  |d	      }| j	                  | j                  |d
            }| j                  |d      }| j                  i d|d|d|d| j                  |      dd d|d| j                  |      d|d| j                  |
      d| j                  | j                  |d            d| j                  |d      d| j                  |d      d	|d|d| j                  |d      dd dd d |	d |d d | j                  |d      |d   d|d|      S )Nr  r&   clientIdr_  rr  r  r  statusr  remainingSizeupdatedTimeclientOrderIdr  r  lastTradeTimestamplastUpdateTimestampr   postOnly
reduceOnlyr   r   r   r7  rl  )rv  rK  )r  r;  filled	remainingrv  r  r7  r  )r   r  r  safe_string_lower	omit_zero
safe_orderr  parse_order_statusparse_order_typeparse_time_in_forcerC  )r   r  r]  r  orderIdr  r  r_  rr  r;  	orderTyper  r  r  r  s                  r   parse_orderzapex.parse_orderC  sj   n %%e[9	""5$/((
;##E84!!(F3!  0!!%0$$UF3	!!%2%%eV4NN4#3#3E?#KL	"//}E  
' 
] 
  
 Y/	 

 !$ 
 "#6 
 d--f5 
 f 
 D)))4 
 433D4D4DUM4Z[ 
 uj9 
 $..= 
 D 
 U 
 D,,UNC 
  t! 
" T# 
$ "((6":. 9 
: ; 	r   r   c                 6    ddddd}| j                  ||d       S )NGOOD_TIL_CANCELFILL_OR_KILLIMMEDIATE_OR_CANCEL	POST_ONLY)r  r  r  r  r  )r   r   timeInForcess      r   r  zapex.parse_time_in_force  s,    0*#8$	
 k4@@r   r  c                 B    |ddddddd}| j                  |||      S |S )Nr  r
  canceled)PENDINGOPENFILLED	CANCELINGCANCELEDUNTRIGGEREDr  )r   r  statusess      r   r  zapex.parse_order_status  s=    !"'&%H ##Hff==r   r  c                 :    ddddddd}| j                  |||      S )NLIMITMARKET
STOP_LIMITSTOP_MARKETTAKE_PROFIT_LIMITTAKE_PROFIT_MARKET)r%  r&  r'  r(  r)  r*  )safe_string_upper)r   r  typess      r   r  zapex.parse_order_type  s2    &(!4"6
 %%eT488r   r  	delimiter
marketTypec                    |||| j                   v r| j                   |   }n|| j                  v r| j                  |   }nh| j                  |      }|| j                  v rI| j                  |   }t        |      }|dkD  r*| j                  |   d   d   |k(  r| j                  |   d   }t        t
        |   ||||      S )Nr   rf  )marketsmarkets_by_idadd_hyphen_before_usdtr@  r   r#   r  )	r   r  r]  r-  r.  newMarketIdr0  
numMarketsr   s	           r   r  zapex.safe_market  s    >h24<<'h/T///++H5"99(C$"4"44"00=G!$WJ!A~--k:1=eDP%)%7%7%DQ%GFT4,Xvy*UUr   
_accountIdc                     |xs t        | j                  d            }d|z   dz   t        | j                               z   dz   t        | j                  d            z   S )N   z	apexomni--   )strrand_numberr  )r   r5  r  s      r   generate_random_client_id_omniz#apex.generate_random_client_id_omni  s\    ;#d&6&6r&:";	Y&,s43D3D3F/GG#MPSTXTdTdefTgPhhhr   c                     |j                         }|j                  d      }| j                  ||dz
        }|dkD  r|dk7  r|d| dz   ||d  z   S |S )Nr  r   r   r8  )upperfindr  )r   r_  uppercaseSymbolindex
symbolChars        r   r2  zapex.add_hyphen_before_usdt  sb     ,,.$$V,%%feai8
19s*!E?S(6%&>99r   c                 r    | j                  | j                  d      }|t        | j                  dz         |S )Nseedsz the "seeds" key is required in the options to access private endpoints. You can find it in API Management > Omni Key, and then set it.options["seeds"] = XXXX)r  r   r   r&   )r   rD  s     r   	get_seedszapex.get_seeds  sC      w7=#DGG  /O  %O  P  Pr   c                     | j                  | j                  dd      }|dk(  r0| j                         }| j                  |dd      | j                  d<   | j                  d   S )Nr  r  r&   )r  r   r!  )r   r  accountDatas      r   get_account_idzapex.get_account_id  s\    $$T\\;D	,,.K(,(8(8dC(PDLL%||K((r   r  r;  rr  c                    | j                          | j                  |      }|j                         }|j                         }	| j                  ||      }
d}|| j	                  ||      }| j                  | j                  di       }| j                  |dd      }| j                  |dd      }| j                  t        j                  t        j                  t        j                  ||
      t        |            t        |d   d	               t        |d   d	   | j                  | j                        }| j!                         }|d
k(  }|r|t#        | j$                  dz         | j'                  |d      }| j)                  |d|      }|d}|s|rd}n|dk(  rd}| j+                  |d      }| j+                  |d      }| j-                  |g d      }| j/                         }|| j1                  |      }| j+                  |g d      }||||d   |
||	t        |      t        |      d	}| j3                  | j5                  | j7                               |      }|d   |	||
||t9        t;        j<                  |dz  dz               ||| j?                  | j@                  dd      d
}||d<   | jC                  | jE                  ||            }| j                  |di       }| jG                  ||      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 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  Nr5   r   gMb@?r   g-C6*?r8  rr  r&  z: createOrder() requires a price argument for market ordersr   r  r  iocr  r  r  r  client_order_idrk  )	r  slotIdr  pairIdr  rr  	directionmakerFeeRatetakerFeeRater&     i ' r   r   )
r_  r  r  r  rr  limitFee
expirationr   r  r   	signaturer   )$r  r]  r>  amount_to_precisionprice_to_precisionr   r   rD  decimal_to_precisionr!   
string_add
string_mulr:  r   r   paddingModer  r   r&   r+  is_post_onlyomitr  rH  r<  get_zk_contract_signature_objremove0x_prefixrE  intmathfloorr  r   privatePostV3Orderr  r  )r   r_  r  r  r;  rr  r  r]  r  	orderSide	orderSize
orderPricer   r   r   rS  timeNowisMarketr   r  r  r  orderToSignrU  r  r  r   s                              r   create_orderzapex.create_order  sV   & 	V$JJL	JJL	,,VV<	
00?J~~dii4  w7  w7,,W-?-?@R@RSZSeSefpr{S|  B  CH  I  AJ  LO  PV  Wb  Pc  dk  Pl  Lm  .n  px  z@  AL  zM  NU  zV  X\  Xj  Xj  lp  l|  l|  }##%(#DGG.j$jkk,,V]C$$XtV<+K)%36=16:.**63cd'')	  ??	JM6#ST"#"Y'"JJ

 66t7K7KDNNL\7]_jk	Tl djj4:K)KLM&%((z6J
  )**4;;w+GH~~h3f--r   r  fromAccount	toAccountc                 	   | j                          | j                  |      }| j                  |di       }| j                  |di       }| j                  |dg       }	| j                  |di       }
| j                  |
dg       }| j                  |
di       }| j	                  |dd      }| j	                  |dd      }| j	                  |d	d      }| j	                  |d
d      }| j                  |      }| j                  |di       }| j                  |di       }| j	                  |dd      }| j	                  |dd      }| j                  |dg       }d}t        |      dkD  r| j	                  |d   dd      }| j	                  |dd      }| j	                  |dd      }i }g }||j                         dk(  r|	}n|}t        dt        |            D ]!  }| j	                  ||   dd      |k(  s||   }# | j	                  |dd      }| j                  |t        j                  d| j                  |dd            z        }| j                  | j                         dz        }| j                  |g d      } | +| j                  | j	                  | j                   d            } | j#                  |g d      }||j                         dk(  rd}!t%        j&                  ||!      }"|dz   }#|"||||t)        |      d| |#dd
}$| j+                  | j-                  | j/                               |$      }%||#| |%||d }&| j1                  | j3                  |&|            }'| j                  |'di       }(| j                         })| j3                  | j5                  |(| j7                  |            |)| j9                  |)      | j;                  |      dd!d"      S |||||t)        |      d||d#	}$| j+                  | j-                  | j/                               |$      }%t)        |      || |%||d|||||||d$}&| j=                  | j3                  |&|            }'| j                  |'di       }(| j                         })| j3                  | j5                  |(| j7                  |            |)| j9                  |)      | j;                  |      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>`
        r   rY  r%  r#  globalcontractAssetPoolEthAddress contractAssetPoolZkAccountIdcontractAssetPoolSubAccountcontractAssetPoolAccountIdspotAccountzkAccountIddefaultSubAccountIdr  subAccountsr   r  ethereumAddressr&   rn  r'  tokenId
   r.  rR  rK  r  
4294967295i $ T)
ru  receiverAddresssubAccountIdreceiverSubAccountIdry  r;  r7  r  timestampSeconds
isContract)r;  
expireTimeclientWithdrawIdrU  r'  
ethAddressr3   )r  r  r;  rk  rl  )	ru  r|  r}  r~  ry  r;  r7  r  r  )r;  r  clientTransferIdrU  ru  r}  r7  r'  ry  receiverAccountIdreceiverZkAccountIdr~  r|  r  )r  r=  r   r>  r  r   r@  lowerr?  parse_to_intra  powrD  r  r  r<  r   r]  r!   
string_modr:  get_zk_transfer_signature_objr_  rE   privatePostV3ContractTransferOutr  parse_transferrK  r  r   privatePostV3TransferOut)*r   r  r;  rk  rl  r  configResponse
configDatarY  contractAssetsr#  
spotAssetsglobalConfigr|  r  r~  r  accountResponserG  rt  ru  r}  rw  r  r  r  rK  r%  rJ  ry  amountNumberr  r  formattedUint32zkSignAccountIdr  ri  rU  r  r  r   currentTimes*                                             r   r   zapex.transferB  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   rK  c                 L   | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }|| j                  |ddg      || j                  |      | j	                  ||      | j                  |d      ||| j                  |d      d		S )
Ncoinr  rk  rl  
transferIdr&   r;  r  )	r  r&   r  r  rK  r;  rk  rl  r  )r  r   r  r  rA  rD  )r   r   rK  rL  r  rk  rl  s          r   r  zapex.parse_transfer  s    %%h7
%%h<	&&x?$$X{;	$$Xd/CD"Y///
HE&&x:&"&&x:

 
	
r   c                     | j                          d}i }|| j                  |      }|d   |d<   | j                  | j                  ||            }| j	                  |di       }|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&   r_  r   )r  r]  privatePostV3DeleteOpenOrdersr  r   )r   r_  r  r]  r  r  r   s          r   cancel_all_orderszapex.cancel_all_orders  sn     	[[(F &tGH55dkk'66RS~~h3r   r&   c                 "   i }| j                  |g d      }d}|;||d<   | j                  |g d      }| j                  | j                  ||            }n&||d<   | j	                  | j                  ||            }| j                  |di       }|S )a\  
        cancels an open order

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

        :param str id: order id
 @param symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        rK  Nr&   r   )r  r]   privatePostV3DeleteClientOrderIdr  privatePostV3DeleteOrderr   r   r&   r_  r  r  r  r  r   s           r   cancel_orderzapex.cancel_order  s     **63cd$)GDMYYv'WXF<<T[[RX=YZHGDM44T[[&5QRH~~h3r   c                 `   | j                          i }| j                  |g d      }d}|;||d<   | j                  |g d      }| j                  | j	                  ||            }n&||d<   | j                  | j	                  ||            }| j                  |di       }| j                  |      S )aX  
        fetches information on an order made by the user

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

        :param str id: the order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.clientOrderId]: a unique id for the order
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        rK  Nr&   r   )r  r  r]   privateGetV3OrderByClientOrderIdr  privateGetV3Orderr   r  r  s           r   fetch_orderzapex.fetch_order  s     	**63cd$)GDMYYv'WXF<<T[[RX=YZHGDM--dkk'6.JKH~~h3%%r   c                     | j                          | j                  |      }| j                  |dg       }| j                  |d||      S )aB  
        fetches information on multiple orders made by the user

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

        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        r   N)r  privateGetV3OpenOrdersr>  parse_orders)r   r_  r  r   r  r  orderss          r   fetch_open_orderszapex.fetch_open_orders  sI     	..v6&"5  ue<<r   c                    | j                          i }d}|| j                  |      }|d   |d<   |||d<   |||d<   | j                  |g d      }|||d<   | j                  |g d      }| j	                  | j                  ||            }| j                  |di       }	| j                  |	d	g       }
| j                  |
|||      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-all-order-history

        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve, default 100
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param dict [params.until]: end time, ms
        :param boolean [params.status]: "PENDING", "OPEN", "FILLED", "CANCELED", "EXPIRED", "UNTRIGGERED"
        :param boolean [params.side]: BUY or SELL
        :param str [params.type]: "LIMIT", "MARKET","STOP_LIMIT", "STOP_MARKET", "TAKE_PROFIT_LIMIT","TAKE_PROFIT_MARKET"
        :param str [params.orderType]: "ACTIVE","CONDITION","HISTORY"
        :param boolean [params.page]: Page numbers start from 0
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr&   r_  r  r   r  r  r   r  )	r  r]  r  r]  privateGetV3HistoryOrdersr  r   r>  r  r   r_  r  r   r  r  r]  r  r  r   r  s              r   fetch_orderszapex.fetch_orders(  s    $ 	[[(F &tGH,1G()$GG..v7_`'*:G&'YYv'OPF11$++gv2NO~~h3h3  >>r   c                 D   | j                          i }| j                  |dd      }|||d<   n||d<   | j                  |ddg      }| j                  | j	                  ||            }| j                  |di       }	| j                  |	dg       }
| j                  |
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>`
        r  r  Nr  r   r  )r  safe_string_2r]  privateGetV3OrderFillsr  r   r>  r  )r   r&   r_  r  r   r  r  r  r  r   r  s              r   fetch_order_tradeszapex.fetch_order_tradesM  s     	**6?JO$'4GO$!#GI6OZ#@A..t{{7F/KL~~h3h3  ue<<r   c                    | j                          i }d}|| j                  |      }|d   |d<   |||d<   |||d<   | j                  |g d      }|||d<   | j                  |g d      }| j	                  | j                  ||            }| j                  |di       }	| j                  |	d	g       }
| j                  |
|||      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&   r_  r  r   r  r  r   r  )	r  r]  r  r]  privateGetV3Fillsr  r   r>  r  r  s              r   fetch_my_tradeszapex.fetch_my_tradesg  s      	[[(F &tGH,1G()$GG..v7_`'*:G&'YYv'OPF))$++gv*FG~~h3h3  >>r   c                    | j                          i }d}|| j                  |      }|d   |d<   |||d<   |||d<   | j                  |g d      }|| j                  |g d      }||d<   | j	                  | j                  ||            }| j                  |di       }	| j                  |	d	g       }
| j                  |
|||      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&   r_  r  r   r  r  r   fundingValues)	r  r]  r  r]  privateGetV3Fundingr  r   r>  parse_incomes)r   r_  r  r   r  r  r]  r  r  r   r  s              r   fetch_funding_historyzapex.fetch_funding_history  s     	[[(F &tGH,1G()$GG..v7_`'YYv'OPF*:G&'++DKK,HI~~h3t_bA!!-FFr   c                 *   | j                  |d      }| j                  ||d d      }d}| j                  |d      }|| j                  ||      ||| j	                  |      | j                  |d      | j                  |d      | j                  |d      dS )	Nr_  rn  r  fundingTimer&   fundingValuer  )r  r_  r  r  r  r&   r;  r  )r  r  r   r  r  rD  )r   incomer]  r  r  r  s         r   parse_incomezapex.parse_income  s     ##FH5!!(FD*E%%fm<	&&x8"Y/""640&&v~>$$VV4	
 		
r   r   c                 D   |t        | j                  dz         | j                          | j                  |      }| j	                  |      }t        j                  d|d      }|d   |d}| j                  | j                  ||            }| j                  |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
        z) setLeverage() requires a symbol argumentr      r&   )r_  initialMarginRater   )
r   r&   r  r]  number_to_stringr!   
string_div!privatePostV3SetInitialMarginRater  r   )
r   r   r_  r  r]  leverageStringr  r  r  r   s
             r   set_leveragezapex.set_leverage  s     >#DGG.Y$YZZV$..x8#..sNAFTl!2
 99$++gv:VW~~h3r   c                     | j                          | j                  |      }| j                  |di       }| j                  |dg       }| j	                  ||      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>`
        r   	positions)r  r   r   r>  parse_positions)r   r  r  r  r   r  s         r   fetch_positionszapex.fetch_positions  sW     	++F3~~h3NN4b9	##Iw77r   positionc           
      x   | j                  |d      }| j                  ||      }|d   }| j                  |d      }| j                  |d      }| j                  |d      }d}| j	                  |ddgd      }	| j                  |	      d	k7  r&| j                  t        j                  d
|	d            }| j                  i d|d| j                  |d      d|d| j                  |d      dd dd dd dd d|d| j                  |      dd d|d| j                  |      dd dd dd dd d |d d d d d      S )Nr_  r  r  r  r-   customInitialMarginRate	customImrr  r   r   r  r  r&   
entryPricer  notional
collateralunrealizedPnl	contractsrw  r  r  r   maintenanceMarginmaintenanceMarginPercentageinitialMargin)initialMarginPercentager   liquidationPricemarginRatior   r  )r  r  r  r   r  precision_from_stringr  r!   r  safe_positionr   r  )
r   r  r]  r  r_  r  quantityr  r   r  s
             r   parse_positionzapex.parse_position  s     ##Hh7!!(F3!%%h7##Hf5%%h>	"&"4"4X@Y[f?gil"m%%&=>!C((););CAXZ[)\]H!! #
H#
$""8T2#
 f#
 $**8\B	#

 #
 #
 $#
 T#
 D#
 **84#
 D#
 #
 Y/#
 d#
  #
  *4!#
" T##
$ (,  $/#
  	r   r   GETc                    | j                  | j                  d   |         dz   |z   }dddd}d|z   }|}	|j                         dk7  r1|rQ|d	| j                  |      z   z  }|d	| j                  |      z   z  }n"| j	                  |      }
| j                  |
      }	|d
k(  r| j                          t        | j                               }||j                         z   |z   }|	||	z   }| j                  | j                  |      | j                  | j                  | j                              t        j                  d      }||d<   | j                  |d<   ||d<   | j                  |d<   |||	|dS )Nr   rd  z	apex-CCXTzapplication/jsonz!application/x-www-form-urlencoded)z
User-AgentAcceptzContent-Typez/api/POST?r   base64zAPEX-SIGNATUREzAPEX-API-KEYzAPEX-TIMESTAMPzAPEX-PASSPHRASE)urlmethodbodyheaders)implode_hostnamer   r>  	rawencodekeysortcheck_required_credentialsr:  r  hmacencodestring_to_base64r   hashlibsha256r   r   )r   pathr   r  r  r  r  r  signPathsignBodysortedQueryr  messageStringrU  s                 r   signz	apex.sign'  s|   ##DIIe$4S$9:S@4G%(?

 T><<>V#C$.."888sT^^F333,,v.K~~k2H)++-D--/0I%6AM# - 8		$++m"<dkk$J_J_`d`k`kJl>movo}o}  @H  II(1G$%&*kkGN#(1G$%)-G%&fh7SSr   reasonr  r  r  r  c
                 2   |y | j                  |d      }
|
|
dk7  r{| j                  dz   |z   }| j                  |dd      }| j                  | j                  d   ||       t        |      }| j                  | j                  d   ||       t        |      y )Nr  r    keymsgr   r   )r   r&   r  throw_broadly_matched_exceptionr   r:  throw_exactly_matched_exceptionr   )r   r  r  r  r  r  r  r  requestHeadersrequestBody	errorCodefeedbackmessager  s                 r   handle_errorszapex.handle_errorsD  s    
 %%h7	 Y!^ww}t+H((5%@G001I7T\]YF001I6S[\))r   )N)NNNN)L__name__
__module____qualname__r   r   r  r   r  r  dictr   r  r!  r   rW  r   r   r\  r  r   r  r:  r  r   r   r  r
   rF  r  r  r   r  r   r  r  r  r  r   r  r   r  r  r  r  r   r  r<  r2  rE  rH  r   r   floatr   rj  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   X# Xt !# /&) )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 26DW[df J# Jc JQT Jkoptku 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 	9S 	9VC V VRU Vjm V  zI V i iS ) gksu O.3 O.i O.y O.RW O.`c O.b [] {S {% {c {c {an {z
t 
x 
= 
" /32  ( 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  ra  ccxt.base.typesr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   typingr   ccxt.base.errorsr   r   r   r   r   ccxt.base.decimal_to_precisionr   r    ccxt.base.preciser!   r#    r   r   <module>r     sb    ( *   S  S  S  S  S  S  * . ' ) . 3 4 %}8[ }r   