
    !:h                       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'y)    )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dSdededefdZddi fdededede
e   fdZdSd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dSdedefdZd Zd Z d Z!d Z"d Z#dTd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d/Z2d0efd1Z3dSd2edede-fd3Z4dddi fd&edededefd4Z5dddi fdededefd5Z6di fd6e7de
e8   fd7Z9dSd8edefd9Z:dddi fdededefd:Z;dSd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d@ZBdSdAedBeCde@fdCZDd0efdDZEdEedFefdGZFdEedFefdHZGdIeHdJedKedLedMedNefdOZIdPdQi ddfdRZJ xZKS )Uderive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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    E/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/derive.pyr  zderive.describe   s   fd < > 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	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 R	    enablec                 J    t         t        |   |       || j                  d<   y )NsandboxMode)r  r$   set_sandbox_moder  )r  r  r  s     r  r  zderive.set_sandbox_mode  s     fd,V4&,]#r  c                 H    | j                  |      }| j                  |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   844r  c                 (   i }| j                  |      }| j                  |dg       }t        dt        |            D ]S  }||   }| j	                  |d      }| j                  |      }| j                  |d|ddddddddddddd|d      ||<   U |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**:6D77 !    $# 
  $#!	 !)9 F4L		4 r  c                     | j                  |      }| j                  |      }| j                  |      }|||g\  }}}| j                  ||      }| j                  ||      }|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  sx     "44V<!44V<#88@3EGY[o2p/[-\ "";<""6=9r  c                     ddd}| j                  | j                  ||            }| j                  |di       }| j                  |dg       }| j	                  |      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  sa    &
 33DKK4PQ(B7~~fmR8!!$''r  c                     ddd}| j                  | j                  ||            }| j                  |di       }| j                  |dg       }| j	                  |      S )NFperpr  r  r  r  r  s         r  r  zderive.fetch_swap_marketsc  sa    %
 33DKK4PQ(B7~~fmR8!!$''r  c                     ddd}| j                  | j                  ||            }| j                  |di       }| j                  |dg       }| j	                  |      S )NFr7   r  r  r  r  r  s         r  r  zderive.fetch_option_marketsm  sa    '
 33DKK4PQ(B7~~fmR8!!$''r  marketc                    | j                  |d      }d}d}d}d}d }d }| j                  |d      }	| j                  |d      }
| j                  |	      }| j                  |
      }| j                  |d      }|dz   |z   }d }d }d }d }d }d }|dk(  rd}d	}n|d
k(  r,d}d}| j                  |      }|dz   |z   dz   |z   }d}d}d}d}n|dk(  rd}| j                  |      }d}d}d}| j                  |d      }| j                  |d      }| j	                  |d      }| j                  |d      }|dz   |z   dz   |z   dz   | j                  |      z   dz   | j                  |      z   dz   |z   }|dk(  rd}nd}d}d}| j                  i d|d|d|d|d|d|	d|
d|dd	|d |d|d!dd|d"| j                  |d#      d$|xs |d%|||rd nd&|| j                  |      | j                  |d'      | j                  |d(      ||| j                  |d)      | j                  |d*      d+d d d,| j                  |d-      | j                  |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  s   (9:!!&/:""6+;<&&v.''0##F,=>e#
 7?DJV^FH,,X6FCZ%'#-6FDFGJXH,,X6FFF!J NN63CDM((AF&&}h?F++M=ILCZ%'#-6<t{{6?RRUXX[_[p[pqw[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2+
  !2+
" f#2+
$ %)D"ll62%%f.>?%%f.>?$**6=A))&+>  
  ++F4DE++F4DE
  
  $ c2+
 2 2	r  r  c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| 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://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  ss     	V$vd|
 ++DKK,HIz ~~h"5  v..r  Ntickerc           
         | j                  |d      }| j                  |d      }| j                  ||      }| j                  |d      }| j                  |d      }| j	                  i d|d|d| j                  |      d| j                  |d      d| j                  |d      d	| j                  |d
      d| j                  |d      d| j                  |d      d| j                  |d      dd dd dd dd dd d|dt        j                  |d      dd d d | j                  |d      | j                  |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	!!(F3vw/!!%)9: !
