
    !:h2                       d dl mZ d dlmZ d dlZd dlZd dlZd dlmZm	Z	m
Z
mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ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%m0Z0 d dl%m1Z1 d dl%m2Z2 d dl3m4Z4 d dl5m6Z6  G d dee      Z7y)    )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    R/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/async_support/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                    K   | j                  |       d{   }| j                  |d      }| j                  |d      S 7 (w)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
        Ndata
serverTime)swapV2PublicGetServerTime	safe_dictsafe_integer)rR  paramsresponserW  s       rT  
fetch_timezbingx.fetch_time  sF      77?? ~~h/  |44 @   AA )Ac                   K   | j                  d      sy| j                  | j                  dd      }|ry| j                  |       d{   }| 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 7 w)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   rd  feeactivedepositre  	precisionlimitscrypto)rn  coder4   rr  r5   rp  rq  re  r#  ro  rs  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
currencyIdru  r5   rc  r#  j
rawNetworkrd  networkCoders  rr  s                      rT  fetch_currencieszbingx.fetch_currencies  s     ..u5NN4<<F	DDVLL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 i Ms   AG	G
E?Gc                    K   | j                  |       d {   }| j                  |d      }| j                  |dg       }| j                  |      S 7 :w)NrW  symbols)spotV1PublicGetCommonSymbolsrZ  rz  parse_markets)rR  r\  r]  rW  marketss        rT  fetch_spot_marketszbingx.fetch_spot_markets(  sT     ::6BB8 ~~h/..y"5!!'**= Cs   AA;Ac                    K   | j                  |       d {   }| j                  |dg       }| j                  |      S 7 (wNrW  )swapV2PublicGetQuoteContractsrz  r  rR  r\  r]  r  s       rT  fetch_swap_marketszbingx.fetch_swap_marketsI  sF     ;;FCC@ ..626!!'**C Dr_  c                    K   | j                  |       d {   }| j                  |dg       }| j                  |      S 7 (wr  )cswapV1PublicGetMarketContractsrz  r  r  s       rT  fetch_inverse_swap_marketsz bingx.fetch_inverse_swap_marketsm  sD     ==fEE& ..626!!'**) Fr_  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settleIdrv  rB   rD   rE   rp  r   rI  r   r   r   )amountr(  rh  )minNotionaltradeMinUSDTminTradeValuemaxNotional)r6  r  r(  cost)rJ  r   r   r   contractSizeexpiryexpiryDatetimestrike
optionTyperr  rs  createdrn  )r}  splitr~  r  rQ  r  rZ  r   rx  safe_number_2r[  safe_market_structuresafe_number_n)rR  r  r4   symbolPartsr  r  r  r   r  checkIsInversecheckIsLinearr  r  r  r  rv  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                   K   | j                  |      g}| j                  | j                  dd      }|s@|j                  | j	                  |             |j                  | j                  |             t        j                  |  d{   }| j                  |dg       }| j                  |dg       }| j                  |dg       }| j                  ||      }| j                  ||      S 7 aw)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
        ra  FNr   r   r   )
r  rx  rL  appendr  r  asynciogatherrz  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;< 22 NN8Q;!^^Ha<nnXq"5''(9;MN  k:: 3s   BC-	C+
A"C-r   Nr  sincer=  c           	        K   | j                          d{    d}| j                  |ddd      \  }}|r| j                  d|||||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                  ||             d{   }
n|d   r*| j                  | j                  ||             d{   }
n|| j	                  |d      }| j                  |d      }|dk(  r*| j                  | j                  ||             d{   }
n)| j                  | j                  ||             d{   }
| j                  |
dg       }t        |t               s|g}| j#                  |||||      S 7 7 7 7 7 s7 Kw)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
        NFrs   paginaterE  r  r4   intervalr   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&@@vW\^cenpvx|}}}V$fTl
 #..t	9U
#&uqy!#4GK $GG##FGY?YYvy1F!&GI&>!<<T[[RX=YZZHi !%!B!B4;;wX^C_!``((9673F?%)%N%Nt{{[bdjOk%llH%)%D%DT[[QXZ`Ea%bbHH 626&$'XF  E5IIK 	" ~  [ a
  mbsl   G:G,9G:G/B/G: G2.G:/G40AG:G6)G:,G8-A G:/G:2G:4G:6G:8G: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_ohlcvV  s    D eT"!!%+  *  *  *  *  *  v{;UF+UF+UE*UG,UH-
 	
rU  c                   K   | j                          d{    | j                  |      }d|d   i}|t        |d      |d<   d}d}| j                  d||      \  }}|dk(  r*| j	                  | j                  ||             d{   }n)| j                  | j                  ||             d{   }| j                  |dg       }	| j                  |	|||      S 7 7 W7 /w)	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>`
        Nr  r4   r:   r=  r   rA   rW  )	r  r  ri  handle_market_type_and_paramsspotV1PublicGetMarketTradesr  swapV2PublicGetQuoteTradesrz  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!==dkk'SY>Z[[H!<<T[[RX=YZZHD &"5  >>a 	" \Zs4   C#CA0C#C)C#1C!2,C#C#!C#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  rn  r  r4   tr  orderIdr  o)r(  p
tradePrice
commissionn)r  r  )r4   rn  	timestampdatetimer  orderrv  r  takerOrMakerr(  r  r  ro  )safe_integer_nr}  	parse8601safe_string_nr~  rx  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           	      ~  K   | j                          d{    | j                  |      }d|d   i}|||d<   d}d}| j                  d||      \  }}|dk(  r*| j                  | j	                  ||             d{   }nX|d   r*| j                  | j	                  ||             d{   }n)| j                  | j	                  ||             d{   }| j                  |di       }| j                  |d	      }	| j                  |d
d      }
| j                  ||d   |
dddd      }|	|d<   |S 7 7 7 7 dw)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
        Nr  r4   r=  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  	orderbookr;  r   r  s               rT  fetch_order_bookzbingx.fetch_order_booki  sb     !!!V$fTl
 $GG
!??@PRXZ`a
F!<<T[[RX=YZZHi !%!A!A$++gW]B^!__!%!?!?GU[@\!]]V NN8VR8	!!)^<''	3=	&&y&2BIvW]_`bcdwA 	" [ `]sG   D=D4A&D==D7>.D=,D9-)D=D;AD=7D=9D=;D=c                 t  K   | j                          d{    | j                  |      }d|d   i}d}|d   r*| j                  | j                  ||             d{   }n)| j	                  | j                  ||             d{   }| j                  |dg       }| j                  ||      S 7 7 U7 -w)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>`
        Nr  r4   rJ  rW  )r  r  "cswapV1PublicGetMarketPremiumIndexr   swapV2PublicGetQuotePremiumIndexrz  parse_funding_raterR  r  r\  r  r  r]  rW  s          rT  fetch_funding_ratezbingx.fetch_funding_rate  s      !!!V$fTl
 )!DDT[[QXZ`EabbH!BB4;;wX^C_``H" ~~h3&&tV447 	" c`4   B8B2AB8B4)B8B6	*B84B86B8r  c                   K   | j                          d{    | j                  |dd      }| j                  | j                  |             d{   }| j	                  |dg       }| j                  ||      S 7 d7 +w)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>`
        NrC   TrW  )r  market_symbolsrD  r  rz  parse_funding_rates)rR  r  r\  r]  rW  s        rT  fetch_funding_rateszbingx.fetch_funding_rates   sx      !!!%%gvt<>>t{{6?RSS~~h3''g66	 	"Ss!   A?A;:A?A=*A?=A?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  nextFundingTimern  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  r3  rX  s        rT  rE  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                 0  K   |t        | j                  dz         | j                          d{    d}| j                  |dd      \  }}|r| j	                  d|||d|       d{   S | j                  |      }d|d   i}|||d	<   |||d
<   | j                  |dd	      }|| j                  |dg      }||d	<   | j                  | j                  ||             d{   }	| j                  |	dg       }
| j                  |
|||      S 7 7 7 /w)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>`
        Nz5 fetchFundingRateHistory() requires a symbol argumentFrg   r  8hr  r4   r  r=  r  rW  )r%   r4   r  r  r  r  r  r  swapV2PublicGetQuoteFundingRater  rz  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_history1  sO     >#DGG.e$eff!!!88AZ\fg&@@AZ\bdikprvx~V$fTl
 #(GK $GG##FG[AYYvy1F#(GK ==dkk'SY>Z[[ ~~h300vueLLC 	" @ \s4   .DD7D(D)A;D$D%,DDDc                     | j                  |d      }|| j                  | j                  |d      |dd      | j                  |d      || j	                  |      dS )NfundingTimer  r  rC   rS  )rn  r  rS  r   r!  )r[  r-  r}  r  r,  )rR  r   r  r   s       rT  parse_funding_rate_historyz bingx.parse_funding_rate_historyd  se     %%h>	&&t'7'7('KVUXZ`a++HmD"Y/
 	
