
    ei                       d dl mZ d dlm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 d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d d	lmZ d d
lm Z  d dlm!Z! d dlm"Z" d dl#m$Z$ d dl%m&Z&  G d dee          Z'dS )    )Exchange)ImplicitAPI)AnyBalancesBool
CurrenciesCurrencyIntMarket
MarketTypeNumOrder	OrderSide	OrderTypePositionStrStringsTickerFundingRateTradeTransaction)List)ExchangeError)AuthenticationError)ArgumentsRequired)
BadRequest)InsufficientFunds)InvalidOrder)OrderNotFound)RateLimitExceeded)	TICK_SIZE)Precisec                   ~    e Zd Zdef fdZdef fdZi fdZi fdefdZ	i fde
e         fdZi fde
e         fdZi fde
e         fd	Zi fde
e         fd
ZdedefdZi fdedefdZdTd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dddi fdededefdZi fdedefdZdTdedefdZd Zd Z d Z!d Z"d Z#dUd efd!Z$di fded"e%d#e&d$e'd%e(f
d&Z)ddi fd'eded"e%d#e&d$e(d%e(fd(Z*di fd'edefd)Z+di f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d,Z/dddi fdededede
e-         fd-Z0dddi fdededefd.Z1d/efd0Z2d1efd2Z3dTd3edede-fd4Z4dddi fd'edededefd5Z5dddi fdededefd6Z6di fd7e7de
e8         fd8Z9dTd9edefd:Z:dddi fdededefd;Z;dTdefd<Z<i fde=fd=Z>de=fd>Z?dddi fd?ededede
e@         fd@ZAdddi fd?ededede
e@         fdAZBdTdBedCeCde@fdDZDd1efdEZEdFedGefdHZFdFedGefdIZGdJeHdKedLedMedNedOefdPZIdQdRi ddfdSZJ xZKS )Vderivereturnc                 H   |                      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d/dd0d
i d1d
d2dd3d
d4d
d5dd6d7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
dedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}d~d|dddddddgg dddg did|di dd
d
ddddi dt          dt          dt
          dt
          dt
          dt          dt          dt          dt
          dt
          dt
          dt
          dt          dt
          dt
          dt
          dt
          i dt
          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          i dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt
          dt          dt          i dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          i dt          dt          dt          dt
          dt
          dt
          dt
          dt          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt          dt
          i dt
          dt
          dt
          dt
          dt
          dt
          dt          dt          dt
          dt
          dt
          dt          dt
          dt          dt
          dt          dt
          i dt          dt          dt          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          d t
          dt
          dt
          dt
          dt
          t
          t
          t
          di ddt          i dd	d
d          S (  Nidr$   name	countriesversionv1	rateLimit2   	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createReduceOnlyOrdercreateStopOrdercreateTriggerOrder	editOrderfetchAccountsfetchBalancefetchBorrowInterestfetchBorrowRateHistoriesfetchBorrowRateHistoryfetchCanceledAndClosedOrdersfetchCanceledOrdersfetchClosedOrdersfetchCrossBorrowRatefetchCrossBorrowRatesfetchCurrenciesfetchDepositAddressfetchDepositAddressesfetchDepositsfetchDepositWithdrawFeeemulated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1m3m5m15m30m1h2h4h8h12h1d3d1w1M)r   r   r   r   r   r   r   r   r   r   r   r   r   r   hostnamez
derive.xyzurlszOhttps://github.com/user-attachments/assets/f835b95f-033a-43dd-b6bb-24e698fc498czhttps://api.lyra.finance/publicz https://api.lyra.finance/private)publicprivatez$https://api-demo.lyra.finance/publicz%https://api-demo.lyra.finance/privatezhttps://www.derive.xyz/zhttps://docs.derive.xyz/docs/z)https://docs.derive.xyz/reference/fees-1/z#https://www.derive.xyz/invite/3VB0B)logoapitestwwwdocfeesreferralr   get_all_currencies)2build_register_session_key_txregister_session_keyderegister_session_keylogin
statisticsr   get_currencyget_instrumentget_all_instrumentsget_instruments
get_tickerget_latest_signed_feedsget_option_settlement_pricesget_spot_feed_historyget_spot_feed_history_candlesget_funding_rate_historyget_trade_historyget_option_settlement_historyget_liquidation_historyget_interest_rate_historyget_transaction
get_marginmargin_watchvalidate_invite_code
get_pointsget_all_pointsget_points_leaderboardget_descendant_treeget_tree_rootsget_swell_percent_pointsget_vault_assetsget_etherfi_effective_balancesget_kelp_effective_balancesget_bridge_balancesget_ethena_participantsget_vault_shareget_vault_statisticsget_vault_balancesestimate_integrator_pointscreate_subaccount_debugdeposit_debugwithdraw_debugsend_quote_debugexecute_quote_debugget_invite_coderegister_inviteget_timeget_live_incidentsget_maker_programsget_maker_program_scores)getpostr   )>get_accountcreate_subaccountget_subaccountget_subaccountsget_all_portfolioschange_subaccount_labelget_notificationsvupdate_notificationsdepositr   transfer_erc20transfer_positiontransfer_positionsorderreplaceorder_debug	get_order
get_ordersget_open_orderscancelcancel_by_labelcancel_by_noncecancel_by_instrument
cancel_allcancel_trigger_orderget_order_historyr   get_deposit_historyget_withdrawal_historysend_rfq
cancel_rfqcancel_batch_rfqsget_rfqs	poll_rfqs
send_quotecancel_quotecancel_batch_quotes
get_quotespoll_quotesexecute_quoterfq_get_best_quoter   get_collateralsget_positionsr   get_subaccount_value_historyexpired_and_cancelled_historyget_funding_historyget_interest_historyget_erc20_transfer_historyr   	liquidateget_liquidator_historysession_keysedit_session_keyregister_scoped_session_keyget_mmp_configset_mmp_config	reset_mmpset_cancel_on_disconnectr   r   r   requiredCredentials)apiKeysecretwalletAddress
privateKey
exceptionsz-32000z-32100z-32700z-32600z-32601z-32602z-326039000100001000110002100031000410005100061000710008100091001010011100121001310014110001100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281105011051110521105311054110551110011101111021110311104111051110611107112001120111202112031200012001120021200313000140001400114002140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321600016001161001700017001170021700317004170051700617007180001800118002180031800418005)180061800719000)exactbroadprecisionMode *0x0ad42b8e602c2d3d475ae52d678cf63d84ab2749)deriveWalletAddressr'   )commonCurrenciesoptions)deep_extendsuperr$   describer    r   r   r   r   r   r   r!   )self	__class__s    I/var/www/html/volatility/venv/lib/python3.11/site-packages/ccxt/derive.pyr  zderive.describe   s   fd 3 3 < < > > RA
(RA
HRA
 RA
 t	RA

 RA
 RA
 4RA
 4RA
  \\\ %\ 	\
 %\ %\ U\ $U\ '\ "4\ '\ t\ \ )%\ $U\   !\" /#\ \$ ,U%\& 0'\( t)\* +\, (-\. "5/\0 %e1\2 T3\4  5\6 7\8 &u9\: +E;\< )%=\> /?\@ &tA\B $TC\D 'E\ \ \F (G\H "4I\J &uK\L (M\N  O\P *:Q\R +ES\T &tU\V #DW\X *4Y\Z $U[\\ "5]\^ *5_\` +Ea\b tc\d  e\f %eg\ \ \h $Ui\j "4k\l +Em\n o\p !%q\r &us\t  u\v ew\x $Uy\z +E{\| %e}\~ "4\@ eA\B !%C\D tE\F #DG\H  I\ \ \J $UK\L !$M\N %eO\P )%Q\R tS\T U\V TW\X tY\Z "5[\\ #E]\^  _\` !%a\b "5c\d #De\f g\h #Ei\j &uk\ \l  $!&#(!!w\ \ \RA
