
    !:h                    P   d dl mZ d dlmZ d dlZd dlmZmZmZm	Z	m
Z
mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ 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      Z1y)    )Exchange)ImplicitAPIN)AnyBalances
CurrenciesCurrencyDepositAddressIntLedgerEntryLeverage	LeveragesMarket
MarketType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
d_d	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d`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ddi fdedededee$   fd Z%d!efd"Z&d`d#ede de$fd$Z'i fdede(fd%Z)di fd&e*de+fd'Z,d`d(edede(fd)Z-d`dede.fd*Z/d+ddi fdedededee.   fd,Z0d`d-edede1fd.Z2d!efd/Z3d0efd1Z4d`d2ededefd3Z5ddi fdedededee1   fd4Z6di fded5e7d6e8de9d7e:f
d8Z;ddi fdeded5e7d6e8de:d7e:fd9Z<di fdedefd:Z=di fdefd;Z>di fdefd<Z?i fd=efd>Z@di fd&e*deAfd?ZBd`d@ededeCfdAZDdi fd&e*deeE   fdBZFd`dCedefdDZGdi fdede9dEede$fdFZHdi fd&e*deIfdGZJd`dedeKfdHZLdddi fdededefdIZMd`defdJZNdi fd@edefdKZOdi fdLedefdMZPi fdedeQfdNZRd`de fdOZSdi fdPe*fdQZTi fdRZUddi fdededefdSZVd`defdTZWdeXdUedVedWedXedYefdZZYd[ ZZd\d]i ddfd^Z[ xZ\S )abitmexreturnc                    | j                  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i dEddFddGddHddIddJddKddLd+dMddNddOd dPddQddRd dSddTddUddVdidWdXdYdZd[d\d]d^d^d_d`dadad_dadbdcgdddedfdgdhdidji dkdldmdldndldodldpdldqdldrdldsdldtdldudldvdldwdldxdldydldzdld{dld|dldldldldldldldldldldldldldldldld}ii d~dlddlddlddlddlddlddlddlddlddlddlddlddlddlddlddlddldldldldldldldldldldldldldldi d~dldndldsdlddlddlddlddlddlddddlddlddddddlddddlddldldldldldldldldldld	dldddddlddd_dt        t
        t
        t        t        t        t        t
        dt        t        t        t        t        t        t
        dddt        ddld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	ddddiidŜdddd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cancelAllOrderscancelAllOrdersAftercancelOrdercancelOrderscloseAllPositionsclosePositioncreateOrdercreateReduceOnlyOrdercreateStopOrdercreateTrailingAmountOrdercreateTriggerOrder	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fetchPositionHistoryfetchPositionsfetchPositionsHistoryfetchPositionsRiskfetchPremiumIndexOHLCVfetchTickerfetchTickersfetchTradesfetchTransactionsfetchTransferfetchTransfersreduceMargin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|   rJ   createOrdersri   rl   rk   rn   rQ   rj   defaultr   index)extendsrJ   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    E/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/bitmex.pyr   zbitmex.describe   s4
   fd < > yA
(yA
HyA
 $yA
 t	yA

 yA
 yA
 yA
 4yA
  FFF %F 	F
 $F %F TF "4F 'F tF F $UF  F tF (F  "4!F" ,T#F$ %d%F& T'F( )F* $T+F, "4-F. &t/F0 (1F2 1%3F4 +J5F6 *:7F8 +D9F: &u;F< #J=F> *4?F@ $TAFB "5CFD tEFF  GFH !$IFJ %eKFL $TMFN /OFP +EQFR SFT !%UFV &uWFX  YFZ d[F\ "4]F^ d_F` !$aFb tcFd  eFf 'gFh !$iFj (kFl %emFn )%oFp tqFr sFt tuFv $ZwFx  yFz !%{F| }F~ 4F@ tAFB TCFD  EFF "5GFH EIFJ DKFyA
