
    i                       d dl Zd dlmZmZmZmZ d dlZd dlm	Z	m
Z
mZmZmZmZmZmZmZmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d d	lmZ d d
lmZ d dlmZ d dlmZ d dlm Z   G d dej!        j"                  Z"dS )    N)
ArrayCacheArrayCacheBySymbolByIdArrayCacheBySymbolBySideArrayCacheByTimestamp)
BalancesIntOrder	OrderBookPositionStrStringsTickerTickersTrade)Client)List)ExchangeError)AuthenticationError)ArgumentsRequired)
BadRequest)NotSupported)RateLimitExceeded)InvalidNonce)Precisec            
           e Zd Z fdZi fdZi fdedefdZdi fdede	fdZ
d	efd
Zd0dZdddi fdedededee         fdZd	efdZd0defdZdi fdededefdZdi fdee         dedefdZd	efdZd Zd Zddi fdedededee         fdZddi fdee         dededee         fdZd	efdZd0dZdddi fdedededee         fdZ d	efdZ!d0dZ"dddi fde#dededee$         fdZ%d0d	efdZ&d0d Z'd! Z(dddi fde#dededee         fd"Z)d	efd#Z*i fde+fd$Z,d	efd%Z-i fd&Z.i fd'Z/i fd(Z0i fd)Z1d	efd*Z2d	efd+Z3d	efd,Z4d- Z5d	efd.Z6d	efd/Z7 xZ8S )1bitgetc                    |                      t          t          |                                           i ddddddddddddd	dd
ddddddddddddddddddddddddddddiiddddddddd d!d"d#d$
d%d&| j        idt
          t          t
          t          t          t          t          t          t          t          t
          t          t
          d'i d(id)          S )*NwsTcreateOrderWsFeditOrderWsfetchOpenOrdersWsfetchOrderWscancelOrderWscancelOrdersWscancelAllOrdersWswatchBalancewatchMyTrades
watchOHLCVwatchOHLCVForSymbolswatchOrderBookwatchOrderBookForSymbolswatchOrderswatchTickerwatchTickers)watchTradeswatchTradesForSymbolswatchPositionsapiz wss://ws.bitget.com/v2/ws/publicz!wss://ws.bitget.com/v2/ws/private)publicprivate  1m5m15m30m1H4H6H12H1D1W)
r6   r7   r8   r9   1h4h6h12h1d1w)tradesLimit
OHLCVLimit
timeframesping)30001300023000330004300053000630007300113001230013300143001530016)exactbroad)hasurlsoptions	streaming
exceptions)deep_extendsuperr   describerI   r   r   r   )self	__class__s    U/var/www/html/crypto-bot/backend/venv/lib/python3.11/site-packages/ccxt/pro/bitget.pyr`   zbitget.describe   s   fd 3 3 < < > >d u $U	
    !% $U    d ' !$ +D t  t!" #$  $)-"&)  . "D#F   $"     	 $ 	 !+!4!+!4!4!2!2!4!4!4!+!4!+   ! gGA
 GA
 G G G	    c                     d }||                      d |          \  }}n,|d         s|d         r|                      ||          \  }}nd}d }|                     |dd|          \  }}|}||gS )NswapfutureSPOTgetInstTypeinstType)handleProductTypeAndParamshandle_option_and_params)ra   marketparamsrj   
instypeAuxs        rc   get_inst_typezbitget.get_inst_typeb   s    >#>>tVLLHffVn 	&"2 	#>>vvNNHffH
!::6=R\^fgg
F&!!rd   symbolreturnc                   K   |                                   d{V  |                     |          }|d         }d|z   }d}|                     ||          \  }}|d|d         d}|                     |||           d{V S )a:  
        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
        :see: https://www.bitget.com/api-doc/spot/websocket/public/Tickers-Channel
        :see: https://www.bitget.com/api-doc/contract/websocket/public/Tickers-Channel
        :param str symbol: unified symbol of the market to watch 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>`
        Nrq   ticker:tickeridrj   channelinstId)load_marketsrm   rp   watch_public)ra   rq   rn   rm   messageHashrj   argss          rc   watch_tickerzbitget.watch_tickero   s       !!!!!!!!!V$$!&(--ff==& Tl
 

 &&{D&AAAAAAAAArd   Nsymbolsc                 f  K   |                                   d{V  |                     |dd          }|                     |d                   }d}|                     ||          \  }}g }g }t	          dt          |                    D ]X}||         }|                     |          }	|d|	d         d}
|                    |
           |                    d|z              Y|                     |||           d{V }| j        ri }|||d         <   |S | 	                    | j
        d|          S )	aK  
        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list
        :see: https://www.bitget.com/api-doc/spot/websocket/public/Tickers-Channel
        :see: https://www.bitget.com/api-doc/contract/websocket/public/Tickers-Channel
        :param str[] symbols: unified symbol of the market to watch the tickers for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        NFr   ru   rv   rw   rt   rq   )rz   market_symbolsrm   rp   rangelenappendwatch_public_multiple
