
    i                    @   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 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)m*Z*  G d dee          Z+dS )    )Exchange)ImplicitAPIN)Balances
CurrenciesCurrencyIntLeverage	LeveragesMarket
MarketTypeNumOrder	OrderBook	OrderSide	OrderTypeStrStringsTickerTickersTradeTransaction)List)ExchangeError)AuthenticationError)PermissionDenied)ArgumentsRequired)
BadRequest)	BadSymbol)InsufficientFunds)InvalidOrder)OrderNotFound)DDoSProtection)ExchangeNotAvailable)	TICK_SIZE)Precisec                       e Zd Z fdZi fdefdZd ZdedefdZ fdZ	dPd
Z
d Zi fdee         fdZ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dQdefdZdddi fd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  Z#dQd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)dQd%ede%fd&Z*dQd%ede+fd'Z,d(ddi fdedededee+         fd)Z-dQd%ede.fd*Z/d+ Z0d, Z1dQd%edefd-Z2ddi fdedededee.         fd.Z3di fded/e4d0e5de6d1e7f
d2Z8ddi fdeded/e4d0e5de7d1e7fd3Z9di fdedefd4Z:di fdefd5Z;di fdefd6Z<di fd#ee         de=fd7Z>dQde?fd8Z@di fd#e'fd9ZAdQd%efd:ZBdi fdede6fd;ZCdi fd#e'fd<ZDdQd%efd=ZEdddi fdededefd>ZFdQd%efd?ZGdi fd@edefdAZHdi fdBedefdCZIi fdefdDZJdQdefdEZKdi fdFe'fdGZLi fdHZMddi fdededefdIZNdQd%efdJZOdK ZPdL ZQdMdNi ddfdOZR xZSS )Rbitmexc                     |                      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d0dd1d(d2dd3di d4dd5dd6dd7dd8dd9dd:dd;dd<dd=dd>dd?dd@ddAddBddCddDdddd(ddd dd dddddEdFdGdHdIdJdKdLdMdMdNdOdPdPdNdPdQdRgdSdTdUdVdWdXdYi dZd[d\d[d]d[d^d[d_d[d`d[dad[dbd[dcd[ddd[ded[dfd[dgd[dhd[did[djd[dkd[d[d[d[d[d[d[d[d[d[d[d[d[d[d[d[dlii dmd[dnd[dod[dpd[dqd[drd[dsd[dtd[dud[dvd[dwd[dxd[dyd[dzd[d{d[d|d[d}d[d[d[d[d[d[d[d[d[d[d[d[d[d[d~i dmd[d]d[dbd[dd[dd[dd[dd[dd[dsddd[dd[dddddd[dddd[dd[d[d[d[d[d[d[d[d[d[d	d[ddddd[dddNdt          t
          t
          t          t          t          t          dt          t          t          t          t          t          t
          dddt          dd[ddddddddddddd
dddddddddd          S )Nidr'   nameBitMEX	countriesSCversionv1	userAgent	rateLimitd   	certifiedTprohasCORSspotmarginFswapfutureoption	addMargincancelAllOrderscancelOrdercancelOrderscloseAllPositionsclosePositioncreateOrdercreateReduceOnlyOrdercreateTrailingAmountOrder	editOrderfetchBalancefetchClosedOrdersfetchCurrenciesfetchDepositAddressfetchDepositAddressesfetchDepositAddressesByNetworkfetchDepositsWithdrawalsemulatedfetchDepositWithdrawFeefetchDepositWithdrawFeesfetchFundingHistoryfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchIndexOHLCVfetchLedgerfetchLeveragefetchLeveragesfetchLeverageTiersfetchLiquidationsfetchMarginAdjustmentHistoryfetchMarketLeverageTiersfetchMarketsfetchMarkOHLCVfetchMyLiquidationsfetchMyTrades
fetchOHLCVfetchOpenOrders
fetchOrderfetchOrderBookfetchOrdersfetchPositionfetchPositionsfetchPositionsRiskfetchPremiumIndexOHLCVfetchTicker)fetchTickersfetchTradesfetchTransactionsfetchTransferfetchTransfersreduceMarginsetLeverage	setMarginsetMarginModesetPositionModetransferwithdraw
timeframes1m5m1h1d)rw   rx   ry   rz   urlszhttps://testnet.bitmex.com)publicprivatezQhttps://github.com/ccxt/ccxt/assets/43336371/cea9cfe5-c57e-4b84-b2ac-77b960b04445z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 ordType)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commonCurrenciesUSDTr   ETHr   )USDtXBtXBTGweiGWEILAMPLAMp)deep_extendsuperr'   describer   r   r    r#   r   r   r$   )self	__class__s    _/var/www/html/crypto-bot/backend/venv/lib/python3.11/site-packages/ccxt/async_support/bitmex.pyr   zbitmex.describe   s   fd 3 3 < < > > GA
(GA
HGA
 $GA
 t	GA

 GA
 GA
 GA
 4GA
  @@@ %@ 	@
 $@ %@ T@ "4@ t@ @ $U@  @ t@ (@ ,T@  T!@" #@ @$ $T%@& "4'@( &t)@* (+@, 1%-@. +J/@0 *:1@2 +D3@4 &u5@6 #E7@8 *49@: $T;@< "5=@> t?@@  A@B !$C@D %eE@ @ @F $TG@H /I@J +EK@L M@N !%O@P &uQ@R  S@T dU@V "4W@X dY@Z !$[@\ t]@^  _@` !$a@b %ec@d )%e@f tg@ @h !%#%/!&"' $#!!%#(! @ @ @GA
\ 	 ]GA
h :;  l67  0<X :G # ! iG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GA
l (;-=%5)5+7%12>  ,?"6BS+?$1DP<L  mGA
T YUGA
V   !+/ % ""##"      WGA
| ! !}GA
 G G G	    returnc                   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dd||d|!ddd|d||<   |S )a+  
        fetches all available currencies on an exchange
        :see: 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currencyr*   r   FscalewithdrawalFeedepositEnabledwithdrawalEnabledTminmax)ru   deposit)	infor)   networkactiver   ru   fee	precisionlimitsenabledminWithdrawalAmountmaxWithdrawalAmountminDepositAmount)amountru   r   )r)   coder   r*   r   r   ru   r   r   r   r   )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   r   r)   r*   chainsr   withdrawEnabledr   r   precisionStringr   jchain	networkIdr   withdrawalFeeRawr   isDepositEnabledisWithdrawEnabledr   currencyEnabledcurrencyActiveminWithdrawalStringminWithdrawalmaxWithdrawalStringmaxWithdrawalminDepositString
