
    !:h                    p   d dl mZ d dlmZ d dlZd dlmZmZmZm	Z	m
Z
mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ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- d dl#m.Z. d dl#m/Z/ d dl#m0Z0 d dl1m2Z2 d dl3m4Z4  G d dee      Z5y)    )Exchange)ImplicitAPIN)AccountAnyBalances
CurrenciesCurrencyDepositAddressGreeksIntMarketNumOptionOptionChainOrder	OrderBook	OrderSide	OrderTypePositionStrStringsTickerTickersFundingRateTradeTradingFeesTransactionMarketInterfaceTransferEntry)List)ExchangeError)AuthenticationError)PermissionDenied)ArgumentsRequired)
BadRequest)InsufficientFunds)InvalidAddress)InvalidOrder)OrderNotFound)NotSupported)DDoSProtection)ExchangeNotAvailable)OnMaintenance)	TICK_SIZE)Precisec                       e Zd Zdef fdZdefdZdkdededed	ede	f
 fd
Z
i fdefdZi fdefdZi fdZi fdZi fdee   fdZd Zi fdee   fdZdefdZi fdefdZi fdedefdZi fdedefdZdldededefdZi fdedefdZdi fde de!fdZ"dddi fdedededee#   fdZ$dld edede%fd!Z&ddi fdedededee%   fd"Z'i fde(fd#Z)di fdedede*fd$Z+d%efd&Z,d'efd(Z-d) Z.dld*edede/fd+Z0di fd,edefd-Z1di fded.e2d/e3d0e4d1e5f
d2Z6ddi fd,eded.e2d/e3d0e5d1e5fd3Z7di fd,edefd4Z8di fdefd5Z9dddi fdedededee/   fd6Z:dddi fdedededee/   fd7Z;dddi fd,edededefd8Z<dddi fdededefd9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%efd<ZAdld=ed>eBde>fd?ZCdld@edefdAZDi fdefdBZEdi fde deeF   fdCZGi fdefdDZHdE ZIdddi fdedededeeJ   fdFZKi fded0e4dGedHedeJf
dIZLdldJed>eBdeJfdKZMd%edefdLZNdi fded0e4dMede>fdNZOdld>eBfdOZPdi fdPe fdQZQi fdedeRfdRZSdddi fdededefdSZTdldedeRfdTZUddi fdededefdUZVdV ZWdddi fdededefdWZXdldefdXZYi fdedeZfdYZ[dldZededeZfd[Z\i fdede]fd\Z^i fdede_fd]Z`dmd^ed>eBdede]fd_Zad` Zbdadbi ddfdcZcddeddeedfedgedhediefdjZe xZfS )nderibitreturnc                  |   | j                  t        t        |          dddg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d)di d*d	d+d	d,d	d-d	d.dd/d	d0dd1d	d2dd3d	d4dd5dd6dd7dd8dd9dd:di d;d	d<dd=dd>d	d?dd@d	dAddBddCddDddEddFd	dGddHd	dId	dJddKd	dd	dddddLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[id\dZd]id]d^d_gd`dadbdcdddei dfdgdhdgdidgdjdgdkdgdldgdmdgdndgdodgdpdgdqdgdrdgdsdgdtdgdudgdvdgdwdgi dxdgdydgdzdgd{dgd|dgd}dgd~dgddgddgddgddgddgddgddgddgddgddgdgdgdgdgdgdidei ddgddgddgddgdpdgdqdgdrdgddgddgddgddgddgddgddgddgddgddgi ddgddgddgddgddgddgddgddgddgddgddgddgddgddgddgddgddgi ddgddgddgddgddgddddgddgddgddddddddddddddddi ddddddddgddgddgddgddgddgddgddgddgddgddgddgddgddgdgdgdgdgdgdgdgdgdgdgdgdgdgdgdgd̜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	dddddӜd	d	d	ddԜd	d d	d	dd՜d d	dddgdd	d	dd֜ddidٜ	ddiddiddidܜddiddidܜdݜ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 d t        dt        dt        dt        dt        dt        dt        dt        dt        d	t        d
t        dt        dt        dt        dt        dt        dt        i dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        d t        d!t        i d"t        d#t        d$t        d%t        d&t        d't        d(t        d)t
        d*t        d+t        d,t
        d-t
        d.t
        d/t
        d0t        d1t
        d2t
        i d3t
        d4t        d5t
        d6t
        d7t
        d8t
        d9t
        d:t        d;t
        d<t        d=t        d>t        d?t        d@t        dAt        dBt        dCt        t        t        t        t        t        t        t        t        t        t        dD
t         dEdFdEidGdHidIdJ      S (K  Nr1   DeribitNLv22   TCORSspotFmarginswapfutureoptioncancelAllOrderscancelOrdercancelOrderscreateDepositAddresscreateOrdercreateReduceOnlyOrdercreateStopLimitOrdercreateStopMarketOrdercreateStopOrdercreateTrailingAmountOrder	editOrderfetchAccountsfetchBalancefetchBorrowRateHistoriesfetchBorrowRateHistoryfetchClosedOrdersfetchCrossBorrowRatefetchCrossBorrowRatesfetchCurrenciesfetchDepositfetchDepositAddressfetchDepositAddressesfetchDepositAddressesByNetworkfetchDepositsfetchDepositWithdrawFeesfetchFundingRatefetchFundingRateHistoryfetchGreeksfetchIndexOHLCVfetchIsolatedBorrowRatefetchIsolatedBorrowRatesfetchLeverageTiersfetchLiquidationsfetchMarginModefetchMarketsfetchMarkOHLCVfetchMyLiquidationsfetchMySettlementHistoryfetchMyTrades
fetchOHLCVfetchOpenOrdersfetchOptionfetchOptionChain
fetchOrderfetchOrderBookfetchOrdersfetchOrderTradesfetchPositionfetchPositionModefetchPositionsfetchPremiumIndexOHLCVfetchStatusfetchTickerfetchTickers	fetchTimefetchTradesfetchTradingFeefetchTradingFeesfetchTransactionsfetchTransferfetchTransfersfetchUnderlyingAssets)fetchVolatilityHistoryfetchWithdrawalfetchWithdrawalssandboxtransferwithdraw135101530601201803607201D)1m3m5m10m15m30m1h2h3h6h12h1drestzhttps://test.deribit.comzchttps://user-images.githubusercontent.com/1294454/41933112-9e2dd65a-798b-11e8-8440-5bab2959fcb8.jpgzhttps://www.deribit.comzhttps://docs.deribit.com/v2zhttps://github.com/deribitz.https://www.deribit.com/pages/information/feesz%https://www.deribit.com/reg-1189.4038g?)urldiscount)testlogoapiwwwdocfeesreferralgetauth   exchange_token
fork_tokenset_heartbeatdisable_heartbeatget_timehellostatusr   	subscribeunsubscribeunsubscribe_allget_announcementsget_book_summary_by_currencyget_book_summary_by_instrumentget_contract_sizeget_currenciesget_delivery_pricesget_funding_chart_dataget_funding_rate_historyget_funding_rate_valueget_historical_volatility	get_indexget_index_priceget_index_price_namesget_instrumentget_instruments get_last_settlements_by_currency"get_last_settlements_by_instrumentget_last_trades_by_currency$get_last_trades_by_currency_and_timeget_last_trades_by_instrument&get_last_trades_by_instrument_and_timeget_mark_price_history)get_order_bookget_trade_volumesget_tradingview_chart_dataget_volatility_index_datatickerlogoutenable_cancel_on_disconnectdisable_cancel_on_disconnectget_cancel_on_disconnectchange_api_key_namechange_scope_in_api_keychange_subaccount_namecreate_api_keycreate_subaccountdisable_api_keydisable_tfa_for_subaccountenable_affiliate_programenable_api_keyget_access_logget_account_summaryget_account_summariesget_affiliate_program_infoget_email_languageget_new_announcementsget_portfolio_marginsget_positionget_positionsget_subaccountsget_subaccounts_detailsget_transaction_loglist_api_keysremove_api_keyremove_subaccountreset_api_keyset_announcement_as_readset_api_key_as_defaultset_email_for_subaccountset_email_languageset_password_for_subaccount$toggle_notifications_from_subaccounttoggle_subaccount_loginexecute_block_trade   get_block_trade!get_last_block_trades_by_currency invalidate_block_trade_signatureverify_block_tradebuyselleditedit_by_labelcancel
cancel_allcancel_all_by_currencycancel_all_by_instrumentcancel_by_labelclose_positionget_marginsget_mmp_configget_open_orders_by_currencyget_open_orders_by_instrumentget_order_history_by_currencyget_order_history_by_instrumentget_order_margin_by_idsget_order_stateget_stop_order_historyget_trigger_order_historyget_user_trades_by_currency$get_user_trades_by_currency_and_timeget_user_trades_by_instrument&get_user_trades_by_instrument_and_time)get_user_trades_by_order	reset_mmpset_mmp_config$get_settlement_history_by_instrument"get_settlement_history_by_currencycancel_transfer_by_idcancel_withdrawalcreate_deposit_addressget_current_deposit_addressget_depositsget_transfersget_withdrawalssubmit_transfer_to_subaccountsubmit_transfer_to_userr   )publicprivate)lastmarkindex)IOCFOKPOGTD)
marginModetriggerPricetriggerPriceTypetriggerDirectionstopLossPricetakeProfitPriceattachedStopLossTakeProfittimeInForcehedgedselfTradePreventiontrailingleveragemarketBuyByCostmarketBuyRequiresPriceicebergd   i )r%  limitdaysBack	untilDayssymbolRequired)r%  triggerr/  r8  )r%  r5  r9  r/  r8  )r%  r5  r6  daysBackCanceledr7  r9  r/  r8  r5    )	r   rB   createOrdersrd   ri   rf   rk   rM   re   extendsdefault)linearinverse)r>  r9   r;   r<   99991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610040100411004310044100451004610047100481100811029110301103111035110361103711038110391104111042110431104411045110461104711048110491105011051110521105311090110911109211093110941109511096120001200112002129981200312004120051210012999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017)
1301813019130201302113025z-32602z-32601z-32700z-3200011054BTCcodemethod$privateGetSubmitTransferToSubaccount)r  rJ   r   )idname	countriesversion	userAgent	rateLimitprohas
timeframesurlsr   features
exceptionsprecisionModeoptions)deep_extendsuperr1   describer#   r"   r!   r(   r)   r&   r+   r*   r,   r-   r%   r'   r.   )self	__class__s    F/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/deribit.pyr  zderibit.describe   s   gt = ? KKK %K 	K
 $K $K "4K tK K 'K tK (K 'K (K "4K  ,T!K" T#K$  %K& 'K( +E)K* )%+K, $T-K. '/K0 (1K2 "43K4 5K6 &t7K8 (9K: 1%;K<  =K> +D?K@ #DAKB *4CKD tEKF "5GKH *5IKJ +EKKL %eMKN $TOKP "5QKR SKT !%UKV &tWKX +EYKZ  [K\ d]K^ "4_K` taKb #DcKd deKf !$gKh uiKj #DkKl  mKn $UoKp !$qKr )%sKt tuKv twKx yKz T{K| t}K~ "5K@ #DAKB $UCKD  EKF !$GKH (IKJ +/#($(  UKZ   6 ~5 110 IB #*  .. )!. %a	. (. ,Q. #A.  . !!. . $Q. &q.  *1!.$ ,Q%.( 7).* 9!+., ,Q-.. )!/.0 .q1.2 1!3.4 3A5.6 1!7.8 4Q9.: $Q;.< *1=.> 0?.@ )!A.B *1C.D ;AE.F =aG.H 6qI.J ?K.L 8M.N A!O.P 1!Q.R +,-.6756"#[.0d  [ ![ 6q	[
 7[ 3A[ $Q[ &q[ *1[ .q[ 21[ 1![ )![  ,Q![" *1#[$ 5a%[& 3A'[( )!)[* )!+[, .q-[. 0/[0 5a1[2 -a3[4 05[6 07[8 '9[: (;[< *1=[> 21?[@ .qA[B (C[D )!E[F ,QG[H (I[J 3AK[L 1!M[N 3AO[P -aQ[R 6qS[T ?U[V 21W[Z .q[[\ *1][^ <Q_[` ;Aa[b -ac[f qg[h i[j k[l (m[n !!o[p %aq[r 1!s[t 3Au[v *1w[x )!y[z &q{[| )!}[~ 6q[@ 8A[B 8C[D :1E[F 21G[H *1I[J 1!K[L 4QM[N 6qO[P ?Q[R 8S[T A!U[V 56%&*+@A>?12-.2378())*+,9:34$%u[]ePf  $&+(, %)$(%)-
 -2).+06:#'#'"&#'	( #(/4$($)+/27#'3$6 %)&+!$$*%+*.& ',#($)*.	# ',!%#($)*.( $(&+!$$*,-%+#($)*.	*  #{@D y
 "9 "9 	 "9 "9 	[Ulr(r ,r 	r
 r r r r r r r *r r r r  )!r" )#r$ )%r& )'r( ))r* )+r, )-r. /r0 1r2 3r4 5r6 7r8 9r: ;r< =r> ?r@ ArB CrD ErF GrH IrJ KrL MrN OrP -QrR SrT UrV WrX YrZ [r\ ]r^ _r` arb crd erf grh irj krl mrn orp qrr srt )urv wrx yrz {r| }r~ r@ ArB CrD ErF GrH IrJ KrL MrN OrP QrR SrT UrV WrX YrZ ,[r\ ]r^ _r` ,arb ,crd ,erf ,grh irj ,krl ,mrn ,orp )qrr ,srt ,urv ,wrx ,yrz ,{r| }r~ ,r@ ArB CrD )ErF GrH IrJ KrL MrN OrP '&&)&$$$$%crf 'E! De[B
 [ [	    symbolc                    d}d }|j                  d      }|j                  d      }d }d }|j                  d      dkD  r>| j                  |d      }| j                  |d      }|j                  d      dkD  r9|dz   }n3| j                  |d      }| j                  | j                  |d            }|j                  d      dkD  rd}d}n|}|}|j                  d	      dkD  r#|j                  d	      }	| j                  |	d      }| j                  |d
      }