rU  c                   K   | j                          d{    | j                  |      }d|d   i}d}|d   r*| j                  | j                  ||             d{   }n)| j	                  | j                  ||             d{   }i }|d   r'| j                  |dg       }| j                  |di       }n| j                  |di       }| j                  ||      S 7 7 7 [w)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:
        Nr  r4   rJ  rW  r   )r  r  "cswapV1PublicGetMarketOpenInterestr   swapV2PublicGetQuoteOpenInterestrz  rZ  parse_open_interest)rR  r  r\  r  r  r]  r  rW  s           rT  fetch_open_interestzbingx.fetch_open_interestu  s      !!!V$fTl
 )!DDT[[QXZ`EabbH!BB4;;wX^C_``H: )>>(FB7D^^D!R0F^^Hfb9F''77Y 	" c`s5   C&C AC&C")C&C$	AC&"C&$C&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!  rn  )r  r}  r-  r  safe_open_interestr,  )rR  interestr  r   r4   r  rk  s          rT  rh  zbingx.parse_open_interest  s    $ ''&+F	h1!!"fc6:''.A&&"&!-"Y/	(
 	 		rU  c                 J  K   | j                          d{    | j                  |      }d|d   i}d}|d   r*| j                  | j                  ||             d{   }nX|d   r*| j	                  | j                  ||             d{   }n)| j                  | j                  ||             d{   }| j                  |d      }|%| j                  |di       }| j                  ||      S | j                  |di       }| j                  ||      S 7 7 7 7 iw)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>`
        Nr  r4   rA   rJ  rW  r   )	r  r  spotV1PublicGetTicker24hrr  cswapV1PublicGetMarketTickerswapV2PublicGetQuoteTickerrz  rZ  parse_ticker)	rR  r  r\  r  r  r]  rW  firstdataDicts	            rT  fetch_tickerzbingx.fetch_ticker  s%     !!!V$fTl
 &>!;;DKKQW<XYYHi !%!B!B4;;wX^C_!``!%!@!@WV\A]!^^: ~~h/NN4B/E$$UF33>>(FB7  622] 	" Z a^sG   D#DAD#D.D#D)D#7D!8A#D#D#D#!D#c                   K   | j                          d{    d}|6| j                  |      }| j                  |d      }|| j                  |      }d}| j	                  d||      \  }}d}| j                  d||      \  }}d}|dk(  r| j                  |       d{   }n8|dk(  r| j                  |       d{   }n| j                  |       d{   }| j                  |d      }| j                  ||      S 7 7 c7 F7 .w)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  rJ  r}  r  r  handle_sub_type_and_paramsrs  rt  ru  rz  parse_tickers)	rR  r  r\  r  firstSymbolrv  subTyper]  tickerss	            rT  fetch_tickerszbingx.fetch_tickers  s!     !!!))'2G**7A6K&[199.&RXYf99.&RXY6>!;;FCCH)#!%!B!B6!JJ!%!@!@!HH< ..62!!'733c 	" D KHsF   D
DB	D
 D!D
?D D
D)D
D
D
D
c                   K   | j                          d{    | j                  |      }d}| j                  d||d      \  }}d|d   i}d}|dk(  r*| j                  | j	                  ||             d{   }n)| j                  | j	                  ||             d{   }t        |d   t              r&| j                  | j                  |d   di       |      S | j                  |d   |      S 7 7 ~7 Vw)	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  r{  rC  r  rD  r  r   rv  rZ  )rR  r  r\  r  r~  r  r]  s          rT  fetch_mark_pricezbingx.fetch_mark_priceJ  s     !!!V$99:JFTZ\defTl
 i!DDT[[QXZ`EabbH$ "BB4;;wX^C_``H hv&-$$T^^HV4Da%LfUU  &!16::W 	" c$ as5   C:C4A C:7C68)C:!C8"AC:6C:8C:c                   K   | j                          d{    d}|6| j                  |      }| j                  |d      }|| j                  |      }d}| j	                  d||d      \  }}d}|dk(  r| j                  |       d{   }n| j                  |       d{   }| j                  |d      }| j                  ||      S 7 7 D7 ,w)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  rJ  r}  r  r{  rC  rD  rz  r|  )rR  r  r\  r  r}  r~  r]  r  s           rT  fetch_mark_priceszbingx.fetch_mark_prices  s      !!!))'2G**7A6K&[199:KVU[]efi!DDVLLH!BB6JJH< ..62!!'733Y 	" MJs4   CCA2C	C
