
    !:hj-                    x   d dl mZ d dlm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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$m0Z0 d dl$m1Z1 d dl2m3Z3 d dl4m5Z5  G d dee      Z6y)    )Exchange)ImplicitAPIN)AnyBalances
CurrenciesCurrencyDepositAddressIntLeverage
MarginModeMarginModificationMarketNumOrder	OrderBookOrderRequest	OrderSide	OrderTypePositionStrStringsTickerTickersFundingRateFundingRatesTradeTradingFeeInterfaceTransactionTransferEntry)List)ExchangeError)AuthenticationError)PermissionDenied)AccountSuspended)ArgumentsRequired)
BadRequest)	BadSymbol)InsufficientFunds)InvalidOrder)OrderNotFound)NotSupported)OperationFailed)DDoSProtection)	TICK_SIZE)Precisec                       e Zd Zdef fdZi fdefdZi fdefdZde	e
   fdZd Zd Zde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dde
defdZddi fdededede	e   fdZddede
defdZdi fdededefdZi fdedefdZdi fdedefdZdde
defdZdddi fde dedefdZ!dde
fdZ"i fdefdZ#dde
fdZ$i fdede%fdZ&d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'fd!Z*dd"ede
de%fd#Z+i fde,fd$Z-de,fd%Z.ddi fdededede	e/   fd&Z0di fdede	e/   fd'Z1i fdefd(Z2dd)ede
fd*Z3i fded+e4d,e5fd-Z6i fded,e5fd.Z7i fded,e5fd/Z8di fded0e9d+e4d1e5d2e:f
d3Z;di fded0e9d+e4d1e5d2e:f
d4Z<i fd5e	e=   fd6Z>d7 Z?d0e fd8Z@dd9ede
deAfd:ZBd;e fd<ZCdi fd=ede fd>ZDdi fde fd?ZEdi fd@e	e   de fdAZFi fdBefdCZGdi fd=ede fdDZHdddi fde dedede	eA   fdEZIdddi fde dedede	eA   fdFZJdddi fde dedede	eA   fdGZKdddi fde dedefdHZLdddi fde dedefdIZMi fdJed1e5dKedLedeNf
dMZOdddi fdJe dedede	eN   fdNZPddOedPeQdeNfdQZRi fdJede	eS   fdRZTi fdJedeSfdSZUddPeQdeSfdTZVdddi fdJe dedede	eW   fdUZXdddi fdJe dedede	eW   fdVZYddWedPeQdeWfdXZZd;efdYZ[di fdZede fd[Z\i fded1e5de]fd\Z^i fded1e5de]fd]Z_i fded1e5de]fd^Z`dd_ede
de]fd`Zai fdedebfdaZcddbede
debfdcZddi fdbede fddZedddi fde dedefdeZfddPeQfdfZgdi fdgefdhZhdi fdJed1e5diedeWfdjZidk Zjdddi fde dedefdlZkdde
fdmZldi fded+e4deAfdnZmi fde	e/   fdoZndi fde fdpZodi fdqepde fdrZqddi fd=eded0e9d+e4d1e:d2e:deAfdsZri fdedesfdtZtddZedesfduZui fdedevfdvZwddwede
devfdxZxdy Zydzd{i ddfd|Zzd} Z{d~epf fdZ|de}dededededefdZ~ xZS )bingxreturnc                 n   | j                  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d/dd0dd1di d2dd3d4d5dd6dd7dd8dd9dd:dd;dd<dd=dd>dd?dd@ddAddBddCdi dDddEddFddGddHddIddJddKddLddMddNddOddPddQddRddSddTdddddddddUdVdWdXdYdZdZdZdZdZdZdZdZdZd[	dd\id]d^d_d`daddb| j	                  dc      | j	                  dc      ddde| j	                  df      | j	                  dg      dddhdidddjdkdbdldldldldldldldldmidldldldndodndpdndndodododododqdrdsdtdbdldlduiidvdldldldldwdxdoidridydbdldldldldzidododndndndndododododod{dndododndodododod|drdsdbdldldldldldldldldldldld}idndndndndndndodndldndndndndndld~dndndndododododnddndndndddsdtdbddliiidyd
dbdldldldldldldidndndndndndndndndndnd
dndndndndndnddndndddsid
dvdbdndndndiiid
dvdododldodndldoddododndnddriid
dvddndndddndndndddriidvdldndodndddlidrid
dvddlidldlddriidddvddniddniddnidiid
dvddnidndndddriiddvdldldlddxdlidr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        t        t         di ddddddddŜdddddɜddddʜddddddddќdddԜ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ٜddoiddddddݜdddddޜdd ddddߜddddddddddd d dddddddid	ddd d dd ddd d ddddldldd dd ddddiddiddd dddiddiddd      S )Nidr1   nameBingX	countriesUS	rateLimitd   versionv1	certifiedTprohasCORSspotmarginFswapfutureoption	addMargincancelAllOrderscancelAllOrdersAftercancelOrdercancelOrderscloseAllPositionsclosePositioncreateMarketBuyOrderWithCostcreateMarketOrderWithCostcreateMarketSellOrderWithCostcreateOrdercreateOrders$createOrderWithTakeProfitAndStopLosscreateReduceOnlyOrdercreateStopLossOrdercreateStopOrdercreateTakeProfitOrdercreateTrailingAmountOrdercreateTrailingPercentOrdercreateTriggerOrder	editOrderfetchBalancefetchCanceledOrdersfetchClosedOrdersfetchCurrenciesfetchDepositAddressfetchDepositAddressesfetchDepositAddressesByNetworkfetchDepositsfetchDepositWithdrawFeeemulatedfetchDepositWithdrawFeesfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchLeveragefetchLiquidationsfetchMarginAdjustmentHistoryfetchMarginModefetchMarketsfetchMarkOHLCVfetchMarkPricefetchMarkPricesfetchMyLiquidationsfetchMyTrades
fetchOHLCVfetchOpenInterestfetchOpenOrders
fetchOrderfetchOrderBookfetchOrdersfetchPositionfetchPositionHistoryfetchPositionModefetchPositionsfetchPositionsHistoryfetchTickerfetchTickers	fetchTimefetchTradesfetchTradingFeefetchTransfersfetchWithdrawals)reduceMarginsandbox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)	rA   rC   contractwalletsuser
subAccountaccountcopyTradingcswapz'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)	tierBasedrA   rC   requiredCredentials)apiKeysecretr      )server/timezcommon/symbolszmarket/tradesmarket/depthmarket/klinezticker/24hrticker/pricezticker/bookTicker      )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/cancelOpenOrderstrade/cancelAllAfter)r   post)publicprivater   )r   r   r   )zget/asset/transferasset/transfercapital/deposit/hisreccapital/withdraw/historyzpost/asset/transfer)r<   v2v3)r   zmarket/historicalTradeszmarket/markPriceKlinesztrade/multiAssetsRules)positionSide/dualtrade/batchCancelReplaceztrade/fullOrdermaintMarginRatioztrade/positionHistoryzpositionMargin/historyztwap/openOrdersztwap/historyOrdersztwap/orderDetailtrade/assetModezuser/marginAssets)ztrade/cancelReplacer   r   ztrade/closePositionztrade/getVstz
twap/orderztwap/cancelOrderr   )r   zquote/contractszquote/pricezquote/depthzquote/tradeszquote/premiumIndexzquote/fundingRatequote/klineszquote/openInterestzquote/tickerquote/bookTicker)user/balanceuser/positionszuser/incomer   ztrade/openOrderr   trade/marginTypetrade/leveragetrade/forceOrdersztrade/allOrderstrade/allFillOrdersztrade/fillHistoryzuser/income/exportr   r   )r   r   trade/closeAllPositionsr   r   r   trade/positionMarginztrade/order/test)r   r   trade/allOpenOrders)r   r   deleter   )zmarket/contractszmarket/premiumIndexzmarket/openInterestzmarket/klinesr   zmarket/ticker)
r   r   r   r   ztrade/orderDetailztrade/orderHistoryr   r   r   r   )r   r   r   r   r   r   )r   ztrade/cancelOrder)allPosition	allOrdersbalance)zcapital/config/getallzcapital/deposit/addresszcapital/innerTransfer/recordsz"capital/subAccount/deposit/addresszcapital/deposit/subHisrecz(capital/subAccount/innerTransfer/recordszcapital/deposit/riskRecords)zcapital/withdraw/applyzcapital/innerTransfer/applyz%capital/subAccountInnerTransfer/applyz capital/deposit/createSubAddress
   )listassetsallAccountBalance)createzapiKey/createzapiKey/editz
apiKey/delupdateStatus)uidzapiKey/queryaccount/apiPermissionsr   z!innerTransfer/authorizeSubAccountz subAccount/asset/transferHistory)z%subAccount/transferAsset/supportCoinszsubAccount/transferAsset)r<   r   authuserDataStream)r   putr   zswap/trace/currentTrack)zswap/trace/closeTrackOrderzswap/trace/setTPSLzspot/trader/sellOrderr   )r   r   r   )
rA   rC   r   r   r   r   r   r   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100410100421100440100500)1005038000180012800148001680017100414100419100437101204110425)exactbroadcommonCurrenciesSnowmanOmniCatz$NAP	TRUMPMAGATRUMP)SNOWOMNINAPr
  TRUMPSOLFUNDPFUTURESSFUTURES)rA   rC   rD   )r  r  r  i  CCXTETHERC20BTCLTC)r  USDTUSDCr  r  ARBITRUMPOLYGON)ARBMATIC)defaultTypeaccountsByTypeaccountsById
recvWindowbrokerdefaultNetworksnetworks)lastmarkindex)triggerPriceTypeprice)IOCFOKPOGTD)
marginModetriggerPricer'  triggerDirectionstopLossPricetakeProfitPriceattachedStopLossTakeProfittimeInForcehedgedtrailingleveragemarketBuyRequiresPricemarketBuyByCostselfTradePreventionicebergmaxi      )r-  limitdaysBack	untilDayssymbolRequired)r-  triggerr5  r@  )r-  r=  rA  r5  r@    i N     )r-  r=  r>  r?  rA  r5  r@  )r-  r=  r>  daysBackCanceledr?  rA  r5  r@  r=    )	r   rP   rQ   rr   rv   ru   rx   r]   rs   defaultForLinear)r=  r>  r?  )extendsrr   rx   )r'  r2  r5  )r=  r?  )rG  rP   rr   rx   r]   rG  defaultForInverse)linearinverse)rG  rx   defaultForFuture)rF  rH  rA   rC   rK  rD   )optionsfeatures)deep_extendsuperr1   describeparse_numberr.   r&   r"   r#   r-   r!   r(   r,   r'   r*   r$   r)   )self	__class__s    D/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/bingx.pyrP  zbingx.describe   s   eT ; = K
@
'K
@
GK
@
 $K
@
 	K
@

 tK
@
 K
@
 4K
@
  LLL %L 	L
 %L %L TL "4L 'L tL L $TL  L /L ,TL  0!L" t#L$ %L& 7'L( ()L* &t+L, "4-L. (/L0 ,T1L2 -d3L4 %d5L6 T7L8 9L: &t;L< $T=L> "4?L@ &tALB (CLD 1$ELF  GLH *:ILJ +DKLL #DMLN *4OLP $TQLR  SLT $UULV /WLX "4YLZ [L\ !$]L^ !$_L` "4aLb &tcLd  eLf dgLh $TiLj "4kLl dmLn !$oLp tqLr  sLt 'uLv $TwLx !$yLz ({L| t}L~ L@ TALB tCLD "4ELF !$GLH #DILJ !%#!!%#' WLK
@
j kK
@
l  RAA EDA"GD#HB
 E ,:=%mK
@
T !$!..w7!..w7  '!..x8!..x8UK
@
n "$oK
@
v  "/023120101/00156	$# 014578237834$ 010156=>67:;89%$ D !!0101$# "6723:;<=	$ !6q%
$U7v "01;<:;:;	$# 67<=34459::;3467453456$ 8956<=7801./4534	%$"J "/034/0/001675601670145$#" 1223/04534/0452356347856677845$$ 0156;<8945238945	% 015678'9!$!2h !! .$#o^@ !457878120112$	# 34567845566745782301$ 012378;<4589% 8956'+$%'R !!/0-.+,$$
 !9:;<ABFG=>LM?@$ ;<?@IJDE	%$, !(**+56$ +-12/0./02%$( "'(01:;56	$ !DQ%
$ %$F(" NO@A)"	(
!: ! 0!% !1!$ !1!'
$  ! 91$ ?@679;%		$  !23:;<=$ !6q%	$W	ywK
@
j kK
@
J YKK
@
L :. + :	
 > + = = 1 1 / j j o i  m!" o#$ ,'.'**..(/*9< ? MK
@
N !!$#!OK
@
^  &"&(# # & (!
 '  ##  $ &&+8  $&+(,$($(%)-
 -2)-+/ )-(,)-1
 &*7 $(#'"&#(	( #'$($)27+//4#(? $D q% ',!$$&%'*.& ',#($)*.	# ',!%#($)*/( ',!%$)%&#($)*.$ ',!%$(,0%&#($)*.	*  #[P%d  2!%$(%)&
 $(&  2,06:$)$ "&$%%&&
 $(!$%)*( "#5 "#6 	  2#'% "#5 "#5 	uBQK
@
 K
 K
	    c                 l    | j                  |      }| j                  |d      }| j                  |d      S )ac  
        fetches the current integer timestamp in milliseconds from the bingx server

        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
        data
serverTime)swapV2PublicGetServerTime	safe_dictsafe_integer)rR  paramsresponserW  s       rT  
fetch_timezbingx.fetch_time  s9     11&9 ~~h/  |44rU  c                 |   | j                  d      sy| j                  | j                  dd      }|ry| j                  |      }| j	                  |dg       }i }t        dt        |            D ]J  }||   }| j                  |d      }| j                  |      }	| j                  |d      }
| j	                  |d      }i }t        dt        |            D ]  }||   }| j                  |d	      }| j                  |      }d
| j                  |d      | j                  |d      di}| j                  | j                  | j                  |d                  }|||| j                  |d      d| j                  |d      | j                  |d      ||d	||<    | j                  ||	|d|
ddd|dddd      ||	<   M |S )a&  
        fetches all available currencies on an exchange

        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sandboxModerW  r   coinr5   networkListnetworkwithdrawwithdrawMinwithdrawMaxminr;  withdrawPrecisionwithdrawFeedepositEnablewithdrawEnable)	infor4   rc  feeactivedepositrd  	precisionlimitscrypto)rm  coder4   rq  r5   ro  rp  rd  r#  rn  rr  type)check_required_credentials	safe_boolrL  &walletsV1PrivateGetCapitalConfigGetall	safe_listrangelensafe_stringsafe_currency_codenetwork_id_to_codesafe_numberrQ  parse_precisionsafe_currency_structure)rR  r\  	isSandboxr]  rW  resultientry