| j                  |d      }| j	                  |      }| j                  |      }i d|dz   | j                  |      z   dz   |
z   dz   |z   d|dz   |z   dz   |z   dz   |z   dz   |
z   dz   |z   d|d|d|d|d|d|dddddd dd dddddddddddd |||d k(  rd!nd"| j                  |
      d d d#d d d$d d d$d d d$d%d d&	S )'NUSD-/r   r   USDC_USDC_      r  r  :basequotesettlebaseIdquoteIdsettleIdactiveFtyper=   r?  r@  r9   r;   r<   Tr:   Ccallputamountpriceminmax)r  r  cost)	contractcontractSizeexpiryexpiryDatetime
optionTypestrike	precisionlimitsinfo)splitfindsafe_stringconvert_market_id_expire_dateconvert_expire_date	parse8601%convert_expire_date_to_market_id_dateparse_number)r  r  r  r  optionParts
symbolBaser  r  	splitBasesplitSymbolr  r  datetime	timestamps                 r  create_expired_option_marketz$deribit.create_expired_option_market  s   ll3'\\#&
;;sb ##J2D%%k15F{{6"R'g~##K3D778H8HVW8XYF;;v#EFF	99S>B**S/K((a8I!!+q1%%k15
++F3NN8,	+
$*tII&QQTWWZ``cffiss+
i#o-3f<sBVKcQTZZ]``cmm+
 D+
 U	+

 f+
 d+
 u+
 +
 e+
 H+
 d+
 t+
 E+
 E+
 e+
  d!+
" e#+
$  &%/3%6&U''/  
  
   U+
 +	
r  NmarketIdmarket	delimiter
marketTypec                     |d uxr$ |j                  d      xs |j                  d      }|r|| j                  vr| j                  |      S t        t        |   ||||      S )Nz-Cz-P)endswithmarkets_by_idr  r  r1   safe_market)r  r  r  r  r  isOptionr  s         r  r  zderibit.safe_marketF  sg    D(f0A0A$0G/eXM^M^_cMdX););;44X>>Wd/&)ZXXr  c                 H    | j                  |      }| j                  |d      S )aF  
        fetches the current integer timestamp in milliseconds from the exchange server

        https://docs.deribit.com/#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)publicGetGetTimesafe_integer)r  paramsresponses      r  
fetch_timezderibit.fetch_timeM  s)     ((0   844r  c                    | j                  |      }| j                  |dg       }i }t        dt        |            D ]  }||   }| j	                  |d      }| j                  |      }| j                  |||| j	                  |d      dddd| j                  |d      | j                  | j                  | j	                  |d                  ddd	ddd	ddd	d
dd      ||<    |S )a  
        fetches all available currencies on an exchange

        https://docs.deribit.com/#public-get_currencies

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        r  r   currencycurrency_longNcryptowithdrawal_feefee_precisionr  )r  r   deposit)r  r  r  r  r  r  r   r  feer  r  networks)
publicGetGetCurrencies	safe_listrangelenr  safe_currency_codesafe_currency_structuresafe_numberr  parse_precision)	r  r	  r
  datar  ir  
currencyIdr  s	            r  fetch_currencieszderibit.fetch_currenciesc  s!    ..v6. ~~h"5q#d)$ 	AAwH))(J?J**:6D77  ((?C  ''2BC!..t/C/CDDTDTU]_nDo/pq  $#
  $#!
  $#  !39 F4L		> r  c                     | j                  | j                  dd      }| j                  | j                  |i       }| j                  |d|      }| j                  |d|      S )Nr  r  )
safe_valuer  )r  
methodNamer	  defaultCoder  r  s         r  code_from_optionszderibit.code_from_options  sS    oodllFEB//$,,
B?w<vvt44r  c                     | j                  |      }| j                  |d      }| j                  |d      }| j                  |dd| j	                               }|dk(  rdnd|dd|d	S )
aA  
        the latest known information on the availability of the exchange API

        https://docs.deribit.com/#public-status

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `status structure <https://docs.ccxt.com/#/?id=exchange-status-structure>`
        r  lockedusIngMbP?falseokmaintenanceN)r   updatedetar   r  )publicGetStatusr"  r  safe_integer_productmilliseconds)r  r	  r
  r  r'  
