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" 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())) } response = requests.get(url, params=params) data = response.json() ohlc = [] for d in data: timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S') ohlc.append([ timestamp, float(d[1]), float(d[2]), float(d[3]), float(d[4]), float(d[5]) ]) df = pd.DataFrame(ohlc, columns=['Open time', 'Open', 'High', 'Low', 'Close', 'Volume']) df.set_index('Open time', inplace=True) return df df = get_klines('BTCUSDT', '15m', 1440)
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', 1440) 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
# Close long position if signal is opposite long_position = None short_position = None positions = client.futures_position_information(symbol=symbol) for p in positions: if p['positionSide'] == 'LONG': long_position = p elif p['positionSide'] == 'SHORT': short_position = p if long_position is not None and short_position is not None: print("Multiple positions found. Closing both positions.") if long_position is not None: client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=long_position['positionAmt'], reduceOnly=True ) time.sleep(1) if short_position is not None: client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=short_position['positionAmt'], reduceOnly=True ) time.sleep(1) print("Both positions closed.") if signal == 'buy': position_side = POSITION_SIDE_LONG opposite_position = short_position elif signal == 'sell': position_side = POSITION_SIDE_SHORT opposite_position = long_position else: print("Invalid signal. No order placed.") return order_quantity = 0 if opposite_position is not None: order_quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt']))) if opposite_position is not None and opposite_position['positionSide'] != position_side: print("Opposite position found. Closing position before placing order.") client.futures_create_order( symbol=symbol, side=SIDE_SELL if opposite_position['positionSide'] == POSITION_SIDE_LONG else SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=True, positionSide=opposite_position['positionSide'] ) time.sleep(1) order = client.futures_create_order( symbol=symbol, side=SIDE_BUY if signal == 'buy' else SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=False, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side, # add position side parameter leverage=leverage ) if order is None: print("Order not placed successfully. Skipping setting stop loss and take profit orders.") return order_id = order['orderId'] print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}") time.sleep(1) # Set stop loss and take profit orders # Get the order details to determine the order price order_info = client.futures_get_order(symbol=symbol, orderId=order_id) if order_info is None: print("Error getting order information. Skipping setting stop loss and take profit orders.") return order_price = float(order_info['avgPrice']) # Set stop loss and take profit orders stop_loss_price = order_price * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == 'sell' else order_price * (1 - STOP_LOSS_PERCENTAGE / 100) take_profit_price = order_price * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == 'buy' else order_price * (1 - TAKE_PROFIT_PERCENTAGE / 100) stop_loss_order = client.futures_create_order( symbol=symbol, side=SIDE_SELL if signal == 'buy' else SIDE_BUY, type=ORDER_TYPE_STOP_LOSS, quantity=order_quantity, stopPrice=stop_loss_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side # add position side parameter ) take_profit_order = client.futures_create_order( symbol=symbol, side=SIDE_SELL if signal == 'buy' else SIDE_BUY, type=ORDER_TYPE_LIMIT, quantity=order_quantity, price=take_profit_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side # add position side parameter ) # Print order creation confirmation messages print(f"Placed stop loss order with stop loss price {stop_loss_price}") print(f"Placed take profit order with take profit price {take_profit_price}") time.sleep(1) - Assistant
The error is occurring because the
Opencolumn does not exist in the DataFramedf.To fix this, you can modify the
get_klinesfunction to extract the correct columns from the API response and rename them to match the DataFrame column names used in thesignal_generatorfunction.Here's the modified
get_klinesfunction: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())) } response = requests.get(url, params=params) data = response.json() 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 - User
Now I getting new ERROR: 06/01/2023 15:17:27 Traceback (most recent call last): File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 63, in df = get_klines('BTCUSDT', '15m', 44640) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 61, 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
This error occurs because the
get_klinesfunction is not returning any data.To fix this, you can add some error handling to the function to print out any errors that occur during the API request process. For example, you can modify the function like this:
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) data = response.json() 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 - User
Now I getting another ERROR: Error in get_klines: cannot access local variable 'df' where it is not associated with a value, what I need to do ?
- Assistant
The "cannot access local variable 'df'" error occurs when the DataFrame
dfis not created due to an error occurring in theget_klinesfunction.To fix this error, you need to first identify what is causing the error in your
get_klinesfunction. You can add some debugging statements to the function to print out the response content and response JSON so you can see what information is being returned from the API: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 - User
Now I getting them: Response content: b'[]' Response JSON: []
- Assistant
The response content and JSON both indicate that the API is returning an empty response. This could be due to several reasons, such as:
- The API key is invalid or not authorized to access the data.
- The parameters passed to the API are incorrect or not accepted by the endpoint.
- The endpoint is currently down or experiencing issues.
- There is an issue with the network connection or web request.
To troubleshoot this issue, you can start by checking the API key to ensure that it is properly configured and authorized to access the data. If the API key is valid, you can try adjusting the parameters passed to the API to see if that resolves the issue. You could also try checking the status of the endpoint by visiting the Binance API documentation page.
If none of these steps work, you can try contacting Binance support for assistance or reporting the issue through their developer documentation website.
- User
I changed API , but I getting same ERROR : Response content: b'[]' Response JSON: []
- Assistant
If you are still receiving an empty JSON response from the Binance API, it is possible that the request parameters you are using are incorrect for that endpoint.
You can try the following steps to troubleshoot this issue:
-
Check that the symbol you are using is valid and active on the futures market.
-
Check that the interval you are using is valid for futures markets.
-
Double check your startTime and endTime parameters to ensure that they are correctly formatted.
-
Try to make the API call directly via a web browser or other tool (such as Postman) to see what the API is returning.
-
If the API is still returning an empty response, reach out to the Binance support team to see if there are any known issues with that endpoint.
It's also possible that the issue is with your code, and not directly related to the API. You can try printing out the request URL and query parameters to ensure they match what you expect and do not contain any typos or other issues.
If you continue to have issues, please let me know the exact API endpoint you are calling and what parameters you are using, and I can try to provide more specific guidance.
-