
    i                    \   d dl mZ d dlmZ d dlZd dlZd dlZd dlmZm	Z	m
Z
mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ d dlmZ d dl m!Z! d dl m"Z" d dl m#Z# d d	l m$Z$ d d
l m%Z% d dl m&Z& d dl m'Z' d dl m(Z( d dl m)Z) d dl m*Z* d dl m+Z+ d dl,m-Z- d dl.m/Z/  G d dee          Z0dS )    )Exchange)ImplicitAPIN)Balances
CurrenciesCurrencyIntLeverage
MarginModeMarginModificationMarketNumOrder	OrderBookOrderRequest	OrderSide	OrderTypePositionStrStringsTickerTickersTradeTransactionTransferEntry)List)ExchangeError)AuthenticationError)PermissionDenied)AccountSuspended)ArgumentsRequired)
BadRequest)	BadSymbol)InsufficientFunds)OrderNotFound)NotSupported)DDoSProtection)DECIMAL_PLACES)Precisec                       e Zd Z fdZi fdZi fdefdZd Zd Zde	fdZ
i fdee	         fdZd	d
d
i fdedededee         fdZdlde	defdZd
d
i fdedededee         fdZdlde	defdZd
i fdededefdZi fdefdZd
i fdefdZdlde	fdZd
d
d
i fdededefdZi fdefdZdlde	fdZi fdedefdZ d
i fdede!fdZ"dlde#de	defdZ$i fde%fdZ&de%fd Z'd
i fdefd!Z(dlde	fd"Z)i fded#e*d$e+fd%Z,i fded$e+fd&Z-i fded$e+fd'Z.d
i fded(e/d#e*d)e+d*e0f
d+Z1d
i fded(e/d#e*d)e+d*e0f
d,Z2i fd-ee3         fd.Z4d/ Z5d0 Z6dlde	de7fd1Z8d2 Z9d
i fd3edefd4Z:d
i fdefd5Z;d
i fd6ee         defd7Z<d
i fd3edefd8Z=d
d
d
i fdedededee7         fd9Z>d
d
d
i fdedededee7         fd:Z?d
d
d
i fdedededee7         fd;Z@i fd<ed)e+d=ed>edeAf
d?ZBd
d
d
i fd<ededefd@ZCdldAeDfdBZEi fd<efdCZFi fd<efdDZGdldAeDfdEZHd
d
d
i fd<edededeeI         fdFZJd
d
d
i fd<edededeeI         fdGZKdldAeDdeIfdHZLdIefdJZMd
i fdKedefdLZNi fded)e+deOfdMZPi fded)e+deOfdNZQi fded)e+deOfdOZRdlde	deOfdPZSi fdedeTfdQZUdldeTfdRZVd
i fdSedefdTZWd
d
d
i fdededefdUZXdldAeDfdVZYd
i fdWefdXZZd
i fd<ed)e+fdYZ[dZ Z\d
d
d
i fdededefd[Z]dlde	fd\Z^d
i fded#e*de7fd]Z_i fdee`         fd^Zad
i fdefd_Zbd
i fd`ecdefdaZdd
d
i fd3eded(e/d#e*d)e0d*e0de7fdbZei fdedeffdcZgdldeffddZhdedfi d
d
fdgZidh Zjdiecf fdjZkdk Zl xZmS )mbingxc                    |                      t          t          |                                           i ddddddgddd	d
dddddi dd ddddddddddddddddddddddddddddddd di d!dd"dd#dd$dd%dd&dd'dd(dd)dd*dd+dd,dd-d.d/dd0dd1dd2di d3dd4dd5dd6dd7dd8dd9dd:dd;dd<dd=dd>dd?dd@ddAddBddCddddddddddddD
dEdFdGdHdIdIdIdIdIdIdIdIdJddKidLdMdNdOdPddQ|                     dR          |                     dR          dSdT|                     dU          |                     dV          dSdWdXdddYdZdQd[d[d[d[d[d\d]id[d[d[d[d[d[d^d[d[d[d[d[d[d\d_d`dadbd[d[d[d[dcddd[id`idedQdfd\iid\d\d\d\dgd\d\d\dhd`dadQd[d\d\d\d\d\d\d\d\d\d\diid[d[d[d[d[d[d[d[d[d[d[d[d[d[djd[d[d[d[d[d[d[dkd[d[d[dldmdadndQdod\iiidpd
dbdQd[d[d[dqiiid
dbd[d\d\d\d\d\drd[d[d[d\dsd`iid
dbd[d[d\dtd[d[d[d[d[dud`iid
dbdvd\idwd[id`iidxdbdyd\idyd\idziid
dbd{d\id\d\d\d|d`iid}dbd\d\d\d~ddd\id`iid	dddddddddddddddddt
          di dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          t          t          t          t          t          t          t          t          t          d	i ddddidddddddddddddddddddi          S )Nidr*   nameBingX	countriesUS	rateLimit  versionv1	certifiedTprohasCORSspotmarginFswapfutureoption	addMargincancelAllOrderscancelOrdercancelOrderscloseAllPositionsclosePositioncreateMarketBuyOrderWithCostcreateMarketOrderWithCostcreateMarketSellOrderWithCostcreateOrdercreateOrders$createOrderWithTakeProfitAndStopLosscreateStopLossOrdercreateTakeProfitOrdercreateTrailingAmountOrdercreateTrailingPercentOrdercreateTriggerOrderfetchBalancefetchClosedOrdersfetchCurrenciesfetchDepositAddressfetchDepositAddressesByNetworkfetchDepositsfetchDepositWithdrawFeeemulatedfetchDepositWithdrawFeesfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchLeveragefetchLiquidationsfetchMarginAdjustmentHistoryfetchMarginModefetchMarketsfetchMarkOHLCVfetchMyLiquidations
fetchOHLCVfetchOpenInterestfetchOpenOrders
fetchOrderfetchOrderBookfetchOrdersfetchPositionModefetchPositionsfetchTickerfetchTickers)
	fetchTimefetchTradesfetchTransfersfetchWithdrawalsreduceMarginsetLeverage	setMarginsetMarginModesetPositionModetransferhostnamez	bingx.comurlszwhttps://github-production-user-asset-6210df.s3.amazonaws.com/1294454/253675376-6983b72e-4999-4549-b177-33b374c195e3.jpgz#https://open-api.{hostname}/openApi)r9   r;   contractwalletsuser
subAccountaccountcopyTradingz'https://open-api-vst.{hostname}/openApizhttps://bingx.com/z!https://bingx-api.github.io/docs/zhttps://bingx.com/invite/OHETOM)logoapitestwwwdocreferralfeesgetz0.001)feeSidemakertakerquotez0.0002z0.0005)	tierBasedr9   r;   requiredCredentials)apiKeysecretr         )server/timezcommon/symbolszmarket/tradeszmarket/depthzmarket/klinezticker/24hr)ztrade/querytrade/openOrdersztrade/historyOrdersztrade/myTradesuser/commissionRatezaccount/balance)trade/orderztrade/canceltrade/batchOrdersztrade/order/cancelReplaceztrade/cancelOrdersztrade/cancelOpenOrdersztrade/cancelAllAfter)r   post)publicprivater   )zget/asset/transferasset/transfercapital/deposit/hisreccapital/withdraw/historyzpost/asset/transfer)r4   v3zticker/price)positionSide/dualzmarket/markPriceKlinesztrade/batchCancelReplaceztrade/fullOrder)ztrade/cancelReplacer   ztrade/closePosition)r   zquote/contractszquote/pricezquote/depthzquote/tradeszquote/premiumIndexzquote/fundingRatequote/klineszquote/openInterestzquote/tickerquote/bookTicker)zuser/balancezuser/positionszuser/incomer   ztrade/openOrderr   trade/marginTypetrade/leverageztrade/forceOrdersztrade/allOrdersztrade/allFillOrderszuser/income/exportr   r   )r   r   ztrade/closeAllPositionsr   r   ztrade/positionMarginztrade/order/test)r   r   ztrade/allOpenOrders)r   r   deleter   r   )r4   v2r   )allPosition	allOrdersbalance)zcapital/config/getallzcapital/deposit/addresszcapital/innerTransfer/recordsz"capital/subAccount/deposit/addresszcapital/deposit/subHisrecz(capital/subAccount/innerTransfer/records)zcapital/withdraw/applyzcapital/innerTransfer/applyz%capital/subAccountInnerTransfer/applyz capital/deposit/createSubAddress)listassetszapiKey/query)createzapiKey/createzapiKey/editz
apiKey/delupdateStatusuidz!innerTransfer/authorizeSubAccountauthuserDataStream)r   putzswap/trace/currentTrack)zswap/trace/closeTrackOrderzswap/trace/setTPSLzspot/trader/sellOrderr   )r   r   r   )	r9   r;   rx   ry   r{   r|   rz   r}   r   
timeframes1m3m5m15m30m1h2h4h6h12h1d3d1w1M)r   r   r   r   r   r   r   r   r   r   r   r   r   r   precisionMode
exceptions400401403404429418500504100001100412100202100204100400100421100440100500100503)	8000180012800148001680017100414100419100437101204)exactbroadcommonCurrenciesSNOWSnowmanoptionsFUNDPFUTURESSFUTURES)r9   r;   r<   )r   r   r   i  CCXTETHERC20BTCLTC)r   USDTUSDCr   r   )defaultTypeaccountsByTypeaccountsById
recvWindowbrokerdefaultNetworks)deep_extendsuperr*   describeparse_numberr'   r!   r   r   r&   r   r#   r"   r$   r   )self	__class__s    ^/var/www/html/crypto-bot/backend/venv/lib/python3.11/site-packages/ccxt/async_support/bingx.pyr   zbingx.describe   s
   eT 2 2 ; ; = = Y@
'Y@
GY@
 $Y@

 Y@
 tY@
 Y@
 4Y@
  >>> %> 	>
 %> %> T> "4> t> > $T>  > /> ,T> 0>  t!>" #> >$ 7%>& &t'>( ()>* ,T+>, -d->. %d/>0 1>2 $T3>4 "45>6 &t7>8 1$9>:  ;>< *:=>> +D?>@ #DA>B *4C>D $TE> > >F  G>H $UI>J /K>L "4M>N O>P !$Q>R &tS>T dU>V $TW>X "4Y>Z d[>\ !$]>^ t_>` $Ta>b !$c>d te>f g> >h "#"&$( $#!!%#' {> > >Y@
P QY@
R  RAA EDA"GD#H	 	 E ,:=# SY@
x !$!..w77!..w77   '!..x88!..x88  yY@
R "$ $SY@
Z  "/023120101/0$ $	# 014578237834$ $ 010156=>67:;89% %$ $ @ "6723:;<=	$ $ !6q%
$ 
$A- -b " .$# 67:;<=34	$ $ 895678% %$ $ , "/034/0/001675601670145$ $#" 1223/04534/04523563478677845$ $" 0156;<45238945% % 015678' '5$ $!0 0d !! .$#MM M^ !!/0-.+,$ $$
 !9:;<ABFG=>LM$ $ ;<?@IJDE	% %$ $* !()*+01$ $ +,12/0./01% %$ $& ! %q$ !DQ%	$ $	 ! 0!% !1!$	$ $	 ! 91$ ?@679:% %		$ 	$  !23:;<=$ $ !6q%	$ 	$ib b[Y@
`
  a
Y@
@ ^AY@
B :. + :	
 > + = = 1 1 / j j i m  m!" m#$ (.'**..(/5  8 ; CY@
@ 	!AY@
F %"&(# # # & (! !
 '  ##  $ $ GY@
 Y@
 Y Y Y	    c                    K   |                      |           d{V }|                     |d          }|                     |d          S )ag  
        fetches the current integer timestamp in milliseconds from the bingx server
        :see: https://bingx-api.github.io/docs/#/swapV2/base-info.html#Get%20Server%20Time
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int: the current integer timestamp in milliseconds from the bingx server
        Ndata
serverTime)swapV2PublicGetServerTime	safe_dictsafe_integer)r   paramsresponser   s       r   
fetch_timezbingx.fetch_time  sX       77???????? ~~h//  |444r   returnc                   K   |                      d          sdS |                     | j        dd          }|rdS |                     |           d{V }|                     |dg           }i }t          dt          |                    D ]V}||         }|                     |d          }|                     |          }	|                     |d          }
|                     |d          }i }d}d}d}i }t          dt          |                    D ]}||         }|                     |d	          }| 	                    |          }|                     |d
          }|                     |d          }d| 
                    |d          | 
                    |d          di}|r| 
                    |d          }|}|}|||||d|d|d	||<   ||	|d|
|d||||d||	<   X|S )a*  
        fetches all available currencies on an exchange
        :see: https://bingx-api.github.io/docs/#/common/account-api.html#All%20Coins
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        FNsandboxModer   r   coinr-   networkListnetwork	isDefaultwithdrawEnableamountswithdrawMinwithdrawMaxminmaxwithdrawFee)	infor,   r  feeactivedepositwithdraw	precisionlimits)r  coder,   r  r-   r  r  r  networksr  r  )check_required_credentials	safe_boolr   &walletsV1PrivateGetCapitalConfigGetall	safe_listrangelensafe_stringsafe_currency_codenetwork_id_to_codesafe_number)r   r   	isSandboxr   r   resultientry
currencyIdr  r-   r  r  r  r  withdrawEnableddefaultLimitsj
rawNetworkr  networkCoder  r  s                          r   fetch_currencieszbingx.fetch_currencies  sp      ..u55 	4NN4<FF	 	4DDVLLLLLLLLH ~~h33q#d))$$ /	 /	AGE))%88J**:66D##E622D..>>KHCF"OM1c+..//  (^
**:yAA"55g>> NN:{CC	"&..=M"N"Nt'7'7
M'R'R[_[k[klv  yF  \G  \G   H   H  +**:}EEC,F$*M&!*$# /!%$
) 
)%%  ! +$' F4LL r   c                    K   |                      |           d {V }|                     |d          }|                     |dg           }|                     |          S )Nr   symbols)spotV1PublicGetCommonSymbolsr   r  parse_markets)r   r   r   r   marketss        r   fetch_spot_marketszbingx.fetch_spot_markets2  si      ::6BBBBBBBB. ~~h//..y"55!!'***r   c                    K   |                      |           d {V }|                     |dg           }|                     |          S )Nr   )swapV2PublicGetQuoteContractsr  r0  )r   r   r   r1  s       r   fetch_swap_marketszbingx.fetch_swap_marketsN  sV      ;;FCCCCCCCC0 ..6266!!'***r   c                 @   |                      |d          }|                    d          }|d         }|d         }|                     |          }|                     |          }|                      |d          }|                     |          }	|                     |d          }
|
)|                     |                      |d                    }
|                     |d          }|)|                     |                      |d	                    }|	d
nd}|dk    }|d
k    }|dz   |z   }|	|d|	z   z  }|                     | j        |i           }|r|                     d          nd }|                      |d          dk    }|rd nd}|rd n|}|                     i d|d|d|d|d|	d|d|d|d|d|ddd
|ddddd|d|d||| 	                    |d          | 	                    |d           |                      |d!          |d d d d ||
d"d |                     |d#          d$| 
                    |d%d&          | 	                    |d'          d$d d d$| 
                    |d(d)          | 	                    |d*          d$d+d |d,          S )-Nsymbol-r   r   currencypricePrecisiontickSizequantityPrecisionstepSizer;   r9   /:1statusFr,   baser   settlebaseIdquoteIdsettleIdtyper:   r<   r=   r  rx   linearr   r   r   )amountpricemaxLongLeverager  minQtytradeMinQuantitymaxQtyminNotionaltradeMinUSDTmaxNotional)leveragerI  rJ  cost)inverser   r   r   contractSizeexpiryexpiryDatetimestrike
optionTyper  r  createdr  )r  splitr  r   precision_from_stringr   r   r   safe_market_structurer!  safe_number_2)r   marketr,   symbolPartsrD  rE  rB  r   r9  rC  r:  r<  rG  r9   r;   r7  r   rU  isActive	isInverseisLinears                        r   parse_marketzbingx.parse_marketj  s   fh//hhsmmQa.&&v..''00##FJ77((22**63CDD!!778H8HQ[8\8\]]N --f6IJJ$ $ : :4;K;KFT^;_;_ ` ` ,vv6v~v~e#cFl"F~~dir2226At((---T##FH55<!-DD	 +44t)) 3+
"3+
f3+
 D3+
 U	3+

 f3+
 f3+
 w3+
 3+
 D3+
 D3+
 e3+
 D3+
 e3+
 e3+
 h3+
  !3+
" h#3+
$ !%%dG44%%dG44''i88("+'   ,,V5FGG 
  --fh@RSS++FH== 
   
  --fm^TT++FMBB  $ e3+
 3+
 3+
 3 3 3	r   c                 n  K   |                      |          g}|                     | j        dd          }|s(|                    |                     |                     t          j        |  d{V }|                     |dg           }|                     |dg           }|                     ||          S )a  
        retrieves data on all markets for bingx
        :see: https://bingx-api.github.io/docs/#/spot/market-api.html#Query%20Symbols
        :see: https://bingx-api.github.io/docs/#/swapV2/market-api.html#Contract%20Information
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        r  FNr   r   )	r5  r  r   appendr2  asynciogatherr  array_concat)r   r   requestsr"  promisesspotMarketsswapMarketss          r   fetch_marketszbingx.fetch_markets  s       ++F334NN4<FF	 	=OOD33F;;<<< 2222222nnXq"55nnXq"55  k:::r   r   Nr7  sincelimitc           	        K   |                                   d{V  d}|                     |ddd          \  }}|r!|                     d|||||d           d{V S |                     |          }d|d         i}|                     | j        ||          |d<   |||d	<   |||d
<   |                     |dd          }	|	|                     |dg          }|	|d<   d}
|d         r0|                     | 	                    ||                     d{V }
n|                     |d          }|                     |d          }|dk    r0| 
                    | 	                    ||                     d{V }
n/|                     | 	                    ||                     d{V }
|                     |
dg           }t          |t                    s|g}|                     |||||          S )a  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :see: https://bingx-api.github.io/docs/#/swapV2/market-api.html#K-Line%20Data
        :see: https://bingx-api.github.io/docs/#/spot/market-api.html#Candlestick%20chart%20data
        :see: https://bingx-api.github.io/docs/#/swapV2/market-api.html#%20K-Line%20Data
        :see: https://bingx-api.github.io/docs/#/en-us/swapV2/market-api.html#K-Line%20Data%20-%20Mark%20Price
        :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 int [params.until]: timestamp in ms of the latest candle to fetch
        :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
        NFrb   paginatei  r7  r,   interval	startTimerp  untilendTimer9   rJ  markr   )load_marketshandle_option_and_params"fetch_paginated_call_deterministicr_  r  r   safe_integer_2omitspotV1PublicGetMarketKlineextend%swapV1PrivateGetMarketMarkPriceKlinesswapV3PublicGetQuoteKlines
safe_value
isinstancer   parse_ohlcvs)r   r7  	timeframero  rp  r   rr  r_  requestru  r   rJ  ohlcvss                r   fetch_ohlcvzbingx.fetch_ohlcv  s^       !!!!!!!!!88z[`aa& 	~@@vW\^cenpvx|}}}}}}}}}V$$fTl
 #..t	9UU
#(GK $GG##FGY??YYvy11F!&GI&> 	_!<<T[[RX=Y=YZZZZZZZZHH$$VW55EYYvw//F!%!K!KDKKX_agLhLh!i!iiiiiii!%!@!@WV\A]A]!^!^^^^^^^H 6266&$'' 	XF  E5IIIr   r_  c           	      .   t          |t                    r|                     |d          |                     |d          |                     |d          |                     |d          |                     |d          |                     |d          gS |                     |dd          |                     |d	          |                     |d
          |                     |d          |                     |d          |                     |d          gS )Nr   r      r         time	closeTimeopenhighlowclosevolume)r  r   r   r!  r{  )r   ohlcvr_  s      r   parse_ohlcvzbingx.parse_ohlcv  s   D eT"" 	!!%++  **  **  **  **  **  v{;;UF++UF++UE**UG,,UH--
 	
r   c                   K   |                                   d{V  |                     |          }d|d         i}|t          |d          |d<   d}d}|                     d||          \  }}|dk    r0|                     |                     ||                     d{V }n/|                     |                     ||                     d{V }|                     |dg           }	|                     |	|||          S )	a  
        get the list of most recent trades for a particular symbol
        :see: https://bingx-api.github.io/docs/#/spot/market-api.html#Query%20transaction%20records
        :see: https://bingx-api.github.io/docs/#/swapV2/market-api.html#The%20latest%20Trade%20of%20a%20Trading%20Pair
        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        Nr7  r,   d   rp  rm   r9   r   )	rx  r_  r  handle_market_type_and_paramsspotV1PublicGetMarketTradesr~  swapV2PublicGetQuoteTradesr  parse_trades)
r   r7  ro  rp  r   r_  r  r   
marketTypetradess
             r   fetch_tradeszbingx.fetch_tradesR  s5      !!!!!!!!!V$$fTl
 "5#GG
!??vW]^^
F!==dkk'SY>Z>Z[[[[[[[[HH!<<T[[RX=Y=YZZZZZZZZHD &"55  >>>r   c                 T   |                      |g d          }|                     |d          }||                     |          }|dk    rd }|                     |d          }|dnd}|                     |g d          }|                     |          }|                     |d          }	|                     |d	          }
|                     |d
d          }d }||	|s|	rdnd}|                     |dd          }|||	
|s|	rdnd}d}|                     |d          }||rdnd}|                     |d          }||rdnd}|                     |g d          }|S|d         rKd|v rG|                     |d         d          }|                     |d          }t          j	        ||          }| 
                    |                     |ddg          |||                     |          |                     |
|d|          |                     |dd          |                     |d          |                     |          ||                     |dd          |||                     t          j        |                     |d d!                              |d d"d#|          S )$N)r  filledTmTr  r   quoteQtyr9   r;   )r9  NcommissionAssetms
buyerMakerisBuyerMakerr   r   sideSsellbuyisBuyerisMaker)qtyrI  qr  r  rM  r,   tr8  orderIdr$  orJ  p
commissionn)rS  r9  rate)r,   r  	timestampdatetimer7  orderrG  r  takerOrMakerrJ  rI  rS  r  )safe_integer_nr  	parse8601safe_string_nr  r  safe_bool_2safe_string_lower_2r(   
string_mul
safe_tradeiso8601safe_symbolsafe_string_2safe_string_lowerparse_order_sider   
string_abs)r   trader_  r  
datetimeIdrS  rG  r&  currencyCoder  marketIdr  takeOrMakerr  r  r  rI  rU  r  s                      r   parse_tradezbingx.parse_trade  s   b ""5*C*C*CDD%%eZ88
!>>*--D199Dz22,vvV''/S/S/STT
..z::NN5#&&##E3//''|^LL$!-&2EaE''gK''vs;;<(am".?!?vv%%..	22#/55D..	22%,9'''K##E+A+A+ABBF6NE8I8I++F6N<NOOL%%eX66F'==F$$UT3K88T**&&xdCC''y#>>**5#66))$//'''w<<))'*<T=O=OPUWceh=i=i*j*jkk(  
  
$ %  	r   c           	      *  K   |                                   d{V  |                     |          }d|d         i}|||d<   d}d}|                     d||          \  }}|dk    r0|                     |                     ||                     d{V }n/|                     |                     ||                     d{V }|                     |di           }|                     |dd	          }	|                     ||d         |	d
ddd          S )a  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :see: https://bingx-api.github.io/docs/#/spot/market-api.html#Query%20depth%20information
        :see: https://bingx-api.github.io/docs/#/swapV2/market-api.html#Get%20Market%20Depth
        :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
        Nr7  r,   rp  rf   r9   r   r  tsbidsasksr   r   )	rx  r_  r  spotV1PublicGetMarketDepthr~  swapV2PublicGetQuoteDepthr   r{  parse_order_book)
