
    !:hEf                    @   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/m0Z0  G d dee      Z1y)    )Exchange)ImplicitAPIN)AnyBalances
CurrenciesCurrencyDepositAddressGreeksIntLedgerEntryLeverage
MarginModeMarginModificationMarketNumOptionOrder	OrderBook	OrderSide	OrderTypePositionStrStringsTickerTickersFundingRateFundingRatesTradeMarketInterface)List)ExchangeError)AuthenticationError)ArgumentsRequired)
BadRequest)	BadSymbol)InsufficientFunds)InvalidOrder)OrderNotFound)ExchangeNotAvailable)	TICK_SIZE)Precisec                   @    e Zd Zdef fdZdefdZdcdededed	ede	f
 fd
Z
i fdefdZi fdZi fdefdZdi f fd	Zd Zi fdee   fdZddd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i fdededefdZdddededefdZddi fdedededee   fdZddded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 Z$i fde#fd!Z%i fdefd"Z&di fdedee'   fd#Z(ddd$edefd%Z)d&efd'Z*ddd(edede+fd)Z,di fded*e-d+e.d,e/d-e0f
d.Z1ddi fd/eded*e-d+e.d,e0d-e0fd0Z2di fd/edefd1Z3di fdefd2Z4dddi fdedededee+   fd3Z5dddi fdedededee+   fd4Z6dddi fdededefd5Z7dddi fdededefd6Z8dddi fd7edededee9   fd8Z:d9 Z;ddd:ed;e<de9fd<Z=i fd7ede>fd=Z?ddd;e<de>fd>Z@i fdedeAfd?ZBdi fdedeCfd@ZDdddedeAfdAZEi fded,e/deFfdBZGi fded,e/deFfdCZHi fdedeFfdDZIdddEededeFfdFZJi fdefdGZKdddefdHZLi fdedeMfdIZNdddJededeMfdKZOdi fdJedefdLZPdddi fdededefdMZQdN ZRdO ZSi fdedeTfdPZUdddQededeTfdRZVi fdee'   fdSZWi fdedeXfdTZYdddUedeXfdVZZi fdede[fdWZ\dedXed;e<dede[fdYZ]dZd[i ddfd\Z^d7e_d]ed^ed_ed`edaefdbZ` xZaS )fdeltareturnc                    | j                  t        t        |          dddg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
dKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d[d\d]d]d\d^d_gd`dadbdcg ddig deg dfg dgg dhdid\djdd| j	                  dk      | j	                  dl      | j	                  dm      | j	                  dk      g| j	                  dn      | j	                  do      g| j	                  dp      | j	                  do      g| j	                  dq      | j	                  dr      g| j	                  ds      | j	                  dt      g| j	                  du      | j	                  dv      g| j	                  dw      | j	                  dx      gg| j	                  dm      | j	                  dr      g| j	                  dn      | j	                  dr      g| j	                  dp      | j	                  dt      g| j	                  dq      | j	                  dv      g| j	                  ds      | j	                  dy      g| j	                  du      | j	                  dz      g| j	                  dw      | j	                  dz      ggd{d|i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
dddd
dd d
dd
d
d
dd d
ddddd
d
d
dddid	ddiddiddidddiddiddt
        dddt        t        t        t        t        t        t        t        t        t        t        t        t        di dd      S )Nr-   zDelta ExchangeVCi,  v2CORSspotTmarginFswapfutureoption	addMargincancelAllOrderscancelOrdercloseAllPositionsclosePositioncreateOrdercreateReduceOnlyOrder	editOrderfetchBalancefetchClosedOrdersfetchCurrenciesfetchDepositfetchDepositAddressfetchDepositAddressesfetchDepositAddressesByNetworkfetchDepositsfetchFundingHistoryfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchGreeksfetchIndexOHLCVfetchLedgerfetchLeveragefetchLeverageTiersfetchMarginModefetchMarginModesfetchMarketLeverageTiersfetchMarketsfetchMarkOHLCVfetchMySettlementHistoryfetchMyTrades
fetchOHLCVfetchOpenInterestfetchOpenOrdersfetchOptionfetchOptionChainfetchOrderBookfetchPositionfetchPositionModefetchPositionsfetchPremiumIndexOHLCVfetchSettlementHistoryfetchStatusfetchTickerfetchTickers	fetchTimefetchTradesfetchTransferfetchTransfersfetchUnderlyingAssetsfetchVolatilityHistoryfetchWithdrawalfetchWithdrawalsreduceMarginsetLeverage	setMarginsetMarginModesetPositionModetransferwithdraw1m3m5m15m30m1h2h4h6h1d7d1w2w30d)ru   rv   rw   rx   ry   rz   r{   r|   r}   r~   r   r   r   1Mzchttps://user-images.githubusercontent.com/1294454/99450025-3be60a00-2931-11eb-9302-f4fd8d8589aa.jpgz"https://testnet-api.delta.exchange)publicprivatezhttps://api.delta.exchangezhttps://www.delta.exchangezhttps://docs.delta.exchangezhttps://www.delta.exchange/feesz2https://www.delta.exchange/app/signup/?code=IULYNB)logotestapiwwwdocfeesreferralget)assetsindicesproductszproducts/{symbol}tickersztickers/{symbol}zl2orderbook/{symbol}ztrades/{symbol}statszhistory/candleszhistory/sparklinessettings)orders%products/{product_id}/orders/leveragezpositions/margined	positionszorders/historyfillszfills/history/download/csvzwallet/balanceszwallet/transactionszwallet/transactions/downloadz%wallets/sub_accounts_transfer_historyzusers/trading_preferencessub_accountsprofilezdeposits/addressorders/leverage)	r   orders/bracketorders/batchr   zpositions/change_marginzpositions/close_allz$wallets/sub_account_balance_transferzorders/cancel_afterr   )r   r   r   zpositions/auto_topupzusers/update_mmpzusers/reset_mmp)r   z
orders/allr   )r   postputdeletetradingz0.0015z0.00100100z0.00132501000z0.0015000z0.000910000z0.0007520000z0.00065z0.0006z0.0005)takermaker)	tierBased
percentager   r   tiersnetworkszTRC20(TRON)z
BEP20(BSC))TRC20BEP20)lastmarkindex)triggerPriceTypeprice)IOCFOKPOGTD)
marginModetriggerPricer   triggerDirectionstopLossPricetakeProfitPriceattachedStopLossTakeProfittimeInForcehedgedselfTradePreventiontrailingicebergleveragemarketBuyByCostmarketBuyRequiresPriced   i )r   limitdaysBack	untilDayssymbolRequired)r   r   triggerr   r   i     )r   r   r   daysBackCanceledr   r   r   r   r     )	sandboxr=   createOrdersrW   
fetchOrderrZ   fetchOrdersrA   rX   extendsdefault)linearinverse)r   r3   r5   r6   )apiKeysecret)insufficient_marginorder_size_exceed_availablerisk_limits_breachedinvalid_contractimmediate_liquidationout_of_bankruptcy!self_matching_disrupted_post_onlyimmediate_execution_post_only
bad_schemainvalid_api_keyinvalid_signatureopen_order_not_foundunavailable)exactbroad)idname	countries	rateLimitversionhas
timeframesurlsr   r   optionsfeaturesprecisionModerequiredCredentials
exceptions)deep_extendsuperr-   describeparse_numberr*   r&   r'   r$   r%   r"   r(   r)   )self	__class__s    D/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/delta.pyr   zdelta.describe   s   eT ; =$DDD %D 	D
 %D $D TD "4D tD $TD  D tD (D TD D  $T!D" "4#D$ %D& &t'D( ()D* 1%+D,  -D. &u/D0 #D1D2 *53D4 $T5D6 t7D8 "49D: t;D<  =D> %e?D@ "4ADB #ECDD +EEDF GDH !$IDJ +EKDL  MDN dODP $TQDR "4SDT tUDV #EWDX !$YDZ  [D\ $U]D^ !$_D` )%aDb )$cDd teDf tgDh iDj TkDl tmDn  oDp !$qDr (sDt )%uDv "4wDx #DyDz {D| t}D~ UD@  ADB "5CDD EEDF EGDL " ~BC
 ;; 41 :P&  "$