f!
!
 Y/!
 D$$UF3	!

 4##E51!
 4##F,<=!
 ))&2CD!
 4##F,<=!
 ))&2CD!
 D!
 D!
 T!
 D!
 T!
 f!
  ',,VU;!!
" t#!
$ **6=A))&,?-!
. / 	r  sincelimitc                    | j                          i }d}|| j                  |      }|d   |d<   ||dkD  rd}||d<   |||d<   | j                  |d      }| j                  |dg      }|||d<   | j	                  | j                  ||            }| j                  |d	i       }	| j                  |	d
g       }
| j                  |
|||      S )at  
        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6G9-&+GN#11$++gv2NOB (B7~~fh3  vue<<r  tradec                    | j                  |d      }| j                  ||      }| j                  |d      }d| j                  |d      d}| j                  || j                  |d      | j                  |d      || j	                  |d      d | j                  |d	      | j                  |d
      | j                  |d      d || j                  |      |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%%e[9	$$UK8
 ""5*5%%eZ8**5+> ,,U4DE%%e];&&un="Y/ 
  	r  c           
      p   | j                          | j                  |      }d|d   i}|||d<   | j                  |d      }| j                  |dg      }|||d<   | j	                  | j                  ||            }| j                  |di       }	| j                  |	dg       }
g }t        dt        |
            D ]R  }|
|   }| j                  |d	      }|j                  ||d
   | j                  |d      || j                  |      d       T | j                  |d	      }| j                  ||d
   ||      S )a[  
        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'   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6G9-&+GN#77GV8TU (B7~~f&<bAq#d)$ 		AGE))%=ILL *#//~F& LL3 		 e[1009I5RWXXr  c                 p    | j                  |dd|      }| j                  |d      }| j                  |      S )an  
        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)  s=     2264FK ~~h*&&t,,r  c                     | j                  |d      }| j                  |d      }i d|d|dd dd dd dd dd dd d	| j                  |d	      d
|d| j                  |      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,,X{C
H
f
 
 $	

 D
 #D
 
 
 4++HmD
  0
 t||,<=
 t
 #D
 "4
 "4
  '!
" &t#
$ %
 	
r  c                    | j                  | j                  g d|      dd      }| j                  | j                  dd      }|rdnd}| j	                  |      }| j	                  d      }| j                  | j                  |||      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
!X' nnT\\=%Hbm]  uw $ 5 56F G&&v.yy++F4I;WYachiir  c                 T    | j                  |      }| j                  |dd  |dd        S N)r  	sign_hash)r  r   r  	hashOrders       r  
sign_orderzderive.sign_orderg  s0    ++E2	~~ioz#$/?@@r  c           
      X   | j                  |      }| j                  |      }| j                  d      }| j                  d      }| j                  || j                  d      || j                  | j	                  |                  }d| j                  | j                  ||      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)PRY[_[f[fgkg|g|  ~Q  hR  \S  Tdii 2 26= I8UZ[[[r  c                    | j                          | j                  |dd  |dd  dd       }|d   }|d   }| j                  | j                  d|d               }d|j	                  dd	      z   |j	                  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    '')JJtCDz:cd+;[$O	cNcNtxxIcN;<aggb#&&S)99A==r  c                 J    | j                  | j                  |      |dd        S r  )r  r  )r  r  r  s      r  sign_messagezderive.sign_message{  s%    ~~d//8*ST:JKKr  numc                 .    t        j                  ||      S N)r"   r;  )r  r  decs      r  parse_unitszderive.parse_units~  s    !!#s++r  r  rQ  r  r  c                 l   | j                          | j                  |      }|t        | j                  dz         d}| j	                  d|      \  }}| j                  |dd      }	| j                  |dd      }
| j                  |dd	      }| j                  |d
      }|j                         }|j                         }| j                         }| j                  |d| j                         dz         }| j                  d      }| j                  | j                  dd      }|rdnd}| j                  |      }d}| j                  |dd      \  }}|t        | j                  dz         | j                  |      }| j                  |      }| j!                  | j#                  g d|d   d   | j%                  |d   d         | j'                  | j)                  |            | j'                  | j)                  | j+                  ||                  | j'                  | j)                  |            ||dk(  g      dd      }d}| j-                  d|      \  }}| j/                  |||||||| j0                  g| j2                        }|d   ||||||||| j5                  | j                  dd      | j0                  d}|
