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 import pandas as pd import requests import json import numpy as np import pytz import datetime as dt
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S") print(date)
url = "https://api.binance.com/api/v1/time" t = time.time()*1000 r = requests.get(url) result = json.loads(r.content)
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 = 'BTCUSDT' quantity = 1 order_type = 'MARKET' leverage = 100 max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
def get_klines(symbol, interval, lookback): url = "https://fapi.binance.com/fapi/v1/klines" params = { "symbol": symbol, "interval": interval, "startTime": int(dt.datetime.timestamp(dt.datetime.now() - dt.timedelta(minutes=lookback))), "endTime": int(dt.datetime.timestamp(dt.datetime.now())) } try: response = requests.get(url, params=params) content = response.content data = response.json() print(f"Response content: {content}") print(f"Response JSON: {data}") 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) if df.empty: print('DataFrame is empty. Check API response.') df.set_index('Open time', inplace=True) return df except Exception as e: print(f'Error in get_klines: {e}') return None df = get_klines('BTCUSDT', '1m', 44640)
def signal_generator(df): open = df.Open.iloc[-1] close = df.Close.iloc[-1] previous_open = df.Open.iloc[-2] previous_close = df.Close.iloc[-2]
code# Bearish pattern if (open>close and previous_open<previous_close and close<previous_open and open>=previous_close): return 'sell' # Bullish pattern elif (open<close and previous_open>previous_close and close>previous_open and open<=previous_close): return 'buy' # No clear pattern else: return ""df = get_klines('BTCUSDT', '1m', 44640) def order_execution(symbol, signal, max_trade_quantity_percentage, leverage): max_trade_quantity = None account_balance = client.futures_account_balance() usdt_balance = float([x['balance'] for x in account_balance if x['asset'] == 'USDT'][0]) max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
- Assistant
Unfortunately, without more information about the specific error you are facing and the context in which you are running this code, it is difficult to provide a definitive solution. However, here are a few potential strategies you could try to troubleshoot the issue:
-
Check the API endpoint and parameters: Make sure that the URL and query parameters you are using to call the Binance API are correct and up-to-date. You can check the Binance API documentation to ensure that you are using the correct endpoints and parameters for the function you are trying to call.
-
Test the API call separately: Try making the API call separately using a tool like Postman or Insomnia to see if you get a successful response. This can help you isolate whether the issue is with your code or with the API itself.
-
Add error handling: Implement exception handling and error logging in your code to help identify the specific issue and provide more verbose error messages. This can help you narrow down the problem and debug more effectively.
-
- User
How my code need to seem ?
- Assistant
Without knowing specifically what the issue is, it's difficult to say exactly what changes need to be made to your code. However, here are a few suggestions that could potentially help:
-
Double-check your API keys: Make sure that your API key and secret key are correct and valid. You can verify this by logging into your Binance account and checking your API settings.
-
Check the API endpoint and parameters: As I mentioned earlier, make sure that you are using the correct API endpoint and parameters when making your calls to the Binance API. The specific endpoint and parameters you need to use will depend on what you are trying to do, so consult the Binance API documentation for details.
-
Implement error handling: Add exception handling to your code so that you can handle specific errors that may be occurring. For example, you can add a try/except block to catch any BinanceAPIException errors and log them or display them in a more user-friendly way.
-
- User
Where is issue in my code ?
- Assistant
Based on the error message you provided ("ERROR: Response content: b'[]' Response JSON: []"), it seems that the response you are getting from the API is an empty JSON array. This could be due to a variety of issues, such as incorrect API keys, incorrect endpoint or query parameters, or a rate-limiting issue.
One potential issue with the code you posted is that you are not adding any headers to your API request. Some API endpoints require certain headers to be present in the request, such as a User-Agent header to identify your client. You can add headers to your request using the
requestslibrary like this:codeheaders = { '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' } response = requests.get(url, headers=headers)Another issue could be that you are using the wrong endpoint or query parameters for the API call you are making. You can try double-checking the Binance API documentation to ensure that you are using the correct endpoint and parameters for your use case.
- User
Give me right code of get_klines based on my code
- Assistant
Sure! Here's an updated version of your
get_klinesfunction that includes headers and handles some potential errors:code - User
Now I used your code, but I getting another ERROR: 06/01/2023 17:16:51 DataFrame is empty. Check API response. Traceback (most recent call last): File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 70, in df = get_klines('BTCUSDT', '15m', 44640) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 65, in get_klines df.set_index('Open time', inplace=True) File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\pandas\core\frame.py", line 5869, in set_index raise KeyError(f"None of {missing} are in the columns") KeyError: "None of ['Open time'] are in the columns", what I need to do ?
- Assistant
The error message you're getting now indicates that the DataFrame is still empty even after checking the API response. Since the DataFrame is empty, trying to set the index to 'Open time' (which does not exist) raises a .