M+#=~ !%"&!..x8!..x8 "..s3T5F5Fx5PQ!..u5t7H7H7RS!..u5t7H7H7RS!..v68I8I'8RS!..v68I8I(8ST!..w79J9J99UV!..w79J9J99UV" "..s3T5F5Fw5OP!..u5t7H7H7QR!..u5t7H7H7RS!..v68I8I)8TU!..v68I8I(8ST!..w79J9J89TU!..w79J9J89TU": *)  $&+(, %)$(%)-
 -2).+004%)7 $(#'"&#(	( #(/4$)#($)+027;$> %)&+!$$*%+*/& #'&+!$#($)*/( $(&+!$$*,-%+#($)*/	*  #y?B y
 "9 "9 	 "9 "9 	YTj '$ ,=3?,6(1-9)59E5A",':)<,9#7 #O	{@
 { {	    symbolc                 6   d}|j                  d      }|j                  d      }d }d }d }|j                  d      dkD  r7| j                  |d      }| j                  |d      }| j                  |d      }n6| j                  |d      }| j                  |d      }| j                  |d      }||dd  |d	d z   |dd	 z   }|}| j                  |d	      }	| j                  |      }
| j	                  |
      }i d
|dz   |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| j                  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USDT-/r   r            r   r   :basequotesettlebaseIdquoteIdsettleIdactiveFtyper7   r   r   r3   r5   r6   Tr4   1Ccallr   amountr   minmax)r  r   cost)	contractcontractSizeexpiryexpiryDatetime
optionTypestrike	precisionlimitsinfo)splitfindsafe_stringconvert_expire_date	parse8601r   )r   r   r	  optionParts
symbolBaser  r  r  r
  r  datetime	timestamps               r   create_expired_option_marketz"delta.create_expired_option_marketX  s   ll3'\\#&

;;sb ##J2D%%k15F))+q9J##K3D%%k15F))+q9JABZ&1+-q;F!!+q1++F3NN8,	+
*s"T)C/&83>G+
dSj5(3.7#=FLvUX[[^hh+
 D+
 U	+

 f+
 d+
 u+
 +
 e+
 H+
 d+
 t+
 E+
 E+
 e+
  d!+
" e#+
$  --c2&%/3%6&U''/  
  
   U+
 +	
r   NmarketIdmarket	delimiter
marketTypec                    |d uxrJ |j                  d      xs7 |j                  d      xs$ |j                  d      xs |j                  d      }|r|| j                  vr| j                  |      S t        t
        |   ||||      S )Nz-Cz-PzC-zP-)endswith
startswithmarkets_by_idr+  r   r-   safe_market)r   r,  r-  r.  r/  isOptionr   s         r   r4  zdelta.safe_market  s    D(  e0A0A$0G  0dXM^M^_cMd  0djrj}j}  C  kD  0d  JR  J]  J]  ^b  JcX););;44X>>UD-h	:VVr   c                 p    | j                  |      }| j                  |di       }| j                  |dd      S )a  
        fetches the current integer timestamp in milliseconds from the exchange server
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        resultserver_timeMbP?)publicGetSettings	safe_dictsafe_integer_product)r   paramsresponser7  s       r   
fetch_timezdelta.fetch_time  s;     ))&1(B7((FFr   c                     | j                  |      }| j                  |di       }| j                  |d      }|dk(  rdnd}| j                  |dd| j	                               }||dd|d	S )
a  
        the latest known information on the availability of the exchange API
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `status structure <https://docs.ccxt.com/#/?id=exchange-status-structure>`
        r7  under_maintenancetruemaintenanceokr8  r9  N)statusupdatedetaurlr!  )r:  r;  r$  r<  milliseconds)r   r=  r>  r7  underMaintenancerE  rF  s          r   fetch_statuszdelta.fetch_status  s     ))&1l (B7++F4GH#3v#=D++FM5$J[J[J]^
 	
r   c                 ,   | j                  |      }| j                  |dg       }i }t        dt        |            D ]  }||   }| j	                  |d      }| j                  |d      }| j                  |      }	| j                  |dg       }
i }t        dt        |
            D ]  }|