!|
|d<   |
r|rt7        | j                  dz         |d|d	<   n|||d	<   | j9                  |d      }| j9                  |d       }| j5                  |d!d"      }|#| j5                  |d#|      }||d$<   d%|d&<   ||d!<   n$|"| j5                  |d#|      } | |d$<   d'|d&<   ||d!<   | j5                  |d(      }!|!|!|d)<   ||d*<   | j;                  |g d+      }d}"|	r"| j=                  | j?                  ||            }"n!| jA                  | j?                  ||            }"| jC                  |"d,      }#| jC                  |#d-      }$|$| jC                  |#d.      }$| jE                  |$|      }%||%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  s   * 	V$=#DGG.X$XYY#??vVf~~ffe4%%flMJ
..v}oV>>&*5JJL	JJL	!!#++F4JDLLN]dLde//0rsnnT\\=%HP[K  cO++E266v}iX>#DGG.d$dee,,V4,,V4"ii(;(; =
 6N/0!!&.1D"EF##D$4$4[$AB##D$4$4T5M5MfVb5c$de##D$4$4\$BC

) h
  #&*&G&GW]&^#VOO 	%
 ??		  &d|"#"&#)$3!--dllDBno((
 !%/GM"h"477-c#cdd'2GO$$'2GO$??6:6__V\:
++F4H&Q ,,X~xPM'4GO$&0GN#,<G()#"..z>:VO'6GO$&2GN#,<G()((A$,GG(6  $d  e11$++gv2NOH,,T[[&-IJHH (3>>&*5~~fg6H  62fr  r'   c                    | j                          | j                  |      }d}	| j                  d|      \  }	}| j                  |dd      }
| j	                  |dd      }| j                  |d      }|j                         }|j                         }| j                         }| j                  |d| j                         d	z         }| j                  d
      }| j                  | j                  dd      }|rdnd}| j                  |      }| j                  |dd      }| j                  |      }| j                  | j                  g d|d   d   | j!                  |d   d         | j#                  | j%                  |            | j#                  | j%                  | j'                  ||                  | j#                  | j%                  |            |	|dk(  g      dd      }d}| j)                  d|      \  }}| j+                  ||	|||||| j,                  g| j.                        }|d   ||||||||	|| j,                  d}|
!|
|d<   |
r|rt1        | j2                  dz         |d|d<   n|||d<   | j                  |d      }|||d<   ||d<   | j5                  |g d      }| j7                  | j9                  ||            }| j;                  |d       }| j;                  |d!      }| j=                  ||      }|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=  sG     	V$#??VTf%%flMJ
..v}oV>>&*5JJL	JJL	!!#**63I4<<>\cKcd//0rsnnT\\=%HP[K  cO++E2''	3?,,V4"ii(;(; =
 6N/0!!&.1D"EF##D$4$4[$AB##D$4$4T5M5MfVb5c$de##D$4$4\$BC

) h
  #&*&G&GU[&\#VOO 	%
 ??		  &d|"$"#"&#)$3((
 !%/GM"h"477-c#cdd'2GO$$'2GO$((A$,GG(6#}~**4;;w+GHV (3>>&'2  62r  c                    |t        | j                  dz         | j                          | j                  |      }| j	                  |ddd      }d}| j                  d|      \  }}| j                  |ddg      }|d   |d}| j                  |d	      }| j                  |d
|      }	|	du}
d}|
r;|	|d
<   | j                  |d	d
g      }| j                  | j                  ||            }nJ||d<   |r"| j                  | j                  ||            }n!| j                  | j                  ||            }d|i}| j                  |d      }|
r|	|d<   | j                  | j                  ||      |      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    >#DGG.Y$YZZV,$$VYF	#??vVf6Iv#67%d|)
  $//H(,(8(8J^(_%7tC<GGYYv'ABF44T[[&5QRH"$GJ==dkk'SY>Z[11$++gv2NOX '/x2.KL*+{{4++E6:LIIr  c                 &   | j                          d}|| j                  |      }d}| j                  d|      \  }}d|i}d}|+|d   |d<   | j                  | j	                  ||            }|S | j                  | j	                  ||            }|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  privatePostCancelByInstrumentr  privatePostCancelAll)r  r  r  r  r  r  r  s          r  cancel_all_orderszderive.cancel_all_orders8  s     	[[(F#??@QSYZf\
 )/G%&99$++gv:VWH   00Wf1MNH r  c           	         | j                          d}| j                  |dd      \  }}|r| j                  d||||dd      S | j                  |ddd      }| j	                  |ddg      }d}| j                  d|      \  }}d	|i}d}	|| j                  |      }	|	d
   |d<   |||d<   nd|d<   |rd|d<   | j                  | j                  ||            }
