
    eiS                    X   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 d dlm Z  d dl!m"Z" d dl!m#Z# d dl!m$Z$ d d	l!m%Z% d d
l!m&Z& d dl!m'Z' d dl!m(Z( d dl!m)Z) d dl!m*Z* d dl!m+Z+ d dl!m,Z, d dl-m.Z. d dl/m0Z0  G d dee          Z1dS )    )Exchange)ImplicitAPIN)AnyADLBalances
CurrenciesCurrencyDepositAddressIntLedgerEntryLeverage	LeveragesMarketNumOrder	OrderBook	OrderSide	OrderTypePositionStrStringsTickerTickersFundingRateFundingRatesTradeTransaction)List)ExchangeError)AuthenticationError)PermissionDenied)ArgumentsRequired)
BadRequest)	BadSymbol)InsufficientFunds)InvalidOrder)OrderNotFound)DDoSProtection)ExchangeNotAvailable)	TICK_SIZE)Precisec                       e Zd Zdef fdZi fdefdZd ZdedefdZ	 fdZ
dkd
Zd Zi fdee         fdZdedefdZdefdZi fdefdZdi fdededefdZdi fdedefdZdddi fdedededee         fdZdddi fdedededee         fdZdddi fdedededee         fdZdddi fdededefdZd Zdldede de!fdZ"dddi fdedededee!         fd Z#dddi fdedededee$         fd!Z%d"efd#Z&dld$ede de$fd%Z'i fdede(fd&Z)di fd'e*de+fd(Z,dld)edede(fd*Z-dldede.fd+Z/d,ddi fded-edededee.         f
d.Z0dld/edede1fd0Z2d"efd1Z3d2efd3Z4dld4ededefd5Z5ddi fdedededee1         fd6Z6di fded7e7d8e8de9d9e:f
d:Z;ddi fdeded7e7d8e8de:d9e:fd;Z<di fdedefd<Z=di fd=ee         defd>Z>di fdefd?Z?i fd@efdAZ@di fd'e*deAfdBZBdldCededeCfdDZDdi fd'e*deeE         fdEZFdldFedefdGZGdi fdede9dHedIede$f
dJZHdi fd'e*deIfdKZJdldedeKfdLZLdddi fdededefdMZMdldefdNZNdi fdCeOdefdOZPdi fdPedefdQZQi fdedeRfdRZSdlde fdSZTdi fdTe*fdUZUdi fd'e*fdVZVdldefdWZWi fdXZXddi fdededefdYZYdldefdZZZdi fd'e*dee[         fd[Z\dld\edede[fd]Z]dddi fdededefd^Z^dmd_Z_dld`Z`deOdaedbedceddedeefdfZadg Zbdhdii ddfdjZc xZdS )nbitmexreturnc                    |                      t          t          |                                           i ddddddgddd	d d
ddddddi dd dddddddddddd ddddddddddddddddd dd!di d"dd#dd$dd%dd&dd'dd(dd)dd*dd+dd,dd-dd.dd/dd0dd1dd2di d3dd4dd5dd6d7d8d7d9dd:dd;d7d<dd=dd>dd?dd@ddAddBddCd7dDdi dEddFddGddHddIddJddKddLddMddNd7dOddPddQddRddSddTddUdi dVddWddXddYddZdd[dd\dd]dd^dd_dd`ddaddbd7dcdddddeddfdd ddddd dddddg
dhdidjdkdldmdndododpdqdrdrdpdrdsdtgdudvdwdxdydzd{i d|d}d~d}dd}dd}dd}dd}dd}dd}dd}dd}dd}dd}dd}dd}dd}dd}dd}d}d}d}d}d}d}d}d}d}d}d}d}d}d}d}dii dd}dd}dd}dd}dd}dd}dd}dd}dd}dd}dd}dd}dd}dd}dd}dd}dd}d}d}d}d}d}d}d}d}d}d}d}d}d}di dd}dd}dd}dd}dd}dd}dd}dd}dddd}dd}dddddd}dddd}dd}d}d}d}d}d}d}d}d}d}d	d}ddddd}dddpdt          t
          t
          t          t          t          t          t
          dt          t          t          t          t          t          t
          dddt          dd}dddddddddddddÜ
dĜdddddddƜdddd dddddǜdddddȜd ddd ddd˜ddddd̜dddddd͜ddd dddddΜddd d dddddϜddidҜ	dddfdiid՜dddfdiid՜ddiddid؜ddiddid؜dٜdddddddddߜ          S )Nidr-   nameBitMEX	countriesSCversionv1	userAgent	rateLimitd   	certifiedTprohasCORSspotmarginFswapfutureoption	addMarginborrowCrossMarginborrowIsolatedMarginborrowMargincancelAllOrderscancelAllOrdersAftercancelOrdercancelOrderscloseAllPositionsclosePositioncreateOrdercreateReduceOnlyOrdercreateStopOrdercreateTrailingAmountOrdercreateTriggerOrder	editOrderfetchAllGreeksfetchBalancefetchBorrowInterestfetchBorrowRatefetchBorrowRateHistoriesfetchBorrowRateHistoryfetchBorrowRatesfetchBorrowRatesPerSymbolfetchClosedOrdersfetchCrossBorrowRatefetchCrossBorrowRatesfetchCurrenciesfetchDepositAddressfetchDepositAddressesfetchDepositAddressesByNetworkfetchDepositsWithdrawalsemulatedfetchDepositWithdrawFeefetchDepositWithdrawFeesfetchFundingHistoryfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchGreeksfetchIndexOHLCVfetchIsolatedBorrowRatefetchIsolatedBorrowRatesfetchLedgerfetchLeveragefetchLeveragesfetchLeverageTiersfetchLiquidationsfetchMarginAdjustmentHistoryfetchMarketLeverageTiersfetchMarketsfetchMarkOHLCVfetchMyLiquidationsfetchMyTrades
fetchOHLCVfetchOpenInterestfetchOpenInterestsfetchOpenOrdersfetchOptionfetchOptionChain
fetchOrderfetchOrderBookfetchOrdersfetchPositionfetchPositionADLRankfetchPositionHistoryfetchPositionsfetchPositionsADLRankfetchPositionsHistoryfetchPositionsRiskfetchPremiumIndexOHLCVfetchSettlementHistoryfetchTickerfetchTickersfetchTradesfetchTransactionsfetchTransferfetchTransfersfetchVolatilityHistoryindex)
reduceMarginrepayCrossMarginrepayIsolatedMarginsandboxsetLeverage	setMarginsetMarginModesetPositionModetransferwithdraw
timeframes1m5m1h1d)r   r   r   r   urlszhttps://testnet.bitmex.com)publicprivatezOhttps://github.com/user-attachments/assets/c78425ab-78d5-49d6-bd14-db7734798f04zhttps://www.bitmex.comz&https://www.bitmex.com/app/apiOverviewzBhttps://github.com/BitMEX/api-connectors/tree/master/official-httpzhttps://www.bitmex.com/app/feesz*https://www.bitmex.com/app/register/NZTR1qg?)urldiscount)testlogoapiwwwdocfeesreferralr   getannouncement   zannouncement/urgentchatzchat/channelszchat/connectedzchat/pinnedfundingguild
instrumentzinstrument/activezinstrument/activeAndIndiceszinstrument/activeIntervalszinstrument/compositeIndexzinstrument/indiceszinstrument/usdVolume	insuranceleaderboard)liquidationzorderBook/L2z
porl/noncequotezquote/bucketedschemazschema/websocketHelp
settlementstatszstats/historyzstats/historyUSDtradeztrade/bucketedzwallet/assetszwallet/networksaddressapiKey	executionzexecution/tradeHistoryglobalNotificationzleaderboard/nameorderzporl/snapshotspositionuserzuser/affiliateStatuszuser/checkReferralCodezuser/commissionzuser/csazuser/depositAddresszuser/executionHistoryzuser/getWalletTransferAccounts)zuser/marginzuser/quoteFillRatiozuser/quoteValueRatiozuser/stakingzuser/staking/instrumentszuser/staking/tierszuser/tradingVolumeuser/unstakingRequestszuser/walletzuser/walletHistoryzuser/walletSummaryuserAffiliates	userEventzguild/archivez
guild/joinz
guild/kickzguild/leavezguild/sharesTrades   zorder/cancelAllAfterzorder/closePositionzposition/isolatezposition/leveragezposition/riskLimitzposition/transferMarginzuser/addSubaccountzuser/cancelWithdrawal)	zuser/communicationTokenzuser/confirmEmailzuser/confirmWithdrawalzuser/logoutzuser/preferenceszuser/requestWithdrawalr   zuser/updateSubaccountzuser/walletTransfer)r   r   )r   z	order/allr   )r   postputdelete
exceptions)zInvalid API Key.zThis key is disabled.zAccess DeniedzDuplicate clOrdIDzorderQty is invalidzInvalid pricezInvalid stopPx for ordTypezAccount is restricted)zSignature not valid
overloadedz*Account has insufficient Available BalancezService unavailablezServer Error,Unable to cancel order due to existing statez$We require all new traders to verify)exactbroadprecisionModeoptionsbtcethbsctronavaxnearxtzdotsolada)
BTCERC20BEP20TRC20AVAXCNEARXTZDOTSOLADA)api-expiresfetchOHLCVOpenTimestampoldPrecisionnetworksfeatures)lastmark)IOCFOKPOGTD)
marginModetriggerPricetriggerPriceTypetriggerDirectionstopLossPricetakeProfitPriceattachedStopLossTakeProfittimeInForcehedgedtrailingmarketBuyRequiresPricemarketBuyByCost  i@B )r   limitdaysBack	untilDayssymbolRequired)r   triggerr   r  )r   r   r  r   r  )r   r   r   r   r  r   r  )r   r   r   daysBackCanceledr   r  r   r  r   i'  )	r   rM   createOrdersrx   r   r|   r   r[   ry   defaultr   )extendsrM   r  derivatives)linearinverse)r  r>   r  r@   rA   commonCurrenciesUSDTr   ETHr   )USDtXBtXBTGweiGWEILAMPLAMp)deep_extendsuperr-   describer    r!   r&   r)   r%   r   r*   )self	__class__s    W/var/www/html/volatility/venv/lib/python3.11/site-packages/ccxt/async_support/bitmex.pyr  zbitmex.describe   sM   fd 3 3 < < > > SA
(SA
HSA
 $SA
 t	SA

 SA
 SA
 SA
 4SA
  ``` %` 	`
 $` %` T` $U` '` ` "4` '` t` ` $U`   !`" t#` `$ (%`& "4'`( ,T)`* %d+`, T-`. !%/`0 1`2 &u3`4 "55`6 +E7`8 )%9`: #E;`< ,U=`> $T?`@ 'A`B (C`D "4E` ` `F &tG`H (I`J 1%K`L +JM`N *:O`P +DQ`R &uS`T #JU`V *4W`X $TY`Z u[`\ "5]`^ *5_`` +Ea`b tc`d  e`f !$g` ` `h %ei`j $Tk`l /m`n +Eo`p q`r !%s`t &uu`v  w`x dy`z $Z{`| %d}`~ "4`@ uA`B #EC`D dE`F !$G`H tI` ` `J  K`L 'M`N 'O`P !$Q`R (S`T (U`V %eW`X )%Y`Z )$[`\ t]`^ _`` ta`b $Zc`d  e`f !%g`h )%i`j k` `l !%$)',#!!%#(! ` ` `SA
\ 	 ]SA
h :;  j67  0<X :G # ! iSA
R  !&!-q! ! (	!
 )!! &q! "1!  ! %a! ,Q! 6q! 5a! 4Q! -a! /!  $Q!!" &q#!$ ()()&'!"*+"#01&'!")*,-!"*+)*+,A! ! !#J!1 ! $Q 1!	
 -a +A   )! #A  / 1! *1 #A .q  0!" 9!#$ ()/001()45././23'(././*+%&=  @!1   (	
 %a %a &q -a   / .q +A ,Q -a 21  -a!" 0#$ 45-.23'(,-232312/05  : "#!" 
 "#%&23 CF FKl lSSA
