
    iN                    4   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 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+  G d dee          Z,dS )    )Exchange)ImplicitAPIN)Balances
CurrenciesCurrencyGreeksIntLeverage
MarginModeMarginModificationMarketMarketInterfaceNumOptionOrder	OrderBook	OrderSide	OrderTypePositionStrStringsTickerTickersTrade)List)ExchangeError)AuthenticationError)ArgumentsRequired)
BadRequest)	BadSymbol)InsufficientFunds)InvalidOrder)OrderNotFound)ExchangeNotAvailable)	TICK_SIZE)Precisec                       e Zd Z fdZdefdZdTdedededed	ef
 fd
Z	i 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dUd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dUded	efdZddi fdededed	ee         fdZdUd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fd!Z%dUdefd"Z&d# Z'dUded	e(fd$Z)di fded%e*d&e+d'e,d(e-f
d)Z.ddi fd*eded%e*d&e+d'e-d(e-fd+Z/di fd*edefd,Z0di fdefd-Z1dddi fdededed	ee(         fd.Z2dddi fdededed	ee(         fd/Z3dddi fdededefd0Z4dddi fdededefd1Z5dddi fd2ededefd3Z6d4 Z7dUd5e8fd6Z9i fd2efd7Z:dUd5e8fd8Z;i fdefd9Z<di fdefd:Z=dUdefd;Z>i fded	e?fd<Z@i fded	e?fd=ZAi fded	e?fd>ZBdUded	e?fd?ZCi fdefd@ZDdUdefdAZEi fded	eFfdBZGdUd	eFfdCZHdi fdDedefdEZIdddi fdededefdFZJdG ZKdH ZLi fded	eMfdIZNdUdefdJZOi fd	eeP         fdKZQi fded	eRfdLZSdUd	eRfdMZTi fded	eUfdNZVdVd5e8defdOZWdPdQi ddfdRZXdS ZY xZZS )Wdeltac                    |                      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dd d d
d
d d ddd
d
d
d
d
d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdLdMdNdNdMdOdPgdQdRdSdTg dUig dVg dWg dXg dYdZdMd[dd|                     d\          |                     d]          |                     d^          |                     d\          g|                     d_          |                     d`          g|                     da          |                     d`          g|                     db          |                     dc          g|                     dd          |                     de          g|                     df          |                     dg          g|                     dh          |                     di          gg|                     d^          |                     dc          g|                     d_          |                     dc          g|                     da          |                     de          g|                     db          |                     dg          g|                     dd          |                     dj          g|                     df          |                     dk          g|                     dh          |                     dk          ggdldmidndodpdqit
          dddrt          t          t          t          t          t          t          t          t          t          t          t          t          dsi dtdu          S )vNr(   zDelta ExchangeVCi,  v2CORSspotTmarginFswapfutureoption	addMargincancelAllOrderscancelOrdercloseAllPositionsclosePositioncreateOrdercreateReduceOnlyOrder	editOrderfetchBalancefetchClosedOrdersfetchCurrenciesfetchDepositfetchDepositAddress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)rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   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)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precisionModerequiredCredentials
exceptions)deep_extendsuperr(   describeparse_numberr%   r!   r"   r   r    r   r#   r$   )self	__class__s    ^/var/www/html/crypto-bot/backend/venv/lib/python3.11/site-packages/ccxt/async_support/delta.pyr   zdelta.describe   s   eT 2 2 ; ; = =$BBB %B 	B
 %B $B TB "4B tB $TB  B tB (B TB B  $T!B" "4#B B$ %B& &t'B(  )B* &u+B, #D-B. *5/B0 $T1B2 t3B4 "45B6 t7B8  9B: %e;B< "4=B> #E?B@ +EABB CBD !$EB B BF +EGBH  IBJ dKBL $TMBN "4OBP tQBR #ESBT !$UBV  WBX $UYBZ !$[B\ )%]B^ )$_B` taBb tcBd eBf TgB Bh  $!%"&).*/#'$( $#"!&#(!!CB B BH  " ~BC 
 ;;  41 :P &    "  $
 
 
    M+ +#= =~ !%"&!..x88!..x88 "..s33T5F5Fx5P5PQ!..u55t7H7H7R7RS!..u55t7H7H7R7RS!..v668I8I'8R8RS!..v668I8I(8S8ST!..w779J9J99U9UV!..w779J9J99U9UV" "..s33T5F5Fw5O5OP!..u55t7H7H7Q7QR!..u55t7H7H7R7RS!..v668I8I)8T8TU!..v668I8I(8S8ST!..w779J9J89T9TU!..w779J9J89T9TU"  : *)  '$ $ ,=3?,6(1-9)59E5A",':)<,9#7  # ad@
 d@
 d d d	    symbolc                    d}|                     d          }|                     d          }d }d }d }|                    d          dk    rC|                     |d          }|                     |d          }|                     |d          }nB|                     |d          }|                     |d          }|                     |d          }|}|                     |d          }	|                     |          }
|                     |
          }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|                     d          ||
|dk    rdnd |                     |	          d d d!d d d"d d d"d d d"d#d d$	S )%NUSDT-/r            r   r   :basequotesettlebaseIdquoteIdsettleIdactiveFtyper1   linearinverser-   r/   r0   Tr.   1Ccallr   amountprice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_market  s   ll3''\\#&&

;;sb  ##J22D%%k155F))+q99JJ##K33D%%k155F))+q99J!!+q11++F3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2&%/3%6%6&&U''//    
   
     U+
 +
 +
 +	
r   NmarketIdmarket	delimiter
marketTypereturnc                 J   |d uoS|                     d          p>|                     d          p)|                    d          p|                    d          }|r|| j        vr|                     |          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   r  zdelta.safe_marketB  s    D(  e0A0A$0G0G  0dXM^M^_cMdMd  0djrj}j}  C  kD  kD  0d  JR  J]  J]  ^b  Jc  Jc 	?X);;;44X>>>UD!!--h	:VVVr   c                    K   |                      |           d{V }|                     |di           }|                     |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
        Nresultserver_timeMbP?)publicGetSettings	safe_dictsafe_integer_product)r   paramsresponser
  s       r   