currencyIdrt  r5   rb  r#  j
rawNetworkrc  networkCoderr  rq  s                      rT  fetch_currencieszbingx.fetch_currencies  s    ..u5NN4<<F	>>vFN ~~h3q#d)$ *	AGE))%8J**:6D##E62D..>KH1c+./ (^
**:yA"55g>#//
MJ#//
MJ!  !--d.B.B4CSCST^`sCt.uv	&!*++JF"#~~j/J $z;K L!*$
)%,  77 ! $ 9 F4L;*	V rU  c                     | j                  |      }| j                  |d      }| j                  |dg       }| j                  |      S )NrW  symbols)spotV1PublicGetCommonSymbolsrZ  ry  parse_markets)rR  r\  r]  rW  marketss        rT  fetch_spot_marketszbingx.fetch_spot_markets'  sG    44V<8 ~~h/..y"5!!'**rU  c                 l    | j                  |      }| j                  |dg       }| j                  |      S NrW  )swapV2PublicGetQuoteContractsry  r  rR  r\  r]  r  s       rT  fetch_swap_marketszbingx.fetch_swap_marketsH  s8    55f=@ ..626!!'**rU  c                 l    | j                  |      }| j                  |dg       }| j                  |      S r  )cswapV1PublicGetMarketContractsry  r  r  s       rT  fetch_inverse_swap_marketsz bingx.fetch_inverse_swap_marketsl  s7    77?& ..626!!'**rU  marketc                    | j                  |d      }|j                  d      }|d   }|d   }| j                  |      }| j                  |      }| j                  |d      }d}	d}
| j                  |d      }||}d}	d}
| j                  |      }| j                  |d	      }|0| j	                  | j                  | j                  |d
                  }| j                  |d      }|0| j	                  | j                  | j                  |d                  }|dnd}|dk(  }|dk(  }|dz   |z   }||d|z   z  }| j                  | j                  |i       }|r| j	                  d      nd }d}| j                  |d      dk(  r| j                  |d      dk(  rd}n;| j                  |d      r)| j                  |d      r| j                  |d      dk(  rd}|rd n|	}|rd n|
}d }|s| j                  |dd      }| j                  |d      }|dk(  rd }| j                  i d|d|d|d|d|d|d |d!|d"|d|d#dd|d$dd%dd&|d'|d(||| j                  |d)      | j                  |d*      | j                  |d+      |d d d d ||d,d d d-|d d-|d d-| j                  |g d.      | j                  |d/      d-d0||d1      S )2Nsymbol-r   r   currencyFTminTickSizetickSizepricePrecisionstepSizequantityPrecisionrC   rA   /:1apiStateOpentrueapiStateCloseapiStateSellapiStateBuystatusminQtytradeMinQuantity
timeOnliner4   baser   settlebaseIdquoteIdsettleIdru  rB   rD   rE   ro  r   rI  r   r   r   )amountr(  rg  )minNotionaltradeMinUSDTminTradeValuemaxNotional)r6  r  r(  cost)rJ  r   r   r   contractSizeexpiryexpiryDatetimestrike
optionTyperq  rr  createdrm  )r|  splitr}  r  rQ  r  rZ  r   rw  safe_number_2r[  safe_market_structuresafe_number_n)rR  r  r4   symbolPartsr  r  r  r   r  checkIsInversecheckIsLinearr  r  r  r  ru  rA   rC   r  r   r  isActive	isInverseisLinear	minAmountr  s                             rT  parse_marketzbingx.parse_market  s   fh/hhsmQa.&&v.''0##FJ7&&v}="H!N!M((2))&*=!!..t/C/CDDTDTU[]mDn/opN ,,VZ@$ $ 1 1$2F2FtGWGWX^`sGt2u v ,v6v~v~e#cFl"F~~diir226t((-TV^4>TEUEUV\^mEnrxExH^^FN3v}8]cgcscstz  }E  dF  JM  dMH!D	 4}	**68=OPI&&v|<
?J)) 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%%dG4''i8("+'  
 %
 '
  --f6fg++FMB$ "e3+
 3 3	rU  c                    | j                  |      g}| j                  | j                  dd      }|s@|j                  | j	                  |             |j                  | j                  |             |}| j                  |dg       }| j                  |dg       }| j                  |dg       }| j                  ||      }| j                  ||      S )a  
        retrieves data on all markets for bingx

        https://bingx-api.github.io/docs/#/spot/market-api.html#Query%20Symbols
        https://bingx-api.github.io/docs/#/swapV2/market-api.html#Contract%20Information
        https://bingx-api.github.io/docs/#/en-us/cswap/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`  Fr   r   r   )r  rw  rL  appendr  r  ry  array_concat)	rR  r\  requestsr  promiseslinearSwapMarketsinverseSwapMarketsspotMarketsswapMarketss	            rT  fetch_marketszbingx.fetch_markets  s     ++F34NN4<<F	OOD;;FCDOOD33F;< NN8Q;!^^Ha<nnXq"5''(9;MN  k::rU  r   Nr  sincer=  c           	      t   | j                          d}| j                  |ddd      \  }}|r| j                  d|||||d      S | j                  |      }d|d   i}| j	                  | j
                  ||      |d<   |t        |d	z
  d
      |d<   |||d<   | j                  |dd      }	|	| j                  |dg      }|	|d<   d}
|d   r"| j                  | j                  ||            }
n|d   r"| j                  | j                  ||            }
nl| j	                  |d      }| j                  |d      }|dk(  r"| j                  | j                  ||            }
n!| j                  | j                  ||            }
| j                  |
dg       }t        |t               s|g}| j#                  |||||      S )a`  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://bingx-api.github.io/docs/#/swapV2/market-api.html#K-Line%20Data
        https://bingx-api.github.io/docs/#/spot/market-api.html#Candlestick%20chart%20data
        https://bingx-api.github.io/docs/#/swapV2/market-api.html#%20K-Line%20Data
        https://bingx-api.github.io/docs/#/en-us/swapV2/market-api.html#Mark%20Price%20Kline/Candlestick%20Data
        https://bingx-api.github.io/docs/#/en-us/cswap/market-api.html#Get%20K-line%20Data

        :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 [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        Frs   paginaterE  r  r4   intervalNr   r   	startTimer=  untilendTimerA   rJ  r(  r%  rW  )load_marketshandle_option_and_params"fetch_paginated_call_deterministicr  r|  r   r;  safe_integer_2omitspotV1PublicGetMarketKlineextendcswapV1PublicGetMarketKlines$swapV1PublicGetMarketMarkPriceKlinesswapV3PublicGetQuoteKlines
safe_value
isinstancer   parse_ohlcvs)rR  r  	timeframer  r=  r\  r  r  requestr  r]  r(  ohlcvss                rT  fetch_ohlcvzbingx.fetch_ohlcv  s   & 	88z[`a&::<QVX]_hjprvwwV$fTl
 #..t	9U
#&uqy!#4GK $GG##FGY?YYvy1F!&GI&>66t{{7F7STHi <<T[[RX=YZ((9673F?#HHU\^dIefH#>>t{{7TZ?[\HH 626&$'XF  E5IIrU  c           	         t        |t              rh| j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      gS | j	                  |dd      | j                  |d	      | j                  |d
      | j                  |d      | j                  |d      | j                  |d      gS )Nr   r   r         r   time	closeTimeopenhighlowclosevolume)r  r   r[  r  r  )rR  ohlcvr  s      rT  parse_ohlcvzbingx.parse_ohlcvU  s    D eT"!!%+  *  *  *  *  *  v{;UF+UF+UE*UG,UH-
 	
rU  c                    | j                          | j                  |      }d|d   i}|t        |d      |d<   d}d}| j                  d||      \  }}|dk(  r"| j	                  | j                  ||            }n!| j                  | j                  ||            }| j                  |dg       }	| j                  |	|||      S )	a  
        get the list of most recent trades for a particular symbol

        https://bingx-api.github.io/docs/#/spot/market-api.html#Query%20transaction%20records
        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>`
        r  r4   Nr:   r=  r   rA   rW  )	r  r  rh  handle_market_type_and_paramsspotV1PublicGetMarketTradesr  swapV2PublicGetQuoteTradesry  parse_trades)
rR  r  r  r=  r\  r  r  r]  
marketTypetradess
             rT  fetch_tradeszbingx.fetch_trades  s     	V$fTl
 "5#GG
!??vW]^
F77GV8TUH66t{{7F7STHD &"5  >>rU  tradec                 x   | j                  |g d      }| j                  |d      }|| j                  |      }|dk(  rd }| j                  |d      }| j                  |g d      }| j	                  |      }| j                  |d      }| j                  |dd      }	| j                  |g d	      }
d }|
||
s|rd
nd}| j                  |dd      }||
|
|
s|rdnd}d}| j                  |d      }||rdnd}| j                  |d      }||rd
nd}| j                  |g d      }|F|d   rAd|v r=| j                  |d   d      }| j                  |d      }t        j                  ||      }| j                  | j                  |ddg      ||| j                  |      | j                  |	|d      | j                  |dd      | j                  |d      | j                  |      || j                  |g d      ||| j!                  t        j"                  | j                  |dd                  |d d!|      S )"N)r  filledTmT	tradeTimer  r   quoteQty)r  NcommissionAssetmsr  )
buyerMakerisBuyerMakerr   r   r   sideSsellbuyisBuyerisMaker)qtyr  qrC   r  rm  r  r4   tr  orderIdr  o)r(  p
tradePrice
commissionn)r  r  )r4   rm  	timestampdatetimer  orderru  r  takerOrMakerr(  r  r  rn  )safe_integer_nr|  	parse8601safe_string_nr}  rw  safe_string_2safe_bool_nsafe_string_lower_2r/   
string_mul
safe_tradeiso8601safe_symbolsafe_string_lowerparse_order_siderQ  
string_abs)rR  r  r  r  
datetimeIdr  r  currencyCoder
  marketIdr  takeOrMakerr  r  r  r  r  r  s                     rT  parse_tradezbingx.parse_trade  sr   X ""5*PQ%%eZ8
!>>*-D19Dz2''/ST
..z:NN5#&%%eS(;''/VW$!-&2a'gK''vs;<(am".!v%%..	2#5D..	2%,''K##E+ABF6NE8I++F6N<NOL%%eX6F''=F$$UT3K8T*&&x=''y#>**5#6))$/'''/KL))'*<*<T=O=OPUWceh=i*jk( 
" # 	rU  c           	      $   | j                          | j                  |      }d|d   i}|||d<   d}d}| j                  d||      \  }}|dk(  r"| j                  | j	                  ||            }nH|d   r"| j                  | j	                  ||            }n!| j                  | j	                  ||            }| j                  |di       }| j                  |d	      }	| j                  |d
d      }
| j                  ||d   |
dddd      }|	|d<   |S )a  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://bingx-api.github.io/docs/#/spot/market-api.html#Query%20depth%20information
        https://bingx-api.github.io/docs/#/swapV2/market-api.html#Get%20Market%20Depth
        https://bingx-api.github.io/docs/#/en-us/cswap/market-api.html#Query%20Depth%20Data

        :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
        r  r4   Nr=  rw   rA   rJ  rW  lastUpdateIdr  tsbidsasksr   r   nonce)r  r  r  spotV1PublicGetMarketDepthr  cswapV1PublicGetMarketDepthswapV2PublicGetQuoteDepthrZ  r[  r  parse_order_book)rR  r  r=  r\  r  r  r]  r  	orderbookr8  r  r  s               rT  fetch_order_bookzbingx.fetch_order_bookh  s5    	V$fTl
 $GG