minDeposits"                                     r   fetch_currencieszbitmex.fetch_currencies&  s      33F;;;;;;;;D q#h--(( O	 O	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 ()+&  $# 
  -,! !
  *#     %1 F4LL4 r   c                     |                      |          }|                     |d          }|                     |          }t          j        ||          }|                     |          S Nr   )r   r   number_to_stringr%   
string_divr   )r   r   r   r   r   amountStringfinalAmounts          r   convert_from_real_amountzbitmex.convert_from_real_amount  sa    ==&&$$X{;;	,,V44(yAA  ---r   r   r   c                     ||S |d S |                      |          }|                     |d          }t          j        ||          S r  )r   r   r%   r   )r   r   r   r   r   s        r   convert_to_real_amountzbitmex.convert_to_real_amount  sO    <M^4==&&$$X{;;	!&)444r   c                 ,   |                      |          }|                     |          }|                     | j        d          }|d         r|s|                     |d         |          }t          t          |                               ||          S )Nr   r7   base)safe_symbolmarketr   r   r  r   r'   amount_to_precision)r   symbolr   r  r   r   s        r   r  zbitmex.amount_to_precision  s    !!&))V$$t|^DD&> 	K, 	K226&>6JJFVT""66vvFFFr   r  c                    |                      | j        d          r|                     |          S |                     |          }|                     || j                  }|s|                     |          S |                     |          }|d         r/|                     |                     ||         |                    S |                     |          S )Nr   r7   )r   r   r   r  in_arraysymbolsr  r  )r   r  rawQuantitycurrencySidemarketExistsr  s         r   convert_from_raw_quantityz bitmex.convert_from_raw_quantity  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   )r"  )r   r  r  s      r   convert_from_raw_costzbitmex.convert_from_raw_cost  s    --fk7KKKr   c                 f   K   |                      |           d{V }|                     |          S )a-  
        retrieves data on all markets for bitmex
        :see: 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   r   r   s      r   fetch_marketszbitmex.fetch_markets  sD       77????????` !!(+++r   c                    |                      |d          }|                      |d          }|                      |d          }|                      |d          }|                     |          }|                      |d          }d}d}	d}
|dk    rd}d	}n8|d
k    rd}d	}	n-|dk    rd}d	}
n"|dk    r|}|                      |d          }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                    }|                     |          }|
rF|                      |d          }|                     |          }|dz   | 	                    |          z   }n|}|                     |dd          }|                     |          }||k    }| 
                    |d          }|                      |dd          }|                     t          j        d|                    }i d|d|d |d!|d"|d#|d$|d%|d&|d|	d'dd|d|
d(dd)|d*|d+|||| 
                    |d,          | 
                    |d-          |||| 
                    |d.          d | 
                    |d/          | 
                    |d0          d1|r|                     d          nd |r|nd d2d |rd n|d2d | 
                    |d3          d2d |r|nd d2d4|                     |                      |d5                    |d6S )7Nr  
underlyingquoteCurrencysettlCurrencytypFFFWCSXr9   TIFXXXPr7   FFCCSXr:   FFICSX
rootSymbol	isInverseisQuantostateUnlisted/:underlyingToPositionMultiplierunderlyingToSettleMultiplier1
multiplierexpiry-positionCurrencymaxOrderQty
initMarginr)   r  r   settlebaseIdquoteIdsettleIdtyper8   r;   r   contractlineartakerFeemakerFeeoptionStrikePricelotSizetickSize)r   pricer   maxPrice)leverager   rN  costlisting)inversequantotakermakercontractSizer=  expiryDatetimestrike
optionTyper   r   createdr   )r   r   r   safe_string_2r   r%   r  
string_abs	parse8601yymmddsafe_number)r   r  r)   rC  rD  rE  rB  r-  r9   r7   r:   rF  r  r   rG  rW  r3  r4  rH  statusr   r=  rX  r  multiplierString
positionIdr   positionIsQuoter@  rA  maxLeverages                                  r   parse_marketzbitmex.parse_marketB  s6   fh//!!&,77""6?;;##FO<<((22 vu--(??DDDH__DDDH__DFFH__G%%fl;;FDF&&v..''00>6OOFK88	??6:665=Gi-0L4!!&'22:% 	CZ%'FF 	CZ%'#-6F C#'#5#5f>^`~## #001CCIY1Z1Z[[#*#5d6F6Fv|6\6\#]#] #001ABB <!%!1!1&(!C!C77#F(;(;; F''0BLQQ
**:66#u,&&v}==%%flC@@
''(:3
(K(KLL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  $ ~~d&6&6vy&I&IJJ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)r   r   r   r   accountr  safe_balance)
r   r   r   r   balance
currencyIdr   rl  rj  rk  s
             r   parse_balancezbitmex.parse_balance  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 )am  
        query for balance and get the amount of funds available for trading or funds locked in orders
        :see: 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extendrp  )r   r   requestr   s       r   fetch_balancezbitmex.fetch_balance  s       !!!!!!!!!
 224;;w3O3OPPPPPPPP` !!(+++r   Nr  limitc                   K   |                                   d{V  |                     |          }d|d         i}|||d<   |                     |                     ||                     d{V }|g g dddd}t	          dt          |                    D ]y}||         }	|	d         dk    rd	nd
}
|                     ||                     |	d                    }|                     |	d          }|||
         	                    ||g           z| 
                    |d
         dd          |d
<   | 
                    |d	         d          |d	<   |S )aE  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :see: 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
        Nr  r)   depth)r  bidsasks	timestampdatetimenoncer   sideSellr|  r{  sizerN  T)rs  r  publicGetOrderBookL2ru  r   r   r"  r   r`  appendsort_by)r   r  rx  r   r  rv  r   r   r   r   r  r   rN  s                r   fetch_order_bookzbitmex.fetch_order_book0  s      !!!!!!!!!V$$fTl
 $GG224;;w3O3OPPPPPPPP
 
 q#h--(( 		5 		5AQKE#Fmv5566FD33FD<L<LUTZ<[<[\\F$$UG44E  t##UFO444fVna>>vfVna88vr   r)   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
        :see: https://www.bitmex.com/api/explorer/#not /Order/Order_getOrders
        :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   r   r!   r)   )r   r)   r  r   r  r   