updateTimes         r  fetch_statuszderibit.fetch_status  sy     ''/ 84!!&(3..xHYHYH[\
%0d}!
 	
r  c                     | j                          | j                  |      }| j                  |dg       }| j                  |      S )a[  
        fetch all the accounts associated with a profile

        https://docs.deribit.com/#private-get_subaccounts

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `account structures <https://docs.ccxt.com/#/?id=account-structure>` indexed by the account type
        r  )load_marketsprivateGetGetSubaccountsr"  parse_accounts)r  r	  r
  r  s       r  fetch_accountszderibit.fetch_accounts  sF     	008F 8R8""6**r  c                 P    || j                  |d      | j                  |d      d dS )Nr  r  )r  r  r  r  r  )r  accounts     r  parse_accountzderibit.parse_account  s4      ""7D1$$Wf5	
 	
r  c                    g }g }i }d}| j                  |ddd      \  }}|r#| j                  |      }|j                  |       n| j                  |      }| j	                  |dg       }t        dt        |            D ]M  }	| j                  ||	   d      }
d|
i}| j                  | j                  ||            }|j                  |       O t        dt        |            D ]  }	| j	                  ||	   dg       }t        dt        |            D ]  }||   }| j                  |d      }|d	k(  }| j                  |d
      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |      }| j                  |      }| j                  |      }| j	                  |d      }|dk(  }| xr |j                  d      dk\  }|j                  d      dk\  }|j                  d      dk\  }| j                  |d      }d}d}|} d}!|rd}!n	|rd}!n|rd	}!d}"d}#|r	|dz   |z   } n|s|dz   |z   dz   |z   } |s|rd| dz   | j                  |d      z   } |rJ| j                  |d      }| j                  |d      }|dk(  rdnd}$| dz   | j                  |      z   dz   |$z   } ||k7  }"||k(  }#| j	                  ||       }%|%rd|| <   | j                  |d      }&| j                  |d      }'|j                  i d |d!| d"|d#|d$|d%|d&|d'|d(|!d	|d)d*d|d|d|d+| j	                  |d,      d-| d.|#|"| j                  |d/      | j                  |d0      | j                  |d1      || j                  |      |||&|'d2ddd3|&dd3|'dd3ddd3d4| j                  |d5      |d6         |S )7aI  
        retrieves data on all markets for deribit

        https://docs.deribit.com/#public-get_currencies
        https://docs.deribit.com/#public-get_instruments

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        Nr`   fetchAllMarketsTr  r   r  kindr9   instrument_namebase_currencycounter_currencysettlement_currencysettlement_period	perpetualr<   r=   comboexpiration_timestampr;   r  r  r   r  option_typer  r  Pmin_trade_amount	tick_sizer  r  r  r  r  r  r  r  r  r:   Fr  	is_activer  r?  taker_commissionmaker_commissioncontract_sizer  r  )r0  r  r  r  creation_timestamp)r@  takermakerr  r  r  r  r  r  r  createdr  )handle_option_and_paramspublicGetGetInstrumentsappendr  r"  r  r  r  extendr  r  r  yymmddr  number_to_stringiso8601)(r  r	  instrumentsResponsesr  parsedMarketsr=  instrumentsResponsecurrenciesResponsecurrenciesResultr  r  requestinstrumentsResultkr  r>  isSpotr  r  r  r  r  r  r  settlementPeriodr;   r<   r=   isComboMarketr  r  r  r  r  r@  r?  letterparsedMarketValueminTradeAmounttickSizes(                                           r  fetch_marketszderibit.fetch_markets  s+     " "&"?"?Xiko"p"&">">v"F ''(;<!%!<!<V!D2  $/A8RP1c"234 OA!--.>q.A:N

! '+&B&B4;;wX^C_&`#T %++,?@_OA` q#234 d	A $0DQ0GSU V1c"345 b*1-''7&.%%f.?@))&/B**63EF++F4IJ..v6//800:#'??6;N#O (K7!@tyy':a'?))H-2 $		' 2a 7**63IJ!
#D#D!D!CZ%/F&!CZ%/#5>F!'#FB0G!G!%)%5%5fh%GF)-)9)9&-)PJ-76-ASF%+c\D4I4I&4Q%QTW%WZ`%`F$G$oF$(OOM6$J!$(,f%!%!1!1&:L!M++FK@ 2"2f2 D2 U	2
 f2 f2 w2 2 D2 F2 e2 D2 f2 f2 doofkB2  F
!2" f#2$  '!--f6HI!--f6HI$($4$4V_$M$&*ll6&:$","0!)" $(#'%
 $2#'#
 $,#'"
 $(#'!$  $009MN"c2 2abd	J r  c                    d|i}g }d|v r| j                  |d      }n|g}t        dt        |            D ]~  }||   }| j                  |d      }| j	                  |      }| j                         }| j                  |d      |d<   | j                  |d      |d<   | j                  |d	      |d
<   |||<    | j                  |      S )Nr  	summariesr   r  available_fundsfreemaintenance_marginusedequitytotal)r  r  r  r  r  r:  safe_balance)	r  balancer  rl  r  r  r  currencyCoder:  s	            r  parse_balancezderibit.parse_balance  s    G
 	'!w<I 	Iq#i.) 	+AQ<D))$
;J22:>LllnG"..t5FGGFO"..t5IJGFO#//h?GG#*F< 	+   ((r  c                 P   | j                          | j                  |d      }| j                  |d      }i }|| j                  |      |d<   d}|| j	                  |      }n!| j                  | j                  ||            }| j                  |di       }| j                  |      S )ah  
        query for balance and get the amount of funds available for trading or funds locked in orders

        https://docs.deribit.com/#private-get_account_summary
        https://docs.deribit.com/#private-get_account_summaries

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.code]: unified currency code of the currency for the balance, if defined 'privateGetGetAccountSummary' will be used, otherwise 'privateGetGetAccountSummaries' will be used
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        r  Nr  r  )	r4  r  omitcurrency_idprivateGetGetAccountSummariesprivateGetGetAccountSummaryrW  	safe_dictrv  )r  r	  r  r`  r
  r  s         r  fetch_balancezderibit.fetch_balance  s     	/66*
"&"2"24"8GJ<99&AH77GV8TUHV (B7!!&))r  r  c                    | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |di       }| j                  |d      }| j                  |       ||dd|dS )a  
        create a currency deposit address

        https://docs.deribit.com/#private-create_deposit_address

        :param str code: unified currency code of the currency for the deposit address
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
        r  r  r  addressN)r  r  tagnetworkr  )r4  r  privateGetCreateDepositAddressrW  r"  r  check_addressr  r  r	  r  r`  r
  r  r  s           r  r  zderibit.create_deposit_addressO  s     	==&
 66t{{7F7ST 8R8""6957#
 	
r  c                    | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |di       }| j                  |d      }| j                  |       ||d|ddS )a  
        fetch the deposit address for a currency associated with self account

        https://docs.deribit.com/#private-get_current_deposit_address

        :param str code: unified currency code
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
        r  r  r  r  N)r  r  r  r  r  )r4  r  "privateGetGetCurrentDepositAddressrW  r"  r  r  r  s           r  fetch_deposit_addresszderibit.fetch_deposit_addressv  s     	==&
 ::4;;wPV;WX$ 8R8""6957#
 	
r  r   c           
         | j                  |dd      }| j                  |d      }| j                  ||      }| j                  |dd      }| j	                  |d|      }| j                  i d|d|d| j                  |      d	| j                  |d	d
      d| j                  |dd      d| j                  |dd      d| j                  |d      d| j                  |dd      d| j                  |d      dd dd d|d|dd dd dd dd d | j                  |d      | j                  |d      | j                  |d       |d!|      S )"Nr  rP  r?  
last_pricer  statsr  r  high	max_pricelow	min_pricebidbest_bid_price	bid_price	bidVolumebest_bid_amountaskbest_ask_price	ask_price	askVolumebest_ask_amountvwapopenclosepreviousClosechange
percentageaveragevolume
mark_priceindex_price)
baseVolumequoteVolume	markPrice
indexPricer  )safe_integer_2r  safe_symbolsafe_string_2r"  safe_tickerrZ  )r  r   r  r  r  r  r  r  s           r  parse_tickerzderibit.parse_ticker  s   ^ ''=QR	##F,=>!!(F3!!&,?8 !
f!
!
 Y/!
 D&&ufkB	!

 4%%eUK@!
 4%%f.>L!
 ))&2CD!
 4%%f.>L!
 ))&2CD!
 D!
 D!
 T!
 D!
 T!
 d!
  $!!
" t#!
$ ++E8<))&,?**6=A-!
. / 	r  c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |d      }| 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.deribit.com/#public-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  )r4  r  publicGetTickerrW  r|  r  r  r  r	  r  r`  r
  r  s          r  fetch_tickerzderibit.fetch_ticker  sp     	V$vd|
 ''GV(DE: (3  00r  symbolsc                    | j                          | j                  |      }| j                  |dd      }d}| j                  |dg      }|]t	        dt        |            D ]E  }| j                  ||         }| ||d   k7  rt        | j                  dz         |<|d   }|d   }G |t        | j                  dz         | j                  |      }d|d	   i}|%d}	|d