newUpdatesfilter_by_arraytickers)ra   r   rn   rm   rj   topicsmessageHashesirq   marketInnerr}   r   results                rc   watch_tickerszbitget.watch_tickers   sj      !!!!!!!!!%%gtU;;WQZ((--ff==&q#g,,'' 		5 		5AQZF++f--K$#%d+ D
 MM$  V!3444422=&&QQQQQQQQ? 	F(/F78$%M##DL(GDDDrd   clientc                     |                      |          }|d         }|| j        |<   d|z   }|                    ||           d S )Nrq   rt   )parse_ws_tickerr   resolve)ra   r   messageru   rq   r|   s         rc   handle_tickerzbitget.handle_ticker   sQ    > %%g..!%V&(v{+++++rd   c                    |                      |di           }|                      |dg           }|                      |di           }|                     |d          }|                     |d          }|dk    rdnd}|                     |d	          }	|                     |	|d |          }|                     |d
          }
|                     |d          }t	          j        |d          }|                     i d|d         d|d|                     |          d|                     |d          d|                     |d          d|                     |d          d|                     |d          d|                     |d          d|                     |d          dd d|                     |d          d|
d |
d!d d"d d#|d$d |                     |d%          |                     |d&          |d'|          S )(Nargdatar   tsrj   rh   spotcontractry   lastPr	change24h100rq   	timestampdatetimehighhigh24hlowlow24hbidbidPr	bidVolumebidSzaskaskPr	askVolumeaskSzvwapopenopen24hcloselastpreviousClosechange
percentageaverage
baseVolumequoteVolume)r   r   info)
safe_valuesafe_integersafe_stringsafe_marketr   
string_mulsafe_tickeriso8601)ra   r   rm   r   r   ru   r   rj   
marketTypemarketIdr   changeDecimalr   s                rc   r   zbitget.parse_ws_ticker   s   N oogub11w33q"--%%fd33	##C44 (F 2 2VV
##FH55!!(FD*EE  22((==#M599 !
fX&!
!
 Y//!
 D$$VY77	!

 4##FH55!
 4##FG44!
 ))&'::!
 4##FG44!
 ))&'::!
 D!
 D$$VY77!
 U!
 E!
 T!
 d!
  &!!
" t#!
$ **6<@@++FMBB)!
 !
 !
* +  	rd   r6   sincelimitc                   K   |                                   d{V  |                     |          }|d         }|                     | j        d          }|                     ||          }d|z   dz   |z   }	d}
|                     ||          \  }
}|
d|z   |d         d}|                     |	||           d{V }| j        r|                    ||          }| 	                    |||d	d
          S )a  
        watches historical candlestick data containing the open, high, low, close price, and the volume of a market
        :see: https://www.bitget.com/api-doc/spot/websocket/public/Candlesticks-Channel
        :see: https://www.bitget.com/api-doc/contract/websocket/public/Candlesticks-Channel
        :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
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        Nrq   rH   candles::candlerv   rw   r   T)
rz   rm   r   r[   r   rp   r{   r   getLimitfilter_by_since_limit)ra   rq   	timeframer   r   rn   rm   rH   intervalr|   rj   r}   ohlcvs                rc   watch_ohlcvzbitget.watch_ohlcv4  s&      !!!!!!!!!V$$!__T\<@@
##J	:: 9,s2V;--ff==& (*Tl
 

 ''T6BBBBBBBB? 	2NN6511E))%q$GGGrd   c                    |                      |di           }|                     |d          }|dk    rdnd}|                     |d          }|                     |d d |          }|d         }|                      | j        |i           | j        |<   |                     |d          }	|	                    d	d
          }
|                      | j        d          }|                     |
|          }|                      | j        |         |          }|;|                     | j        dd          }t          |          }|| j        |         |<   |                      |dg           }t          dt          |                    D ]3}|                     ||         |          }|                    |           4d|z   dz   |z   }|                    ||           d S )Nr   rj   rh   r   r   ry   rq   rx   r    rH   rG   r5   r   r   r   r   )r   r   r   ohlcvsreplacer[   find_timeframer   r   r   r   parse_ws_ohlcvr   r   )ra   r   r   r   rj   r   r   rm   rq   rx   r   rH   r   storedr   r   r   parsedr|   s                      rc   handle_ohlcvzbitget.handle_ohlcvR  s   D oogub11##C44 (F 2 2VV
##C22!!(D$
CC!"oodk62FFF""3	22??8R00__T\<@@
''*==	V!4i@@>%%dlL$GGE*511F-3DK	*w33q#d))$$ 	" 	"A((a&99FMM&!!!! 9,s2V;v{+++++rd   c           	         |d         rdnd}|                      |d          |                     |d          |                     |d          |                     |d          |                     |d          |                     ||          gS )	Ninverse      r               )r   safe_number)ra   r   rm   volumeIndexs       rc   r   zbitget.parse_ws_ohlcv  s     #9-5aaAeQ''UA&&UA&&UA&&UA&&UK00
 	