fetch_timezdelta.fetch_timeI  sZ       //77777777(B77((FFFr   c                   K   |                      |           d{V }|                     |di           }|                     |d          }|dk    rdnd}|                     |dd|                                           }||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>`
        Nr
  under_maintenancetruemaintenanceokr  r  )statusupdatedetaurlr   )r  r  r   r  milliseconds)r   r  r  r
  underMaintenancer  r  s          r   fetch_statuszdelta.fetch_statusT  s       //77777777l (B77++F4GHH#3v#=#=D++FM5$J[J[J]J]^^
 
 	
r   c                   K   |                      |           d{V }|                     |dg           }i }t          dt          |                    D ]}||         }|                     |d          }|                     |d          }|                     |          }	|                     |d          }
|                     |d          }|
dk    }|dk    }|o|}|||	|                     |d	          |||||                     |d
          |                     | 	                    |                     |d                              ddd|                     |d          dddi d||	<   |S )a  
        fetches all available currencies on an exchange
        :see: 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
        Nr
  r   r   r   deposit_statuswithdrawal_statusenabledr   base_withdrawal_feer   r   min_withdrawal_amount)r   rl   )r   	numericIdcoder   r   r   depositrl   feer   r   r   )
publicGetAssets	safe_listrangelenr   safe_integersafe_currency_codesafe_numberr   parse_precision)r   r  r  
currenciesr
  icurrencyr   r%  r&  depositStatuswithdrawalStatusdepositsEnabledwithdrawalsEnabledr   s                  r   fetch_currencieszdelta.fetch_currencies  s      --f55555555> ^^Hh;;
q#j//** 	 	A!!}H!!(H55B))(D99I**2..D ,,X7GHHM#//:MNN,	9O"2i"?$;);F&((6::  *.''2GHH!..t/C/CDDTDTU]_jDkDk/l/lmm&*488#//:QRR#! !  % F4LL( r   Fc                 n  K   t          t          |                               ||           d {V }|                     | j        d          }||r"|                     | j                  | j        d<   |                     | j        d          }||r"|                     | j                  | j        d<   |S )NcurrenciesByNumericIdmarketsByNumericId)r   r(   load_marketsr  r   index_by_stringified_numeric_idr1  markets)r   reloadr  r>  r:  r;  r   s         r   r<  zdelta.load_markets  s      eT**77GGGGGGGG $t|=T U U!)f)484X4XY]Yh4i4iDL01!^^DL:NOO&6&151U1UVZVb1c1cDL-.r   c                     i }|d S t          |                                          }t          dt          |                    D ]0}||         }||         }|                     |d          }|+|||<   1|S )Nr   r%  )listkeysr+  r,  r   )r   inputr
  rB  r2  keyitemnumericIdStrings           r   r=  z%delta.index_by_stringified_numeric_id  s    =4EJJLL!!q#d))$$ 	+ 	+Aq'C:D"..t[AAO&&*F?##r   c                   K   |                      |           d{V }|                     |dg           }g }t          dt          |                    D ]}||         }|                     |d          }|dk    r(|                     |di           }|                     |di           }	|                     |d          }
|                     |d	i           }|                     |	d
          }|                     |d
          }|                     |
d
          }|                     |d
          }|                     |d          }|                     |          }|                     |          }|                     |          }|dk    }|dk    }|dk    }|dk    }|dk    }|dk    }|p|p|}|                     |d          }|                     |d          }|                     |          }| 	                    |d          }d}|r=| 
                    |                     |                     |d                              }n| 
                    d          }||k    } d}!|dz   |z   }"|s|s|rP|"dz   |z   }"|s|rB|"dz   |                     |          z   }"|r"d}d}#d}!|rd}#d}!n|rd}#d }!|"dz   |z   dz   |#z   }"nd!}nd"}|                     |d#          }$|                    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|  | 	                    |d1          | 	                    |d2          |||| 
                    |          |!|| 	                    |d3          d4ddd5| 
                    d          | 	                    |d6          d5ddd5| 	                    |d7          dd5d8|                     |                     |d9                    |d:           |S );a  
        retrieves data on all markets for delta
        :see: 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
        Nr
  r   contract_typeoptions_combosquoting_assetunderlying_assetsettling_assetproduct_specsr   r   call_optionsput_optionsmove_optionsr-   perpetual_futuresfuturesstrike_pricesettlement_timecontract_valueunderlying_precisionr   r   r   r   r1   r   r   Pr   Mmover0   r/   stater%  r   r   r   r   r   r   r   r.   Fr   liver   taker_commission_ratemaker_commission_rate	tick_sizer   r   position_size_limitmin_size)leverager   r   r   launch_time)r   r   r   r   r   r   r   r   r   r   r   createdr   )publicGetProductsr*  r+  r,  r   r  r-  r.  r   r/  r   r0  yymmddappend)%r   r  r  r>  r
  r2  r   r   quotingAssetunderlyingAssetsettlingAssetproductSpecsr   r   r   r   r%  r   r   r   callOptions