k(  rd
}	n|dk(  s|dk(  rd}	n|dk(  rd}	|	|	|d<   | j                  | j                  ||            }
| j                  |
dg       }i }t	        dt        |            D ]   }| j                  ||         }|d   }|||<   " | j                  |d|      S )a  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market

        https://docs.deribit.com/#public-get_book_summary_by_currency

        :param str[] [symbols]: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.code]: *required* the currency code to fetch the tickers for, eg. 'BTC', 'ETH'
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        r  r  Nr   r  z fetchTickers the base currency must be the same for all symbols, self endpoint only supports one base currency at a time. Read more about it here: https://docs.deribit.com/#public-get_book_summary_by_currencyr  zW fetchTickers requires a currency/code(eg: BTC/ETH/USDT) parameter to fetch tickers forr  r9   r<   r  r=   r>  r  r  )r4  market_symbolsr  rx  r  r  r  r%   r  r$   r  !publicGetGetBookSummaryByCurrencyrW  r  r  filter_by_array_tickers)r  r  r	  r  r  r  r  r  r`  requestTyper
  r  tickersr   r  s                  r  fetch_tickerszderibit.fetch_tickers  s    	%%g.!!&&*=6F8,1c'l+ *WQZ0#v(>$TWW  0C  &C  D  D<!&>D!&>D* <#DGG  /H  %H  I  I==&
 Kv~$!dj&8&!&&"-99$++gv:VW> (B7q#f+& 	%A&&vay1FH%F$GFO	% ++GXwGGr  r   sincer5  c           
         | j                          d}| j                  |dd      \  }}|r| j                  d|||||d      S | j                  |      }|d   | j	                  | j
                  ||      d}| j                  |      }	| j                         }
||d}|
|dz
  |	z  dz  z
  |d	<   |
|d
<   n7t        |dz
  d      }||d	<   ||
|d
<   n| j                  |||	z  dz        |d
<   | j                  |d      }|| j                  |d      }||d
<   | j                  | j                  ||            }| j                  |di       }| j                  |ddddddd      }| j!                  |||||      S )aF  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://docs.deribit.com/#public-get_tradingview_chart_data

        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param int [since]: timestamp in ms of the earliest candle to fetch
        :param int [limit]: the maximum amount of candles to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.paginate]: whether to paginate the results, set to False by default
        :param int [params.until]: the latest time in ms to fetch ohlcv for
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        Fre   paginatei  r  )r?  
resolutionr;  r   start_timestampend_timestampr   untilr  ticksr  r  r  r  r  T)r4  rT  "fetch_paginated_call_deterministicr  r  r  parse_timeframer0  r  sumr  rx   publicGetGetTradingviewChartDatarW  r"  convert_trading_view_to_ohlcvparse_ohlcvs)r  r  	timeframer  r5  r	  r  r  r`  durationnowr  r
  r  ohlcvss                  r  fetch_ohlcvzderibit.fetch_ohlcvm  s    	88zZ&::<QVX]_hjprvwwV$%d|**4??IyQ
 ''	2!=}),	X/E/L)LG%&'*GO$	1%E).G%&}+.(+/88E58;Kd;R+S(!!&'2YYvw/F',GO$88Wf9UV( 8R833FGVVUZ\cemost  E5IIr  tradec                    | j                  |d      }| j                  |d      }| j                  ||      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  ||      }| j                  |d      }	t	        j
                  |	|      }
|d   rt	        j                  |	|      }
| j                  |d      }d }|	|d	k(  rd
nd}| j                  |d      }d }|(| j                  |d      }| j                  |      }||d}| j                  |||| j                  |      || j                  |d      | j                  |d      ||||	|
|d|      S )Ntrade_idr?  r  	directionr  r  r@  	liquidityMrR  rQ  r  fee_currencyr  r  order_id
order_type)r  r  r  r  r  orderr  sidetakerOrMakerr  r  r  r  )
r  r  r  r  r/   
string_mul
string_divr  
safe_traderZ  )r  r  r  r  r  r  r  r  priceStringr  r  r  r  feeCostStringr  feeCurrencyIdfeeCurrencyCodes                    r  parse_tradezderibit.parse_trade  s   V eZ0##E+<=!!(F3%%e[9	{3&&ug6!!(F3 !!%2!!&+6)%%fk:D$$UK8	 '0C'77gL((6$ ,,UNCM"55mDO%+C "Y/%%eZ8$$UL9(  
  	r  c                    | j                          | j                  |      }|d   dd}|||d<   |t        |d      |d<   | j                  |dd	      }|| j	                  |dg      }||d	<   d}|&d	|vr"| j                  | j                  ||            }n!| j                  | j                  ||            }| j                  |d
i       }	| j                  |	dg       }
| j                  |
|||      S )a  

        https://docs.deribit.com/#public-get_last_trades_by_instrument
        https://docs.deribit.com/#public-get_last_trades_by_instrument_and_time

        get the list of most recent trades for a particular symbol.
        :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>`
        r  T)r?  include_oldNr  r;  countr  r  r  trades)r4  r  r  r  rx  "publicGetGetLastTradesByInstrumentrW  )publicGetGetLastTradesByInstrumentAndTimer"  r  parse_trades)r  r  r  r5  r	  r  r`  r  r
  r  r  s              r  fetch_tradeszderibit.fetch_trades  s    	V$%d|
 ).G%&"5$/GG##FG_EYYvy1F',GO$MOw$>>>t{{7TZ?[\HEEdkkRY[aFbcH4 8R8"5  >>r  c                    | j                          | j                  d|      }| j                  |      }|d   dd}| j                  | j	                  ||            }| j                  |di       }| j                  |dg       }i }i }	i }
t        dt        |            D ]  }||   }| j                  |d      }|d	k(  r'|| j                  |d
      | j                  |d      d}	F|dk(  r'|| j                  |d
      | j                  |d      d}r|dk(  sx|| j                  |d
      | j                  |d      d}
 i }t        dt        | j                              D ]}  }| j                  |   }| j                  |      }||dd|d   |d   d}|d   r| j	                  ||      }n/|d	   r| j	                  ||	      }n|d   r| j	                  ||
      }|||<    |S )aP  
        fetch the trading fees for multiple markets

        https://docs.deribit.com/#private-get_account_summary

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `fee structures <https://docs.ccxt.com/#/?id=fee-structure>` indexed by market symbols
        rw   r  T)r  extendedr  r   r   instrument_typer<   	maker_fee	taker_fee)r  rR  rQ  rD  r=   rR  rQ  )r  r  r  	tierBasedrR  rQ  r;   )r4  r%  r  r{  rW  r"  r  r  r  r  r  r  )r  r	  r  r  r`  r
  r  r   perpetualFee	futureFee	optionFeer  r  instrumentType
parsedFeesr  r  s                    r  fetch_trading_feeszderibit.fetch_trading_feesD  s"    	%%&8&A==& 
 33DKK4PQd 8R8vvr2		q#d)$ 	Aq'C!--c3DEN)!--c;?!--c;?	
  ;.!--c;?!--c;? 
  8+!--c;?!--c;?	!	* 
q#dll+, 	%A\\!_F[[(F "!C f~kk#|4!kk#y1!kk#y1!$Jv#	%$ r  c                 J   | j                          | j                  |      }d|d   i}|||d<   | j                  | j                  ||            }| j	                  |di       }| j                  |d      }| j                  |d      }	| j                  ||d   |      }
|	|
d<   |
S )	a-  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://docs.deribit.com/#public-get_order_book

        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        r?  r  depthr  r  	change_idr  nonce)r4  r  publicGetGetOrderBookrW  r"  r  parse_order_book)r  r  r5  r	  r  r`  r
  r  r  r  	orderbooks              r  fetch_order_bookzderibit.fetch_order_book  s     	V$vd|
 $GG--dkk'6.JKP 8R8%%fk:	!!&+6))&&2BIN	"	'r  r   c                 8    dddddd}| j                  |||      S )Nr  canceledclosedrejected)r  	cancelledfilledr  untriggeredr9  r  r   statusess      r  parse_order_statuszderibit.parse_order_status  s/    #"!
 &&99r  r,  c                 4    dddd}| j                  |||      S )NGTCr"  r!  )good_til_cancelledfill_or_killimmediate_or_cancelr9  )r  r,  timeInForcess      r  parse_time_in_forcezderibit.parse_time_in_force   s)    "'!#(

 k;GGr  c                 6    ddddd}| j                  |||      S )Nr5  r  )
stop_limit
take_limitstop_markettake_marketr9  )r  	orderType
orderTypess      r  parse_order_typezderibit.parse_order_type  s,    !!##	

 
IyAAr  r  c                    | j                  |d      }| j                  ||      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }|dk(  rd }| j                  |d      }| j                  |d      }	| j                  |d	      }
t        j                  |	|      }| j                  |d
      r|dk7  rt        j                  |