r   r7  rp  r   r_  r  r   r  	orderbookr  s
             r   fetch_order_bookzbingx.fetch_order_book  sT      !!!!!!!!!V$$fTl
 $GG
!??@PRXZ`aa
F!<<T[[RX=Y=YZZZZZZZZHH!;;DKKQW<X<XYYYYYYYYHt NN8VR88	''	3==	$$Yx0@)VU[]^`abbbr   c                 0  K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     |dg           }|                     ||          S )a~  
        fetch the current funding rate
        :see: https://bingx-api.github.io/docs/#/swapV2/market-api.html#Current%20Funding%20Rate
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `funding rate structure <https://docs.ccxt.com/#/?id=funding-rate-structure>`
        Nr7  r,   r   )rx  r_   swapV2PublicGetQuotePremiumIndexr~  r  parse_funding_rater   r7  r   r_  r  r   r   s          r   fetch_funding_ratezbingx.fetch_funding_ratej  s       !!!!!!!!!V$$fTl
 >>t{{7TZ?[?[\\\\\\\\" ~~h33&&tV444r   r.  c                 4  K   |                                   d{V  |                     |dd          }|                     |                     |                     d{V }|                     |dg           }g }t          dt          |                    D ]}||         }|                     |d          }|                     |ddd          }	|| 	                    |	d         |          r)|
                    |                     ||	                     |S )a  
        fetch the current funding rate
        :see: https://bingx-api.github.io/docs/#/swapV2/market-api.html#Current%20Funding%20Rate
        :param str[] [symbols]: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `funding rate structure <https://docs.ccxt.com/#/?id=funding-rate-structure>`
        Nr;   Tr   r   r7  )rx  market_symbolsr  r~  r  r  r  r  safe_marketin_arrayrf  r  )
r   r.  r   r   r   filteredResponser$  itemr  r_  s
             r   fetch_funding_rateszbingx.fetch_funding_rates  s.      !!!!!!!!!%%gvt<<>>t{{6?R?RSSSSSSSS~~h33q#d))$$ 	O 	OA7D''h77H%%hdFCCFDMM&2BG$L$L ''(?(?f(M(MNNNr   c                    |                      |d          }|                     |d          }i d|d|                     ||dd          d|                     |d          d|                     |d          dd d	d d
d dd d|                     |d          dd dd dd d|d|                     |          dd dd dd S )Nr7  nextFundingTimer  r8  r;   	markPrice
indexPriceinterestRateestimatedSettlePricer  r  fundingRatelastFundingRatefundingTimestampfundingDatetimenextFundingRatenextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetime)r  r   r  r!  r  )r   rx   r_  r  r  s        r   r  zbingx.parse_funding_rate  sU    ##Hh77#00;LMM
H
d&&xfEE
 ))(K@@
 $**8\BB	

 D
 #D
 
 
 4++H6GHH
 
 t
 t
 #$8
 "4<<0D#E#E
 "4
  '!
" &t#
 	
r   c           
         K   |t          | j        dz             |                                  d{V  d}|                     |dd          \  }}|r |                     d|||d|           d{V S |                     |          }d|d         i}|||d	<   |||d