numResultss          r   fetch_orderzbitmex.fetch_orderW  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 )a|  
        :see: 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>`
        NFrd   paginater2   r)   r  	startTimecountuntilendTimer  )rs  handle_option_and_paramsfetch_paginated_call_dynamicr  iso8601safe_integer_2omitr   jsonprivateGetOrderparse_orders
r   r  r  rx  r   r  r  rv  r  r   s
             r   r  zbitmex.fetch_ordersj  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
        :see: 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   r  r  rx  r   rv  s         r   fetch_open_orderszbitmex.fetch_open_orders  s[       

 &&vueT=M=MgW]=^=^_________r   c                 v   K   |                      ||||           d{V }|                     |dddgd          S )aB  
        fetches information on multiple closed orders made by the user
        :see: 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>`
        Nra  closedcanceledF)r  filter_by_array)r   r  r  rx  r   orderss         r   fetch_closed_orderszbitmex.fetch_closed_orders  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<   |||d	<   |                     |d
d          }|/|                     |d
g          }|                     |          |d<   |                     ||          }d|v r|                     |d                   |d<   | 	                    |           d{V }	| 
                    |	|||          S )a  
        fetch all trades made by the user
        :see: 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>`
        NFr_   r  r2   r)   r  r  r  r  r  r  )rs  r  r  r  r  r  r  r   r  privateGetExecutionTradeHistoryparse_tradesr  s
             r   fetch_my_tradeszbitmex.fetch_my_trades  s      !!!!!!!!!88R\]]& 	o::?FTY[`bhjmnnnnnnnnn[[((F &tGH#'<<#6#6GK $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transactionr8   rt   r   r   )
WithdrawalRealisedPNLUnrealisedPNLDepositTransferAffiliatePayout	SpotTrader   )r   rF  typess      r   parse_ledger_entry_typezbitmex.parse_ledger_entry_type  s=    '#%$") 
 
 tT222r   r   c                    |                      |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
transactIDrl  txtransactTyper   r   transactTimer   r   )rQ  r   walletBalance0outintransactStatus)r)   r   r}  r~  	directionrl  referenceIdreferenceAccountrF  r   r   beforeafterra  r   )r   r  r   r  r^  r   r%   
string_subr  	string_ltr]  parse_transaction_statusr  )r   itemr   r)   rl  r  r  rF  ro  r   r  r   r}  feeCostr   r  r  r  ra  s                      r   parse_ledger_entryzbitmex.parse_ledger_entry  so   T dL11""433&&tT22++D,<,<T>,R,RSS%%dJ77
&&z8<<''h77,,T<@@NN4#3#3D.#I#IJJ	 I""4//11$@@G%%g..
 
   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 )ag  
        fetch the history of changes, actions done by the user or operations that altered balance of the user
        :see: 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 entrys to return, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ledger structure <https://docs.ccxt.com/#/?id=ledger-structure>`
        Nr  r)   r   )rs  r   privateGetUserWalletHistoryru  parse_ledger)r   r   r  rx  r   rv  r   r   s           r   fetch_ledgerzbitmex.fetch_ledgert  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 )