l (;-=%5)5+7%12>-=	 	 ,?"6BS+?$1DP<L  mSA
V YWSA
X   !+/ % ""##"      YSA
~ #&*(,$($(- - -1).+06:#'#'"&#(	( ( #($(27+0)$ $6 %)&+!$$(%,*/& & ',#($)*/	# # ',!$#($)*/( ( ',!$$(%,#($)*/$ $ ',!$$(,0%,#($)*/	* 	*  #KH HT  )*#U-$   )*#T-$    "= "= 	  "= "= 	 Ej jSA
T ! !USA
 S S S	    c                   K   |                      |           d{V }i }t          dt          |                    D ]}||         }|                     |d          }|                     |          }|                     |d          }|                     |d          }	|                     |dg           }
d}d}i }|                     |d          }|                     |          }|                     |          }t          dt          |
                    D ]}|
|         }|                     |d          }|                     |          }|                     |d	          }|                     t          j
        ||                    }|                     |d
d          }|                     |dd          }|o|}|rd}|rd}|||||||ddddddddd	||<   |                     |d          }|p|p|}|                     |d          }|                     t          j
        ||                    }|                     |d          }|                     t          j
        ||                    }|                     |d          } |                     t          j
        | |                    }!|                     |d          dk    }"||||	|||d|ddd||d|!ddd||"rdndd||<   |S )a'  
        fetches all available currencies on an exchange

        https://www.bitmex.com/api/explorer/#not /Wallet/Wallet_getAssetsConfig

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        Nr   assetcurrencyr1   r   FscalewithdrawalFeedepositEnabledwithdrawalEnabledTminmax)r   deposit)	infor0   networkactiver%  r   fee	precisionlimitsenabledminWithdrawalAmountmaxWithdrawalAmountminDepositAmountcurrencyTypeCrypto)amountr   r%  cryptoother)r0   coder&  r1   r(  r%  r   r)  r*  r+  r   type)publicGetWalletAssetsrangelensafe_stringsafe_currency_code
safe_valueparse_precisionparse_numbernetwork_id_to_coder+   
string_mul	safe_bool)#r  paramsresponseresultir  r  r5  r0   r1   chainsr   withdrawEnabledr   r  precisionStringr*  jchain	networkIdr'  withdrawalFeeRawr  isDepositEnabledisWithdrawEnabledr(  currencyEnabledcurrencyActiveminWithdrawalStringminWithdrawalmaxWithdrawalStringmaxWithdrawalminDepositString
minDepositisCryptos#                                      r  fetch_currencieszbitmex.fetch_currencies  s      33F;;;;;;;;D q#h--(( Q	 Q	A{H$$Xw77E**511D!!(J77B##Hf55D__Xz2>>F"N#OH$$Xw77E"22599O))/::I1c&kk**    q	 ,,UG<<	11)<<#'#3#3E?#K#K  $ 1 1'2DEUWf2g2g h h#'>>%9I5#Q#Q $(NN5:Mu$U$U!*@/@# *%)N$ +&*O!#&$/ 1(!% $(#'% %
 $(#'$ $	 	% %!!( #ooh	BBO,S1R?N"&"2"28=R"S"S --g.@ATVe.f.fggM"&"2"28=R"S"S --g.@ATVe.f.fggM#//:LMM**7+=>NP_+`+`aaJ''.AAXMH ()+&  $# 
  -,! !
  *#     %$,9'3 F4LL6 r  c                     |                      |          }|                     |d          }|                     |          }t          j        ||          }|                     |          S Nr*  )r  r:  number_to_stringr+   
string_divr>  )r  r5  r2  r  r*  amountStringfinalAmounts          r  convert_from_real_amountzbitmex.convert_from_real_amount2  sa    ==&&$$X{;;	,,V44(yAA  ---r  r5  r2  c                     ||S |d S |                      |          }|                     |d          }t          j        ||          S rZ  )r  r:  r+   r@  )r  r5  r2  r  r*  s        r  convert_to_real_amountzbitmex.convert_to_real_amount9  sO    <M^4==&&$$X{;;	!&)444r  c                 ,   |                      |          }|                     |          }|                     | j        d          }|d         r|s|                     |d         |          }t          t          |                               ||          S )Nr   r>   base)safe_symbolmarketr<  r   r_  r  r-   amount_to_precision)r  symbolr2  re  r   r  s        r  rf  zbitmex.amount_to_precisionB  s    !!&))V$$t|^DD&> 	K, 	K226&>6JJFVT""66vvFFFr  rc  c                    |                      | j        d          r|                     |          S |                     |          }|                     || j                  }|s|                     |          S |                     |          }|d         r/|                     |                     ||         |                    S |                     |          S )Nr   r>   )r<  r   r>  rd  in_arraysymbolsre  ra  )r  rg  rawQuantitycurrencySidemarketExistsre  s         r  convert_from_raw_quantityz bitmex.convert_from_raw_quantityJ  s    ??4<88 	2$$[111!!&))}}VT\:: 	2$$[111V$$&> 	e$$T%@%@AUWb%c%cddd  ---r  c                 0    |                      ||d          S )Nr   )rn  )r  rg  rk  s      r  convert_from_raw_costzbitmex.convert_from_raw_costV  s    --fk7KKKr  c                 f   K   |                      |           d{V }|                     |          S )a)  
        retrieves data on all markets for bitmex

        https://www.bitmex.com/api/explorer/#not /Instrument/Instrument_getActive

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        N)publicGetInstrumentActiveparse_markets)r  rB  rC  s      r  fetch_marketszbitmex.fetch_marketsY  sD       77????????` !!(+++r  re  c                    |                      |d          }|                      |d          }|                      |d          }|                      |d          }|                     |          }|                      |d          }d }d}	d}
d}|dk    rd}d	}	nC|d
k    rd}d	}
n8|dk    rd}d	}n-|dk    r|}|                      |d          }d}d	}n
|dk    rd}d	}	|                     |          }|                     |          }|	p|}d }|                     |d          }|                     |d          }|r| o| nd }|                      |d          }|dk    }d }d }d }|
r	|dz   |z   }n|r|dz   |z   dz   |z   }|r@|                     |dd          }|                     t          j        d|                    }n=t          j        |                      |d                    }|                     |          }|                      |d          }|                     |          }||dz   | 	                    |          z   }n|}|                     |dd          }|                     |          }||k    }| 
                    |d          }|                      |dd          }|                     t          j        d|                    }|
r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 | 
                    |d0          | 
                    |d1          d2|r|                     d          nd |r|nd d3d |rd n|d3d | 
                    |d4          d3d |r|nd d3d5d |d6S )7Nrg  
underlyingquoteCurrencysettlCurrencytypFFFWCSXr@   TIFXXXPr>   FFCCSXrA   FFICSX
rootSymbolFFSCSX	isInverseisQuantostateOpen/:underlyingToPositionMultiplierunderlyingToSettleMultiplier1
multiplierexpiry-positionCurrencymaxOrderQty
initMarginr0   rc  r   settlebaseIdquoteIdsettleIdr6  r?   rB   r(  contractr  takerFeemakerFeeoptionStrikePricelotSizetickSize)r2  pricer"  maxPrice)leverager2  r  cost)r	  quantotakermakercontractSizer  expiryDatetimestrike
optionTyper*  r+  createdr&  )r:  r;  r<  safe_string_2r>  r+   r\  
string_abs	parse8601yymmddsafe_number)r  re  r0   r  r  r  r  ry  r6  r@   r>   rA   rc  r   r  r  r  r  r  statusr(  r  r  rg  multiplierString
positionIdr   positionIsQuoter  r  maxLeverages                                  r  parse_marketzbitmex.parse_market  sI   fh//!!&,77""6?;;##FO<<((22 vu--(??DDDH__DDDH__DFFH__G%%fl;;FDFFH__DD&&v..''00>6OOFK88	??6:665=Gi-0L4!!&'226! 	CZ%'FF 	CZ%'#-6F C#'#5#5f>^`~## #001CCIY1Z1Z[[#*#5d6F6Fv|6\6\#]#] #001ABB!--fh??N^^N33F!#F(;(;; F''0BLQQ
**:66#u,&&v}==%%flC@@
''(:3
(K(KLL 	IHF3
"3
f3
 D3
 U	3

 f3
 f3
 w3
 3
 D3
 D3
 e3
 D3
 f3
 e3
 f3
  !3
" f#3
$ !%%fj99%%fj99(,&&v/BCC**69==))&*==  6>G4,,S1114*2<;; 
  #2C44 
  ++FJ?? 
  *9C;;t  $ e3
 3
 3
 3	
r  c                    d|i}t          dt          |                    D ]}||         }|                     |d          }|                     |          }|                                 }|                     |d          }|                     |d          }	|                     ||          |d<   |                     ||	          |d<   |||<   |                     |          S )Nr&  r   r  availableMarginmarginBalancefreetotal)r8  r9  r:  r;  accountra  safe_balance)
r  rC  rD  rE  balance
currencyIdr5  r  r  r  s
             r  parse_balancezbitmex.parse_balanceP  s    ` )q#h--(( 		# 		#AqkG))':>>J**:66DllnnG##G->??D$$Wo>>E"99$EEGFO#::4GGGG"F4LL  (((r  c                    K   |                                   d{V  ddi}|                     |                     ||                     d{V }|                     |          S )ag  
        query for balance and get the amount of funds available for trading or funds locked in orders

        https://www.bitmex.com/api/explorer/#not /User/User_getMargin

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/?id=balance-structure>`
        Nr  all)load_marketsprivateGetUserMarginextendr  )r  rB  requestrC  s       r  fetch_balancezbitmex.fetch_balance  s       !!!!!!!!!
 224;;w3O3OPPPPPPPP` !!(+++r  Nrg  r   c                   K   |                                   d{V  |                     |          }d|d         i}|||d<   |                     |                     ||                     d{V }|g g dddd}t	          dt          |                    D ]{}||         }	|	d         dk    rd	nd
}
|                     ||                     |	d                    }|                     |	d          }|||
         }|	                    ||g           || 
                    |d
         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://www.bitmex.com/api/explorer/#not /OrderBook/OrderBook_getL2

        :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
        Nrg  r0   depth)rg  bidsasks	timestampdatetimenoncer   sideSellr  r  sizer  T)r  re  publicGetOrderBookL2r  r8  r9  rn  r:  r  appendsort_by)r  rg  r   rB  re  r  rC  rD  rE  r   r  r2  r  
resultSides                 r  fetch_order_bookzbitmex.fetch_order_book  s      !!!!!!!!!V$$fTl
 $GG224;;w3O3OPPPPPPPP
 
 q#h--(( 
	3 
	3AQKE#Fmv5566FD33FD<L<LUTZ<[<[\\F$$UG44E  #D\
!!5&/222fVna>>vfVna88vr  r0   c           	         K   dd|ii}|                      |dd|                     ||                     d{V }t          |          }|dk    r|d         S t          | j        dz   |z   dz             )a  
        fetches information on an order made by the user

        https://www.bitmex.com/api/explorer/#not /Order/Order_getOrders

        :param str id: the 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>`
        filterorderIDNr   r   z: The order z not found.)fetch_ordersr  r9  r'   r0   )r  r0   rg  rB  r  rC  