C#C$)CCC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	lastPricerm  r  priceChangePercent% priceChanger  r   bidPricebidQtyaskPriceaskQtyr   r!  r  r  bid	bidVolumeask	askVolumevwapr  r  r$  previousClosechange
percentageaveragerO  rP  )rl  rm  rO  rP  rn  )r}  safe_marketreplacer[  r,  safe_ticker)rR  r  r  r3  r  rv  r  r  r  r  r  rm  rl  r  r  r8  r!  r  r  r  r  s                        rT  rv  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                   K   | j                          d{    d}d}| j                  |ddd      \  }}d}| j                  dd|      \  }}| j                  dd|      \  }}|r| j	                  |       d{   }nW|dk(  r| j                  |       d{   }n8|dk(  r| j                  |       d{   }n| j                  |       d{   }| j                  |      S 7 7 o7 R7 57 w)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  r{  r  contractV1PrivateGetBalancespotV1PrivateGetAccountBalancecswapV1PrivateGetUserBalanceswapV2PrivateGetUserBalanceparse_balance)rR  r\  r]  r  r~  r  marketTypeQuerys          rT  fetch_balancezbingx.fetch_balance  s     !!!88Q[]bc&99.$PVW&*&H&HY]_e&f#
O!==oNNH& 6!!@@QQH$ )#!%!B!B?!SS* "&!A!A/!RR* !!(++s 	" O( R& T* SsX   C2C(A#C2:C*;C2C,C28C.9C2C0C2*C2,C2.C20C2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 )Nrn  rW  r   balancesassetavailableMarginavailableBalancefree
usedMarginusedmaxWithdrawAmounttotallockedr   )	rz  rZ  r{  r|  r}  r~  r   r'  safe_balance)rR  r]  r  standardAndInverseBalancesfirstStandardOrInverseisStandardOrInversespotDataspotBalances	firstSpotisSpotr  r   r  ru  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                   K   | j                          d{    | j                  |      }d|d   i}|||d<   |||d<   | j                  d||      \  }}d}|d   r*| j                  | j	                  ||             d{   }nt        | j                  dz         | j                  |d	i       }| j                  |d
g       }	| j                  |	      }
| j                  |
|||      S 7 7 jw)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>`
        Nr  r4   pageSizestartTsendTsrI  zC fetchPositionHistory() is not supported for inverse swap positionsrW  positionHistory)r  r  handle_until_option$swapV1PrivateGetTradePositionHistoryr  r+   r4   rZ  rz  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(!FFt{{SZ\bGcddHtww)nnoo: ~~h3..'8"=((1	00FE5QQ] 	" es#   C/C+A+C/C-A)C/-C/c                 8  K   | j                          d{    | j                  |      }d}| j                  |ddd      \  }}d}|r| j                  |       d{   }nd}|6| j                  |      }| j	                  |d      }|| j                  |      }d}| j                  d||      \  }}|dk(  r| j                  |       d{   }n| j                  |       d{   }| j                  |dg       }| j                  ||      S 7 7 7 G7 /w)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  rJ  r  contractV1PrivateGetAllPositionr}  r  r{  cswapV1PrivateGetUserPositionsswapV2PrivateGetUserPositionsrz  r  )	rR  r  r\  r  r]  r  r}  r~  r  s	            rT  fetch_positionszbingx.fetch_positions8	  s<     !!!%%g.88AQS]_de&!AA&IIHF"--g6"..w:*![[5FG"==>NPVX^_OGV)#!%!D!DV!LL8 "&!C!CF!KK@ NN8VR8	##Iw77] 	" J M8 LsG   DDADDA0DDD(D)*DDDDc                   K   | j                          d{    | j                  |      }|d   st        | j                  dz         d|d   i}d}|d   r*| j	                  | j                  ||             d{   }n)| j                  | j                  ||             d{   }| j                  |dg       }| j                  |di       }| j                  ||      S 7 7 h7 @w)	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>`
        NrC   z+ fetchPosition() supports swap markets onlyr  r4   rJ  rW  r   )
r  r  r&   r4   r  r  r  rz  rZ  parse_position)rR  r  r\  r  r  r]  rW  rw  s           rT  fetch_positionzbingx.fetch_position	  s      !!!V$f~TWW'TTUUfTl
 )!@@WV\A]^^H8 "??GU[@\]]H@ ~~h3tQ+""5&11O 	" _8 ^s4   C(C"A$C(;C$<)C(%C&&=C($C(&C(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openTimern  r4   
positionIdrC   notionalpositionValuer-  liquidationPrice
entryPriceavgPriceunrealizedPnlunrealizedProfitrealizedPnlrealisedProfitr  	contractspositionAmtr  rO  r  r  positionSider4  r   
updateTimeinitialMarginr6  )r!  lastUpdateTimestampmaintenanceMarginmaintenanceMarginPercentage
collateralr  initialMarginPercentager6  marginRatior0  r1  )
r}  r  rx  r[  safe_positionr-  r  r  r.  r,  )rR  r  r  r3  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                 T   K   ||d<   | j                  |d||d|       d{   S 7 w)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_costb
  s3      #'&&vxtT6RRRR   (&(c                 T   K   ||d<   | j                  |dd|d|       d{   S 7 w)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_costn
  s3      #'&&vxdFSSSSr  c                 T   K   ||d<   | j                  |dd|d|       d{   S 7 w)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_costy
  s3      #'&&vxtVTTTTr  rv  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  rv  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_LIMITrv  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  rv  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  rx  
string_divjson)6rR  r  rv  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                   K   | j                          d{    | j                  |      }| j                  |dd      }| j                  |d      }| j	                  ||||||      }	d}
|d   rt|r| j                  |	       d{   }
nq|d   r| j                  |	       d{   }
nR|dk(  r| j                  |	       d{   }
n3| j                  |	       d{   }
n| j                  |	       d{   }
t        |
t              r"| j                  |
      }
| j                  |
      }
| j                  |
di       }i }|d   r|d   r|
}n| j                  |d|      }n|}| j                  ||      S 7 a7 7 7 7 7 w)	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>`
        Nr   FrC   rJ  twaprW  r"  )r  r  rx  r  rA  swapV2PrivatePostTradeOrderTestcswapV1PrivatePostTradeOrderswapV1PrivatePostTwapOrderswapV2PrivatePostTradeOrderspotV1PrivatePostTradeOrderr  strfix_stringified_json_members
parse_jsonrZ  parse_order)rR  r  rv  r  r  r(  r\  r  r   r  r]  rW  r  s                rT  r  zbingx.create_order@  s    D !!!V$~~ffe466*++FD$vV&>!%!E!Eg!NN	"!%!B!B7!KK!%!@!@!II!%!A!A'!JJ!==gFFHB h$ 88BHx0H~~h3&>i !gt<F//A 	" OKIJFsk   FE7A-FE:F#E<$FE>FF F6F7BF:F<F>F FFordersc           	      J  K   | j                          d{    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   rK|dkD  rt        | j                  dz         | j                  |      |d<   | j                  |       d{   }nG| j                  |dd	      }|rd
|d<   | j                  |      |d<   | j                  |       d{   }t!        |t"              r"| j%                  |      }| j'                  |      }| j                  |di       }| j)                  |dg       }| j+                  ||      S 7 7 7 sw)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>`
        Nr   r  rv  r  r  r(  r\  FTrC   r   zJ createOrders() can not create more than 5 orders at once for swap marketsbatchOrderssyncrW  rM  )r  r{  r|  r}  r  r  rZ  rA  rJ  r  r)   r4   r#  !swapV2PrivatePostTradeBatchOrdersrx  !spotV1PrivatePostTradeBatchOrdersr  rI  rJ  rK  rz  parse_orders)rR  rM  r\  ordersRequests	marketIdsr  rawOrderr3  rv  r  r  r(  orderParamsorderRequestr  symbolsLengthr  r  r]  rP  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"!CCGLLH>>&&%8D"&"ii7GFO!CCGLLH\ h$ 88BHx0H~~h3h3  00g 	". M Ms6   H#HEH#%H&AH#-H!.A/H#H#!H#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stopr^  )rR  rv  typess      rT  parse_order_typezbingx.parse_order_type0  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  )ro  r  r  r  r  r   r  r  r  r  rv  r  	StopPricerf  takern  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  ro  r  r  )safe_dict_2r'  r  r)  r$  r  safe_string_upper_nr&  r  	omit_zeror}  r  numbersRealrI  rK  find