<   |                     |dd	          }||                     |dg          }||d	<   |                     | 	                    ||                     d{V }	| 
                    |	dg           }
g }t          dt          |
                    D ]}|
|         }|                     |d          }|                     ||dd          }|                     |d          }|                    |||                     |d          ||                     |          d           |                     |d          }|                     ||d         ||          S )a  
        fetches historical funding rate prices
        :see: https://bingx-api.github.io/docs/#/swapV2/market-api.html#Funding%20Rate%20History
        :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 of the latest funding rate to fetch
        :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[]: a list of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>`
        Nz5 fetchFundingRateHistory() requires a symbol argumentFrY   rr  8hr7  r,   rt  rp  ru  r   r   r8  r;   fundingTimer  )r  r7  r  r  r  r  )r    r,   rx  ry  rz  r_  r{  r|  swapV2PublicGetQuoteFundingRater~  r  r  r  r  r  r   rf  r!  r  sort_byfilter_by_symbol_since_limit)r   r7  ro  rp  r   rr  r_  r  ru  r   r   ratesr$  r%  r  symbolInnerr  sorteds                     r   fetch_funding_rate_historyz bingx.fetch_funding_rate_history  sh      >#DG.e$efff!!!!!!!!!88AZ\fgg& 	@@@AZ\bdikprvx~V$$fTl
 #(GK $GG##FG[AAYYvy11F#(GK ==dkk'SY>Z>Z[[[[[[[[ ~~h33q#d))$$ 	 	AGE''x88H**8VS&IIK))%??ILL%#//}EE& LL33      e[11009I5RWXXXr   c                 0  K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     |di           }|                     ||          S )a  
        Retrieves the open interest of a currency
        :see: https://bingx-api.github.io/docs/#/swapV2/market-api.html#Get%20Swap%20Open%20Positions
        :param str symbol: Unified CCXT market symbol
        :param dict [params]: exchange specific parameters
        :returns dict} an open interest structure{@link https://docs.ccxt.com/#/?id=open-interest-structure:
        Nr7  r,   r   )rx  r_   swapV2PublicGetQuoteOpenInterestr~  r   parse_open_interestr  s          r   fetch_open_interestzbingx.fetch_open_interest  s       !!!!!!!!!V$$fTl
 >>t{{7TZ?[?[\\\\\\\\ ~~h33''f555r   c                    |                      |d          }|                     |d          }|                     ||dd          }|                     |d          }|                     |d d d |||                     |          |d|          S )Nr  r7  r8  r;   openInterest)r7  
baseVolumequoteVolumeopenInterestAmountopenInterestValuer  r  r  )r   r  r  r!  safe_open_interestr  )r   interestr_  r  r,   r7  r  s          r   r  zbingx.parse_open_interest  s     %%h77	h11!!"fc6::''.AA&&"&!-"Y//	(
 	(
 	 	 		r   c                 .  K   |                                   d{V  |                     |          }d|d         i}d}|d         r0|                     |                     ||                     d{V }n/|                     |                     ||                     d{V }|                     |d          }|-|                     |di           }|                     ||          S |                     |di           }|                     ||          S )av  
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
        :see: https://bingx-api.github.io/docs/#/swapV2/market-api.html#Get%20Ticker
        :see: https://bingx-api.github.io/docs/#/spot/market-api.html#24%E5%B0%8F%E6%97%B6%E4%BB%B7%E6%A0%BC%E5%8F%98%E5%8A%A8%E6%83%85%E5%86%B5
        :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>`
        Nr7  r,   r9   r   r   )rx  r_  spotV1PublicGetTicker24hrr~  swapV2PublicGetQuoteTickerr  r   parse_ticker)	r   r7  r   r_  r  r   r   firstdataDicts	            r   fetch_tickerzbingx.fetch_ticker2  s:      !!!!!!!!!V$$fTl
 &> 	[!;;DKKQW<X<XYYYYYYYYHH!<<T[[RX=Y=YZZZZZZZZH~~h//NN4B//E$$UF333>>(FB77  6222r   c                   K   |                                   d{V  d}|B|                     |          }|                     |d          }||                     |          }d}|                     d||          \  }}d}|dk    r|                     |           d{V }n|                     |           d{V }|                     |d          }|                     ||          S )a&  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
        :see: https://bingx-api.github.io/docs/#/swapV2/market-api.html#Get%20Ticker
        :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   rk   r9   r   )	rx  r  r  r_  r  r
  r  r  parse_tickers)r   r.  r   r_  firstSymbolrG  r   tickerss           r   fetch_tickerszbingx.fetch_tickersL  s      !!!!!!!!!))'22G**7A66K&[1199.&RXYYf6>>!;;FCCCCCCCCHH!<<VDDDDDDDDH..622!!'7333r   tickerc                    |                      |d          }|                      |d          }|dn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$|          S )%Nr7  lastQtyr9   r;   	openPrice	highPricelowPrice	lastPricer  r  priceChangePercent% priceChanger  bidPricebidQtyaskPriceaskQtyr  r  r  r  bid	bidVolumeask	askVolumevwapr  r  lastpreviousClosechange
percentageaverage)r  r  r  )r  r  replacer   r  safe_ticker)r   r  r_  r  r  rG  r7  r  r  r  r  r  r  r,  r+  r  r  r$  r%  r&  r'  s                        r   r  zbingx.parse_tickere  s   R ##FH55""6955 "/vv!!(FD$??!4444vz22  55&&v}==%%fh77
%%f.BCC
!#++C44J!!&-88v{33<<##vz22$$VX66	vz22$$VX66	 !
f!
!
 !
 D	!

 3!
 3!
 !
 3!
 !
 D!
 D!
 U!
 D!
 T!
 f!
  *!!
" t#!
$ %&)!
 !
 !
* +  	r   c                   K   |                                   d{V  d}d}|                     |ddd          \  }}|                     dd|          \  }}|r|                     |           d{V }n=|dk    r|                     |           d{V }n|                     |           d{V }|                     |          S )a  
        query for balance and get the amount of funds available for trading or funds locked in orders
        :see: https://bingx-api.github.io/docs/#/spot/trade-api.html#Query%20Assets
        :see: https://bingx-api.github.io/docs/#/swapV2/account-api.html#Get%20Perpetual%20Swap%20Account%20Asset%20Information
        :see: https://bingx-api.github.io/docs/#/standard/contract-interface.html#Query%20standard%20contract%20balance
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.standard]: whether to fetch standard contract balances
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        NrO   standardFr9   )rx  ry  r  contractV1PrivateGetBalancespotV1PrivateGetAccountBalanceswapV2PrivateGetUserBalanceparse_balance)r   r   r   r1  r  marketTypeQuerys         r   fetch_balancezbingx.fetch_balance  s      !!!!!!!!!88Q[]bcc&&*&H&HY]_e&f&f#
O 	O!==oNNNNNNNNHH6!!!@@QQQQQQQQHH!==oNNNNNNNNHB !!(+++r   c                    |                      |d          }|                     |dd|          }d|i}t          |t                    rt	          dt          |                    D ]}||         }|                     |d          }|                     |          }|                                 }	| 	                    |dd          |	d<   |                     |d	          |	d
<   |                     |d          |	d<   |	||<   nv|                     |d          }|                     |          }|                                 }	|                     |d          |	d<   |                     |d          |	d
<   |	||<   | 
                    |          S )Nr   r   balancesr  r   assetfreeavailableBalancelockedusedtotalavailableMargin
usedMargin)r  safe_value_2r  r   r  r  r  r  r|   r  safe_balance)
r   r   r   r9  r#  r$  r   r&  r  r|   s
             r   r5  zbingx.parse_balance  s   x00$$T9j$GG(#h%% 	#1c(mm,, ' '"1+!--gw??
..z::,,.."&"4"4WfFX"Y"Y"&"2"27H"E"E#'#3#3GY#G#G &t' ))(G<<J**:66DllnnG"..x9JKKGFO"..xFFGFO"F4L  (((r   c                 n  K   |                                   d{V  |                     |          }d}|                     |ddd          \  }}d}|r|                     |           d{V }n|                     |           d{V }|                     |dg           }|                     ||          S )a_  
        fetch all open positions
        :see: https://bingx-api.github.io/docs/#/swapV2/account-api.html#Perpetual%20Swap%20Positions
        :see: https://bingx-api.github.io/docs/#/standard/contract-interface.html#Query%20standard%20contract%20balance
        :param str[]|None symbols: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.standard]: whether to fetch standard contract positions
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        Nri   r1  Fr   )rx  r  ry  contractV1PrivateGetAllPositionswapV2PrivateGetUserPositionsr  parse_positions)r   r.  r   r1  r   	positionss         r   fetch_positionszbingx.fetch_positions*  s       !!!!!!!!!%%g..88AQS]_dee& 	H!AA&IIIIIIIIHH!??GGGGGGGGH, NN8VR88	##Iw777r   c                    |                      |dd          }|                    dd          }|                     |d          }d }||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 d d d d d |                     |d          d |                     |d           d d d d!          S )"Nr7  r  r>  r8  isolatedcrossr  r,   
positionIdr;   notionalpositionValue
marginModeliquidationPrice
entryPriceavgPriceunrealizedPnlunrealizedProfitrealizedPnlrealisedProfitr,  	contractspositionAmtrU  r  r  r  positionSidehedgedr  initialMarginrR  )r  lastUpdateTimestampmaintenanceMarginmaintenanceMarginPercentage
collateralr\  initialMarginPercentagerR  marginRatiostopLossPricetakeProfitPrice)r  r.  r  safe_positionr  r!  r^  r  )r   positionr_  r  rK  rP  s         r   parse_positionzbingx.parse_positionU  s   L ##Hh;;##C-->>(J77
'/<WJ!! #
H#
$""8\::#
 d&&xfEE#
 ((?CC	#

 *#
 #
 $,,Xz<PP#
 T--h8JKK#
 4++H6FGG#
 $#
 ))(MBB#
 D#
 #
 #
 D**8^DD#
  d!#
" ##
$ #'!%+/!--hHH'+((:>>!#9#
 #
 #
   	r   r  rS  c                 P   K   ||d<   |                      |d||d|           d{V S )a  
        create a market order by providing the symbol, side and cost
        :param str symbol: unified symbol of the market to create an order in
        :param str side: 'buy' or 'sell'
        :param float cost: how much you want to trade in units of the quote currency
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        quoteOrderQtyr_  Ncreate_order)r   r7  r  rS  r   s        r   create_market_order_with_costz#bingx.create_market_order_with_cost  sB       #'&&vxtT6RRRRRRRRRr   c                 P   K   ||d<   |                      |dd|d|           d{V S )a  
        create a market buy order by providing the symbol and cost
        :param str symbol: unified symbol of the market to create an order in
        :param float cost: how much you want to trade in units of the quote currency
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        ri  r_  r  Nrj  r   r7  rS  r   s       r   !create_market_buy_order_with_costz'bingx.create_market_buy_order_with_cost  sB       #'&&vxdFSSSSSSSSSr   c                 P   K   ||d<   |                      |dd|d|           d{V S )a  
        create a market sell order by providing the symbol and cost
        :param str symbol: unified symbol of the market to create an order in
        :param float cost: how much you want to trade in units of the quote currency
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        ri  r_  r  Nrj  rn  s       r   "create_market_sell_order_with_costz(bingx.create_market_sell_order_with_cost  sB       #'&&vxtVTTTTTTTTTr   rG  rI  rJ  c                 :   |                      |          }d}d}	|                     d||          \  }	}|                                }|d         ||                                d}
|dk    }|	dk    }|rdnd}|                     ||d	          }|||
|<   |                     |d
          }|                     ||dk    |          \  }}|s|dk    rd|