|      }d }|	t        j                  |	d      }|r|}| j                  | j                  |d            }| j                  |d      }| j                  |d      }d }|t        j                  |      }||d   d}| j                  |d      }| j                  |      }| j                  |d      }| j                  | j                  |d            }| j                  |d      }| j                  i d|d|dd d|d| j                  |      d|d|d   d|d|d|d|d|d | j                  |d!      d	|
d"|d#|d$|	d |||d%|      S )&Nr?  rP  last_update_timestampr  r  market_priceaverage_pricefilled_amountr  r@  0order_stater  
commissionr  r  r  r  time_in_force	post_onlyr  r  clientOrderIdr  r  lastTradeTimestampr  r  r,  postOnlyr  r&  
stop_pricer  r  r  )	remainingr   r  r  )r  r  r  r/   r  	safe_boolr  	string_gtr  safe_string_lower
string_absr  r"  r  
safe_orderrZ  )r  r  r  r  r  
lastUpdater  r  averageStringfilledStringr  r  r   isFilledPositiver   r  r  r  rawTyper  r  r,  r!  s                          r  parse_orderzderibit.parse_order  s   8 ##E+<=!!(F3%%e-AB	&&u.EF
eZ0&&ug6.(K((@ ''?!!%2!!,>>>&),#))&-@!#&00sC%/"(()9)9%)OP%%e[9((=$#..}=M%"6NC ""5,7$$W-1..t/?/?/WX??5+6  
E 
" 
 T 
 	 

 Y/ 
 !"4 
 fX& 
 D 
 ; 
  
 D 
 [ 
 DOOE<@ 
 f 
 D 
  }! 
" l# 
$ + 
, - 	r  r  c                     | j                          d|i}d}|| j                  |      }| j                  | j                  ||            }| j	                  |d      }| j                  ||      S )a  
        fetches information on an order made by the user

        https://docs.deribit.com/#private-get_order_state

        :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
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r  Nr  )r4  r  privateGetGetOrderStaterW  r|  r.  )r  r  r  r	  r`  r  r
  r  s           r  fetch_orderzderibit.fetch_orderk  sw     	
 [[(F//GV0LM: (3//r  r  r  r  r  c                 X   | j                          | j                  |      }|d   | j                  ||      |d}| j                  |dd      }	| j	                  |d      }
| j                  |dd      }| j                  |d      }| j                  |d	      }| j                  |d
d      }|du}|dk(  }|dk(  }|dk(  }|dk(  }|xs |xs |du}|xs |xs |du}|r|rt        | j                  dz         |xs |}|dk(  xs |xs |}|dk(  xs |xs |}| j                  |d      }| j                  |||      }|rd|d<   | j                  ||      |d<   nd|d<   |r|	|d<   d|d<   | j                  |      |d<   n?|r=||n|}| j                  ||      |d<   |	|d<   |r|rd|d<   nd|d<   n|rd|d<   nd|d<   |rd|d<   |r
d|d<   d|d<   |
|
dk(  rd|d<   |
dk(  rd|d<   |
d k(  rd!|d<   | j                  |g d"      }d}| j                  |      d#k(  r"| j                  | j!                  ||            }n!| j#                  | j!                  ||            }| j                  |d$i       }| j                  |d%      }| j                  |d&g       }||d&<   | j%                  ||      S )'a  
        create a trade order

        https://docs.deribit.com/#private-buy
        https://docs.deribit.com/#private-sell

        :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 you want to trade in units of the base currency. For perpetual and inverse futures the amount is in USD units. For options it is in the underlying assets 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.trigger]: the trigger type 'index_price', 'mark_price', or 'last_price', default is 'last_price'
        :param float [params.trailingAmount]: the quote amount to trail away from the current market price
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r  )r?  r  r  r9  r  r,  
reduceOnlyreduce_onlyr)  r*  trailingAmounttrigger_offsetNr  r  r  r  zR createOrder() only allows one of stopLossPrice or takeProfitPrice to be specifiedr5  r  r  r  r  trailing_stoptrigger_priceTreject_post_onlyr  r  r  r!  r
  r"  r	  )r,  r)  r*  r!  r3  r5  Buyr  r  r  )r4  r  amount_to_precisionr  safe_string_uppersafe_value_2r"  r  r(   r  is_post_onlyprice_to_precisionparse_to_numericrx  
capitalizeprivateGetBuyrW  privateGetSellr.  ) r  r  r  r  r  r  r	  r  r`  r9  r,  r3  r)  r*  r5  isTrailingAmountOrderisStopLimitisStopMarketisTakeLimitisTakeMarketisStopLossOrderisTakeProfitOrderisStopOrderisLimitOrderisMarketOrderexchangeSpecificPostOnlyr!  r&  r
  r  r  r  s                                    r  create_orderzderibit.create_order  sR   " 	V$%d|..vv>
 ""69lC,,V]C&&v|]K
@//&2CD++F4DFVW .d :l*},l*},%TT-t:S'X<XOSW<W0tww)}}~~%:):FKF;)JlJl#'??6;#G $$]4LfU%GFO#66vuEGG&GFO !(GI-GFO(,(=(=n(MG$%-:-F=_L'+'>'>v|'TGO$!(GI &3GFO '3GFO &3GFO '3GFO%)GM"#'GK *.G&'"e#+?(e#+@(e#+9(6  $C  D??4 E)))$++gv*FGH**4;;w+GHHj 8R8026 hv..r  c                 
   |t        | j                  dz         | j                          || j                  ||      d}|| j	                  ||      |d<   | j                  |dd      }	|	du}
|
r&| j                  |	      |d<   | j                  |d      }| j                  | j                  ||            }| j                  |di       }| j                  |d      }| j                  |d	g       }||d	<   | j                  |      S )
a  
        edit a trade order

        https://docs.deribit.com/#private-edit

        :param str id: edit order id
        :param str [symbol]: unified symbol of the market to edit an order in
        :param str [type]: 'market' or 'limit'
        :param str [side]: 'buy' or 'sell'
        :param float amount: how much you want to trade in units of the base currency. For perpetual and inverse futures the amount is in USD units. For options it is in the underlying assets 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 float [params.trailingAmount]: the quote amount to trail away from the current market price
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nz( editOrder() requires an amount argument)r  r  r  r5  r6  r  r  r  )r$   r  r4  r;  r?  r  r@  rx  privateGetEditrW  r"  r.  )r  r  r  r  r  r  r  r	  r`  r5  rD  r
  r  r  r  s                  r  
edit_orderzderibit.edit_order<  s     >#DGG.X$XYY..vv>
 #66vuEGG++F4DFVW .d : (,(=(=n(MG$%YYv'78F&&t{{7F'CD8R8026 h&&r  c                     | j                          d|i}| j                  | j                  ||            }| j                  |di       }| j	                  |      S )af  
        cancels an open order

        https://docs.deribit.com/#private-cancel

        :param str id: order id
        :param str symbol: not used by deribit cancelOrder()
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r  r  )r4  privateGetCancelrW  r|  r.  )r  r  r  r	  r`  r
  r  s          r  cancel_orderzderibit.cancel_orderf  s\     	
 ((Wf)EF(B7''r  c                    | j                          i }d}|"| j                  | j                  ||            }n:| j                  |      }|d   |d<   | j	                  | j                  ||            }| j                  d|i      gS )a  
        cancel all open orders

        https://docs.deribit.com/#private-cancel_all
        https://docs.deribit.com/#private-cancel_all_by_instrument

        :param str symbol: unified market symbol, only orders in the market of self symbol are cancelled when symbol is not None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr  r?  r  )r4  privateGetCancelAllrW  r  privateGetCancelAllByInstrumentr(  )r  r  r	  r`  r
  r  s         r  cancel_all_orderszderibit.cancel_all_ordersy  s     	>//GV0LMH[[(F)/G%&;;DKKQW<XYH OO 
 	
r  c                    | j                          i }d}d}|M| j                  d|      }| j                  |      }	|	d   |d<   | j                  | j	                  ||            }n:| j                  |      }|d   |d<   | j                  | j	                  ||            }| j                  |dg       }
| j                  |
|||      S )aX  
        fetch all unfilled currently open orders

        https://docs.deribit.com/#private-get_open_orders_by_currency
        https://docs.deribit.com/#private-get_open_orders_by_instrument

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch open orders for
        :param int [limit]: the maximum number of  open orders structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nrf   r  r  r?  r  )	r4  r%  r  !privateGetGetOpenOrdersByCurrencyrW  r  #privateGetGetOpenOrdersByInstrumentr  parse_ordersr  r  r  r5  r	  r`  r  r
  r  r  r  s              r  fetch_open_orderszderibit.fetch_open_orders  s     	>))*;VDD}}T*H"*4.GJ==dkk'SY>Z[H[[(F)/G%&??GU[@\]H(B7  >>r  c                    | j                          i }d}d}|M| j                  d|      }| j                  |      }	|	d   |d<   | j                  | j	                  ||            }n:| j                  |      }|d   |d<   | j                  | j	                  ||            }| j                  |dg       }