|   }| j	                  |d      }| j                  |      }||| j	                  |d      || j	                  |d      d	k(  | j	                  |d
      d	k(  | j	                  |d      d	k(  | j                  |d      | j                  |d      dd| j                  |d      dddd	||<    | j                  |||	| j	                  |d      |d| j	                  |d
      d	k(  | j	                  |d      d	k(  | j                  |d      | j                  | j                  | j	                  |d                  ddd| j                  |d      ddd|dd      ||	<    |S )a  
        fetches all available currencies on an exchange

        https://docs.delta.exchange/#get-list-of-all-assets

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        r7  r   r   r   r   networkr   rE  enableddeposit_statuswithdrawal_statusbase_withdrawal_feemin_deposit_amountNr  min_withdrawal_amount)depositrt   )	r   rM  r   r!  r  rT  rt   feer   r  )r  rt   crypto)r   	numericIdcoder   r!  r  rT  rt   rU  r  r   r   r  )publicGetAssets	safe_listrangelenr$  safe_integersafe_currency_codenetwork_id_to_codesafe_numbersafe_currency_structurer   parse_precision)r   r=  r>  
currenciesr7  icurrencyr   rW  rX  chainsr   jchain	networkIdnetworkCodes                   r   fetch_currencieszdelta.fetch_currencies  si    ''/b ^^Hh;
q#j/* 3	A!!}H!!(H5B))(D9I**2.D^^Hj"=FH1c&k* q	 ,,UI>	"55i@#* ,,UF;!"..uh?9L#//7GHIU $ 0 08K LPY Y++E3HI $(#3#3E;O#P#'$
 $(#3#3E;R#S#'%	)%	0  77&((6: ++H6FG9T ,,X7JKyX''2GH!..t/C/CDDTDTU]_jDk/lm&*48#//:QR#! % '9 F4L?3	h r   Fc                 P   t         t        |   ||      }| j                  | j                  d      }||r(| j                  | j                        | j                  d<   | j                  | j                  d      }||r(| j                  | j                        | j                  d<   |S )NcurrenciesByNumericIdmarketsByNumericId)r   r-   load_marketsr;  r   index_by_stringified_numeric_idrc  markets)r   reloadr=  rq  rm  rn  r   s         r   ro  zdelta.load_marketsg  s    t1&&A $t||=T U!)f484X4XY]YhYh4iDLL01!^^DLL:NO&6151U1UVZVbVb1cDLL-.r   c                     i }|y t        |j                               }t        dt        |            D ]&  }||   }||   }| j	                  |d      }|"|||<   ( |S )Nr   rW  )listkeysr[  r\  r$  )r   inputr7  ru  rd  keyitemnumericIdStrings           r   rp  z%delta.index_by_stringified_numeric_idq  sw    =EJJL!q#d)$ 	+Aq'C:D"..t[AO&&*F?#	+ r   c                    | j                  |      }| j                  |dg       }g }t        dt        |            D ]&  }||   }| j	                  |d      }|dk(  r!| j                  |di       }| j                  |di       }	| j                  |d      }
| j                  |di       }| j	                  |	d	      }| j	                  |d	      }| j	                  |
d	      }| j	                  |d	      }| j                  |d
      }| j                  |      }| j                  |      }| j                  |      }|dk(  }|dk(  }|dk(  }|dk(  }|dk(  }|dk(  }|xs |xs |}| j	                  |d      }| j	                  |d      }| j                  |      }| j                  |d      }d}|r1| j                  | j                  | j	                  |d                  }n| j                  d      }||k(  } d}!|dz   |z   }"|s|s|rL|"dz   |z   }"|s|r>|"dz   | j                  |      z   }"|r"d}d}#d}!|rd}#d}!n|rd}#d }!|"dz   |z   dz   |#z   }"nd!}nd"}| j	                  |d#      }$|j                  i d
|d$|d	|"d%|d&|d'|d(|d)|d*|d+|d|d,|rdnd-d"|d!|d|d.|$d/k(  d0| |rdn| |rdn|  | j                  |d1      | j                  |d2      |||| j                  |      |!|| j                  |d3      d4ddd5| j                  d      | j                  |d6      d5ddd5| j                  |d7      dd5d8| j                  | j	                  |d9            |d:       ) |S );a  
        retrieves data on all markets for delta

        https://docs.delta.exchange/#get-list-of-products

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        r7  r   contract_typeoptions_combosquoting_assetunderlying_assetsettling_assetproduct_specsr   r   call_optionsput_optionsmove_optionsr3   perpetual_futuresfuturesstrike_pricesettlement_timecontract_valueNunderlying_precisionr  r  r  r  r7   r  r  Pr   Mmover6   r5   staterW  r  r	  r
  r  r  r  r  r4   Fr  liver  taker_commission_ratemaker_commission_rate	tick_sizer  r  position_size_limitmin_size)r   r  r   r  launch_time)r   r   r   r   r  r  r  r  r  r  r   createdr!  )publicGetProductsrZ  r[  r\  r$  r;  r]  r^  r&  r`  r   rb  yymmddappend)%r   r=  r>  rq  r7  rd  r-  r  quotingAssetunderlyingAssetsettlingAssetproductSpecsr  r  r  r   rW  r  r	  r
  callOptions
putOptionsmoveOptionsr3   r5   r6   r7   r  r  r  r  amountPrecisionr   r  r   letterr  s%                                        r   fetch_marketszdelta.fetch_markets  s    ))&1f ..8R8q#g,' m	AQZF##FO<D''>>&/2FL"nnV5GLO NN63CDM>>&/2FL%%ox@F&&|X>G''x@H!!&(3B))&$7I**62D++G4E,,X6F>1K-/J>1KFND//Di'F!>Z>;F%%fn=F!--f6GHN^^N3F++F4DEL"O"&"3"3D4H4HIYIYZfh~I  5A  #B #'"3"3C"8oFJCZ%'Fv#.V#c\DKK,??F'!$%+
%%(F).J(%(F)/J!'#!6!<v!E'!D$$VW5EMM 3b3Y3 &3 	3
 3 &3 &3 73 H3 3 3 $$E3 3 &3 &3  5F?!3" H#3$ #'$F#'4Z))&2IJ))&2IJ , "0++F3(-!--fkB  $#!
  $005#//8MN
  $#
  $//
C#$  >>$*:*:6=*QRe3 3um	\ r   tickerc           
         | j                  |dd      }| j                  |d      }| j                  ||      }| j                  |d      }| j                  |di       }| j	                  i d|d|d| j                  |      d| j                  |d      d| j                  |d      d	| j                  |d
      d| j                  |d      d| j                  |d      d| j                  |d      dd d| j                  |d      d|d|dd dd dd dd | j                  |d      | j                  |d      | j                  |d      | j                  |d      |d|      S )Nr*  r9  r   closequotesr)  highlowbidbest_bid	bidVolumebid_sizeaskbest_ask	askVolumeask_sizevwapopenr   previousClosechanger   averagevolumeturnover
mark_price
spot_price)
baseVolumequoteVolume	markPrice
indexPricer!  )r<  r$  safe_symbolr;  safe_tickeriso8601r`  )r   r  r-  r*  r,  r   r   r  s           r   parse_tickerzdelta.parse_ticker  s   h --fk5I	##FH5!!(F30"5 !
f!
!
 Y/!
 D$$VV4	!

 4##FE2!
 4##FJ7!
 ))&*=!
 4##FJ7!
 ))&*=!
 D!
 D$$VV4!
 T!
 D!
 T!
 d!
  $!!
" t#!
$ **68<++FJ?))&,?**6<@-!
. / 	r   c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |di       }| j                  ||      S )a  
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://docs.delta.exchange/#get-ticker-for-a-product-by-symbol

        :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   r7  )ro  r-  publicGetTickersSymbolextendr;  r  r   r   r=  r-  requestr>  r7  s          r   fetch_tickerzdelta.fetch_ticker?  ss     	V$fTl
 ..t{{7F/KLz (B7  00r   symbolsc                 &   | j                          | 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.delta.exchange/#get-tickers-for-products

        :param str[]|None 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
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        r7  r   r   )ro  market_symbolspublicGetTickersrZ  r[  r\  r  filter_by_array_tickers)	r   r  r=  r>  r   r7  rd  r  r   s	            r   fetch_tickerszdelta.fetch_tickers  s     	%%g.((0F ..8R8q#g,' 	$A&&wqz2FH%F#F6N	$ ++FHgFFr   r   c           	          | j                          | j                  |      }d|d   i}|||d<   | j                  | j                  ||            }| j	                  |di       }| j                  ||d   ddddd	      S )
a+  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://docs.delta.exchange/#get-l2-orderbook

        :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   Ndepthr7  buysellr   size)ro  r-  publicGetL2orderbookSymbolr  r;  parse_order_book)r   r   r   r=  r-  r  r>  r7  s           r   fetch_order_bookzdelta.fetch_order_booke  s     	V$fTl
 $GG224;;w3OP& (B7$$VVH-=tUFT[]cddr   tradec                 j   | j                  |d      }| j                  |d      }| j                  | j                  |d            }| j                  |dd|      }| j                  |d      }| j                  |d      }| j                  |di       }| j                  |d	      }	| j	                  |	|      }