putOptionsmoveOptionsr-   r/   r0   r1   r   r   r   r   amountPrecisionr   r   r   letterrZ  s%                                        r   fetch_marketszdelta.fetch_markets  s      //77777777f ..8R88q#g,,'' m	 m	AQZF##FO<<D'''>>&/2FFL"nnV5GLLO NN63CDDM>>&/2FFL%%ox@@F&&|X>>G''x@@H!!&(33B))&$77I**622D++G44E,,X66F>1K-/J>1KFND//Di'F!>Z>;F%%fn==F!--f6GHHN^^N33F++F4DEEL"O 9"&"3"3D4H4HIYIYZfh~II  5A  5A  #B  #B #'"3"3C"8"8nFJCZ%'F "v " "#. "V "#c\DKK,?,??F ('!$%+
% 0%(F).JJ( 0%(F)/J!'#!6!<v!E'!D$$VW55EMM 3b3Y3 &3 	3
 3 &3 &3 73 H3 3 3 $1$$E3 3 &3 &3  5F?!3" H#3$ #'2$$F#'744Z))&2IJJ))&2IJJ , "0++F33(-!--fkBB   $#! !
  $0055#//8MNN 
  $# 
  $//
CC#  $  >>$*:*:6=*Q*QRRe3 3 3 3 3 3 3h r   c                    |                      |dd          }|                     |d          }|                     ||          }|                     |d          }|                     |di           }|                     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|          S )Nr   r  r   closequotesr   highlowbidbest_bid	bidVolumebid_sizeaskbest_ask	askVolumeask_sizevwapopenlastpreviousClosechanger   averagevolumeturnover)
baseVolumequoteVolumer   )r  r   safe_symbolr  safe_tickeriso8601r/  )r   tickerr   r   r   r   r  rs  s           r   parse_tickerzdelta.parse_ticker(  s   h --fk5II	##FH55!!(F3300"55 !
f!
!
 Y//!
 D$$VV44	!

 4##FE22!
 4##FJ77!
 ))&*==!
 4##FJ77!
 ))&*==!
 D!
 D$$VV44!
 T!
 D!
 T!
 d!
  $!!
" t#!
$ **68<<++FJ??)!
 !
 !
* +  	r   c                 0  K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     |di           }|                     ||          S )a  
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
        :see: 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>`
        Nr   r   r
  )r<  r   publicGetTickersSymbolextendr  r  r   r   r  r   requestr  r
  s          r   fetch_tickerzdelta.fetch_ticker  s       !!!!!!!!!V$$fTl
 44T[[&5Q5QRRRRRRRRz (B77  000r   symbolsc                   K   |                                   d{V  |                     |          }|                     |           d{V }|                     |dg           }i }t	          dt          |                    D ]*}|                     ||                   }|d         }|||<   +|                     |d|          S )a  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
        :see: 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>`
        Nr
  r   r   )r<  market_symbolspublicGetTickersr*  r+  r,  r  filter_by_array_tickers)	r   r  r  r  r   r
  r2  r  r   s	            r   fetch_tickerszdelta.fetch_tickersE  s       !!!!!!!!!%%g....v66666666F ..8R88q#g,,'' 	$ 	$A&&wqz22FH%F#F6NN++FHgFFFr   limitc           	      T  K   |                                   d{V  |                     |          }d|d         i}|||d<   |                     |                     ||                     d{V }|                     |di           }|                     ||d         ddddd	          S )
a/  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :see: 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
        Nr   r   depthr
  buysellr   size)r<  r   publicGetL2orderbookSymbolr  r  parse_order_book)r   r   r  r  r   r  r  r
  s           r   fetch_order_bookzdelta.fetch_order_book  s       !!!!!!!!!V$$fTl
 $GG88Wf9U9UVVVVVVVV& (B77$$VVH-=tUFT[]cdddr   c                    |                      |d          }|                      |d          }|                     |                      |d                    }|                     |dd|          }|                      |d          }|                      |d          }|                     |di           }|                      |d	          }	|                     |	|          }
|                      |d
          }|                      |d          }||dk    rd}n|dk    rd}|                      |d          }|                     |di           }|                      |d          }||                    dd          }|                      |d          }d }|G|                     |di           }|                      |d	          }|                     |          }||d}|                     ||||                     |          |
||||d |||d|          S )Nr   order_id
created_atr   r  r   r  productr   seller_rolesider   r  r   r  role	meta_data
order_type_order 
commissionrL  r   r3  )r   orderr   r   r   r   r  r   r   r   takerOrMakerr(  r   )	r   r   r  r  r  replacer.  
safe_trader  )r   trader   r   orderIdr   priceStringamountStringr  r   r   
sellerRoler  r  metaDatar   feeCostStringr(  ri  feeCurrencyIdfeeCurrencyCodes                        r   parse_tradezdelta.parse_trade   sE   ` eT**""5*55NN4#3#3E<#H#HII	--e[%SS	&&ug66''v66..	266##GX66!!(F33%%e];;
v..<W$$w&&''v66>>%b99,77<<"--D((==$ NN74DbIIM ,,]HEEM"55mDDO%+ C "Y// "( 
  
   	r   sincec                 4  K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     |dg           }|                     ||||          S )a  
        get the list of most recent trades for a particular symbol
        :see: 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>`
        Nr   r   r
  )r<  r   publicGetTradesSymbolr  r*  parse_trades)	r   r   r  r  r  r   r  r  r
  s	            r   fetch_tradeszdelta.fetch_trades_  s       !!!!!!!!!V$$fTl
 33DKK4P4PQQQQQQQQ  (B77  >>>r   c           	         |                      |d          |                     |d          |                     |d          |                     |d          |                     |d          |                     |d          gS )Ntimer  rt  ru  rr  r  )safe_timestampr/  )r   ohlcvr   s      r   parse_ohlcvzdelta.parse_ohlcv  s     v..UF++UF++UE**UG,,UH--
 	
r   rm   c                 (  K   |                                   d{V  |                     |          }d|                     | j        ||          i}|                     |          }|r|nd}|%|                                 }	|	|d<   |	||z  z
  |d<   n9|                     |dz            }