h 	iyA
t :; j67 0<X :G #!uyA
^  !&!-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Kl_yA
x (;-=%5)5+7%12>-=	 ,?"6BS+?$1DP<LyyA
b YcyA
d   !+/ % ""##"    eyA
J #&*(,$($(- -1).+06:#'#'"&#(	( #($(27+0)$6 %)&+!$$(%,*/& ',#($)*/	# ',!$#($)*/( ',!$$(%,#($)*/$ ',!$$(,0%,#($)*/	*  #KHT  )*#U-$  )*#T-$  "= "= 	 "= "= 	EjKyA
` !ayA
 y y	    c                    | j                  |      }i }t        dt        |            D ]Z  }||   }| j                  |d      }| j	                  |      }| j                  |d      }| j                  |d      }	| j                  |dg       }
d}d}i }| j                  |d      }| j                  |      }| j                  |      }t        dt        |
            D ]  }|
|   }| j                  |d      }| j                  |      }| j                  |d      }| j                  t        j                  ||            }| j                  |d	d      }| j                  |d
d      }|xr |}|rd}|rd}|||||||ddddddddd	||<    | j                  |d      }|xs |xs |}| j                  |d      }| j                  t        j                  ||            }| j                  |d      }| j                  t        j                  ||            }| j                  |d      } | j                  t        j                  | |            }!| 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
        r   assetcurrencyr1   r   FscalewithdrawalFeedepositEnabledwithdrawalEnabledTN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  r  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    --f5D q#h-( Q	A{H$$Xw7E**51D!!(J7B##Hf5D__Xz2>F"N#OH$$Xw7E"2259O))/:I1c&k*  q	 ,,UG<	11)<#'#3#3E?#K  $ 1 1'2D2DEUWf2g h#'>>%9I5#Q $(NN5:Mu$U!*@/@#%)N$&*O!#&$/ 1(!% $(#'%
 $(#'$	%! B #ooh	BO,S1R?N"&"2"28=R"S --g.@.@ATVe.fgM"&"2"28=R"S --g.@.@ATVe.fgM#//:LM**7+=+=>NP_+`aJ''.AXMH ()+&  $#
  -,!
  *#  %$,'3F4LoQ	d r  c                     | j                  |      }| j                  |d      }| j                  |      }t        j                  ||      }| 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  sU    ==&$$X{;	,,V4((yA  --r  r  r  c                     ||S |y | j                  |      }| j                  |d      }t        j                  ||      S rA  )r  r!  r+   r'  )r   r  r  r  r  s        r   convert_to_real_amountzbitmex.convert_to_real_amount  sG    <M^==&$$X{;	!!&)44r  c                     | j                  |      }| j                  |      }| j                  | j                  d      }|d   r|s| j	                  |d   |      }t
        t        |   ||      S )Nr   r>   base)safe_symbolmarketr#  r   rF  r   r-   amount_to_precision)r   symbolr  rL  r   r   s        r   rM  zbitmex.amount_to_precision(  sh    !!&)V$t||^D&>,226&>6JFVT6vvFFr  c                 r   | j                  | j                  d      r| j                  |      S | j                  |      }| j	                  || j
                        }|s| j                  |      S | j                  |      }|d   r$| j                  | j                  ||   |            S | j                  |      S )Nr   r>   )r#  r   r%  rK  in_arraysymbolsrL  rH  )r   rN  rawQuantitycurrencySidemarketExistsrL  s         r   convert_from_raw_quantityz bitmex.convert_from_raw_quantity0  s    ??4<<8$$[11!!&)}}VT\\:$$[11V$&>$$T%@%@AUWb%cdd  --r  c                 (    | j                  ||d      S )Nr   )rU  )r   rN  rR  s      r   convert_from_raw_costzbitmex.convert_from_raw_cost<  s    --fk7KKr  c                 F    | j                  |      }| j                  |      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
        )publicGetInstrumentActiveparse_markets)r   r)  r*  s      r   fetch_marketszbitmex.fetch_markets?  s(     11&9` !!(++r  rL  c                    | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |      }| j                  |d      }d}d}	d}
|dk(  rd}d	}n1|d
k(  rd}d	}	n'|dk(  rd}d	}
n|dk(  r|}| j                  |d      }d}d	}
| j                  |      }| j                  |      }|xs |
}d }| j                  |d      }| j                  |d      }|r| xr | nd }| j                  |d      }|dk(  }d }d }d }|	r	|dz   |z   }n|r|dz   |z   dz   |z   }|r9| j                  |dd      }| j	                  t        j                  d|            }n6t        j                  | j                  |d            }| j	                  |      }| j                  |d      }| j                  |      }||dz   | j                  |      z   }n|}| j                  |dd      }| j                  |      }||k(  }| j                  |d      }| j                  |dd      }| j	                  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+|||| j                  |d,      | j                  |d-      |||| j                  |d.      d | j                  |d/      | j                  |d0      d1|r| j	                  d      nd |r|nd d2d |rd n|d2d | j                  |d3      d2d |r|nd d2d4d |d5S )6NrN  
underlyingquoteCurrencysettlCurrencytypFFFWCSXr@   TIFXXXPr>   FFCCSXrA   FFICSX
rootSymbol	isInverseisQuantostateOpen/:underlyingToPositionMultiplierunderlyingToSettleMultiplier1
multiplierexpiry-positionCurrencymaxOrderQty
initMarginr0   rJ  r   settlebaseIdquoteIdsettleIdr  r?   rB   r  contractr   takerFeemakerFeeoptionStrikePricelotSizetickSize)r  pricer	  maxPrice)leverager  r  cost)r   quantotakermakercontractSizerp  expiryDatetimestrike
optionTyper  r  createdr  )r!  r"  r#  safe_string_2r%  r+   rC  
string_abs	parse8601yymmddsafe_number)r   rL  r0   rv  rw  rx  ru  r`  r@   r>   rA   r  rJ  r   ry  r  rf  rg  r   statusr  rp  r  rN  multiplierString
positionIdr   positionIsQuoters  rt  maxLeverages                                  r   parse_marketzbitmex.parse_market  si   fh/!!&,7""6?;##FO<((2 vu-(?DDH_DDH_DFH_G%%fl;FDF&&v.''0>6OOFK8	??6:65=i-0L4!!&'26!CZ%'FCZ%'#-6F#'#5#5f>^`~# #001C1CCIY1Z[#*#5#5d6F6Fv|6\#] #001AB!--fh?N^^N3F!#F(;; F''0BLQ
**:6#u,&&v}=%%flC@
''(:(:3
(K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%%fj9(,&&v/BC**69=))&*= 6>4,,S14*2;
  #24
  ++FJ?
  *9;t$ e3
 3	
r  c                 v   d|i}t        dt        |            D ]  }||   }| j                  |d      }| j                  |      }| j	                         }| j                  |d      }| j                  |d      }	| j                  ||      |d<   | j                  ||	      |d<   |||<    | j                  |      S )Nr  r   r  availableMarginmarginBalancefreetotal)r  r   r!  r"  accountrH  safe_balance)
r   r*  r+  r,  balance
currencyIdr  r  r  r  s
             r   parse_balancezbitmex.parse_balance3  s    ` )q#h-( 		#AqkG))':>J**:6DllnG##G->?D$$Wo>E"99$EGFO#::4GGG"F4L		#   ((r  c                     | j                          ddi}| j                  | j                  ||            }| j                  |      S )ai  
        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>`
        r  all)load_marketsprivateGetUserMarginextendr  )r   r)  requestr*  s       r   fetch_balancezbitmex.fetch_balancep  sM     	
 ,,T[[&-IJ` !!(++r  NrN  r   c                    | j                          | j                  |      }d|d   i}|||d<   | j                  | j                  ||            }|g g dddd}t	        dt        |            D ]b  }||   }	|	d   dk(  rd	nd
}
| j                  || j                  |	d            }| j                  |	d      }|K||
   }|j                  ||g       d | j                  |d
   dd      |d
<   | j                  |d	   d      |d	<   |S )aA  
        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
        rN  r0   Ndepth)rN  bidsasks	timestampdatetimenoncer   sideSellr  r  sizer  T)r  rL  publicGetOrderBookL2r  r  r   rU  r!  r  appendsort_by)r   rN  r   r)  rL  r  r*  r+  r,  r   r  r  r  
resultSides                 r   fetch_order_bookzbitmex.fetch_order_book  s9    	V$fTl
 $GG,,T[[&-IJ
 q#h-( 
	3AQKE#Fmv56FD33FD<L<LUTZ<[\F$$UG4E  #D\
!!5&/2
	3 fVna>vfVna8vr  r0   c           	          dd|ii}| j                  |dd| j                  ||            }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   r   r'   r0   )r   r0   rN  r)  r  r*  
numResultss          r   fetch_orderzbitmex.fetch_order  sv     2

 $$VT49I9I&RX9YZ]
?A;DGGn4r9MIJJr  sincec                    | j                          d}| j                  |dd      \  }}|r| j                  d||||d      S d}i }|| j                  |      }|d   |d<   || j	                  |      |d<   |||d	<   | j                  |d
d      }|'| j                  |d
g      }| j	                  |      |d<   | j                  ||      }d|v r| j                  |d         |d<   | j                  |      }	| j                  |	|||      S )ax  

        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>`
        Frn   paginater9   Nr0   rN  	startTimecountuntilendTimer  )r  handle_option_and_paramsfetch_paginated_call_dynamicrL  iso8601safe_integer_2omitr   jsonprivateGetOrderparse_orders
r   rN  r  r   r)  r  rL  r  r  r*  s
             r   r  zbitmex.fetch_orders  s?    	88PZ[&44]FESXZ`beff[[(F &tGH#'<<#6GK $GG##FGY?YYvy1F!%e!4GI""7F3 w $		'(*; <GH''0  65%@@r  c           	      V    dddii}| j                  |||| j                  ||            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  openT)r  r   )r   rN  r  r   r)  r  s         r   fetch_open_orderszbitmex.fetch_open_orders  s?     

   t7G7GQW7XYYr  c                 V    | j                  ||||      }| j                  |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>`
        r  closedcanceledF)r  filter_by_array)r   rN  r  r   r)  orderss         r   fetch_closed_orderszbitmex.fetch_closed_orders+  s6     ""65%@##FHx6LeTTr  c                 *   | j                          d}| j                  |dd      \  }}|r| j                  d||||d      S d}i }|| j                  |      }|d   |d<   || j	                  |      |d<   |t        d	|      |d