rd   c                 B   K   |                      |g||           d{V S )a  
        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :see: https://www.bitget.com/api-doc/spot/websocket/public/Depth-Channel
        :see: https://www.bitget.com/api-doc/contract/websocket/public/Order-Book-Channel
        :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
        N)watch_order_book_for_symbols)ra   rq   r   rn   s       rc   watch_order_bookzbitget.watch_order_book  s4       66xOOOOOOOOOrd   c                 L  K   |                                   d{V  |                     |          }d}d}|dk    s|dk    s|dk    r|t          |          z  }d}g }g }t          dt	          |                    D ]s}||         }	|                     |	          }
d}|                     |
|          \  }}|||
d	         d
}|                    |           |                    d|	z              t|                     |||           d{V }|r|	                                S |S )a  
        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :see: https://www.bitget.com/api-doc/spot/websocket/public/Depth-Channel
        :see: https://www.bitget.com/api-doc/contract/websocket/public/Order-Book-Channel
        :param str[] symbols: unified array of symbols
        :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
        NbooksTr   r      Fr   rv   rw   
orderbook:)
rz   r   strr   r   rm   rp   r   r   r   )ra   r   r   rn   rx   incrementalFeedr   r   r   rq   rm   rj   r}   	orderbooks                 rc   r   z#bitget.watch_order_book_for_symbols  si      !!!!!!!!!%%g..QJJEQJJERKKs5zz!G#Oq#g,,'' 	8 	8AQZF[[((FH#11&&AAHf$" , D
 MM$  !6777744]FFSSSSSSSS	 	??$$$rd   c                 4   |                      |d          }|                     |d          }|                     |d          }|dk    rdnd}|                     |d          }|                     |d d |          }|d         }	d	|	z   }
|                      |d
          }|                      |d          }|                     |d          }|dk    }|rY|	| j        vr$|                     i           }|	|d<   || j        |	<   | j        |	         }|                      |dg           }|                      |dg           }|                     |d         |           |                     |d         |           ||d<   |                     |          |d<   |                     | j	        dd          }|                     |d          dk    }|sb|r_|d         }|d         }t          |          }t          |          }g }t          dd          D ]}||k     rN|                    ||         d         d                    |                    ||         d         d                    ||k     rN|                    ||         d         d                    |                    ||         d         d                    d                    |          }|                     |d          }|                     |d          }||k    r-t          | j        dz             }|                    ||
           nK|                     i           }|                     ||	|          } |                    |            || j        |	<   |                    | j        |	         |
           d S )Nr   rx   rj   rh   r   r   ry   rq   r   r   r   r   r   asksbidsr   r   checksumTactionsnapshot   r   r   r   z invalid checksum)r   r   r   r   