!??@PRXZ`a
F66t{{7F7STHi ;;DKKQW<XY99$++gv:VWV NN8VR8	!!)^<''	3=	&&y&2BIvW]_`bcdwrU  c                 0   | j                          | j                  |      }d|d   i}d}|d   r"| j                  | j                  ||            }n!| j	                  | j                  ||            }| j                  |dg       }| j                  ||      S )a  
        fetch the current funding rate

        https://bingx-api.github.io/docs/#/swapV2/market-api.html#Current%20Funding%20Rate
        https://bingx-api.github.io/docs/#/en-us/cswap/market-api.html#Price%20&%20Current%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>`
        r  r4   NrJ  rW  )r  r  "cswapV1PublicGetMarketPremiumIndexr   swapV2PublicGetQuotePremiumIndexry  parse_funding_raterR  r  r\  r  r  r]  rW  s          rT  fetch_funding_ratezbingx.fetch_funding_rate  s     	V$fTl
 )>>t{{7TZ?[\H<<T[[RX=YZH" ~~h3&&tV44rU  r  c                     | j                          | j                  |dd      }| j                  | j                  |            }| j	                  |dg       }| j                  ||      S )a  
        fetch the current funding rate for multiple symbols

        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 list of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-structure>`
        rC   TrW  )r  market_symbolsrA  r  ry  parse_funding_rates)rR  r  r\  r]  rW  s        rT  fetch_funding_rateszbingx.fetch_funding_rates  sb     	%%gvt<88V9LM~~h3''g66rU  c                 ^   | j                  |d      }| j                  |d      }i d|d| j                  ||dd      d| j                  |d      d| j                  |d      dd d	d d
d dd d| j                  |d      dd dd dd d|d| j	                  |      dd dd dd dd iS )Nr  nextFundingTimerm  r  rC   	markPrice
indexPriceinterestRateestimatedSettlePricer  r  fundingRatelastFundingRatefundingTimestampfundingDatetimenextFundingRatenextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetimer  )r|  r[  r*  r  r)  )rR  r   r  r0  rT  s        rT  rB  zbingx.parse_funding_rate  sL    ##Hh7#00;LM
H
d&&xfE
 ))(K@
 $**8\B	

 D
 #D
 
 
 4++H6GH
 
 t
 t
 #$8
 "4<<0D#E
 "4
  '!
" &t#
$ %
 	
rU  c                    |t        | j                  dz         | j                          d}| j                  |dd      \  }}|r| j	                  d|||d|      S | j                  |      }d|d   i}|||d<   |||d	<   | j                  |d
d      }|| j                  |d
g      }||d<   | j                  | j                  ||            }	| j                  |	dg       }
| j                  |
|||      S )a  
        fetches historical funding rate prices

        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>`
        z5 fetchFundingRateHistory() requires a symbol argumentFrg   r  8hr  r4   r  r=  r  rW  )r%   r4   r  r  r  r  r  r  swapV2PublicGetQuoteFundingRater  ry  parse_funding_rate_histories)rR  r  r  r=  r\  r  r  r  r  r]  rW  s              rT  fetch_funding_rate_historyz bingx.fetch_funding_rate_history0  s*    >#DGG.e$eff88AZ\fg&::;TV\^cejlprxyyV$fTl
 #(GK $GG##FG[AYYvy1F#(GK 77GV8TU ~~h300vueLLrU  c                     | j                  |d      }|| j                  | j                  |d      |dd      | j                  |d      || j	                  |      dS )NfundingTimer  r  rC   rO  )rm  r  rO  r  r  )r[  r*  r|  r  r)  )rR  r   r  r  s       rT  parse_funding_rate_historyz bingx.parse_funding_rate_historyc  se     %%h>	&&t'7'7('KVUXZ`a++HmD"Y/
 	
rU  c                    | j                          | j                  |      }d|d   i}d}|d   r"| j                  | j                  ||            }n!| j	                  | j                  ||            }i }|d   r'| j                  |dg       }| j                  |di       }n| j                  |di       }| j                  ||      S )a  
        retrieves the open interest of a trading pair

        https://bingx-api.github.io/docs/#/swapV2/market-api.html#Get%20Swap%20Open%20Positions
        https://bingx-api.github.io/docs/#/en-us/cswap/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:
        r  r4   NrJ  rW  r   )r  r  "cswapV1PublicGetMarketOpenInterestr   swapV2PublicGetQuoteOpenInterestry  rZ  parse_open_interest)rR  r  r\  r  r  r]  r  rW  s           rT  fetch_open_interestzbingx.fetch_open_interestt  s     	V$fTl
 )>>t{{7TZ?[\H<<T[[RX=YZH: )>>(FB7D^^D!R0F^^Hfb9F''77rU  c                     | j                  |dd      }| j                  |d      }| j                  ||dd      }| j                  |d      }| j	                  |d d d ||| j                  |      |d|      S )Nr  r  r  r  rC   openInterest)r  
baseVolumequoteVolumeopenInterestAmountopenInterestValuer  r  rm  )r  r|  r*  r  safe_open_interestr)  )rR  interestr  r  r4   r  rg  s          rT  rd  zbingx.parse_open_interest  s    $ ''&+F	h1!!"fc6:''.A&&"&!-"Y/	(
 	 		rU  c                    | j                          | j                  |      }d|d   i}d}|d   r"| j                  | j                  ||            }nH|d   r"| j	                  | j                  ||            }n!| j                  | j                  ||            }| j                  |d      }|%| j                  |di       }| j                  ||      S | j                  |di       }| j                  ||      S )a  
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://bingx-api.github.io/docs/#/en-us/swapV2/market-api.html#Get%20Ticker
        https://bingx-api.github.io/docs/#/en-us/spot/market-api.html#24-hour%20price%20changes
        https://bingx-api.github.io/docs/#/en-us/cswap/market-api.html#Query%2024-Hour%20Price%20Change

        :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>`
        r  r4   NrA   rJ  rW  r   )	r  r  spotV1PublicGetTicker24hrr  cswapV1PublicGetMarketTickerswapV2PublicGetQuoteTickerry  rZ  parse_ticker)	rR  r  r\  r  r  r]  rW  firstdataDicts	            rT  fetch_tickerzbingx.fetch_ticker  s     	V$fTl
 &>55dkk'66RSHi <<T[[RX=YZ::4;;wPV;WX: ~~h/NN4B/E$$UF33>>(FB7  622rU  c                    | j                          d}|6| j                  |      }| j                  |d      }|| j                  |      }d}| j	                  d||      \  }}d}| j                  d||      \  }}d}|dk(  r| j                  |      }n(|dk(  r| j                  |      }n| j                  |      }| j                  |d      }| j                  ||      S )a  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market

        https://bingx-api.github.io/docs/#/en-us/swapV2/market-api.html#Get%20Ticker
        https://bingx-api.github.io/docs/#/en-us/spot/market-api.html#24-hour%20price%20changes
        https://bingx-api.github.io/docs/#/en-us/cswap/market-api.html#Query%2024-Hour%20Price%20Change

        :param str[]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        Nr   r   rA   rJ  rW  )r  rF  r|  r  r  handle_sub_type_and_paramsro  rp  rq  ry  parse_tickers)	rR  r  r\  r  firstSymbolru  subTyper]  tickerss	            rT  fetch_tickerszbingx.fetch_tickers
  s     	))'2G**7A6K&[199.&RXYf99.&RXY6>55f=H)#<<VD::6B< ..62!!'733rU  c                    | j                          | j                  |      }d}| j                  d||d      \  }}d|d   i}d}|dk(  r"| j                  | j	                  ||            }n!| j                  | j	                  ||            }t        |d   t              r&| j                  | j                  |d   di       |      S | j                  |d   |      S )	a  
        fetches mark prices for the market

        https://bingx-api.github.io/docs/#/en-us/swapV2/market-api.html#Mark%20Price%20and%20Funding%20Rate

        :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 dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        Nro   rI  r  r4   rJ  rW  r   )
r  r  rw  r@  r  rA  r  r   rr  rZ  )rR  r  r\  r  rz  r  r]  s          rT  fetch_mark_pricezbingx.fetch_mark_priceI  s     	V$99:JFTZ\defTl
 i>>t{{7TZ?[\H$ <<T[[RX=YZH hv&-$$T^^HV4Da%LfUU  &!16::rU  c                 d   | j                          d}|6| j                  |      }| j                  |d      }|| j                  |      }d}| j	                  d||d      \  }}d}|dk(  r| j                  |      }n| j                  |      }| j                  |d      }| j                  ||      S )a  
        fetches mark prices for multiple markets

        https://bingx-api.github.io/docs/#/en-us/swapV2/market-api.html#Mark%20Price%20and%20Funding%20Rate

        :param str[] [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   rp   rI  rJ  rW  )	r  rF  r|  r  rw  r@  rA  ry  rx  )rR  r  r\  r  ry  rz  r]  r{  s           rT  fetch_mark_priceszbingx.fetch_mark_prices  s     	))'2G**7A6K&[199:KVU[]efi>>vFH<<VDH< ..62!!'733rU  tickerc           
         | j                  |d      }| j                  |d      }|dnd}| j                  ||d |      }|d   }| j                  |d      }| j                  |d      }| j                  |d      }	| j                  |d      }
| j                  |d	      }| j                  |d
      }| j                  |d      }||j                  dd      }| j                  |d      }| j                  |d      }|dk(  rd }| j	                  |      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  i d|d|d|d|d|	d|d|d|d|dd d|d|
d d d!d d"|d#|d$d ||| j                  |d%      | j                  |d&      |d'|      S )(Nr  lastQtyrA   rC   	openPrice	highPricelowPrice	lastPriceri  r  priceChangePercent% priceChanger  r   bidPricebidQtyaskPriceaskQtyr  r  r  r  bid	bidVolumeask	askVolumevwapr  r  r$  previousClosechange
percentageaveragerK  rL  )rh  ri  rK  rL  rm  )r|  safe_marketreplacer[  r)  safe_ticker)rR  r  r  r0  r  ru  r  r  r  r  r  ri  rh  r  r  r5  r  r  r  r  r  s                        rT  rr  zbingx.parse_ticker  s   d ##FH5""695 "/v!!(FD$?!44vz2  5&&v}=%%fh7
%%f.BC
!#++C4J!!&-8v{37B<<#vz2$$VX6	vz2$$VX6	 !
f!
!
 !
 D	!

 3!
 3!
 !
 3!
 !
 D!
 D!
 U!
 D!
 T!
 f!
  *!!
" t#!
$ %&))&+>**6<@-!
. / 	rU  c                 |   | j                          d}d}| j                  |ddd      \  }}d}| j                  dd|      \  }}| j                  dd|      \  }}|r| j	                  |      }n?|dk(  r| j                  |      }n(|dk(  r| j                  |      }n| j                  |      }| j                  |      S )a  
        query for balance and get the amount of funds available for trading or funds locked in orders

        https://bingx-api.github.io/docs/#/spot/trade-api.html#Query%20Assets
        https://bingx-api.github.io/docs/#/swapV2/account-api.html#Get%20Perpetual%20Swap%20Account%20Asset%20Information
        https://bingx-api.github.io/docs/#/standard/contract-interface.html#Query%20standard%20contract%20balance
        https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Query%20Account%20Assets

        :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>`
        Nr[   standardFrA   rJ  )	r  r  rw  r  contractV1PrivateGetBalancespotV1PrivateGetAccountBalancecswapV1PrivateGetUserBalanceswapV2PrivateGetUserBalanceparse_balance)rR  r\  r]  r  rz  r  marketTypeQuerys          rT  fetch_balancezbingx.fetch_balance  s     	88Q[]bc&99.$PVW&*&H&HY]_e&f#
O77HH& 6!::?KH$ )#<<_M*  ;;OL* !!(++rU  c                 B   d|i}| j                  |d      }| j                  |d      }|d u}| j                  |di       }| j                  |d      }| j                  |d      }|d u}	|rt        dt        |            D ]  }
||
   }| j	                  |d      }| j                  |      }| j                         }| j                  |dd      |d<   | j	                  |d	      |d
<   | j	                  |d      |d<   |||<    n|	rt        dt        |            D ]i  }
||
   }| j	                  |d      }| j                  |      }| j                         }| j	                  |d      |d<   | j	                  |d      |d