|
|d<   |                     |
||z            |d<   |                     |d          }|dk    rd	|d
         z   |d<   n)|dk    r|d         d         d         |d<   n|d
         |d<   |                     |d          }| 	                    | 
                    ||                     d{V }|                     |dg           }|                     |||||          S )a  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :see: https://docs.delta.exchange/#get-ohlc-candles
        :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
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        N
resolutioni  endstarti  r   markzMARK:r   r   indexr   
spot_indexr
  )r<  r   r   r   parse_timeframesecondsparse_to_intsumomitpublicGetHistoryCandlesr  r*  parse_ohlcvs)r   r   	timeframer  r  r  r   r  durationr  r  r   r  r
  s                 r   fetch_ohlcvzdelta.fetch_ohlcv  s      !!!!!!!!!V$$$**4?IyQQ
 ''	22(D=,,..C GEN"UX%55GG%%edl33E$GG!XXeUX-=>>GEN  11F?? '&, 6GHg &v| <X FGH &tGH67++55dkk'66R6RSSSSSSSS (B77  E5IIIr   c                    |                      |dg           }d|i}|                     | j        di           }t          dt	          |                    D ]}||         }|                     |d          }|                     ||          }||n|d         }	|                                 }
|                     |d          |
d<   |                     |d	          |
d
<   |
||	<   |                     |          S )Nr
  r   r:  r   asset_idr&  balancetotalavailable_balancefree)r*  r  r   r+  r,  r   accountsafe_balance)r   r  balancesr
  r:  r2  r  
currencyIdr3  r&  r  s              r   parse_balancezdelta.parse_balance  s    >>(Hb99(# $t|=TVX Y Yq#h--(( 	# 	#AqkG))':>>J~~&;ZHHH"*"2::&9IDllnnG#//CCGG"..w8KLLGFO"F4LL  (((r   c                    K   |                                   d{V  |                     |           d{V }|                     |          S )a`  
        query for balance and get the amount of funds available for trading or funds locked in orders
        :see: 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>`
        N)r<  privateGetWalletBalancesr  )r   r  r  s      r   fetch_balancezdelta.fetch_balance  sg       !!!!!!!!!66v>>>>>>>>, !!(+++r   c                 0  K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     |di           }|                     ||          S )a  
        fetch data on a single open contract trade position
        :see: 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>`
        N
product_idr%  r
  )r<  r   privateGetPositionsr  r  parse_positionr  s          r   fetch_positionzdelta.fetch_position  s       !!!!!!!!!V$$&-
 11$++gv2N2NOOOOOOOO (B77""66222r   c                    K   |                                   d{V  |                     |           d{V }|                     |dg           }|                     ||          S )al  
        fetch all open positions
        :see: 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>`
        Nr
  )r<  privateGetPositionsMarginedr*  parse_positions)r   r  r  r  r
  s        r   fetch_positionszdelta.fetch_positions  s~       !!!!!!!!!99&AAAAAAAA, (B77##FG444r   c                    |                      |d          }|                     ||          }|d         }|                     |dd          }|                      |d          }d }|/t          j        |d          rd}nt          j        |d          rd}|                     i d	|d
d d|dd dd d|                     |d          d|                     |d          dd dd d|                     |          d|                     |d          dd d|dd d|d| 	                    |          dd d d d d d d d d d          S )Nproduct_symbolr   r   r  r  r   r  r  r   r   notional
marginModeliquidationPriceliquidation_price
entryPriceentry_priceunrealizedPnlr   	contractsr   	markPricer  hedgedr   maintenanceMargin)maintenanceMarginPercentage
collateralinitialMargininitialMarginPercentagera  marginRatiostopLossPricetakeProfitPrice)
r   r  r  r&   	string_gt	string_ltsafe_positionr/  r   r  )r   positionr   r   r   r   
sizeStringr  s           r   r  zdelta.parse_position1  s   8 ##H.>??!!(F33!--hUKK	%%h77
! S11 ":s33 !! #
H#
$#
 f#
 	#

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

 Y// 
 !$ 
 f 
 D 
 D 
 U 
 f 
 D 
 w 
 d 
  
  f! 
" 3# 
$ d% 
  
& '  	r   r   r  r   r   c                   K   |                                   d{V  |dz   }|                     |          }|d         |                     |d         |          ||d}	|dk    r|                     |d         |          |	d<   |                     |dd	          }
|                     |dd	g          }|
|
|	d	<   |                     |d
          }|r||	d<   |                     |d
          }|                     |                     |	|                     d{V }| 	                    |di           }| 
                    ||          S )a  
        create a trade order
        :see: 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 fullfilled, 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>`
        Nr  r%  r   )r  r  r  r  r  r  r  r  
reduceOnlyreduce_onlyr
  )r<  r   amount_to_precisionprice_to_precisionsafe_string_2r  	safe_boolprivatePostOrdersr  r  r  )r   r   r   r  r   r   r  	orderTyper   r  r  r  r  r
  s                 r   create_orderzdelta.create_order  s}      !!!!!!!!!8O	V$$ -,,VH-=vFF#

 

 7??%)%<%<VH=Mu%U%UGM"**6?DUVV6O5F#GHH$)6G%&^^FL99
 	5%/GM"YYv|44F//GV0L0LMMMMMMMMJ (B77///r   r   c                   K   |                                   d{V  |                     |          }t          |          |d         d}	|&t          |                     ||                    |	d<   ||                     ||          |	d<   |                     |                     |	|                     d{V }