| j                  |d
      }| j                  |d      }||dk(  rd}n|dk(  rd}| j                  |d      }| j                  |di       }| j                  |d      }||j                  dd      }| j                  |d      }d }|;| j                  |di       }| j                  |d	      }| j                  |      }||d}| j                  |||| j                  |      |
||||d |||d|      S )Nr   order_id
created_atr*  r9  r   r  productr   seller_rolesider   r  r   r  role	meta_data
order_type_order 
commissionr  r  re  )r   orderr*  r)  r   r  r  r   r  r  takerOrMakerrU  r!  )	r$  r&  r<  r;  r  replacer^  
safe_trader  )r   r  r-  r   orderIdr*  priceStringamountStringr  r,  r   
sellerRoler  r  metaDatar  feeCostStringrU  r  feeCurrencyIdfeeCurrencyCodes                        r   parse_tradezdelta.parse_trade  s   ` eT*""5*5NN4#3#3E<#HI	--e[%S	&&ug6''v6..	26##GX6!!(F3%%e];
v.<W$w&''v6>>%b9,7<<"-D((=$ NN74DbIM ,,]HEM"55mDO%+C "Y/ "( 
  	r   sincec                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |dg       }| j                  ||||      S )a  
        get the list of most recent trades for a particular symbol

        https://docs.delta.exchange/#get-public-trades

        :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
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        r   r   r7  )ro  r-  publicGetTradesSymbolr  rZ  parse_trades)	r   r   r  r   r=  r-  r  r>  r7  s	            r   fetch_tradeszdelta.fetch_trades  sv     	V$fTl
 --dkk'6.JK  (B7  >>r   c           	          | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      gS )Ntimer  r  r  r  r  )safe_timestampr`  )r   ohlcvr-  s      r   parse_ohlcvzdelta.parse_ohlcv  sn     v.UF+UF+UE*UG,UH-
 	
r   ru   c                    | j                          | j                  |      }d| j                  | j                  ||      i}| j	                  |      }|r|nd}| j                  |dd      }	|	du}
|
r| j                  |	      }	|%|
r|	n| j                         }||d<   |||z  z
  |d<   n5| j                  |dz        }||d<   |
r|	n| j                  |||z        |d<   | j                  |d	      }|d
k(  rd|d   z   |d<   n|dk(  r|d   d   d   |d<   n|d   |d<   | j                  |d	dg      }| j                  | j                  ||            }| j                  |dg       }| j                  |||||      S )a  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://docs.delta.exchange/#delta-exchange-api-v2-historical-ohlc-candles-sparklines

        :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 str [params.until]: timestamp in ms of the latest candle to fetch
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        
resolutionr   untilr9  Nendstarti  r   r   zMARK:r   r   r   r!  
spot_indexr7  )ro  r-  r$  r   parse_timeframer<  parse_to_intsecondssumomitpublicGetHistoryCandlesr  rZ  parse_ohlcvs)r   r   	timeframer  r   r=  r-  r  durationr  untilIsDefinedr  r  r   r>  r7  s                   r   fetch_ohlcvzdelta.fetch_ohlcv$  s    	V$$**4??IyQ
 ''	2D))&'5At+%%e,E=)%t||~C GEN"UX%55GG%%edl3E$GG&4U$((5%RZJZ:[GEN  1F? '&, 6GHg &v| <X FGH &tGH6GW#56//GV0LM (B7  E5IIr   c                    | j                  |dg       }d|i}| j                  | j                  di       }t        dt	        |            D ]s  }||   }| j                  |d      }| j                  ||      }||n|d   }	| j                         }
| j                  |d      |
d<   | j                  |d	      |
d
<   |
||	<   u | j                  |      S )Nr7  r!  rm  r   asset_idrX  balancetotalavailable_balancefree)rZ  r;  r   r[  r\  r$  accountsafe_balance)r   r>  balancesr7  rm  rd  r  
currencyIdre  rX  r  s              r   parse_balancezdelta.parse_balance[  s    >>(Hb9) $t||=TVX Yq#h-( 	#AqkG))':>J~~&;ZHH"*"2:&9IDllnG#//CGG"..w8KLGFO"F4L	#   ((r   c                 f    | j                          | j                  |      }| j                  |      S )a\  
        query for balance and get the amount of funds available for trading or funds locked in orders

        https://docs.delta.exchange/#get-wallet-balances

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        )ro  privateGetWalletBalancesr  )r   r=  r>  s      r   fetch_balancezdelta.fetch_balancej  s3     	008, !!(++r   c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |di       }| j                  ||      S )a  
        fetch data on a single open contract trade position

        https://docs.delta.exchange/#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>`
        
product_idrW  r7  )ro  r-  privateGetPositionsr  r;  parse_positionr  s          r   fetch_positionzdelta.fetch_position  ss     	V$&-
 ++DKK,HI (B7""6622r   c                     | j                          | j                  |      }| j                  |dg       }| j                  ||      S )ah  
        fetch all open positions

        https://docs.delta.exchange/#get-margined-positions

        :param str[]|None symbols: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        r7  )ro  privateGetPositionsMarginedrZ  parse_positions)r   r  r=  r>  r7  s        r   fetch_positionszdelta.fetch_positions  sG     	33F;, (B7##FG44r   positionc                 B   | j                  |d      }| j                  ||      }|d   }| j                  |dd      }| j                  |d      }d }|1t        j                  |d      rd}nt        j
                  |d      rd}| j                  i d	|d