<   | j                  |dd      }|'| j                  |dg      }| j	                  |      |d<   | j                  ||      }d|v r| j                  |d         |d<   | j                  |      }	| j                  |	|||      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>`
        Fri   r  r9   Nr0   rN  r  r   r  r  r  r  )r  r  r  rL  r  r
  r  r  r   r  privateGetExecutionTradeHistoryparse_tradesr  s
             r   fetch_my_tradeszbitmex.fetch_my_trades;  sH    	88R\]&44_feUZ\bdghh[[(F &tGH#'<<#6GK "3GG##FGY?YYvy1F!%e!4GI""7F3 w $		'(*; <GH77@l   65%@@r  c                 <    dddddddd}| j                  |||      S )Ntransactionr?   r   r   r   )
WithdrawalRealisedPNLUnrealisedPNLDepositTransferAffiliatePayout	SpotTrader!  )r   r  typess      r   parse_ledger_entry_typezbitmex.parse_ledger_entry_type  s5    '#%$") 
 tT22r  itemr  c                 `   | j                  |d      }| j                  |d      }| j                  |d      }d }| j                  | j                  |d            }| j                  |d      }| j                  ||      }	| j                  ||      }| j                  |d      }
| j	                  |	|
      }| j                  | j                  |d            }|d}d }| j                  |d	      }|&| j	                  |	|      }| j                  |      |	d
}| j                  |d      }|| j	                  |	|      }| j                  t        j                  | j                  |      | j                  |                  }d }t        j                  |
d      r(d}| j	                  |	t        j                  |
            }nd}| j                  | j                  |d            }| j                  |||| j                  |      ||||||	| j                  |      || j                  |      ||d|      S )N
transactIDr  txtransactTyper  r  transactTimer   r  )r  r  walletBalance0outintransactStatus)r  r0   r  r  	directionr  referenceIdreferenceAccountr  r  r  beforeafterr  r  )r!  r  r"  safe_currencyrH  r  r%  r+   
string_subrB  	string_ltr  parse_transaction_statussafe_ledger_entryr  )r   r  r  r0   r  r  r  r  r  r  rD  r  r  r  feeCostr  r  r  r  s                      r   parse_ledger_entryzbitmex.parse_ledger_entry  sK   T dL1""43&&tT2++D,<,<T>,RS%%dJ7
&&z8<%%j(;''h7,,T<@NN4#3#3D.#IJ	 I""4/11$@G))'2 C   7//e<E""7#5#5d6K6KE6RTXTiTijpTq#rs	\3/I00w7I7I,7WXFI..t/?/?FV/WX%%"Y/"& 0''/&&u-'
  ! 	r  c                     | j                          i }|||d<   d}|| j                  |      }|d   |d<   | j                  | j                  ||            }| j	                  ||||      S )a`  
        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>`
        Nr  r0   r  )r  r  privateGetUserWalletHistoryr  parse_ledger)r   r  r  r   r)  r  r  r*  s           r   fetch_ledgerzbitmex.fetch_ledger  s     	
 $GG}}T*H"*4.GJ33DKK4PQ*   8UEBBr  c                    | j                          ddi}d}|| j                  |      }|d   |d<   |||d<   | j                  | j                  ||            }| j	                  |dddgd	      }| j                  ||||      S )
as  
        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>`
        r  r  Nr0   r  r  r  r  F)r  r  r  r  r  parse_transactions)	r   r  r  r   r)  r  r  r*  transactionss	            r   fetch_deposits_withdrawalsz!bitmex.fetch_deposits_withdrawals5  s     	
 }}T*H"*4.GJ$GG33DKK4PQ++Hn|U^F_afg&&|XueLLr  r  c                 6    ddddd}| j                  |||      S )Npendingr  ok)	ConfirmedCanceled	CompletedPendingr  r   r  statusess      r   r  zbitmex.parse_transaction_statusU  s,    "" 	
 &&99r  r  c                 "   | j                  |d      }| j                  ||      }| j                  | j                  |d            }| j                  | j                  |d            }| j                  |d      }d }d }d }	|dk(  r'| j                  |d      }| j                  |d      }|}	n)|dk(  r$| j                  |d      }	| j                  |d      }| j                  |d	      }
t	        j
                  |
      }| j                  |d
   |      }| j                  |d      }| j                  |d
   |      }| j                  |d      }|| j                  |      }i d|d| j                  |d      d| j                  |d      d|d|d
   d| j                  | j                  |d      |d
         d	| j                  |      d|d|d| j                  |      d|d|d|	dd dd dd d|d d |d
   | j                  |      d ddS )Nr  r  r  r  