|                     |
d          }|                     ||          S )a  
        edit a trade order
        :see: 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 fullfilled, 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>`
        Nr%  r   r  r  r  r
  )	r<  r   intr!  r"  privatePutOrdersr  r  r  )r   r   r   r   r  r   r   r  r   r  r  r
  s               r   
edit_orderzdelta.edit_order  s      !!!!!!!!!V$$b'' -
 
 !$":":66"J"JKKGFO%)%<%<VU%K%KGM"..t{{7F/K/KLLLLLLLL$ (33///r   c                 |  K   |t          | j        dz             |                                  d{V  |                     |          }t	          |          |d         d}|                     |                     ||                     d{V }|                     |d          }|                     ||          S )a|  
        cancels an open order
        :see: 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>`
        Nz) cancelOrder() requires a symbol argumentr%  r)  r
  )	r   r   r<  r   r*  privateDeleteOrdersr  r  r  )r   r   r   r  r   r  r  r
  s           r   cancel_orderzdelta.cancel_orderL  s       >#DG.Y$YZZZ!!!!!!!!!V$$b'' -
 
 11$++gv2N2NOOOOOOOOJ (33///r   c                    K   |t          | j        dz             |                                  d{V  |                     |          }d|d         i}|                     |                     ||                    }|S )a  
        cancel all open orders in a market
        :see: 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>`
        Nz- cancelAllOrders() requires a symbol argumentr  r%  )r   r   r<  r   privateDeleteOrdersAllr  )r   r   r  r   r  r  s         r   cancel_all_orderszdelta.cancel_all_orders  s       >#DG.]$]^^^!!!!!!!!!V$$&-

 ..t{{7F/K/KLL r   c                 D   K   |                      d||||           d{V S )a  
        fetch all unfilled currently open orders
        :see: 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>`
        privateGetOrdersNfetch_orders_with_methodr   r   r  r  r  s        r   fetch_open_orderszdelta.fetch_open_orders  s9       223EvuV[]cdddddddddr   c                 D   K   |                      d||||           d{V S )aF  
        fetches information on multiple closed orders made by the user
        :see: 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>`
        privateGetOrdersHistoryNr5  r7  s        r   fetch_closed_orderszdelta.fetch_closed_orders  s:       223LfV[]bdjkkkkkkkkkr   c                   K   |                                   d {V  i }d }| |                     |          }|d         |d<   |t          |          dz   |d<   |||d<   d }|dk    r0|                     |                     ||                     d {V }n5|dk    r/|                     |                     ||                     d {V }|                     |dg           }	|                     |	|||          S )	Nr%  product_ids000
start_time	page_sizer4  r:  r
  )r<  r   strr4  r  r:  r*  parse_orders)
r   methodr   r  r  r  r  r   r  r
  s
             r   r6  zdelta.fetch_orders_with_method  s?     !!!!!!!!!	
 [[((F%+K%8GM"$'JJ$6GL!#(GK '''!224;;w3O3OPPPPPPPPHH000!99$++gv:V:VWWWWWWWWH0 (B77  >>>r   c                 ~  K   |                                   d{V  i }d}| |                     |          }|d         |d<   |t          |          dz   |d<   |||d<   |                     |                     ||                     d{V }|                     |dg           }|                     ||||          S )a  
        fetch all trades made by the user
        :see: 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>`
        Nr%  r=  r>  r?  r@  r
  )r<  r   rA  privateGetFillsr  r*  r  )	r   r   r  r  r  r  r   r  r
  s	            r   fetch_my_tradeszdelta.fetch_my_trades  s       !!!!!!!!!
 [[((F%+K%8GM"$'JJ$6GL!#(GK --dkk'6.J.JKKKKKKKK\ (B77  >>>r   r&  c                 P  K   |                                   d{V  i }d}| |                     |          }|d         |d<   |||d<   |                     |                     ||                     d{V }|                     |dg           }|                     ||||          S )aW  
        fetch the history of changes, actions done by the user or operations that altered balance of the user
        :see: 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 entrys 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-structure>`
        Nr%  r  r@  r
  )r<  r3  privateGetWalletTransactionsr  r*  parse_ledger)	r   r&  r  r  r  r  r3  r  r
  s	            r   fetch_ledgerzdelta.fetch_ledger7  s       !!!!!!!!!
 }}T**H"*;"7GJ#(GK ::4;;wPV;W;WXXXXXXXX, (B77  5%@@@r   c                 D    dddddddd}|                      |||          S )Npnltransactionr(  r  r   rebate)rL  r'  
withdrawalr  
conversionreferral_bonuscommission_rebater  )r   r   typess      r   parse_ledger_entry_typezdelta.parse_ledger_entry_typeh  s?    $'! )!)
 
 tT222r   r3  c                    |                      |d          }d }d }|                     |di           }|                      |d          }d }|                      |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}|                     |	          }	|                      |d          }
|                     | j        d          }|                     ||
|          }|d n|d         }|                      |d          }|                     |                      |d                    }|                      |d          }t          j        dt          j        ||                    }d}|||||||	|| 	                    |          | 	                    |          | 	                    |          ||| 
                    |          d dS )Nuuidr  transaction_idtransaction_typer'  rR  rQ  rL  withdrawal_cancellationpromo_creditinrO  r  rP  perpetual_futures_fundingoutr  r:  r&  r   r  r  r   r  )r   r   	directionr  referenceIdreferenceAccountr   r3  r   beforeafterr  r   r   r(  )r   r  rT  r   r  r   r&   
string_max
string_subr   r  )r   rE  r3  r   r^  r  r  r_  r`  r   r  r:  r&  r   r   rb  ra  r  s                     r   parse_ledger_entryzdelta.parse_ledger_entryw  sK     dF++	>>$R88&&x1ABB&899I4+>#>#>DL\D\D\bfjobobouy  ~W  vW  vW  ]a  es  ]s  ]sIIl""(<(<$,BVBV\`d\\I++D11%%dJ77
 $t|=T U U??#8*hOO (ttx/?!!$11NN4#3#3D,#G#GHH	  y11#C);E6)J)JKK"& 0''//''//&&u--"Y//
 
 	
r   c                   K   |                                   d{V  |                     |          }d|d         i}|                     |d          }|/|                     ||          |d<   |                     |d          }|                     |                     ||                     d{V }|                     |di           }|                     ||          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>`
        Nasset_symbolr   networkr
  )	r<  r3  safe_string_uppernetwork_code_to_idr  privateGetDepositsAddressr  r  parse_deposit_address)r   r&  r  r3  r  networkCoder  r
  s           r   fetch_deposit_addresszdelta.fetch_deposit_address  s       !!!!!!!!!==&&HTN
 ,,VY??"!%!8!8d!K!KGIYYvy11F77GV8T8TUUUUUUUU$ (B77))&(;;;r   c                 6   |                      |d          }|                      |d          }|                      |d          }|                     |           |                     ||          ||                      |d          |                     |          |dS )Naddressrg  rh  memo)r3  rp  tagrh  r   )r   check_addressr.  network_id_to_code)r   depositAddressr3  rp  r   	networkIds         r   rl  zdelta.parse_deposit_address  s     "">9==##NNCC$$^Y??	7###//(CC##NF;;..y99"
 
 	
r   c                 n  K   |                                   d{V  |                     |          }|d         st          | j        dz             d|d         i}|                     |                     ||                     d{V }|                     |di           }|                     ||          S )ak  
        fetch the current funding rate
        :see: 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>`
        Nr/   z0 fetchFundingRate() supports swap contracts onlyr   r   r
  )r<  r   r    r   r  r  r  parse_funding_rater  s          r   fetch_funding_ratezdelta.fetch_funding_rate  s       !!!!!!!!!V$$f~ 	ZDG&XXYYYfTl
 44T[[&5Q5QRRRRRRRR\ (B77&&vv666r   c                 P  K   |                                   d{V  |                     |          }ddi}|                     |                     ||                     d{V }|                     |dg           }|                     |          }|                     |d|          S )a  
        fetch the funding rate for multiple markets
        :see: 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 dictionary of `funding rates structures <https://docs.ccxt.com/#/?id=funding-rates-structure>`, indexe by market symbols
        Ncontract_typesrQ  r
  r   )r<  r  r  r  r*  parse_funding_ratesfilter_by_array)r   r  r  r  r  ratesr
  s          r   fetch_funding_rateszdelta.fetch_funding_rates/	  s       !!!!!!!!!%%g..1
 ..t{{7F/K/KLLLLLLLL` x266))%00##FHg>>>r   c                    |                      |dd          }|                     |d          }|                     |d          }t          j        |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 S )Nr   r  r   funding_rater   r   r  
mark_price
indexPrice
spot_priceinterestRateestimatedSettlePricer   fundingRatefundingTimestampfundingDatetimenextFundingRatenextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetime)r  r   r&   
string_divr  r/  r  r   )r   r   r   r   r   fundingRateStringr  s          r   rx  zdelta.parse_funding_ratep	  sv   V --hUKK	##Hh77 ,,X~FF():EBB
H
d&&x88
 ))(LAA
 $**8\BB	

 D
 #D
 
 Y//
 4,,[99
 
 t
 t
 #D
 "4
 "4
  '!
" &t#
 	
r   c                 B   K   |                      ||d|           d{V S )a|  
        add margin
        :see: 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>`
        addNmodify_margin_helperr   r   r   r  s       r   
add_marginzdelta.add_margin	  s4       ..vvufMMMMMMMMMr   c                 B   K   |                      ||d|           d{V S )a  
        remove margin from a position
        :see: 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>`
        reduceNr  r  s       r   reduce_marginzdelta.reduce_margin	  s4       ..vvxPPPPPPPPPr   c                   K   |                                   d {V  |                     |          }t          |          }|dk    rt          j        |d          }|d         |d}|                     |                     ||                     d {V }|                     |di           }|                     ||          S )Nr  z-1r%  )r  delta_marginr
  )	r<  r   rA  r&   
string_mul privatePostPositionsChangeMarginr  r  parse_margin_modification)	r   r   r   r   r  r   r  r  r
  s	            r   r  zdelta.modify_margin_helper	  s      !!!!!!!!!V$$V8'55F -"
 
 >>t{{7TZ?[?[\\\\\\\\0 (B77--ff===r   c                     |                      |d          }|                     ||          }||d         d dd |                     |d          d d d d d
S )Nr  r   isolatedr.   )
r   r   r   r  r   r  r&  r  r   r   )r   r  r/  )r   datar   r   s       r   r  zdelta.parse_margin_modification	  sq    * ##D*:;;!!(F33X&$%%dH55
 
 	
r   c                 n  K   |                                   d{V  |                     |          }|d         st          | j        dz             d|d         i}|                     |                     ||                     d{V }|                     |di           }|                     ||          S )ak  
        retrieves the open interest of a derivative market
        :see: 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:
        Nr   z3 fetchOpenInterest() supports contract markets onlyr   r   r
  )r<  r   r   r   r  r  r  parse_open_interestr  s          r   fetch_open_interestzdelta.fetch_open_interest
  s       !!!!!!!!!V$$j! 	^TW'\\]]]fTl
 44T[[&5Q5QRRRRRRRRj (B77''777r   c                    |                      |dd          }|                     |d          }|                     |                     ||          |                     |d          |                     |d          |                     |d          |                     |d          ||                     |          |d|          S )	Nr   r  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_interestY
  s    d --hUKK	##Hh77&&&&x88**8Z@@++HnEE"&"2"28^"L"L!%!1!1(D!A!A"Y//	(
 	(
 	 	 		r   c                 0  K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     |di           }|                     ||          S )aX  
        fetch the set leverage for a market
        :see: 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>`
        Nr  r%  r
  )r<  r   )privateGetProductsProductIdOrdersLeverager  r  parse_leverager  s          r   fetch_leveragezdelta.fetch_leverage
  s       !!!!!!!!!V$$&-
 GGT[]cHdHdeeeeeeee (B77""66222r   c                     |                      |d          }|                     |d          }||                     ||          |                     |d          ||dS )Nindex_symbolra  margin_mode)r   r   r  longLeverageshortLeverage)r   r-  r  safe_string_lower)r   ra  r   r   leverageValues        r   r  zdelta.parse_leverage
  sj    ##Hn==))(J??&&x8800=II)*
 
 	