| j                  |
d      }| j                  |d      }|+| j                  |d      }| j                  |d      }||kD  rg S | j                  |d      }| j                  ||	||      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[&88PUW\^dflnqrr$$VYF	6Iv#67#??vVf\
 [[(F)/G%&#(GK #&GK  -GH,,T[[&-IJ\ x2  0l;J++JDKk!	h/  >>r  c                 r    | j                          | j                  |ddi      }| j                  ||||      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  s<     	Vh-?@  ~FFr  c                 r    | j                          | j                  |ddi      }| j                  ||||      S )r  r  filledr  r  s         r  fetch_closed_orderszderive.fetch_closed_orders  s<     	Vh-AB  ~FFr  c                 r    | j                          | j                  |ddi      }| j                  ||||      S )a0  
        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  s<     	Vh-DE  ~FFr  r  c                 6    ddddd}| j                  ||d       S )NIOCFOKGTCPO)iocfokgtcr  r  )r  r  timeInForcess      r  parse_time_in_forcezderive.parse_time_in_force  s,    	
 k4@@r  r  c                 @    |dddddd}| j                  |||      S |S )Nr*  closedcanceledrejected)r*  r  r  r   r  r*  r  r  statusess      r  parse_order_statuszderive.parse_order_status  s:    %"'%H ##Hff==r  r  c                    | j                  |d      }||}| j                  |dd      }| j                  |d      }| j                  |d      }|| j                  ||      }|d   }| j                  |d      }| j                  |d      }	| j                  |d	      }
| j                  |d
      }| j                  |d      }| j	                  |d      }| j                  |d      }| j                  |d      }||rd}nd}| j                  |d      }d }d }d }|| j                  |d      }|dk(  r|}n|}| j                  |d      }| j                  |d      }| j                  |d      }| j                  i d|d| j                  |d      d|d| j                  |      dd d|d| j                  |      d|d|d | j                  |      d!d d"| j                  |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  
safe_orderr  r3  r,  )r  r  r  r   r  orderIdr  r  r  r1  r  r  r  r  isBidrQ  triggerTyper  r  r  r?  r  r  s                          r  r  zderive.parse_order  s   h x0=E''2FP	""5*5##E+<=%%h7F!  6""5/:!!%)9:!!%9uk2**5,?	uh/{3<&&un="++E?CLj( ,"."//:QR!!%8&&uo>  
' 
T--eW= 
  
 Y/	 

 !$ 
 "#6 
 d--f5 
 f 
 I 
 433K@ 
  
 $..> 
 D 
 U 
 L 
  ! 