d
<   n|dk    rd|
d
<   n|dk    rd|
d
<   |                     |dd          }|rr|                     |dd          }|                     |d          }|-|                     | 	                    ||                    |
d<   n|rV|Tt          j        |                     |          |                     |                    }|                     |          |
d<   n,|                     |                     ||                    |
d<   |s,|                     |                     ||                    |
d<   |`|r-|                     |
d          t!          | j        dz             |                     ||          |
d<   |dk    rd|
d<   n|dk    rd|
d<   n|dk    rd|
d
<   |                     |d          }|                     |d          }|                     |d          }|                     |dd          }|                     |dd           }|du}|du}|du}|du}|du}|p|}|                     |d!          }|                     |d"          }|du} |du}!|dk    s|dk    s|d#k    s|d$k    r.|s,|                     |                     ||                    |
d<   |                     |d%d&          }"|rM|                     |                     ||                    |
d<   |s|dk    rd|
d<   n|dk    s|dk    rd|
d<   n|s|rd'}"|rL|                     |                     ||                    |
d<   |s|d(k    rd(|
d<   n|dk    s|d#k    rd#|
d<   n|rK|                     |                     ||                    |
d<   |s|d)k    rd)|
d<   nc|dk    s|d$k    rd$|
d<   nQ|rO||
d<   |r|                     |          |
d<   n/|r-t          j        |d*          }#|                     |#          |
d<   | s|!r?|                     |          }$| r|                     |dd|          }%|                     |d+d,          }&|                     |dd(          }'|                     |                     ||%                    |&|'d-}(|                     |d          })|),|                     |                     ||)                    |(d<   |                     |d|$          }*|                     |                     ||*                    |(d<   |                     |(          |
d!<   |!r|                     |dd|          }+|                     |d+d,          },|                     |dd)          }-|                     |                     ||+                    |,|-d-}.|                     |d          })|),|                     |                     ||)                    |.d<   |                     |d|$          }/|                     |                     ||/                    |.d<   |                     |.          |
d"<   d}0|"r|d.k    rd/nd0}0n
|d.k    rd0nd/}0|0|
d1<   |                     |                     ||                    |
d<   |                     |g d2          }|                     |
|          S )3aW  
         * @ignore
        helper function to build request
        :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 you want to trade in units of the base currency
        :param float [price]: the price at which the order is to be fullfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: request to be sent to the exchange
        NrG   r,   )r7  rG  r  MARKETr9   newClientOrderIdclientOrderIDclientOrderIdtimeInForcePostOnlyIOCGTC	stopPricetriggerPricerS  ri  quantityrJ  zl createOrder() requires the cost parameter(or the amount + price) for placing spot market-buy trigger ordersLIMITTRIGGER_LIMITrG  TRIGGER_MARKETFOKrc  rd  trailingAmounttrailingPercent	priceRatetrailingTypeTRAILING_STOP_MARKETstopLoss
takeProfitSTOPTAKE_PROFIT
reduceOnlyFTSTOP_MARKETTAKE_PROFIT_MARKET100workingType
MARK_PRICE)r{  r  rG  r  SHORTLONGrZ  )
r  r|  rc  rd  r  r  r  r  r  rv  )r_  r  upperr  safe_string_upperhandle_post_onlyr^  r|  parse_to_numericcost_to_precisionr(   r  number_to_stringamount_to_precisionprice_to_precisionr  r    r,   r  r  
string_divjsonr~  )1r   r7  rG  r  rI  rJ  r   r_  postOnlyr  r  isMarketOrderisSpotexchangeClientOrderIdrv  rw  r|  rS  calculatedCostrc  rd  r  r  r  isTriggerOrderisStopLossPriceOrderisTakeProfitPriceOrderisTrailingAmountOrderisTrailingPercentOrder
isTrailingr  r  
isStopLossisTakeProfitr  requestTrailingPercentstringifiedAmountslTriggerPriceslWorkingTypeslType	slRequestslPrice
slQuantitytkTriggerPricetkWorkingTypetpType	tpRequest
tkQuantityrZ  s1                                                    r   create_order_requestzbingx.create_order_request  sK	    V$$
!??vW]^^
Fzz||TlJJLL
 

 (v%6< Q 2 2/**63H/ZZ$-:G)*,,V]CC00z@Y[abb& 	+z11%/GM""E!!%*GM""E!!%*GM"))&+~NN n	K%%ffoFFDYYvv..F+/+@+@AWAWX^`dAeAe+f+f((  je&7%,%78M8Mf8U8UW[WlWlmrWsWs%t%tN/3/D/D^/T/TGO,,*.*?*?@X@XY_ag@h@h*i*iGJ'  a#'#8#89P9PQWY^9_9_#`#` '  fT%5%5g%O%O%W+DG  7e  -e  f  f  f'+'>'>v|'T'T$7??&5GFOOX%%&6GFOe##).& ,,V_EEM"..v7HIIO!--f6FGGN"009JKXXO++FNDZ[[L)5N#0#< %4D%@"$2$$>!%4D%@".H2HJvz::H>>J!-J%T1Ldo&=&=46>>W[_lWlWl  xBWl#'#8#89P9PQWY^9_9_#`#` eDDJ Y'+'<'<T=T=TU[]i=j=j'k'k$  6T-=%=%=&6GFOOgoo4?+B+B&5GFO% Y)? Y!
' 8+/+@+@AXAXY_anAoAo+p+pGK($ 1)>)>*7'//tv~~*0+ 8+/+@+@AXAXY_apAqAq+r+rGK($ 81E)E)E*>'//t}/D/D*7 Y".( Y'+'<'<^'L'LGG$$+ Y-4-?QV-W-W*+/+@+@AW+X+XGK( A\ A$($9$9&$A$A! ?%)%7%7.R]_g%h%hN$($4$4X}l$[$[M!--hNNF%)%:%:4;R;RSY[i;j;j%k%k'4 &' 'I
 #..xAAG*-1-B-B4CZCZ[acjCkCk-l-l	'*!%!1!1(JHY!Z!ZJ,0,A,A$BZBZ[acmBnBn,o,oIj)*.))I*>*>GJ' A%)%7%7
NT_ak%l%lN$($4$4ZP\$]$]M!--j&BVWWF%)%:%:4;R;RSY[i;j;j%k%k'4 &' 'I
 #..z7CCG*-1-B-B4CZCZ[acjCkCk-l-l	'*!%!1!1*jJ[!\!\J,0,A,A$BZBZ[acmBnBn,o,oIj),0IIi,@,@GL)L F+/5==wwv*.%--vvg&2GN#"&"7"78P8PQWY_8`8`"a"aGJYYv  (J  (J  (J  K  KF{{7F+++r   c                   K   |                                   d{V  |                     |          }|                     |dd          }|                     |d          }|                     ||||||          }	d}
|d         r:|r|                     |	           d{V }
n7|                     |	           d{V }
n|                     |	           d{V }
t          |
t                    r*| 
                    |
          }
|                     |
          }
|                     |
di           }|                     |d|          }|                     ||          S )a7	  
        create a trade order
        :see: https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Trade%20order
        :see: https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Create%20an%20Order
        :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 you want to trade in units of the base currency
        :param float [price]: the price at which the order is to be fullfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.clientOrderId]: a unique id for the order
        :param bool [params.postOnly]: True to place a post only order
        :param str [params.timeInForce]: spot supports 'PO', 'GTC' and 'IOC', swap supports 'PO', 'GTC', 'IOC' and 'FOK'
        :param bool [params.reduceOnly]: *swap only* True or False whether the order is reduce only
        :param float [params.triggerPrice]: *swap only* triggerPrice at which the attached take profit / stop loss order will be triggered
        :param float [params.stopLossPrice]: *swap only* stop loss trigger price
        :param float [params.takeProfitPrice]: *swap only* take profit trigger price
        :param float [params.cost]: the quote quantity that can be used alternative for the amount
        :param float [params.trailingAmount]: *swap only* the quote amount to trail away from the current market price
        :param float [params.trailingPercent]: *swap only* the percent to trail away from the current market price
        :param dict [params.takeProfit]: *takeProfit object in params* containing the triggerPrice at which the attached take profit order will be triggered
        :param float [params.takeProfit.triggerPrice]: take profit trigger price
        :param dict [params.stopLoss]: *stopLoss object in params* containing the triggerPrice at which the attached stop loss order will be triggered
        :param float [params.stopLoss.triggerPrice]: stop loss trigger price
        :param boolean [params.test]: *swap only* whether to use the test endpoint or not, default is False
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr   Fr;   r   r  )rx  r_  r  r|  r  swapV2PrivatePostTradeOrderTestswapV2PrivatePostTradeOrderspotV1PrivatePostTradeOrderr  strfix_stringified_json_members
parse_jsonr  r   parse_order)r   r7  rG  r  rI  rJ  r   r_  r   r  r   r   r  s                r   rk  zbingx.create_orderX  s     8 !!!!!!!!!V$$~~ffe4466**++FD$vVV&> 	G K!%!E!Eg!N!NNNNNNN!%!A!A'!J!JJJJJJJ!==gFFFFFFFFHN h$$ 	1 88BBHx00Hx44tWd33v...r   ordersc           	        K   |                                   d{V  g }d}t          dt          |                    D ]}||         }|                     |d          }||}n||k    rt	          | j        dz             |                     |d          }|                     |d          }	|                     |d          }
|                     |d          }|                     |d	i           }|                     |||	|
||          }|	                    |           | 
                    |          }i }d}|d
         r4|                     |          |d<   |                     |           d{V }n3|                     |          |d<   |                     |           d{V }|                     |di           }|                     |dg           }|                     ||          S )a>  
        create a list of trade orders
        :see: https://bingx-api.github.io/docs/#/spot/trade-api.html#Batch%20Placing%20Orders
        :see: https://bingx-api.github.io/docs/#/swapV2/trade-api.html#Bulk%20order
        :param Array orders: list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr   r7  z; createOrders() requires all orders to have the same symbolrG  r  rI  rJ  r   r;   batchOrdersr   r  )rx  r  r  r  r!   r,   r!  r   r  rf  r_  r  !swapV2PrivatePostTradeBatchOrders!spotV1PrivatePostTradeBatchOrdersr  parse_orders)r   r  r   ordersRequestsr7  r$  rawOrderr  rG  r  rI  rJ  orderParamsorderRequestr_  r  r   r   r#  s                      r   create_orderszbingx.create_orders  s!      !!!!!!!!!q#f++&& 	0 	0AayH''(;;H~!X%%$TW/l%lmmm##Hf55D##Hf55D%%h99F$$Xw77E..8R@@K44XtT6SXZeffL!!,////V$$&> 	M%)YY~%>%>GM"!CCGLLLLLLLLHH"ii77GFO!CCGLLLLLLLLH\ ~~h33h33  000r   c                 B    ddddddd}|                      |||          S )Nr  r  )BUYSELLr  r  r&  r$  r  )r   r  sidess      r   r  zbingx.parse_order_side  s:    
 
 tT222r   c                 :    ddd}|                      |||          S )Nr_  rp  )trigger_markettrigger_limitr  )r   rG  typess      r   parse_order_typezbingx.parse_order_type  s.    &$
 
 tT222r   c                 .   |}|                      |dd          }||}|                     |dd          }|dnd}|                     |dd          }||                     |d d |          }|                     |d	d
          }|                     |g d          }	|                     |dd          }