r   ra  c                 
  K   |t          | j        dz             |                                  d{V  |                     |          }|d         |d}|                     |                     ||                     d{V S )ae  
        set the level of leverage for a market
        :see: 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
        Nz) setLeverage() requires a symbol argumentr%  )r  ra  )r   r   r<  r   *privatePostProductsProductIdOrdersLeverager  )r   ra  r   r  r   r  s         r   set_leveragezdelta.set_leverage
  s       >#DG.Y$YZZZ!!!!!!!!!V$$ - 
 
 DDT[[QXZ`EaEabbbbbbbbbr   c                   K   |                                   d{V  d}||                     |          }ddi}|||d<   |                     |                     ||                     d{V }|                     |dg           }|                     ||          }	|                     |	d          }
|                     |
|d         ||          S )a  
        fetches historical settlement records
        :see: 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expiredr@  r
  r   r   )r<  r   rd  r  r*  parse_settlementssort_byfilter_by_symbol_since_limit)r   r   r  r  r  r   r  r  r
  settlementssorteds              r   fetch_settlement_historyzdelta.fetch_settlement_history
  s       !!!!!!!!![[((Fi
 #(GK //GV0L0LMMMMMMMMv (B77,,VV<<k;77009I5RWXXXr   c                     |                      |d          }|                      |d          }||                     ||          |                     |d          |                     |          |dS )NrT  r   settlement_price)r   r   r   r   r   )r   r  r/  r   )r   
settlementr   r   r   s        r   parse_settlementzdelta.parse_settlement2  s{    l ##J0ABB##J99&&x88%%j2DEE11 
 
 	
r   c                     g }t          dt          |                    D ]1}|                    |                     ||         |                     2|S )Nr   )r+  r,  rf  r  )r   r  r   r
  r2  s        r   r  zdelta.parse_settlementsr  sX    q#k**++ 	I 	IAMM$//AGGHHHHr   c                 0  K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     |di           }|                     ||          S )a  
        fetches an option contracts greeks, financial metrics used to measure the factors that affect the price of an options contract
        :see: 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>`
        Nr   r   r
  )r<  r   r  r  r  parse_greeksr  s          r   fetch_greekszdelta.fetch_greeksx  s       !!!!!!!!!V$$fTl
 44T[[&5Q5QRRRRRRRRj (B77  000r   c                    |                      |dd          }|                     |d          }|                     ||          }|                     |di           }|                     |di           }i d|d|d|                     |          d|                     |d          d|                     |d          d	|                     |d	          d