withdrawalr   r  r  r  r  r  r  r  r0   r  txidr  r  r  r  addressFrom	addressTotagtagFromtagToupdated)r  r  rate)internalcommentr  )r!  r  r  safe_string_lowerr+   r  rH  r  r&  r%  r  )r   r  r  r  r  r  r  r   r  r  rD  amountStringAbsr  feeCostStringr  r  s                   r   parse_transactionzbitmex.parse_transaction^  s   ( %%k:>
%%j(; ~~d&6&6{N&STNN4#3#3K#MN	%%k>B	<&&{I>G**;=KIY((i@I**;=K''X>!,,\:,,Xf-=O((e<--hv.>N!!+/?@226:F
K
$"";=
 D$$[$7
 D	

 (
 t..t/?/?Y/WYabhYij
 d''/
 f
 
 \2
 w
 ;
 
 4
 t
  T!
" y#
$ $V,))'2)
 	
r  c                    | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |d      }|t        | j                  dz   |z   dz         | j                  ||      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>`
        rN  r0   r   z fetchTicker() symbol z
 not found)r  rL  publicGetInstrumentr  r#  r$   r0   parse_ticker)r   rN  r)  rL  r  r*  tickers          r   fetch_tickerzbitmex.fetch_ticker  s     	V$fTl
 ++DKK,HI1->DGG&>>G,VWW  00r  rQ  c                     | j                          | j                  |      }| j                  |      }i }t        dt	        |            D ]0  }| j                  ||         }| j                  |d      }|,|||<   2 | j                  |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>`
        r   rN  )r  market_symbols#publicGetInstrumentActiveAndIndicesr  r   r  r!  filter_by_array_tickers)r   rQ  r)  r*  r+  r,  r   rN  s           r   fetch_tickerszbitmex.fetch_tickers  s     	%%g.;;FCq#h-( 	(A&&x{3F%%fh7F!!'v		(
 ++FHgFFr  r   c           	         | j                  |d      }| j                  ||      }| j                  | j                  |d            }| j                  |d      }| j                  |d      }| j                  i d|d|d| j	                  |      d| j                  |d      d| j                  |d	      d
| j                  |d      dd d| j                  |d      dd d| j                  |d      d|d|d|dd dd dd dd | j                  |d      | j                  |d      | j                  |d      |d|      S )NrN  r  prevPrice24h	lastPricer  high	highPricelowlowPricebidbidPrice	bidVolumeaskaskPrice	askVolumevwapr  closer   previousClosechange
percentageaveragehomeNotional24hforeignNotional24h	markPrice)
baseVolumequoteVolumer<  r  )r!  rK  r  safe_tickerr  )r   r   rL  marketIdrN  r  r  r   s           r   r  zbitmex.parse_ticker  s   ##FH5!!(F3NN4#3#3FK#HI	74 !
f!
!
 Y/!
 D$$V[9	!

 4##FJ7!
 4##FJ7!
 !
 4##FJ7!
 !
 D$$VV4!
 D!
 T!
 D!
 T!
 d!
  $!!
" t#!
$ **63DE++F4HI))&+>+!
, - 	r  c                 b   | j                  |d      }| j                  ||      }| j                  |d   | j                  |d            }| j                  | j                  |d            | j	                  |d      | j	                  |d      | j	                  |d      | j	                  |d      |gS )NrN  volumer  r  r*  r,  r5  )r!  safe_marketrU  r  r  )r   ohlcvrL  r@  rB  s        r   parse_ohlcvzbitmex.parse_ohlcv  s    $ ##E84!!(F3//x0@$BRBRSXZbBcdNN4++E;?@UF+UF+UE*UG,
 	
r  r   c                    | j                          d}| j                  |dd      \  }}|r| j                  d|||||      S | j                  |      }|d   | j	                  | j
                  ||      dd}|||d<   | j                  |d      }	|	'| j                  |dg      }| j                  |	      |d	<   | j                  |      d
z  }
| j                  | j                  dd      }|-|}|r| j                  ||
      }| j                  |      }||d<   nd|d<   | j                  | j                  ||            }| j                  |||||      }|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
        Frj   r  r0   T)rN  binSizepartialr  r  r    r   r  reverser   )r  r  "fetch_paginated_call_deterministicrL  r!  r   safe_integerr  r  parse_timeframer(  r   sumpublicGetTradeBucketedr  parse_ohlcvsr  r   )r   rN  	timeframer  r   r)  r  rL  r  r  durationr   r  r  r*  r+  r,  s                    r   fetch_ohlcvzbitmex.fetch_ohlcv  s    	88zZ&::<QVX]_hjpqq V$Tl''IN	
 $GG!!&'2YYvy1F!%e!4GI''	2T9"&..?XZ^"_I& HHY9	Y/I#,GK !%GI..t{{7F/KL ""8VYuM" 1c&k* 7%ay|h6q	!7r  r   c                    | j                  |d      }| j                  ||      }| j                  | j                  |d            }| j                  |dd      }| j	                  || j                  |dd            }| j                  | j                  || j                  |d                  }| j                  |d      }	| j                  |d	      }
| j                  |d
      }d }| j                  | j                  || j                  |d                  }|8| j                  |dd      }|| j                  |      | j                  |d      d}| j                  |d      }d }||dk(  rt        j                  |d      rdnd}| j                  |d      }| j                  ||| j                  |      ||	|
||||t        j                  |      ||d|      S )NrN  r  avgPxr  r  lastQtyexecCost
trdMatchIDr  r  execCommr_  r  
commission)r  r  r  execTyper   r  r  r  ordType)r  r  r  rN  r0   r   r  takerOrMakerr  r  r  r  r  )r!  rK  r  r  rU  rB  rW  r  r"  r+   r  
safe_trader  r  )r   r   rL  r@  rN  r  priceStringrD  rW  r0   r   r  r  r  r  r[  r]  r  s                     r   parse_tradezbitmex.parse_tradeU  s   J ##E84!!(F3NN4#3#3E;#GH	((A55fd>P>PQVX^`i>jk(()C)CFDL\L\]bdnLo)pqe\2  	2%%eV4--d.H.HQUQaQabgisQt.uv$++E?JOJ% 33J?((=C ##E:6$W)<&-&7&7s&K7QXL%%eY7"Y/( &&x0" 
  	r  c                 F    ddddddddddddd}| j                  |||      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  sD    % "# " !
 &&99r  r   c                 6    ddddd}| j                  |||      S )NDayGTCr   r   )rq  GoodTillCancelImmediateOrCancel