d d|dd dd d| j                  |d      d| j                  |d      dd dd d| j                  |      d| j                  |d      dd d|dd d|d| j                  |      dd d d d d d d d d d      S )Nproduct_symbolr   r*  r9  r  r   r  r  r!  r   notionalr   liquidationPriceliquidation_price
entryPriceentry_priceunrealizedPnlr   	contractsr  r  r  r   r)  maintenanceMargin)maintenanceMarginPercentage
collateralinitialMargininitialMarginPercentager   marginRatior   r   )
r$  r4  r<  r+   	string_gt	string_ltsafe_positionr`  r   r  )r   r#  r-  r,  r   r*  
sizeStringr  s           r   r  zdelta.parse_position  s   8 ##H.>?!!(F3!--hUK	%%h7
!  S1"":s3!! #
H#
$#
 f#
 	#

 $#
  0 0;N O#
 $**8]C#
 T#
 $#
 **:6#
 D,,V^D#
 #
 D#
 d#
 #
  Y/!#
"  ##
$ ,0!'+!#3#
  	r   rE  c                 6    ddddd}| j                  |||      S )Nr  closedcanceled)r  pendingr8  	cancelledr$  )r   rE  statusess      r   parse_order_statuszdelta.parse_order_status  s,    #	
 &&99r   r  c                    | j                  |d      }| j                  |d      }| j                  | j                  |d            }| j                  |d      }| j                  | j                  di       }| j	                  |||      }||n|d   }| j                  | j                  |d            }	| j                  |d      }
| j                  |d	      }|j                  d
d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }d }| j                  |d      }|Bd }|9| j                  |d   di       }| j                  |d      }| j                  |      }||d}| j                  i d|d|d|d|d| j                  |      dd d|d|d|
d|d|dd d|dd d|d|	d |d!d i|      S )"Nr   client_order_idr  r  rn  r   r  r  r  r  r  limit_pricer  unfilled_sizeaverage_fill_pricepaid_commissionr!  r  r  clientOrderIdr*  r)  lastTradeTimestampr  r   r  r  r  filled	remainingrE  rU  trades)
r$  r&  r;  r   
safe_valuer>  r  r^  
safe_orderr  )r   r  r-  r   rE  r*  r,  rn  r   rE  r  r  r   r  rH  r  rU  r  r  r  r  s                        r   parse_orderzdelta.parse_order  s   H eT*((0ABNN4#3#3E<#HI	##E<8!^^DLL:NPRS!3XvF$n6(3C(()9)9%)IJv.|4||Hb)  6!!%0$$UO<	""5*>?((0AB$"O! $vf~?OQS T $ 0 0 I"&"9"9-"H%+C   
E 
" 
 ] 
 	 

 Y/ 
 !$ 
 f 
 D 
 D 
 U 
 f 
 D 
 w 
 d 
  
  f! 
" 3# 
$ d% 
& ' 	r   r  r  r  r   c                     | j                          |dz   }| j                  |      }|d   | j                  |d   |      ||d}	|dk(  r| j                  |d   |      |	d<   | j	                  |dd      }
| j                  |ddg      }|
|
|	d<   | j                  |d	      }|r||	d
<   | j                  |d	      }| j                  | j                  |	|            }| j                  |di       }| j                  ||      S )a  
        create a trade order

        https://docs.delta.exchange/#place-order

        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of currency you want to trade in units of base currency
        :param float [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param bool [params.reduceOnly]: *contract only* indicates if self order is to reduce the size of a position
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r  rW  r   )r  r  r  r  r   rA  rE  r@  
reduceOnlyreduce_onlyr7  )ro  r-  amount_to_precisionprice_to_precisionsafe_string_2r  	safe_boolprivatePostOrdersr  r;  rL  )r   r   r  r  r  r   r=  	orderTyper-  r  rE  rN  r>  r7  s                 r   create_orderzdelta.create_orderm  s"    	8O	V$ -,,VH-=vF#

 7?%)%<%<VH=Mu%UGM"**6?DUV6O5F#GH$)6G%&^^FL9
%/GM"YYv|4F))$++gv*FGJ (B7//r   r   c                 ^   | j                          | j                  |      }t        |      |d   d}	|t        | j                  ||            |	d<   || j	                  ||      |	d<   | j                  | j                  |	|            }
| j                  |
d      }| j                  ||      S )a  
        edit a trade order

        https://docs.delta.exchange/#edit-order

        :param str id: order id
        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of the currency you want to trade in units of the base currency
        :param float [price]: the price at which the order is to be fulfilled, in units of the quote currency
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        rW  r   r  r  rA  r7  )	ro  r-  intrP  rQ  privatePutOrdersr  r;  rL  )r   r   r   r  r  r  r   r=  r-  r  r>  r7  s               r   
edit_orderzdelta.edit_order  s     	V$b' -
 !$":":66"JKGFO%)%<%<VU%KGM"((Wf)EF$ (3//r   c                 $   |t        | j                  dz         | j                          | j                  |      }t	        |      |d   d}| j                  | j                  ||            }| j                  |d      }| j                  ||      S )ax  
        cancels an open order

        https://docs.delta.exchange/#cancel-order

        :param str id: order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        z) cancelOrder() requires a symbol argumentrW  rX  r7  )	r#   r   ro  r-  rY  privateDeleteOrdersr  r;  rL  )r   r   r   r=  r-  r  r>  r7  s           r   cancel_orderzdelta.cancel_order  s     >#DGG.Y$YZZV$b' -
 ++DKK,HIJ (3//r   c                     |t        | j                  dz         | j                          | j                  |      }d|d   i}| j	                  | j                  ||            }| j                  d|i      gS )a~  
        cancel all open orders in a market

        https://docs.delta.exchange/#cancel-all-open-orders

        :param str symbol: unified market symbol of the market to cancel orders in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        z- cancelAllOrders() requires a symbol argumentr  rW  r!  )r#   r   ro  r-  privateDeleteOrdersAllr  rK  )r   r   r=  r-  r  r>  s         r   cancel_all_orderszdelta.cancel_all_orders'  s     >#DGG.]$]^^V$&-

 ..t{{7F/KL OO 
 	
r   c                 ,    | j                  d||||      S )a  
        fetch all unfilled currently open orders

        https://docs.delta.exchange/#get-active-orders

        :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 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>`
        privateGetOrdersfetch_orders_with_methodr   r   r  r   r=  s        r   fetch_open_orderszdelta.fetch_open_ordersG  s      ,,-?PUW]^^r   c                 ,    | j                  d||||      S )aB  
        fetches information on multiple closed orders made by the user

        https://docs.delta.exchange/#get-order-history-cancelled-and-closed

        :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>`
        privateGetOrdersHistoryrd  rf  s        r   fetch_closed_orderszdelta.fetch_closed_ordersU  s!     ,,-FPUW\^deer   c                    | j                          i }d }|| j                  |      }|d   |d<   |t        |      dz   |d<   |||d<   d }|dk(  r"| j                  | j	                  ||            }n&|dk(  r!| j                  | j	                  ||            }| j                  |dg       }	| j                  |	|||      S )	NrW  product_ids000
start_time	page_sizerc  ri  r7  )ro  r-  strrc  r  ri  rZ  parse_orders)
r   methodr   r  r   r=  r  r-  r>  r7  s
             r   re  zdelta.fetch_orders_with_methodc  s    	
 [[(F%+K%8GM"$'J$6GL!#(GK '',,T[[&-IJH0033DKK4PQH0 (B7  >>r   c                 $   | j                          i }d}|| j                  |      }|d   |d<   |t        |      dz   |d<   |||d<   | j                  | j	                  ||            }| j                  |dg       }| j                  ||||      S )a  
        fetch all trades made by the user

        https://docs.delta.exchange/#get-user-fills-by-filters

        :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>`
        NrW  rl  rm  rn  ro  r7  )ro  r-  rp  privateGetFillsr  rZ  r  )	r   r   r  r   r=  r  r-  r>  r7  s	            r   fetch_my_tradeszdelta.fetch_my_trades  s     	
 [[(F%+K%8GM"$'J$6GL!#(GK ''GV(DE\ (B7  >>r   rX  c                     | j                          i }d}|| j                  |      }|d   |d<   |||d<   | j                  | j                  ||            }| j	                  |dg       }| j                  ||||      S )aP  
        fetch the history of changes, actions done by the user or operations that altered the balance of the user

        https://docs.delta.exchange/#get-wallet-transactions

        :param str [code]: unified currency code, default is None
        :param int [since]: timestamp in ms of the earliest ledger entry, default is None
        :param int [limit]: max number of ledger entries to return, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ledger structure <https://docs.ccxt.com/#/?id=ledger>`
        NrW  r  ro  r7  )ro  re  privateGetWalletTransactionsr  rZ  parse_ledger)	r   rX  r  r   r=  r  re  r>  r7  s	            r   fetch_ledgerzdelta.fetch_ledger  s     	
 }}T*H"*;"7GJ#(GK 44T[[&5QR, (B7  5%@@r   c                 <    dddddddd}| j                  |||      S )NpnltransactionrU  r  r   rebate)r{  rT  
