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 = ''
Get the USDT balance and calculate the max trade size based on the leverage
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.")
max_trade_size = float(usdt_balance) * leverage
Get the current time and timestamp
now = dt.datetime.now()
date = now.strftime("%m/%d/%Y %H:%M:%S")
print(date)
As the error suggests: TypeError: Entry.__init__.<locals>.unbound_method() got an unexpected keyword argument 'symbol', it seems that the fapiPrivatePostOrder method does not take the symbol argument. Instead of using the symbol argument, you need to pass the params as a dictionary to the fapiPrivatePostOrder method. You can modify the order_execution function as follows:
Is it need to seem like that ? Code: # Placing new order
api_method = 'fapiPrivatePostOrder'
params = {
'symbol': symbol,
'side': signal.upper(),
'type': order_type,
'quantity': quantity,
'positionSide': position_side,
'leverage': leverage,
'price': price,
'stopPrice': stop_loss_price,
'takeProfit': take_profit_price
}
# Place order
response = getattr(binance_futures, api_method)(params=params)(
symbol=symbol,
side=signal.upper(),
type=order_type,
quantity=quantity,
positionSide=position_side,
leverage=leverage,
price=price,
stopPrice=stop_loss_price,
takeProfit=take_profit_price
)
Assistant
No, you don't need the second set of arguments in the getattr() call. The getattr() method will return a reference to the fapiPrivatePostOrder method, which you can then call with the params parameter like this:
The 400 Client Error: Bad Request error suggests that the request sent to the Binance API is invalid. The BadSymbol: binance {"code":-1121,"msg":"Invalid symbol."} error message indicates that the symbol used in the binance_futures variable does not exist in the Binance API.
Please double-check the symbol variable in your code and make sure that it is correct. If the symbol is correct, try printing the markets variable to see if the symbol is listed in the available markets. You can print the list of available markets with the following code:
print(markets.keys())
Also, please make sure that you have the correct permissions for the API key and secret that you are using. The fapiPrivatePosit endpoint may require additional permissions for specific symbols or positions.
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
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)
def signal_generator(df):
if df is None:
return ""
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(symbol, '1m', 89280)
def order_execution(symbol, signal, step_size, leverage, order_type):
# Set default value for response
response = {}
# Close any existing positions
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position["symbol"] == symbol:
current_position = position
if current_position is not None and current_position["positionAmt"] != 0:
response = binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side='SELL' if current_position['positionSide'] == 'LONG' else 'BUY',
type='MARKET',
quantity=abs(float(current_position['positionAmt'])),
positionSide=current_position['positionSide'],
reduceOnly=True
)
if 'orderId' in response:
print(f'Closed position: {response}')
else:
print(f'Error closing position: {response}')
time.sleep(1)
# Calculate appropriate order quantity and price based on signal
opposite_position = None
quantity = step_size
position_side = None #initialise to None
price = None
# Set default take profit price
take_profit_price = None
stop_loss_price = None
if signal == 'buy':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'SHORT' else None
order_type = 'TAKE_PROFIT_MARKET'
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'ask' in ticker:
price = ticker['ask']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None
order_type = 'STOP_MARKET'
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'bid' in ticker:
price = ticker['bid']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
# Set stop loss price
stop_loss_price = None
if price is not None:
price = round_step_size(price, step_size=step_size)
if signal == 'buy':
# Calculate take profit and stop loss prices for a buy signal
take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
elif signal == 'sell':
# Calculate take profit and stop loss prices for a sell signal
take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
# Adjust quantity if opposite position exists
if opposite_position is not None:
quantity = round_step_size(abs(float(opposite_position['positionAmt'])), step_size=step_size)
# Place order
response = binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side=signal.upper(),
type=order_type,
quantity=quantity,
positionSide=position_side,
leverage=leverage,
price=price,
stopPrice=stop_loss_price,
takeProfit=take_profit_price
)
if 'orderId' in response:
print(f'Order placed: {response}')
else:
print(f'Error placing order: {response}')
time.sleep(1)
return response
signal = signal_generator(df)
while True:
df = get_klines(symbol, '1m', 89280) # await the coroutine function here
if df is not None:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, signal:{signal}")
if signal:
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
time.sleep(0.1)
but I getting ERROR in line 249 tell me what I need to change only in this line , ERROR: The signal time is: 2023-06-09 12:54:02, signal:buy
Error closing position: {}
Traceback (most recent call last):
File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 275, in
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 249, in order_execution
response = binance_futures.fapiPrivatePostOrder(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Entry.init..unbound_method() got an unexpected keyword argument 'symbol'
I used your code, but I getting ERROR: The signal time is: 2023-06-09 13:17:01, signal:buy
Error closing position: {}
Traceback (most recent call last):
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 560, in fetch
response.raise_for_status()
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\requests\models.py", line 1021, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://fapi.binance.com/fapi/v1/order
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 277, in
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 262, in order_execution
response = getattr(binance_futures, api_method)(params=params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\types.py", line 25, in unbound_method
return _self.request(self.path, self.api, self.method, params, config=self.config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 7409, in request
response = self.fetch2(path, api, method, params, headers, body, config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 2819, in fetch2
return self.fetch(request['url'], request['method'], request['headers'], request['body'])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 576, in fetch
skip_further_error_handling = self.handle_errors(http_status_code, http_status_text, url, method, headers, http_response, json_response, request_headers, request_body)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 7386, in handle_errors
self.throw_exactly_matched_exception(self.exceptions['exact'], error, feedback)
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 3169, in throw_exactly_matched_exception
raise exactstring
ccxt.base.errors.BadSymbol: binance {"code":-1121,"msg":"Invalid symbol."}