FillOrKillr  )r   r   timeInForcess      r   parse_time_in_forcezbitmex.parse_time_in_force  s,    #!&	
 k;GGr  r   c           
         | j                  |d      }| j                  ||      }|d   }| j                  |d      }d }d }d}|#| j                  | j                  dd      }	|	dk(  }n| j                  |dd      }|r| j	                  ||      }n| j	                  ||      }| j                  |d      }
d }| j                  | j	                  || j                  |d                  }|rt        j                  ||
      }n|}| j                  |d	      }d }||d
k(  }| j                  | j                  |d            }| j                  |d      }| j                  |d      }| j                  i d|d| j                  |d      d| j                  |d      d|d| j                  |      d| j                  | j                  |d            d|d| j                  |d      d| j                  | j                  |d            d|d| j                  |d      d| j                  |d      d|d|d|d|
d || j	                  ||      | j                  | j                  |d!            d d d"|      S )#NrN  orderQtyFdefaultSubTyper   r   rU  cumQtyexecInstParticipateDoNotInitiater  stopPx	leavesQtyr  r0   r  clientOrderIdclOrdIDr  lastTradeTimestampr  r  r\  r   postOnlyr  r  r   r  r  r9  filled	ordStatus)	remainingr  r  trades)r!  rC  r   r(  rU  rB  r+   rC  r  r  
safe_orderr  r  rw  ro  )r   r   rL  r@  rN  qtyr  r  rf  rz  r9  r  r{  r|  r  r  r   r  s                     r   parse_orderzbitmex.parse_order  s   L ##E84!!(F3!uj1	!--dll<LhWN'94Ivy%@I11&#>D33FC@F""5'2&&t'E'EfdN^N^_dfnNo'pq''8FF##E:6 $>>HNN4#3#3E;#GH	''x8$$UK8	  
E 
$""5)4 
 T--eY? 
 	 

 Y/ 
 !$..1A1A%1X"Y 
 f 
 D**5)< 
 433D4D4DUM4Z[ 
  
 D**5&9 
 T%%eW5 
 L 
 f 
 D 
  w! 
" f# 
$ 77	J--d.>.>uk.RS+ 
, - 	r  c                    | j                          d}| j                  |dd      \  }}|r| j                  d||||      S | j                  |      }d|d   i}|| j	                  |      |d<   nd|d<   |t        |d	      |d
<   | j                  |dd      }|'| j                  |dg      }| j	                  |      |d<   | j                  | j                  ||            }	| j                  |	|||      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>`
        Frw   r  rN  r0   r  TrJ  rI  r  r  r  )r  r  r  rL  r  r
  r  r  publicGetTrader  r  r  s
             r   fetch_tradeszbitmex.fetch_trades9  s    	88PZ[&44]FESXZ`aaV$fTl
 #'<<#6GK  "&GI"5$/GG##FGY?YYvy1F!%e!4GI&&t{{7F'CD:   65%@@r  r  r  r  c                 @   | j                          | j                  |      }| j                  |      }| j                  |d      }	|	+|d   s&|d   s!t	        | j
                  dz   |d   z   dz         | j                  | j                  dd	      }
| j                  | j                  ||            }|d
   | j                  |      |||
d}| j                  |g d      }| j                  |dd      }|du}|du}|s|r| j                  |d      }|dk(  }|dk(  s|dk(  r| j                  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}|rI|dk(  xr |dk(  xs |dk(  }|dk(  xr |dk(  xs |dk(  }|s|rd|z   }| j                  |      |d<   d|d<   nD|t        | j
                  dz   |z   dz         | j                  | j                  ||            |d <   ||d!<   | j!                  |g d"      }|d#k(  s
|dk(  s|dk(  r$| j                  | j                  ||            |d$<   | j                  |d%d&      }|||d%<   | j!                  |d%d&g      }| j#                  | j%                  ||            }| j'                  ||      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 - '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>`
        
reduceOnlyNr@   rA   z/ createOrder() does not support reduceOnly for r  zI orders, reduceOnly orders are supported for swap and future markets onlybrokerIdCCXTr0   )rN  r  ry  r\  text)r   r~  	stopPricetrailingAmountpegOffsetValuer   abover   rL  rJ   belowbuy	StopLimitLimitIfTouchedStopMarketIfTouchedsellrq  TrailingStopPegpegPriceTypez9 createOrder() requires a triggerPrice parameter for the z order typer~  r\  )r   r  r~  r   r  Limitr  r  r  )r  rL  
capitalizer#  r&   r0   r!  r   parse_to_intrM  safe_number_nr  check_required_argumentparse_to_numericr"   price_to_precisionr  privatePostOrderr  r  )r   rN  r  r  r  r  r)  rL  	orderTyper  r  r  r  r   r  isTriggerOrderisTrailingAmountOrderr   triggerAboveisStopSellOrderisBuyIfTouchedOrderr  r*  s                          r   create_orderzbitmex.create_ordery  s7   " 	V$OOD)	__V\:
!6NVH-="477-^#^aghnao#o  s~  $~    ##DLL*fE 8 8 HITlOOD) 
 ))&2YZ++F4DFVW%T1 .d :2#//8JK,7LTX%5,,]<LN`cjlsbtuw5=/;AQI4@ 0kI!5=*6<MI5A 1vI$#'6>"lf9L8kR[_jRj'+u}&IIZ<Z;~`im}`}#"&9%(>%9N,0,A,A.,Q()*;''+DGG6q,qt},}  AN  -N  O  O$($9$9$:Q:QRXZf:g$h!!*GIYYv'tuF i;&>IQaDa#44T5L5LVUZ5[\GG**69oN$!.GIYYv	?'CDF((Wf)EF&11r  c                 x   | j                          i }| j                  |dd      }	|	d u}