withdrawalr  
conversionreferral_bonuscommission_rebater<  )r   r  typess      r   parse_ledger_entry_typezdelta.parse_ledger_entry_type	  s7    $'! )!)
 tT22r   rx  re  c                 b   | j                  |d      }d }d }| j                  |di       }| j                  |d      }d }| j                  |d      }	|	dk(  s|	dk(  s|	dk(  s|	dk(  s
|	d	k(  s|	d
k(  rd}n|	dk(  s|	dk(  s
|	dk(  s|	dk(  rd}| j                  |	      }	| j                  |d      }
| j                  | j                  d      }| j	                  ||
|      }|d n|d   }| j                  |d      }| j                  | j                  |d            }| j                  |d      }t        j                  dt        j                  ||            }d}| j                  |||||||	|| j                  |      | j                  |      | j                  |      ||| j                  |      d d|      S )Nuuidr  transaction_idtransaction_typerT  r  r  r{  withdrawal_cancellationpromo_creditinr~  r  r  perpetual_futures_fundingoutr  rm  rX  r  r  r  r   rD  )r!  r   	directionr  referenceIdreferenceAccountr  re  r  beforeafterrE  r*  r)  rU  )r$  r;  r  r   rJ  r&  r+   
string_max
string_subsafe_ledger_entryr   r  )r   rx  re  r   r  r  r  r  r  r  r  rm  rX  r  r*  r  r  rE  s                     r   parse_ledger_entryzdelta.parse_ledger_entry'	  s     dF+	>>$R8&&x1AB&89I4+>#>DL\D\bfjobouy  ~W  vW  ]a  es  ]sIl"(<$,BV\`d\I++D1%%dJ7
 $t||=T U??#8*hO (tx/?!!$1NN4#3#3D,#GH	  y1##C););E6)JK%%"& 0''/''/&&u-"Y/'
  ! 	r   c                 T   | j                          | j                  |      }d|d   i}| j                  |d      }|'| j                  ||      |d<   | j	                  |d      }| j                  | j                  ||            }| j                  |di       }| j                  ||      S )as  
        fetch the deposit address for a currency associated with self account
        :param str code: unified currency code
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.network]: unified network code
        :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
        asset_symbolr   rM  r7  )	ro  re  safe_string_uppernetwork_code_to_idr  privateGetDepositsAddressr  r;  parse_deposit_address)r   rX  r=  re  r  rj  r>  r7  s           r   fetch_deposit_addresszdelta.fetch_deposit_address^	  s     	==&HTN
 ,,VY?"!%!8!8d!KGIYYvy1F11$++gv2NO$ (B7))&(;;r   c                     | j                  |d      }| j                  |d      }| j                  |d      }| j                  |       || j                  ||      | j                  |      || j                  |d      dS )Naddressr  rM  memo)r!  re  rM  r  tag)r$  check_addressr^  r_  )r   depositAddressre  r  r,  ri  s         r   r  zdelta.parse_deposit_address	  s     "">9=##NNC$$^Y?	7#"//(C..y9##NF;
 	
r   c                    | j                          | j                  |      }|d   st        | j                  dz         d|d   i}| j	                  | j                  ||            }| j                  |di       }| j                  ||      S )ag  
        fetch the current funding rate

        https://docs.delta.exchange/#get-ticker-for-a-product-by-symbol

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `funding rate structure <https://docs.ccxt.com/#/?id=funding-rate-structure>`
        r5   z0 fetchFundingRate() supports swap contracts onlyr   r   r7  )ro  r-  r%   r   r  r  r;  parse_funding_rater  s          r   fetch_funding_ratezdelta.fetch_funding_rate	  s     	V$f~DGG&XXYYfTl
 ..t{{7F/KL\ (B7&&vv66r   c                     | j                          | j                  |      }ddi}| j                  | j                  ||            }| j	                  |dg       }| j                  ||      S )a  
        fetch the funding rate for multiple markets

        https://docs.delta.exchange/#get-tickers-for-products

        :param str[]|None symbols: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rates-structure>`, indexed by market symbols
        contract_typesr  r7  )ro  r  r  r  rZ  parse_funding_rates)r   r  r=  r  r>  ratess         r   fetch_funding_rateszdelta.fetch_funding_rates	  sr     	%%g.1
 ((Wf)EF` x26''w77r   c                    | j                  |dd      }| j                  |d      }| j                  |d      }t        j                  |d      }i d|d| j	                  ||      d| j                  |d      d	| j                  |d
      dd dd d|d| j                  |      d| j                  |      dd dd dd dd dd dd dd dd dd iS )Nr*  r9  r   funding_rater   r!  r  r  r  r  interestRateestimatedSettlePricer)  fundingRatefundingTimestampfundingDatetimenextFundingRatenextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetimeinterval)r<  r$  r+   
string_divr  r`  r  r   )r   r  r-  r*  r,  fundingRateStringr  s          r   r  zdelta.parse_funding_rate#
  sj   V --hUK	##Hh7 ,,X~F(():EB
H
d&&x8
 ))(LA
 $**8\B	

 D
 #D
 
 Y/
 4,,[9
 
 t
 t
 #D
 "4
 "4
  '!
" &t#
$ %
 	
r   c                 *    | j                  ||d|      S )ax  
        add margin

        https://docs.delta.exchange/#add-remove-position-margin

        :param str symbol: unified market symbol
        :param float amount: amount of margin to add
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `margin structure <https://docs.ccxt.com/#/?id=add-margin-structure>`
        addmodify_margin_helperr   r   r  r=  s       r   