| j                  |
|||      S )a  
        fetches information on multiple closed orders made by the user

        https://docs.deribit.com/#private-get_order_history_by_currency
        https://docs.deribit.com/#private-get_order_history_by_instrument

        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        NrM   r  r  r?  r  )	r4  r%  r  #privateGetGetOrderHistoryByCurrencyrW  r  %privateGetGetOrderHistoryByInstrumentr  r]  r^  s              r  fetch_closed_orderszderibit.fetch_closed_orders  s     	>))*=vFD}}T*H"*4.GJ??GU[@\]H[[(F)/G%&AA$++gW]B^_H(B7  >>r  c                     | j                          d|i}| j                  | j                  ||            }| j                  |dg       }| j	                  |d||      S )a  
        fetch all the trades made from a single order

        https://docs.deribit.com/#private-get_user_trades_by_order

        :param str id: order id
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        r  r  N)r4  privateGetGetUserTradesByOrderrW  r  r  )	r  r  r  r  r5  r	  r`  r
  r  s	            r  fetch_order_tradeszderibit.fetch_order_trades  se     	
 66t{{7F7STD (B7  ue<<r  c                 j   | j                          ddi}d}|||d<   d}|v| j                  d|      }| j                  |      }	|	d   |d<   |"| j                  | j	                  ||            }n||d<   | j                  | j	                  ||            }nc| j                  |      }|d   |d	<   |"| j                  | j	                  ||            }n&||d<   | j                  | j	                  ||            }| j                  |d
i       }
| j                  |
dg       }| j                  ||||      S )a  
        fetch all trades made by the user

        https://docs.deribit.com/#private-get_user_trades_by_currency
        https://docs.deribit.com/#private-get_user_trades_by_currency_and_time
        https://docs.deribit.com/#private-get_user_trades_by_instrument
        https://docs.deribit.com/#private-get_user_trades_by_instrument_and_time

        :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
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        r  TNr  rd   r  r  r  r?  r  r  )r4  r%  r  !privateGetGetUserTradesByCurrencyrW  (privateGetGetUserTradesByCurrencyAndTimer  #privateGetGetUserTradesByInstrument*privateGetGetUserTradesByInstrumentAndTimer"  r  r  )r  r  r  r5  r	  r`  r  r
  r  r  r  r  s               r  fetch_my_tradeszderibit.fetch_my_trades	  sY    	4
 $GG>))/6BD}}T*H"*4.GJ}AA$++gW]B^_-2)*HHU\^dIef[[(F)/G%&}CCDKKPWY_D`a-2)*JJ4;;W^`fKghD 8R8"5  >>r  c                 L   |t        | j                  dz         | j                          | j                  |      }d|d   i}|||d<   | j	                  | j                  ||            }| j                  |di       }| j                  |dg       }	| j                  |	||||      S )a   
        fetch all deposits made to an account

        https://docs.deribit.com/#private-get_deposits

        :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
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        z2 fetchDeposits() requires a currency code argumentr  r  r  r  r  )	r$   r  r4  r  privateGetGetDepositsrW  r"  r  parse_transactions
r  r  r  r5  r	  r  r`  r
  r  r  s
             r  fetch_depositszderibit.fetch_depositsZ	  s     <#DGG.b$bcc==&
 $GG--dkk'6.JK* 8R8~~ffb1&&tXueVLLr  c                 L   |t        | j                  dz         | j                          | j                  |      }d|d   i}|||d<   | j	                  | j                  ||            }| j                  |di       }| j                  |dg       }	| j                  |	||||      S )a  
        fetch all withdrawals made from an account

        https://docs.deribit.com/#private-get_withdrawals

        :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
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        z5 fetchWithdrawals() requires a currency code argumentr  r  r  r  r  )	r$   r  r4  r  privateGetGetWithdrawalsrW  r"  r  ro  rp  s
             r  fetch_withdrawalszderibit.fetch_withdrawals	  s     <#DGG.e$eff==&
 $GG00Wf1MN2 8R8~~ffb1&&tXueVLLr  c                 2    ddd}| j                  |||      S )Nr*  pending)	completedunconfirmedr9  r  s      r  parse_transaction_statusz deribit.parse_transaction_status	  s&    $
 &&99r  transactionr  c                 ,   | j                  |d      }| j                  ||      }| j                  |dd      }| j                  |d      }| j	                  | j                  |d            }| j                  |d      }| j                  |d      }	d}
d }|	d	}
|	|d
}i d|d| j                  |d      d| j                  |d      d|d| j                  |      d|d|dd dd dd dd d|
d| j                  |d      d|d|d|dd d d |dS )Nr  created_timestampreceived_timestampupdated_timestampstater  r  r  
withdrawalr  r  r  txidtransaction_idr  r  	addressToaddressFromr  tagTotagFromr  r  r   r,  r  )internalcommentr  )r  r  r  r  ry  r  rZ  )r  rz  r  r  r  r  r,  r   r  feeCostr  r  s               r  parse_transactionzderibit.parse_transaction	  s   < %%k:>
&&z8<''5HJ^_	##K1DE..t/?/?W/UV"";	:"";6D C
K
$"";5
 D$$[2BC
 	

 Y/
 w
 
 4
 4
 T
 t
 D
 d&&{H=
 
 f
  w!
" t#
$ )
 	
r  positionc                    | j                  |d      }| j                  ||      }| j                  |d      }|dk(  rdnd}| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d	      }| j                         }	| j                  i d
|dd d| j                  |d      d|	d| j	                  |	      dd d| j                  |      d| j                  t        j                  t        j                  ||      d            d| j                  |      d| j                  t        j                  t        j                  ||      d            d| j                  |d      d| j                  |      d| j                  |d      d| j                  |      dd d| j                  |d      dd | j                  |d      | j                  |d      d d d |d d d d d
      S ) Nr?  r  r   longshortfloating_profit_lossinitial_marginsize_currencyro  r  r  r  r  r  lastUpdateTimestampinitialMargininitialMarginPercentage100maintenanceMarginmaintenanceMarginPercentage
entryPricer  notionalr0  unrealizedPnl	contractsr  marginRatioestimated_liquidation_pricer  )
liquidationPricer  	lastPrice
collateralr%  r  r  r-  r)  r*  )r  r  r0  safe_positionrZ  r  r/   r  r  r  r  )
r  r  r  r  r  r  initialMarginStringnotionalStringmaintenanceMarginStringcurrentTimes
             r  parse_positionzderibit.parse_position
  s   6 ##H.?@!!(F3+6%-vg((3IJ"..x9IJ))(OD"&"2"28=Q"R'')!! #
H#
$#
 d&&vx8#
 	#

 [1#
 "4#
 T../BC#
 &t'8'89K9KGL^L^_r  uC  MD  FK  :L  (M#
  !2!23J!K#
 *4+<+<W=O=OPWPbPbcz  }K  QL  NS  >T  ,U#
 $**8_E#
 )).9#
 ))(J?#
 T..}=#
 #
  D,,V^D!#
" 4##
$ !% 0 0;X Y))(LA!#7#
  	r  c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |d      }| j                  |      S )a  
        fetch data on a single open contract trade position

        https://docs.deribit.com/#private-get_position

        :param str symbol: unified market symbol of the market the position is held in, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        r?  r  r  )r4  r  privateGetGetPositionrW  r|  r  r  s          r  fetch_positionzderibit.fetch_positionG
  sn     	V$vd|
 --dkk'6.JK6 (3""6**r  c                 .   | j                          | j                  |d      }i }|+| j                  |d      }| j                  |      }|d   |d<   | j	                  | j                  ||            }| j                  |d      }| j                  ||      S )aw  
        fetch all open positions

        https://docs.deribit.com/#private-get_positions

        :param str[]|None symbols: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.currency]: currency code filter for positions
        :param str [params.kind]: market type filter for positions 'future', 'option', 'spot', 'future_combo' or 'option_combo'
        :param int [params.subaccount_id]: the user id for the subaccount
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        r  r  r  )r4  r  rx  r  privateGetGetPositionsrW  r  parse_positions)r  r  r	  r  r`  r  r
  r  s           r  fetch_positionszderibit.fetch_positionst
  s     	
3YYvz2F}}T*H"*4.GJ..t{{7F/KL< (3##FG44r  c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |      S )a  
        fetch the historical volatility of an option market based on an underlying asset

        https://docs.deribit.com/#public-get_historical_volatility

        :param str code: unified currency code
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `volatility history objects <https://docs.ccxt.com/#/?id=volatility-structure>`
        r  r  )r4  r   publicGetGetHistoricalVolatilityrW  parse_volatility_history)r  r  r	  r  r`  r
  s         r  fetch_volatility_historyz deribit.fetch_volatility_history
  s^     	==&
 88Wf9UV ,,X66r  c                    | j                  |dg       }g }t        dt        |            D ]Q  }| j                  ||   d      }| j	                  ||   d      }|j                  ||| j                  |      |d       S |S )Nr  r   r   )r  r  r  
volatility)r"  r  r  r  r  rV  rZ  )r  r  volatilityResultr  r  r  volatilityObjs          r  r  z deribit.parse_volatility_history
  s      ??:xDq#./0 	A))*:1*=qAI ,,-=a-@!DMMM%& LL3+	 	 r  c                 L   |t        | j                  dz         | j                          | j                  |      }d|d   i}|||d<   | j	                  | j                  ||            }| j                  |di       }| j                  |dg       }	| j                  |	||||      S )a-  
        fetch a history of internal transfers made on an account

        https://docs.deribit.com/#private-get_transfers

        :param str code: unified currency code of the currency transferred
        :param int [since]: the earliest time in ms to fetch transfers for
        :param int [limit]: the maximum number of  transfers structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `transfer structures <https://docs.ccxt.com/#/?id=transfer-structure>`
        z3 fetchTransfers() requires a currency code argumentr  r  r  r  r  )	r$   r  r4  r  privateGetGetTransfersrW  r"  r  parse_transfers)