aw  
        fetch history of deposits and withdrawals
        :see: 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   rr  r)   r  r  r  r  F)rs  r   r  ru  r  parse_transactions)	r   r   r  rx  r   rv  r   r   transactionss	            r   fetch_deposits_withdrawalsz!bitmex.fetch_deposits_withdrawals  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   c                 >    ddddd}|                      |||          S )Npendingr  ok)	ConfirmedCanceled	CompletedPendingr  r   ra  statusess      r   r  zbitmex.parse_transaction_status  s4    "" 	
 
 &&999r   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   r   r   r   r  r   r)   r  txidrF  r   ra  r~  addressFrom	addressTotagtagFromtagToupdated)r   rQ  rate)internalcommentr   )r   safe_currencyr^  safe_string_lowerr%   r]  r  r  r   r   r  )r   r  r   ro  r  r}  rF  r   r  r  r  amountStringAbsr   feeCostStringr  ra  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
        :see: 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>`
        Nr  r)   r   z fetchTicker() symbol z
 not found)rs  r  publicGetInstrumentru  r   r   r)   parse_ticker)r   r  r   r  rv  r   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   r  c                 |  K   |                                   d{V  |                     |          }|                     |           d{V }i }t          dt	          |                    D ]:}|                     ||                   }|                     |d          }||||<   ;|                     |d|          S )a3  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
        :see: 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   r  )rs  market_symbols#publicGetInstrumentActiveAndIndicesr   r   r  r   filter_by_array_tickers)r   r  r   r   r   r   r  r  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|          S )Nr  r}  prevPrice24h	lastPricer~  high	highPricelowlowPricebidbidPrice	bidVolumeaskaskPrice	askVolumevwapr  closelastpreviousClosechange
percentageaveragehomeNotional24hforeignNotional24h)
baseVolumequoteVolumer   )r   r  r^  safe_tickerr  )r   r  r  marketIdr  r}  r  r  s           r   r  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 )Nr  volumer}  r  r  r  r  )r   safe_marketr"  r^  r`  )r   ohlcvr  r  r  s        r   parse_ohlcvzbitmex.parse_ohlcvY  s    $ ##E844!!(F33//x0@$BRBRSXZbBcBcddNN4++E;??@@UF++UF++UE**UG,,
 	