safe_orderr-  r,  r[  rh  r/  parse_order_statusr/   r0  safe_bool_2)rR  r"  r  rn  newOrderr  r  r3  r  r   ry  statusIdfeeCurrencyCodefeeCostr  r0  r  r1  rawTyper  r.  s                        rT  rL  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FAILEDr^  rR  r  statusess      rT  r  zbingx.parse_order_status  s8     &"# 	
 &&99rU  r4   c                   K   | j                          d{    | j                  |dd      }| j                  |d      }d}d}|r/d|i}| j                  | j	                  ||             d{   }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	                  ||             d{   }nX|dk(  r*| j                  | j	                  ||             d{   }n)| j                  | j	                  ||             d{   }| j                  |di       }| j                  |d|      }| j                  ||      S 7 7 ^7 7 n7 Fw)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>`
        NrC  Frv  z) cancelOrder() requires a symbol argumentr  r4   r  r  r  rI   rA   rJ  rW  r"  )r  rx  r   swapV1PrivatePostTwapCancelOrderr  r%   r4   r  r'  r  r{  spotV1PrivatePostTradeCancel$cswapV1PrivateDeleteTradeCancelOrderswapV2PrivateDeleteTradeOrderrZ  rL  )rR  r4   r  r\  r&  r]  r  r-  r  r  rv  r~  rW  r"  s                 rT  cancel_orderzbingx.cancel_order  s     !!!nnVVU;66*r!K "BB4;;{\bCcddH4 ~'2](]^^[[(F&,G !..vXMYYv'89F(+8(%'	"DG==mVU[\LD&"==mVU[\OGVv~!%!B!B4;;wX^C_!``i'%)%N%Nt{{[bdjOk%llH%)%G%GT[]cHd%eeHF ~~h3tWd3v..} 	" eV a  mesY   GG	AG.G/CG3G4.G"G#)GG=GGGGGc                 l  K   |t        | j                  dz         | j                          d{    | j                  |      }d|d   i}d}|d   r*| j	                  | j                  ||             d{   }nv|d   rY|d   r*| j                  | j                  ||             d{   }nB| j                  | j                  ||             d{   }nt        | j                  dz         | j                  |d	i       }| j                  |d
dg       }| j                  |      S 7 7 7 7 [w)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  successrM  )r%   r4   r  r  &spotV1PrivatePostTradeCancelOpenOrdersr  &cswapV1PrivateDeleteTradeAllOpenOrders%swapV2PrivateDeleteTradeAllOpenOrdersr&   rZ  safe_list_2rS  )rR  r  r\  r  r  r]  rW  rM  s           rT  cancel_all_orderszbingx.cancel_all_ordersd  s@     >#DGG.]$]^^!!!V$fTl
 &>!HHU\^dIeffH. F^i !%!L!LT[[Y`bhMi!jjr "&!K!KDKKX_agLh!ii> TWW'ffgg~~h3!!$	8R@  ((w 	" g2 kr jsG   .D4D,AD48D.93D4,D0-)D4D2AD4.D40D42D4idsc                   K   |t        | j                  dz         | j                          d{    | j                  |      }d|d   i}| j	                  |d      }| j                  |d      }|}|du}|r|}g }	t        dt        |            D ]#  }
||
   }t        |      }|	j                  |       % d}|d   rD|rdnd	}d
j                  |	      ||<   | j                  | j                  ||             d{   }nE|r| j                  |	      |d<   n|	|d<   | j                  | j                  ||             d{   }| j                  |di       }| j!                  |ddg       }| j#                  |      S 7 P7 7 Aw)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  rM  )r%   r4   r  r  r  r  r{  r|  rI  r  join"spotV1PrivatePostTradeCancelOrdersr  r#  #swapV2PrivateDeleteTradeBatchOrdersrZ  r  rS  )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!DDT[[QXZ`EabbH8 !/3yy/C+,)2&!EEdkkRY[aFbccH< ~~h3""4HbA  ))i 	"( c@ ds5   .FF CF=F>AFF=FFFtimeoutc                   K   | j                          d{    |dkD  }|rdnd|r| j                  |dz        ndd}d}d}| j                  dd|      \  }}|dk(  r+| j                  | j	                  ||             d{   }|S |d	k(  r+| j                  | j	                  ||             d{   }|S t        | j                  d
z   |z   dz         7 7 V7 (w)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
        Nr   ACTIVATECLOSErB  )rv  timeOutrH   rA   rC   z- cancelAllOrdersAfter() is not supported for  markets)r  parse_to_intr  $spotV1PrivatePostTradeCancelAllAfterr  $swapV2PrivatePostTradeCancelAllAfterr+   r4   )rR  r  r\  r  r  r]  rv  s          rT  cancel_all_orders_afterzbingx.cancel_all_orders_afterT  s      !!!aK#+J'?G))'D.9a
 99:PRVX^_f6>!FFt{{SZ\bGcddH   V^!FFt{{SZ\bGcddH  tww)XX[__bllmm 	" eds4   CCA+CC/C2C3%CCCc                 H  K   | j                          d{    | j                  |dd      }| j                  |d      }d}d}|r.d|i}| j                  | j	                  ||             d{   }n|t        | j                  dz         | j                  |      }|d   |d}d}	d}
| j                  d||      \  }	}| j                  d||      \  }
}|	d	k(  r*| j                  | j	                  ||             d{   }nX|
d
k(  r*| j                  | j	                  ||             d{   }n)| j                  | j	                  ||             d{   }| j                  |di       }| j                  |d|      }| j                  ||      S 7 7 +7 7 n7 Fw)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>`
        NrC  Frv  z( fetchOrder() requires a symbol argumentr4   )r  r  rv   rA   rJ  rW  r"  )r  rx  r  swapV1PrivateGetTwapOrderDetailr  r%   r4   r  r  r{  spotV1PrivateGetTradeQuery!cswapV1PrivateGetTradeOrderDetailswapV2PrivateGetTradeOrderrZ  rL  )rR  r4   r  r\  r&  r]  r  r-  r  rv  r~  rW  r"  s                rT  fetch_orderzbingx.fetch_order|  s     !!!nnVVU;66*r!K "AA$++k[aBbccH6 ~'2\(\]][[(F ,G DG==lFTZ[LD&"==lFTZ[OGVv~!%!@!@WV\A]!^^0 i'%)%K%KDKKX_agLh%iiHj &*%D%DT[[QXZ`Ea%bbH6 ~~h3tWd3v..w 	" dN _2  jj  csY   F"FAF".F/BF" F.F"/F0)F"F =F"F"F"F" F"c                   K   | j                          d{    i }d}|| j                  |      }|d   |d<   d}| j                  d||      \  }}|dk7  rt        | j                  dz         |||d<   |||d<   | j                  d	||      \  }}| j                  | j                  ||             d{   }| j                  |d