numResultss          r  fetch_orderzbitmex.fetch_order  s       2

 **64t?O?OPVX^?_?_````````]]
??A;DGn4r9MIJJJr  sincec                   K   |                                   d{V  d}|                     |dd          \  }}|r |                     d||||d           d{V S d}i }| |                     |          }|d         |d<   ||                     |          |d<   |||d	<   |                     |d
d          }|/|                     |d
g          }|                     |          |d<   |                     ||          }d|v r|                     |d                   |d<   | 	                    |           d{V }	| 
                    |	|||          S )av  

        https://www.bitmex.com/api/explorer/#not /Order/Order_getOrders

        fetches information on multiple orders made by the user
        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: the earliest time in ms to fetch orders for
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        NFr   paginater9   r0   rg  	startTimecountuntilendTimer  )r  handle_option_and_paramsfetch_paginated_call_dynamicre  iso8601safe_integer_2omitr  jsonprivateGetOrderparse_orders
r  rg  r  r   rB  r  re  r  r  rC  s
             r  r  zbitmex.fetch_orders  s      !!!!!!!!!88PZ[[& 	m::=&RWY^`fhklllllllll[[((F &tGH#'<<#6#6GK $GG##FGY??YYvy11F!%e!4!4GI""7F33 w $		'(*; < <GH--g66666666  65%@@@r  c           	      v   K   dddii}|                      ||||                     ||                     d{V S )a  
        fetch all unfilled currently open orders

        https://www.bitmex.com/api/explorer/#not /Order/Order_getOrders

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch open orders for
        :param int [limit]: the maximum number of  open orders structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        r  openTN)r  r  )r  rg  r  r   rB  r  s         r  fetch_open_orderszbitmex.fetch_open_orders5  s[       

 &&vueT=M=MgW]=^=^_________r  c                 v   K   |                      ||||           d{V }|                     |dddgd          S )a<  
        fetches information on multiple closed orders made by the user

        https://www.bitmex.com/api/explorer/#not /Order/Order_getOrders

        :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>`
        Nr  closedcanceledF)r  filter_by_array)r  rg  r  r   rB  orderss         r  fetch_closed_orderszbitmex.fetch_closed_ordersH  sR       ((vFFFFFFFF##FHx6LeTTTr  c                   K   |                                   d{V  d}|                     |dd          \  }}|r |                     d||||d           d{V S d}i }| |                     |          }|d         |d<   ||                     |          |d<   |t          d	|          |d
<   |                     |dd          }|/|                     |dg          }|                     |          |d<   |                     ||          }d|v r| 	                    |d                   |d<   | 
                    |           d{V }	|                     |	|||          S )a  
        fetch all trades made by the user

        https://www.bitmex.com/api/explorer/#not /Execution/Execution_getTradeHistory

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/?id=trade-structure>`
        NFrx   r  r9   r0   rg  r  r   r  r  r  r  )r  r  r  re  r  r#  r  r  r  r  privateGetExecutionTradeHistoryparse_tradesr  s
             r  fetch_my_tradeszbitmex.fetch_my_tradesX  s      !!!!!!!!!88R\]]& 	o::?FTY[`bhjmnnnnnnnnn[[((F &tGH#'<<#6#6GK "3GG##FGY??YYvy11F!%e!4!4GI""7F33 w $		'(*; < <GH==gFFFFFFFFl   65%@@@r  c                 D    dddddddd}|                      |||          S )Ntransactionr?   r   r   r   )
WithdrawalRealisedPNLUnrealisedPNLDepositTransferAffiliatePayout	SpotTrader:  )r  r6  typess      r  parse_ledger_entry_typezbitmex.parse_ledger_entry_type  s=    '#%$") 
 
 tT222r  itemr  c                 2   |                      |d          }|                      |d          }|                      |d          }d }|                     |                      |d                    }|                      |d          }|                     ||          }	|                     ||          }|                      |d          }
|                     |	|
          }|                     |                      |d                    }|d}d }|                      |d	          }|.|                     |	|          }|                     |          |	d
}|                      |d          }||                     |	|          }|                     t          j        | 	                    |          | 	                    |                              }d }t          j
        |
d          r+d}|                     |	t          j        |
                    }nd}|                     |                      |d                    }|                     ||||                     |          ||||||	|                     |          ||                     |          ||d|          S )N
transactIDr  txtransactTyper  r2  transactTimer   r)  )r  r  walletBalance0outintransactStatus)r&  r0   r  r  	directionr  referenceIdreferenceAccountr6  r  r2  beforeafterr  r)  )r:  r  r;  safe_currencyra  r  r>  r+   
string_subr[  	string_ltr  parse_transaction_statussafe_ledger_entryr  )r  r  r  r0   r  r  r  r6  r  r5  r]  r2  r  r)  feeCostr  r  r
  r  s                      r  parse_ledger_entryzbitmex.parse_ledger_entry  s   T dL11""433&&tT22++D,<,<T>,R,RSS%%dJ77
