def get_ticker_price(ticker, coin=False): if ticker and not coin: url = f"https://query1.finance.yahoo.com/v8/finance/chart/{ticker}?region=US&lang=en-US&includePrePost=false&interval=1m&useYfid=true&range=1d&corsDomain=finance.yahoo.com&.tsrc=finance" headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36' } res = requests.get(url, headers=headers) data = json.loads(res.text) try: return float( data["chart"]["result"][0]["meta"]["regularMarketPrice"]) except TypeError: return False elif ticker and coin: b_api_key = "8AiGAyxlhYQaRpE1s7097hx5sZ12Ogtr8ir9DsyztaD5j24LrI0fEoToDzCI5lle" b_api_secret = "VhudTs0HsBVFNdSTghmqfCjUuIXF6rFiXIfROxHIaM71TGgib7NeZ5aOsJUHjI9f" client = Client(b_api_key, b_api_secret) res = client.get_all_tickers() if isinstance(ticker, str): for c_ticker in res: if ticker == c_ticker["symbol"]: return c_ticker["price"] return False elif isinstance(ticker, list): tickers_prices = {} for c_ticker in res: if c_ticker["symbol"] in ticker: tickers_prices[c_ticker["symbol"]] = c_ticker["price"] return tickers_prices
class Binance: def __init__(self): api_key = '0Lqjlvte26MGjAYXJa8UWggtQrqjyhWklxvWdJD72oSIfVcKr4AWeVq7OOm415uw' api_secret = 'ItyCJ0Re2bjNiHWfHHEb6d01OSZTFxitKoWVmkTwMPFmX3bVAl8F5GtQsoGM6vEx' self.client = Client(api_key, api_secret) def balances(self): balances = self.client.get_account() for balance in balances['balances']: if float(balance['locked']) > 0 or float(balance['free']) > 0: print('%s: %s' % (balance['asset'], balance['free'])) def balance(self, asset='BTC'): balances = self.client.get_account() balances['balances'] = {item['asset']: item for item in balances['balances']} print(balances['balances'][asset]['free']) def orders(self, symbol, limit): orders = self.client.get_open_orders(symbol, limit) print(orders) def tickers(self): return self.client.get_all_tickers() def server_status(self): systemT=int(time.time()*1000) #timestamp when requested was launch serverT= self.client.get_server_time() #timestamp when server replied lag=int(serverT['serverTime']-systemT) print('System timestamp: %d' % systemT) print('Server timestamp: %d' % serverT['serverTime']) print('Lag: %d' % lag) if lag>1000: print('\nNot good. Excessive lag (lag > 1000ms)') elif lag<0: print('\nNot good. System time ahead server time (lag < 0ms)') else: print('\nGood (0ms > lag > 1000ms)') return def openorders(self): return self.client.get_open_orders() def profits(self, asset='BTC'): coins = self.client.get_products() for coin in coins['data']: if coin['quoteAsset'] == asset: orders = self.client.get_order_books(coin['symbol'], 5) if len(orders['bids'])>0 and len(orders['asks'])>0: lastBid = float(orders['bids'][0][0]) #last buy price (bid) lastAsk = float(orders['asks'][0][0]) #last sell price (ask) if lastBid!=0: profit = (lastAsk - lastBid) / lastBid * 100 else: profit = 0 print('%6.2f%% profit : %s (bid: %.8f / ask: %.8f)' % (profit, coin['symbol'], lastBid, lastAsk)) else: print('---.--%% profit : %s (No bid/ask info retrieved)' % (coin['symbol'])) def market_value(self, symbol, kline_size, dateS, dateF="" ): dateS=datetime.strptime(dateS, "%d/%m/%Y %H:%M:%S") if dateF!="": dateF=datetime.strptime(dateF, "%d/%m/%Y %H:%M:%S") else: dateF=dateS + timedelta(seconds=59) print('Retrieving values...\n') klines = self.client.get_klines(symbol, kline_size, int(dateS.timestamp()*1000), int(dateF.timestamp()*1000)) if len(klines)>0: for kline in klines: print('[%s] Open: %s High: %s Low: %s Close: %s' % (datetime.fromtimestamp(kline[0]/1000), kline[1], kline[2], kline[3], kline[4])) return