<   |||<   k n| j                  |di       }| j                  |d      }|rb| j	                  |d      }| j                  |      }| j                         }| j	                  |d      |d<   | j	                  |d	      |d
<   |||<   | j                  |      S )Nrm  rW  r   balancesassetavailableMarginavailableBalancefree
usedMarginusedmaxWithdrawAmounttotallockedr   )	ry  rZ  rz  r{  r|  r}  r   r$  safe_balance)rR  r]  r  standardAndInverseBalancesfirstStandardOrInverseisStandardOrInversespotDataspotBalances	firstSpotisSpotr  r   r  rt  r   linearSwapDatalinearSwapBalances                    rT  r  zbingx.parse_balance  sJ   ^ )%)^^Hf%E"!%0JA!N4D@>>(FB7~~h
;NN<3	$&1c"<=> '4Q7!--gw?
..z:,,."&"4"4W>OQc"d"&"2"27L"I#'#3#3G=P#Q &t' 1c,/0 '&q/!--gw?
..z:,,."&"2"27F"C"&"2"27H"E&t' "^^HfbAN $~y I !--.?I
..z:,,."&"2"23DFW"X"&"2"23Dl"S&t  ((rU  c                    | j                          | j                  |      }d|d   i}|||d<   |||d<   | j                  d||      \  }}d}|d   r"| j                  | j	                  ||            }nt        | j                  dz         | j                  |d	i       }| j                  |d
g       }	| j                  |	      }
| j                  |
|||      S )ab  
        fetches historical positions

        https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Query%20Position%20History

        :param str symbol: unified contract symbol
        :param int [since]: the earliest time in ms to fetch positions for
        :param int [limit]: the maximum amount of records to fetch
        :param dict [params]: extra parameters specific to the exchange api endpoint
        :param int [params.until]: the latest time in ms to fetch positions for
        :returns dict[]: a list of `position structures <https://docs.ccxt.com/#/?id=position-structure>`
        r  r4   NpageSizestartTsendTsrI  zC fetchPositionHistory() is not supported for inverse swap positionsrW  positionHistory)r  r  handle_until_option$swapV1PrivateGetTradePositionHistoryr  r+   r4   rZ  ry  parse_positionsfilter_by_symbol_since_limit)rR  r  r  r=  r\  r  r  r]  rW  records	positionss              rT  fetch_position_historyzbingx.fetch_position_history  s     	V$fTl
 "'GJ!&GI227GVL(@@WV\A]^Htww)nnoo: ~~h3..'8"=((1	00FE5QQrU  c                    | j                          | j                  |      }d}| j                  |ddd      \  }}d}|r| j                  |      }nzd}|6| j                  |      }| j	                  |d      }|| j                  |      }d}| j                  d||      \  }}|dk(  r| j                  |      }n| j                  |      }| j                  |dg       }| j                  ||      S )a  
        fetch all open positions

        https://bingx-api.github.io/docs/#/en-us/swapV2/account-api.html#Query%20position%20data
        https://bingx-api.github.io/docs/#/en-us/standard/contract-interface.html#position
        https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Query%20warehouse

        :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 structures <https://docs.ccxt.com/#/?id=position-structure>`
        Nr|   r  Fr   rJ  rW  )r  rF  r  contractV1PrivateGetAllPositionr|  r  rw  cswapV1PrivateGetUserPositionsswapV2PrivateGetUserPositionsry  r  )	rR  r  r\  r  r]  r  ry  rz  r  s	            rT  fetch_positionszbingx.fetch_positions7	  s    	%%g.88AQS]_de&;;FCHF"--g6"..w:*![[5FG"==>NPVX^_OGV)#>>vF8  ==fE@ NN8VR8	##Iw77rU  c                    | j                          | j                  |      }|d   st        | j                  dz         d|d   i}d}|d   r"| j	                  | j                  ||            }n!| j                  | j                  ||            }| j                  |dg       }| j                  |di       }| j                  ||      S )	a  
        fetch data on a single open contract trade position

        https://bingx-api.github.io/docs/#/en-us/swapV2/account-api.html#Query%20position%20data
        https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Query%20warehouse

        :param str symbol: unified market symbol of the market the position is held in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        rC   z+ fetchPosition() supports swap markets onlyr  r4   NrJ  rW  r   )
r  r  r&   r4   r  r  r  ry  rZ  parse_position)rR  r  r\  r  r  r]  rW  rs  s           rT  fetch_positionzbingx.fetch_position	  s     	V$f~TWW'TTUUfTl
 )::4;;wPV;WXH8 99$++gv:VWH@ ~~h3tQ+""5&11rU  positionc                    | j                  |dd      }|j                  dd      }| j                  |d      }d }||rdnd}| j                  |d      }| j	                  i d|d	| j                  |d
      d| j                  ||dd      d| j                  |d      d|dd d| j                  |dd      d| j                  |d      d| j                  |d      dd d| j                  |d      dd d| j                  |d      dd d| j                  |d      dd d|| j                  |      | j                  |d       d d d | j                  |d!      d | j                  |d"      d d d d#      S )$Nr  r  r  r  isolatedcrossopenTimerm  r4   
positionIdrC   notionalpositionValuer-  liquidationPrice
entryPriceavgPriceunrealizedPnlunrealizedProfitrealizedPnlrealisedProfitr  	contractspositionAmtr  rK  r  r  positionSider4  r  
updateTimeinitialMarginr6  )r  lastUpdateTimestampmaintenanceMarginmaintenanceMarginPercentage
collateralr  initialMarginPercentager6  marginRatior0  r1  )
r|  r  rw  r[  safe_positionr*  r  r  r+  r)  )rR  r  r  r0  r  r-  r  s          rT  r  zbingx.parse_position	  s   f ##Hh;##C->>(J7
'/WJ%%h
;	!! #
H#
$""8\:#
 d&&xfE#
 ((?C	#

 *#
 #
 $,,Xz<P#
 T--h8JK#
 4++H6FG#
 $#
 ))(MB#
 D#
 ))(K@#
 #
 D**8^D#
  d!#
" ##
$ Y/#'#4#4X|#L!%+/!--hH'+((:>!#9#
  	rU  r  r  c                 8    ||d<   | j                  |d||d|      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)rR  r  r  r  r\  s        rT  create_market_order_with_costz#bingx.create_market_order_with_costa
  s)     #'  4tVLLrU  c                 8    ||d<   | j                  |dd|d|      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>`
        r  r  r  Nr  rR  r  r  r\  s       rT  !create_market_buy_order_with_costz'bingx.create_market_buy_order_with_costm
  s)     #'  5$fMMrU  c                 8    ||d<   | j                  |dd|d|      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>`
        r  r  r  Nr  r  s       rT  "create_market_sell_order_with_costz(bingx.create_market_sell_order_with_costx
  s)     #'  64vNNrU  ru  r  r(  c           
         | j                  |      }d}d}	| j                  d||      \  }	}|j                         }|d   ||j                         d}
|dk(  }|	dk(  }|dk(  }|r|rt        | j                  dz         | j                  |d	      }| j                  |d
      }| j                  |dd      }|du}|du}|du}|rdnd}| j                  ||d      }|||
|<   | j                  |d      }| j                  ||dk(  |      \  }}|s|dk(  rd|
d<   n|dk(  rd|
d<   n
|dk(  rd|
d<   |r| j                  |dd      }| j                  |d      }|%| j                  | j                  ||            |
d<   nq|rK|It        j                  | j                  |      | j                  |            }| j                  |      |
d<   n$| j                  | j                  ||            |
d<   |s$| j                  | j!                  ||            |
d<   |Z|r*| j                  |
d      t#        | j                  dz         | j!                  ||      |
d<   |dk(  rd|
d<   n|dk(  rd|
d<   n||||n|}|dk(  rd|
d<   n
|dk(  rd|
d<   | j                  | j!                  ||            |
d<   n|re|
d   |
d    |d!k(  rd"nd#| j                  | j!                  ||            | j                  | j                  ||            d$}| j%                  ||      S |d%k(  rd%|
d<   | j                  |d&      }| j                  |d'd(      }| j                  |d)d*      }|du}|du}|xs |} | j'                  |d+      }!| j'                  |d,      }"|!du}#|"du}$|dk(  s|dk(  s
|d-k(  s|d.k(  r&| s$| j                  | j!                  ||            |
d<   | j)                  |d/d0      }%|rA| j                  | j!                  ||            |
d<   |s|dk(  rd|
d<   n|dk(  s|dk(  rd|
d<   n|s|rd1}%|rA| j                  | j!                  ||            |
d<   |s|d2k(  rd2|
d<   n|dk(  s|d-k(  rd-|
d<   n|r| j                  | j!                  ||            |
d<   |s|d3k(  rd3|
d<   nZ|dk(  s|d.k(  rPd.|
d<   nJ| rH||
d<   |r| j                  |      |
d<   n,|r*t        j*                  |d4      }&| j                  |&      |
d(<   |#s|$r| j                  |      }'|#r| j                  |!dd|!      }(| j                  |!d5d6      })| j                  |!dd2      }*| j                  | j!                  ||(            |)|*d7}+| j                  |!d      },|,$| j                  | j!                  ||,            |+d<   | j                  |!d|'      }-| j                  | j                  ||-            |+d<   | j-                  |+      |
d+<   |$r| j                  |"dd|"      }.| j                  |"d5d6      }/| j                  |"dd3      }0| j                  | j!                  ||.            |/|0d7}1| j                  |"d      },|,$| j                  | j!                  ||,            |1d<   | j                  |"d|'      }2| j                  | j                  ||2            |1d<   | j-                  |1      |
d,<   d}3| j)                  |d8d0      }4|4r(| j                  |d/      }|%r
|d!k(  rd#nd"}3n|d!k(  rd"nd#}3nd9}3|3|
d:<   |}5|d;   s!| j                  | j                  ||            }5|5|
d<   | j                  |g d<      }| j%                  |
|      S )=aL  
 @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 fulfilled, 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
        NrP   r4   )r  ru  r  MARKETrA   TWAPz6 createOrder() twap order supports swap contracts onlyr0  r1  	stopPricer.  newClientOrderIdclientOrderIDclientOrderIdr3  PostOnlyr)  GTCr  r  quantityr(  zl createOrder() requires the cost parameter(or the amount + price) for placing spot market-buy trigger ordersLIMITTRIGGER_LIMITru  TRIGGER_MARKETTAKE_STOP_LIMITTAKE_STOP_MARKETr  r  r  LONGSHORT)r  r  r  r.  totalAmountr*  trailingAmounttrailingPercent	priceRatetrailingTypeTRAILING_STOP_MARKETstopLoss
takeProfitSTOPTAKE_PROFIT
reduceOnlyFTSTOP_MARKETTAKE_PROFIT_MARKET100workingType
MARK_PRICE)r  r  ru  r4  BOTHr  rJ  )
r4  r.  r0  r1  r  r  r  r  r
  r  )r  r  upperr'   r4   r|  r$  safe_string_upperhandle_post_onlyr  parse_to_numericcost_to_precisionr/   r'  number_to_stringamount_to_precisionprice_to_precisionr%   r  r  rw  