|                     |dd          }|                     |dd          }|                     |g d          }|(|d         r|dk    r	|d         }n|d         }n|d         }|                     |d          }d }||dk    r|                     |d          }|`t          |t          j                  sF|dk    r@t          |t                    r|                     |          }|                     |d          }|                     |d          }d }||dk    r|                     |d          }|`t          |t          j                  sF|dk    r@t          |t                    r|                     |          }|                     |d          }|                     i d|d|                     |dd          d|                     |g 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 |                     |g d0          |                     |d1d2          d |                     |          |t-          j        |          d3d |                     |d4          d5	|          S )6NnewOrderResponseorderOpenResponserZ  psr9   r;   r7  r  r  r  )r  transactTimeE
updateTimer  rA  XfeeAssetr  )r  r  r  r  rB  r   r  r  r{  r  r  r,   r  r$  rv  )ru  origClientOrderIdcr8  r  r  lastTradeTimestampr]  rG  r  rw  r  rJ  r  r|  rc  rd  rS  ap)origQtyr  r}  executedQtyz)r9  rS  r  )	r-  rS  rI  filled	remainingrA  r  r  r  )safe_dict_2r  r  r  r  r{  r  r  r!  r  numbersRealr  r  
safe_orderr  r  r   r  r  r  parse_order_statusr(   r  r  )r   r  r_  r  newOrderrZ  r  r  r  r  r  statusIdfeeCurrencyCodefeeCostr  rc  r  rd  s                     r   r  zbingx.parse_order  s   R ##E+=?RSSE))%FF , 4VV6
%%eXs;;>%%hdJGGF''vs;;''/L/L/LMM	!00cJJ%%eXs;;,,UJDD$$U,F,F,FGG#f~ 25==&,VnOO&,WoOO"(/??5*55 x2~~ ,,XzBBM Jx,N,N V^bdVdVd(C(( 5??844 ,,X{CCM__UL99
!zR'7'7"..z<HHO"jW\.R.R"ZdhjZjZj*c** 9!__Z88
"..z;GGO  
D 
$$$UIs;; 
 T//7b7b7bcc 
 d&&xjII	 

  
 Y// 
 !"4 
 "4#4#4UL#I#I 
 D))$*B*B5&RU*V*VWW 
 4++E=AA 
  
 D))$// 
 T''w<< 
 ))%== 
 D,,UK@@ 
  ]! 
" # 
$ ))%TBB((0L0L0LMM((sCC--h77+*733  ..==; 
  
  
< =  	r   c                 D    dddddddd}|                      |||          S )Nr  closedcanceled)NEWPENDINGPARTIALLY_FILLEDFILLEDCANCELED	CANCELLEDFAILEDr  r   rA  statusess      r   r  zbingx.parse_order_status)	  s=     &"# 
 
 &&999r   r,   c                   K   |t          | j        dz             |                                  d{V  |                     |          }d|d         i}|                     |dd          }|                     |dg          }|||d<   n||d<   d}|                     d||          \  }}	|d	k    r0|                     |                     ||	                     d{V }n/| 	                    |                     ||	                     d{V }| 
                    |d
          }
|                     |
d|
          }|                     ||          S )a=  
        cancels an open order
        :see: https://bingx-api.github.io/docs/#/spot/trade-api.html#Cancel%20an%20Order
        :see: https://bingx-api.github.io/docs/#/swapV2/trade-api.html#Cancel%20an%20Order
        :param str id: order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.clientOrderId]: a unique id for the order
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nz) cancelOrder() requires a symbol argumentr7  r,   rv  ru  r  r@   r9   r   r  )r    r,   rx  r_  r  r|  r  spotV1PrivatePostTradeCancelr~  swapV2PrivateDeleteTradeOrderr  r   r  )r   r,   r7  r   r_  r  rv  r   r  queryr   r  s               r   cancel_orderzbingx.cancel_order5	  s      >#DG.Y$YZZZ!!!!!!!!!V$$fTl
 **6?OTT6O#455$'4GO$$!#GI >>}fV\]]
E!>>t{{7TY?Z?Z[[[[[[[[HH!??GUZ@[@[\\\\\\\\H^ x00tWd33v...r   c                   K   |t          | j        dz             |                                  d{V  |                     |          }d|d         i}d}|d         r0|                     |                     ||                     d{V }nO|d         r0|                     |                     ||                     d{V }nt          | j        dz             |S )a*  
        cancel all open orders
        :see: https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Cancel%20orders%20by%20symbol
        :see: https://bingx-api.github.io/docs/#/swapV2/trade-api.html#Cancel%20All%20Orders
        :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>`
        Nz- cancelAllOrders() requires a symbol argumentr7  r,   r9   r;   z= cancelAllOrders is only supported for spot and swap markets.)r    r,   rx  r_  &spotV1PrivatePostTradeCancelOpenOrdersr~  %swapV2PrivateDeleteTradeAllOpenOrdersr!   )r   r7  r   r_  r  r   s         r   cancel_all_orderszbingx.cancel_all_orders	  s      >#DG.]$]^^^!!!!!!!!!V$$fTl
 &> 8	h!HHU\^dIeIeffffffffHH. F^  	h!GGT[]cHdHdeeeeeeeeHH> TW'ffgggr   idsc                   K   |t          | j        dz             |                                  d{V  |                     |          }d|d         i}|                     |d          }|                     |d          }|}|du}|r|}g }	t          dt          |                    D ].}
||
         }t          |          }|		                    |           /d}|d         rN|rdnd	}d

                    |	          ||<   |                     |                     ||                     d{V }nO|r|                     |	          |d<   n|	|d<   |                     |                     ||                     d{V }|S )aS  
        cancel multiple orders
        :see: https://bingx-api.github.io/docs/#/swapV2/trade-api.html#Cancel%20a%20Batch%20of%20Orders
        :see: https://bingx-api.github.io/docs/#/spot/trade-api.html#Cancel%20a%20Batch%20of%20Orders
        :param str[] ids: order ids
        :param str symbol: unified market symbol, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str[] [params.clientOrderIds]: client order ids
        :returns dict: an list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nz* cancelOrders() requires a symbol argumentr7  r,   clientOrderIdsr   r9   clientOrderIDsorderIds,clientOrderIDListorderIdList)r    r,   rx  r_  r  r|  r  r  r  rf  join"spotV1PrivatePostTradeCancelOrdersr~  r  #swapV2PrivateDeleteTradeBatchOrders)r   r  r7  r   r_  r  r  
idsToParseareClientOrderIds	parsedIdsr$  r,   stringIdr   
spotReqKeys                  r   cancel_orderszbingx.cancel_orders	  s      >#DG.Z$Z[[[!!!!!!!!!V$$fTl
 1ABB6#344
+47 	('J	q#j//** 	' 	'AAB2wwHX&&&&&> 		d->N))JJ"%((9"5"5GJ!DDT[[QXZ`EaEabbbbbbbbHH  3/3yy/C/C+,,)2&!EEdkkRY[aFbFbccccccccH< r   c                 4  K   |t          | j        dz             |                                  d{V  |                     |          }|d         |d}d}|                     d||          \  }}|dk    r0|                     |                     ||                     d{V }n/|                     |                     ||                     d{V }|                     |d          }	| 	                    |	d|	          }
| 
                    |
|          S )	a  
        fetches information on an order made by the user
        :see: https://bingx-api.github.io/docs/#/spot/trade-api.html#Query%20Orders
        :see: https://bingx-api.github.io/docs/#/swapV2/trade-api.html#Query%20Order
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nz( fetchOrder() requires a symbol argumentr,   )r7  r  re   r9   r   r  )r    r,   rx  r_  r  spotV1PrivateGetTradeQueryr~  swapV2PrivateGetTradeOrderr  r   r  )r   r,   r7  r   r_  r  r   r  r  r   r  s              r   fetch_orderzbingx.fetch_order
  sH      >#DG.X$XYYY!!!!!!!!!V$$Tl
 
  >>|VU[\\
E!<<T[[RW=X=XYYYYYYYYHH!<<T[[RW=X=XYYYYYYYYHh x00tWd33v...r   c                   K   |                                   d{V  i }d}| |                     |          }|d         |d<   d}|                     d||          \  }}|dk    rt          | j        dz             |||d<   |||d<   |                     |d	d
          }|                     |d|          }	|                     |g d          }|	|	|d<   |                     | 	                    ||                     d{V }
| 
                    |
di           }|                     |dg           }|                     ||||          S )a	  
        fetches information on multiple orders made by the user
        :see: https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#User's%20All%20Orders
        :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 latest time in ms to fetch entries for
        :param int [params.orderId]: Only return subsequent orders, and return the latest order by default
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr,   r7  rg   r;   z1 fetchOrders() is only supported for swap marketsrp  rt  ru  tillrv  )rv  r  ru  r   r  )rx  r_  r  r%   r,   r{  r   r|  swapV1PrivateGetTradeFullOrderr~  r   r  r  )r   r7  ro  rp  r   r  r_  rG  ru  rv  r   r   r  s                r   fetch_orderszbingx.fetch_ordersf
  s      !!!!!!!!![[((F &tGH99-QWXXf6>>tw)\\]]]$GG#(GK ##FGV<<##FIu==6#?#?#?@@!(GI<<T[[RX=Y=YZZZZZZZZj ~~h33h33  >>>r   c                   K   |                                   d{V  d}i }| |                     |          }|d         |d<   d}|                     d||          \  }}	|dk    r0|                     |                     ||	                     d{V }n/|                     |                     ||	                     d{V }|                     |di           }