i       }	| j                  |	dg       }
| j                  |
|||      S 7 7 @w)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  rM  )r  r  r  r+   r4   r  swapV1PrivateGetTradeFullOrderr  rZ  rz  rS  )rR  r  r  r=  r\  r  r  rv  r]  rW  rM  s              rT  fetch_orderszbingx.fetch_orders(  s"     !!![[(F &tGH99-QWXf6>tww)\\]]$GG#(GK 229gvN<<T[[RX=YZZj ~~h3h3  >>M 	" [s"   C:C6B C:7C88?C:8C:c                   K   | j                          d{    d}i }|| j                  |      }|d   |d<   d}d}d}	| j                  d||      \  }}| j                  d||      \  }}|dk(  r*| j	                  | j                  ||             d{   }	n| j                  |dd      }
| j                  |d      }|
r*| j                  | j                  ||             d{   }	nX|dk(  r*| j                  | j                  ||             d{   }	n)| j                  | j                  ||             d{   }	| j                  |	d	i       }| j                  |d
dg       }| j                  ||||      S 7 i7 7 7 p7 Hw)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   rC  FrJ  rW  rM  r   )r  r  r  r{  spotV1PrivateGetTradeOpenOrdersr  rx  r  swapV1PrivateGetTwapOpenOrders cswapV1PrivateGetTradeOpenOrdersswapV2PrivateGetTradeOpenOrdersrZ  r  rS  )rR  r  r  r=  r\  r  r  rv  r~  r]  r&  rW  rM  s                rT  fetch_open_orderszbingx.fetch_open_orders  s      !!![[(F &tGH99:KVU[\f99:KVU[\6>!AA$++gW]B^__H..?KYYvv.F!%!D!DT[[QXZ`Ea!bbI%!%!F!Ft{{SZ\bGc!dd!%!E!EdkkRY[aFb!ccX ~~h3!!$&"=  >>G 	" `
 cdcsZ   F
E?A>F
FAF
&F'.F
F)F
?F A F
F
F
F
F
c                    K   | j                          d{    | j                  ||||       d{   }| j                  |dd      S 7 37 w)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>`
        Nr  r  r   fetch_canceled_and_closed_orders	filter_byrR  r  r  r=  r\  rM  s         rT  fetch_closed_orderszbingx.fetch_closed_orders4  sP     " !!!<<VUESYZZ~~fh99 	"Z   AA
AAAAc                    K   | j                          d{    | j                  ||||       d{   }| j                  |dd      S 7 37 w)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>`
        Nr  r  r  r  s         rT  fetch_canceled_orderszbingx.fetch_canceled_ordersI  sP     " !!!<<VUESYZZ~~fh
;; 	"Zr  c                 X  K   | j                          d{    d}i }|| j                  |      }|d   |d<   d}d}d}	d}
| j                  d||      \  }}| j                  d||      \  }}| j	                  |ddd      \  }	}|	r+| j                  | j                  ||             d{   }
n.|dk(  r1|||d<   | j                  | j                  ||             d{   }
n| j                  |d	d      }| j                  |d	      }|ryd
|d<   |dn||d<   |d
n||d<   | j                  |d| j                               }| j                  |d      }||d<   | j                  | j                  ||             d{   }
nX|dk(  r*| j                  | j                  ||             d{   }
n)| j                  | j                  ||             d{   }
| j                  |
di       }| j!                  |ddg       }| j#                  ||||      S 7 7 s7 ?7 7 t7 Lw)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  rC  r   	pageIndexr:   r  r  r  rJ  rW  rM  r   )r  r  r  r{  r  contractV1PrivateGetAllOrdersr  "spotV1PrivateGetTradeHistoryOrdersrx  r  r[  milliseconds!swapV1PrivateGetTwapHistoryOrders"cswapV1PrivateGetTradeOrderHistoryswapV2PrivateGetTradeAllOrdersrZ  r  rS  )rR  r  r  r=  r\  r  r  rv  r~  r  r]  r&  r  rW  rM  s                  rT  r  z&bingx.fetch_canceled_and_closed_orders^  sf    & !!![[(F &tGH99:MvW]^f99:MvW]^88ATV`bgh&!??GU[@\]]HV^ &+
#!DDT[[QXZ`EabbH4 ..?KYYvv.F'($.3mc%
#-2]q$))&'4;L;L;NO673%*	"!%!G!GT[]cHd!ee< I%!%!H!HU\^dIe!ffn "&!D!DT[[QXZ`Ea!bb: ~~h3!!$&"=  >>U 	" ^ cF f> gn csl   H*HBH*+H,6H*"H!#BH*H$.H*1H&2)H*H(A H*H*!H*$H*&H*(H*ru  fromAccount	toAccountc           
        K   | j                          d{    | j                  |      }| j                  | j                  di       }| j	                  |||      }| j	                  |||      }	|d   | j                  ||      |dz   |	z   d}
| j                  | j                  |
|             d{   }|| j	                  |d      dd||||dd	S 7 7 "w)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>`
        Nr  r4   _)r  r  rv  tranId	rn  r4   r   r!  r  r  r  r  r  )r  r  rZ  rL  r}  currency_to_precision spotV3PrivateGetGetAssetTransferr  )rR  ru  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'

 >>t{{7TZ?[\\ ""8X6&"

 
	
! 	" ]s"   CCBC2C3!CCc                 D  K   | j                          d{    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                  ||             d{   }| j                  |d
g       }| j                  ||||      S 7 7 .w)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 requiredrv  r  r  sizerows)r  r  rZ  rL  r}  r!   r4   spotV3PrivateGetAssetTransferr  rz  parse_transfers)rR  ru  r  r=  r\  r  r  r  r  r  r  r  r]  r  s                 rT  fetch_transferszbingx.fetch_transfersF  sA     !!!}}T*H6FK&&v}=$$V[9	!!.+{K	9E>T\*[ [\\FSL4'
 #(GK #GFO;;DKKQW<XYY  ~~h3##D(E5AAG 	"$ Zs"   D DCD /D0,D D 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  rv  r  r   r   r  r  )r}  r[  r~  rZ  rL  r  r,  r  )rR  r   r  r  r   r2  r  r  typeIdtypeIdSplitr  r  r  r  s                 rT  parse_transferzbingx.parse_transferw  s   !!(H5%%h<	..tX>!!(H5~~dllNBG!!(F3ll3'!!+q1*&&|VVD$$\4>	"Y/$&&x:&"

 
	
rU  c                   K   | j                          d{    | j                  |      }| j                  | j                  d      }| j                  | j                  d|      }|d   dd|d}| j                  | j                  ||             d{   }| j                  | j                  |d      d      }| j                  ||d   gd	      }	| j                  |	d
      S 7 7 Qw)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
        Nr   r4   r   rB  )rb  offsetr=  r   rW  ru  Frd  )r  r  r[  rL  parse_params(walletsV1PrivateGetCapitalDepositAddressr  rz  rZ  parse_deposit_addressesindex_by)
rR  ru  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$	
 FFt{{SZ\bGcdd& ~~dnnXv>G--dXf5E4FN}}VY//? 	" es#   C'C#A<C'C%AC'%C'c                   K   | j                  |d      }| j                  |dg      }| j                  ||       d{   }|| j                  ||      S | j                  | j                  d      }| j                  ||      }|| j                  ||      S t        |j                               }| j                  |d      }| j                  ||      S 7 w)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>`
        rd  Nr"  r   )r}  r  r  rZ  rL  r   keys)	rR  ru  r\  rd  addressStructuresrL  defaultNetworkForCurrencyr  keys	            rT  fetch_deposit_addresszbingx.fetch_deposit_address  s      ""6956I;/"&"I"I$PV"WW>>"3W==nnT\\3DEG(,(8(8$(G%(4~~&79RSS-2245&&tQ/~~&7== Xs   ;CCBCc                    | j                  |d      }| j                  |d      }| j                  ||      }|d   }| j                  |d      }| j                  |d      }| j                  ||      }| j                  |       |||||dS )Ntagrb  ru  addressWithPrefixrd  )rn  r  rd  addressr	  )r}  safe_currencyr  check_address)	rR  depositAddressr  r	  r  ru  r  