r  r  r  r5  r	  r  r`  r
  r  	transferss
             r  fetch_transferszderibit.fetch_transfers
  s     <#DGG.c$cdd==&
 $GG..t{{7F/KLD 8R8NN6626	##IxvNNr  fromAccount	toAccountc                    | j                          | j                  |      }||d   |d}| j                  |d      }| j                  |d      }|0| j	                  | j
                  di       }	| j                  |	dd      }d}
|dk(  r"| j                  | j                  ||            }
n!| j                  | j                  ||            }
| j                  |
di       }| j                  ||      S )	a_  
        transfer currency internally between wallets on the same account

        https://docs.deribit.com/#private-submit_transfer_to_user
        https://docs.deribit.com/#private-submit_transfer_to_subaccount

        :param str code: unified currency code
        :param float amount: amount to transfer
        :param str fromAccount: account to transfer from
        :param str toAccount: account to transfer to
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `transfer structure <https://docs.ccxt.com/#/?id=transfer-structure>`
        r  )r  r  destinationr  Nr   r  privateGetSubmitTransferToUserr  )r4  r  r  rx  r"  r  r  rW  r  r|  parse_transfer)r  r  r  r  r  r	  r  r`  r  transferOptionsr
  r  s               r  r   zderibit.transfer   s     	==& $

 !!&(368,>"oodllJKO%%oxAghF55::4;;wPV;WXH@@WV\A]^H$ (B7""6844r  r   c                 v   | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }|| j                  |d      | j                  |      | j                  |d      | j	                  ||      ||k7  ||k(  || j                  |      d	S )	Nr|  r  
other_sider  r  r  r  )	r  r  r   r  r  r  r  r  r  )safe_timestampr  parse_transfer_statusr  r  rZ  )r  r   r  r  r   r:  r  r  s           r  r  zderibit.parse_transferS  s     ''2EF	!!(G4""8\:$$X{;	%%h
;
""8T2008&&x://
HE$/"g-"Y/

 
	
r  c                 6    ddddd}| j                  |||      S )Nrv  r*  r   )prepared	confirmedr   waiting_for_adminr9  r  s      r  r  zderibit.parse_transfer_statusr  s,    !$!*	
 &&99r  r  c                 \   | j                  ||      \  }}| j                  |       | j                          | j                  |      }|d   ||d}| j                  | j                  | j                        |d<   | j                  | j                  ||            }| j                  ||      S )a  
        make a withdrawal

        https://docs.deribit.com/#private-withdraw

        :param str code: unified currency code
        :param float amount: the amount to withdraw
        :param str address: the address to withdraw to
        :param str tag:
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        r  )r  r  r  tfa)	handle_withdraw_tag_and_paramsr  r4  r  twofatotpprivateGetWithdrawrW  r  )	r  r  r  r  r  r	  r  r`  r
  s	            r  r   zderibit.withdraw{  s     99#vFV7#==& 
 ::!!YYtzz2GEN**4;;w+GH%%h99r  c                 <    || j                  |d      ddd d di dS )Nr  F)r  r  )r  r   r  r  )r  )r  r  r  s      r  parse_deposit_withdraw_feez"deribit.parse_deposit_withdraw_fee  s<     ''-=>#
 " 
 	
r  codesc                     | j                          | j                  |      }| j                  |dg       }| j                  ||d      S )a^  
        fetch deposit and withdraw fees

        https://docs.deribit.com/#public-get_currencies

        :param str[]|None codes: list of unified currency codes
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a list of `fee structures <https://docs.ccxt.com/#/?id=fee-structure>`
        r  r  )r4  r  r  parse_deposit_withdraw_fees)r  r  r	  r
  r  s        r  fetch_deposit_withdraw_feesz#deribit.fetch_deposit_withdraw_fees  sI     	..v6. ~~h"5//eZHHr  c                     | j                          | j                  |      }| j                         }|d   |dz
  |d}| j                  | j	                  ||            }| j                  ||      S )a  
        fetch the current funding rate

        https://docs.deribit.com/#public-get_funding_rate_value

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.start_timestamp]: fetch funding rate starting from self timestamp
        :param int [params.end_timestamp]: fetch funding rate ending at self timestamp
        :returns dict: a `funding rate structure <https://docs.ccxt.com/#/?id=funding-rate-structure>`
        r  i t)r?  r  r  )r4  r  r0  publicGetGetFundingRateValuerW  parse_funding_rate)r  r  r	  r  timer`  r
  s          r  fetch_funding_ratezderibit.fetch_funding_rate  sx     	V$  "%d|#'9:!

 44T[[&5QR &&x88r  c                 F   | j                          | j                  |      }d}| j                  |dd      \  }}d}d}|r)| j                  d||||| j	                  |ddi      |      S | j                  |      dz  }	| j                         }
d	}||
|z
  }n||z   }
|d
   |dz
  d}| j                  |dd      }|| j                  |dg      }||d<   n|
|d<   d|v r9| j                  |d      }| j                  |||	z        }t        |d   |      |d<   | j                  | j	                  ||            }g }| j                  |dg       }t        dt        |            D ]*  }||   }| j                  ||      }|j!                  |       , | j#                  ||||      S )a>  
        fetch the current funding rate

        https://docs.deribit.com/#public-get_funding_rate_history

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch funding rate history for
        :param int [limit]: the maximum number of entries to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: fetch funding rate ending at self timestamp
        :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 rate structure <https://docs.ccxt.com/#/?id=funding-rate-structure>`
        FrX   r  i  r   isDeribitPaginationCallTr;  l    H4 r  r   )r?  r  r  r  r  r   )r4  r  rT  r  rW  r  r0  r  rx  r  r  publicGetGetFundingRateHistoryr"  r  r  r  rV  filter_by_symbol_since_limit)r  r  r  r5  r	  r  r  maxEntriesPerRequesteachItemDurationr  r  monthr`  r  maxUntilr
  ratesr  r  frrates                        r  fetch_funding_rate_historyz"deribit.fetch_funding_rate_history  s    	V$88AZ\fg&"::;TV\^cejl|  C  J  J  KQ  Tm  os  St  u  wK  L  L''(89D@  "(=5LE5=D%d|$qy
 ##FG_EYYvy1F',GO$'+GO$$.YYv'@AFxxux'78H'*7?+CX'NGO$66t{{7F7ST  8R8q#f+& 	AB**2v6DLL	 00uMMr  c                     | j                  |d      }| j                  |      }| j                  |dd      }i d|d| j                  d |      dd d| j	                  |d      d	d d
d d|d|d|dd dd dd dd dd dd dd dd ddiS )Nr  r  interest_8hr  r  r  r  r  interestRateestimatedSettlePricer  fundingRatefundingTimestampfundingDatetimenextFundingRatenextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetimeinterval8h)r  rZ  safe_number_2r  r  )r  r  r  r  r  r  s         r  r  zderibit.parse_funding_rate<  s0   & %%h<	<<	*##HhF
H
d&&tV4
 
 $**8]C	

 D
 #D
 
 
 6
 
 t
 t
 #D
 "4
 "4
  '!
" &t#
$ %
 	
r  c           
         | j                          d}| j                  |dd      \  }}|r| j                  d||||ddd      S | j                  |      }|d   r!t	        | j
                  dz   |d   z   d	z         |d
   dd}|||d<   |||d<   | j                  | j                  ||            }| j                  |di       }	| j                  |	d      }
| j                  |	dg       }| j                  |
|      }| j                  ||||      S )a$  
        retrieves the public liquidations of a trading pair

        https://docs.deribit.com/#public-get_last_settlements_by_currency

        :param str symbol: unified CCXT market symbol
        :param int [since]: the earliest time in ms to fetch liquidations for
        :param int [limit]: the maximum number of liquidation structures to retrieve
        :param dict [params]: exchange specific parameters for the deribit 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: an array of `liquidation structures <https://docs.ccxt.com/#/?id=liquidation-structure>`
        Fr^   r  continuationNr9   z& fetchLiquidations() does not support r   marketsr  
bankruptcyr?  r  search_start_timestampr  r  settlements)r4  rT  fetch_paginated_call_cursorr  r*   r  'publicGetGetLastSettlementsByInstrumentrW  r"  r  add_pagination_cursor_to_resultparse_liquidations)r  r  r  r5  r	  r  r  r`  r
  r  cursorr  settlementsWithCursors                r  fetch_liquidationszderibit.fetch_liquidationsg  sV    	88ATV`a&334GQVX]_egu  xF  HL  M  MV$&>tww)QQTZ[aTbbeoopp%d| 
 05G,-$GG??GU[@\]2 8R8!!&.9oofmR@ $ D DV[ Y&&'<feUSSr  c                 r    |4t        |      }|dkD  r$|d   }||dz
     }||d<   ||d<   ||d<   |||dz
  <   |S )Nr   r   r  )r  )r  r  r  
dataLengthfirstr  s         r  r   z'deribit.add_pagination_cursor_to_result  s_    TJA~QJN+(.n%'-^$Q'+Z!^$r  c                    |t        | j                  dz         | j                          | j                  |      }|d   r!t	        | j                  dz   |d   z   dz         |d   dd}|||d	<   |||d
<   | j                  | j                  ||            }| j                  |di       }| j                  |dg       }	| j                  |	|||      S )a,  
        retrieves the users liquidated positions

        https://docs.deribit.com/#private-get_settlement_history_by_instrument

        :param str symbol: unified CCXT market symbol
        :param int [since]: the earliest time in ms to fetch liquidations for
        :param int [limit]: the maximum number of liquidation structures to retrieve
        :param dict [params]: exchange specific parameters for the deribit api endpoint
        :returns dict: an array of `liquidation structures <https://docs.ccxt.com/#/?id=liquidation-structure>`
        z1 fetchMyLiquidations() requires a symbol argumentr9   z( fetchMyLiquidations() does not support r  r  r  r  r  r  r  r  r  )