|
r| j                  |d      }|dk(  }|dk(  s|dk(  r| j                  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(  xr |dk(  xs |d
k(  }|d	k(  xr |dk(  xs |dk(  }|s|rd|	z   }	| j	                  |	      |d<   | j                  |ddg      }| j                  |dd      }|4||d<   | j                  |dd      }|||d<   | j                  |g d      }n||d<   |&| j                  | j                  ||            }||d<   |||d<   | j                  | j                  dd      }||d<   | j                  | j                  ||            }| j                  |      S )Nr  r  r   r  r   rL  rJ   r  r  r  r  r  r  r  rq  origClOrdIDr  r  )r  r  r  r  ry  r  r  r  r  )r  r  r!  r  r  r  r  rM  r   privatePutOrderr  r  )r   r0   rN  r  r  r  r  r)  r  r  r  r   r  r  r  r  r  r  r  r  r*  s                        r   
edit_orderzbitmex.edit_order  s3   ++F4DFVW .d : #//8JK,7LTX%5,,]<LN`cjlsbtuIw5=/;AQI4@ 0kI!5=*6<MI5A 1vI#v~hY&5H4gi[fNfO#'5="{	EV8V7z\eiy\y"5!$~!5(,(=(=n(MG$%YYv(:<L'MNF((P"%0GM" ,,VYPM(%2	"YYv'RSF!#GI##D$<$<VV$LMC"%GJ$GG##DLL*fE"''GV(DE))r  c                    | j                          | j                  |dd      }i }|||d<   n||d<   | j                  |ddg      }| j                  | j	                  ||            }| j                  |di       }| j                  |d      }|/|j                  d      dk\  rt        | j                  dz   |z         | j                  |      S )ay  
        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>`
        r  r  r  r   errorr   z cancelOrder() failed: )r  safe_value_2r  privateDeleteOrderr  r#  r!  findr'   r0   r  )	r   r0   rN  r)  r  r  r*  r   r  s	            r   cancel_orderzbitmex.cancel_order  s     	))&)_M !#GI!.GIYYv	?'CDF**4;;w+GH!R0  0zzHIQN#DGG.G$G%$OPP&&r  c                     | j                          | j                  |dd      }i }|||d<   n||d<   | j                  |ddg      }| j                  | j	                  ||            }| j                  |      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>`
        r  r  r  )r  r  r  r  r  r  )r   idsrN  r)  r  r  r*  s          r   cancel_orderszbitmex.cancel_orders  s     	))&)_M !$GI!.GIYYv	?'CDF**4;;w+GH  **r  c                     | j                          i }d}|| j                  |      }|d   |d<   | j                  | j                  ||            }| j	                  ||      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   rN  )r  rL  privateDeleteOrderAllr  r  )r   rN  r)  r  rL  r*  s         r   cancel_all_orderszbitmex.cancel_all_orders'  sm     	[[(F &tGH--dkk'6.JKP   622r  timeoutc                     | j                          d|dkD  r| j                  |dz        ndi}| j                  | j                  ||            }|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
        r  r   rI  )r  r  privatePostOrderCancelAllAfterr  )r   r  r)  r  r*  s        r   cancel_all_orders_afterzbitmex.cancel_all_orders_aftera  sW     	Wq[t((48q
 66t{{7F7ST r  c                 l    | j                          | j                  ||      }| j                  ||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>`
        rN  )r  fetch_positionsparse_leverages)r   rQ  r)  	leveragess       r   fetch_leverageszbitmex.fetch_leveragesx  s7     	((&9	##IwAAr  r  c                     | j                  |d      }|| j                  ||      | j                  |d      | j                  |d      | j                  |d      dS )NrN  r   r  )r  rN  r   longLeverageshortLeverage)r!  rK  r  rL  )r   r  rL  r@  s       r   parse_leveragezbitmex.parse_leverage  sa    ##Hh7&&x800<H --h
C!..xD
 	
r  c                     | j                          | j                  |      }| j                  ||      }| j                  |d|d      S )at  
        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>`
        rN  F)r  privateGetPositionparse_positionsfilter_by_array_positions)r   rQ  r)  r*  resultss        r   r  zbitmex.fetch_positions  sL     	**62D &&x9--gx%PPr  r   c                 p   | j                  | j                  |d      |      }|d   }| j                  |d      }| j                  |d      }|du rdnd}t        j                  | j                  |dd            }| j                  |d	      }| j                  || j                  |d
            }	| j                  || j                  |d            }