orderbookscounted_order_bookhandle_deltasr   	safe_boolr[   r   r   r   joincrc32r   rv   reject
order_bookparse_order_bookresetr   )!ra   r   r   r   rx   rj   r   r   rm   rq   r|   r   rawOrderBookr   incrementalBookobstoredOrderBookr   r   r   
isSnapshot
storedAsks
storedBids
asksLength
bidsLengthpayloadArrayr   payloadcalculatedChecksumresponseChecksumerrorr   parsedOrderbooks!                                    rc   handle_order_bookzbitget.handle_order_book  s   > oogu--""3	22##C44 (F 2 2VV
##C22!!(D$
CC!"V+w//tQ//%%lD99	!W, '	0do--,,R00%8*,'"of5O??<<<D??<<<Dv6===v6===+4OK(*.,,y*A*AOJ'~~dlJEEH))'8<<
JJ 6( 6,V4
,V4
 __
 __
!q" A AA:~~$++JqM!,<Q,?@@@$++JqM!,<Q,?@@@:~~$++JqM!,<Q,?@@@$++JqM!,<Q,?@@@((<00%)ZZ%>%>"#'#4#4\:#N#N %)999(3F)FGGEMM%555++I"33L&)TTOOOO,,,&/DOF#tv.<<<<<rd   c                     |                      |dd          }|                    |           |                    |           d S )Nr   r   )parse_bid_askr   
storeArray)ra   booksidedeltabidAsks       rc   handle_deltazbitget.handle_delta(  sG    ##E1a00 	eF#####rd   c                 ~    t          dt          |                    D ]}|                     |||                    d S )Nr   )r   r   r  )ra   r  deltasr   s       rc   r   zbitget.handle_deltas/  sH    q#f++&& 	3 	3Ahq	2222	3 	3rd   c                 D   K   |                      |g|||           d{V S )  
        get the list of most recent trades for a particular symbol
        :see: https://www.bitget.com/api-doc/spot/websocket/public/Trades-Channel
        :see: https://www.bitget.com/api-doc/contract/websocket/public/New-Trades-Channel
        :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>`
        N)watch_trades_for_symbols)ra   rq   r   r   rn   s        rc   watch_tradeszbitget.watch_trades3  s6       22F8UE6RRRRRRRRRrd   c                   K   t          |          }|dk    rt          | j        dz             |                                  d{V  |                     |          }g }g }t          dt          |                    D ]s}||         }	|                     |	          }
d}|                     |
|          \  }}|d|
d         d}|                    |           |                    d|	z              t| 	                    |||           d{V }| j
        rB|                     |d          }|                     |d          }|                    ||          }|                     |||d	d
          S )r  r   z> watchTradesForSymbols() requires a non-empty array of symbolsNtraderv   rw   trade:rq   r   T)r   r   rv   rz   r   r   rm   rp   r   r   r   r   r   r   r   )ra   r   r   r   rn   symbolsLengthr   r   r   rq   rm   rj   r}   tradesfirsttradeSymbols                   rc   r  zbitget.watch_trades_for_symbols@  s      GA#DG.n$nooo!!!!!!!!!%%g..q#g,,'' 	4 	4AQZF[[((FH#11&&AAHf$" , D
 MM$  F!2333311-PPPPPPPP? 	8OOFA..E**5(;;KOOK77E))&%TRRRrd   c                    |                      |di           }|                     |d          }|dk    rdnd}|                     |d          }|                     |d d |          }|d         }|                      | j        |          }	|	5|                     | j        dd	          }
t          |
          }	|	| j        |<   |                     |d
g           }t          |          }t          d|          D ]=}||z
  dz
  }||         }| 
                    ||          }|	                    |           >d|z   }|                    |	|           d S )Nr   rj   rh   r   r   ry   rq   rF   r5   r   r   r   r  )r   r   r   r  r   r[   r   	safe_listr   r   parse_ws_trader   r   )ra   r   r   r   rj   r   r   rm   rq   r   r   r   lengthr   indexrawTrader   r|   s                     rc   handle_tradeszbitget.handle_tradese  sb   " oogub11##C44 (F 2 2VV
##C22!!(D$
CC!f55>%%dlM4HHE&&F"(DK~~gvr22Tq&!! 	" 	"AQJNEE{H((6::FMM&!!!!'v{+++++rd   c                    |                      |d          }||                     |d d d          }|                     |g d          }|                      |d          }d }|B|                      |d          }|                     |          }t	          j        |          |d}|                     ||                      |d          |                      |d          ||                     |          |d	         d |                      |d
          d |                     |dd          |                      |d          |                      |d          |d|          S )Nry   r   )uTimecTimer   fillFeefillFeeCoincostcurrencytradeIdorderIdrq   sidepriceAvgpricesizefillNotionalUsd)r   rv   orderr   r   rq   typer1  takerOrMakerr3  amountr-  fee)	r   r   safe_integer_nsafe_currency_coder   
string_abs
safe_trader   safe_string_2)	ra   r  rm   ry   r   feeCostr:  feeCurrencyIdfeeCurrencyCodes	            rc   r"  zbitget.parse_ws_trade  s{   \ !!%22>%%fdD*EEF''/G/G/GHH	""5)44 ,,UMBBM"55mDDO*733+ C ""5)44%%eY77"Y//X&$$UF33 ''z7CC&&uf55$$U,=>> 
  
   	rd   c                   K   |                                   d{V  d}d}d}d}|                     |          }|                     |          s.|                     |          }|                     ||          \  }}|dz   |z   }|ddd}	|                     |||	|           d{V }
| j        r|
S |                     |
|||d          S )	a>  
        watch all open positions
        :see: https://www.bitget.com/api-doc/contract/websocket/private/Positions-Channel
        :param str[]|None symbols: list of unified market symbols
        :param dict params: extra parameters specific to the exchange API endpoint
        :param str [params.instType]: one of 'USDT-FUTURES', 'USDC-FUTURES', 'COIN-FUTURES', 'SUSDT-FUTURES', 'SUSDC-FUTURES' or 'SCOIN-FUTURES', default is 'USDT-FUTURES'
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/en/latest/manual.html#position-structure>`
        Nr   	positionsUSDT-FUTURES
:positionsdefaultrw   T)rz   r   is_emptyget_market_from_symbolsrp   watch_privater   filter_by_symbols_since_limit)ra   r   r   r   rn   rm   r|   subscriptionHashrj   r}   newPositionss              rc   watch_positionszbitget.watch_positions  s      !!!!!!!!!&!%%g..}}W%% 	B11'::F#11&&AAHf-; "
 

 "//=MtU[\\\\\\\\? 	 11,PUW[\\\rd   c                     |                      |di           }|                     |dd          }| j        i | _        || j        vrt                      | j        |<   | j        |         }|                      |dg           }t	          |          }|dk    rd S g }t          dt	          |                    D ]x}	||	         }