r   rw   c                   K   |                                   d{V  d}|                     |dd          \  }}|r |                     d|||||           d{V S |                     |          }|d         |                     | j        ||          d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
        :see: 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
        NFr`   r  r)   T)r  binSizepartialr  r  r    r   r  reverser   )rs  r  "fetch_paginated_call_deterministicr  r   rv   r  r  r  parse_timeframer   r   sumpublicGetTradeBucketedru  parse_ohlcvsr   r   )r   r  	timeframer  rx  r   r  r  rv  r  durationr   r}  r  r   r   r   s                    r   fetch_ohlcvzbitmex.fetch_ohlcvw  s>      !!!!!!!!!88zZZ& 	x@@vW\^cenpvwwwwwwwww V$$Tl''INN	
 	
 $GG##FGY??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   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 )Nr  r}  avgPxrN  r  lastQtyexecCost
trdMatchIDr  r  execCommr,  r   
commission)rQ  r   r  execTyper   r  rV  rU  ordType)r   r}  r~  r  r)   r   rF  takerOrMakerr  rN  rQ  r   r   )r   r  r^  r\  r"  r  r$  r  r   r%   r  
safe_trader  r]  )r   r   r  r  r  r}  priceStringr  r&  r)   r   r  r   r  ro  r*  r,  rF  s                     r   parse_tradezbitmex.parse_trade  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   c                 >    ddddd}|                      |||          S )NDayGTCIOCFOK)r@  GoodTillCancelImmediateOrCancel
FillOrKillr  )r   timeInForcetimeInForcess      r   parse_time_in_forcezbitmex.parse_time_in_force:  s4    #!&	
 
 k;GGGr   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
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 )#Nr  orderQtyFdefaultSubTyperH  rS  r$  cumQtyexecInstParticipateDoNotInitiater}  stopPx	leavesQtyr   r)   r  clientOrderIdclOrdIDr~  lastTradeTimestampr  rF  r+  rG  postOnlyr  rN  	stopPricetriggerPricer   rQ  r
  	ordStatus)filled	remainingra  r   trades)r   r  r   r   r"  r  r%   r  r^  r`  
safe_orderr  r  rI  r>  )r   r   r  r  r  qtyrQ  r   r3  rL  r
  rY  rM  rN  rU  r}  rV  rZ  s                     r   parse_orderzbitmex.parse_orderC  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:66 $>>HNN4#3#3E;#G#GHH	$$UH55	$$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 
  
 I 
 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
        :see: 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>`
        NFrk   r  r  r)   r  Tr  r  r  r  r  )rs  r  r  r  r  r   r  r  publicGetTraderu  r  r  s
             r   fetch_tradeszbitmex.fetch_trades  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   rF  r  rN  c                 .  K   |                                   d{V  |                     |          }|                     |          }|                     |d          }	|	3|d         s+|d         s#t	          | j        dz   |d         z   dz             |                     | j        dd	          }
|                     | 	                    ||                    }|d
         |                     |          |||
d}| 
                    |g d          }|                     |dd          }|du}|du}|s|r*|                     |d          }|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
        :see: 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 fullfilled, 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 - 'above' or 'below'
        :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>`
        N