networkdIdr  s	            rT  parse_deposit_addresszbingx.parse_deposit_address  s     ~u5%%nf=
%%j(;"">3FG%%ni@
--j$?7#""
 	
rU  c                   K   | j                          d{    i }d}|| j                  |      }|d   |d<   |||d<   |||d<   | j                  | j                  ||             d{   }| j	                  ||||      S 7 n7 w)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   rb  r  r=  )r  r  $spotV3PrivateGetCapitalDepositHisrecr  parse_transactionsrR  ru  r  r=  r\  r  r  r]  s           rT  fetch_depositszbingx.fetch_deposits  s      !!!
}}T*H&tnGFO#(GK $GGBB4;;wX^C_``$ &&x5%HH; 	" a"   B	BAB	,B-B	B	c                   K   | j                          d{    i }d}|| j                  |      }|d   |d<   |||d<   |||d<   | j                  | j                  ||             d{   }| j	                  ||||      S 7 n7 w)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   rb  r  r=  )r  r  &spotV3PrivateGetCapitalWithdrawHistoryr  r  r  s           rT  fetch_withdrawalszbingx.fetch_withdrawals  s      !!!
}}T*H&tnGFO#(GK $GGDDT[[QXZ`Eabb( &&x5%HH? 	" cr  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	applyTimerd  rb  r   r  transferType0rq  
withdrawalrn  txidtxIdrv  r  r  r  r   r!  addressFrom	addressTor	  tagFromtagToupdatedtransactionFee)r  r  rate)commentro  internal)r  r}  r[  r,  r%  r~  r  r  r  r  parse_transaction_status)rR  r  r  rW  dataIdr4   r  r	  r   r!  rd  r  ru  r  rv  s                  rT  parse_transactionzbingx.parse_transactionF  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6r^  r  s      rT  r-  zbingx.parse_transaction_status  sJ    
  &&99rU  r-  c                 <  K   |t        | j                  dz         | j                          d{    | 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                  ||             d{   S | j                  | j                  ||             d{   S 7 7 /7 w)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 argumentrv  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&   r{  !cswapV1PrivatePostTradeMarginTyper   swapV2PrivatePostTradeMarginType)rR  r-  r  r\  r  r  r~  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??GU[@\]]]>>t{{7TZ?[\\\% 	"  ^\s4   .DDB7D(D)(DDDDDc                 l   K   ddi}| j                  ||| j                  ||             d {   S 7 w)Nrv  r   
set_marginr  rR  r  r  r\  r  s        rT  
add_marginzbingx.add_margin  8     A
 __VVT[[&5QRRRR   +424c                 l   K   ddi}| j                  ||| j                  ||             d {   S 7 w)Nrv  r   rI  rK  s        rT  reduce_marginzbingx.reduce_margin  rM  rN  c                   K   | j                  |d      }|t        | j                  dz         | j                  |ddg      st        | j                  dz         | j	                          d{    | j                  |      }|d   | j                  |d   |      |d}| j                  | j                  ||             d{   }| j                  ||      S 7 l7 w)	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>`
        rv  NzV setMargin() requires a type parameter either 1(increase margin) or 2(decrease margin)r   r   r4   r  )r  r  rv  )
r[  r%   r4   in_arrayr  r  r   $swapV2PrivatePostTradePositionMarginr  parse_margin_modification)rR  r  r  r\  rv  r  r  r]  s           rT  rJ  zbingx.set_margin  s        0<#DGG  /G  %G  H  H}}TAq6*#DGG  /G  %G  H  H!!!V$Tl..vh/?H

 BB4;;wX^C_`` --h??! 	" as%   A,C.C/ACCCCrW  c                     | j                  |d      }|| j                  |d      |dk(  rdndd| j                  |d      | j                  |d      | j                  |d	      d d d d

S )Nrv  r  r  addreducer  r  rB   r  )
rn  r  rv  r-  r  r  ru  r  r   r!  )r}  r  )rR  rW  r  rv  s       rT  rT  zbingx.parse_margin_modification  sz     f-&&vx8"ckE$&&tX6%%dH5$$VX6
 	
rU  c                 t  K   | j                          d{    | j                  |      }d|d   i}d}|d   r*| j                  | j                  ||             d{   }n)| j	                  | j                  ||             d{   }| j                  |di       }| j                  ||      S 7 7 U7 -w)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>`
        Nr  r4   rJ  rW  )r  r  cswapV1PrivateGetTradeLeverager  swapV2PrivateGetTradeLeveragerZ  parse_leveragerF  s          rT  fetch_leveragezbingx.fetch_leverage  s      !!!V$fTl
 )!@@WV\A]^^H$ "??GU[@\]]H& ~~h3""400[ 	" _$ ^rH  r6  c                     | j                  |d      }|| j                  ||      d | j                  |d      | j                  |d      dS )Nr  longLeverageshortLeverage)rn  r  r-  r^  r_  )r}  r-  r[  )rR  r6  r  r3  s       rT  r[  zbingx.parse_leverageW  sV    : ##Hh7&&x8 --hG!..xI
 	
rU  c                   K   |t        | j                  dz         | j                  |d      }| j                  d|dg d       | j	                          d{    | j                  |      }|d   ||d}|d   r)| j                  | j                  ||             d{   S | j                  | j                  ||             d{   S 7 u7 /7 w)	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
        Nz) 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 

 )==dkk'SY>Z[[[$ <<T[[RX=YZZZ5 	" \$ [s7   ACCAC C!(C	C
CCCc                 |  K   |t        | j                  dz         | j                          d{    | j                  |      }i }d}d}d}	| j	                  d||      \  }	}|	dk(  rj| j                  |d      }
|
t        | j                  dz         | j                  | j                  ||             d{   }| j                  |dg       }nJ|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
   rW|||d<   | j                  | j                  ||             d{   }| j                  |di       }| j                  |dg       }ny| j                  |dd      }| j                  |d      }||d<   | j                  | j                  ||             d{   }| j                  |di       }| j                  |dg       }| j!                  |||||      S 7 7 |7 7 Gw)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  r{  r}  #cswapV1PrivateGetTradeAllFillOrdersr  rz  r  r[  r  spotV1PrivateGetTradeMyTradesrZ  r  "swapV2PrivateGetTradeAllFillOrdersr  )rR  r  r  r=  r\  r  r  rf  r]  r~  r  nowstartTimeReqr  