|                     |d
          d|                     |d          d|                     |d          d|                     |d          d|                     |d          d|                     |d          d|                     |d          d|                     |d          d|                     |d          d|                     |d          dd |                     |d          |dS )Nr   r  r   greeksrs  r   r(   gammathetavegarhobidSizery  askSizer}  bidImpliedVolatilitybid_ivaskImpliedVolatilityask_ivmarkImpliedVolatilitymark_ivbidPricerw  askPricer{  r  r  	lastPricer  )underlyingPricer   )r  r   r  r  r  r/  )r   r  r   r   r   r   r   rs  s           r   r  zdelta.parse_greeks  sE   d --fk5II	##FH55!!(F33vx44"55
f

 Y//
 T%%eW55	

 T%%eW55
 T%%eW55
 D$$UF33
 4##E511
 t''
;;
 t''
;;
 #D$4$4VX$F$F
 #D$4$4VX$F$F
 $T%5%5fi%H%H
 ((<<
 ((<<
  ))&,??!
" #
$  $//EE'
 
 
 	
r   c                    K   |                                   d{V  ddd}|                     |                     ||                     d{V }|                     |                     |di                     }|gS )am  
        closes all open positions for a market type
        :see: 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>`
        NT)close_all_portfolioclose_all_isolatedr
  )r<  privatePostPositionsCloseAllr  r  r  )r   r  r  r  r  s        r   close_all_positionszdelta.close_all_positions
  s       !!!!!!!!!#'"&
 

 ::4;;wPV;W;WXXXXXXXX &&t~~h"'M'MNNzr   c                    K   |                                   d{V  d}||                     |          }|                     |           d{V }|                     |di           }|                     ||          S )a~  
        fetches the margin mode of a trading pair
        :see: 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>`
        Nr
  )r<  r   privateGetProfiler  parse_margin_mode)r   r   r  r   r  r
  s         r   fetch_margin_modezdelta.fetch_margin_mode  s       !!!!!!!!![[((F//77777777@ (B77%%ff555r   c                 N    d }||d         }|||                      |d          dS )Nr   r  )r   r   r  r  )r   r  r   r   s       r   r  zdelta.parse_margin_moden  s?    H%F**:}EE
 
 	
r   c                 2  K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     |di           }|                     |d|          S )a  
        fetches option data that is commonly found in an option chain
        :see: 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>`
        Nr   r   r
  )r<  r   r  r  r  parse_optionr  s          r   fetch_optionzdelta.fetch_optionx  s       !!!!!!!!!V$$fTl
 44T[[&5Q5QRRRRRRRRj (B77  v666r   c                    |                      |d          }|                     ||          }|                     |di           }|                     |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 S )Nr   rs  r   r  r   r3  r   impliedVolatilityr  openInterestr  r  rw  r  r{  midPriceimpact_mid_pricer  r  r  r  r  r  r   r  r  r  )r   r  r  r  r  r/  )r   chainr3  r   r   rs  r   s          r   r  zdelta.parse_option  s   d ##E844!!(F33x44--e[%HH	
E

 fX&
 	

 Y//
  !1!1&)!D!D
 D,,UD99
 ((<<
 ((<<
 ((1CDD
 ))%>>
 
 t//|DD
 d
 $
  $**5(;;!
" 4#
 	
r   r|   GETc                    d| j         z   dz   |                     ||          z   }| j        d         |         |z   }|                     ||                     |                    }	|dk    r|	r|d|                     |	          z   z  }n|dk    r|                                  t          |                                           }
| j	        |
d}||
z   |z   }|dk    s|dk    r%|	r"d|                     |	          z   }||z  }||z  }n| 
                    |	          }||z  }d	|d
<   |                     |                     |          |                     | j                  t          j                  }||d<   ||||dS )Nr   r   r|   ?r}   )zapi-keyr   r  DELETEzapplication/jsonzContent-Type	signature)r  rC  bodyheaders)r   implode_paramsr   r  extract_params	urlencodecheck_required_credentialsrA  r  r   jsonhmacencoder   hashlibsha256)r   pathr   rC  r  r  r  requestPathr  queryr   authqueryStringr  s                 r   signz
delta.sign  s   DL(3.1D1DT61R1RRis#k1		&$"5"5d";";<<(?? 3sT^^E2222I++---DLLNN++I;& G I%3D%Vx%7%7 '"%u(=(="=KK'D;&Cyy''*<'		$++d"3"3T[[5M5Mw~^^I#,GK fdwOOOr   c
                 ,   |d S |                      |di           }
|                     |
d          }|`| j        dz   |z   }|                     | j        d         ||           |                     | j        d         ||           t          |          d S )Nerrorr&   r   r   )r  r   r   throw_exactly_matched_exceptionr   throw_broadly_matched_exceptionr   )r   r&  reasonr  rC  r  r  r  requestHeadersrequestBodyr
  	errorCodefeedbacks                r   handle_errorszdelta.handle_errors#  s    4 x"55$$UF33	 w}t+H001I9V^___001I9V^___)))tr   )NNNN)N)NN)[__name__