|                     |
d          }|                     |d d d          }|                     |
|          }|                    |           |                    |           y| 	                    ||dz             }t          dt	          |                    D ]}	||	         }|
                    d	          }|d
         }|
                    d          }|                     |d|d          }|                     |          s|                    ||           |                    ||dz              d S )Nr   rj   r   r   r   ry   r   z:positions::z::r   ,rq   FrF  )r   r   rD  r   r   r   r   parse_ws_positionr   find_message_hashessplitr   rH  r   )ra   r   r   r   rj   cacherawPositions
dataLengthrM  r   rawPositionr   rm   positionr   r|   partssymbolsStringr   rD  s                       rc   handle_positionszbitget.handle_positions  s   L oogub11##CR88>!DNDN**'?'A'ADN8$x(w;;&&
??Fq#l++,, 	# 	#A&q/K''X>>H%%hdJGGF--k6BBH)))LL""""00N9RSSq#m,,-- 	7 	7A'*K%%d++E!!HM#))#..G,,\8WeTTI==++ 7y+666|X%<=====rd   c                    |                      |d          }|                      |d          }|                     |ddd          }|                      |d          }|dk    rdnd	}|                     |d
d          }|                      |d          }	t          j        |	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&          d'          S )(Nry   
marginModecrossisolated)crossedr_  posMode
hedge_modeTFr(  r)  unrealizedPLRr   contractSizer   rv   posIdrq   r   notionalliquidationPrice
entryPriceopenPriceAvgunrealizedPnlunrealizedPLr   	contractstotal	markPricer1  holdSidehedgedr   r   maintenanceMarginkeepMarginRateleverage
marginRate)maintenanceMarginPercentage
collateralinitialMargininitialMarginPercentagers  marginRatio)
r   get_supported_mappingsafe_integer_2r   r   safe_positionsafe_symbolr   parse_numberr   )ra   rX  rm   r   marginModeIdr]  hedgedIdrp  r   percentageDecimalr   rd  s               rc   rQ  zbitget.parse_ws_position8  s   4 ##Hh77'',??//"?
 ?
  
 ##Hi88"l22'''7CC	 ,,XGG'(95AA
!.1L!! #
H#
$""8W55#
 d&&xzJJ#
 	#

 *#
  0 0;M N N#
 $**8^DD#
 T--hGG#
 $++J77#
 ))(G<<#
 L#
 #
 D$$Xz::#
 f#
 #
  Y//!#
"  ##
$ ,0+;+;HFV+W+W!'+((:>>++HlCC/#
 #
 #
   	rd   c                 ^  K   |                                   d{V  d}d}|                     |dd          }|                     |d          }|rdnd}d}	|-|                     |          }|d         }|d         }|d	z   |z   }d}
|                     d
||          \  }
}|
dk    r|t          | j        dz   |
z   dz             |r#|
dk    rt          | j        dz   |
z   dz             d}|                     ||          \  }}|
dk    r|	d	z   |z   }	|r|	dz   }	|
dk    r|nd}|rdnd}d}| 	                    d
|          \  }}|d}|dk    rd}nd}|||d}| 
                    ||	||           d{V }| j        r|                    ||          }|                     ||||d          S )af  
        watches information on multiple orders made by the user
        :see: https://www.bitget.com/api-doc/spot/websocket/private/Order-Channel
        :see: https://www.bitget.com/api-doc/contract/websocket/private/Order-Channel
        :see: https://www.bitget.com/api-doc/contract/websocket/private/Plan-Order-Channel
        :see: https://www.bitget.com/api-doc/margin/cross/websocket/private/Cross-Orders
        :see: https://www.bitget.com/api-doc/margin/isolated/websocket/private/Isolate-Orders
        :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 boolean [params.stop]: *contract only* set to True for watching trigger orders
        :param str [params.marginMode]: 'isolated' or 'cross' for watching spot margin orders
        :returns dict[]: a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure
        NstopFtriggerOrderr6  order:tradesrq   rv   r   r,   r   z, watchOrders requires a symbol argument for 	 markets.z. watchOrders does not support stop orders for z:stoprG  zorders-algoordersMARGINr_  zorders-isolatedzorders-crossedrw   T)rz   r   omitrm   handle_market_type_and_paramsr   rv   r   rp   handle_margin_mode_and_paramsrJ  r   r   filter_by_symbol_since_limit)ra   rq   r   r   rn   rm   r   isStopr|   rL  r7  rj   ry   rx   r]  r}   r  s                    rc   watch_orderszbitget.watch_ordersz  sU       !!!!!!!!!6666**)/=nng)[[((FH%Fd|H%+f4K99-QWXXfFNN#DG.\$\_c$cfq$qrrr 	pdfnntw)YY\``cnnooo--ff==&6>>/#5> 	:/'9"fnn9#)7--x
!??vVV
F!HZ''+* 
 

 ))+7GvVVVVVVVV? 	3OOFE22E00tTTTrd   c                    |                      |di           }|                     |d          }|                     |d          }d }|dk    rd}n|dk    rd}nd}|                      |dg           }| j        D|                     | j        d	d
          }	t          |	          | _        t          |	          | _        |dk    r| j        n| j        }