add_marginzdelta.add_marging
  s     ((GGr   c                 *    | j                  ||d|      S )a  
        remove margin from a position

        https://docs.delta.exchange/#add-remove-position-margin

        :param str symbol: unified market symbol
        :param float amount: the amount of margin to remove
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `margin structure <https://docs.ccxt.com/#/?id=reduce-margin-structure>`
        reducer  r  s       r   reduce_marginzdelta.reduce_margint
  s     ((6JJr   c                 ,   | j                          | j                  |      }t        |      }|dk(  rt        j                  |d      }|d   |d}| j                  | j                  ||            }| j                  |di       }| j                  ||      S )Nr  z-1rW  )r  delta_marginr7  )	ro  r-  rp  r+   
string_mul privatePostPositionsChangeMarginr  r;  parse_margin_modification)	r   r   r  r  r=  r-  r  r>  r7  s	            r   r  zdelta.modify_margin_helper
  s    V$V8''5F -"
 88Wf9UV0 (B7--ff==r   datac                     | j                  |d      }| j                  ||      }||d   d dd | j                  |d      d d d d d
S )Nr%  r   isolatedr4   )
r!  r   r  r   r  r  rX  rE  r*  r)  )r$  r4  r`  )r   r  r-  r,  s       r   r  zdelta.parse_margin_modification
  sc    * ##D*:;!!(F3X&$%%dH5
 	
r   c                    | j                          | j                  |      }|d   st        | j                  dz         d|d   i}| j	                  | j                  ||            }| j                  |di       }| j                  ||      S )ag  
        retrieves the open interest of a derivative market

        https://docs.delta.exchange/#get-ticker-for-a-product-by-symbol

        :param str symbol: unified market symbol
        :param dict [params]: exchange specific parameters
        :returns dict} an open interest structure{@link https://docs.ccxt.com/#/?id=open-interest-structure:
        r  z3 fetchOpenInterest() supports contract markets onlyr   r   r7  )ro  r-  r$   r   r  r  r;  parse_open_interestr  s          r   fetch_open_interestzdelta.fetch_open_interest
  s     	V$j!TWW'\\]]fTl
 ..t{{7F/KLj (B7''77r   c                 @   | j                  |dd      }| j                  |d      }| j                  | j                  ||      | j	                  |d      | j	                  |d      | j	                  |d      | j	                  |d      || j                  |      |d|      S )	Nr*  r9  r   oi_valueoi_value_usdoi_contractsoi)r   r  r  openInterestAmountopenInterestValuer*  r)  r!  )r<  r$  safe_open_interestr  r`  r  )r   interestr-  r*  r,  s        r   r  zdelta.parse_open_interest  s    d --hUK	##Hh7&&&&x8**8Z@++HnE"&"2"28^"L!%!1!1(D!A"Y/	(
 	 		r   c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |di       }| j                  ||      S )aT  
        fetch the set leverage for a market

        https://docs.delta.exchange/#get-order-leverage

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `leverage structure <https://docs.ccxt.com/#/?id=leverage-structure>`
        r  rW  r7  )ro  r-  )privateGetProductsProductIdOrdersLeverager  r;  parse_leverager  s          r   fetch_leveragezdelta.fetch_leverageR  st     	V$&-
 AA$++gW]B^_ (B7""6622r   r   c                     | j                  |d      }| j                  |d      }|| j                  ||      | j                  |d      ||dS )Nindex_symbolr   margin_mode)r!  r   r   longLeverageshortLeverage)r$  r]  r  safe_string_lower)r   r   r-  r,  leverageValues        r   r  zdelta.parse_leverager  sY    ##Hn=))(J?&&x800=I)*
 	
r   c                     |t        | j                  dz         | j                          | j                  |      }|d   |d}| j	                  | j                  ||            S )aa  
        set the level of leverage for a market

        https://docs.delta.exchange/#change-order-leverage

        :param float leverage: the rate of leverage
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: response from the exchange
        z) setLeverage() requires a symbol argumentrW  )r  r   )r#   r   ro  r-  *privatePostProductsProductIdOrdersLeverager  )r   r   r   r=  r-  r  s         r   set_leveragezdelta.set_leverage}  si     >#DGG.Y$YZZV$ - 
 >>t{{7TZ?[\\r   c                 @   | j                          d}|| j                  |      }ddi}|||d<   | j                  | j                  ||            }| j	                  |dg       }| j                  ||      }	| j                  |	d      }
| j                  |
|d   ||      S )a  
        fetches historical settlement records

        https://docs.delta.exchange/#get-product-settlement-prices

        :param str symbol: unified market symbol of the settlement history
        :param int [since]: timestamp in ms
        :param int [limit]: number of records
        :param dict [params]: exchange specific params
        :returns dict[]: a list of `settlement history objects <https://docs.ccxt.com/#/?id=settlement-history-structure>`
        Nstatesexpiredro  r7  r*  r   )ro  r-  r  r  rZ  parse_settlementssort_byfilter_by_symbol_since_limit)r   r   r  r   r=  r-  r  r>  r7  settlementssorteds              r   fetch_settlement_historyzdelta.fetch_settlement_history  s     	[[(Fi
 #(GK ))$++gv*FGv (B7,,VV<k;7009I5RWXXr   c                     | j                  |d      }| j                  |d      }|| j                  ||      | j                  |d      | j                  |      |dS )Nr  r   settlement_price)r!  r   r   r*  r)  )r$  r  r`  r&  )r   
settlementr-  r)  r,  s        r   parse_settlementzdelta.parse_settlement  sg    l ##J0AB##J9&&x8%%j2DE1 
 	
r   c                     g }t        dt        |            D ]&  }|j                  | j                  ||   |             ( |S )Nr   )r[  r\  r  r  )r   r  r-  r7  rd  s        r   r  zdelta.parse_settlements2  sF    q#k*+ 	IAMM$//AGH	I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.delta.exchange/#get-ticker-for-a-product-by-symbol

        :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   r7  )ro  r-  r  r  r;  parse_greeksr  s          r   fetch_greekszdelta.fetch_greeks8  ss     	V$fTl
 ..t{{7F/KLj (B7  00r   greeksc                    | j                  |dd      }| j                  |d      }| j                  ||      }| j                  |di       }| 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d | j                  |d      |dS )Nr*  r9  r   r  r  r)  r-   gammathetavegarhobidSizer  askSizer  bidImpliedVolatilitybid_ivaskImpliedVolatilityask_ivmarkImpliedVolatilitymark_ivbidPricer  askPricer  r  r  	lastPricer  )underlyingPricer!  )r<  r$  r  r;  r  r`  )r   r  r-  r*  r,  r   r   r  s           r   r  zdelta.parse_greeks  s   d --fk5I	##FH5!!(F3vx4"5
f

 Y/
 T%%eW5	

 T%%eW5
 T%%eW5
 D$$UF3
 4##E51
 t''
;
 t''
;
 #D$4$4VX$F
 #D$4$4VX$F
 $T%5%5fi%H
 ((<
 ((<
  ))&,?!
" #
$  $//E'
 	
r   c                     | j                          ddd}| j                  | j                  ||            }| j                  | j	                  |di             }|gS )ai  
        closes all open positions for a market type

        https://docs.delta.exchange/#close-all-positions

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.user_id]: the users id
        :returns dict[]: A list of `position structures <https://docs.ccxt.com/#/?id=position-structure>`
        T)close_all_portfolioclose_all_isolatedr7  )ro  privatePostPositionsCloseAllr  r  r;  )r   r=  r  r>  r#  s        r   close_all_positionszdelta.close_all_positions  sa     	#'"&

 44T[[&5QR &&t~~h"'MNzr   c                     | j                          d}|| j                  |      }| j                  |      }| j                  |di       }| j	                  ||      S )az  
        fetches the margin mode of a trading pair

        https://docs.delta.exchange/#get-user

        :param str symbol: unified symbol of the market to fetch the margin mode for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `margin mode structure <https://docs.ccxt.com/#/?id=margin-mode-structure>`
        Nr7  )ro  r-  privateGetProfiler;  parse_margin_mode)r   r   r=  r-  r>  r7  s         r   fetch_margin_modezdelta.fetch_margin_mode  sa     	[[(F))&1@ (B7%%ff55r   r   c                 @    d }||d   }||| j                  |d      dS )Nr   r  )r!  r   r   r<  )r   r   r-  r   s       r   r  zdelta.parse_margin_mode4  s7    H%F**:}E
 	