L  MRA
l mRA
n i?A 
 EF  16CA oRA
L  -3 3 3	8 8t  ? ? ?Au| |MRA
F  GRA
J "!%"	$ $KRA
V {/{/{ j{ j	{
 j{ l{ l{ L{ Z{ Z{ Z{ Z{ \{ Z{ Z{  Z!{" Z#{ {$ Z%{& \'{( .){* .+{, ]-{. ]/{0 .1{2 \3{4 \5{6 \7{8 \9{: ];{< \={> \?{@ \A{B \C{D \E{ { {F \G{H \I{J \K{L \M{N \O{P \Q{R \S{T \U{V .W{X \Y{Z \[{\ \]{^ \_{` \a{b Zc{d \e{f \g{ { {h \i{j \k{l \m{n \o{p \q{r \s{t \u{v \w{x \y{z \{{| \}{~ \{@ \A{B \C{D \E{F \G{H \I{ { {J \K{L \M{N \O{P ZQ{R ZS{T ZU{V ZW{X \Y{Z Z[{\ Z]{^ Z_{` Za{b Zc{d Ze{f Zg{h \i{j Zk{ { {l Zm{n Zo{p Zq{r Zs{t Zu{v Zw{x 0y{z \{{| Z}{~ Z{@ ZA{B 0C{D ZE{F 0G{H ZI{J 0K{L ZM{ { {N 0O{P 0Q{R 0S{T ZU{V ZW{X ZY{Z Z[{\ Z]{^ Z_{` Za{b Zc{d Ze{f Zg{h Zi{j Zk{l Zm{n Zo{ {p (''u{ { {x{ WRA
V YWRA
X! (*B ]RA
 RA
 RA
 R R R	    enablec                 l    t          t          |                               |           || j        d<   d S )NsandboxMode)r  r$   set_sandbox_moder  )r  r  r  s     r  r  zderive.set_sandbox_mode  s3    fd,,V444&,]###r  c                 X    |                      |          }|                     |d          S )aS  
        fetches the current integer timestamp in milliseconds from the exchange server

        https://docs.derive.xyz/reference/post_public-get-time

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        result)publicPostGetTimesafe_integer)r  paramsresponses      r  
fetch_timezderive.fetch_time  s/     ))&11   8444r  c                 b   i }|                      |          }|                     |dg           }t          dt          |                    D ]b}||         }|                     |d          }|                     |          }|                     |d|ddddddddddddd|d          ||<   c|S )a   
        fetches all available currencies on an exchange

        https://docs.derive.xyz/reference/post_public-get-all-currencies

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        r  r   currencyNminmax)r   r   )r'   r(   code	precisionactivefeenetworksr   r   limitsinfo)publicGetGetAllCurrencies	safe_listrangelensafe_stringsafe_currency_codesafe_currency_structure)	r  r  r  tokenResponse
currenciesir  
currencyIdr  s	            r  fetch_currencieszderive.fetch_currencies  s     66v>>b ^^M8R@@
q#j//** 	 	A!!}H))(J??J**:66D77 !    $#   
  $#! !	 	 !)9 9  F4LL, r  c                     |                      |          }|                     |          }|                     |          }|||g\  }}}|                     ||          }|                     ||          }|S )a   
        retrieves data on all markets for bybit

        https://docs.derive.xyz/reference/post_public-get-all-instruments

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        )fetch_spot_marketsfetch_swap_marketsfetch_option_marketsarray_concat)	r  r  spotMarketsPromiseswapMarketsPromiseoptionMarketsPromisespotMarketsswapMarketsoptionMarketsr  s	            r  fetch_marketszderive.fetch_markets  s     "44V<<!44V<<#88@@3EGY[o2p/[-\ "";<<""6=99r  c                     ddd}|                      |                     ||                    }|                     |di           }|                     |dg           }|                     |          S )NFerc20expiredinstrument_typer  instrumentspublicPostGetAllInstrumentsextend	safe_dictr  parse_marketsr  r  requestr  r  datas         r  r  zderive.fetch_spot_marketsY  su    &
 
 33DKK4P4PQQ(B77~~fmR88!!$'''r  c                     ddd}|                      |                     ||                    }|                     |di           }|                     |dg           }|                     |          S )NFperpr  r  r  r  r  s         r  r  zderive.fetch_swap_marketsc  su    %
 
 33DKK4P4PQQ(B77~~fmR88!!$'''r  c                     ddd}|                      |                     ||                    }|                     |di           }|                     |dg           }|                     |          S )NFr7   r  r  r  r  r  s         r  r  zderive.fetch_option_marketsm  su    '
 
 33DKK4P4PQQ(B77~~fmR88!!$'''r  marketc                    |                      |d          }d}d}d}d}d }d }|                      |d          }	|                      |d          }
|                     |	          }|                     |
          }|                      |d          }|dz   |z   }d }d }d }d }d }d }|dk    rd}d	}n|d
k    r0d}d}|                     |          }|dz   |z   dz   |z   }d}d}d}d}n|dk    rd}|                     |          }d}d}d}|                     |d          }|                     |d          }|                     |d          }|                      |d          }|dz   |z   dz   |z   dz   |                     |          z   dz   |                     |          z   dz   |z   }|dk    rd}nd}d}d}|                     i d|d|d|d|d|d|	d|
d|d|d	|d |d|d!dd|d"|                     |d#          d$|p|d%|||rd nd&|| 	                    |          | 
                    |d'          | 
                    |d(          ||| 
                    |d)          | 
                    |d*          d+d d d,| 
                    |d-          | 
                    |d.          d,d d d,d d d,d/d |d0          S )1Nr  FTbase_currencyquote_currencyinstrument_name/r  r3   r  USDC:r5   r7   option_detailsexpirystrikeoption_type-Pputcallr'   symbolbasequotesettlebaseIdquoteIdsettleIdtyper4   r6   r  	is_activecontractlinear   taker_fee_ratemaker_fee_rateamount_step	tick_size)amountpricer  minimum_amountmaximum_amount)leverager  r  cost)inversecontractSizer  expiryDatetimetakermakerr  
optionTyper  r  createdr  )r  r  r  safe_timestampr  yymmddnumber_to_stringsafe_market_structure	safe_booliso8601safe_number)r  r  r  r3   r4   r5   r7   r  r  r  r  r  r  marketIdr  r  r  r  r  r  optionLetter
marketTypeoptionDetailss                          r  parse_marketzderive.parse_marketw  s8   (9::!!&/::""6+;<<&&v..''00##F,=>>e#
 7??DJJV^^FH,,X66FCZ%'#-6FDFGJJXH,,X66FFF!J NN63CDDM((AAF&&}h??F++M=IILCZ%'#-6<t{{6?R?RRUXX[_[p[pqw[x[xx{~~  BN  NFs"""

#
FG)) 2+
(2+
f2+
 D2+
 U	2+

 f2+
 f2+
 w2+
 2+
 J2+
 D2+
 f2+
 D2+
 e2+
 f2+
 dnnV[992+
  !2+
" f#2+
$ %)1DD"ll622%%f.>??%%f.>??$**6=AA))&+>>    
  ++F4DEE++F4DEE 
   
    $ c2+
 2+
 2+
 2 2 2	r  r  c                    |                                   |                     |          }d|d         i}|                     |                     ||                    }|                     |di           }|                     ||          S )a  
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://docs.derive.xyz/reference/post_public-get-ticker

        :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  r'   r  )load_marketsr  publicPostGetTickerr  r  parse_ticker)r  r  r  r  r  r  r  s          r  fetch_tickerzderive.fetch_ticker  s     	V$$vd|
 ++DKK,H,HIIz ~~h"55  v...r  Ntickerc           
         |                      |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t          j        |d          dd d d |                      |d          |                      |d          |d|          S )Nr  	timestampstatspercent_changer  datetimehighlowbidbest_bid_price	bidVolumebest_bid_amountaskbest_ask_price	askVolumebest_ask_amountvwapopencloselastpreviousClosechange
percentage100averageindex_price
mark_price)
baseVolumequoteVolume
indexPrice	markPricer  )r  safe_integer_omit_zerosafe_symbolr  safe_tickerr  r"   
string_mul)r  r  r  r  r  r  r  r.  s           r  r  zderive.parse_ticker,  s   p ##F,=>>//DD	!!(F33vw//!!%)9:: !
f!
!
 Y//!
 D$$UF33	!

 4##E511!
 4##F,<==!
 ))&2CDD!
 4##F,<==!
 ))&2CDD!
 D!
 D!
 T!
 D!
 T!
 f!
  ',VU;;!!
" t#!
$ **6=AA))&,??-!
 !
 !
. /  	r  sincelimitc                    |                                   i }d}| |                     |          }|d         |d<   ||dk    rd}||d<   |||d<   |                     |d          }|                     |dg          }|||d<   |                     |                     ||                    }|                     |d	i           }	|                     |	d
g           }
|                     |
|||          S )ar  
        get the list of most recent trades for a particular symbol

        https://docs.derive.xyz/reference/post_public-get-trade-history

        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: the latest time in ms to fetch trades for
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/?id=public-trades>`
        Nr'   r  i  	page_sizefrom_timestampuntilto_timestampr  trades)	r  r  r  omitpublicPostGetTradeHistoryr  r  r  parse_trades)r  r  r<  r=  r  r  r  rA  r  r  r  s              r  fetch_tradeszderive.fetch_trades  s    	[[((F)/G%&t||#(GK (-G$%!!&'226G9--&+GN#11$++gv2N2NOOB (B77~~fh33  vue<<<r  tradec                    |                      |d          }|                     ||          }|                     |d          }d|                      |d          d}|                     ||                      |d          |                      |d          ||                     |d          d |                      |d	          |                      |d
          |                      |d          d ||                     |          |d|          S )Nr  r  r  	trade_fee)r  r   trade_idorder_id	directionliquidity_roletrade_pricetrade_amount)r  r'   r   r  sider  takerOrMakerr  r  r   r  r  r  )r  r9  r  
safe_tradesafe_string_lowerr  )r  rH  r  r  r  r  r  s          r  parse_tradezderive.parse_trade  s!   2 ##E+<==!!(F33%%e[99	$$UK88
 
 ""5*55%%eZ88**5+>> ,,U4DEE%%e];;&&un=="Y// 
  
   	r  c           
         |                                   |                     |          }d|d         i}|||d<   |                     |d          }|                     |dg          }|||d<   |                     |                     ||                    }|                     |di           }	|                     |	dg           }
g }t          d	t          |
                    D ]h}|
|         }|                     |d
          }|
                    ||d         |                     |d          ||                     |          d           i|                     |d
          }|                     ||d         ||          S )aY  
        fetches historical funding rate prices

        https://docs.derive.xyz/reference/post_public-get-funding-rate-history

        :param str symbol: unified symbol of the market to fetch the funding rate history for
        :param int [since]: timestamp in ms of the earliest funding rate to fetch
        :param int [limit]: the maximum amount of funding rate structures to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `funding rate structures <https://docs.ccxt.com/?id=funding-rate-history-structure>`
        r  r'   Nstart_timestamprA  rB  r  funding_rate_historyr   r  r  funding_rate)r  r  fundingRater  r  )r  r  r  rD  publicPostGetFundingRateHistoryr  r  r  r  r  appendr  r  sort_byfilter_by_symbol_since_limit)r  r  r<  r=  r  r  r  rA  r  r  r  ratesr  entryr  sorteds                   r  fetch_funding_rate_historyz!derive.fetch_funding_rate_history  s    	V$$vd|
 ).G%&!!&'226G9--&+GN#77GV8T8TUU (B77~~f&<bAAq#d))$$ 		 		AGE))%==ILL *#//~FF& LL33      e[11009I5RWXXXr  c                     |                      |dd|          }|                     |d          }|                     |          S )al  
        fetch the current funding rate

        https://docs.derive.xyz/reference/post_public-get-funding-rate-history

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `funding rate structure <https://docs.ccxt.com/?id=funding-rate-structure>`
        Nr  r   )rb  r  parse_funding_rate)r  r  r  r  r  s        r  fetch_funding_ratezderive.fetch_funding_rate)  sF     2264FKK ~~h**&&t,,,r  c                    |                      |d          }|                     |d          }i d|d|dd dd dd dd dd dd d	|                     |d	          d
|d|                     |          dd dd dd dd dd dd dd iS )Nr  r  r  r7  r6  interestRateestimatedSettlePricer  rZ  fundingTimestampfundingDatetimenextFundingRatenextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetimeinterval)r  r  r  r  )r  r  r  r  ri  s        r  rd  zderive.parse_funding_rateE  s.   !!(H55,,X{CC
H
f
 
 $	

 D
 #D
 
 
 4++HmDD
  0
 t||,<==
 t
 #D
 "4
 "4
  '!
" &t#
$ %
 
 	
r  c                 L   |                      |                     g d|          dd          }|                     | j        dd          }|rdnd}|                     |          }|                     d          }|                      |                     |||          dd	          S )
N)bytes32uint256rt  addressrs  rt  ru  ru  keccakbinaryr  F@9bcf4dc06df5d8bf23af818d5716491b995020f377d3b7b64c29ed14e3dd1105@d96e5f90797da7ec8dc4e276260c7f3f87fedf68775fbe1ef116e996fc60441b1901hex)hasheth_abi_encoder  r  base16_to_binarybinary_concat)r  r   accountHashr  DOMAIN_SEPARATORbinaryDomainSeparatorprefixs          r  hash_order_messagezderive.hash_order_message]  s    ii 3 3 5
 5
 5
! !X' ' nnT\=%HHbm  w]]  uw $ 5 56F G G&&v..yy++F4I;WWYachiiir  c                 x    |                      |          }|                     |dd          |dd                    S N)r  	sign_hash)r  r   r  	hashOrders       r  
sign_orderzderive.sign_orderg  s:    ++E22	~~ioz#$$/?@@@r  c           
         |                      |          }|                     |          }|                     d          }|                     d          }|                     ||                      d          ||                      |                     |                              }d|                     |                     ||          dd          z   S )N190azEthereum Signed Message:0xrv  r{  )encodebinary_lengthr~  r  r
  r|  )r  messagebinaryMessagebinaryMessageLengthx19newliner  s          r  hash_messagezderive.hash_messagek  s    G,,"00??##D))''--##C5O)P)PRY[_[f[fgkg|g|  ~Q  hR  hR  \S  \S  T  Tdii 2 26= I I8UZ[[[[r  c                 ^   |                                   |                     |dd          |dd          dd           }|d         }|d         }|                     |                     d|d                             }d|                    dd	          z   |                    dd	          z   |z   S )
Nr  	secp256k1rs   vr  @   0)check_required_credentialsecdsaint_to_base16sumrjust)r  r|  r  	signaturer  r  r  s          r  r  zderive.sign_hashs  s    '')))JJtCDDz:cdd+;[$OO	cNcNtxxIcN;;<<aggb#&&&S)9)99A==r  c                 d    |                      |                     |          |dd                    S r  )r  r  )r  r  r  s      r  sign_messagezderive.sign_message{  s-    ~~d//88*STT:JKKKr  1000000000000000000numc                 ,    t          j        ||          S N)r"   r;  )r  r  decs      r  parse_unitszderive.parse_units~  s    !#s+++r  r  rQ  r  r  c                 	   |                                   |                     |          }|t          | j        dz             d}|                     d|          \  }}|                     |dd          }	|                     |dd          }
|                     |dd	          }|                     |d
          }|                                }|                                }| 	                                }| 
                    |d|                                 dz             }|                     d          }|                     | j        dd          }|rdnd}|                     |          }d}|                     |dd          \  }}|t          | j        dz             |                     |          }|                     |          }|                     |                     g d|d         d         |                     |d         d                   |                     |                     |                    |                     |                     |                     ||                              |                     |                     |                    ||dk    g          dd          }d}|                     d|          \  }}|                     |||||||| j        g| j                  }|d         |||||||||                     | j        dd          | j        d}|
 |
|d<   |
r|rt7          | j        dz             |d|d	<   n|||d	<   |                     |d          }|                     |d           }|                     |d!d"          }|'|                     |d#|          }||d$<   d%|d&<   ||d!<   n(|&|                     |d#|          } | |d$<   d'|d&<   ||d!<   |                     |d(          }!|!|!|d)<   ||d*<   |                     |g d+          }d}"|	r*|                     |                     ||                    }"n)|                      |                     ||                    }"| !                    |"d,          }#| !                    |#d-          }$|$| !                    |#d.          }$| "                    |$|          }%||%d/<   |%S )0a  
        create a trade order

        https://docs.derive.xyz/reference/post_private-order

        :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 fulfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.subaccount_id]: *required* the subaccount id
        :param float [params.triggerPrice]: The price a trigger order is triggered at
        :param dict [params.takeProfit]: *takeProfit object in params* containing the triggerPrice at which the attached take profit order will be triggered(perpetual swap markets only)
        :param float [params.takeProfit.triggerPrice]: take profit trigger price
        :param dict [params.stopLoss]: *stopLoss object in params* containing the triggerPrice at which the attached stop loss order will be triggered(perpetual swap markets only)
        :param float [params.stopLoss.triggerPrice]: stop loss trigger price
        :param float [params.max_fee]: *required* the maximum fee you are willing to pay for the order
        :returns dict: an `order structure <https://docs.ccxt.com/?id=order-structure>`
        Nz( createOrder() requires a price argumentrE   r   F
reduceOnlyreduce_onlytimeInForcetime_in_forcepostOnlysignature_expiry_sec v @4d7a9f27c403ff9c0f19bce61d76d82f9aa29f8d6d4b0c5474607d9770d1af17r  *0x87F2863866D85E3192a35A73b388BD625D83f2be*0xB8D20c2B7a1Ad2EE33Bc50eF10876eD3035b5e7bmax_feez4 createOrder() requires a max_fee argument in paramsru  uintintr  r  r  boolr  base_asset_addressbase_asset_sub_idbuyrv  rw  r'   r  )r  rM  
order_typenoncer  limit_pricer  subaccount_idr  referral_codesigner4 cannot use reduce only with post only time in force	post_onlystopLoss
takeProfittrigger_price_typemarktriggerPricetrigger_pricestoplosstrigger_type
takeprofitclientOrderIdlabelr  )r  r  r  r  r  r   r  	stopPricer  r  r  r  r  r  raw_datar   r  )#r  r  r   r'   handle_derive_subaccount_idr  safe_bool_2safe_string_lower_2lowermillisecondsr  secondsr~  r  r
  handle_option_and_paramsr|  r}  parse_to_numericconvert_to_big_intr  amount_to_precisionhandle_derive_wallet_addressr  r  r  r  r   
safe_valuerD  privatePostOrderDebugr  privatePostOrderr  parse_order)&r  r  r  rQ  r  r  r  r  subaccountIdr   r  r  r  	orderType	orderSider  signatureExpiryACTION_TYPEHASHr  TRADE_MODULE_ADDRESSpriceStringmaxFeemaxFeeStringamountStringtradeModuleDataHashr  r  r  r  r  triggerPriceTypestopLossPricetakeProfitPricer  r  r  rawOrderr   s&                                         r  create_orderzderive.create_order  sr   * 	V$$=#DG.X$XYYY#??vVVf~~ffe44%%flMJJ
..v}oVV>>&*55JJLL	JJLL	!!##++F4JDLLNN]dLdee//0rssnnT\=%HHP[   OKK  cO++E2266v}iXX>#DG.d$deee,,V44,,V44"ii(;(; =
 =
 =
 6N/0!!&.1D"EFF##D$4$4[$A$ABB##D$4$4T5M5MfVb5c5c$d$dee##D$4$4\$B$BCC

) 
) h
  
  #&*&G&GW]&^&^#VOO 	%
 ?	 		  &d|"#"&#)$3!--dlDBnoo(
 
 !%/GM" eh e"47-c#cddd'2GO$$$'2GO$??6:66__V\::
++F4H&QQ ,,X~xPPM'4GO$&0GN#,<G())#"..z>:VVO'6GO$&2GN#,<G()((AA$,GG(6  $d  $d  $d  e  e 	K11$++gv2N2NOOHH,,T[[&-I-IJJHH (33>>&*55~~fg66H  622fr  r'   c                    |                                   |                     |          }d}	|                     d|          \  }	}|                     |dd          }
|                     |dd          }|                     |d          }|                                }|                                }|                                 }|                     |d| 	                                d	z             }| 
                    d
          }|                     | j        dd          }|rdnd}|                     |          }|                     |dd          }|                     |          }|                     |                     g d|d         d         |                     |d         d                   |                     |                     |                    |                     |                     |                     ||                              |                     |                     |                    |	|dk    g          dd          }d}|                     d|          \  }}|                     ||	|||||| j        g| j                  }|d         ||||||||	|| j        d}|
 |
|d<   |
r|rt1          | j        dz             |d|d<   n|||d<   |                     |d          }|||d<   ||d<   |                     |g d          }|                     |                     ||                    }|                     |d           }|                     |d!          }|                     ||          }|S )"a  
        edit a trade order

        https://docs.derive.xyz/reference/post_private-replace

        :param str id: order id
        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of currency you want to trade in units of base currency
        :param float [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.subaccount_id]: *required* the subaccount id
        :returns dict: an `order structure <https://docs.ccxt.com/?id=order-structure>`
        NrJ   r  r  r  r  r  r  r  r  r  Fr  r  r  r  r  r  r  r  r  rv  rw  r'   )r  order_id_to_cancelrM  r  r  r  r  r  r  r  r  r  r  r  r  r  )r  r  r  r  r  r  r  r   )r  r  r  r  r  r  r  r  r  r  r~  r  r
  r  r|  r}  r  r  r  r  r  r  r  r  r   r'   rD  privatePostReplacer  r  r  ) r  r'   r  r  rQ  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   s                                    r  
edit_orderzderive.edit_order=  s     	V$$#??VTTf%%flMJJ
..v}oVV>>&*55JJLL	JJLL	!!##**63I4<<>>\cKcdd//0rssnnT\=%HHP[   OKK  cO++E22''	3??,,V44"ii(;(; =
 =
 =
 6N/0!!&.1D"EFF##D$4$4[$A$ABB##D$4$4T5M5MfVb5c5c$d$dee##D$4$4\$B$BCC

) 
) h
  
  #&*&G&GU[&\&\#VOO 	%
 ?	 		  &d|"$"#"&#)$3(
 
 !%/GM" eh e"47-c#cddd'2GO$$$'2GO$((AA$,GG(6#}#}#}~~**4;;w+G+GHHV (33>>&'22  622r  c                 t   |t          | j        dz             |                                  |                     |          }|                     |ddd          }d}|                     d|          \  }}|                     |ddg          }|d         |d}|                     |d	          }|                     |d
|          }	|	du}
d}|
rG|	|d
<   |                     |d	d
g          }|                     | 	                    ||                    }nZ||d<   |r*| 
                    | 	                    ||                    }n)|                     | 	                    ||                    }d|i}|                     |d          }|
r|	|d<   | 	                    |                     ||          |          S )a  

        https://docs.derive.xyz/reference/post_private-cancel

        cancels an open order
        :param str id: 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 boolean [params.trigger]: whether the order is a trigger/algo order
        :param str [params.subaccount_id]: *required* the subaccount id
        :returns dict: An `order structure <https://docs.ccxt.com/?id=order-structure>`
        Nz) cancelOrder() requires a symbol argumenttriggerstopFr=   r'   )r  r  r  r  rL  r  r  client_order_id)r   r'   r  r  r  r  rD  r  privatePostCancelByLabelr  privatePostCancelTriggerOrderprivatePostCancelr  r  )r  r'   r  r  r  	isTriggerr  r  clientOrderIdUnifiedclientOrderIdExchangeSpecificisByClientOrderr  extendParamsr   s                 r  cancel_orderzderive.cancel_order  s    >#DG.Y$YZZZV,,$$VYFF	#??vVVf6Iv#677%d|)
 
  $//HH(,(8(8J^(_(_%7tC 		P<GGYYv'ABBF44T[[&5Q5QRRHH"$GJ P==dkk'SY>Z>Z[[11$++gv2N2NOOX '/x22 	L.KL*+{{4++E6::LIIIr  c                    |                                   d}||                     |          }d}|                     d|          \  }}d|i}d}|5|d         |d<   |                     |                     ||                    }n)|                     |                     ||                    }|                     d|i          gS )a  

        https://docs.derive.xyz/reference/post_private-cancel-by-instrument
        https://docs.derive.xyz/reference/post_private-cancel-all

        cancel all open orders in a market
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.subaccount_id]: *required* the subaccount id
        :returns dict: an list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        Nr;   r  r'   r  r  )r  r  r  privatePostCancelByInstrumentr  privatePostCancelAll
safe_order)r  r  r  r  r  r  r  s          r  cancel_all_orderszderive.cancel_all_orders8  s     	[[((F#??@QSYZZf\
 )/G%&99$++gv:V:VWWHH00Wf1M1MNNH  23344r  c           	         |                                   d}|                     |dd          \  }}|r|                     d||||dd          S |                     |ddd          }|                     |ddg          }d}|                     d|          \  }}d	|i}d}	| |                     |          }	|	d
         |d<   |||d<   nd|d<   |rd|d<   |                     |                     ||                    }
| 	                    |
d          }| 
                    |d          }|4|                     |d          }| 
                    |d          }||k    rg S |                     |d          }|                     ||	||          S )a,  
        fetches information on multiple orders made by the user

        https://docs.derive.xyz/reference/post_private-get-orders

        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.paginate]: set to True if you want to fetch orders with pagination
        :param boolean [params.trigger]: whether the order is a trigger/algo order
        :param str [params.subaccount_id]: *required* the subaccount id
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        Frt   paginatepage  r  r  Nr  r'   r  r?  untriggeredstatusr  
pagination	num_pagesorders)r  r   fetch_paginated_call_incrementalr  rD  r  r  privatePostGetOrdersr  r  r  r  r  parse_orders)r  r  r<  r=  r  r  r  r  r  r  r  r  r  r  currentPager  s                   r  fetch_orderszderive.fetch_ordersb  s    	88PZ[[& 	s88PUW\^dflnqrrr$$VYFF	6Iv#677#??vVVf\
 [[((F)/G%&#(GK  #&GK  	. -GH,,T[[&-I-IJJ\ x22  00l;;J++JDDKk!!	h//  >>>r  c                     |                                   |                     |ddi          }|                     ||||          S )  
        fetches information on multiple orders made by the user

        https://docs.derive.xyz/reference/post_private-get-orders

        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.paginate]: set to True if you want to fetch orders with pagination
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        r  r*  r  r  r  r  r  r<  r=  r  extendedParamss         r  fetch_open_orderszderive.fetch_open_orders  sH     	Vh-?@@  ~FFFr  c                     |                                   |                     |ddi          }|                     ||||          S )r  r  filledr  r  s         r  fetch_closed_orderszderive.fetch_closed_orders  sH     	Vh-ABB  ~FFFr  c                     |                                   |                     |ddi          }|                     ||||          S )a.  
        fetches information on multiple canceled orders made by the user

        https://docs.derive.xyz/reference/post_private-get-orders

        :param str symbol: unified market symbol of the market the orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        r  	cancelledr  r  s         r  fetch_canceled_orderszderive.fetch_canceled_orders  sH     	Vh-DEE  ~FFFr  r  c                 >    ddddd}|                      ||d           S )NIOCFOKGTCPO)iocfokgtcr  r  )r  r  timeInForcess      r  parse_time_in_forcezderive.parse_time_in_force  s4    	
 
 k4@@@r  r  c                 H    |dddddd}|                      |||          S |S )Nr*  closedcanceledrejected)r*  r  r  r"  r  r,  r  r  statusess      r  parse_order_statuszderive.parse_order_status  sB    %"'% H ##Hff===r  r  c                    |                      |d          }||}|                     |dd          }|                     |d          }|                     |d          }||                     ||          }|d         }|                     |d          }|                     |d          }	|                     |d	          }
|                     |d
          }|                     |d          }|                     |d          }|                     |d          }|                     |d          }||rd}nd}|                     |d          }d }d }d }|!|                     |d          }|dk    r|}n|}|                     |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+|          S ),Nr  creation_timestampr  rL  r  r  r  average_pricedesired_amountfilled_amount	order_feer  is_bidrM  r  sellr  r  r  last_update_timestamporder_statusr  r'   r  r  r  r  lastTradeTimestamplastUpdateTimestampr  r  r  r  r  r  rQ  r  r  r  r  r  )r   r  )r1  r  r  	remainingr   rC  r  r  )r  safe_integer_2r  safe_marketrT  r  r  r  r  r5  r.  )r  r  r  r   r  orderIdr  r  r  r1  r  r  r  r  isBidrQ  triggerTyper  r  r  rA  r  r  s                          r  r  zderive.parse_order  sH   h x00=E''2FPP	""5*55##E+<==%%h77F!  66""5/::!!%)9::!!%99uk22**5,??	uh//{33< &&un=="++E?CCLj(( ,"."//:QRR!!%88&&uo>>  
' 
T--eW== 
  
 Y//	 

 !$ 
 "#6 
 d--f55 
 f 
 I 
 433K@@ 
  
 $..>> 
 D 
 U 
 L 
  ! 
" ]# 
$ "  9 
  
  
: ;  	r  c                    |                                   d}|                     d|          \  }}||d}d}| |                     |          }|d         |d<   |||d<   |||d<   |                     |                     ||                    }	|                     |	di           }
|                     |
d	g           }|                     |||||          S )
ag  
        fetch all the trades made from a single order

        https://docs.derive.xyz/reference/post_private-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
        :param str [params.subaccount_id]: *required* the subaccount id
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/?id=trade-structure>`
        Nru   )rL  r  r'   r  r?  r@  r  rC  )r  r  r  privatePostGetTradeHistoryr  r  r  rF  )r  r'   r  r<  r=  r  r  r  r  r  r  rC  s               r  fetch_order_tradeszderive.fetch_order_trades}  s    	#??@RTZ[[f)
 
 [[((F)/G%&#(GK (-G$%224;;w3O3OPPJ (B77"55  vFFFr  c           	         |                                   d}|                     |dd          \  }}|r|                     d||||dd          S d}|                     d|          \  }}d|i}d}| |                     |          }|d         |d	<   |||d
<   |||d<   |                     |                     ||                    }	|                     |	di           }
|                     |d          }|4|                     |
d          }|                     |d          }||k    rg S | 	                    |
dg           }| 
                    |||||          S )a  
        fetch all trades made by the user

        https://docs.derive.xyz/reference/post_private-get-trade-history

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.paginate]: set to True if you want to fetch trades with pagination
        :param str [params.subaccount_id]: *required* the subaccount id
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/?id=trade-structure>`
        Frl   r  r  r  Nr  r'   r  r?  r@  r  r  r  rC  )r  r  r  r  r  rI  r  r  r  r  rF  )r  r  r<  r=  r  r  r  r  r  r  r  r  r  r  rC  s                  r  fetch_my_tradeszderive.fetch_my_trades  s    	88R\]]& 	u88&RWY^`fhnpsttt#??QWXXf\
 [[((F)/G%&#(GK (-G$%224;;w3O3OPPJ (B77  00==J++JDDKk!!	"55  vFFFr  symbolsc                 p   |                                   d}|                     d|          \  }}d|i}|                     |dg          }|                     |                     ||                    }|                     |di           }|                     |dg           }|                     ||          S )a  
        fetch all open positions

        https://docs.derive.xyz/reference/post_private-get-positions

        :param str[] [symbols]: not used by kraken fetchPositions()
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.subaccount_id]: *required* the subaccount id
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/?id=position-structure>`
        Nrx   r  r  	positions)r  r  rD  privatePostGetPositionsr  r  r  parse_positions)r  rM  r  r  r  r  r  rO  s           r  fetch_positionszderive.fetch_positions  s     	#??@PRXYYf\
 6O#455//GV0L0LMMN (B77NN6;;;	##Iw777r  positionc                    |                      |d          }|                     ||          }|                      |d          }d }t          j        |d          rd}nd}|                      |d          }|                      |d          }|                     |d          }|                      |d	          }	t          j        |          }t          j        ||          }
|                     i d
|dd d|                      |d          d|d|                     |          dd d|                      |d          dd d|                      |d          dd dd d| 	                    |
          d| 
                    |d          d| 	                    |	          d| 	                    |          d| 	                    |          dd | 
                    |d          | 	                    |          d d d |d d d d d
          S )Nr  r  r  longshortr  r3  r7  unrealized_pnlr  r'   r  r  r  rA  initialMargininitial_margininitialMarginPercentagemaintenanceMarginmaintenance_marginmaintenanceMarginPercentage
entryPricenotionalr  unrealizedPnl	contractsmarginRatioliquidation_price)
liquidationPricer7  	lastPrice
collateral
marginModerQ  r/  hedgedr  r  )r  rD  r"   	string_gtr  
string_absr;  safe_positionr  parse_numberr  )r  rS  r  r  sizerQ  r  r7  r  unrealisedPnlr_  s              r  parse_positionzderive.parse_positionO  s   > ##H.?@@!!(F33(33T3'' 	DDD''??$$X|<<	%%h0DEE	((3CDD!$''%dI66!! #
H#
$#
 d&&vx88#
 	#

 Y//#
 "4#
 T--h8HII#
 &t#
  !1!1(<P!Q!Q#
 *4#
 $#
 ))(33#
 ((:>>#
 T..}==#
 **400#
  D--l;;!#
" 4##
$ !% 0 0;N O O**955!#7#
 #
 #
   	r  c           	         |                                   d}|                     |dd          \  }}|r|                     d||||dd          S d}|                     d|          \  }}d|i}d}| |                     |          }|d         |d	<   |||d
<   |||d<   |                     |                     ||                    }	|                     |	di           }
|                     |d          }|4|                     |
d          }|                     |d          }||k    rg S | 	                    |
dg           }| 
                    ||||          S )a5  
        fetch the history of funding payments paid and received on self account

        https://docs.derive.xyz/reference/post_private-get-funding-history

        :param str [symbol]: unified market symbol
        :param int [since]: the earliest time in ms to fetch funding history for
        :param int [limit]: the maximum number of funding history structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :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 `funding history structure <https://docs.ccxt.com/?id=funding-history-structure>`
        Fr\   r  r  r  Nr  r'   r  rW  r?  r  r  r  events)r  r  r  r  r  privatePostGetFundingHistoryr  r  r  r  parse_incomes)r  r  r<  r=  r  r  r  r  r  r  r  r  r  r  rq  s                  r  fetch_funding_historyzderive.fetch_funding_history  s    	88AVXbcc& 	{889NPVX]_dflntvyzzz#??@UW]^^f\
 [[((F)/G%&).G%&#(GK 44T[[&5Q5QRR@ (B77  00==J++JDDKk!!	"55!!&&%???r  c           	         |                      |d          }|                     ||          }|                      |d          }|                     d          }|                     |d          }|||||                     |          d d |dS )Nr  fundingr  r  )r  r  r  r  r  r'   r  rate)r  r9  r  r  r  )r  incomer  r  r  rw  r  r  s           r  parse_incomezderive.parse_income  s     ##F,=>>!!(F33	22&&v..%%fk::	"Y//	
 	
 		
r  c                    |                                   d}|                     d|          \  }}d|i}|                     |                     ||                    }|                     |d          }|                     |          S )ak  
        query for balance and get the amount of funds available for trading or funds locked in orders

        https://docs.derive.xyz/reference/post_private-get-all-portfolios

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/?id=balance-structure>`
        NrL   walletr  )r  r  privatePostGetAllPortfoliosr  r  parse_balance)r  r  r  r  r  r  s         r  fetch_balancezderive.fetch_balance  s     	"&*&G&GX^&_&_#V)
 33DKK4P4PQQb (33!!&)))r  c                 R   d|i}t          dt          |                    D ]}||         }|                     |dg           }t          dt          |                    D ]}||         }|                     |                     |d                    }|                     ||          }	|	.|                                 }	|                     |d          |	d<   n4|                     |d          }
t          j        |	d         |
          |	d<   |	||<   | 	                    |          S )Nr  r   collateralsr  r  total)
r  r  r  r  r  r  accountr"   
string_addsafe_balance)r  r  r  r  
subaccountr  jbalancer  r  r  s              r  r}  zderive.parse_balance?	  s3   H
 q#h--(( 	' 	'A!!J..]BGGK1c+..// 
' 
'%a...t/?/?/T/TUU..66?"llnnG'+'7'7'J'JGG$$!--gx@@F'.'9'':JF'S'SGG$&t
'   (((r  r  c                 ~   |                                   d}|                     d|          \  }}d|i}|||d<   |                     |                     ||                    }|                     |          }|                     |di           }	|                     |	d          }
|                     |
||||          S )aZ  
        fetch all deposits made to an account

        https://docs.derive.xyz/reference/post_private-get-deposit-history

        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch deposits for
        :param int [limit]: the maximum number of deposits structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.subaccount_id]: *required* the subaccount id
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/?id=transaction-structure>`
        NrX   r  rW  r  rq  )r  r  privatePostGetDepositHistoryr  safe_currencyr  r  parse_transactionsr  r  r<  r=  r  r  r  r  r  r  rq  s              r  fetch_depositszderive.fetch_depositsS	  s     	#??QWXXf\
 ).G%&44T[[&5Q5QRR& %%d++(B7711&&vxvNNNr  c                 ~   |                                   d}|                     d|          \  }}d|i}|||d<   |                     |                     ||                    }|                     |          }|                     |di           }	|                     |	d          }
|                     |
||||          S )ah  
        fetch all withdrawals made from an account

        https://docs.derive.xyz/reference/post_private-get-withdrawal-history

        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch withdrawals for
        :param int [limit]: the maximum number of withdrawals structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.subaccount_id]: *required* the subaccount id
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/?id=transaction-structure>`
        Nr   r  rW  r  rq  )r  r  privatePostGetWithdrawalHistoryr  r  r  r  r  r  s              r  fetch_withdrawalszderive.fetch_withdrawals	  s     	#??@RTZ[[f\
 ).G%&77GV8T8TUU& %%d++(B7711&&vxvNNNr  transactionr  c                    |                      |d          }|                     |d          }|                      |d          }|dk    r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S )Nassetr  tx_hash0x0r  r'   txidr  ru  addressFrom	addressTotagtagFromtagTor  r  r  r  	tx_statusupdatedcomment)internalr  network)r  r  r  r  parse_transaction_status)r  r  r  r  r  txIds         r  parse_transactionzderive.parse_transaction	  sx    W55%%k;??	Y775==D
K
$
 D
 	

 Y//
 t
 4
 
 4
 t
 T
 D
 d&&{H==
 
 d33D4D4D[R]4^4^__
  t!
" t#
$ )
 
 
 	
r  c                 :    ddd}|                      |||          S )Nokfailed)settledrevertedr,  r3  s      r  r  zderive.parse_transaction_status	  s.     
 
 &&999r  
methodNamer  c                     d }|                      ||d          \  }}||dk    r|| j        d<   ||gS |                     | j        d          }|||gS t          | j        dz   |z   dz             )Nr  r   z^() requires a subaccount_id parameter inside 'params' or exchange.options['subaccount_id']=ID.r  r  r  r   r'   )r  r  r  derivesubAccountIdoptionsWallets        r  r  z"derive.handle_derive_subaccount_id	  s    !%)%B%B6:Wf%g%g"F*1Cr1I1I,>DL)&//((GG$!6**#
 :  >b  !b  c  c  	cr  c                     d }|                      ||d          \  }}||dk    r|| j        d<   ||gS |                     | j        d          }|||gS t          | j        dz   |z   dz             )Nr  r  r  z() requires a deriveWalletAddress parameter inside 'params' or exchange.options['deriveWalletAddress'] = ADDRESS, the address can find in HOME => Developers tab.r  )r  r  r  r  r  s        r  r  z#derive.handle_derive_wallet_address	  s    "&*&C&CFJXm&n&n#V+2E2K2K2EDL./'00((7LMM$!6**#
 :  >e  !e  f  f  	fr  httpCodereasonurlmethodheadersbodyc
                 P   |sd S |                      |d          }
|
|                     |
d          }| j        dz   |                     |          z   }|                     | j        d         ||           |                     | j        d         ||           t          |          d S )Nerrorr  r  r  r  )r  r  r'   jsonthrow_broadly_matched_exceptionr  throw_exactly_matched_exceptionr   )r  r  r  r  r  r  r  r  requestHeadersrequestBodyr  	errorCodefeedbacks                r  handle_errorszderive.handle_errors	  s     	4x11((77Iw}tyy':'::H001I4QYZZZ001I9V^___)))tr  r   GETc                 T   | j         d         |         dz   |z   }|dk    rddi}|dk    rdt          |                                           }|                     || j                  }	|                     | j        d          |d<   ||d	<   |	|d
<   |                     |          }||||dS )Nr   r  POSTzContent-Typezapplication/jsonr   r  zX-LyraWalletzX-LyraTimestampzX-LyraSignature)r  r  r  r  )r   strr  r  r  r  r  r  )
r  pathr   r  r  r  r  r  nowr  s
             r  signzderive.sign	  s    is#c)D0V 2G i$++--.. --c4?CC	*.*:*:4<I^*_*_'-0)*-6)*99V$$DfdwOOOr  r  )r  )L__name__
__module____qualname__r   r  r  r  r  r   r  r   r   r  r  r  r  dictr  r  r   r  r  r
   r   rG  rU  r   rb  r   re  rd  r  r  r  r  r  r  r   r   floatr   r  r  r  r	  r   r  r  r   r#  r.  r5  r  rJ  rL  r   r   rR  ro  rt  ry  r   r~  r}  r   r  r  r	   r  r  r  r  r  r  r  __classcell__)r  s   @r  r$   r$      s	       S# S S S S S Sj-t - - - - - - !# 5 5 5 5$ ') V VZ V V V Vp $& < <$v, < < < <| )+ ( (tF| ( ( ( ( )+ ( (tF| ( ( ( ( +- ( (f ( ( ( (d4 dF d d d dL 02 M/ M/3 M/f M/ M/ M/ M/^T T4 T T6 T T T Tl 6:UW @= @=3 @=s @=# @=\`af\g @= @= @= @=D. . .v . . . . .` 8<$]ajl 3Y 3Y 3YC 3YWZ 3Y 3Y 3Y 3Yj 68 - - -K - - - -8
 
6 
[ 
 
 
 
0j j jA A A\ \ \> > >L L L, ,s , , , , gksu z z3 zi zy zRW z`c z z z zx `drv  @B a aS a# aY ai aY\ alo a a a aF 37r VJ VJs VJC VJ VJ VJ VJp /32 (5 (5 (5 (5 (5 (5T *.Dt\^ [? [?3 [?c [? [?cghmcn [? [? [? [?z /3TXac G G G3 Gc Ghlmrhs G G G G" 154VZce G G# GS GPS Gjnotju G G G G" 37TX\eg G GC Gs GRU G G G G"As A A A A
 
 
 
 
t tD t& tE t t t tl 9=4^bkm DG DGS DG# DGS DGX[ DG DG DG DGL -1tRV_a MG MGc MG MGC MG MG MG MG^ 26b ;8 ;8w ;8T(^ ;8 ;8 ;8 ;8zI It IV I I I IV 37TX\eg G@ G@C G@s G@RU G@ G@ G@ G@R
 
6 
 
 
 
2 $& A* A*( A* A* A* A*F) ) ) ) )( *.Dt\^ +O +O3 +Oc +O +Ocghsct +O +O +O +OZ -1tRV_a +O +Oc +O +OC +Ofjkvfw +O +O +O +OZ&
 &
T &
X &
Q\ &
 &
 &
 &
P:s : : : :	cc 	c4 	c 	c 	c 	c	fs 	fD 	f 	f 	f 	f
c 
3 
S 
# 
X\ 
dg 
 
 
 
 &eBSW P P P P P P P Pr  r$   N)(ccxt.base.exchanger   ccxt.abstract.deriver   ccxt.base.typesr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   typingr   ccxt.base.errorsr   r   r   r   r   r   r   r    ccxt.base.decimal_to_precisionr!   ccxt.base.preciser"   r$    r  r  <module>r     s7   ( ' ' ' ' ' , , , , , , B  B  B  B  B  B  B  B  B  B  B  B  B  B  B  B  B  B  B  B  B  B  B  B  B  B  B  B  B  B  B  B  B  B  B  B  B  B  B  B  B  B       * * * * * * 0 0 0 0 0 0 . . . . . . ' ' ' ' ' ' . . . . . . ) ) ) ) ) ) * * * * * * . . . . . . 4 4 4 4 4 4 % % % % % %u'P u'P u'P u'P u'PX{ u'P u'P u'P u'P u'Pr  