&&z8<<%%j(;;''h77,,T<@@NN4#3#3D.#I#IJJ	 I""4//11$@@G))'22  C   77//e<<E""7#5d6K6KE6R6RTXTiTijpTqTq#r#rss	\3// 	I00w7I,7W7WXXFFI..t/?/?FV/W/WXX%%"Y//"& 0''//&&u--'
 '
  !  	r  c                 "  K   |                                   d{V  i }|||d<   d}| |                     |          }|d         |d<   |                     |                     ||                     d{V }|                     ||||          S )an  
        fetch the history of changes, actions done by the user or operations that altered the balance of the user

        https://www.bitmex.com/api/explorer/#not /User/User_getWalletHistory

        :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-entry-structure>`
        Nr  r0   r  )r  r  privateGetUserWalletHistoryr  parse_ledger)r  r5  r  r   rB  r  r  rC  s           r  fetch_ledgerzbitmex.fetch_ledger   s       !!!!!!!!!
 $GG}}T**H"*4.GJ99$++gv:V:VWWWWWWWW*   8UEBBBr  c                 Z  K   |                                   d{V  ddi}d}| |                     |          }|d         |d<   |||d<   |                     |                     ||                     d{V }|                     |dddgd	          }|                     ||||          S )
aq  
        fetch history of deposits and withdrawals

        https://www.bitmex.com/api/explorer/#not /User/User_getWalletHistory

        :param str [code]: unified currency code for the currency of the deposit/withdrawals, default is None
        :param int [since]: timestamp in ms of the earliest deposit/withdrawal, default is None
        :param int [limit]: max number of deposit/withdrawals to return, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a list of `transaction structure <https://docs.ccxt.com/?id=transaction-structure>`
        Nr  r  r0   r  r  r  r  F)r  r  r  r  r  parse_transactions)	r  r5  r  r   rB  r  r  rC  transactionss	            r  fetch_deposits_withdrawalsz!bitmex.fetch_deposits_withdrawalsR  s       !!!!!!!!!
 }}T**H"*4.GJ$GG99$++gv:V:VWWWWWWWW++Hn|U^F_afgg&&|XueLLLr  r  c                 >    ddddd}|                      |||          S )Npendingr  ok)	ConfirmedCanceled	CompletedPendingr  r  r  statusess      r  r  zbitmex.parse_transaction_statusr  s4    "" 	
 
 &&999r  r  c                    |                      |d          }|                     ||          }|                     |                      |d                    }|                     |                      |d                    }|                     |d          }d }d }d }	|dk    r/|                      |d          }|                      |d          }|}	n2|dk    r,|                      |d          }	|                      |d          }|                      |d	          }
t	          j        |
          }|                     |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S )Nr  r  r  r  
withdrawalr   r  r%  r2  r5  r)  r	  r&  r0   r  txidr6  r'  r  r  addressFrom	addressTotagtagFromtagToupdated)r  r  rate)internalcommentr)  )r:  r  r  safe_string_lowerr+   r  ra  r  r?  r>  r  )r  r  r  r  r  r  r6  r   r*  r+  r]  amountStringAbsr2  feeCostStringr  r  s                   r  parse_transactionzbitmex.parse_transaction{  s   ( %%k:>>
%%j(;; ~~d&6&6{N&S&STTNN4#3#3K#M#MNN	%%k>BB	<&&{I>>G**;==KIIY((i@@I**;==K''X>>!,\::,,Xf-=OO((e<<--hv.>NN!!+/?@@226::F
K
$"";==
 D$$[$77
 D	

 (
 t..t/?/?Y/W/WYabhYijj
 d''//
 f
 
 \22
 w
 ;
 
 4
 t
  T!
" y#
$ $V,))'22 )
 
 
 	
r  c                 l  K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     |d          }|t          | j        dz   |z   dz             |                     ||          S )a  
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://www.bitmex.com/api/explorer/#not /Instrument/Instrument_get

        :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>`
        Nrg  r0   r   z fetchTicker() symbol z
 not found)r  re  publicGetInstrumentr  r<  r$   r0   parse_ticker)r  rg  rB  re  r  rC  tickers          r  fetch_tickerzbitmex.fetch_ticker  s       !!!!!!!!!V$$fTl
 11$++gv2N2NOOOOOOOO1-->DG&>>G,VWWW  000r  rj  c                 |  K   |                                   d{V  |                     |          }|                     |           d{V }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

        https://www.bitmex.com/api/explorer/#not /Instrument/Instrument_getActiveAndIndices

        :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   rg  )r  market_symbols#publicGetInstrumentActiveAndIndicesr8  r9  r9  r:  filter_by_array_tickers)r  rj  rB  rC  rD  rE  r:  rg  s           r  fetch_tickerszbitmex.fetch_tickers  s       !!!!!!!!!%%g..AA&IIIIIIIIq#h--(( 	( 	(A&&x{33F%%fh77F!!'v++FHgFFFr  r:  c           	      
   |                      |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|          S )Nrg  r  prevPrice24h	lastPricer  high	highPricelowlowPricebidbidPrice	bidVolumeaskaskPrice	askVolumevwapr  closer   previousClosechange
percentageaveragehomeNotional24hforeignNotional24h	markPrice)
baseVolumequoteVolumerV  r&  )r:  rd  r  safe_tickerr  )r  r:  re  marketIdrg  r  r  r   s           r  r9  zbitmex.parse_ticker  s   ##FH55!!(F33NN4#3#3FK#H#HII	7744 !
f!
!
 Y//!
 D$$V[99	!

 4##FJ77!
 4##FJ77!
 !
 4##FJ77!
 !
 D$$VV44!
 D!
 T!
 D!
 T!
 d!
  $!!
" t#!
$ **63DEE++F4HII))&+>>+!
 !
 !
, -  	r  c                    |                      |d          }|                     ||          }|                     |d         |                      |d                    }|                     |                      |d                    |                     |d          |                     |d          |                     |d          |                     |d          |gS )Nrg  volumer  r  rD  rF  rO  )r:  safe_marketrn  r  r  )r  ohlcvre  rZ  r\  s        r  parse_ohlcvzbitmex.parse_ohlcv  s    $ ##E844!!(F33//x0@$BRBRSXZbBcBcddNN4++E;??@@UF++UF++UE**UG,,
 	
r  r   	timeframec                   K   |                                   d{V  d}|                     |dd          \  }}|r |                     d|||||           d{V S |                     |          }|d         |                     | j        ||          dd}|||d<   |                     |d	          }	|	/|                     |d	g          }|                     |	          |d
<   | 	                    |          dz  }
| 
                    | j        dd          }|5|}|r|                     ||
          }|                     |          }||d<   nd|d<   |                     |                     ||                     d{V }|                     |||||          }|r:t!          dt#          |                    D ]}||         d         |
z
  ||         d<   |S )a  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://www.bitmex.com/api/explorer/#not /Trade/Trade_getBucketed

        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param int [since]: timestamp in ms of the earliest candle to fetch
        :param int [limit]: the maximum amount of candles to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        NFry   r  r0   T)rg  binSizepartialr  r  r    r   r  reverser   )r  r  "fetch_paginated_call_deterministicre  r:  r   safe_integerr  r  parse_timeframerA  r   sumpublicGetTradeBucketedr  parse_ohlcvsr8  r9  )r  rg  r`  r  r   rB  r  re  r  r  durationr   r  r  rC  rD  rE  s                    r  fetch_ohlcvzbitmex.fetch_ohlcv,  s<      !!!!!!!!!88zZZ& 	x@@vW\^cenpvwwwwwwwww V$$Tl''INN	
 	
 $GG!!&'22YYvy11F!%e!4!4GI''	22T9"&..?XZ^"_"_I& : HHY99	Y//I#,GK  !%GI44T[[&5Q5QRRRRRRRR ""8VYuMM" 	7 1c&kk** 7 7%ay|h6q	!r  r   c                 h   |                      |d          }|                     ||          }|                     |                      |d                    }|                     |dd          }|                     ||                     |dd                    }|                     |                     ||                      |d                              }|                      |d          }	|                      |d	          }
|                     |d
          }d }|                     |                     ||                      |d                              }|D|                     |dd          }||                     |          |                      |d          d}|                      |d          }d }||dk    rt          j
        |d          rdnd}|                     |d          }|                     |||                     |          ||	|
||||t          j        |          ||d|          S )Nrg  r  avgPxr  r  lastQtyexecCost
trdMatchIDr  r  execCommrx  r  
commission)r  r  r0  execTyper   r  r  r  ordType)r&  r  r  rg  r0   r   r6  takerOrMakerr  r  r  r2  r)  )r:  rd  r  r  rn  r[  rp  r3  r;  r+   r  
safe_trader  r  )r  r   re  rZ  rg  r  priceStringr]  rq  r0   r   r  r)  r5  r  ru  rw  r6  s                     r  parse_tradezbitmex.parse_trader  sP   J ##E844!!(F33NN4#3#3E;#G#GHH	((AA55fd>P>PQVX^`i>j>jkk(()C)CFDL\L\]bdnLoLo)p)pqqe\22  	22%%eV44--d.H.HQUQaQabgisQtQt.u.uvv$++E?JOOJ% 33J??((== C ##E:66$W)<)<&-&7s&K&KX77QXL%%eY77"Y//( &x00" 
  
   	r  c                 N    ddddddddddddd}|                      |||          S )Nr  r  r  rejectedexpired)NewPartiallyFilledFilled
DoneForDayr"  PendingCancel
PendingNewRejectedExpiredStoppedUntriggered	Triggeredr  r%  s      r  parse_order_statuszbitmex.parse_order_status  sL    % "# " !
 
 &&999r  r   c                 >    ddddd}|                      |||          S )NDayGTCr   r   )r  GoodTillCancelImmediateOrCancel