|dk    rdnd}i }t          dt          |                    D ]}||         }d|v r| 	                    ||           |                     |d          }| 
                    |d d |          }|                     ||          }|
                    |           |d         }d||<   t          |                                          }t          dt          |                    D ](}||         }|dz   |z   }|                    |
|           )|                    |
|           d S )Nr   rx   rj   rh   r   r  r   r   ordersLimitr5   
ordersAlgor  r6  r   r/  ry   rq   Tr   )r   r   r  r   r[   r   triggerOrdersr   r   handle_my_tradesr   parse_ws_orderr   listkeysr   )ra   r   r   subscriptionr   rx   rj   r   r   r   r   r|   marketSymbolsr   r6  r   rm   r   rq   r  innerMessageHashs                        rc   handle_orderzbitget.handle_order  s0   J oogub11""3	22##C44
vJJ!!JJ#Jw33;%%dlM4HHE077DK!7!>!>D(/<(?(?##dk)0L)@)@nnwq#d))$$ 		) 		)AGEE!!%%fe444''x88H%%hdJGGF((77FMM&!!!H%F$(M&!!M&&(())q#d))$$ 	5 	5A!WF*S069NN6#34444v{+++++rd   c           	         |                      |d          }|                     ||          }|                     |d          }|d         }|                      |d          }|                     |dg           }|                     |d          }|                      |d          }	d }
|	S|                      |d          }|                     t          j        |	                    |                     |          d	}
|                     |d
          }|                      |d          }| 	                    | 
                    |dd                    }|                     |g d          }|                      |d          }|                      |d          }|dk    r%|d         r|dk    r|                      |d|          }| 
                    |dd          }|                      |d          }|d         r|dk    r|dk    s|                      |d|          }|d         r||                      |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*|          S )+Nry   r)  rq   status	feeDetailr   r:  feeCoinr,  triggerPricer3  r2  	fillPrice)rf  notionalUsd	quoteSizer1  	orderTypebuyr   rm   newSizeaccBaseVolumer   rf   r4  r   rv   r0  clientOrderId	clientOidr   r   lastTradeTimestampr(  r7  timeInForceforcepostOnly	stopPricer9  r-  r   )filled	remainingr  r:  r  )r   r   r   r   r~  r   r=  r<  r   	omit_zeror?  safe_string_n
safe_orderr   safe_string_upperparse_ws_order_status)ra   r6  rm   r   r   rq   	rawStatusorderFeer:  	feeAmount	feeObjectfeeCurrencyr  r3  avgPricer-  r1  r7  r  r9  s                       rc   r  zbitget.parse_ws_order^  s   J ##E844!!(F33%%eW55	!$$UH55	??5+r::ooh**$$S%00		 **3	::K))'*<Y*G*GHH 33K@@ I ''~>>  00>>$"4"4UJ"T"TUU!!%)Q)Q)QRRv..{335==VF^=1A1A##E9d;;D##E?LII !!%66f~ 	@demm8H8H%%eY??F&> 	5v~%%eV44F  
E 
f 
 $""5)44 
 T--e[AA	 

  
 Y// 
 !$"3"3E7"C"C 
 D 
 411%AA 
  
 D 
 U 
  
 L 
 f 
  D! 
" x# 
$ 00;;- 
  
  
. /  	rd   c                 @    dddddd}|                      |||          S )Nr   closedcanceled)livepartially_filledr  	cancellednot_trigger)r   )ra   r  statusess      rc   r  zbitget.parse_ws_order_status  s7     &#!
 
 &&999rd   c                   K   |                                   d{V  d}d}|%|                     |          }|d         }|dz   |z   }d}|                     d||          \  }}|dk    rt          | j        dz   |z   dz             d}|                     ||          \  }}d	}	|d
