I used this code: import time from binance.client import Client from binance.enums…
- User
I used this code: import time from binance.client import Client from binance.enums import * from binance.exceptions import BinanceAPIException from binance.helpers import round_step_size import pandas as pd import json import numpy as np import pytz import datetime as dt import ccxt from decimal import Decimal import requests import hmac import hashlib API_KEY = ‘’ API_SECRET = ‘’
client = Client(API_KEY, API_SECRET)
Set the endpoint and parameters for the request
url = “https://fapi.binance.com/fapi/v2/account” timestamp = int(time.time() * 1000) recv_window = 5000
params = { “timestamp”: timestamp, “recvWindow”: recv_window }
Sign the message using the Client’s secret key
message = ‘&’.join([f"{k}={v}" for k, v in params.items()]) signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest() params[‘signature’] = signature leverage = 100
Send the request using the requests library
response = requests.get(url, params=params, headers={‘X-MBX-APIKEY’: API_KEY}) account_info = response.json()
Get the USDT balance and calculate the max trade size based on the leverage
usdt_balance = next((item for item in account_info[‘assets’] if item[“asset”] == “USDT”), {“balance”: 0}) max_trade_size = float(usdt_balance.get(“balance”, 0)) * leverage
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)
STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = ‘SELL’ POSITION_SIDE_LONG = ‘BUY’ quantity = 1 symbol = ‘BTC/USDT’ order_type = ‘market’ leverage = 100 max_trade_quantity_percentage = 1 binance_futures = ccxt.binance({ ‘apiKey’: API_KEY, ‘secret’: API_SECRET, ‘enableRateLimit’: True, # enable rate limitation ‘options’: { ‘defaultType’: ‘future’, ‘adjustForTimeDifference’: True },‘future’: { ‘sideEffectType’: ‘MARGIN_BUY’, # MARGIN_BUY, AUTO_REPAY, etc… } })
Load the market symbols
try: markets = binance_futures.load_markets() except ccxt.BaseError as e: print(f’Error fetching markets: {e}‘) markets = []
if symbol in markets: print(f"{symbol} found in the market") else: print(f"{symbol} not found in the market")
Get server time and time difference
def get_server_time(exchange): server_time = exchange.fetch_currencies() return server_time[‘timestamp’]
def get_time_difference(): server_time = get_server_time(binance_futures) local_time = int(time.time() * 1000) time_difference = local_time - server_time return time_difference time.sleep(1)
def get_klines(symbol, interval, lookback): url = “ end_time = int(time.time() * 1000) # end time is now start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago symbol = symbol.replace(“/”, “”) # remove slash from symbol 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(symbol, ‘1m’, 89280)
- Assistant
It seems that the API response does not contain the expected key "assets". You can try printing the response and checking its structure to see which key holds the information you need. Alternatively, you can try using a try-except block to handle the KeyError and provide a default value in case the key is not found. For example:
try: usdt_balance = next((item for item in account_info['balances'] if item["asset"] == "USDT"), {"free": 0})['free'] except KeyError: usdt_balance = 0 print("Error: Could not retrieve USDT balance from API response.")
This will try to get the USDT balance from the "balances" key instead of "assets", and if the KeyError is raised, it will set the balance to 0 and print an error message.
- User
I used your code, btu I getting ERROR: Error: Could not retrieve USDT balance from API response. Traceback (most recent call last): File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 43, in usdt_balance = next((item for item in account_info['balances'] if item["asset"] == "USDT"), {"free": 0})['free'] ~~~~~~~~~~~~^^^^^^^^^^^^ KeyError: 'balances'
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 47, in max_trade_size = float(usdt_balance.get("balance", 0)) * leverage ^^^^^^^^^^^^^^^^ AttributeError: 'int' object has no attribute 'get'
- Assistant
It looks like the API response structure has changed, and now uses the "accountBalance" key instead of "balances". To fix the KeyError, you can try changing the key to "accountBalance" in the code that retrieves the USDT balance:
try: usdt_balance = next((item for item in account_info['accountBalance'] if item["asset"] == "USDT"), {"free": 0})['free'] except KeyError: usdt_balance = 0 print("Error: Could not retrieve USDT balance from API response.")
For the AttributeError, it seems that the "usdt_balance" variable is now an integer instead of a dictionary as previously expected. You can replace the "usdt_balance.get()" line with simply "usdt_balance * leverage" to calculate the max trade size:
max_trade_size = float(usdt_balance) * leverage
- User
I used your code, but I getting ERROR: Error fetching markets: binance {"code":-1021,"msg":"Timestamp for this request was 1000ms ahead of the server's time."} BTC/USDT not found in the market
- Assistant
The error message suggests that there is a time difference between your local system clock and the Binance server clock. You can try to resolve this issue by adjusting the time on your local system to match the Binance server time.
You can also try adding a time difference correction to the code to adjust the timestamps to the Binance server time. Here is an example on how to adjust the timestamps in the code:
- First, define the Binance server time:
pythonserver_time = int(binance_futures.fetch_time()['timestamp'])- Then, define the time difference between your local system and the Binance server time:
pythonlocal_time = int(time.time() * 1000) time_difference = local_time - server_time - User
Is it need to seem like that code? Code: try: markets = binance_futures.load_markets() except ccxt.BaseError as e: print(f'Error fetching markets: {e}') markets = []
if symbol in markets: print(f"{symbol} found in the market") else: print(f"{symbol} not found in the market")
Get server time and time difference
def get_server_time(exchange): server_time = int(binance_futures.fetch_time()['timestamp']) return server_time['timestamp']
def get_time_difference(): server_time = get_server_time(binance_futures) local_time = int(time.time() * 1000) time_difference = local_time - server_time return time_difference time.sleep(1)
- Assistant
There is an issue with the
get_server_time()function definition, which should return the integer value of the Binance server time instead of a dictionary. You can modify the function as follows:pythondef get_server_time(exchange): server_time = int(exchange.fetch_time()['timestamp']) return server_timeOther than that, the code snippet you provided looks correct. It attempts to load the market symbols using the
load_markets()method and checks if the desired symbol is available in the list ofmarkets. It also defines two timestamp-handling functions (get_server_time()andget_time_difference()) that can be used to adjust the timestamps in the code to match the Binance server time, as described in the previous response. Finally, it adds atime.sleep(1)statement to prevent rate limiting issues when making repeated API requests.