| j                  t        j                  | j                  |d                  }| j                  |d      }d }| j                  |d      }||d   dk(  rd}nd}| j                  i d|d| j                  |d      d|d| j                  |      d|dd dd d|d|d|d| j                  |d      d| j                  |d      dd d| j                  |      d| j                  |d      d d d!| j                  |d"      | j                  |d#      |	| j                  |d$      |
| j                  |d%      |d | j                  |d&      d d d'
      S )(NrN  r  crossMarginTcrossisolatedforeignNotionalhomeNotionalru  maintMarginunrealisedPnl
currentQtyr  r   rq  shortlongr  r0   r  r  lastUpdateTimestampr   r  	contracts
entryPriceavgEntryPricer<  r)  notionalr  
collateralinitialMarginrt  initMarginReqmaintMarginReqliquidationPriceunrealisedPnlPcnt)
initialMarginPercentagemaintenanceMarginmaintenanceMarginPercentageunrealizedPnlr  r   marginRatior8  r   r   )rC  r!  r#  r+   r  r  rH  r%  r  safe_positionr  )r   r   rL  rN  r  r  r   notionalStringsettleCurrencyCoder  r  r  r  r  r  s                  r   parse_positionzbitmex.parse_position 	  s   @ !!$"2"28X"FO!##Hk:ooh>!,!4W:
 ++D,>,>xIZ\j,kl!--fh? 778JDL\L\]egtLuv334FHXHXYacrHst%%g&8&89I9I(T`9a&bc	''?''.A#A#%!! #
H#
$""8Y7#
 f#
 1	#

 #
 "4#
 d#
 D#
 #
 L#
 $**8_E#
 ))(K@#
 #
 )).9#
 ((:>#
  $!#
" T--hE##
$ (,'7'7/'R!2+/+;+;HFV+W* $ 0 0;M N$**85HI!#7#
  	r  r   c                    | j                  ||      \  }}| j                  |       | j                          | j                  |      }| j	                  ||      }d}| j                  |      \  }}|d   ||| j                  ||d         d}	| j                  | j                  | j                        |	d<   | j                  | j                  |	|            }
| j                  |
|      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   r  )r  r  r   r  otpToken)handle_withdraw_tag_and_paramscheck_addressr  r  rF  handle_network_code_and_paramsnetwork_code_to_idtwofatotp privatePostUserRequestWithdrawalr  r  )r   r  r  r   r  r)  r  r  networkCoder  r*  s              r   r   zbitmex.withdraw	  s     99#vFV7#==&++D&9"AA&IV ..{HV<LM	
 ::!"&))DJJ"7GJ88Wf9UV$ %%h99r  c                    | j                          | j                  |      }g }t        dt        |            D ]Q  }||   }| j	                  |d      }| j                  |      }| j                  |dd      }	|	sA|j                  |       S | j                  |      }| j                  |      }
| j                  |
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
        r   rN  r@   F)r  r$  r  r   r!  rC  r(  r  r#  parse_funding_ratesr  )r   rQ  r)  r*  filteredResponser,  r  r@  rL  r@   r+  s              r   fetch_funding_rateszbitmex.fetch_funding_rates	  s     	;;FCq#h-( 	.AA;D''h7H%%h/F>>&&%8D ''-	. %%g.))*:;##FHg>>r  c                    | j                  |d      }| j                  |d      }| j                  |d      }i d|d| j                  ||      d| j                  |d      dd dd d| j                  |d	      d| j                  |      d
|d| j                  |d      d| j                  |      d|d| j                  |d      dd dd dd dd dd dd iS )Nr  rN  fundingTimestampr  r<  
indexPriceinterestRateestimatedSettlePriceindicativeSettlePricer  fundingRatefundingDatetimenextFundingRateindicativeFundingRatenextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetimeintervalr!  rK  r  r  )r   ry  rL  r  r@  r  s         r   parse_funding_ratezbitmex.parse_funding_rate	  sl   ##Hk:##Hh7**85GH
H
d&&x8
 ))(K@
 $	

 D
 #D$4$4X?V$W
 1
 
 4++HmD
  ?
 
 t//:QR
 #D
 "4
 "4
  '!
" &t#
$ %
 	
r  c                    | j                          i }d}|| j                  v r| j                  |      }|d   |d<   n}|{|j                  d      }t	        |      }	g d}
|	dkD  r=| j                  |d   |
      r(| j                  |d         }|d   dz   |d   z   }||d<   n| j                  |      }|d   |d<   || j                  |      |d<   |||d	<   | j                  |d
      }| j                  |d
g      }|| j                  |      |d<   ||d|d<   | j                  | j                  ||            }| j                  ||||      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   rN  rk  )nearestdailyweeklymonthly	quarterlybiquarterly	perpetualr   r   r  r  r  r  TrJ  )r  
currenciesr  splitr   rP  rL  r  rL  r  publicGetFundingr  parse_funding_rate_histories)r   rN  r  r   r)  r  rL  r  splitSymbolsplitSymbolLengthr   r  r*  s                r   fetch_funding_rate_historyz!bitmex.fetch_funding_rate_history	  s{   " 	T__$==(D $T
GH ,,s+K #K 0kJ!A%4==Q+T}}[^4dc)KN:$*!V,$*4L!#'<<#6GK $GG!!&'26G9-!%e!4GIM!%GI((Wf)EF 0065%PPr  c                     | j                  |d      }| j                  |d      }|| j                  ||      | j                  |d      | j                  |      |dS )NrN  r  r  )r  rN  r  r  r  r  )r   r  rL  r@  r  s        r   parse_funding_rate_historyz!bitmex.parse_funding_rate_history/
  sd     ##D(3##D+6&&x8++D-@1 
 	
r  c                 ^   |t        | j                  dz         |dk  s|dkD  rt        | j                  dz         | j                          | j	                  |      }|d   dk7  r |d   dk7  rt        | j                  dz         |d	   |d
}| j                  | j                  ||            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
        z) setLeverage() requires a symbol argumentg{Gz?r9   z( leverage should be between 0.01 and 100r  r@   rA   z6 setLeverage() supports future and swap contracts onlyr0   )rN  r  )r"   r0   r#   r  rL  r$   privatePostPositionLeverager  )r   r  rN  r)  rL  r  s         r   set_leveragezbitmex.set_leverageC
  s     >#DGG.Y$YZZtOCTWW'QQRRV$&>V#v((BDGG&^^__Tl 
 //GV0LMMr  r   c                    |t        | j                  dz         |j                         }|dk7  r|dk7  rt        | j                  dz         | j	                          | j                  |      }|d   dk7  r |d   dk7  rt        | j                  dz         |dk(  rd	nd
}|d   |d}| j                  | j                  ||            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
        z+ setMarginMode() requires a symbol argumentr  r  z@ setMarginMode() marginMode argument should be isolated or crossr  r@   rA   z8 setMarginMode() supports swap and future contracts onlyFTr0   )rN  r  )	r"   r0   lowerr#   r  rL  r$   privatePostPositionIsolater  )r   r   rN  r)  rL  r  r  s          r   set_margin_modezbitmex.set_margin_mode\
  s     >#DGG.[$[\\%%'
#
g(=TWW'iijjV$6Nf$6&>X+EDGG&``aa&'1%Tl
 ..t{{7F/KLLr  c                    | j                          d}| j                  |      \  }}|t        | j                  dz         | j	                  |      }| j                  |d      }|d   | j                  ||d         d}| j                  | j                  ||            }||||j                  dd      j                  dd      dd	S )
aI  
        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   r  )r  r  " )r  r  r  r   r  )
r  r  r"   r0   r  r  r  privateGetUserDepositAddressr  replace)r   r  r)  r  r  r  r*  s          r   fetch_deposit_addresszbitmex.fetch_deposit_addressw
  s     	"AA&IV#DGG._$_``==&69- ..{HV<LM
 44T[[&5QR
 "''R088bA
 	
r  c                     | j                  |dg       }t        |      }|d d dd d di d}|dk7  r| j                  |d      }| j                  |      }t	        d|      D ]  }||   }	| j                  |	d      }
| j                  |d      }| j                  |
|      }| j                  |	d      }| j                  t        j                  ||            }d d d|d	dd
|d   |<   |dk(  s||d   d<   d	|d   d<    |S )Nr   )r  r8  )r  r   r  r   r   r  r  r  r  F)r  r   r   r   r  r8  )	r#  r   r!  r$  r  r&  r%  r+   r'  )r   r  r  r   networksLengthr+  r  r  r,  r  r2  currencyCoder  withdrawalFeeIdr  s                  r   parse_deposit_withdraw_feez!bitmex.parse_deposit_withdraw_fee
  sG   6 ??3
B7X"
 " 
 Q$$S'2E,,U3I1n- ="1+ ,,Wg>	#//&A"55iN"&"2"27O"L $ 1 1'2D2D_V_2` a'+4@(5U K3z";/ "Q&0=F:&u-7<F:&|4= r  codesc                 j    | j                          | j                  |      }| j                  ||d      S )av  
        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>`
        r  )r  r  parse_deposit_withdraw_fees)r   r3  r)  assetss       r   fetch_deposit_withdraw_feesz"bitmex.fetch_deposit_withdraw_fees
  s7     	++F3< //wGGr  c                 b    | j                  d      }| j                  |dd      }|dk7  r|r|S y|S )NFr  r      )check_required_credentialsr#  )r   r   methodpathr)  configisAuthenticatedr  s           r   calculate_rate_limiter_costz"bitmex.calculate_rate_limiter_cost   s;    99%@vvq119r  c                 b   | j                          d}| j                  |dd      \  }}|r| j                  d||||      S | j                  |      }d|d   i}|||d<   |||d<   | j	                  d||      \  }}| j                  | j                  ||            }| j                  ||||      S )	at  
        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>`
        Frc   r  rN  r0   r  r  r  )r  r  r  rL  handle_until_optionpublicGetLiquidationr  parse_liquidations)	r   rN  r  r   r)  r  rL  r  r*  s	            r   fetch_liquidationszbitmex.fetch_liquidations
  s     	88ATV`a&445H&RWY^`fggV$fTl
 #(GK $GG229gvN,,T[[&-IJ &&xFFr  c                     | j                  |d      }| j                  || j                  ||      d | j                  |d      | j                  |d      d d d d d	      S )NrN  r  r  )	r  rN  r  r  r  	baseValue