reduceOnlyr9   r:   z/ createOrder() does not support reduceOnly for rF  zI orders, reduceOnly orders are supported for swap and future markets onlybrokerIdCCXTr)   )r  r  rK  r+  text)rW  rP  rV  trailingAmountpegOffsetValuetriggerDirectionaboverx  r  rB   belowbuy	StopLimitLimitIfTouchedStopMarketIfTouchedsellr>  TrailingStopPegpegPriceTypezK createOrder() requires a triggerPrice(stopPx|stopPrice) parameter for the z order typerP  r+  )rW  rV  rP  ri  rg  LimitrN  rS  rR  )rs  r  
capitalizer   r    r)   r   r   parse_to_intr  safe_number_nr\  check_required_argumentparse_to_numericr   price_to_precisionr  privatePostOrderru  r^  )r   r  rF  r  r   rN  r   r  	orderTyperc  rd  r]  rv  rW  rg  isTriggerOrderisTrailingAmountOrderri  triggerAboveisStopSellOrderisBuyIfTouchedOrderrR  r   s                          r   create_orderzbitmex.create_order  s,      !!!!!!!!!V$$OOD))	__V\::
!6N VH-= "47-^#^aghnao#o  s~  $~      ##DL*fEE 8 8 H HIITlOOD)) 
 
 ))&2Y2Y2YZZ++F4DFVWW%T1 .d : 	v2 	v#//8JKK,7L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()*;'''+DG  7D  -D  GP  -P  S`  -`  a  a  a$($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    }|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 )Nrg  rh  ri  rj  rx  r  rB   rk  rl  rm  rn  ro  rp  rq  r>  origClOrdIDrR  rS  )r  rS  rR  r  rK  rN  rd  re  rf  )rs  r\  r   rx  ry  r  rv  r  r   privatePutOrderru  r^  )r   r)   r  rF  r  r   rN  r   rv  rg  r~  ri  r  r|  r  r  r  rR  r]  rd  r   s                        r   
edit_orderzbitmex.edit_order(  s     !!!!!!!!!++F4DFVWW .d :  	O#//8JKK,7L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 )	a}  
        cancels an open order
        :see: 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>`
        NrS  rR  r  r   errorr   z cancelOrder() failed: )rs  safe_value_2r  privateDeleteOrderru  r   r   findr!   r)   r^  )	r   r)   r  r   rR  rv  r   r   r  s	            r   cancel_orderzbitmex.cancel_orderV  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   c                 >  K   |                                   d{V  |                     |dd          }i }|||d<   n||d<   |                     |ddg          }|                     |                     ||                     d{V }|                     |          S )a  
        cancel multiple orders
        :see: 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>`
        NrS  rR  r  )rs  r  r  r  ru  r  )r   idsr  r   rR  rv  r   s          r   cancel_orderszbitmex.cancel_ordersp  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
        :see: 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>`
        Nr)   r  )rs  r  privateDeleteOrderAllru  r  )r   r  r   rv  r  r   s         r   cancel_all_orderszbitmex.cancel_all_orders  s       !!!!!!!!![[((F &tGH33DKK4P4PQQQQQQQQP   6222r   c                    K   |                                   d{V  |                     ||           d{V }|                     ||d          S )a  
        fetch the set leverage for all contract markets
        :see: 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>`
        Nr  )rs  fetch_positionsparse_leverages)r   r  r   	leveragess       r   fetch_leverageszbitmex.fetch_leverages  sk       !!!!!!!!!..w????????	##IwAAAr   c                     |                      |d          }||                     ||          |                     |d          |                     |d          |                     |d          dS )Nr  
marginModerP  )r   r  r  longLeverageshortLeverage)r   r  r  safe_integer)r   rP  r  r  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 )ax  
        fetch all open positions
        :see: 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>`
        Nr  F)rs  privateGetPositionparse_positionsfilter_by_array_positions)r   r  r   r   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   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 )(Nr  r}  crossMarginTcrossisolatedforeignNotionalhomeNotionalrB  maintMarginunrealisedPnl
currentQtyrW  r   r>  shortlongr   r)   rl  r~  lastUpdateTimestamphedgedr  	contracts
entryPriceavgEntryPrice	markPricer  notionalrP  
collateralinitialMarginrA  initMarginReqmaintMarginReqliquidationPriceunrealisedPnlPcnt)
initialMarginPercentagemaintenanceMarginmaintenanceMarginPercentageunrealizedPnlr  r  marginRatior	  stopLossPricetakeProfitPrice)r  r   r   r%   r]  r\  r  r   r`  safe_positionr^  )r   r   r  r  r~  r  r  notionalStringsettleCurrencyCoder  r  r  rW  r  r  s                  r   parse_positionzbitmex.parse_positionB  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   c                   K   |                      ||          \  }}|                     |           |                                  d{V  |                     |          }|                     ||          }d}|                     |          \  }}|d         |||                     ||d                   d}	|                     |                     |	|                     d{V }
| 	                    |
|          S )a  
        make a withdrawal
        :see: 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>`
        Nr)   r   )r   r   r   r   )
handle_withdraw_tag_and_paramscheck_addressrs  r   r  handle_network_code_and_paramsnetwork_code_to_id privatePostUserRequestWithdrawalru  r  )r   r   r   r   r  r   r   r]  networkCoderv  r   s              r   ru   zbitmex.withdraw  s      99#vFFV7###!!!!!!!!!==&&++D&99"AA&IIV ..{HV<LMM	
 
 >>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
        :see: 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 dictionary of `funding rates structures <https://docs.ccxt.com/#/?id=funding-rates-structure>`, indexe by market symbols
        Nr   r  r9   F)rs  r  r   r   r   r  r   r  r  parse_funding_ratesr  )r   r  r   r   filteredResponser   r  r  r  r9   r   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 S )Nr}  r  fundingTimestampr   r  