FillOrKillr  )r  r   timeInForcess      r  parse_time_in_forcezbitmex.parse_time_in_force  s4    #!&	
 
 k;GGGr  r   c                    |                      |d          }|                     ||          }|d         }|                      |d          }d }d }d}|#|                      | j        dd          }	|	dk    }n|                     |dd          }|r|                     ||          }n|                     ||          }|                      |d          }
d }|                     |                     ||                      |d                              }|rt          j        ||
          }n|}|                      |d	d
          }d }d }t          |          dk    rK|	                    d          dk    }|	                    d          dk    p|	                    d          dk    }| 
                    |                      |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&|          S )'Nrg  orderQtyFdefaultSubTyper  r	  ro  cumQtyexecInst r   ParticipateDoNotInitiate
ReduceOnlyCloser  stopPx	leavesQtyr&  r0   r  clientOrderIdclOrdIDr  lastTradeTimestampr  r6  rv  r   postOnly
reduceOnlyr  r  r   r2  r  rS  	ordStatus)filled	remainingr  r)  trades)r:  r]  r   rA  rn  r[  r+   r\  r9  findr  r  
safe_orderr  r3  r  r  )r  r   re  rZ  rg  qtyr  r2  r  r  rS  r  r  r  r  r  r  r   r  s                      r  parse_orderzbitmex.parse_order  s   L ##E844!!(F33!uj11	!--dl<LhWWN'94IIvy%@@I 	A11&#>>DD33FC@@F""5'22&&t'E'EfdN^N^_dfnNoNo'p'pqq 	'88FFF##E:r::
x==1 &@AAQFH#==66!;]wAWAW[\A\JNN4#3#3E;#G#GHH	''x88$$UK88	  
E 
$""5)44 
 T--eY?? 
 	 

 Y// 
 !$..1A1A%1X1X"Y"Y 
 f 
 D**5)<< 
 433D4D4DUM4Z4Z[[ 
  
 * 
 D**5&99 
 T%%eW55 
 L 
 f 
  D! 
" w# 
$ 77	JJ--d.>.>uk.R.RSS- 
  
  
. /  	r  c                 z  K   |                                   d{V  d}|                     |dd          \  }}|r|                     d||||           d{V S |                     |          }d|d         i}||                     |          |d<   nd|d	<   |t          |d
          |d<   |                     |dd          }|/|                     |dg          }|                     |          |d<   |                     | 	                    ||                     d{V }	| 
                    |	|||          S )a  
        get the list of most recent trades for a particular symbol

        https://www.bitmex.com/api/explorer/#not /Trade/Trade_get

        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/?id=public-trades>`
        NFr   r  rg  r0   r  Tre  rd  r  r  r  )r  r  r  re  r  r#  r  r  publicGetTrader  r  r  s
             r  fetch_tradeszbitmex.fetch_tradesY  s      !!!!!!!!!88PZ[[& 	h::=&RWY^`fgggggggggV$$fTl
 #'<<#6#6GK   "&GI"5$//GG##FGY??YYvy11F!%e!4!4GI,,T[[&-I-IJJJJJJJJ:   65%@@@r  r6  r  r  c                 X  K   |                                   d{V  |                     |          }|                     |          }|                     |d          }	|	3|d         s+|d         s#t	          | j        dz   |d         z   dz             |                     |d          }
|                     |ddg          }|                     | j	        d	d
          }| 
                    |                     ||                    }|d         |                     |          |||d}g }|	du r|                    d           |
du r|                    d           t          |          }|dk    rd                    |          |d<   |                     |g d          }|                     |dd          }|du}|du}|s|r0|                     |d          }|dk    p|dk    }|dk    s|dk    r|                     d|dddg           |dk    r|dk    r|rdnd}n |rdnd}n|dk    r|dk    r|rd nd!}n|rd!nd }|rK|d"k    o|d k    p|dk    }|dk    o|d!k    p|dk    }|s|rd#|z   }|                     |          |d<   d$|d%<   nK|t'          | j        d&z   |z   d'z             |                     |                     ||                    |d(<   ||d)<   |                     |g d*          }|d+k    s|dk    s|dk    r,|                     |                     ||                    |d,<   |                     |d-d.          }|||d-<   |                     |d-d.g          }|                     |                     ||                     d{V }|                     ||          S )/a  
        create a trade order

        https://www.bitmex.com/api/explorer/#not /Order/Order_new

        :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 dict [params.triggerPrice]: the price at which a trigger order is triggered at
        :param dict [params.triggerDirection]: the direction whenever the trigger happens with relation to price - 'ascending' or 'descending'
        :param float [params.trailingAmount]: the quote amount to trail away from the current market price
        :returns dict: an `order structure <https://github.com/ccxt/ccxt/wiki/Manual#order-structure>`
        Nr  r@   rA   z/ createOrder() does not support reduceOnly for r6  zI orders, reduceOnly orders are supported for swap and future markets onlyr  brokerIdCCXTr0   )rg  r  r  rv  textTr  r  r   ,r  )r   r  	stopPricetrailingAmountpegOffsetValuer   	ascendingabover   re  rM   belowbuy	StopLimitLimitIfTouchedStopMarketIfTouchedsellr  TrailingStopPegpegPriceTypez9 createOrder() requires a triggerPrice parameter for the z order typer  rv  )r   r  r  r   r  Limitr  r  r  )r  re  
capitalizer<  r&   r0   rA  r  r:  r   parse_to_intrf  r  r9  joinsafe_number_nr  check_required_argumentparse_to_numericr"   price_to_precisionprivatePostOrderr  r  )r  rg  r6  r  r2  r  rB  re  	orderTyper  r  r  r  r  execInstructionsexecInstLengthr   r  isTriggerOrderisTrailingAmountOrderr   triggerAboveisStopSellOrderisBuyIfTouchedOrderr  rC  s                             r  create_orderzbitmex.create_order  s     " !!!!!!!!!V$$OOD))	__V\::
!6N VH-= "47-^#^aghnao#o  s~  $~      >>&*556L*#=>>##DL*fEE 8 8 H HIITlOOD)) 
 
 ##L111t##$>???-..A"%((+;"<"<GJ))&2Y2Y2YZZ++F4DFVWW%T1 .d : 	v2 	v#//8JKK-<^BRV]B]LTX%5%5,,]<LN`cjlsbtuuuw5==/; QAQII4@ Q 0 0kII!!5==*6 M<MII5A M 1 1vI$ i#'6>"lf9L8kR[_jRj'+u}&IIZ<Z;~`im}`}#" :&9 :%(>%9N,0,A,A.,Q,Q()*;'''+DG6q,qt},}  AN  -N  O  O  O$($9$9$:Q:QRXZf:g:g$h$h!!*GIYYv't't'tuuF  i;&>&>IQaDaDa#44T5L5LVUZ5[5[\\GG**69oNN$!.GIYYv	?'CDDF..t{{7F/K/KLLLLLLLL&111r  c                   K   |                                   d {V  i }|                     |dd          }	|	d u}
|
r|                     |d          }|dk    p|dk    }|dk    s|dk    r|                     d|ddd	g           d }|dk    r|d
k    r|rdnd}n |rdnd}n|dk    r|d
k    r|rdnd}n|rdnd}|dk    o|dk    p|dk    }|d
k    o|dk    p|dk    }|s|rd|	z   }	|                     |	          |d<   |                     |ddg          }|                     |dd          }|<||d<   |                     |dd          }|||d<   |                     |g d          }n||d<   |.|                     |                     ||                    }||d<   |||d<   |                     | j        dd          }||d<   | 	                    | 
                    ||                     d {V }|                     |          S )Nr  r  r   r  r  r   re  rM   r  r  r  r  r  r  r  r  origClOrdIDr  r  )r  r  r  r  r  r  r  r  r  )r  r  r:  r  r  r  r  rf  r   privatePutOrderr  r  )r  r0   rg  r6  r  r2  r  rB  r  r  r  r   r  r  r  r  r  r  r  r  rC  s                        r  
