I used your code: import time from binance.client import Client from binance.enums…
- User
I used your code: import time from binance.client import Client from binance.enums import * from binance.exceptions import BinanceAPIException import pandas as pd import requests import json import numpy as np import pytz import datetime as dt import ccxt
Get the current time and timestamp
now = dt.datetime.now() date = now.strftime("%m/%d/%Y %H:%M:%S") print(date) timestamp = int(time.time() * 1000)
Get the server time from Binance’s API and calculate the time difference
url = f"https://api.binance.com/api/v1/time?timestamp={timestamp}" r = requests.get(url) result = json.loads(r.content) server_time = result['serverTime'] time_difference = server_time - int(timestamp/1000)*1000 - now.microsecond/1000
API keys and other configuration
API_KEY = '' API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = 'SELL' POSITION_SIDE_LONG = 'BUY' symbol = 'BTC/USDT' quantity = 1 order_type = 'MARKET' leverage = 100 max_trade_quantity_percentage = 1 binance_futures = ccxt.binance({ 'apiKey': '', 'secret': '', 'enableRateLimit': True, # enable rate limitation 'options': { 'defaultType': 'future', 'adjustForTimeDifference': True } })
Get server time and time difference
server_time = binance_futures.public_get_time() server_timestamp = server_time['serverTime'] print(f'Timestamp:{server_time}')
server_time = binance_futures.public_get_time() server_timestamp = int(server_time['serverTime']) - 1000 print(f'Timestamp:{server_timestamp}')
try: timestamp = int(time.time() * 1000) - (server_timestamp * 1000 - result['serverTime']) - 500 print(f'Timestamp: {timestamp}') except KeyError: print(f"Error accessing 'serverTime' in API response. Response: {result}") timestamp = int(time.time() * 1000)
codetime_difference = int(time.time() * 1000) - server_timestamp * 1000 - 500Get current time adjusted for time difference
current_time = int(time.time() * 1000) - time_difference
Use adjusted timestamp in subsequent requests
balances = binance_futures.fetch_balance({'timestamp': timestamp}) print(balances)
def get_klines(symbol, interval, lookback): url = "https://fapi.binance.com/fapi/v1/klines" start_time = (dt.datetime.now() - dt.timedelta(minutes=lookback)) end_time = dt.datetime.now() query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}" headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' } try: response = requests.get(url + query_params, headers=headers) response.raise_for_status() data = response.json() if not data: # if data is empty, return None print('No data found for the given timeframe and symbol') return None ohlc = [] for d in data: timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S') ohlc.append({ 'Open time': timestamp, 'Open': float(d[1]), 'High': float(d[2]), 'Low': float(d[3]), 'Close': float(d[4]), 'Volume': float(d[5]) }) df = pd.DataFrame(ohlc) df.set_index('Open time', inplace=True) return df except requests.exceptions.RequestException as e: print(f'Error in get_klines: {e}') return None df = get_klines('BTCUSDT', '1m', 44640)
- Assistant
The error you're getting indicates that the
serverTimekey is not present in the dictionary returned by the Binance API call. This could be due to a few different reasons, such as a network issue or an incorrect API endpoint.To troubleshoot, you can try printing out the entire contents of the
resultdictionary to see if there are any other unexpected keys or values. You can also check the API documentation to ensure that you're using the correct endpoint and parameters for your particular use case. - User
What I need to change ?
- Assistant
Here are a few things you can try to troubleshoot the
KeyErrorissue:- Make sure you're using the correct API endpoint and parameters. Double-check the API documentation to ensure that you're using the appropriate endpoint for the Binance API that you need.
- Check your network connection to ensure that you can successfully make a request to the Binance API. You can try printing out the contents of the
r.contentvariable to see if there are any errors or unexpected outputs. - Check the
resultdictionary returned by the API call to see if there are any unexpected keys or values. You can print out the entire contents of theresultdictionary to see if anything looks unusual. - If none of the above solutions work, you can try using a different Python wrapper library for the Binance API, such as
binance-sdkorpython-binance. These libraries may have different methods for accessing the API that could help you debug the issue.
- User
How it need to seem ?
- Assistant