r$   r  r4  r  r*   *privateGetGetSettlementHistoryByInstrumentrW  r"  r  r  )
r  r  r  r5  r	  r  r`  r
  r  r  s
             r  fetch_my_liquidationszderibit.fetch_my_liquidations  s     >#DGG.a$abbV$&>tww)SSV\]cVddgqqrr%d| 
 05G,-$GGBB4;;wX^C_`2 8R8nnV]B?&&{FE5IIr  c                     | j                  |d      }| j                  || j                  d |      d | j                  |d      d | j                  |d      d || j	                  |      d	      S )Nr  r  session_bankrupcy)	r  r  r  r  r  	baseValue
quoteValuer  r  )r  safe_liquidationr  r  rZ  )r  liquidationr  r  s       r  parse_liquidationzderibit.parse_liquidation  sz     %%k;?	$$&&tV4 ,,V^D))+7JK"Y/
&
 
 
	r  c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |di       }| j                  ||      S )a  
        fetches an option contracts greeks, financial metrics used to measure the factors that affect the price of an options contract

        https://docs.deribit.com/#public-ticker

        :param str symbol: unified symbol of the market to fetch greeks for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `greeks structure <https://docs.ccxt.com/#/?id=greeks-structure>`
        r?  r  r  )r4  r  r  rW  r"  parse_greeksr  s          r  fetch_greekszderibit.fetch_greeks   ss     	V$vd|
 ''GV(DE^ 8R8  00r  greeksc                    | j                  |d      }| j                  |d      }| j                  ||      }| j                  |di       }i d|d|d| j	                  |      d| j                  |d      d| j                  |d      d| j                  |d      d	| j                  |d	      d
| j                  |d
      d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      | j                  |d      |dS )Nr  r?  r  r  r  deltagammathetavegarhobidSizer  askSizer  bidImpliedVolatilitybid_ivaskImpliedVolatilityask_ivmarkImpliedVolatilitymark_ivbidPricer  askPricer  r  r  r  r  underlying_price)underlyingPricer  )r  r  r  r"  rZ  r  )r  r  r  r  r  r  r  s          r  r  zderibit.parse_greeksA  s   P %%fk:	##F,=>!!(F3"5
f

 Y/
 T%%eW5	

 T%%eW5
 T%%eW5
 D$$UF3
 4##E51
 t''0AB
 t''0AB
 #D$4$4VX$F
 #D$4$4VX$F
 $T%5%5fi%H
 ((1AB
 ((1AB
  ))&,?!
" ))&,?#
$  $//8JK'
 	
r  c                    | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |dg       }| j                  |di       }| j                  |d|      S )a  
        fetches option data that is commonly found in an option chain

        https://docs.deribit.com/#public-get_book_summary_by_instrument

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `option chain structure <https://docs.ccxt.com/#/?id=option-chain-structure>`
        r?  r  r  r   N)r4  r  #publicGetGetBookSummaryByInstrumentrW  r  r|  parse_option)r  r  r	  r  r`  r
  r  chains           r  fetch_optionzderibit.fetch_option  s     	V$vd|
 ;;DKKQW<XYB (B7vq"-  f55r  c                     | j                          | j                  |      }|d   dd}| j                  | j                  ||            }| j	                  |dg       }| j                  |dd      S )a  
        fetches data for an underlying asset that is commonly found in an option chain

        https://docs.deribit.com/#public-get_book_summary_by_currency

        :param str code: base currency to fetch an option chain for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a list of `option chain structures <https://docs.ccxt.com/#/?id=option-chain-structure>`
        r  r=   )r  r>  r  r@  r?  )r4  r  r  rW  r  parse_option_chain)r  r  r	  r  r`  r
  r  s          r  fetch_option_chainzderibit.fetch_option_chain  sw     	==& 
 99$++gv:VWB (B7&&v@QRRr  r+  c                    | j                  |d      }| j                  ||      }| j                  |d      }| j                  ||      }| j                  |d      }i d|d|d|d   d|d| j	                  |      dd d	| j                  |d
      d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      dd d| j                  |d      d| j                  |d      d| j                  |d      S )Nr?  r@  r  r  r  r  r  impliedVolatilityopenInterestopen_interestr$  r  r%  r  midPrice	mid_pricer  r  r  r  r'  r&  r  r  price_changer  r  r  
volume_usd)r  r  r  r  rZ  r  )r  r+  r  r  r  r  r  r  s           r  r*  zderibit.parse_option  s   0 ##E+<=!!(F3%%e_=
&&z8<%%e[9	
E

 fX&
 	

 Y/
  
 D,,UOD
 ((<
 ((<
 ((<
 ))%>
 ))%8
 t//7IJ
 d
 $**5.A
  $**5(;!
" 4++E<@#
 	
r  c                 "    | j                         S N)r0  )r  s    r  r  zderibit.nonce  s      ""r  r  GETc                    d| j                   z   dz   |z   dz   |z   }|dk(  r|r|d| j                  |      z   z  }|dk(  r| j                          t        | j	                               }t        | j                               }	d}
|r|d| j                  |      z   z  }|dz   |z   dz   |
z   dz   }|	dz   |z   dz   |z   }| j                  | j                  |      | j                  | j                        t        j                        }dd	| j                  z   d
z   |	z   dz   |z   dz   dz   |z   i}| j                  d   d   |z   }||||dS )Nz/api/r  r  ?r  rG  
Authorizationzderi-hmac-sha256 id=z,ts=z,sig=,znonce=r   r   )r   r  bodyheaders)r  	urlencodecheck_required_credentialsstrr  r0  hmacencodesecrethashlibsha256apiKeyr  )r  pathr   r  r	  rA  r@  r`  r  r  requestBodyrequestDatar   	signaturer   s                  r  signzderibit.sign  su   -3c9C?$F(?3!777)++-

%ED--/0IK3!777 4-'1D8;FMKt#e+d2[@D		$++d"3T[[5Mw~~^I!7$++!E!NQZ!Z]d!dgp!psv!v  zB  "B  EJ  "JG iiv&0fdwOOr  httpCodereasonr   r  rA  r@  c
                     |sy | j                  |d      }
|
L| j                  |
d      }| j                  dz   |z   }| j                  | j                  ||       t        |      y )Nerrorr   )r"  r  r  throw_exactly_matched_exceptionr  r!   )r  rP  rQ  r   r  rA  r@  r
  requestHeadersrL  rS  	errorCodefeedbacks                r  handle_errorszderibit.handle_errors4  sh     '2((7Iww}t+H00)XV))r  )NNNNr9  )NN)g__name__
__module____qualname__r   r  rD  r  r   r   r   r  r   r  r   r   r%  r2  r    r   r7  r;  rj  r   rv  r}  r
   r  r  dictr   r  r  r   r   r  listr  r   r  r  r   r  r   r  r  r  r  r   r.  r1  r   r   floatr   rO  rR  rU  rY  r_  rc  rf  rl  r   rq  rt  ry  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  rO  intrY  __classcell__)r  s   @r  r1   r1      s   \# \|H
3 H
TYC Y YRU Yjm Y  zI Y !# 5s 5, ') AZ AF 46 5 #% 
B %' .+4= .+`
, $& b$v, bH) )( $& B*( B*H 8: %
3 %
n %
N 79 *
# *
^ *
XK4 K K6 KZ 02 -13 -1f -1^ 04B MHW MH7 MH^ 26DW[df AJ# AJc AJQT AJkoptku AJFT Tv T Tl 6:UW <?3 <?s <?# <?\`af\g <?| )+ o{ ob :>b ?s ?3 ?Y ?B: :Hs HBX Xv X Xt 26b 00c 003 00d gksu ]/3 ]/i ]/y ]/RW ]/`c ]/~ `drv  @B ('S ('# ('Y ('i ('Y\ ('lo ('T 37r (s (C (& /32 "
 "
H /3TXac ? ?3 ?c ?hlmrhs ?: 154VZce ?# ?S ?PS ?jnotju ?: 9=4^bkm 4=S 4=# 4=S 4=X[ 4=l -1tRV_a K?c K? K?C K?Z *.Dt\^ ,M3 ,Mc ,M ,Mcghsct ,M\ -1tRV_a 0Mc 0M 0MC 0Mfjkvfw 0Md:s :B
T B
X B
Q\ B
H@t @V @D 24 ++S ++Z 26b 35w 35T(^ 35j :< 7S 7@8 +/TPT]_ 9OC 9Os 9O# 9Odhivdw 9Ov [] 15S 15% 15c 15c 15an 15f
t 
x 
= 
>:C :C : DHPR :S :% :# :Wb ::
 
4 <@ #I #IJ 68 9 9K 9B 8<$]ajl BN BNC BNWZ BNH)
6 )
[ )
V <@d[] :T :TS :T :Tx
 37TX\eg 5JC 5Js 5JRU 5JnV 4 02 ?13 ?1f ?1B@
4 @
 @
6 @
D 02 263 26f 26h 46 2Ss 2S+ 2Sh/
$ /
( /
6 /
]c /
b# &eBSW P*c 3 S # X\ dg r  r1   )6ccxt.base.exchanger   ccxt.abstract.deribitr   rH  ccxt.base.typesr   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   typingr    ccxt.base.errorsr!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   ccxt.base.decimal_to_precisionr.   ccxt.base.preciser/   r1    r  r  <module>rj     s    ( -  g  g  g  g  g  g  g  g  * 0 - . ' . + ) * ) + 1 * 4 %o8h o8r  