|                     |
dg           }|                     ||||          S )a  
        :see: https://bingx-api.github.io/docs/#/spot/trade-api.html#Query%20Open%20Orders
        :see: https://bingx-api.github.io/docs/#/swapV2/trade-api.html#Query%20all%20current%20pending%20orders
        fetch all unfilled currently open orders
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch open orders for
        :param int [limit]: the maximum number of open order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr,   r7  rd   r9   r   r  )	rx  r_  r  spotV1PrivateGetTradeOpenOrdersr~  swapV2PrivateGetTradeOpenOrdersr   r  r  )r   r7  ro  rp  r   r_  r  r   r  r  r   r  s               r   fetch_open_orderszbingx.fetch_open_orders
  s;      !!!!!!!!![[((F &tGH >>?PRXZ`aa
E!AA$++gW\B]B]^^^^^^^^HH!AA$++gW\B]B]^^^^^^^^Hp ~~h33h33  >>>r   c                   K   |t          | j        dz             |                                  d{V  |                     |          }d|d         i}d}d}|                     |ddd          \  }}|                     d||          \  }	}
|r0|                     |                     ||
                     d{V }ne|	dk    r0|                     |                     ||
                     d{V }n/| 	                    |                     ||
                     d{V }| 
                    |d	g           }|                     |d
g           }|                     ||||          S )a  
        fetches information on multiple closed orders made by the user
        :see: https://bingx-api.github.io/docs/#/spot/trade-api.html#Query%20Order%20History
        :see: https://bingx-api.github.io/docs/#/swapV2/trade-api.html#User's%20Force%20Orders
        :see: https://bingx-api.github.io/docs/#/standard/contract-interface.html#Historical%20order
        :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 latest time in ms to fetch orders for
        :param boolean [params.standard]: whether to fetch standard contract orders
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nz/ fetchClosedOrders() requires a symbol argumentr7  r,   rP   r1  Fr9   r   r  )r    r,   rx  r_  ry  r  contractV1PrivateGetAllOrdersr~  "spotV1PrivateGetTradeHistoryOrdersswapV2PrivateGetTradeAllOrdersr  r  r  )r   r7  ro  rp  r   r_  r  r   r1  r  r  r   r  s                r   fetch_closed_orderszbingx.fetch_closed_orders  s      >#DG._$_```!!!!!!!!!V$$fTl
 88ATV`bghh& >>?RTZ\bcc
E 	^!??GUZ@[@[\\\\\\\\HH6!!!DDT[[QXZ_E`E`aaaaaaaaHH!@@WV[A\A\]]]]]]]]Hp x44h33  >>>r   r  fromAccount	toAccountc           
        K   |                                   d{V  |                     |          }|                     | j        di           }|                     |||          }|                     |||          }	|d         |                     ||          |dz   |	z   d}
|                     |                     |
|                     d{V }||                     |d          dd||||dd	S )a6  
        transfer currency internally between wallets on the same account
        :see: https://bingx-api.github.io/docs/#/spot/account-api.html#User%20Universal%20Transfer
        :param str code: unified currency code
        :param float amount: amount to transfer
        :param str fromAccount: account to transfer from
        :param str toAccount: account to transfer to
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `transfer structure <https://docs.ccxt.com/#/?id=transfer-structure>`
        Nr   r,   _)r:  rI  rG  tranId	r  r,   r  r  r9  rI  r'  r(  rA  )rx  r9  r   r   r  currency_to_precision spotV3PrivateGetGetAssetTransferr~  )r   r  rI  r'  r(  r   r9  r   fromIdtoIdr  r   s               r   ru   zbingx.transferj  s'      !!!!!!!!!==&&6FKK!!.+{KK	9EEd^00v>>SL4'
 

 >>t{{7TZ?[?[\\\\\\\\ ""8X66&"

 

 
	
r   c                 z  K   |                                   d{V  d}||                     |          }|                     | j        di           }|                     |d          }|                     |d          }|                     |||          }	|                     |||          }
|	|
t          | j        dz             d|	dz   |
z   i}|||d<   |||d	<   |                     |                     ||                     d{V }| 	                    |d
g           }| 
                    ||||          S )aw  
        fetch a history of internal transfers made on an account
        :see: https://bingx-api.github.io/docs/#/spot/account-api.html#Query%20User%20Universal%20Transfer%20History%20(USER_DATA)
        :param str [code]: unified currency code of the currency transferred
        :param int [since]: the earliest time in ms to fetch transfers for
        :param int [limit]: the maximum number of transfers structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `transfer structures <https://docs.ccxt.com/#/?id=transfer-structure>`
        Nr   r'  r(  z/ fromAccount & toAccount parameter are requiredrG  r*  rt  sizerows)rx  r9  r   r   r  r   r,   spotV3PrivateGetAssetTransferr~  r  parse_transfers)r   r  ro  rp  r   r9  r   r'  r(  r/  r0  r  r   r3  s                 r   fetch_transferszbingx.fetch_transfers  sr      !!!!!!!!!}}T**H6FKK&&v}==$$V[99	!!.+{KK	9EE>T\*[ [\\\FSL4'
 #(GK #GFO;;DKKQW<X<XYYYYYYYY  ~~h33##D(E5AAAr   r9  c           
      Z   |                      |d          }|                     |d          }|                     d |          }|                      |d          }|                     | j        di           }|                      |d          }|                    d          }	|                      |	d          }
|                      |d          }|                      ||
|
          }|                      |||          }||||                     |          ||                     |d	          |||d
	S )Nr+  r  rA  r   rG  r*  r   r   rI  r,  )r  r   r  r   r   r[  r  r!  )r   ru   r9  r+  r  r  rA  r   typeIdtypeIdSplitr/  r0  r'  r(  s                 r   parse_transferzbingx.parse_transfer  s1   !!(H55%%h<<	..tX>>!!(H55~~dlNBGG!!(F33ll3''!!+q11**&&|VVDD$$\4>>	"Y//$&&x::&"

 

 
	
r   c                   K   |                                   d{V  |                     |          }|                     | j        d          }|                     | j        d|          }|d         dd|d}|                     |                     ||                     d{V }|                     |                     |d          d          }| 	                    ||d         gd	          }	| 
                    |	d
          S )a  
        fetch the deposit addresses for a currency associated with self account
        :see: https://bingx-api.github.io/docs/#/en-us/common/wallet-api.html#Query%20Main%20Account%20Deposit%20Address
        :param str code: unified currency code
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary `address structures <https://docs.ccxt.com/#/?id=address-structure>`, indexed by the network
        Nr   r,   r   r2   )r  offsetrp  r   r   r  Fr  )rx  r9  r   r   parse_params(walletsV1PrivateGetCapitalDepositAddressr~  r  r   parse_deposit_addressesindex_by)
r   r  r   r9  defaultRecvWindowr   r  r   r   parseds
             r   "fetch_deposit_addresses_by_networkz(bingx.fetch_deposit_addresses_by_network  s      !!!!!!!!!==&& --dlLII&&t'8,HYZZ
TN$	
 
 FFt{{SZ\bGcGcdddddddd& ~~dnnXv>>GG--dXf5E4FNN}}VY///r   c                   K   |                      |d          }|                     |dg          }|                     ||           d{V }||                     ||          S |                     | j        d          }|                      ||          }||                     ||          S t          |                                          }|                      |d          }|                     ||          S )aG  
        fetch the deposit address for a currency associated with self account
        :see: https://bingx-api.github.io/docs/#/en-us/common/wallet-api.html#Query%20Main%20Account%20Deposit%20Address
        :param str code: unified currency code
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.network]: The chain of currency. This only apply for multi-chain currency, and there is no need for single chain currency
        :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
        r  Nr   r   )r  r|  rC  r   r   r   keys)	r   r  r   r  addressStructuresr   defaultNetworkForCurrencyrE  keys	            r   fetch_deposit_addresszbingx.fetch_deposit_address  s      ""69556I;//"&"I"I$PV"W"WWWWWWW>>"3W===nnT\3DEEG(,(8(8$(G(G%(4~~&79RSSS-224455&&tQ//~~&7===r   c                 (   |                      |d          }|                      |d          }|                      |d          }|                     ||          }|d         }|                      |d          }|                     |           |||||dS )Naddresstagr  r  r  )r9  rK  rL  r  r  )r  safe_currencycheck_address)r   depositAddressr9  rK  rL  r&  r  r  s           r   parse_deposit_addresszbingx.parse_deposit_address  s     "">9==~u55%%nf==
%%j(;;"">9==7###"
 
 	
r   c                 0  K   |                                   d{V  i }d}| |                     |          }|d         |d<   |||d<   |||d<   |                     |                     ||                     d{V }|                     ||||          S )a8  
        fetch all deposits made to an account
        :see: https://bingx-api.github.io/docs/#/spot/account-api.html#Deposit%20History(supporting%20network)
        :param str [code]: unified currency code
        :param int [since]: the earliest time in ms to fetch deposits for
        :param int [limit]: the maximum number of deposits structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        Nr,   r  rt  rp  )rx  r9  $spotV3PrivateGetCapitalDepositHisrecr~  parse_transactionsr   r  ro  rp  r   r  r9  r   s           r   fetch_depositszbingx.fetch_deposits2  s       !!!!!!!!!
}}T**H&tnGFO#(GK $GGBB4;;wX^C_C_````````$ &&x5%HHHr   c                 0  K   |                                   d{V  i }d}| |                     |          }|d         |d<   |||d<   |||d<   |                     |                     ||                     d{V }|                     ||||          S )aG  
        fetch all withdrawals made from an account
        :see: https://bingx-api.github.io/docs/#/spot/account-api.html#Withdraw%20History%20(supporting%20network)
        :param str [code]: unified currency code
        :param int [since]: the earliest time in ms to fetch withdrawals for
        :param int [limit]: the maximum number of withdrawals structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        Nr,   r  rt  rp  )rx  r9  &spotV3PrivateGetCapitalWithdrawHistoryr~  rS  rT  s           r   fetch_withdrawalszbingx.fetch_withdrawals[  s       !!!!!!!!!
}}T**H&tnGFO#(GK $GGDDT[[QXZ`EaEabbbbbbbb( &&x5%HHHr   c                 `   |                      |d          }|d n|                     |d          }|                     |d|          }|                     |d          }|                     |d          }|                     |d          }|                     |          }	|+|                     |d          }	|                     |	          }|                     |d          }
|                     |d          }|                     ||          }|7||
k    r1|                    |
          d	k    r|
|                    |
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 S )!Nr   r,   rK  
addressTag
insertTime	applyTimer  r  r   r  transferType0r  
withdrawalr  txidtxIdrG  r9  rI  rA  r  r  addressFrom	addressTorL  tagFromtagToupdatedtransactionFee)r9  rS  r  )commentr  internal)r  r  r   r  r  r  findr.  r   r!  parse_transaction_status)r   transactionr9  r   dataIdr,   rK  rL  r  r  r  r&  r  rawTyperG  s                  r   parse_transactionzbingx.parse_transaction  s   ` {F33,T-=-=dD-I-Ik488"";	::{L99%%k<@@	<<	**''[AAHx00I"";	::%%k6::
&&z8<<47??		'8J8Ja8O8O"||GR00"";??$^^yy,
K
"
 D$$[&99
 D	

 
 t..w77
 d&&{H==
 d33D4D4D[RZ4[4[\\
 
 
 w
 4
 
 3
 s
  T!
" t#
$ ''V<< ((6FGG 
 1
 
 
 	
r   rA  c                 R    ddddddddddddddd}|                      |||          S )Npendingokrejected)r^  r@  1020304050607023456r  r  s      r   rk  zbingx.parse_transaction_status  sR    
 
  &&999r   rP  c                   K   |t          | j        dz             |                                  d{V  |                     |          }|d         dk    rt	          | j        dz             |                                }|dk    rd}|dk    r|dk    rt          | j        d	z             |d
         |d}|                     |                     ||                     d{V S )a  
        set margin mode to 'cross' or 'isolated'
        :see: https://bingx-api.github.io/docs/#/swapV2/trade-api.html#Switch%20Margin%20Mode
        :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 argumentrG  r;   z- setMarginMode() supports swap contracts onlyCROSSCROSSEDISOLATEDz@ setMarginMode() marginMode argument should be isolated or crossr,   )r7  
marginType)	r    r,   rx  r_  r"   r  r!    swapV2PrivatePostTradeMarginTyper~  )r   rP  r7  r   r_  r  s         r   set_margin_modezbingx.set_margin_mode  s      >#DG.[$[\\\!!!!!!!!!V$$&>V##DG&UUVVV%%''
  "J##
i(?(?TW'iijjjTl$
 
 ::4;;wPV;W;WXXXXXXXXXr   c                 p   K   ddi}|                      |||                     ||                     d {V S )NrG  r   
set_marginr~  r   r7  rI  r   r  s        r   
add_marginzbingx.add_margin  J      A
 __VVT[[&5Q5QRRRRRRRRRr   c                 p   K   ddi}|                      |||                     ||                     d {V S )NrG  r  r  r  s        r   reduce_marginzbingx.reduce_margin  r  r   c                   K   |                      |d          }|t          | j        dz             |                     |ddg          st          | j        dz             |                                  d{V  |                     |          }|d         |                     |d         |          |d}|                     |                     ||                     d{V }| 	                    ||          S )	a  
        Either adds or reduces margin in an isolated position in order to set the margin to a specific value
        :see: https://bingx-api.github.io/docs/#/swapV2/trade-api.html#Adjust%20isolated%20margin
        :param str symbol: unified market symbol of the market to set margin in
        :param float amount: the amount to set the margin to
        :param dict [params]: parameters specific to the bingx api endpoint
        :returns dict: A `margin structure <https://docs.ccxt.com/#/?id=add-margin-structure>`
        rG  NzV setMargin() requires a type parameter either 1(increase margin) or 2(decrease margin)r   r  r,   r7  )r7  rI  rG  )
r   r    r,   r  rx  r_  r  $swapV2PrivatePostTradePositionMarginr~  parse_margin_modification)r   r7  rI  r   rG  r_  r  r   s           r   r  zbingx.set_margin  s8        00<#DG  /G  %G  H  H  H}}TAq6** 	H#DG  /G  %G  H  H  H!!!!!!!!!V$$Tl..vh/?HH
 

 BB4;;wX^C_C_```````` --h???r   c                     |                      |d          }||                      |d          |dk    rdndd|                     |d          |                     |d          |                      |d	          d d d d