string_divjson)6rR  r  ru  r  r  r(  r\  r  postOnlyr  r  isMarketOrderr  isTwapOrderr0  r1  r.  isTriggerOrderisStopLossPriceOrderisTakeProfitPriceOrderexchangeClientOrderIdr  r3  r  calculatedCoststopTakePricetwapRequestr  r  r  isTrailingAmountOrderisTrailingPercentOrder
isTrailingr
  r  
isStopLossisTakeProfitr  requestTrailingPercentstringifiedAmountslTriggerPriceslWorkingTypeslType	slRequestslPrice
slQuantitytkTriggerPricetkWorkingTypetpType	tpRequest
tkQuantityr  r4  	amountReqs6                                                         rT  create_order_requestzbingx.create_order_request
  s    V$
!??vW]^
Fzz|TlJJL

 (v%fn6DGG&^^__((A**63DE))&+~N%T1,D8!0!<6< 2/**63H/Z$-:G)*,,V]C00z@Y[ab&z1%/GM"E!%*GM"E!%*GM"%%ffoFDYYvv.F+/+@+@AWAWX^`dAe+f( e&7%,%7%78M8Mf8UW[WlWlmrWs%tN/3/D/D^/TGO,*.*?*?@X@XY_ag@h*iGJ' #'#8#89P9PQWY^9_#` ' T%5%5g%O%W+DGG  7e  -e  f  f'+'>'>v|'T$7?&5GFOX%&6GFO+1L2?2KRa7?&7GFOX%&8GFO'+'<'<T=T=TU[]j=k'l$%h/#FO/3u}F7$($9$9$:Q:QRXZf:g$h#'#8#89Q9QRXZ`9a#b%$ {{;77e#).&!--f6FGN"009JKXO++FNDZ[L$2$$>!%4D%@".H2HJvz:H>J!-J%T1Ldo&=46>W[_lWl  xB#'#8#89P9PQWY^9_#` eDJ'+'<'<T=T=TU[]i=j'k$ T-=%=&6GFOgo4?+B&5GFO%)?!
'+/+@+@AXAXY_anAo+pGK($)>*7'/tv~*0++/+@+@AXAXY_apAq+rGK($1E)E*>'/t}/D*7".('+'<'<^'LGG$+-4-?-?QV-W*+/+@+@AW+XGK(\$($9$9&$A!%)%7%7.R]_g%hN$($4$4X}l$[M!--hNF%)%:%:4;R;RSY[i;j%k'4 &'I
 #..xAG*-1-B-B4CZCZ[acjCk-l	'*!%!1!1(JHY!ZJ,0,A,A$BZBZ[acmBn,oIj)*.))I*>GJ'%)%7%7
NT_ak%lN$($4$4ZP\$]M!--j&BVWF%)%:%:4;R;RSY[i;j%k'4 &'I
 #..z7CG*-1-B-B4CZCZ[acjCk-l	'*!%!1!1*jJ[!\J,0,A,A$BZBZ[acmBn,oIj),0IIi,@GL)L^^FHe<F6<8/3u}76L.2em6'L%&2GN#I)$ 11$2J2J6SY2Z[	"+GJ6  $B  C{{7F++rU  c                    | j                          | j                  |      }| j                  |dd      }| j                  |d      }| j	                  ||||||      }	d}
|d   rT|r| j                  |	      }
nQ|d   r| j                  |	      }
n:|dk(  r| j                  |	      }
n#| j                  |	      }
n| j                  |	      }
t        |
t              r"| j                  |
      }
| j                  |
      }
| j                  |
di       }i }|d   r|d   r|
}n| j                  |d|      }n|}| j                  ||      S )	a
  
        create a trade order

        https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Trade%20order
        https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Create%20an%20Order
        https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Trade%20order
        https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Place%20TWAP%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 fulfilled, 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]: triggerPrice at which the attached take profit / stop loss order will be triggered
        :param float [params.stopLossPrice]: stop loss trigger price
        :param float [params.takeProfitPrice]: 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
        :param str [params.positionSide]: *contracts only* "BOTH" for one way mode, "LONG" for buy side of hedged mode, "SHORT" for sell side of hedged mode
        :param boolean [params.hedged]: *swap only* whether the order is in hedged mode or one way mode
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r   FNrC   rJ  twaprW  r  )r  r  rw  r  r<  swapV2PrivatePostTradeOrderTestcswapV1PrivatePostTradeOrderswapV1PrivatePostTwapOrderswapV2PrivatePostTradeOrderspotV1PrivatePostTradeOrderr  strfix_stringified_json_members
parse_jsonrZ  parse_order)rR  r  ru  r  r  r(  r\  r  r   r  r]  rW  r  s                rT  r  zbingx.create_order?  sK   D 	V$~~ffe466*++FD$vV&>??H	"<<WE::7C;;GD77@HB h$ 88BHx0H~~h3&>i !gt<F//rU  ordersc           	         | j                          g }g }t        dt        |            D ]  }||   }| j                  |d      }| j                  |d      }|j	                  |       | j                  |d      }	| j                  |d      }
| j                  |d      }| j                  |di       }| j                  |||	|
||      }|j	                  |        | j                  |dd	d
d
      }t        |      }| j                  |d         }i }d}|d   rC|dkD  rt        | j                  dz         | j                  |      |d<   | j                  |      }n?| j                  |dd	      }|rd
|d<   | j                  |      |d<   | j                  |      }t!        |t"              r"| j%                  |      }| j'                  |      }| j                  |di       }| j)                  |dg       }| j+                  ||      S )a  
        create a list of trade orders

        https://bingx-api.github.io/docs/#/spot/trade-api.html#Batch%20Placing%20Orders
        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
        :param boolean [params.sync]: *spot only* if True, multiple orders are ordered serially and all orders do not require the same symbol/side/type
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r   r  ru  r  r  r(  r\  NFTrC   r   zJ createOrders() can not create more than 5 orders at once for swap marketsbatchOrderssyncrW  rH  )r  rz  r{  r|  r  r  rZ  r<  rF  r  r)   r4   r  !swapV2PrivatePostTradeBatchOrdersrw  !spotV1PrivatePostTradeBatchOrdersr  rD  rE  rF  ry  parse_orders)rR  rH  r\  ordersRequests	marketIdsr  rawOrderr0  ru  r  r  r(  orderParamsorderRequestr  symbolsLengthr  r  r]  rK  rW  r  s                         rT  create_orderszbingx.create_orders  s    		q#f+& 
	0AayH''(;H##Hf5DX&##Hf5D%%h9F$$Xw7E..8R@K44XtT6SXZefL!!,/
	0 %%iudDIGWQZ(&>q "477-y#yzz%)YY~%>GM"==gFH>>&&%8D"&"ii7GFO==gFH\ h$ 88BHx0H~~h3h3  00rU  c                 :    ddddddd}| j                  |||      S )Nr  r  )BUYSELLr  r  r  r  r|  )rR  r  sidess      rT  r,  zbingx.parse_order_side$  s2    
 tT22rU  c                 :    ddddddd}| j                  |||      S )Nr  r=  )trigger_markettrigger_limit
stop_limitstop_markettake_profit_marketstoprY  )rR  ru  typess      rT  parse_order_typezbingx.parse_order_type/  s2    &$!#"*
 tT22rU  r  c                    |}| j                  |dd      }||}| j                  |dd      }|dnd}| j                  |dd      }|| j                  |d d |      }| j                  |d	d
      }| j	                  |g d      }	| j                  |dd      }
| j                  |g d      }| j                  |dd      }| j                  |g d      }||d   r|dk(  r|d   }n|d   }n|d   }| j                  |d      }d }|&|dk7  r!| j                  | j                  |d            }|at        |t        j                        sG|dk7  rBt        |t              r| j                  |      }| j                  | j                  |d            }| j                  |d      }d }|&|dk7  r!| j                  | j                  |d            }|at        |t        j                        sG|dk7  rBt        |t              r| j                  |      }| j                  | j                  |d            }| j                  |dd      }| j                  | j                  |dd            }|}|4|j!                  d      dkD  r||}d }|j!                  d      dkD  r||}d }| j#                  i d|d | j                  |g d!      d"| j                  |g d#      d| j%                  ||d$|      d%|	d&| j'                  |	      d'|
d(| j)                  |d      d| j+                  |      d)| j                  |d)      d*d d	| j-                  |      d+| j                  |d+d,      d-|d.|d/|d0| j                  |d1d2      | j                  |d3      | j                  |g d4      | j                  |d5d6      d | j/                  |      |t1        j2                  |      d7d | j5                  |d8d9      d:|      S );NnewOrderResponseorderOpenResponser  psrA   rC   r  r  r  r  )r  transactTimeEcreatedTimer  r  )r  XorderStatusfeeAssetr  )rn  r  r  r  r  r   r
  r  r  r  ru  r  	StopPricera  takerm  r4   )r  r  mainOrderIdr  )r  r  origClientOrderIdcr  r  r  lastTradeTimestampr  r3  r  r(  r  r.  r0  r1  r  r  apcummulativeQuoteQty)origQtyr  r  r  executedQtyz)r  r  r  ro)r  r  filled	remainingr  rn  r   r  )safe_dict_2r$  r  r&  r!  r  safe_string_upper_nr#  r  	omit_zeror|  r  numbersRealrD  rF  find
safe_orderr*  r)  r[  rc  r,  parse_order_statusr/   r-  safe_bool_2)rR  r  r  rm  newOrderr  r  r0  r  r  rt  statusIdfeeCurrencyCodefeeCostr
  r0  r  r1  rawTyper  r.  s                        rT  rG  zbingx.parse_order:  s   v ##E+=?RSE))%F , 4V6
%%eXs;>%%hdJGF''vs;''/[\	!00cJ++E3QR,,UJD$$U,FG#f~5=&,VnO&,WoO"(/??5*5 x2~ NN4+;+;Hj+QRM Jx,NV^bdVd(C(??84 NN4+;+;Hk+RSM__UL9
!zR'7"nnT-=-=j,-WXO"jW\\.RZdhjZj*c*!__Z8
"nnT-=-=j+-VWO**5&#>NN4#5#5e[+#VW	  V$r)0E )#V$r)0G"+#  
D 
$$$U,KL 
 T//7st 
 d&&xjI	 

  
 Y/ 
 !"4 
 "4#4#4UL#I 
 D))'2 
 4++E=A 
  
 D))$/ 
 T''w< 
 L 
 ] 
  ! 
" t))%TB# 
$ $$U,AB((0[\((sC--h7+**73 **5,E9 
: ; 	rU  r  c           	      >    ddddddddd}| j                  |||      S )Nr  closedcanceled)NEWPENDINGPARTIALLY_FILLEDRUNNINGFILLEDCANCELED	CANCELLEDFAILEDrY  rR  r  statusess      rT  r  zbingx.parse_order_status  s8     &"# 	
 &&99rU  r4   c                 >   | j                          | j                  |dd      }| j                  |d      }d}d}|r'd|i}| j                  | j	                  ||            }n|t        | j                  dz         | j                  |      }d|d   i}| j                  |dd	      }	| j                  |dg      }|	|	|d	<   n||d
<   d}
d}| j                  d||      \  }
}| j                  d||      \  }}|
dk(  r"| j                  | j	                  ||            }nH|dk(  r"| j                  | j	                  ||            }n!| j                  | j	                  ||            }| j                  |di       }| j                  |d|      }| j                  ||      S )a  
        cancels an open order

        https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Cancel%20Order
        https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Cancel%20Order
        https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Cancel%20an%20Order
        https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Cancel%20TWAP%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>`
        r>  FNrq  z) cancelOrder() requires a symbol argumentr  r4   r  r  r  rI   rA   rJ  rW  r  )r  rw  r   swapV1PrivatePostTwapCancelOrderr  r%   r4   r  r$  r  rw  spotV1PrivatePostTradeCancel$cswapV1PrivateDeleteTradeCancelOrderswapV2PrivateDeleteTradeOrderrZ  rG  )rR  r4   r  r\  r!  r]  r  r(  r  r  ru  rz  rW  r  s                 rT  cancel_orderzbingx.cancel_order  s    	nnVVU;66*r!K <<T[[V\=]^H4 ~'2](]^^[[(F&,G !..vXMYYv'89F(+8(%'	"DG==mVU[\LD&"==mVU[\OGVv~<<T[[RX=YZi'#HHU\^dIefH#AA$++gW]B^_HF ~~h3tWd3v..rU  c                    |t        | j                  dz         | j                          | j                  |      }d|d   i}d}|d   r"| j	                  | j                  ||            }nf|d   rI|d   r"| j                  | j                  ||            }n:| j                  | j                  ||            }nt        | j                  dz         | j                  |d	i       }| j                  |d
dg       }| j                  |      S )a|  
        cancel all open orders

        https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Cancel%20orders%20by%20symbol
        https://bingx-api.github.io/docs/#/swapV2/trade-api.html#Cancel%20All%20Orders
        https://bingx-api.github.io/docs/#/en-us/cswap/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 argumentr  r4   rA   rC   rJ  z= cancelAllOrders is only supported for spot and swap markets.rW  successrH  )r%   r4   r  r  &spotV1PrivatePostTradeCancelOpenOrdersr  &cswapV1PrivateDeleteTradeAllOpenOrders%swapV2PrivateDeleteTradeAllOpenOrdersr&   rZ  safe_list_2rN  )rR  r  r\  r  r  r]  rW  rH  s           rT  cancel_all_orderszbingx.cancel_all_ordersc  s    >#DGG.]$]^^V$fTl
 &>BB4;;wX^C_`H. F^i FFt{{SZ\bGcdr  EEdkkRY[aFbc> TWW'ffgg~~h3!!$	8R@  ((rU  idsc                    |t        | j                  dz         | j                          | j                  |      }d|d   i}| j	                  |d      }| j                  |d      }|}|du}|r|}g }	t        dt        |            D ]#  }
||
   }t        |      }|	j                  |       % d}|d   r<|rdnd	}d
j                  |	      ||<   | j                  | j                  ||            }n=|r| j                  |	      |d<   n|	|d<   | j                  | j                  ||            }| j                  |di       }| j!                  |ddg       }| j#                  |      S )aI  
        cancel multiple orders

        https://bingx-api.github.io/docs/#/swapV2/trade-api.html#Cancel%20a%20Batch%20of%20Orders
        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 argumentr  r4   clientOrderIdsr   rA   clientOrderIDsorderIds,clientOrderIDListorderIdListrW  r  rH  )r%   r4   r  r  r  r  rz  r{  rD  r  join"spotV1PrivatePostTradeCancelOrdersr  r  #swapV2PrivateDeleteTradeBatchOrdersrZ  r  rN  )rR  r  r  r\  r  r  r  
idsToParseareClientOrderIds	parsedIdsr  r4   stringIdr]  
spotReqKeyrW  r  s                    rT  cancel_orderszbingx.cancel_orders  s    >#DGG.Z$Z[[V$fTl
 1AB6#34
+47'J	q#j/* 	'AAB2wHX&	' &>->)JJ"%((9"5GJ>>t{{7TZ?[\H8 !/3yy/C+,)2&??GU[@\]H< ~~h3""4HbA  ))rU  timeoutc                 z   | j                          |dkD  }|rdnd|r| j                  |dz        ndd}d}d}| j                  dd|      \  }}|dk(  r#| j                  | j	                  ||            }|S |d	k(  r#| j                  | j	                  ||            }|S t        | j                  d
z   |z   dz         )a.  
        dead man's switch, cancel all orders after the given timeout

        https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Cancel%20all%20orders%20in%20countdown
        https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Cancel%20all%20orders%20in%20countdown

        :param number timeout: time in milliseconds, 0 represents cancel the timer
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.type]: spot or swap market
        :returns dict: the api result
        r   ACTIVATECLOSErB  )ru  timeOutNrH   rA   rC   z- cancelAllOrdersAfter() is not supported for  markets)r  parse_to_intr  $spotV1PrivatePostTradeCancelAllAfterr  $swapV2PrivatePostTradeCancelAllAfterr+   r4   )rR  r  r\  r  r  r]  ru  s          rT  cancel_all_orders_afterzbingx.cancel_all_orders_afterS  s     	aK#+J'?G))'D.9a
 99:PRVX^_f6>@@WV\A]^H   V^@@WV\A]^H  tww)XX[__bllmmrU  c                    | j                          | j                  |dd      }| j                  |d      }d}d}|r&d|i}| j                  | j	                  ||            }n|t        | j                  dz         | j                  |      }|d   |d}d}	d}
| j                  d||      \  }	}| j                  d||      \  }
}|	d	k(  r"| j                  | j	                  ||            }nH|
d
k(  r"| j                  | j	                  ||            }n!| j                  | j	                  ||            }| j                  |di       }| j                  |d|      }| j                  ||      S )a  
        fetches information on an order made by the user

        https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Query%20Order%20details
        https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Query%20Order%20details
        https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Query%20Order
        https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#TWAP%20Order%20Details

        :param str id: the order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.twap]: if fetching twap order
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r>  FNrq  z( fetchOrder() requires a symbol argumentr4   )r  r  rv   rA   rJ  rW  r  )r  rw  r  swapV1PrivateGetTwapOrderDetailr  r%   r4   r  r  rw  spotV1PrivateGetTradeQuery!cswapV1PrivateGetTradeOrderDetailswapV2PrivateGetTradeOrderrZ  rG  )rR  r4   r  r\  r!  r]  r  r(  r  ru  rz  rW  r  s                rT  fetch_orderzbingx.fetch_order{  s    	nnVVU;66*r!K ;;DKKU[<\]H6 ~'2\(\]][[(F ,G DG==lFTZ[LD&"==lFTZ[OGVv~::4;;wPV;WX0 i'#EEdkkRY[aFbcHj  $>>t{{7TZ?[\H6 ~~h3tWd3v..rU  c                    | j                          i }d}|| j                  |      }|d   |d<   d}| j                  d||      \  }}|dk7  rt        | j                  dz         |||d<   |||d<   | j                  d	||      \  }}| j                  | j                  ||            }| j                  |d
i       }	| j                  |	dg       }
| j                  |
|||      S )a{  
        fetches information on multiple orders made by the user

        https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#All%20Orders
        https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Query%20Order%20history(returns less fields than above)

        :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>`
        Nr4   r  rx   rC   z1 fetchOrders() is only supported for swap marketsr=  r  r  rW  rH  )r  r  r  r+   r4   r  swapV1PrivateGetTradeFullOrderr  rZ  ry  rN  )rR  r  r  r=  r\  r  r  ru  r]  rW  rH  s              rT  fetch_orderszbingx.fetch_orders'  s    	[[(F &tGH99-QWXf6>tww)\\]]$GG#(GK 229gvN66t{{7F7STj ~~h3h3  >>rU  c                    | j                          d}i }|| j                  |      }|d   |d<   d}d}d}	| j                  d||      \  }}| j                  d||      \  }}|dk(  r"| j	                  | j                  ||            }	n| j                  |dd      }
| j                  |d      }|
r"| j                  | j                  ||            }	nH|dk(  r"| j                  | j                  ||            }	n!| j                  | j                  ||            }	| j                  |	d	i       }| j                  |d
dg       }| j                  ||||      S )a  
        fetch all unfilled currently open orders

        https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Current%20Open%20Orders
        https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Current%20All%20Open%20Orders
        https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Query%20all%20current%20pending%20orders
        https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Query%20TWAP%20Entrusted%20Order

        :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
        :param boolean [params.twap]: if fetching twap open orders
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr4   r  ru   rA   r>  FrJ  rW  rH  r   )r  r  r  rw  spotV1PrivateGetTradeOpenOrdersr  rw  r  swapV1PrivateGetTwapOpenOrders cswapV1PrivateGetTradeOpenOrdersswapV2PrivateGetTradeOpenOrdersrZ  r  rN  )rR  r  r  r=  r\  r  r  ru  rz  r]  r!  rW  rH  s                rT  fetch_open_orderszbingx.fetch_open_orders~  se     	[[(F &tGH99:KVU[\f99:KVU[\6>;;DKKQW<XYH..?KYYvv.F>>t{{7TZ?[\I%@@WV\A]^??GU[@\]X ~~h3!!$&"=  >>rU  c                 p    | j                          | j                  ||||      }| j                  |dd      S )a  
        fetches information on multiple closed orders made by the user

        https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Query%20Order%20history
        https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Query%20Order%20history
        https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#User's%20History%20Orders
        https://bingx-api.github.io/docs/#/standard/contract-interface.html#Historical%20order

        :param str symbol: unified market symbol of the closed orders
        :param int [since]: timestamp in ms of the earliest order
        :param int [limit]: the max number of closed orders to return
        :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 Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        r  r  r   fetch_canceled_and_closed_orders	filter_byrR  r  r  r=  r\  rH  s         rT  fetch_closed_orderszbingx.fetch_closed_orders3  s9    " 	66vueVT~~fh99rU  c                 p    | j                          | j                  ||||      }| j                  |dd      S )a  
        fetches information on multiple canceled orders made by the user

        https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Query%20Order%20history
        https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Query%20Order%20history
        https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#User's%20History%20Orders
        https://bingx-api.github.io/docs/#/standard/contract-interface.html#Historical%20order

        :param str symbol: unified market symbol of the canceled orders
        :param int [since]: timestamp in ms of the earliest order
        :param int [limit]: the max number of canceled orders to return
        :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>`
        r  r  r  r  s         rT  fetch_canceled_orderszbingx.fetch_canceled_ordersH  s9    " 	66vueVT~~fh
;;rU  c                    | j                          d}i }|| j                  |      }|d   |d<   d}d}d}	d}
| j                  d||      \  }}| j                  d||      \  }}| j	                  |ddd      \  }	}|	r#| j                  | j                  ||            }
n|dk(  r)|||d<   | j                  | j                  ||            }
n| j                  |d	d      }| j                  |d	      }|rqd
|d<   |dn||d<   |d
n||d<   | j                  |d| j                               }| j                  |d      }||d<   | j                  | j                  ||            }
nH|dk(  r"| j                  | j                  ||            }
n!| j                  | j                  ||            }
| j                  |
di       }| j!                  |ddg       }| j#                  ||||      S )a  
        fetches information on multiple closed orders made by the user

        https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Query%20Order%20history
        https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Query%20Order%20history
        https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#User's%20History%20Orders
        https://bingx-api.github.io/docs/#/standard/contract-interface.html#Historical%20order
        https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Query%20TWAP%20Historical%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 orders for
        :param boolean [params.standard]: whether to fetch standard contract orders
        :param boolean [params.twap]: if fetching twap orders
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr4   r  r]   r  FrA   r  r>  r   	pageIndexr:   r  r  r  rJ  rW  rH  r   )r  r  r  rw  r  contractV1PrivateGetAllOrdersr  "spotV1PrivateGetTradeHistoryOrdersrw  r  r[  milliseconds!swapV1PrivateGetTwapHistoryOrders"cswapV1PrivateGetTradeOrderHistoryswapV2PrivateGetTradeAllOrdersrZ  r  rN  )rR  r  r  r=  r\  r  r  ru  rz  r  r]  r!  r  rW  rH  s                  rT  r  z&bingx.fetch_canceled_and_closed_orders]  s   & 	[[(F &tGH99:MvW]^f99:MvW]^88ATV`bgh&99$++gv:VWHV^ &+
#>>t{{7TZ?[\H4 ..?KYYvv.F'($.3mc%
#-2]q$))&'4;L;L;NO673%*	"AA$++gW]B^_< I%BB4;;wX^C_`n  >>t{{7TZ?[\: ~~h3!!$&"=  >>rU  rt  fromAccount	toAccountc           
         | j                          | j                  |      }| j                  | j                  di       }| j	                  |||      }| j	                  |||      }	|d   | j                  ||      |dz   |	z   d}
| j                  | j                  |
|            }|| j	                  |d      dd||||dd	S )a2  
        transfer currency internally between wallets on the same account

        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>`
        r  r4   _)r  r  ru  tranIdN	rm  r4   r  r  r  r  r  r  r  )r  r  rZ  rL  r|  currency_to_precision spotV3PrivateGetGetAssetTransferr  )rR  rt  r  r  r  r\  r  r  fromIdtoIdr  r]  s               rT  r   zbingx.transfer  s     	==&6FK!!.+{K	9Ed^00v>SL4'

 88Wf9UV ""8X6&"

 
	
rU  c                    | j                          d}|| j                  |      }| j                  | j                  di       }| j	                  |d      }| j	                  |d      }| j	                  |||      }	| j	                  |||      }
|	|
t        | j                  dz         d|	dz   |
z   i}|||d<   |||d	<   | j                  | j                  ||            }| j                  |d
g       }| j                  ||||      S )as  
        fetch a history of internal transfers made on an account

        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 requiredru  r  r  sizerows)r  r  rZ  rL  r|  r!   r4   spotV3PrivateGetAssetTransferr  ry  parse_transfers)rR  rt  r  r=  r\  r  r  r  r  r  r  r  r]  r  s                 rT  fetch_transferszbingx.fetch_transfersE  s&    	}}T*H6FK&&v}=$$V[9	!!.+{K	9E>T\*[ [\\FSL4'
 #(GK #GFO55dkk'66RS  ~~h3##D(E5AArU  r   r  c           
         | j                  |d      }| j                  |d      }| j                  d |      }| j                  |d      }| j                  | j                  di       }| j                  |d      }|j                  d      }	| j                  |	d      }
| j                  |d      }| j                  ||
|
      }| j                  |||      }|||| j                  |      || j                  |d	      |||d
	S )Nr  r  r  r  ru  r  r   r   r  r  )r|  r[  r}  rZ  rL  r  r)  r  )rR  r   r  r  r  r/  r  r  typeIdtypeIdSplitr  r  r  r  s                 rT  parse_transferzbingx.parse_transferv  s   !!(H5%%h<	..tX>!!(H5~~dllNBG!!(F3ll3'!!+q1*&&|VVD$$\4>	"Y/$&&x:&"

 
	
rU  c                    | j                          | j                  |      }| j                  | j                  d      }| j                  | j                  d|      }|d   dd|d}| j                  | j                  ||            }| j                  | j                  |d      d      }| j                  ||d   gd      }	| j                  |	d	      S )
a  
        fetch the deposit addresses for a currency associated with self account

        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
        r   r4   r   rB  )ra  offsetr=  r   rW  rt  Frc  )r  r  r[  rL  parse_params(walletsV1PrivateGetCapitalDepositAddressr  ry  rZ  parse_deposit_addressesindex_by)
rR  rt  r\  r  defaultRecvWindowr   r  r]  rW  parseds
             rT  "fetch_deposit_addresses_by_networkz(bingx.fetch_deposit_addresses_by_network  s     	==& --dllLI&&t'8'8,HYZ
TN$	
 @@WV\A]^& ~~dnnXv>G--dXf5E4FN}}VY//rU  c                    | j                  |d      }| j                  |dg      }| j                  ||      }|| j                  ||      S | j                  | j                  d      }| j                  ||      }|| j                  ||      S t        |j                               }| j                  |d      }| j                  ||      S )aC  
        fetch the deposit address for a currency associated with self account

        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>`
        rc  r"  r   )r|  r  r  rZ  rL  r   keys)	rR  rt  r\  rc  addressStructuresrL  defaultNetworkForCurrencyr  keys	            rT  fetch_deposit_addresszbingx.fetch_deposit_address  s     ""6956I;/ CCD&Q>>"3W==nnT\\3DEG(,(8(8$(G%(4~~&79RSS-2245&&tQ/~~&7==rU  c                    | j                  |d      }| j                  |d      }| j                  ||      }|d   }| j                  |d      }| j                  |d      }| j                  ||      }| j                  |       |||||dS )Ntagra  rt  addressWithPrefixrc  )rm  r  rc  addressr  )r|  safe_currencyr~  check_address)	rR  depositAddressr  r  r  rt  r  
networkdIdr  s	            rT  parse_deposit_addresszbingx.parse_deposit_address  s     ~u5%%nf=
%%j(;"">3FG%%ni@
--j$?7#""
 	
rU  c                     | j                          i }d}|| j                  |      }|d   |d<   |||d<   |||d<   | j                  | j                  ||            }| j	                  ||||      S )a4  
        fetch all deposits made to an account

        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>`
        Nr4   ra  r  r=  )r  r  $spotV3PrivateGetCapitalDepositHisrecr  parse_transactionsrR  rt  r  r=  r\  r  r  r]  s           rT  fetch_depositszbingx.fetch_deposits  s     	
}}T*H&tnGFO#(GK $GG<<T[[RX=YZ$ &&x5%HHrU  c                     | j                          i }d}|| j                  |      }|d   |d<   |||d<   |||d<   | j                  | j                  ||            }| j	                  ||||      S )aC  
        fetch all withdrawals made from an account

        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>`
        Nr4   ra  r  r=  )r  r  &spotV3PrivateGetCapitalWithdrawHistoryr  r  r  s           rT  fetch_withdrawalszbingx.fetch_withdrawals  s     	
}}T*H&tnGFO#(GK $GG>>t{{7TZ?[\( &&x5%HHrU  transactionc                    | j                  |d      }|d n| j                  |d      }| j                  |d|      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |      }	|#| j                  |d      }	| j	                  |	      }| j                  |d      }
| j                  |d      }| j                  ||      }|-||
k7  r(|j                  |
      d	k\  r|
|j                  |
d
      }| j                  |d      }|dk(  rdnd}i d|d|d| j                  |d      d|d|d| j                  |
      d| j                  |d      d| j                  | j                  |d            d|d|	d|dd d|d|d|dd dd | j                  |d      || j                  |d      d dd d S )!NrW  r4   r  
addressTag
insertTime	applyTimerc  ra  r   r  transferType0rp  
withdrawalrm  txidtxIdru  r  r  r  r  r  addressFrom	addressTor  tagFromtagToupdatedtransactionFee)r  r  rate)commentrn  internal)r  r|  r[  r)  r"  r}  r  r  r~  r  parse_transaction_status)rR  r  r  rW  dataIdr4   r  r  r  r  rc  r  rt  r  ru  s                  rT  parse_transactionzbingx.parse_transactionE  sz   ` {F3,T-=-=dD-Ik48"";	:{L9%%k<@	<<	*''[AHx0I"";	:%%k6:
&&z8<47?		'8Ja8O"||GR0"";?$^y,
K
"
 D$$[&9
 D	

 
 t..w7
 d&&{H=
 d33D4D4D[RZ4[\
 
 
 w
 4
 
 3
 s
  T!
" t#
$ ''V< ((6FG
 1
 	
rU  c                 J    ddddddddddddddd}| j                  |||      S )Npendingokrejected)r  r  1020304050607023456rY  r  s      rT  r&  zbingx.parse_transaction_status  sJ    
  &&99rU  r-  c                    |t        | j                  dz         | j                          | j                  |      }|d   dk7  rt	        | j                  dz         |j                         }|dk(  rd}|dk7  r|dk7  rt        | j                  d	z         |d
   |d}d}| j                  d||      \  }}|dk(  r!| j                  | j                  ||            S | j                  | j                  ||            S )a  
        set margin mode to 'cross' or 'isolated'

        https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Change%20Margin%20Type
        https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Set%20Margin%20Type

        :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 argumentru  rC   z- setMarginMode() supports swap contracts onlyCROSSCROSSEDISOLATEDz@ setMarginMode() marginMode argument should be isolated or crossr4   )r  
marginTyper   rJ  )r%   r4   r  r  r'   r  r&   rw  !cswapV1PrivatePostTradeMarginTyper   swapV2PrivatePostTradeMarginType)rR  r-  r  r\  r  r  rz  s          rT  set_margin_modezbingx.set_margin_mode  s	    >#DGG.[$[\\V$&>V#DGG&UUVV%%'
 "J#
i(?TWW'iijjTl$
 99/6SYZi99$++gv:VWW88Wf9UVVrU  c                 P    ddi}| j                  ||| j                  ||            S )Nru  r   
set_marginr  rR  r  r  r\  r  s        rT  
add_marginzbingx.add_margin  .    A
 vvt{{7F/KLLrU  c                 P    ddi}| j                  ||| j                  ||            S )Nru  r   rB  rD  s        rT  reduce_marginzbingx.reduce_margin  rF  rU  c                    | j                  |d      }|t        | j                  dz         | j                  |ddg      st        | j                  dz         | j	                          | j                  |      }|d   | j                  |d   |      |d}| j                  | j                  ||            }| j                  ||      S )a  
        Either adds or reduces margin in an isolated position in order to set the margin to a specific value

        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>`
        ru  zV setMargin() requires a type parameter either 1(increase margin) or 2(decrease margin)r   r   r4   r  )r  r  ru  )
r[  r%   r4   in_arrayr  r  r  $swapV2PrivatePostTradePositionMarginr  parse_margin_modification)rR  r  r  r\  ru  r  r  r]  s           rT  rC  zbingx.set_margin  s       0<#DGG  /G  %G  H  H}}TAq6*#DGG  /G  %G  H  HV$Tl..vh/?H

 <<T[[RX=YZ --h??rU  rW  c                     | j                  |d      }|| j                  |d      |dk(  rdndd| j                  |d      | j                  |d      | j                  |d	      d d d d

S )Nru  r  r  addreducer  r  rB   r  )
rm  r  ru  r-  r  r  rt  r  r  r  )r|  r  )rR  rW  r  ru  s       rT  rL  zbingx.parse_margin_modification  sz     f-&&vx8"ckE$&&tX6%%dH5$$VX6
 	
rU  c                 0   | j                          | j                  |      }d|d   i}d}|d   r"| j                  | j                  ||            }n!| j	                  | j                  ||            }| j                  |di       }| j                  ||      S )a  
        fetch the set leverage for a market

        https://bingx-api.github.io/docs/#/swapV2/trade-api.html#Query%20Leverage
        https://bingx-api.github.io/docs/#/en-us/cswap/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>`
        r  r4   NrJ  rW  )r  r  cswapV1PrivateGetTradeLeverager  swapV2PrivateGetTradeLeveragerZ  parse_leveragerC  s          rT  fetch_leveragezbingx.fetch_leverage  s     	V$fTl
 )::4;;wPV;WXH$ 99$++gv:VWH& ~~h3""400rU  r6  c                     | j                  |d      }|| j                  ||      d | j                  |d      | j                  |d      dS )Nr  longLeverageshortLeverage)rm  r  r-  rV  rW  )r|  r*  r[  )rR  r6  r  r0  s       rT  rS  zbingx.parse_leverageV  sV    : ##Hh7&&x8 --hG!..xI
 	
rU  c                 h   |t        | j                  dz         | j                  |d      }| j                  d|dg d       | j	                          | j                  |      }|d   ||d}|d   r!| j                  | j                  ||            S | j                  | j                  ||            S )a"  
        set the level of leverage for a market

        https://bingx-api.github.io/docs/#/swapV2/trade-api.html#Switch%20Leverage
        https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Modify%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
        z) setLeverage() requires a symbol argumentr  r   )r  r  r  r4   )r  r  r6  rJ  )	r%   r4   r  check_required_argumentr  r  cswapV1PrivatePostTradeLeverager  swapV2PrivatePostTradeLeverage)rR  r6  r  r\  r  r  r  s          rT  set_leveragezbingx.set_leverage|  s     >#DGG.Y$YZZ%%ff5$$]D&B[\V$Tl 

 )77GV8TUU$ 66t{{7F7STTrU  c                     |t        | j                  dz         | j                          | j                  |      }i }d}d}d}	| j	                  d||      \  }	}|	dk(  rb| j                  |d      }
|
t        | j                  dz         | j                  | j                  ||            }| j                  |dg       }n:|d   |d	<   | j                         }||d
   rdnd}|||<   n|d   r|dz
  |d<   | j                  |d      }| j                  |d      }||d
   rdnd}|||<   n
|d   r||d<   |d
   rO|||d<   | j                  | j                  ||            }| j                  |di       }| j                  |dg       }nq| j                  |dd      }| j                  |d      }||d<   | j                  | j                  ||            }| j                  |di       }| j                  |dg       }| j!                  |||||      S )a  
        fetch all trades made by the user

        https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Query%20transaction%20details
        https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Query%20historical%20transaction%20orders
        https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Query%20historical%20transaction%20details
        https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Query%20Order%20Trade%20Detail

        :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)
        :param str params['orderId']: the order id required for inverse swap
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        Nz+ fetchMyTrades() requires a symbol argumentrr   rJ  r  zE fetchMyTrades() requires an orderId argument for inverse swap tradesrW  r4   r  rA   r  r  rC   l    H4 r  r  r  r=  fillstradingUnitCONTfill_orders)r%   r4   r  r  rw  r|  #cswapV1PrivateGetTradeAllFillOrdersr  ry  r  r[  r  spotV1PrivateGetTradeMyTradesrZ  r  "swapV2PrivateGetTradeAllFillOrdersr  )rR  r  r  r=  r\  r  r  r^  r]  rz  r  nowstartTimeReqr  
endTimeReqrW  r_  s                    rT  fetch_my_tradeszbingx.fetch_my_trades  sK   $ >#DGG.[$[\\V$99/6SYZi&&vy9G'2y(yzz??GU[@\]HNN8VR8E8 !'tGH##%C .4Vn{)(-%%(+C%C	"%%fg6EYYvw/F *0.Yg
&+
##& f~$',GG$==dkk'SY>Z[~~h;tWb94 #44V]FS6=9)4&BB4;;wX^C_`~~h;t]B?*   ufEErU  c                    | j                  |dg       }t        |      }|d d dd d di d}|dk7  rt        d|      D ]  }||   }| j                  |d      }| j	                  |d      }	| j                  |d      }
| j                  ||
      }d d d| j                  |d      d	dd
|d   |<   |	st| j                  |d      |d   d<   d	|d   d<    |S )Nrb  )rn  r  )rm  rd  rp  r#  r   rc  	isDefaultrt  rj  F)rp  rd  r#  rd  rn  r  )ry  r{  rz  r|  rw  r~  r  )rR  rn  r  rb  networkListLengthr  r  rc  	networkIdrj  r/  r  s               rT  parse_deposit_withdraw_feez bingx.parse_deposit_withdraw_fee>  s   : nnS-<,"
 " 
 !1/0 =%a. ,,Wi@	 NN7K@	#//&A"55iN'+4@(,(8(8-(P`e f3z";/ 040@0@-0XF:&u-7<F:&|4= rU  codesc                     | j                          | j                  |      }| j                  |d      }| j                  ||d      S )a  
        fetch deposit and withdraw fees

        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>`
        rW  ra  )r  rx  ry  parse_deposit_withdraw_fees)rR  rn  r\  r]  coinss        rT  fetch_deposit_withdraw_feesz!bingx.fetch_deposit_withdraw_feesy  sE     	>>vFx0//ufEErU  r  c                    | j                  ||      \  }}| j                  |       | j                          | j                  |      }| j	                  |dd      }|d   || j                  ||      |d}| j                  |d      }	|	| j                  |	      |d<   |||d<   | j                  |ddg      }| j                  | j                  ||            }
| j                  |
d      }| j                  |      S )aS  
        make a withdrawal

        https://bingx-api.github.io/docs/#/en-us/spot/wallet-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, 15 spot account
        :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        
walletTyper   r4   )ra  r  r  rt  rc  r  rW  )handle_withdraw_tag_and_paramsr  r  r  r[  r  r  network_code_to_idr  (walletsV1PrivatePostCapitalWithdrawApplyr  r  r(  )rR  rt  r  r  r  r\  r  rt  r  rc  r]  rW  s               rT  rd  zbingx.withdraw  s    99#vFV7#==&&&v|Q?
TN00v>$	
 ((;!%!8!8!AGI?$'GL!6L)#<=@@WV\A]^x0 %%d++rU  c                 J   | j                  |      }t        |j                               }t        dt	        |            D ]`  }||   }||   }t        |t              sd}t        dt	        |            D ]  }||   }	|dkD  r|dz  }|t        |	      z  }! |dz  }|||<   b |S )Nr   [r  ]keysortr   r  rz  r{  r  rD  )
rR  r\  sortedParamsr  r  r   valuearrStrr  arrayElements
             rT  r  zbingx.parse_params  s    ||F+L%%'(q#d)$ 	+Aq'C %E%&q#e*- 0A#(8L1u#c,//F	0
 #$*S!	+ rU  c                    | j                          ddi}| j                  d||      \  }}d}|| j                  |      }|d   |d<   |||d<   |||d<   d}| j                  d	||      \  }}d}d}	|d
k(  r5| j	                  | j                  ||            }| j                  |dg       }	nG| j                  | j                  ||            }| j                  |di       }
| j                  |
dg       }	| j                  |	|||      S )a  
        retrieves the users liquidated positions

        https://bingx-api.github.io/docs/#/swapV2/trade-api.html#User's%20Force%20Orders
        https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Query%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>`
        autoCloseTypeLIQUIDATIONr  Nr4   r  r  r=  rq   rJ  rW  rH  )
r  r  r  rw  !cswapV1PrivateGetTradeForceOrdersr  ry   swapV2PrivateGetTradeForceOrdersrZ  parse_liquidations)rR  r  r  r=  r\  r  r  rz  r]  liquidationsrW  s              rT  fetch_my_liquidationszbingx.fetch_my_liquidations  s8    	]
 229gvN[[(F &tGH#(GK $GG99:OQWY_`i==dkk'SY>Z[H8  >>(FB?L<<T[[RX=YZH< >>(FB7D>>$"=L&&|VUEJJrU  c                    | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }t        j                  ||      }t        j                  ||      }	| j	                  || j                  ||      | j                  |      | j                  |      | j                  |      | j                  |      | j                  |	      || j                  |      d	      S )Nr  r  rx  r  r  )	rm  r  r  r  r(  	baseValue
quoteValuer  r  )r|  r[  r/   r'  safe_liquidationr*  rQ  r)  )
rR  liquidationr  r0  r  contractsStringcontractSizeStringpriceStringbaseValueStringquoteValueStrings
             rT  parse_liquidationzbingx.parse_liquidation#  s   , ##K:%%k6:	**;F!--fnE&&{J?!,,_>PQ"--o{K$$&&x8**?; --.@A&&{3**?;++,<="Y/
&
 
 
	rU  c                    | j                          | j                  |      }| j                  |d      }i }d}|"| j                  | j	                  ||            }nP|d   |d<   |d   r"| j                  | j	                  ||            }n!| j                  | j	                  ||            }| j                  |d      }| j                  ||      S )av  
        closes open positions for a market

        https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#One-Click%20Close%20All%20Positions
        https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Close%20all%20positions%20in%20bulk

        :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]: the id of the position you would like to close
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r  Nr4   r  rJ  rW  )	r  r  r|  #swapV1PrivatePostTradeClosePositionr  (cswapV1PrivatePostTradeCloseAllPositions'swapV2PrivatePostTradeCloseAllPositionsrZ  rG  )	rR  r  r  r\  r  r  r  r]  rW  s	            rT  close_positionzbingx.close_positionL  s     	V$%%fl;
!??GU[@\]H$ !'tGHi HHU\^dIef  GGT[]cHde ~~h/f--rU  c                    | j                          | j                  | j                  d      }| j                  | j                  d|      }d}| j	                  dd|      \  }}d}| j                  dd|      \  }}|dk(  rt        | j                  dz   |z   dz         d|i}d}|dk(  r"| j                  | j                  ||            }n!| j                  | j                  ||            }| j                  |di       }| j                  |d	g       }	g }
t        d
t        |	            D ])  }| j                  d|	|   i      }|
j!                  |       + |
S )a  
        closes open positions for a market

        https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#One-Click%20Close%20All%20Positions
        https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Close%20all%20positions%20in%20bulk

        :param dict [params]: extra parameters specific to the bingx 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>`
        r   NrK   rB   z% closePositions() cannot be used for r  rJ  rW  r  r   r  )r  r[  rL  r  r  rw  r&   r4   r  r  r  rZ  ry  rz  r{  r  r  )rR  r\  r  r   r  rz  r  r]  rW  r  r  r  r  s                rT  close_all_positionszbingx.close_all_positions  sv    	 --dllLI&&t'8'8,HYZ

!??@SUY[ab
F99:MtU[\!TWW'NNQ[[^hhii*
 iDDT[[QXZ`EabH CCDKKPWY_D`aH ~~h3..y"5	q#g,' 	'A**L'!*+EFHX&	' rU  c                 ~    | j                  |      }| j                  |di       }| j                  |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

        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
        rW  dualSidePositionr  )rm  r4  ) swapV1PrivateGetPositionSideDualrZ  r|  )rR  r  r\  r]  rW  r  s         rT  fetch_position_modezbingx.fetch_position_mode  sQ     88@ ~~h3++D2DE'61
 	
rU  r4  c                 ^    d}|rd}nd}d|i}| j                  | j                  ||            S )a  
        set hedged to True or False for a market

        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  )rR  r4  r  r\  r  r  s         rT  set_position_modezbingx.set_position_mode  sD      %& 0
 55dkk'66RSSrU  c                 `   | j                          | j                  |      }| j                  ||||||      }	||	d<   d|	d<   d}
|d   r"| j                  | j	                  |	|            }
n!| j                  | j	                  |	|            }
| j                  |
d      }| j                  ||      S )a  
        cancels an order and places a new order

        https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Cancel%20order%20and%20place%20a%20new%20order  # spot
        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 fulfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.triggerPrice]: 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>`
        cancelOrderIdSTOP_ON_FAILUREcancelReplaceModeNrC   rW  )r  r  r<  #swapV1PrivatePostTradeCancelReplacer  (spotV1PrivatePostTradeOrderCancelReplacerZ  rG  )rR  r4   r  ru  r  r  r(  r\  r  r  r]  rW  s               rT  
edit_orderzbingx.edit_order  s    @ 	V$++FD$vV#% '8#$&>??GU[@\]Hp DDT[[QXZ`EabHL ~~h/f--rU  c                 `   | j                          | j                  |      }d|d   i}d}d}| j                  d||      \  }}|dk(  r"| j                  | j	                  ||            }n!| j                  | j	                  ||            }| j                  |di       }| j                  ||      S )a  
        fetches the margin mode of the trading pair

        https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Query%20Margin%20Type
        https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Query%20Margin%20Type

        :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>`
        r  r4   Nrl   rJ  rW  )r  r  rw   cswapV1PrivateGetTradeMarginTyper  swapV2PrivateGetTradeMarginTyperZ  parse_margin_mode)rR  r  r\  r  r  rz  r]  rW  s           rT  fetch_margin_modezbingx.fetch_margin_mode  s     	V$fTl
 99:KVU[\i<<T[[RX=YZH ;;DKKQW<XYH ~~h3%%dF33rU  c                     | j                  |d      }| j                  |d      }|dk(  rdn|}|| j                  ||dd      |dS )Nr  r=  crossedr  r  rC   )rm  r  r-  )r|  r+  r*  )rR  r-  r  r0  r=  s        rT  r  zbingx.parse_margin_mode  sX    ##J9++JE
!+y!8Wz
&&xfE$
 	
rU  c                 p   | j                          | j                  |      }d|d   i}d}i }| j                  |di       }|d   r$| j                  | j	                  ||            }|}n=|d   r| j                  |      }|}n$| j                  |      }| j                  |di       }| j                  ||      S )aP  
        fetch the trading fees for a market

        https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Query%20Trading%20Commission%20Rate
        https://bingx-api.github.io/docs/#/en-us/swapV2/account-api.html#Query%20Trading%20Commission%20Rate
        https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Query%20Trade%20Commission%20Rate

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `fee structure <https://docs.ccxt.com/#/?id=fee-structure>`
        r  r4   NrW  rA   rJ  r  )r  r  rZ  "spotV1PrivateGetUserCommissionRater  #cswapV1PrivateGetUserCommissionRate"swapV2PrivateGetUserCommissionRateparse_trading_fee)rR  r  r\  r  r  r]  r  rW  s           rT  fetch_trading_feezbingx.fetch_trading_fee  s     	V$fTl
 
~~h3&>>>t{{7TZ?[\H Ji CCFK "
BB6J "^^D,C
%%j&99rU  rn  c                 f    ||d   nd }||| j                  |d      | j                  |d      dddS )Nr  makerCommissionRatetakerCommissionRateF)rm  r  r   r   r  r   )r  )rR  rn  r  r  s       rT  r  zbingx.parse_trading_fee  sM     '-&8!t%%c+@A%%c+@A
 	
rU  c                    | j                  |      }t        |j                               }d }d }t        dt	        |            D ]  }||   }||   }t        |t              rd }	t        dt	        |            D ]g  }
||
   }t        |t              }|r,|
dkD  r|	dt        |      z   dz   z  }	4dt        |      z   dz   }	F|
dkD  r|	dt        |      z   z  }	]t        |      }	i d|	z   dz   }|}|dk(  r	|dz   |z   }|d|z   dz   |z   z  } |S )	Nr   z,""r  ry  rz  =&r{  )rR  r\  r}  r  adjustedValuer  r  r   r~  r  r  r  isStrings                rT  custom_encodezbingx.custom_encode  s<   ||F+L%%'(q#d)$ 	2Aq'C %E%&q#e*- 7A#(8L *< =Hq5"i#l2C&Cc&IIF%(3|+<%<s%BFq5"cC,=&==F%(%6F7 !$fs 2%AvsU*#)c/E11/	20 rU  r   GETc                    |d   }|d   }|d   }	| j                  | j                  dd      }
|
r#|dk7  rt        | j                  dz   |z   dz         | j	                  | j
                  d	   |         }| j                  ||      }|d
k(  rd}|d   }|d   }	|dk7  r|dk(  r|dk(  r|dz  }n|d|z   z  }|d|z   dz   |z   z  }| j                  || j                  |            }| j                         |d<   | j                  |      }|	dk(  r|r/|d| j                  |      z   z  }n|	dk(  r| j                          |dk(  xs |dk(  xr |dk(  }d }d }|r| j                  |      }n"| j                  |      }| j                  |      }| j!                  | j#                  |      | j#                  | j$                        t&        j(                        }| j*                  | j-                  | j                  dd      d}|rd|d<   ||d<   | j/                  |      }n"| j                  |      }|d|z   dz   dz   |z   z  }||||d S )!Nr   r   r   r`  FrC   z) does not have a testnet/sandbox URL for z
 endpointsr   r   zaccount/transferr  r   rA   r   z/apir  r  r   ?r   r   POSTr!  r  )zX-BX-APIKEYzX-SOURCE-KEYzapplication/jsonzContent-Type	signaturer  z
signature=)urlmethodbodyheaders)rw  rL  r+   r4   implode_hostnamer   implode_paramsr  extract_paramsr8  r|  	urlencoderv  r  r  	rawencodehmacencoder   hashlibsha256r   r|  r  )rR  pathsectionr  r\  r  r  ru  r;   accessr  r  isJsonContentTypeparsedParamsencodeRequestr  querys                    rT  signz
bingx.sign7  sr   qz!*NN4<<F	$&.tww)TTW[[^jjkk##DIIe$4T$:;""40j %DajGQZF++v~'T/vsTz!sW}s"T))64#6#6t#<="jjl{f%XsT^^F333y ++-#'<#7"XTEW=W!p_eio_oL M  $ 2 26 :#008 $| <		$++m"<dkk$++>VX_XfXfgI#{{ $ 0 0x PG !*<'&/{#yy(|4sU{S(<7)CCfdwOOrU  c                 "    | j                         S N)r  )rR  s    rT  r8  zbingx.nonceh  s      ""rU  enablec                 J    t         t        |   |       || j                  d<   y )Nr`  )rO  r1   set_sandbox_moderL  )rR  r  rS  s     rT  r  zbingx.set_sandbox_modek  s     eT+F3&,]#rU  httpCodereasonr  r  r  r  c
                 Z   |y | j                  |d      }
| j                  |d      }|
|
dk7  r}| j                  dz   |z   }| j                  | j                  d   ||       | j                  | j                  d   |
|       | j	                  | j                  d   ||       t        |      y )Nrt  msgr   r  r  )r|  r4   throw_exactly_matched_exceptionr   throw_broadly_matched_exceptionr!   )rR  r  r  r  r  r  r  r]  requestHeadersrequestBodyrt  messagefeedbacks                rT  handle_errorszbingx.handle_errorso  s     &1""8U3ww}t+H001I7T\]001I4QYZ001I7T\]))rU  r  )__name__
__module____qualname__r   rP  r
   r^  r   r  r    r   r  r  r  dictr  r  rD  r   r  r  r   r  r2  r   r>  r   rD  r   r   rH  rB  r   r]  r`  re  rd  r   ru  r   r|  r~  r  rr  r   r  r  r   r  r  r  r  r   floatr  r  r  r   r   r<  r  r   rU  r,  rc  r   rG  r  r  r  r  r  r  r  r  r  r  r  r   r   r  r   r  r	   r  r  r
  r   r  r  r(  r&  r@  r   rE  rH  rC  rL  r   rT  rS  r\  rh  rm  rr  rd  r  r  r  r  r  r  boolr  r  r   r  r  r   r  r  r  r  r8  r  intr  __classcell__)rS  s   @rT  r1   r1      s
   L
# L
\ !# 5s 5, ') bZ bH+DL +B"+H+._4 _F _B $& ;$v, ;. 26DW[df XJ# XJc XJQT XJkoptku XJt2
 2
4 2
h 6:UW =?3 =?s =?# =?\`af\g =?~^ ^v ^ ^@ :>b ms m3 mY m^ 68 &5 &5K &5P 6:" 77 7 7 
6 
[ 
B 8<$]ajl 1M 1MC 1MWZ 1Mf
6 
" 79 78# 78rF B 02 :33 :3f :3x 04B =4W =47 =4~ 46 5;s 5;& 5;n 48 64 64w 64pb4 b b6 bH $& f,( f,Pt) t)l @DRV_a ;RS ;R ;RC ;Rfjksft ;Rz 26b [8w [8T(^ [8z 24 R2S R2hwt wV wr _a 
MC 
My 
MPU 
M RT 	N 	N5 	N SU 	O 	OE 	O os{} z,3 z,i z,y z,Z_ z,hk z,x gksu B03 B0i B0y B0RW B0`c B0H @B _1D$6 _1B	3	3S 	3k kv k kZ: : 37r m/s m/C m/^ /32 I) I)V ;?r c*c c*C c*J <> &s &P 26b j/c j/3 j/X *.Dt\^ U?3 U?c U? U?cghmcn U?n /3TXac s? s?3 s?c s?hlmrhs s?j 154VZce :# :S :PS :jnotju :* 37TX\eg <C <s <RU <* >BPTcgpr }?s }?# }?]` }?~ [] '
S '
% '
c '
c '
an '
R +/TPT]_ /BC /Bs /B# /Bdhivdw /Bb
t 
x 
= 
0 DF )0s )0$~J^ )0V 79 ># >^ >4
h 
R` 
4 *.Dt\^ )I3 )Ic )I )Icghsct )IV -1tRV_a +Ic +I +IC +Ifjkvfw +IZ[
T [
X [
Q\ [
z:s :& >B"  W#  Ws  WD =? M Me MCU M @B MC M MFX M =?  @  @e  @CU  @D
d 
F 
N` 
. 24 81S 81 81t$
t $
V $
x $
L 9=R +US +U# +Uz -1tRV_a CFc CF CFC CFJ9 9v <@ F F DHPR (,S (,% (,# (,Wb (,T" 37TX\eg ^KC ^Ks ^KRU ^K@'V 'R =A B.S B.	 B.PU B.H *, :X :x 15R 
# 
8 =A T Tc T: `drv  @B F.S F.# F.Y F.i F.Y\ F.lo F.  GL F.P 57 ,4 ,4: ,4\
D 
* 
 57 @: @:;N @:D
T 
6 
EX 
"> "*%DW[ /Pb#-t -c 3 S # X\ dg rU  r1   )7ccxt.base.exchanger   ccxt.abstract.bingxr   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   r   r   r   r   r   typingr    ccxt.base.errorsr!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   ccxt.base.decimal_to_precisionr.   ccxt.base.preciser/   r1    rU  rT  <module>r     s    ( +   ~  ~  ~  ~  ~  ~  ~  ~  * 0 - - . ' & . ) * ) , + 4 %eaHk earU  