dd}
|                     ||	|
|           d{V }| j        r|                    ||          }| 	                    ||||d          S )a	  
        watches trades made by the user
        :see: https://www.bitget.com/api-doc/contract/websocket/private/Order-Channel
        :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
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        NmyTradesrq   r   r'   r   z$ watchMyTrades is not supported for r  r  r  rG  rw   T)
rz   rm   r  r   rv   rp   rJ  r   r   r  )ra   rq   r   r   rn   rm   r|   r7  rj   rL  r}   r  s               rc   watch_my_tradeszbitget.watch_my_trades  sS      !!!!!!!!! [[((FH%F%+f4K99/6SYZZf6>>tw)OORVVYddeee--ff==&) 
 

 ))+7GvVVVVVVVV? 	3OOFE22E00tTTTrd   c                 L   | j         0|                     | j        dd          }t          |          | _         | j         }|                     |          }|                    |           |d         }d}|                    ||           d|z   }|                    ||           d S )NrF   r5   rq   r  z	myTrades:)r  r   r[   r   r"  r   r   )	ra   r   r   r   r   r   rq   r|   symbolSpecificMessageHashs	            rc   r  zbitget.handle_my_trades*  s    @ = %%dlM4HHE&u--DM$$W--f! v{+++$/&$8!v899999rd   c                 j  K   d}|                      dd|          \  }}d}|                     d|          \  }}d}d}|dk    s|dk    rd}n|d}|dk    rd	}nd
}nd}|                     |dd|          \  }}||dd}d|                                z   }|                     ||||           d{V S )a	  
        watch balance and get the amount of funds available for trading or funds locked in orders
        :see: https://www.bitget.com/api-doc/spot/websocket/private/Account-Channel
        :see: https://www.bitget.com/api-doc/contract/websocket/private/Account-Channel
        :see: https://www.bitget.com/api-doc/margin/cross/websocket/private/Margin-Cross-Account-Assets
        :see: https://www.bitget.com/api-doc/margin/isolated/websocket/private/Margin-isolated-account-assets
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.type]: spot or contract if not provided self.options['defaultType'] is used
        :param str [params.instType]: one of 'SPOT', 'MARGIN', 'USDT-FUTURES', 'USDC-FUTURES', 'COIN-FUTURES', 'SUSDT-FUTURES', 'SUSDC-FUTURES' or 'SCOIN-FUTURES'
        :param str [params.marginMode]: 'isolated' or 'cross' for watching spot margin balances
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        Nr&   accountrf   rg   rE  r  r_  account-isolatedaccount-crossedrh   rj   rG  )rj   rx   coinbalance:)r  r  rl   lowerrJ  )ra   rn   r7  r]  rj   rx   r}   r|   s           rc   watch_balancezbitget.watch_balanceV  s      99.$PVWWf
!??PVWW
FFNN 0 0%HH#HZ'',+H88Q[]eff& 
 

 !8>>#3#33''[$OOOOOOOOOrd   c                 P   |                      |dg           }t          dt          |                    D ]}||         }|                     |dd          }|                     |          }|| j        v r| j        |         n|                                 }|                     |d          }	|	.|                     |d          }
t          j	        |	|
          |d<   d|v rdnd	}|                     ||          |d
<   |                     |d          |d<   |                     |d          |d<   || j        |<   | 
                    | j                  | _        |                      |d          }|                     |d          }d|z   }|                    | j        |           d S )Nr   r   r  
marginCoinborrowinterestdebtmaxTransferOut	availablefreeequityrm  frozenusedr   rj   r  )r   r   r   r?  r<  balancer  r   r   
string_addsafe_balancesafe_string_lowerr   )ra   r   r   r   r   
rawBalance
currencyIdcoder  r  r  	freeQueryr   rj   r|   s                  rc   handle_balancezbitget.handle_balance|  s   v w33q#d))$$ 	) 	)AaJ++JMMJ**:66D-1T\-A-Adl4((G%%j(;;F!++J
CC")"4VX"F"F-=-K-K((R]I"..z9EEGFO#//
HEEGG"..z8DDGFO!(DL((66oogu--))#z:: 8+t|[11111rd   c                    K   | j         d         d         d         }d|gd}|                     ||          }|                     ||||           d {V S Nr2   r   r3   	subscribeopr}   )rZ   extendwatch)ra   r|   r}   rn   urlrequestr   s          rc   r{   zbitget.watch_public  so      it$X.F
 
 ++gv..ZZ[';GGGGGGGGGrd   c                    K   | j         d         d         d         }d|d}|                     ||          }|                     ||||           d {V S r  )rZ   r  watch_multiple)ra   r   	argsArrayrn   r  r  r   s          rc   r   zbitget.watch_public_multiple  so      it$X.
 
 ++gv..((mWmTTTTTTTTTrd   c                 x  K   |                                   | j        d         d         d         }|                     |          }d}|                    |          }|                     |j        |          }|t          |                                           }|dz   dz   }|                     | 	                    |          | 	                    | j
                  t          j        d          }	d}
|
| j        | j        ||	d	gd
}|                     ||          }|                     ||||           | d {V S )Nr2   r   r4   authenticatedGETz/user/verifybase64login)apiKey
passphraser   signr  )check_required_credentialsrZ   r   rg   r   subscriptionsr   secondshmacencodesecrethashlibsha256r  passwordr  r  )ra   rn   r  r   r|   rg   r  r   auth	signature	operationr  r   s                rc   authenticatezbitget.authenticate  s=     '')))it$Y/S!!%{++(<kJJ DLLNN++Iu$~5D		$++d"3"3T[[5M5Mw~_ghhII #'+&*m%. )	 
 
G kk'622GJJsK+>>>||||||rd   c                    K   |                                   d {V  | j        d         d         d         }d|gd}|                     ||          }|                     ||||           d {V S )Nr2   r   r4   r  r  )r  rZ   r  r  )ra   r|   rL  r}   rn   r  r  r   s           rc   rJ  zbitget.watch_private  s      !!!!!!!!!it$Y/F
 
 ++gv..ZZ[';KLLLLLLLLLrd   c                 j    d}|                      |j        |          }|                    d           d S )Nr  T)r   futuresr   )ra   r   r   r|   rg   s        rc   handle_authenticatezbitget.handle_authenticate  s6     &==trd   c                 p   |                      |d          }	 |dk    r|                      |d          }| j        dz   |                     |          z   }|                     | j        d         d         ||           |                      |dd          }|                     | j        d         d	         ||           t          |          d
S # t          $ r_}t          |t                    r*d}|
                    ||           ||j        v r|j        |= n|
                    |           Y d }~dS d }~ww xY w)Neventr	  r   r   rW   msgr   rX   Fr  T)r   rv   jsonthrow_exactly_matched_exceptionr]   throw_broadly_matched_exceptionr   	Exception