edit_orderzbitmex.edit_order  s     !!!!!!!!!++F4DFVWW .d :  	O#//8JKK-<^BRV]B]LTX%5%5,,]<LN`cjlsbtuuuIw5==/; QAQII4@ Q 0 0kII!!5==*6 M<MII5A M 1 1vI#v~hY&5H4gi[fNfO#'5="{	EV8V7z\eiy\y 6"5 6!$~!5(,(=(=n(M(MG$%YYv(:<L'MNNF((PP"%0GM" ,,VYPPM(%2	"YYv'R'R'RSSFF!#GI##D$<$<VV$L$LMMC"%GJ$GG##DL*fEE"--dkk'6.J.JKKKKKKKK)))r  c                   K   |                                   d{V  |                     |dd          }i }|||d<   n||d<   |                     |ddg          }|                     |                     ||                     d{V }|                     |di           }|                     |d          }|3|                    d          dk    rt          | j	        dz   |z             | 
                    |          S )	aw  
        cancels an open order

        https://www.bitmex.com/api/explorer/#not /Order/Order_cancel

        :param str id: order id
        :param str symbol: not used by bitmex cancelOrder()
        :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   errorr   z cancelOrder() failed: )r  safe_value_2r  privateDeleteOrderr  r<  r:  r  r'   r0   r  )	r  r0   rg  rB  r  r  rC  r   r  s	            r  cancel_orderzbitmex.cancel_order  s'      !!!!!!!!!))&)_MM !#GI!.GIYYv	?'CDDF00Wf1M1MNNNNNNNN!R00  00zzHIIQNN#DG.G$G%$OPPP&&&r  idsc                 >  K   |                                   d{V  |                     |dd          }i }|||d<   n||d<   |                     |ddg          }|                     |                     ||                     d{V }|                     |          S )a  
        cancel multiple orders

        https://www.bitmex.com/api/explorer/#not /Order/Order_cancel

        :param str[] ids: order ids
        :param str symbol: not used by bitmex cancelOrders()
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        Nr  r  r  )r  r  r  r  r  r  )r  r  rg  rB  r  r  rC  s          r  cancel_orderszbitmex.cancel_orders9  s       !!!!!!!!!))&)_MM !$GI!.GIYYv	?'CDDF00Wf1M1MNNNNNNNN  ***r  c                   K   |                                   d{V  i }d}| |                     |          }|d         |d<   |                     |                     ||                     d{V }|                     ||          S )a  
        cancel all open orders

        https://www.bitmex.com/api/explorer/#not /Order/Order_cancelAll

        :param str symbol: unified market symbol, only orders in the market of self symbol are cancelled when symbol is not None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        Nr0   rg  )r  re  privateDeleteOrderAllr  r  )r  rg  rB  r  re  rC  s         r  cancel_all_orderszbitmex.cancel_all_ordersQ  s       !!!!!!!!![[((F &tGH33DKK4P4PQQQQQQQQP   6222r  timeoutc                    K   |                                   d{V  d|dk    r|                     |dz            ndi}|                     |                     ||                     d{V }|S )ak  
        dead man's switch, cancel all orders after the given timeout

        https://www.bitmex.com/api/explorer/#not /Order/Order_cancelAllAfter

        :param number timeout: time in milliseconds, 0 represents cancel the timer
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: the api result
        Nr  r   rd  )r  r  privatePostOrderCancelAllAfterr  )r  r  rB  r  rC  s        r  cancel_all_orders_afterzbitmex.cancel_all_orders_after  s       !!!!!!!!!Wq[[t((4888q
 <<T[[RX=Y=YZZZZZZZZ r  c                    K   |                                   d{V  |                     ||           d{V }|                     ||d          S )a  
        fetch the set leverage for all contract markets

        https://www.bitmex.com/api/explorer/#not /Position/Position_get

        :param str[] [symbols]: a list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a list of `leverage structures <https://docs.ccxt.com/?id=leverage-structure>`
        Nrg  )r  fetch_positionsparse_leverages)r  rj  rB  	leveragess       r  fetch_leverageszbitmex.fetch_leverages  sk       !!!!!!!!!..w????????	##IwAAAr  r  c                     |                      |d          }||                     ||          |                     |d          |                     |d          |                     |d          dS )Nrg  r   r  )r&  rg  r   longLeverageshortLeverage)r:  rd  r3  rg  )r  r  re  rZ  s       r  parse_leveragezbitmex.parse_leverage  su    ##Hh77&&x8800<HH --h
CC!..xDD
 
 	
r  c                    K   |                                   d{V  |                     |           d{V }|                     ||          }|                     |d|d          S )ar  
        fetch all open positions

        https://www.bitmex.com/api/explorer/#not /Position/Position_get

        :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>`
        Nrg  F)r  privateGetPositionparse_positionsfilter_by_array_positions)r  rj  rB  rC  resultss        r  r  zbitmex.fetch_positions  s       !!!!!!!!!0088888888D &&x99--gx%PPPr  r   c                 J   |                      |                     |d          |          }|d         }|                     |d          }|                     |d          }|du rdnd}t          j        |                     |dd                    }|                     |d	          }|                     ||                     |d
                    }	|                     ||                     |d                    }
|                     t          j        |                     |d                              }|                     |d          }d }|                     |d          }||d         dk    rd}n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'
          S )(Nrg  r  crossMarginTcrossisolatedforeignNotionalhomeNotionalr  maintMarginunrealisedPnl
currentQtyr  r   r  shortlongr&  r0   r  r  lastUpdateTimestampr   r  	contracts
entryPriceavgEntryPricerV  rC  notionalr  
collateralinitialMarginr  initMarginReqmaintMarginReqliquidationPriceunrealisedPnlPcnt)
initialMarginPercentagemaintenanceMarginmaintenanceMarginPercentageunrealizedPnlr  r   marginRatiorR  r   r   )r]  r:  r<  r+   r  r  ra  r>  r  safe_positionr  )r  r   re  rg  r  r  r   notionalStringsettleCurrencyCoder
  r  r  r  r  r  s                  r  parse_positionzbitmex.parse_position*	  s:   @ !!$"2"28X"F"FOO!##Hk::ooh>>!,!4!4WW:
 +D,>,>xIZ\j,k,kll!--fh?? 778JDL\L\]egtLuLuvv334FHXHXYacrHsHstt%%g&89I9I(T`9a9a&b&bcc	''??''.AA#A#%%!! #
H#
$""8Y77#
 f#
 11	#

 #
 "4#
 d#
 D#
 #
 L#
 $**8_EE#
 ))(K@@#
 #
 )).99#
 ((:>>#
  $!#
" T--hEE##
$ (,'7'7/'R'R!2+/+;+;HFV+W+W* $ 0 0;M N N$**85HII!#7#
 #
 #
   	r  r   r,  c                 @  K   |                      ||          \  }}|                     |           |                                  d{V  |                     |          }|                     ||          }d}|                     |          \  }}|d         |||                     ||d                   d}	| j        |                     | j                  |	d<   | 	                    | 
                    |	|                     d{V }
|                     |
|          S )a  
        make a withdrawal

        https://www.bitmex.com/api/explorer/#not /User/User_requestWithdrawal

        :param str code: unified currency code
        :param float amount: the amount to withdraw
        :param str address: the address to withdraw to
        :param str tag:
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `transaction structure <https://docs.ccxt.com/?id=transaction-structure>`
        Nr0   r5  )r  r2  r   r'  otpToken)handle_withdraw_tag_and_paramscheck_addressr  r  r_  handle_network_code_and_paramsnetwork_code_to_idtwofatotp privatePostUserRequestWithdrawalr  r6  )r  r5  r2  r   r,  rB  r  r  networkCoder  rC  s              r  r   zbitmex.withdraw	  s;      99#vFFV7###!!!!!!!!!==&&++D&99"AA&IIV ..{HV<LMM	
 
 :!"&))DJ"7"7GJ>>t{{7TZ?[?[\\\\\\\\$ %%h999r  c                   K   |                                   d{V  |                     |           d{V }g }t          dt          |                    D ]c}||         }|                     |d          }|                     |          }|                     |dd          }	|	r|                    |           d|                     |          }| 	                    |          }
| 
                    |
d|          S )a  
        fetch the funding rate for multiple markets

        https://www.bitmex.com/api/explorer/#not /Instrument/Instrument_getActiveAndIndices

        :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
        Nr   rg  r@   F)r  r>  r8  r9  r:  r]  rA  r  r=  parse_funding_ratesr  )r  rj  rB  rC  filteredResponserE  r  rZ  re  r@   rD  s              r  fetch_funding_rateszbitmex.fetch_funding_rates	  s      !!!!!!!!!AA&IIIIIIIIq#h--(( 	. 	.AA;D''h77H%%h//F>>&&%88D . ''---%%g..))*:;;##FHg>>>r  c                    |                      |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 iS )Nr  rg  fundingTimestampr&  rV  
indexPriceinterestRateestimatedSettlePriceindicativeSettlePricer  fundingRatefundingDatetimenextFundingRateindicativeFundingRatenextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetimeintervalr:  rd  r  r  )r  r  re  r  rZ  r'  s         r  parse_funding_ratezbitmex.parse_funding_rate
  s   ##Hk::##Hh77**85GHH
H
d&&x88
 ))(K@@
 $	

 D
 #D$4$4X?V$W$W
 11
 
 4++HmDD
  ? ?
 
 t//:QRR
 #D
 "4
 "4
  '!
" &t#
$ %
 
 	
r  c                 H  K   |                                   d{V  i }d}|| j        v r!|                     |          }|d         |d<   n||                    d          }t	          |          }	g d}
|	dk    rQ|                     |d         |
          r5|                     |d                   }|d         dz   |d         z   }||d<   n |                     |          }|d         |d<   ||                     |          |d<   |||d	<   |                     |d
          }| 	                    |d
g          }||                     |          |d<   ||d|d<   | 
                    |                     ||                     d{V }|                     ||||          S )a  
        Fetches the history of funding rates

        https://www.bitmex.com/api/explorer/#not /Funding/Funding_get

        :param str symbol: unified symbol of the market to fetch the funding rate history for
        :param int [since]: timestamp in ms of the earliest funding rate to fetch
        :param int [limit]: the maximum amount of `funding rate structures <https://docs.ccxt.com/?id=funding-rate-history-structure>` to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms for ending date filter
        :param bool [params.reverse]: if True, will sort results newest first
        :param int [params.start]: starting point for results
        :param str [params.columns]: array of column names to fetch in info, if omitted, will return all columns
        :param str [params.filter]: generic table filter, send json key/value pairs, such as {"key": "value"}, you can key on individual fields, and do more advanced querying on timestamps, see the `timestamp docs <https://www.bitmex.com/app/restAPI#Timestamp-Filters>` for more details
        :returns dict[]: a list of `funding rate structures <https://docs.ccxt.com/?id=funding-rate-history-structure>`
        Nr0   rg  r  )nearestdailyweeklymonthly	quarterlybiquarterly	perpetualr   r   r  r  r  r  Tre  )r  
