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
Assistant
The error occurs because the fetch_time() method from the ccxt library returns an integer value, which is not subscriptable. To fix the issue, you can modify the get_server_time() function to just return the integer value and remove the subscripting operation in the get_time_difference() function:
This should properly calculate the time difference and prevent the subscripting error.
User
But I getting ERROR: & "C:/Program Files/Python311/python.exe" c:/Users/Alan/.vscode/jew_bot/jew_bot/jew_bot.py
Traceback (most recent call last):
File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 59, in
timestamp = int(time.time() * 1000) - get_time_difference()
^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 52, in get_time_difference
server_time = get_server_time(binance_futures)['timestamp']
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^
TypeError: 'int' object is not subscriptable
Assistant
The error suggests that you are still trying to subscript an integer object, which is not allowed in Python. To solve this, you should modify the get_server_time function to just return the integer value without wrapping it in a dictionary:
Now, server_time is just the integer value returned by fetch_time(), so you don't need to subscript it. This should fix the error you were seeing.
User
But I still getting same ERROR: Error fetching markets: binance {"code":-1021,"msg":"Timestamp for this request was 1000ms ahead of the server's time."}
Assistant
The error message indicates that the timestamp in your API request is ahead of the server's time by 1000ms. This can happen if your computer's clock is not synced with the server's clock.
To fix this, you can use the ntp module to synchronize your computer's clock with an NTP server:
import ntplib
def sync_time():
ntp_client = ntplib.NTPClient()
response = ntp_client.request('pool.ntp.org', version=3)
now = time.time()
offset = response.offset
new_time = now + offset
# Set the system clock to the new time
os.system(f'sudo date -s @{int(new_time)}')
print(f'New time: {dt.datetime.now()}')
Call the sync_time() function once at the start of the script to synchronize the clock. This should ensure that your computer's clock is accurate and in sync with the server's clock.
Another solution is to try increasing the recv_window parameter in your API requests. This can give the server more time to process your request and reduce the likelihood of a timestamp error. For example, you can try setting recv_window to 10000 (10 seconds):
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
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, '15m', 66240)
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, '15m', 66240)
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)
# 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
}
response = getattr(binance_futures, api_method)(params=params)
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, '15m', 66240) # 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}")
time.sleep(0.1)
But I getting ERROR: File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 61, in
timestamp = int(time.time() * 1000) - get_time_difference()
^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 54, in get_time_difference
server_time = get_server_time(binance_futures)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 49, in get_server_time
server_time = int(exchange.fetch_time()['timestamp'])
~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^
TypeError: 'int' object is not subscriptable