quoteValuer  r  )r!  safe_liquidationrK  r  )r   r   rL  r@  s       r   parse_liquidationzbitmex.parse_liquidation4  sp     ##K:$$&&x8 ,,V^D%%k7;
&
 
 
	r  reasonr   r;  headersbodyc
                 x   |y |dk(  rt        | j                  dz   |z         |dk\  r| j                  |di       }
| j                  |
d      }| j                  dz   |z   }| j	                  | j
                  d   ||       | j                  | j
                  d   ||       |dk(  rt        |      t        |      y )Ni   i  r  messager   r   )	r(   r0   r#  r!  throw_exactly_matched_exceptionr   throw_broadly_matched_exceptionr#   r   )r   r  rJ  r   r;  rK  rL  r*  requestHeadersrequestBodyr  rO  feedbacks                r   handle_errorszbitmex.handle_errorsK  s    3; 3!5663;OOHgr:E&&ui8Gww}t+H001I7T\]001I7T\]s{ **))r  c                 "    | j                         S N)milliseconds)r   s    r   r  zbitmex.nonce[  s      ""r  r   GETc                 *   d| j                   z   dz   |z   }|dk(  r|rW|d| j                  |      z   z  }n?| j                  |d      }|+|d| j                  d|i      z   z  }| j                  |d      }| j                  d   |   |z   }	| j                  d      }
|dk(  s|d	k(  r|
r| j                          ||z   }| j                  | j                  d
      }d| j                  d}| j                  | j                         |      }t        |      }||z  }||d
<   |dk(  s
|dk(  s|dk(  r|r| j                  |      }||z  }| j                  | j                  |      | j                  | j                        t         j"                        |d<   |	|||dS )Nz/api/rj  rY  ?_formatr   Fr   r   r   zapplication/json)zContent-Typezapi-keyPOSTPUTDELETEzapi-signature)r   r;  rL  rK  )r5   	urlencoder!  r  r   r:  rL  r   r   rN  secondsstrr  hmacencodesecrethashlibsha256)r   r<  r   r;  r)  rK  rL  queryformatr   r>  authexpiresstringExpiress                 r   signzbitmex.sign^  s   $,,&,t3U?t~~f555%%fi8F!t~~y&.ABBB695iis#e+99%@)xO++-E>D''mDG 2;;G hht||~w7GLMM!D%2GM"6U?f6H99V,DDLD'+yyT1BDKKPTP[P[D\^e^l^l'mGO$fdwOOr  )rJ  rW  )]__name__
__module____qualname__r   r   r   r?  rF  r   rH  rM  rU  rW  r   r   r[  dictr  r   r  r  rb  r
   r   r  r  r   r  r  r  r  r  r   r   r  r  r   r  r  r  r   r!  r   r   r&  r  listrE  rS  r   r`  ro  rw  r  r  r   r   floatr   r  r  r  r  r  r  r   r  r   r  r   r  r  r   r   r  r   r  r  r   r#  r'  r	   r-  r2  r7  r?  rD  rI  intrU  r  rm  __classcell__)r   s   @r   r-   r-      s   z# zx ') ~Z ~@.53 5 5G
.L $& y,$v, y,vw
4 w
F w
r;) ;)z $& =,( =,~ :>b (s (3 (Y (T 26b Kc K3 K, *.Dt\^ 'A3 'Ac 'A 'Acghmcn 'AR /3TXac Z Z3 Zc Zhlmrhs Z& 154VZce U# US UPS Ujnotju U  -1tRV_a [Ac [A [AC [Az
3]t ]x ]; ]~ (,$TZ\ 0C 0CC 0Cs 0Caefqar 0Cd 6:[_hj Ms M# MUX Most  pA M@:s :G
T G
X G
Q\ G
R 02 13 1f 1* 04B GW G7 G,4  6 >
 
4 
< 26DW[df D# Dc DQT Dkoptku DLl lv l l\: :"Hs HZ Zv Z Zx 6:UW >A3 >As >A# >A\`af\g >A@ gksu J23 J2i J2y J2RW J2`c J2X `drv  @B ,*S ,*# ,*Y ,*i ,*Y\ ,*lo ,*\ 37r 's 'C '8 04B + +0 /32 83 83t <> s . 26b Bw BY B
t 
V 
x 
 26b nQw nQT(^ nQ`Nt NV N` DHPR 0:S 0:% 0:# 0:Wb 0:d 6:" ?7 ? ?2
6 
[ 
4 8<$]ajl 8Q 8QC 8QWZ 8Qt
v 
( 9=R NS N# N2 >B" M# Ms M6 79  
#  
^  
D: :x <@ )H )HV MO  <@d[] (G (GS (G (GTV .# s  c TX `c  # &eBSW Pr  r-   )2ccxt.base.exchanger   ccxt.abstract.bitmexr   rf  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~     sv    ( ,  P  P  P  P  P  P  P  * 0 - . ' & . ) * + 1 4 %a-PX{ a-Pr  