currenciesr  splitr9  ri  re  r  rg  r  publicGetFundingr  parse_funding_rate_histories)r  rg  r  r   rB  r  re  r5  splitSymbolsplitSymbolLengthr   r  rC  s                r  fetch_funding_rate_historyz!bitmex.fetch_funding_rate_history
  s     " !!!!!!!!!T_$$==((D $T
GH ,,s++K #K 0 0kkkJ!A%%4==Q+T+T%}}[^44dc)KN:$*!!V,,$*4L!#'<<#6#6GK $GG!!&'226G9--!%e!4!4GIM!%GI..t{{7F/K/KLLLLLLLL 0065%PPPr  c                     |                      |d          }|                      |d          }||                     ||          |                     |d          |                     |          |dS )Nrg  r  r&  )r&  rg  r&  r  r  r0  r  r&  re  rZ  r  s        r  parse_funding_rate_historyz!bitmex.parse_funding_rate_historyY
  sx     ##D(33##D+66&&x88++D-@@11 
 
 	
r  c                   K   |t          | j        dz             |dk     s|dk    rt          | j        dz             |                                  d{V  |                     |          }|d         dk    r#|d         dk    rt          | j        d	z             |d
         |d}|                     |                     ||                     d{V S )ay  
        set the level of leverage for a market

        https://www.bitmex.com/api/explorer/#not /Position/Position_updateLeverage

        :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 argumentg{Gz?r9   z( leverage should be between 0.01 and 100r6  r@   rA   z6 setLeverage() supports future and swap contracts onlyr0   )rg  r  )r"   r0   r#   r  re  r$   privatePostPositionLeverager  )r  r  rg  rB  re  r  s         r  set_leveragezbitmex.set_leveragem
  s       >#DG.Y$YZZZtOOCTW'QQRRR!!!!!!!!!V$$&>V##v((B(BDG&^^___Tl 
 
 55dkk'66R6RSSSSSSSSSr  r   c                   K   |t          | j        dz             |                                }|dk    r|dk    rt          | j        dz             |                                  d{V  |                     |          }|d         dk    r#|d         dk    rt          | j        d	z             |dk    rd
nd}|d         |d}|                     |                     ||                     d{V S )a{  
        set margin mode to 'cross' or 'isolated'

        https://www.bitmex.com/api/explorer/#not /Position/Position_isolateMargin

        :param str marginMode: 'cross' or 'isolated'
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: response from the exchange
        Nz+ setMarginMode() requires a symbol argumentr  r  z@ setMarginMode() marginMode argument should be isolated or crossr6  r@   rA   z8 setMarginMode() supports swap and future contracts onlyFTr0   )rg  r,  )	r"   r0   lowerr#   r  re  r$   privatePostPositionIsolater  )r  r   rg  rB  re  r,  r  s          r  set_margin_modezbitmex.set_margin_mode
  s&      >#DG.[$[\\\%%''
##
g(=(=TW'iijjj!!!!!!!!!V$$6Nf$$6&>X+E+EDG&``aaa&'11%%Tl
 
 44T[[&5Q5QRRRRRRRRRr  c                   K   |                                   d{V  d}|                     |          \  }}|t          | j        dz             |                     |          }|                     |d          }|d         |                     ||d                   d}|                     |                     ||                     d{V }||||	                    dd          	                    dd          dd	S )
aG  
        fetch the deposit address for a currency associated with self account

        https://www.bitmex.com/api/explorer/#not /User/User_getDepositAddress

        :param str code: unified currency code
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.network]: deposit chain, can view all chains via self.publicGetWalletAssets, default is eth, unless the currency has a default chain within self.options['networks']
        :returns dict: an `address structure <https://docs.ccxt.com/?id=address-structure>`
        Nz/ fetchDepositAddress requires params["network"]r'  r0   r5  )r  r'  "r  )r&  r  r'  r   r,  )
r  r  r"   r0   r  r  r  privateGetUserDepositAddressr  replace)r  r5  rB  r  r  r  rC  s          r  fetch_deposit_addresszbitmex.fetch_deposit_address
  s*      !!!!!!!!!"AA&IIV#DG._$_```==&&69-- ..{HV<LMM
 
 ::4;;wPV;W;WXXXXXXXX
 "''R0088bAA
 
 	
r  c                 d   |                      |dg           }t          |          }|d d dd d di d}|dk    r|                     |d          }|                     |          }t	          d|          D ]}||         }	|                     |	d          }
|                     |d          }|                     |
|          }|                     |	d          }|                     t          j        ||                    }d d d|d	dd
|d         |<   |dk    r||d         d<   d	|d         d<   |S )Nr   )r)  rR  )r&  r   r%  r   r   r  r  r5  r  F)r%  r   r   r   r)  rR  )	r<  r9  r:  r=  r8  r?  r>  r+   r@  )r  r)  r  r   networksLengthrD  r  r*  rE  r'  rK  currencyCoder  withdrawalFeeIdr  s                  r  parse_deposit_withdraw_feez!bitmex.parse_deposit_withdraw_fee
  s   6 ??3
B77X" 
 "  
 
 Q$$S'22E,,U33I1n-- = ="1+ ,,Wg>>	#//&AA"55iNN"&"2"27O"L"L $ 1 1'2D_V_2`2` a a'+4@@(5U K K3 3z";/ "Q&&0=F:&u-7<F:&|4r  codesc                    K   |                                   d{V  |                     |           d{V }|                     ||d          S )at  
        fetch deposit and withdraw fees

        https://www.bitmex.com/api/explorer/#not /Wallet/Wallet_getAssetsConfig

        :param str[]|None codes: list of unified currency codes
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a list of `fee structures <https://docs.ccxt.com/?id=fee-structure>`
        Nr  )r  r7  parse_deposit_withdraw_fees)r  rU  rB  assetss       r  fetch_deposit_withdraw_feesz"bitmex.fetch_deposit_withdraw_fees
  sk       !!!!!!!!!11&99999999< //wGGGr  c                    K   |                                   d{V  i }d}|                     |                     ||                     d{V }|                     |          }|                     ||          S )ao  
        Retrieves the open interest for a list of symbols

        https://docs.bitmex.com/api-explorer/get-stats

        :param str[] [symbols]: a list of unified CCXT market symbols
        :param dict [params]: exchange specific parameters
        :returns dict[]: a list of `open interest structures <https://docs.ccxt.com/?id=open-interest-structure>`
        N)r  publicGetStatsr  r=  parse_open_interests)r  rj  rB  r  rC  s        r  fetch_open_interestszbitmex.fetch_open_interests*  s       !!!!!!!!!,,T[[&-I-IJJJJJJJJ %%g..((7;;;r  c                 h   |                      |d          }|                      |d          }|                     |          }|                     |          }|}||dz   |z   dz   |z   }|                     |d          }|                     |d          }	|                     ||||	||	d d d|          S )Nr  r~  r  r  openInterest	openValue)r&  rg  rW  rX  openInterestAmountopenInterestValuer  r  )r:  r;  r  safe_open_interest)
r  interestre  r  r  quoteSymbol
baseSymbolrg  r_  r`  s
             r  parse_open_interestzbitmex.parse_open_interestH  s     ""8Z88!!(L99--g66,,V44
"#%3c9KGF''.AA$$X{;;	&&&$".!*	(
 	(
 	 	 		r  c                 v    |                      d          }|                     |dd          }|dk    r|r|S dS |S )NFr  r      )check_required_credentialsr<  )r  r   methodpathrB  configisAuthenticatedr  s           r  calculate_rate_limiter_costz"bitmex.calculate_rate_limiter_costi  sJ    99%@@vvq11199 rr  c                   K   |                                   d{V  d}|                     |dd          \  }}|r|                     d||||           d{V S |                     |          }d|d         i}|||d<   |||d<   |                     d	||          \  }}|                     |                     ||                     d{V }|                     ||||          S )
ar  
        retrieves the public liquidations of a trading pair

        https://www.bitmex.com/api/explorer/#not /Liquidation/Liquidation_get

        :param str symbol: unified CCXT market symbol
        :param int [since]: the earliest time in ms to fetch liquidations for
        :param int [limit]: the maximum number of liquidation structures to retrieve
        :param dict [params]: exchange specific parameters for the bitmex api endpoint
        :param int [params.until]: timestamp in ms of the latest liquidation
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns dict: an array of `liquidation structures <https://docs.ccxt.com/?id=liquidation-structure>`
        NFrr   r  rg  r0   r  r  r  )r  r  r  re  handle_until_optionpublicGetLiquidationr  parse_liquidations)	r  rg  r  r   rB  r  re  r  rC  s	            r  fetch_liquidationszbitmex.fetch_liquidationss  s8      !!!!!!!!!88ATV`aa& 	n::;NPVX]_dflmmmmmmmmmV$$fTl
 #(GK $GG229gvNN224;;w3O3OPPPPPPPP &&xFFFr  c                    |                      |d          }|                     ||                     ||          d |                     |d          |                     |d          |                     |d          d d d d d
          S )Nrg  r  r  r  )
r&  rg  r  r  r  r  	baseValue
quoteValuer  r  )r:  safe_liquidationrd  r  r3  )r  r   re  rZ  s       r  parse_liquidationzbitmex.parse_liquidation  s     ##K::$$&&x88 ,,V^DD%%k7;;**;??&
 &
   	r  c                    K   |                                   d{V  |                     |dddd          }|                     |           d{V }|                     ||          S )a  
        fetches the auto deleveraging rank and risk percentage for a list of symbols

        https://www.bitmex.com/api/explorer/#not /Position/Position_get

        :param str[] [symbols]: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an `auto de leverage structure <https://docs.ccxt.com/?id=auto-de-leverage-structure>`
        NT)r  r=  r  parse_adl_ranks)r  rj  rB  rC  s       r  fetch_positions_adl_rankzbitmex.fetch_positions_adl_rank  s       !!!!!!!!!%%gtT4FF0088888888j ##Hg666r  r&  c                     |                      |d          }|                      |d          }||                     ||d d          |                     |d          d d |                     |          |dS )Nrg  r  r  deleveragePercentile)r&  rg  rankratingrR  r  r  )r:  rd  rg  r  rB  s        r  parse_adl_rankzbitmex.parse_adl_rank8  s    j ##D(33##D+66&&xzJJ%%d,BCC11 
 
 	