S )NrG  r7  r@  addreducerK  rI  r:   rC  )
r  r7  rG  rP  rI  r?  r  rA  r  r  )r  r!  )r   r   r_  rG  s       r   r  zbingx.parse_margin_modification<  s     f--&&vx88"ckkEE$&&tX66%%dH55$$VX66
 
 	
r   c                 0  K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     |di           }|                     ||          S )ar  
        fetch the set leverage for a market
        :see: https://bingx-api.github.io/docs/#/swapV2/trade-api.html#Query%20Leverage
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `leverage structure <https://docs.ccxt.com/#/?id=leverage-structure>`
        Nr7  r,   r   )rx  r_  swapV2PrivateGetTradeLeverager~  r   parse_leverager  s          r   fetch_leveragezbingx.fetch_leverageS  s       !!!!!!!!!V$$fTl
 ;;DKKQW<X<XYYYYYYYY ~~h33""4000r   c                     |                      |d          }||                     ||          d |                     |d          |                     |d          dS )Nr7  longLeverageshortLeverage)r  r7  rP  r  r  )r  r  r   )r   rR  r_  r  s       r   r  zbingx.parse_leveragen  se    ##Hh77&&x88 --hGG!..xII
 
 	
r   rR  c                 l  K   |t          | j        dz             |                     |d          }|                     d|dg d           |                                  d{V  |                     |          }|d         ||d}|                     |                     ||                     d{V S )a  
        set the level of leverage for a market
        :see: https://bingx-api.github.io/docs/#/swapV2/trade-api.html#Switch%20Leverage
        :param float leverage: the rate of leverage
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.side]: hedged: ['long' or 'short']. one way: ['both']
        :returns dict: response from the exchange
        Nz) setLeverage() requires a symbol argumentr  rq   )r  r  BOTHr,   )r7  r  rR  )r    r,   r  check_required_argumentrx  r_  swapV2PrivatePostTradeLeverager~  )r   rR  r7  r   r  r_  r  s          r   set_leveragezbingx.set_leveragex  s       >#DG.Y$YZZZ%%ff55$$]D&B[B[B[\\\!!!!!!!!!V$$Tl 
 
 88Wf9U9UVVVVVVVVVr   c                   K   |t          | j        dz             |                                  d{V  |                     |          }|                                 }d}d|d         i}||d         rdnd}	|||	<   n|d         r|d	z
  |d<   |                     |d
          }
|                     |d
          }|
|d         rdnd}|
||<   n|d         r||d<   d}|d         r^|                     |                     ||                     d{V }| 	                    |di           }| 
                    |dg           }n|                     |dd          }|                     |d          }||d<   |                     |                     ||                     d{V }| 	                    |di           }| 
                    |dg           }|                     |||||          S )at  
        fetch all trades made by the user
        :see: https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Query%20Order%20History
        :see: https://bingx-api.github.io/docs/#/swapV2/trade-api.html#Query%20historical%20transaction%20orders
        :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 int [params.until]: timestamp in ms for the ending date filter, default is None
        :param str params['trandingUnit']: COIN(directly represent assets such and ETH) or CONT(represents the number of contract sheets)
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        Nz+ fetchMyTrades() requires a symbol argumentr7  r,   r9   rt  startTsr;   l    X ru  rv  endTsr   fillstradingUnitCONTfill_orders)r    r,   rx  r_  millisecondsr   r|  spotV1PrivateGetTradeMyTradesr~  r   r  r  "swapV2PrivateGetTradeAllFillOrdersr  )r   r7  ro  rp  r   r_  nowr   r  startTimeReqru  
endTimeReqr  r   r  s                  r   fetch_my_tradeszbingx.fetch_my_trades  sG      >#DG.[$[\\\!!!!!!!!!V$$!!fTl
 *0.G;;iL$)GL!!F^ 	2!$z!1GI!!&'2267++&,VnA'J"'GJF^ 	#"GG&> "	<!??GU[@\@\]]]]]]]]H>>(FB77DNN4"55EE4 00OOKYYv}55F%0GM"!DDT[[QXZ`EaEabbbbbbbbH>>(FB77DNN4;;E*   ufEEEr   c                    |                      |dg           }t          |          }|d d dd d di d}|dk    rt          d|          D ]}||         }|                     |d          }|                     |d          }	|                     |d          }
|                     ||
          }d d d|                     |d          d	dd
|d         |<   |	r*|                     |d          |d         d<   d	|d         d<   |S )Nr  )r  r,  )r  r  r  r  r   r  r  r  r  F)r  r  r  r  r  r,  )r  r  r  r  r  r   r!  )r   r  r9  r  networkListLengthr#  r$  r  	networkIdr  r  r+  s               r   parse_deposit_withdraw_feez bingx.parse_deposit_withdraw_fee  sZ   : nnS-<<,," 
 "  
 
 !!1/00 = =%a. ,,Wi@@	 NN7K@@	#//&AA"55iNN'+4@@(,(8(8-(P(P`e f f3 3z";/  =040@0@-0X0XF:&u-7<F:&|4r   codesc                    K   |                                   d{V  |                     |           d{V }|                     |d          }|                     ||d          S )a  
        fetch deposit and withdraw fees
        :see: https://bingx-api.github.io/docs/#/common/account-api.html#All%20Coins'%20Information
        :param str[]|None codes: list of unified currency codes
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a list of `fee structures <https://docs.ccxt.com/#/?id=fee-structure>`
        Nr   r  )rx  r  r  parse_deposit_withdraw_fees)r   r  r   r   coinss        r   fetch_deposit_withdraw_feesz!bingx.fetch_deposit_withdraw_fees0  s|       !!!!!!!!!DDVLLLLLLLLx00//ufEEEr   c                 z  K   |                                   d{V  |                     |          }|                     |d          }|d}|                     |g d          st	          | j        dz             |d         ||                     |          |d}|                     |d          }	|	|                     |	          |d<   | 	                    |ddg          }| 
                    |                     ||                     d{V }
|                     |
d	          }|                     |          S )
aC  
        make a withdrawal
        :see: https://bingx-api.github.io/docs/#/common/account-api.html#Withdraw
        :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
        :param int [params.walletType]: 1 fund account, 2 standard account, 3 perpetual account
        :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        N
walletTyper   )r   r  r   zj withdraw() requires either 1 fund account, 2 standard futures account, 3 perpetual account for walletTyper,   )r  rK  rI  r  r  r   )rx  r9  r   r  r!   r,   r  r  network_code_to_idr|  (walletsV1PrivatePostCapitalWithdrawApplyr~  r  ro  )r   r  rI  rK  rL  r   r9  r  r  r  r   r   s               r   r  zbingx.withdraw=  sr      !!!!!!!!!==&&&&v|<<
J}}Z33 	UTW  (T  T  U  U  UTN++F33$	
 
 ((;;!%!8!8!A!AGI6L)#<==FFt{{SZ\bGcGcddddddddx00 %%d+++r   c                    |                      |          }t          |                                          }t          dt	          |                    D ]x}||         }||         }t          |t                    rQd}t          dt	          |                    D ]'}||         }	|dk    r|dz  }|t          |	          z  }(|dz  }|||<   y|S )Nr   [r
  ])keysortr   rE  r  r  r  r  )
r   r   sortedParamsrE  r$  rH  valuearrStrr)  arrayElements
             r   r=  zbingx.parse_paramse  s    ||F++L%%''((q#d))$$ 	+ 	+Aq'C %E%&& +q#e**-- 0 0A#(8L1uu#c,///FF#$*S!r   c                   K   |                                   d{V  ddi}|                     d||          \  }}d}||                     |          }||d<   |||d<   |||d<   |                     |                     ||                     d{V }|                     |di           }|                     |d	g           }	|                     |	|||          S )
a  
        retrieves the users liquidated positions
        :see: https://bingx-api.github.io/docs/#/swapV2/trade-api.html#User's%20Force%20Orders
        :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 bingx api endpoint
        :param int [params.until]: timestamp in ms of the latest liquidation
        :returns dict: an array of `liquidation structures <https://docs.ccxt.com/#/?id=liquidation-structure>`
        NautoCloseTypeLIQUIDATIONrv  r7  rt  rp  r   r  )rx  handle_until_optionr_   swapV2PrivateGetTradeForceOrdersr~  r   r  parse_liquidations)
r   r7  ro  rp  r   r  r_  r   r   liquidationss
             r   fetch_my_liquidationszbingx.fetch_my_liquidationsv  s      !!!!!!!!!]
 229gvNN[[((F &GH#(GK $GG>>t{{7TZ?[?[\\\\\\\\< ~~h33~~dHb99&&|VUEJJJr   c                 |   |                      |d          }|                     |d          }|                      |d          }|                      |d          }|                      |d          }t          j        ||          }t          j        ||          }	|                     ||                     ||          |                     |          |                     |          |                     |          |                     |          |                     |	          ||                     |          d	          S )Nr7  r  r  rU  rS  )	r  r7  rX  rU  rJ  	baseValue
quoteValuer  r  )r  r   r(   r  safe_liquidationr  r   r  )
r   liquidationr_  r  r  contractsStringcontractSizeStringpriceStringbaseValueStringquoteValueStrings
             r   parse_liquidationzbingx.parse_liquidation  s5   , ##K::%%k6::	**;FF!--fnEE&&{J??!,_>PQQ"-o{KK$$&&x88**?;; --.@AA&&{33**?;;++,<=="Y//
&
 
&
 
 
 
	r   c                   K   |                                   d{V  |                     |d          }|                     |d          }d}|4d|i}|                     |                     ||                     d{V }nN|                     |          }d|d         i}|                     |                     ||                     d{V }|                     |d          }|                     |          S )a,  
        closes open positions for a market
        :see: https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#One-Click%20Close%20All%20Positions
        :param str symbol: Unified CCXT market symbol
        :param str [side]: not used by bingx
        :param dict [params]: extra parameters specific to the bingx api endpoint
        :param str|None [params.positionId]: it is recommended to hasattr(self, fill) parameter when closing a position
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        NrM  r7  r,   r   )	rx  r  r|  #swapV1PrivatePostTradeClosePositionr~  r_  'swapV2PrivatePostTradeCloseAllPositionsr   r  )	r   r7  r  r   rM  r   r  r_  r   s	            r   close_positionzbingx.close_position  s&      !!!!!!!!!%%fl;;
6<00!jG "EEdkkRY[aFbFbccccccccHH[[((F&,G "II$++V]_eJfJfggggggggH@ ~~h//%%%r   c                   K   |                                   d{V  |                     | j        d          }|                     | j        d|          }d}|                     dd|          \  }}|dk    rt          | j        dz   |z   dz             d|i}|                     |                     ||                     d{V }| 	                    |di           }| 
                    |dg           }g }	t          d	t          |                    D ]4}
|                     d
||
         i          }|	                    |           5|	S )a  
        closes open positions for a market
        :see: https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#One-Click%20Close%20All%20Positions
        :param dict [params]: extra parameters specific to the okx api endpoint
        :param str [params.recvWindow]: request valid time window value
        :returns dict[]: `A list of position structures <https://docs.ccxt.com/#/?id=position-structure>`
        Nr   rB   r:   z% closePositions() cannot be used for z marketsr   successr   rM  )rx  r   r   r=  r  r!   r,   r  r~  r   r  r  r  rg  rf  )r   r   rA  r   r  r  r   r   r  rH  r$  rf  s               r   close_all_positionszbingx.close_all_positions  s|      !!!!!!!!! --dlLII&&t'8,HYZZ

!??@SUY[abb
F!!TW'NNQ[[^hhiii*
 EEdkkRY[aFbFbcccccccc ~~h33..y"55	q#g,,'' 	' 	'A**L'!*+EFFHX&&&&r   c                    K   |                      |           d{V }|                     |di           }|                     |d          }||dk    dS )a  
        fetchs the position mode, hedged or one way, hedged for binance is set identically for all linear markets or all inverse markets
        :see: https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Get%20Position%20Mode
        :param str symbol: unified symbol of the market to fetch the order book for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an object detailing whether the market is in hedged or one-way mode
        Nr   dualSidePositiontrue)r  r[  ) swapV1PrivateGetPositionSideDualr   r  )r   r7  r   r   r   r  s         r   fetch_position_modezbingx.fetch_position_mode<  su       >>vFFFFFFFF ~~h33++D2DEE'61
 
 	