__module____qualname__r   rA  r   r   r   r   r  r  r  r   r8  r<  r=  r   rp  r   r  r  r   r   r  r	   r   r  r   r  r  rA  r  r  r   r  r  r  r  r  r  r   r  r   r   floatr   r'  r,  r/  r2  r8  r;  r6  rF  rJ  rT  r   re  rn  rl  ry  r  rx  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  __classcell__)r   s   @r   r(   r(      s       e e e e eN?
3 ?
 ?
 ?
 ?
BW WC W WRU Wjm W  zI W W W W W W ') 	G 	G 	G 	G )+ F
 F
 F
 F
P -/ F F: F F F FP ).b         *, j jV j j j jX	N N6 NV N N N N` 68 K1 K1 K1F K1 K1 K1 K1Z 6:" SG SG7 SG SG SG SG SGj @DB $e $eS $e $eS\ $e $e $e $eL] ] ]5 ] ] ] ]~ <@d[]  ?  ?  ?S  ?  ?bfglbm  ?  ?  ?  ?D
 
 
4 
 
 
 
( 8<$]ajl .J .J .JC .JWZ .Jquvzq{ .J .J .J .J`) ) ) ) ) *, , , , , , ,@ 8: 3 33 3 3 3 36 8<B  5  5W  5  5  5  5DA Av A A A AF: : :R R R5 R R R Rh mqy{ K0 K0 K0I K0Y K0X] K0fi K0 K0 K0 K0Z fjx|  FH ,0 ,03 ,0 ,09 ,0I ,0_b ,0ru ,0 ,0 ,0 ,0\ 9=R 70 70S 70# 70 70 70 70r 59  c    4 59tZ^gi 
e 
ec 
e 
eTW 
enrsxny 
e 
e 
e 
e 7;\`ik 
l 
l 
l3 
lVY 
lptuzp{ 
l 
l 
l 
l DHVZimvx 1? 1?S 1?PS 1?cf 1? 1? 1? 1?f 37TX\eg K? K?C K?s K?RU K? K? K? K?Z .2SW`b /A /As /A# /AS /A /A /A /Ab3 3 35
 5
 5
 5
 5
 5
n =? $< $< $< $< $< $<L
 
h 
 
 
 
6 <> >7 >7s >7 >7 >7 >7@ <@ ?? ?? ?? ?? ?? ??BA
 A
6 A
 A
 A
 A
F <> 	N 	Ns 	NBT 	N 	N 	N 	N ?A 	Q 	Q# 	QEW 	Q 	Q 	Q 	Q LN #> #> #>Rd #> #> #> #>J"
 "
f "
HZ "
 "
 "
 "
H =? E8 E8 E8 E8 E8 E8N= =F = = = =~ 8: 3 33 3h 3 3 3 3<	
 	
x 	
 	
 	
 	
 ?C2 c c3 c c c c c< <@daenp QY QYS QY QY[^ QY QY QY QYf>
 >
 >
@   68 C1 C1 C1F C1 C1 C1 C1JK
 K
6 K
 K
 K
 K
Z 02  d8n    * ;= M6 M6c M6 M6 M6 M6 M6^
 
J 
 
 
 
 68 C7 C7 C7F C7 C7 C7 C7JH
 H
H H
V H
 H
 H
 H
T &eBSW P P P P8      r   r(   )- ccxt.async_support.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   typingr   ccxt.base.errorsr   r   r   r   r    r!   r"   r#   r$   ccxt.base.decimal_to_precisionr%   ccxt.base.preciser&   r(    r   r   <module>r!     sl   6 5 5 5 5 5 + + + + + +  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p       * * * * * * 0 0 0 0 0 0 . . . . . . ' ' ' ' ' ' & & & & & & . . . . . . ) ) ) ) ) ) * * * * * * 1 1 1 1 1 1 4 4 4 4 4 4 % % % % % %X4 X4 X4 X4 X4Hk X4 X4 X4 X4 X4r   