r  c                   K   |                                   d{V  i }d}| |                     |          }|d         |d<   ||                     |          |d<   |||d<   |                     |d          }|.|                     |          |d<   |                     |d          }|                     |                     ||                     d{V }|                     ||||          S )a  
        fetches historical settlement records

        https://docs.bitmex.com/api-explorer/get-settlements

        :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
        :param int [params.until]: timestamp in ms

 EXCHANGE SPECIFIC PARAMETERS
        :param str [params.filter]: generic table filter, send json key/value pairs, such as {"key": "value"}, you can key on individual fields, and do more advanced querying on timestamps, see the timestamp docs for more details, default value = {}
        :param str [params.columns]: array of column names to fetch, if omitted, will return all columns, note that self method will always return item keys, even when not specified, so you may receive more columns that you expect
        :param int [params.start]: possible values are >= 0 starting point for results, default value = 0
        :param boolean [params.reverse]: if True, will sort results newest first, default value = False
        :returns dict[]: a list of `settlement history objects <https://docs.ccxt.com/?id=settlement-history-structure>`
        Nr0   rg  r  r  r  r  )r  re  r  r:  r  publicGetSettlementr  parse_settlements)	r  rg  r  r   rB  r  re  r  rC  s	            r  fetch_settlement_historyzbitmex.fetch_settlement_history  s     & !!!!!!!!!	
 [[((F &tGH#'<<#6#6GK $GG  11!%e!4!4GIYYvw//F11$++gv2N2NOOOOOOOO %%huEEEr  c                 ,   g }t          dt          |                    D ]1}|                    |                     ||         |                     2|                     |d          }|                     |d          }|                     ||||          S )Nr   r  rg  )r8  r9  r  parse_settlementr  r:  filter_by_symbol_since_limit)	r  settlementsre  r  r   rD  rE  sortedrg  s	            r  r  zbitmex.parse_settlements  s    q#k**++ 	I 	IAMM$//AGGHHHHfk22!!&(3300NNNr  c                     |                      |d          }|                      |d          }||                     ||          |                     |d          |                     |          |dS )Nr  rg  settledPrice)r&  rg  r  r  r  r0  )r  r   re  r  rZ  s        r  r  zbitmex.parse_settlement  sx     ##J<<##J99&&x88%%j.AA11 
 
 	
r  reasonr   rk  headersbodyc
                    |d S |dk    rt          | j        dz   |z             |dk    r|                     |di           }
|                     |
d          }| j        dz   |z   }|                     | j        d         ||           |                     | j        d         ||           |dk    rt          |          t          |          d S )Ni   i  r  messager   r   )	r(   r0   r<  r:  throw_exactly_matched_exceptionr   throw_broadly_matched_exceptionr#   r   )r  r5  r  r   rk  r  r  rC  requestHeadersrequestBodyr  r  feedbacks                r  handle_errorszbitmex.handle_errors  s    43;; 3!56663;;OOHgr::E&&ui88Gw}t+H001I7T\]]]001I7T\]]]s{{ ***)))tr  c                 *    |                                  S N)milliseconds)r  s    r  r  zbitmex.nonce  s      """r  r   GETc                 x   d| j         z   dz   |z   }|dk    r|r|d|                     |          z   z  }nK|                     |d          }|3|d|                     d|i          z   z  }|                     |d          }| j        d         |         |z   }	|                     d          }
|dk    s|d	k    r|
r|                                  ||z   }|                     | j        d
          }d| j        d}| 	                    | 
                                |          }t          |          }||z  }||d
<   |dk    s|dk    s|dk    r|r|                     |          }||z  }|                     |                     |          |                     | j                  t           j                  |d<   |	|||dS )Nz/api/r  r  ?_formatr   Fr   r   r   zapplication/json)zContent-Typezapi-keyPOSTPUTDELETEzapi-signature)r   rk  r  r  )r5   	urlencoder:  r  r   rj  rg  r   r   ri  secondsstrr  hmacencodesecrethashlibsha256)r  rl  r   rk  rB  r  r  queryformatr   rn  authexpiresstringExpiress                 r  signzbitmex.sign  s   $,&,t3U?? 6t~~f5555%%fi88F!t~~y&.ABBBB6955is#e+99%@@)xO++---E>D''mDDG 2; G hht||~~w77GLLMM!D%2GM"6U??f6H6H !99V,,DDLD'+yyT1B1BDKKPTP[D\D\^e^l'm'mGO$fdwOOOr  )rc  r  )NNN)e__name__
__module____qualname__r   r  r   rX  r_  r   ra  rf  rn  rp  r   r   rt  dictr  r   r  r  r  r   r   r  r  r   r  r  r  r  r  r	   r   r  r  r   r  r  r6  r   r;  r   r   r@  r9  listr_  rm  r   rz  r  r  r  r  r   r   floatr   r  r  r  r  r  r  r   r  r   r  r   r  r  r   r   r  r   r1  r@  rC  intrF  rJ  r
   rO  rT  rY  r]  rg  ro  rt  ry  r   r|  r  r  r  r  r  r  r  __classcell__)r  s   @r  r-   r-      s       T# T T T T T Tl -/ ~ ~: ~ ~ ~ ~@. . .53 5 5 5 5 5G G G G G
. 
. 
. 
.L L L *, y, y,V y, y, y, y,vz
4 z
F z
 z
 z
 z
x;) ;) ;) ;) ;)z *, =, =, =, =, =, =,~ @DB ( (S ( (S\ ( ( ( (T 8<B K KC K K K K K, 04$UYbd 'A 'A 'AC 'As 'Aimnsit 'A 'A 'A 'AR 59tZ^gi ` `c ` `TW `nrsxny ` ` ` `& 7;\`ik U U U3 UVY Uptuzp{ U U U U  37TX\eg [A [AC [As [ARU [A [A [A [Az
3 
3 
3] ]t ]x ]; ] ] ] ]~ .2SW`b 0C 0Cs 0C# 0CS 0Cgklwgx 0C 0C 0C 0Cd <@daenp M MS M M[^ Muy  {F  vG M M M M@:s : : : :G
 G
T G
X G
Q\ G
 G
 G
 G
R 68 1 1 1F 1 1 1 1* 6:" G G7 G G G G G, 4  6    >
 
 
4 
 
 
 
< ?CQUdhqs D D D D3 D^a Dx|  ~B  yC D D D DLl l lv l l l l l\: : : : :"Hs H H H H] ] ]v ] ] ] ] ]~ <@d[] >A >A >AS >A >Abfglbm >A >A >A >A@ mqy{ T2 T2 T2I T2Y T2X] T2fi T2 T2 T2 T2l fjx|  FH ,* ,*3 ,* ,*9 ,*I ,*_b ,*ru ,* ,* ,* ,*\ 9=R ' 'S '# ' ' ' '8 AER + +tCy +# + + + +0 59 83 83c 83 83 83 83t BD  S    . 8<B B BW B9 B B B B
 
t 
V 
x 
 
 
 
 8<B nQ nQW nQ4PX> nQ nQ nQ nQ`N Nt NV N N N N` QU]_ 0: 0:3 0: 0: 0:# 0:do 0: 0: 0: 0:d <@ ? ? ?| ? ? ? ?2
 
6 
[ 
 
 
 
4 >BPTcgpr 8Q 8Qs 8Q# 8Q]` 8Q 8Q 8Q 8Qt
 
v 
 
 
 
( ?C2 T T3 T T T T T2 DHPR S S SS S S S S6 =?  
  
  
>  
  
  
  
D: : : : : :x BFb )H )Hw )H )H )H )HV =A < <' < < < << F    B MO     BFTXac (G (Gs (G3 (Gc (G (G (G (GT V    0 AER A7 A7g A7TXY\T] A7 A7 A7 A7F
 
4 
 
3 
 
 
 
B <@daenp 5F 5FS 5F 5F[^ 5F 5F 5F 5FnO O O O
 
 
 
&# s  c TX `c     # # # &eBSW P P P P P P P Pr  r-   )2 ccxt.async_support.base.exchanger   ccxt.abstract.bitmexr   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   typingr   ccxt.base.errorsr   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   ccxt.base.decimal_to_precisionr*   ccxt.base.preciser+   r-    r  r  <module>r     s   6 5 5 5 5 5 , , , , , ,  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I       * * * * * * 0 0 0 0 0 0 - - - - - - . . . . . . ' ' ' ' ' ' & & & & & & . . . . . . ) ) ) ) ) ) * * * * * * + + + + + + 1 1 1 1 1 1 4 4 4 4 4 4 % % % % % %a4P a4P a4P a4P a4PX{ a4P a4P a4P a4P a4Pr  