isinstancer   r   r  )	ra   r   r   r
  r  feedbackr  er|   s	            rc   handle_error_messagezbitget.handle_error_message  sV      '22	''887S=499W+=+==44T_T5J75SUY[cddd&&wr::44T_T5J75SUXZbccc#H---5 		 		 		!011 !-a---&"666,[9 a   44444		s   B2C 
D5AD00D5c           	      H   |                      ||          rd S |                     |d          }|dk    r|                     ||           d S |dk    r|                     ||           d S |                     |d          }|dk    r|                     ||           d S |dk    r|                     ||           d S | j        | j        | j        | j        | j        | j	        | j        | j        d}| 
                    |di           }| 
                    |dd	          }| 
                    ||          }| |||           |                    d
          dk    r|                     ||           |                    d          dk    r|                     ||           d S d S )Nr   pongr
  r  r  )ru   r  r  r  r  rD  r  r  r   rx   r   r   r   r   )r  r   handle_pongr  handle_subscription_statusr   r&  r  r  r[  r   findr   r  )	ra   r   r   contentr
  methodsr   topicmethods	            rc   handle_messagezbitget.handle_message$  s   F $$VW55 	F""7I66fVW---FfVW---F  '22G$$VW555FK++FG<<<F(''+*. $ 3#2	
 	
 oogub11Y33%00F67###::h1$$fg...::g!##""6733333 $#rd   c                     dS )NrI    )ra   r   s     rc   rI   zbitget.pingk  s    vrd   c                 8    |                                  |_        |S N)millisecondslastPongra   r   r   s      rc   r  zbitget.handle_pongn  s    ++--rd   c                     |S r"  r   r%  s      rc   r  z!bitget.handle_subscription_statusr  s	     rd   r"  )9__name__
__module____qualname__r`   rp   r   r   r~   r   r   r   r   r   r   r   r   r  r   r   r   r
   r   r   r  r  r   r   r  r  r&  r"  r   rN  r[  rQ  r   r	   r  r  r  r  r  r  r   r  r  r{   r   r  rJ  r  r  r  rI   r  r  __classcell__)rb   s   @rc   r   r      s       H H H H HT ,. " " " " 68 B B BF B B B B, 6:" E E7 E E E E EB#,F #, #, #, #,Jg g g gR 8<$]ajl H H HC HWZ Hquvzq{ H H H H<7,6 7, 7, 7, 7,r
 
D 
 
 
 
. @DB 
P 
PS 
P 
PS\ 
P 
P 
P 
P SW_a # #$s) #C #fo # # # #JS= S= S= S= S=j$ $ $3 3 3 <@d[] S S SS S Sbfglbm S S S S OSaenp #S #Sd3i #S #S[^ #Suyz  vA #S #S #S #SJ%,F %, %, %, %,NI I I IV 8<$]ajl ] ]W ]C ]WZ ]quv~q ] ] ] ]:B>v B> B> B> B>H@ @ @ @D 04$UYbd :U :U :UC :Us :Uimnsit :U :U :U :Uxf, f,6 f, f, f, f,P\ \ \ \|: : : 37TX\eg "U "UC "Us "URU "Ulpqvlw "U "U "U "UH*:v *: *: *: *:X *, $P $P $P $P $P $PLN2V N2 N2 N2 N2` <> H H H H LN U U U U )+    6 OQ M M M M&    6    2E4V E4 E4 E4 E4N  &            rd   r   )#ccxt.async_supportccxt ccxt.async_support.base.ws.cacher   r   r   r   r  ccxt.base.typesr   r   r	   r
   r   r   r   r   r   r   !ccxt.async_support.base.ws.clientr   typingr   ccxt.base.errorsr   r   r   r   r   r   r   ccxt.base.preciser   async_supportr   r   rd   rc   <module>r4     s       A  A  A  A  A  A  A  A  A  A  A  A  k k k k k k k k k k k k k k k k k k k k k k k k 4 4 4 4 4 4       * * * * * * 0 0 0 0 0 0 . . . . . . ' ' ' ' ' ' ) ) ) ) ) ) . . . . . . ) ) ) ) ) ) % % % % % %c c c c cT& c c c c crd   