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
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" end_time = int(dt.datetime.timestamp(dt.datetime.now())) start_time = int(dt.datetime.timestamp(dt.datetime.now() - dt.timedelta(minutes=lookback))) 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', '15m', 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]
# 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', '15m', 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
The error message "No data found for the given timeframe and symbol" suggests that there is no data available for the specified symbol and timeframe in Binance's API.
You can try the following steps to troubleshoot:
-
Check if the symbol is correct and exists on Binance. You can do this by checking the Binance website or using the Binance API to retrieve a list of available symbols.
-
Check if the timeframe is valid. Binance has specific time intervals available, and the timeframe you specified might not be supported. You can check the available time intervals on Binance's website or API documentation.
-
Check if there is an issue with the API request. You can print the response content and status code to see if there are any errors or issues with the request.
-
Check if there is an issue with the API rate limit. Binance has rate limits for API requests, and if you exceed these limits, your requests may be blocked. You can check the API documentation for more information on the rate limits and how to handle them.
Once you identify the issue, you can make the necessary changes to your code to retrieve the data successfully.
-
- User
But every thing what you told me working so good, I think the issue in code, what do you think >
- Assistant
If the steps I provided didn't help resolve the issue, then it could be an issue with the code. You may want to try debugging the code by adding print statements and checking the values of the variables to see if they match your expectations.
For example, you could print out the
query_paramsvariable to see if it's correctly formatted, print out thedatavariable to see if it's empty or not, and so on.If you're still having trouble, please provide more information on what you're trying to do, what your expected output is, and any error messages you're receiving. That way, I can better understand your issue and try to help you resolve it.
- User
Where is issue in my code ?
- Assistant
Based on the code you provided, the issue could be with the
get_klines()function. This function sends a request to the Binance API to retrieve data for a specific symbol, interval, and time frame.The error message "No data found for the given timeframe and symbol" suggests that the API request is not returning any data. This could be because the specified symbol and/or timeframe is incorrect, or the API response is empty or missing data.
Here are a few things you can try to troubleshoot the issue:
-
Double-check that the symbol and interval are correct and match what's available on Binance. You can find a list of symbols and intervals in the Binance API documentation.
-
Check if the start and end time for the API request are correct. You may want to print out the
start_timeandend_timevariables to make sure they're in the correct format.
-
- User
Terminal returns me them : 1682951258 1685629658 No data found for the given timeframe and symbol 1682951259 1685629659 No data found for the given timeframe and symbol 1682951260 1685629660 No data found for the given timeframe and symbol 1682951261 1685629661 No data found for the given timeframe and symbol 1682951262 1685629662 No data found for the given timeframe and symbol 1682951263 1685629663 No data found for the given timeframe and symbol 1682951264 1685629664 No data found for the given timeframe and symbol 1682951265 1685629665
- Assistant
Based on the output you provided, it seems that the
get_klines()function is sending requests to the Binance API but not getting a response with the data you're looking for.The first step you can take is to check if the symbol and time interval you're using are valid and supported by the Binance API. You can check on the Binance website or API documentation to verify this.
Next, you can try to print out the API response to the console to see if there's any information or error message. You can also try to print out the
start_timeandend_timevariables to check if they are correctly set.It's also possible that there's an issue with your API key or secret. Make sure that you're using the correct keys and that they have the necessary permissions to access the Binance API.
Finally, if none of the above suggestions help resolve the issue, you may want to consider debugging your code step by step to see where the issue might be occurring.
I hope this helps! Let me know if you have any other questions or if there's anything else I can do to assist you.
- User
How I can set time end_time = int(dt.datetime.timestamp(dt.datetime.now())) start_time = int(dt.datetime.timestamp(dt.datetime.now() - dt.timedelta(minutes=lookback))) to .strftime("%m/%d/%Y %H:%M:%S") ?
- Assistant
If you want to convert the start time and end time to a formatted string instead of a Unix timestamp, you can use the
strftime()function to format the timestamps into the desired format.Here's an example of how you can format the start time and end time into the format "%m/%d/%Y %H:%M:%S":
start_time = (dt.datetime.now() - dt.timedelta(minutes=lookback)).strftime("%m/%d/%Y %H:%M:%S") end_time = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S")This will set the
start_timeandend_timevariables to strings in the format "mm/dd/yyyy HH:MM:SS".Keep in mind that some Binance API endpoints may require Unix timestamps instead of formatted strings for the start and end times. In that case, you can use the
timestamp()function to convert the formatted strings back to Unix timestamps if needed.