r   c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |di       }| j                  |d|      S )a  
        fetches option data that is commonly found in an option chain

        https://docs.delta.exchange/#get-ticker-for-a-product-by-symbol

        :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   r7  N)ro  r-  r  r  r;  parse_optionr  s          r   fetch_optionzdelta.fetch_option>  su     	V$fTl
 ..t{{7F/KLj (B7  v66r   rh  c                 $   | j                  |d      }| j                  ||      }| j                  |di       }| j                  |dd      }i d|dd d|d   d|d| j	                  |      d| j                  |d	      d
| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      dd d| j                  |d      dd dd d| j                  |d      dd S )Nr   r  r*  r9  r!  re  r)  impliedVolatilityr  openInterestr  r  r  r  r  midPriceimpact_mid_pricer  r  r  r  r  r  r   r  r  r  )r$  r4  r;  r<  r  r`  )r   rh  re  r-  r,  r  r*  s          r   r  zdelta.parse_option  s   d ##E84!!(F3x4--e[%H	
E

 fX&
 	

 Y/
  !1!1&)!D
 D,,UD9
 ((<
 ((<
 ((1CD
 ))%>
 
 t//|D
 d
 $
  $**5(;!
" 4#
 	
r   r   GETc                    d| j                   z   dz   | j                  ||      z   }| j                  d   |   |z   }| j                  || j	                  |            }	|dk(  r|	r|d| j                  |	      z   z  }n|dk(  r| j                          t        | j                               }
| j                  |
d}||
z   |z   }|dk(  r!|	r:d| j                  |	      z   }||z  }||z  }n| j                  |	      }||z  }d|d	<   | j                  | j                  |      | j                  | j                        t        j                        }||d
<   ||||dS )Nr  r   r   ?r   )zapi-keyr*  r  zapplication/jsonzContent-Type	signature)rH  rr  bodyheaders)r   implode_paramsr   r  extract_params	urlencodecheck_required_credentialsrp  r  r   jsonhmacencoder   hashlibsha256)r   pathr   rr  r=  r   r  requestPathrH  queryr*  authqueryStringr  s                 r   signz
delta.sign  sY   DLL(3.1D1DT61RRiis#k1		&$"5"5d";<(?sT^^E222I++-DLLN+I;;&G I%3D"%u(="=KK'D;&Cyy'*<'		$++d"3T[[5Mw~~^I#,GK fdwOOr   reasonrH  rr  r   r  c
                    |y | j                  |di       }
| j                  |
d      }|]| j                  dz   |z   }| j                  | j                  d   ||       | j                  | j                  d   ||       t        |      y )NerrorrX   r   r   )r;  r$  r   throw_exactly_matched_exceptionr   throw_broadly_matched_exceptionr!   )r   rX  r0  rH  rr  r   r  r>  requestHeadersrequestBodyr2  	errorCodefeedbacks                r   handle_errorszdelta.handle_errors  s     x"5$$UF3	 ww}t+H001I9V^_001I9V^_))r   )NNNN)N)NN)b__name__
__module____qualname__r   r   rp  r+  r   r   r   r4  r   r?  rK  r   rk  ro  rp  r    r  dictr   r  r  r   r   r  r   r  r   r  r  rt  r  r  r   r  r  r  r   r"  r  r>  r   rL  r   r   floatr   rV  r[  r^  ra  rg  rj  re  ru  r   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   r  r  r/  rY  r:  __classcell__)r   s   @r   r-   r-      s   |# ||	A
3 A
FWC W WRU Wjm W  zI W !# 	Gs 	G #% F
P ') pZ pd #(  $& l$v, l\	P4 P P6 Pd 02 M13 M1f M1^ 04B UGW UG7 UGn :>b &es &e3 &eY &eP] ]v ] ]~ 6:UW "?3 "?s "?# "?\`af\g "?H
 
4 
( 26DW[df 5J# 5Jc 5JQT 5Jkoptku 5Jn) ) $&  ,(  ,D 24 3S 3: 26b "5w "5T(^ "5HAt AV AF: :R Rv R Rh gksu M03 M0i M0y M0RW M0`c M0^ `drv  @B .0S .0# .0Y .0i .0Y\ .0lo .0` 37r 90s 90C 90v /32 
 
@ /3TXac _ _3 _c _hlmrhs _ 154VZce f# fS fPS fjnotju f >BPTcgpr 1?s 1?# 1?]` 1?f -1tRV_a M?c M? M?C M?^ (,$TZ\ 1A 1AC 1As 1Aaefqar 1Af35t 5x 5; 5n 79 $<# $<^ $<L
h 
R` 
6 68 @7 @7K @7D 6:" @87 @8 @8DB
6 B
[ B
H =? H He HCU H @B KC K KFX K FH #>3 #>L^ #>J"
d "
F "
N` "
H 79 G8# G8R=F =~ 24 3S 3 3@	
t 	
V 	
x 	
 9=R ]S ]# ]@ 6:[_hj SYs SY# SYUX SYj>
@ 02 E13 E1f E1NK
4 K
 K
6 K
Z *, X . 57 O6 O6: O6b
D 
* 
 02 E73 E7f E7NH
$ H
( H
6 H
]c H
T &eBSW P8# s  c TX `c r   r-   )2ccxt.base.exchanger   ccxt.abstract.deltar   r(  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)   ccxt.base.decimal_to_precisionr*   ccxt.base.preciser+   r-    r   r   <module>rI     st    ( +  m  m  m  m  m  m  m  m  * 0 . ' & . ) * 1 4 %`7Hk `7r   