endTimeReqrW  rg  s                    rT  fetch_my_tradeszbingx.fetch_my_trades  s}    $ >#DGG.[$[\\!!!V$99/6SYZi&&vy9G'2y(yzz!EEdkkRY[aFbccHNN8VR8E8 !'tGH##%C .4Vn{)(-%%(+C%C	"%%fg6EYYvw/F *0.Yg
&+
##& f~$',GG$!%!C!CDKKPWY_D`!aa~~h;tWb94 #44V]FS6=9)4&!%!H!HU\^dIe!ff~~h;t]B?*   ufEE_ 	" d\ b> gsI   .H<H2BH<9H5:B>H<8H89A9H<2H:3A H<5H<8H<:H<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 )Nrc  )ro  r  )rn  re  rq  r#  r   rd  	isDefaultru  rk  F)rq  re  r#  re  ro  r  )rz  r|  r{  r}  rx  r  r  )rR  ro  r  rc  networkListLengthr  r  rd  	networkIdrr  r2  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                    K   | j                          d{    | j                  |       d{   }| j                  |d      }| j                  ||d      S 7 B7 +w)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>`
        NrW  rb  )r  ry  rz  parse_deposit_withdraw_fees)rR  rv  r\  r]  coinss        rT  fetch_deposit_withdraw_feesz!bingx.fetch_deposit_withdraw_feesz  s[      !!!DDVLLx0//ufEE 	"Ls   AAAA*AAr  c                 (  K   | j                  ||      \  }}| j                  |       | j                          d{    | j                  |      }| j	                  |dd      }|d   || j                  ||      |d}| j                  |d      }	|	| j                  |	      |d<   |||d<   | j                  |ddg      }| j                  | j                  ||             d{   }
| j                  |
d      }| j                  |      S 7 7 )w)	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>`
        N
walletTyper   r4   )rb  r  r  r|  rd  r  rW  )handle_withdraw_tag_and_paramsr  r  r  r[  r  r  network_code_to_idr  (walletsV1PrivatePostCapitalWithdrawApplyr  r  r/  )rR  ru  r  r  r	  r\  r  r|  r  rd  r]  rW  s               rT  re  zbingx.withdraw  s&     99#vFV7#!!!==&&&v|Q?
TN00v>$	
 ((;!%!8!8!AGI?$'GL!6L)#<=FFt{{SZ\bGcddx0 %%d++1 	" es"   :DDB)D&D'(DD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  r{  r|  r  rI  )
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                 T  K   | j                          d{    ddi}| j                  d||      \  }}d}|| j                  |      }|d   |d<   |||d<   |||d<   d}| j                  d	||      \  }}d}d}	|d
k(  r=| j	                  | j                  ||             d{   }| j                  |dg       }	nO| j                  | j                  ||             d{   }| j                  |di       }
| j                  |
dg       }	| j                  |	|||      S 7 7 ~7 Cw)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>`
        NautoCloseTypeLIQUIDATIONr  r4   r  r  r=  rq   rJ  rW  rM  )
r  r  r  r{  !cswapV1PrivateGetTradeForceOrdersr  rz   swapV2PrivateGetTradeForceOrdersrZ  parse_liquidations)rR  r  r  r=  r\  r  r  r~  r]  liquidationsrW  s              rT  fetch_my_liquidationszbingx.fetch_my_liquidations  s]     !!!]
 229gvN[[(F &tGH#(GK $GG99:OQWY_`i!CCDKKPWY_D`aaH8  >>(FB?L!BB4;;wX^C_``H< >>(FB7D>>$"=L&&|VUEJJa 	"$ b< as4   D(D!BD(%D$&<D("D&#?D($D(&D(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  r}  r  r  )	rn  r  r  r  r(  	baseValue
quoteValuer   r!  )r}  r[  r/   r*  safe_liquidationr-  rQ  r,  )
rR  liquidationr  r3  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                   K   | j                          d{    | j                  |      }| j                  |d      }i }d}|*| j                  | j	                  ||             d{   }n`|d   |d<   |d   r*| j                  | j	                  ||             d{   }n)| j                  | j	                  ||             d{   }| j                  |d      }| j                  ||      S 7 7 7 V7 .w)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>`
        Nr  r4   r  rJ  rW  )	r  r  r}  #swapV1PrivatePostTradeClosePositionr  (cswapV1PrivatePostTradeCloseAllPositions'swapV2PrivatePostTradeCloseAllPositionsrZ  rL  )	rR  r  r  r\  r  r  r  r]  rW  s	            rT  close_positionzbingx.close_positionM  s     !!!V$%%fl;
!!EEdkkRY[aFbccH$ !'tGHi !%!N!Nt{{[bdjOk!ll "&!M!MdkkZaciNj!kk ~~h/f--k 	" d( m lsF   C:C2AC:(C4)6C:C6 )C:	C8
)C:4C:6C:8C:c                   K   | j                          d{    | 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                  ||             d{   }n)| j                  | j                  ||             d{   }| j                  |di       }| j                  |d	g       }	g }
t        d
t        |	            D ])  }| j                  d|	|   i      }|
j!                  |       + |
S 7 Z7 7 tw)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>`
        Nr   rK   rB   z% closePositions() cannot be used for r  rJ  rW  r  r   r  )r  r[  rL  r  r  r{  r&   r4   r  r  r  rZ  rz  r{  r|  r  r  )rR  r\  r  r   r  r~  r  r]  rW  r  r  r  r  s                rT  close_all_positionszbingx.close_all_positions  s     !!! --dllLI&&t'8'8,HYZ

!??@SUY[ab
F99:MtU[\!TWW'NNQ[[^hhii*
 i!JJ4;;W^`fKghhH "II$++V]_eJfggH ~~h3..y"5	q#g,' 	'A**L'!*+EFHX&	' _ 	" i hs5   E7E0B?E7E3)E7 E5A0E73E75E7c                    K   | j                  |       d{   }| j                  |di       }| j                  |d      }||dk(  dS 7 1w)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
        NrW  dualSidePositionr  )rn  r4  ) swapV1PrivateGetPositionSideDualrZ  r}  )rR  r  r\  r]  rW  r  s         rT  fetch_position_modezbingx.fetch_position_mode  s^      >>vFF ~~h3++D2DE'61
 	
 Gs   AA	2Ar4  c                 z   K   d}|rd}nd}d|i}| j                  | j                  ||             d{   S 7 w)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  sO       %& 0
 ;;DKKQW<XYYYYs   2;9;c                   K   | j                          d{    | j                  |      }| j                  ||||||      }	||	d<   d|	d<   d}