" ]# 
$ " 9 
: ; 	r  c                 h   | j                          d}| j                  d|      \  }}||d}d}|| j                  |      }|d   |d<   |||d<   |||d<   | j                  | j	                  ||            }	| j                  |	di       }
| j                  |
d	g       }| j                  |||||      S )
ai  
        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3OPJ (B7"5  vFFr  c           	      F   | j                          d}| j                  |dd      \  }}|r| j                  d||||dd      S d}| j                  d|      \  }}d|i}d}|| j	                  |      }|d   |d	<   |||d
<   |||d<   | j                  | j                  ||            }	| j                  |	di       }
| j                  |d      }|+| j                  |
d      }| j                  |d      }||kD  rg S | j                  |
dg       }| j                  |||||      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  rH  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  sj    	88R\]&88&RWY^`fhnpstt#??QWXf\
 [[(F)/G%&#(GK (-G$%224;;w3OPJ (B7  0=J++JDKk!	"5  vFFr  symbolsc                 0   | j                          d}| j                  d|      \  }}d|i}| j                  |dg      }| j                  | j	                  ||            }| j                  |di       }| j                  |dg       }| j                  ||      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  rL  r  r  r  r  r  rN  s           r  fetch_positionszderive.fetch_positions  s     	#??@PRXYf\
 6O#45//GV0LMN (B7NN6;;	##Iw77r  positionc                    | j                  |d      }| j                  ||      }| j                  |d      }d }t        j                  |d      rd}nd}| j                  |d      }| j                  |d      }| j	                  |d      }| j                  |d	      }	t        j
                  |      }t        j                  ||      }
| j                  i d
|dd d| j                  |d      d|d| j                  |      dd d| j                  |d      dd d| j                  |d      dd dd d| j                  |
      d| j                  |d      d| j                  |	      d| j                  |      d| j                  |      dd | j                  |d      | j                  |      d d d |d d d d d
      S )Nr  r  r  longshortr  r3  r5  unrealized_pnlr  r'   r  r  r  r?  initialMargininitial_margininitialMarginPercentagemaintenanceMarginmaintenance_marginmaintenanceMarginPercentage
entryPricenotionalr  unrealizedPnl	contractsmarginRatioliquidation_price)
liquidationPricer7  	lastPrice
collateral
marginModerQ  r/  hedgedr  r  )r  rB  r"   	string_gtr  
string_absr;  safe_positionr  parse_numberr  )r  rR  r  r  sizerQ  r  r7  r  unrealisedPnlr^  s              r  parse_positionzderive.parse_positionO  sO   > ##H.?@!!(F3(3T3'DD''?$$X|<	%%h0DE	((3CD!!$'%%dI6!! #
H#
$#
 d&&vx8#
 	#

 Y/#
 "4#
 T--h8HI#
 &t#
  !1!1(<P!Q#
 *4#
 $#
 ))(3#
 ((:>#
 T..}=#
 **40#
  D--l;!#
" 4##
$ !% 0 0;N O**95!#7#
  	r  c           	      D   | j                          d}| j                  |dd      \  }}|r| j                  d||||dd      S d}| j                  d|      \  }}d|i}d}|| j	                  |      }|d   |d	<   |||d
<   |||d<   | j                  | j                  ||            }	| j                  |	di       }
| j                  |d      }|+| j                  |
d      }| j                  |d      }||kD  rg S | j                  |
dg       }| j                  ||||      S )a7  
        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  rp  s                  r  fetch_funding_historyzderive.fetch_funding_history  sl    	88AVXbc&889NPVX]_dflntvyzz#??@UW]^f\
 [[(F)/G%&).G%&#(GK 44T[[&5QR@ (B7  0=J++JDKk!	"5!!&&%??r  c           	          | j                  |d      }| j                  ||      }| j                  |d      }| j                  d      }| j                  |d      }||||| j	                  |      d d |dS )Nr  fundingr  r  )r  r  r  r  r  r'   r  rate)r  r9  r  r  r  )r  incomer  r  r  rv  r  r  s           r  parse_incomezderive.parse_income  s     ##F,=>!!(F3	2&&v.%%fk:	"Y/	
 		
r  c                     | j                          d}| j                  d|      \  }}d|i}| j                  | j                  ||            }| j	                  |d      }| j                  |      S )am  
        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4PQb (3!!&))r  c                    d|i}t        dt        |            D ]  }||   }| j                  |dg       }t        dt        |            D ]  }||   }| j                  | j	                  |d            }| j                  ||      }	|	&| j                         }	| j	                  |d      |	d<   n.| j	                  |d      }
t        j                  |	d   |
      |	d<   |	||<     | j                  |      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?	  s   H
 q#h-( 	'A!!J..]BGK1c+./ 
'%a...t/?/?/TU..6?"llnG'+'7'7'JGG$!--gx@F'.'9'9'':JF'SGG$&t
'	'   ((r  r  c                 >   | j                          d}| j                  d|      \  }}d|i}|||d<   | j                  | j                  ||            }| j	                  |      }| j                  |di       }	| j                  |	d      }
| j                  |
||||      S )a\  
        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  rp  )r  r  privatePostGetDepositHistoryr  safe_currencyr  r  parse_transactionsr  r  r<  r=  r  r  r  r  r  r  rp  s              r  fetch_depositszderive.fetch_depositsS	  s     	#??QWXf\
 ).G%&44T[[&5QR& %%d+(B71&&vxvNNr  c                 >   | j                          d}| j                  d|      \  }}d|i}|||d<   | j                  | j                  ||            }| j	                  |      }| j                  |di       }	| j                  |	d      }
| j                  |
||||      S )aj  
        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  rp  )r  r  privatePostGetWithdrawalHistoryr  r  r  r  r  r  s              r  fetch_withdrawalszderive.fetch_withdrawals	  s     	#??@RTZ[f\
 ).G%&77GV8TU& %%d+(B71&&vxvNNr  transactionr  c                 n   | j                  |d      }| j                  |d      }| j                  |d      }|dk(  rd }i d|dd d|d|d| j                  |      d	d d
d dd dd dd dd dd d| j                  |d      d|d| j	                  | j                  |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	  sW    W5%%k;?	Y75=D
K
$
 D
 	

 Y/
 t
 4
 
 4
 t
 T
 D
 d&&{H=
 
 d33D4D4D[R]4^_
  t!
" t#
$ )
 	
r  c                 2    ddd}| j                  |||      S )Nokfailed)settledrevertedr*  r1  s      r  r  zderive.parse_transaction_status	  s&     
 &&99r  
methodNamer  c                     d }| j                  ||d      \  }}||dk7  r|| j                  d<   ||gS | j                  | 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"F*1Cr1I,>DLL)&//((G$!6**#
 :  >b  !b  c  	cr  c                     d }| j                  ||d      \  }}||dk7  r|| j                  d<   ||gS | j                  | 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#V+2E2K2EDLL./'00((7LM$!6**#
 :  >e  !e  f  	fr  httpCodereasonurlmethodheadersbodyc
                 .   |sy | j                  |d      }
|
~| j                  |
d      }| j                  dz   | j                  |      z   }| j	                  | j
                  d   ||       | j                  | j
                  d   ||       t        |      y )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    x1((7Iww}tyy'::H001I4QYZ001I9V^_))r  r   GETc                 :   | j                   d   |   dz   |z   }|dk(  rxddi}|dk(  r^t        | j                               }| j                  || j                        }	| j                  | j                  d      |d<   ||d	<   |	|d
<   | j                  |      }||||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    iis#c)D0V 2G i$++-. --c4??C	*.*:*:4<<I^*_'-0)*-6)*99V$DfdwOOr  r  )1000000000000000000)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,  r3  r  rI  rK  r   r   rQ  rn  rs  rx  r   r}  r|  r   r  r  r	   r  r  r  r  r  r  r  __classcell__)r  s   @r  r$   r$      s   S# Sj-t - !# 5$ ') VZ Vp $& <$v, <| )+ (tF| ( )+ (tF| ( +- (f (d4 dF dL 02 M/3 M/f M/^T4 T T6 Tl 6:UW @=3 @=s @=# @=\`af\g @=D. .v . .` 8<$]ajl 3Y 3YC 3YWZ 3Yj 68 - -K -8
6 
[ 
0jA\>L,s , gksu z3 zi zy zRW z`c zx `drv  @B aS a# aY ai aY\ alo aF 37r VJs VJC VJp /32 ( (T *.Dt\^ [?3 [?c [? [?cghmcn [?z /3TXac G G3 Gc Ghlmrhs G" 154VZce G# GS GPS Gjnotju G" 37TX\eg GC Gs GRU G"As A
 
tD t& tE tl 9=4^bkm DGS DG# DGS DGX[ DGL -1tRV_a MGc MG MGC MG^ 26b ;8w ;8T(^ ;8zIt IV IV 37TX\eg G@C G@s G@RU G@R
6 
2 $& A*( A*F) )( *.Dt\^ +O3 +Oc +O +Ocghsct +OZ -1tRV_a +Oc +O +OC +Ofjkvfw +OZ&
T &
X &
Q\ &
P:s :	cc 	c4 	c	fs 	fD 	f
c 
3 
S 
# 
X\ 
dg 
 &eBSW 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     sd    ( , B  B  B  B  B  B  * 0 . ' . ) * . 4 %u'PX{ u'Pr  