indexPriceinterestRateestimatedSettlePriceindicativeSettlePricer~  fundingRatefundingDatetimenextFundingRateindicativeFundingRatenextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetime)r   r  r`  r^  r  )r   rG  r  r~  r  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                 L  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          }| 	                    |d
dg          }||                     |          |d<   ||d|d<   | 
                    |                     ||                     d{V }|                     ||||          S )a  
        Fetches the history of funding rates
        :see: 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>`
        Nr)   r  r8  )nearestdailyweeklymonthly	quarterlybiquarterly	perpetualr   r   r  r  r  tillr  Tr  )rs  
currenciesr   splitr   r  r  r  r  r  publicGetFundingru  parse_funding_rate_histories)r   r  r  rx  r   rv  r  r   splitSymbolsplitSymbolLengthrv   r  r   s                r   fetch_funding_rate_historyz!bitmex.fetch_funding_rate_history0	  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##FGV<<6GV#455!%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 )Nr  r}  r  )r   r  r  r}  r~  )r   r  r`  r^  )r   r   r  r  r~  s        r   parse_funding_rate_historyz!bitmex.parse_funding_rate_historyh	  sx     ##D(33##D+66&&x88++D-@@11 
 
 	
r   rP  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 )a}  
        set the level of leverage for a market
        :see: 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?r2   z( leverage should be between 0.01 and 100rF  r9   r:   z6 setLeverage() supports future and swap contracts onlyr)   )r  rP  )r   r)   r   rs  r  r   privatePostPositionLeverageru  )r   rP  r  r   r  rv  s         r   set_leveragezbitmex.set_leverage|	  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'
        :see: 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 crossrF  r9   r:   z8 setMarginMode() supports swap and future contracts onlyFTr)   )r  r   )	r   r)   lowerr   rs  r  r   privatePostPositionIsolateru  )r   r  r  r   r  r   rv  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 )
aM  
        fetch the deposit address for a currency associated with self account
        :see: 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   r)   r   )r   r   " )r   r   r  r   r   )
rs  r  r   r)   r   r  r  privateGetUserDepositAddressru  replace)r   r   r   r  r   rv  r   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   r	  )r   ru   r   r   r   r   r   r   r   F)r   ru   r   ru   r   r	  )	r   r   r   r   r   r   r   r%   r   )r   r   r   r   networksLengthr   r   r   r   r   r   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 )az  
        fetch deposit and withdraw fees
        :see: 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   )rs  r   parse_deposit_withdraw_fees)r   r  r   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                 v    |                      d          }|                     |dd          }|dk    r|r|S dS |S )NFrQ  r      )check_required_credentialsr   )r   r   methodpathr   configisAuthenticatedrQ  s           r   calculate_rate_limiter_costz"bitmex.calculate_rate_limiter_cost1
  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 )
ax  
        retrieves the public liquidations of a trading pair
        :see: 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>`
        NFrY   r  r  r)   r  r  r  )rs  r  r  r  handle_until_optionpublicGetLiquidationru  parse_liquidations)	r   r  r  rx  r   r  r  rv  r   s	            r   fetch_liquidationszbitmex.fetch_liquidations;
  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	          S )Nr  rW  rN  )	r   r  r  rW  rN  	baseValue
quoteValuer}  r~  )r   safe_liquidationr  r`  )r   r   r  r  s       r   parse_liquidationzbitmex.parse_liquidationc
  s     ##K::$$&&x88 ,,V^DD%%k7;;