r   r[  c                 ~   K   d}|rd}nd}d|i}|                      |                     ||                     d{V S )a  
        set hedged to True or False for a market
        :see: https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Set%20Position%20Mode
        :param bool hedged: set to True to use dualSidePosition
        :param str symbol: not used by bingx setPositionMode()
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: response from the exchange
        Nr  falser  )!swapV1PrivatePostPositionSideDualr~  )r   r[  r7  r   r  r  s         r   set_position_modezbingx.set_position_modeV  si         	'%& 0
 ;;DKKQW<X<XYYYYYYYYYr   c                   K   |                                   d{V  |                     |          }|                     ||||||          }	||	d<   d|	d<   d}
|d         r0|                     |                     |	|                     d{V }
n/|                     |                     |	|                     d{V }
|                     |
d          }|                     ||          S )a  
        cancels an order and places a new order
        :see: https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Cancel%20order%20and%20place%20a%20new%20order  # spot
        :see: https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Cancel%20an%20order%20and%20then%20Place%20a%20new%20order  # swap
        :param str id: order id
        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of the currency you want to trade in units of the base currency
        :param float [price]: the price at which the order is to be fullfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.stopPrice]: Trigger price used for TAKE_STOP_LIMIT, TAKE_STOP_MARKET, TRIGGER_LIMIT, TRIGGER_MARKET order types.
        :param dict [params.takeProfit]: *takeProfit object in params* containing the triggerPrice at which the attached take profit order will be triggered
        :param float [params.takeProfit.triggerPrice]: take profit trigger price
        :param dict [params.stopLoss]: *stopLoss object in params* containing the triggerPrice at which the attached stop loss order will be triggered
        :param float [params.stopLoss.triggerPrice]: stop loss trigger price
         *
         * EXCHANGE SPECIFIC PARAMETERS
        :param str [params.cancelClientOrderID]: the user-defined id of the order to be canceled, 1-40 characters, different orders cannot use the same clientOrderID, only supports a query range of 2 hours
        :param str [params.cancelRestrictions]: cancel orders with specified status, NEW: New order, PENDING: Pending order, PARTIALLY_FILLED: Partially filled
        :param str [params.cancelReplaceMode]: STOP_ON_FAILURE - if the cancel order fails, it will not continue to place a new order, ALLOW_FAILURE - regardless of whether the cancel order succeeds or fails, it will continue to place a new order
        :param float [params.quoteOrderQty]: order amount
        :param str [params.newClientOrderId]: custom order id consisting of letters, numbers, and _, 1-40 characters, different orders cannot use the same newClientOrderId.
        :param str [params.positionSide]: *contract only* position direction, required for single position, for both long and short positions only LONG or SHORT can be chosen, defaults to LONG if empty
        :param str [params.reduceOnly]: *contract only* True or False, default=false for single position mode. self parameter is not accepted for both long and short positions mode
        :param float [params.priceRate]: *contract only* for type TRAILING_STOP_Market or TRAILING_TP_SL, Max = 1
        :param str [params.workingType]: *contract only* StopPrice trigger price types, MARK_PRICE(default), CONTRACT_PRICE, or INDEX_PRICE
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        NcancelOrderIdSTOP_ON_FAILUREcancelReplaceModer;   r   )rx  r_  r  #swapV1PrivatePostTradeCancelReplacer~  (spotV1PrivatePostTradeOrderCancelReplacer   r  )r   r,   r7  rG  r  rI  rJ  r   r_  r  r   r   s               r   
edit_orderzbingx.edit_orderq  s     < !!!!!!!!!V$$++FD$vVV#% '8#$&> 9	i!EEdkkRY[aFbFbccccccccHHp "JJ4;;W^`fKgKghhhhhhhhHL ~~h//f---r   c                 0  K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     |di           }|                     ||          S )a  
        fetches the margin mode of the trading pair
        :see: https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Query%20Margin%20Mode
        :param str symbol: unified symbol of the market to fetch the margin mode for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `margin mode structure <https://docs.ccxt.com/#/?id=margin-mode-structure>`
        Nr7  r,   r   )rx  r_  swapV2PrivateGetTradeMarginTyper~  r   parse_margin_moder  s          r   fetch_margin_modezbingx.fetch_margin_mode  s       !!!!!!!!!V$$fTl
 ==dkk'SY>Z>Z[[[[[[[[ ~~h33%%dF333r   c                 Z    |                      |d          }|dk    rdn|}||d         |dS )Nr  crossedrL  r7  )r  r7  rP  )r  )r   rP  r_  r  s       r   r  zbingx.parse_margin_mode  sG    ++JEE
!+y!8!8WWz
X&$
 
 	
r   r   GETc                 v   |d         }|d         }|d         }	|                      | j        dd          }
|
r#|dk    rt          | j        dz   |z   dz             |                     | j        d	         |                   }|d
k    r|dk    r|dz  }n|d|z   z  }|d|z   dz   z  }|                     ||          }||z  }|                     ||                     |                    }| 	                    |          }|	dk    r5| 
                                |d<   |r|d|                     |          z   z  }n|	dk    r|                                  | 
                                |d<   |                     |          }|                     |          }|                     |                     |                     |                    |                     | j                  t$          j                  }|r	d|z   dz   }n|dz  }|d|z   z  }| j        |                     | j        dd          d}||z  }||||dS )Nr   r   r  r  Fr;   z) does not have a testnet/sandbox URL for z
 endpointsr   r9   r   z/apir>  r   r  ?r   &z
signature=r   r   )zX-BX-APIKEYzX-SOURCE-KEY)urlmethodbodyheaders)r  r   r%   r,   implode_hostnamerw   implode_paramsr|  extract_paramsr  nonce	urlencoder  r=  hmacencode	rawencoder   hashlibsha256r   r  )r   pathsectionr  r   r  r  rG  r3   accessr"  r  parsedParamsr  	signatures                  r   signz
bingx.sign  s]   qz!*NN4<FF	 	l$&..tw)TTW[[^jjkkk##DIe$4T$:;;6>>goo6MCC3:CsW}s""""400t64#6#6t#<#<==f%%X"&**,,F; 4sT^^F3333y  ++---"&**,,F;,,V44LNN<00E		$++dnn\.J.J"K"KT[[Y]YdMeMegnguvvI ec)\I--E#{ $ 0 0x P P G 5LCfdwOOOr   c                 *    |                                  S N)r  )r   s    r   r  zbingx.nonceA  s      """r   enablec                 l    t          t          |                               |           || j        d<   d S )Nr  )r   r*   set_sandbox_moder   )r   r  r   s     r   r  zbingx.set_sandbox_modeD  s3    eT++F333&,]###r   c
                 z   |d S |                      |d          }
|                      |d          }|
|
dk    r| j        dz   |z   }|                     | j        d         ||           |                     | j        d         |
|           |                     | j        d         ||           t          |          d S )Nr  msgr^   r   r   )r  r,   throw_exactly_matched_exceptionr   throw_broadly_matched_exceptionr   )r   httpCodereasonr  r  r  r  r   requestHeadersrequestBodyr  messagefeedbacks                r   handle_errorszbingx.handle_errorsH  s    4 &11""8U33w}t+H001I7T\]]]001I4QYZZZ001I7T\]]])))tr   r  )n__name__
__module____qualname__r   r   r   r,  r2  r5  r   rd  r   rn  r  r   r   r  r  r   r  r  r   r  r  r   r  r  r   r  r   r  r   r  r   r  dictr  r   r7  r5  rI  rg  r   floatrl  ro  rq  r   r   r  rk  r   r  r  r  r   r  r  r   r  r  r  r  r!  r&  r   ru   r6  r   r:  rC  rI  rP  r   rU  rX  ro  rk  r  r   r  r  r  r  r	   r  r  r  r  r  r  r  r=  r  r  r  r   r  r  boolr  r  r
   r  r  r  r  r  r  __classcell__)r   s   @r   r*   r*      s       Z Z Z Z Zx ') 5 5 5 5( -/ b b: b b b bH+ + +8+ + +8Mf M M M M^ *, ; ;V ; ; ; ;" 8<$]ajl RJ RJ RJC RJWZ RJquvzq{ RJ RJ RJ RJh2
 2
 2
4 2
 2
 2
 2
h <@d[] ;? ;? ;?S ;? ;?bfglbm ;? ;? ;? ;?zD D D5 D D D DL @DB Sc ScS Sc ScS\ Sc Sc Sc Scj <> 5 5s 5 5 5 5B <@            *
 
6 
 
 
 
@ >BPTcgpr =Y =Ys =Y# =Y]` =Y =Y =Y =Y~ =? 6 6 6 6 6 68 F    . 68 3 3 3F 3 3 3 34 6:" 4 47 4 4 4 4 42U U4 U U6 U U U Un *, U, U, U, U, U, U,n) ) ) ) ). 8<B )8 )8W )8 )8 )8 )8VI Iv I I I IV eg 
S 
S# 
SY 
SV[ 
S 
S 
S 
S XZ 	T 	Tc 	T 	T 	T 	T 	T Y[ 	U 	Us 	U% 	U 	U 	U 	U os{} T, T,3 T,i T,y T,Z_ T,hk T, T, T, T,l mqy{ V/ V/ V/I V/Y V/X] V/fi V/ V/ V/ V/p FH S1 S1$|*< S1 S1 S1 S1j	3 	3 	33 3 3P P P5 P P P Pd
: 
: 
: 9=R N/ N/S N/# N/ N/ N/ N/` 59 J Jc J J J JX AER E EtCy E# E E E EN 8<B L/ L/C L/ L/ L/ L/ L/\ 04$UYbd V? V? V?C V?s V?imnsit V? V? V? V?p 59tZ^gi P? P?c P? P?TW P?nrsxny P? P? P? P?d 7;\`ik X? X? X?3 X?VY X?ptuzp{ X? X? X? X?t ac %
 %
3 %
 %
C %
TW %
gt %
 %
 %
 %
N 154VZce -B -B# -BS -BPS -B -B -B -B^
 
 
 
 
 
0 JL '0 '0S '0 '0 '0 '0R =? > > > > > >0
 
h 
 
 
 
2 04$UYbd 'I 'I 'IC 'Is 'Iimnyiz 'I 'I 'I 'IR 37TX\eg )I )IC )Is )IRU )Ilpq|l} )I )I )I )IV[
 [
x [
; [
 [
 [
 [
z:s : : : :& DHPR Y Y YS Y Y Y Y4 CE S Ss SE SI[ S S S S FH S S# Su SL^ S S S S CE @ @s @E @I[ @ @ @ @@
 
f 
HZ 
 
 
 
. 8: 1 13 1h 1 1 1 16
 
x 
 
 
 
 ?C2 W W3 W W W W WB 37TX\eg ZF ZFC ZFs ZFRU ZF ZF ZF ZFx9 9 9 9 9 9v BFb F Fw F F F F EIQS &, &,3 &, &, &, &, &,P  " 9=4^bkm 8K 8K# 8KS 8KX[ 8K 8K 8K 8Kt' 'V ' ' ' 'R CGr 9& 9&3 9&i 9&V[ 9& 9& 9& 9&v 02 & &d8n & & & &P 7;2 
 
 
 
 
 
4 CGr Z Zd ZC Z Z Z Z6 fjx|  FH D. D.3 D. D.9 D.I D._b D.ru D.  MR D. D. D. D.L ;= 4 4c 4 4 4 4 44
 
J 
 
 
 
 "*%DW[ %P %P %P %PN# # #-t - - - - - -      r   r*   )1 ccxt.async_support.base.exchanger   ccxt.abstract.bingxr   rg  r  r  ccxt.base.typesr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   typingr   ccxt.base.errorsr   r   r   r   r    r!   r"   r#   r$   r%   r&   ccxt.base.decimal_to_precisionr'   ccxt.base.preciser(   r*    r   r   <module>r,     s   6 5 5 5 5 5 + + + + + +    y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y  y       * * * * * * 0 0 0 0 0 0 - - - - - - - - - - - - . . . . . . ' ' ' ' ' ' & & & & & & . . . . . . * * * * * * ) ) ) ) ) ) + + + + + + 9 9 9 9 9 9 % % % % % %@ @ @ @ @Hk @ @ @ @ @r   