|d   r*| j                  | j	                  |	|             d{   }
n)| j                  | j	                  |	|             d{   }
| j                  |
d      }| j                  ||      S 7 7 T7 ,w)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>`
        NcancelOrderIdSTOP_ON_FAILUREcancelReplaceModerC   rW  )r  r  rA  #swapV1PrivatePostTradeCancelReplacer  (spotV1PrivatePostTradeOrderCancelReplacerZ  rL  )rR  r4   r  rv  r  r  r(  r\  r  r  r]  rW  s               rT  
edit_orderzbingx.edit_order  s     @ !!!V$++FD$vV#% '8#$&>!EEdkkRY[aFbccHp "JJ4;;W^`fKghhHL ~~h/f--M 	" dp is4   CC
A C7C8)C!C")CCCc                   K   | j                          d{    | j                  |      }d|d   i}d}d}| j                  d||      \  }}|dk(  r*| j                  | j	                  ||             d{   }n)| j                  | j	                  ||             d{   }| j                  |di       }| j                  ||      S 7 7 U7 -w)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>`
        Nr  r4   rl   rJ  rW  )r  r  r{   cswapV1PrivateGetTradeMarginTyper  swapV2PrivateGetTradeMarginTyperZ  parse_margin_mode)rR  r  r\  r  r  r~  r]  rW  s           rT  fetch_margin_modezbingx.fetch_margin_mode  s      !!!V$fTl
 99:KVU[\i!BB4;;wX^C_``H "AA$++gW]B^__H ~~h3%%dF33C 	" a `s4   CC
AC6C7)C C!*CCCc                     | j                  |d      }| j                  |d      }|dk(  rdn|}|| j                  ||dd      |dS )Nr  rD  crossedr  r  rC   )rn  r  r-  )r}  r.  r-  )rR  r-  r  r3  rD  s        rT  r  zbingx.parse_margin_mode  sX    ##J9++JE
!+y!8Wz
&&xfE$
 	
rU  c                   K   | j                          d{    | j                  |      }d|d   i}d}i }| j                  |di       }|d   r,| j                  | j	                  ||             d{   }|}nM|d   r| j                  |       d{   }|}n,| j                  |       d{   }| j                  |di       }| j                  ||      S 7 7 h7 I7 /w)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>`
        Nr  r4   rW  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&>!DDT[[QXZ`EabbH Ji !%!I!I&!QQ "
!%!H!H!PP "^^D,C
%%j&99i 	" c R QsF   C"CAC"3C4 C"CC"0C 1*C"C"C" C"ro  c                 f    ||d   nd }||| j                  |d      | j                  |d      dddS )Nr  makerCommissionRatetakerCommissionRateF)rn  r  r   r   r  r   )r  )rR  ro  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  r  r  =&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   ra  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)rx  rL  r+   r4   implode_hostnamer   implode_paramsr  extract_paramsr;  r  	urlencoderw  r  r  	rawencodehmacencoder   hashlibsha256r   r}  r#  )rR  pathsectionr  r\  r  r  rv  r;   accessr  r  isJsonContentTypeparsedParamsencodeRequestr  querys                    rT  signz
bingx.sign8  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  r;  zbingx.noncei  s      ""rU  enablec                 J    t         t        |   |       || j                  d<   y )Nra  )rO  r1   set_sandbox_moderL  )rR  r  rS  s     rT  r  zbingx.set_sandbox_model  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 )Nru  msgr    r  r  )r}  r4   throw_exactly_matched_exceptionr   throw_broadly_matched_exceptionr!   )rR  r  r  r  r  r  r  r]  requestHeadersrequestBodyru  messagefeedbacks                rT  handle_errorszbingx.handle_errorsp  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  rI  r   r  r  r   r  r5  r   rA  r   rG  r   r   rL  rE  r   ra  rd  ri  rh  r   ry  r   r  r  r  rv  r   r  r  r   r  r  r  r  r   floatr  r  r  r   r   rA  r  r   rZ  r/  rh  r   rL  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-  rG  r   rL  rP  rJ  rT  r   r\  r[  rd  rp  ru  rz  re  r  r  r  r  r  r  boolr  r  r   r  r  r   r  r  r  r  r;  r  intr  __classcell__)rS  s   @rT  r1   r1      s
   L
# L
\ ') 5S 5, -/ b: bH+$v, +B"+H+._4 _F _B *, ;V ;. 8<$]ajl XJ XJC XJWZ XJquvzq{ XJt2
 2
4 2
h <@d[] =? =?S =? =?bfglbm =?~^ ^v ^ ^@ @DB mS m mS\ m^ <> &5s &5+ &5P <@ 7 7| 7 
6 
[ 
B >BPTcgpr 1Ms 1M# 1M]` 1Mf
6 
" =? 78 78rF B 68 :3 :3F :3x 6:" =47 =4 =4~ :< 5;S 5; 5;n :>b 64w 64W 64pb4 b b6 bH *, f, f,Pt) t)l FJX\eg ;R3 ;Rs ;RRU ;Rlpqylz ;Rz 8<B [8W [84PX> [8z 8: R23 R2hwt wV wr eg 
S# 
SY 
SV[ 
S XZ 	Tc 	T 	T Y[ 	Us 	U% 	U os{} z,3 z,i z,y z,Z_ z,hk z,x mqy{ B0 B0I B0Y B0X] B0fi B0H FH _1$|*< _1B	3	3S 	3k kv k kZ: : 9=R m/S m/# m/^ 59 I)c I)V AER c*tCy c*# c*J BD &S &P 8<B j/C j/ j/X 04$UYbd U? U?C U?s U?imnsit U?n 59tZ^gi s?c s? s?TW s?nrsxny s?j 7;\`ik : :3 :VY :ptuzp{ :* 9=4^bkm <# <S <X[ <* DHVZimvx }?S }?PS }?cf }?~ ac '
3 '
 '
C '
TW '
gt '
R 154VZce /B# /BS /BPS /Bjno|j} /Bb
t 
x 
= 
0 JL )0S )0PTUcPd )0V =? > >> >4
h 
R` 
4 04$UYbd )I )IC )Is )Iimnyiz )IV 37TX\eg +IC +Is +IRU +Ilpq|l} +IZ[
T [
X [
Q\ [
z:s :& DHPR  ]  ]S  ]D CE Ss SE SI[ S FH S# Su SL^ S CE  @s  @E  @I[  @D
d 
F 
N` 
. 8: 813 81h 81t$
t $
V $
x $
L ?C2 +[3 +[ +[z 37TX\eg CFC CFs CFRU CFJ9 9v BFb Fw F JNVX (,3 (, (, (,]h (,T" 9=4^bkm ^K# ^KS ^KX[ ^K@'V 'R CGr B.3 B.i B.V[ B.H 02 :d8n :x 7;2 
 
8 CGr Zd ZC Z: fjx|  FH F.3 F. F.9 F.I F._b F.ru F.  MR F.P ;= ,4c ,4 ,4\
D 
* 
 ;= @:c @:AT @:D
T 
6 
EX 
"> "*%DW[ /Pb#-t -c 3 S # X\ dg rU  r1   )8 ccxt.async_support.base.exchanger   ccxt.abstract.bingxr   r  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    6 +    ~  ~  ~  ~  ~  ~  ~  ~  * 0 - - . ' & . ) * ) , + 4 %eaHk earU  