&
 
&
 
 
 
	r   c
                    |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"   r)   r   r   throw_exactly_matched_exceptionr   throw_broadly_matched_exceptionr   r   )r   r   reasonr~   r  headersbodyr   requestHeadersrequestBodyr  r  feedbacks                r   handle_errorszbitmex.handle_errorsz
  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/r7  r+  ?_formatr   Fr}   r|   r   zapplication/json)zContent-Typezapi-keyPOSTPUTDELETEzapi-signature)r~   r  r#  r"  )r.   	urlencoder   r  r{   r  r  r   r   r  secondsstrr  hmacencodesecrethashlibsha256)r   r  r   r  r   r"  r#  queryformatr~   r  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   )r  r)  )T__name__
__module____qualname__r   r   r  r  r   r  r  r"  r$  r   r   r(  rf  r   rp  rw  r4  r   r   r  r  r   r  r  r  r  r  r   r  r  r   r  r  r  r   r  r   r   r  r  listr  r"  r   r/  r>  rI  r^  ra  r   r   floatr   r  r  r  r  r  r
   r  r	   r  r  r  ru   r  r  r  r  r  r  r  r  r	  r  r  r  r'  r  r?  __classcell__)r   s   @r   r'   r'      su
       H H H H HT -/ z z: z z z zx. . .53 5 5 5 5 5G G G G G
. 
. 
. 
.L L L *, w, w,V w, w, w, w,rr
f r
 r
 r
 r
h;) ;) ;) ;) ;)z *, ;, ;, ;, ;, ;, ;,z @DB % %S % %S\ % % % %N 8<B K KC K K K K K& 04$UYbd %A %A %AC %As %Aimnsit %A %A %A %AN 59tZ^gi ` `c ` `TW `nrsxny ` ` ` `" 7;\`ik U U U3 UVY Uptuzp{ U U U U 37TX\eg YA YAC YAs YARU YA YA YA YAv
3 
3 
3[
 [
 [
 [
 [
 [
z .2SW`b .C .Cs .C# .CS .C .C .C .C` <@daenp M MS M M[^ Muy  {F  vG M M M M<: : :G
 G
x G
; G
 G
 G
 G
R 68 1 1 1F 1 1 1 1& 6:" G G7 G G G G G( 6 V    <
 
 
4 
 
 
 
< 8<$]ajl B B BC BWZ Bquvzq{ B B B BHl l l5 l l l l\: : :"H H H[ [ [5 [ [ [ [z <@d[] <A <A <AS <A <Abfglbm <A <A <A <A| mqy{ H2 H2 H2I H2Y H2X] H2fi H2 H2 H2 H2T fjx|  FH ,* ,*3 ,* ,*9 ,*I ,*_b ,*ru ,* ,* ,* ,*\ 9=R ' 'S '# ' ' ' '4 6:" + +s + + + +, 59 63 63c 63 63 63 63p :>b 
B 
BT#Y 
BY 
B 
B 
B 
B
 
x 
 
 
 
 8<B lQ lQW lQ lQ lQ lQ\N Nv N N N N` EIQS ,: ,:3 ,: ,: ,: ,: ,:\ <@ ? ? ? ? ? ?.
 
6 
 
 
 
2 >BPTcgpr 6Q 6Qs 6Q# 6Q]` 6Q 6Q 6Q 6Qp
 
v 
 
 
 
( ?C2 T T3 T T T T T. DHPR S S SS S S S S2 =? 
 
 
 
 
 
@: : : : : :x BFb 'H 'Hw 'H 'H 'H 'HR MO     BFTXac &G &Gs &G3 &Gc &G &G &G &GP V    .   # # # &eBSW P P P P P P P Pr   r'   ), ccxt.async_support.base.exchanger   ccxt.abstract.bitmexr   r8  ccxt.base.typesr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   typingr   ccxt.base.errorsr   r   r   r   r   r   r   r    r!   r"   r#   ccxt.base.decimal_to_precisionr$   ccxt.base.preciser%   r'    r   r   <module>rN     sv   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       * * * * * * 0 0 0 0 0 0 - - - - - - . . . . . . ' ' ' ' ' ' & & & & & & . . . . . . ) ) ) ) ) ) * * * * * * + + + + + + 1 1 1 1 1 1 4 4 4 4 4 4 % % % % % %P*P P*P P*P P*P P*PX{ P*P P*P P*P P*P P*Pr   