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 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 import ntplib import os import ta API_KEY = '' API_SECRET = ''
client = Client(API_KEY, API_SECRET)
Set the endpoint and parameters for the request
url = "https://fapi.binance.com/fapi/v2/account" recv_window = 10000 # update the recv_window value
params = { "timestamp": int(time.time() * 1000), "recvWindow": recv_window }
Get the Binance server time and calculate the time difference
async def get_server_time(): client = await Client.create("","") server_time = client.time()['serverTime'] local_time = int(time.time() * 1000) time_difference = server_time - local_time return time_difference time_difference = get_server_time()
Adjust the timestamp to synchronize with the Binance server time
params = { "timestamp": int(time.time() * 1000) + time_difference, "recvWindow": recv_window }
Sign the message using the Client’s secret key
message = "&".join([f"{k}={v}" for k, v in params.items()]) signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest() params['signature'] = signature leverage = 100
Send the request using the requests library
response = requests.get(url, params=params, headers={'X-MBX-APIKEY': API_KEY}) account_info = response.json()
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)
STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = 'SELL' POSITION_SIDE_LONG = 'BUY' quantity = 1 symbol = 'BTC/USDT' order_type = 'market' leverage = 100 max_trade_quantity_percentage = 1 binance_futures = ccxt.binance({ 'apiKey': API_KEY, 'secret': API_SECRET, 'enableRateLimit': True, # enable rate limitation 'options': { 'defaultType': 'future', 'adjustForTimeDifference': True }, 'future': { 'sideEffectType': 'MARGIN_BUY', # MARGIN_BUY, AUTO_REPAY, etc… } })
Load the market symbols
params = { "timestamp": int(time.time() * 1000) + time_difference, "recvWindow": recv_window } try: markets = binance_futures.load_markets() except ccxt.BaseError as e: print(f'Error fetching markets: {e}') markets = []
if symbol in markets: print(f"{symbol} found in the market") else: print(f"{symbol} not found in the market")
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' } 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 df = get_klines(symbol, '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] # Calculate EMA indicators ema_10 = ta.trend.EMAIndicator(df['Close'], window=10) ema_50 = ta.trend.EMAIndicator(df['Close'], window=50) ema_100 = ta.trend.EMAIndicator(df['Close'], window=100) ema_200 = ta.trend.EMAIndicator(df['Close'], window=200)
# Calculate MA indicator ma = ta.trend.SMAIndicator(df['Close'], window=20) # Calculate EMA indicator values ema_10_value = ema_10.ema_indicator()[-1] #get the EMA 10 indicator value for the last value in the DataFrame ema_50_value = ema_50.ema_indicator()[-1] #get the EMA 50 indicator value for the last value in the DataFrame ema_100_value = ema_100.ema_indicator()[-1] #get the EMA 100 indicator value for the last value in the DataFrame ema_200_value = ema_200.ema_indicator()[-1] #get the EMA 200 indicator value for the last value in the DataFrame ma_value = ma.sma_indicator()[-1] #get the MA indicator value for the last value in the DataFrame #Bearish pattern with EMA and MA indicators if (open>close and previous_open<previous_close and close<previous_open and open>=previous_close and close<ema_10_value and close<ema_50_value and close<ema_100_value and close<ema_200_value and close<ma_value): return 'sell' #Bullish pattern with EMA and MA indicators elif (open<close and previous_open>previous_close and close>previous_open and open<=previous_close and close>ema_10_value and close>ema_50_value and close>ema_100_value and close>ema_200_value and close>ma_value): return 'buy' #No clear pattern with EMA and MA indicators else: return ''df = get_klines(symbol, '1m', 44640)
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) # 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 responsesignal = signal_generator(df) while True: df = get_klines(symbol, '1m', 44640) # 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(1) But I getting ERROR: File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 44, in "timestamp": int(time.time() * 1000) + time_difference, ~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~ TypeError: unsupported operand type(s) for +: 'int' and 'coroutine' sys:1: RuntimeWarning: coroutine 'get_server_time' was never awaited
- Assistant
The error is occurring because
get_server_time()returns a coroutine, but the result is not being awaited before adding it to an integer value. To fix the issue, you need to add anawaitkeyword before callingget_server_time()on line 44:time_difference = await get_server_time()This will ensure that the result of the coroutine is awaited and ready to be added to the integer value.
- User
But it will be ERROR
- Assistant
You are right. It seems that
awaitcannot be used outside of async functions, and you are trying to call it in the global scope. Instead, you can defineget_server_time()as a normal function (withoutasyncandawait), since you are not using anyasyncfunctionality inside it. Here's an updated code snippet that should work: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 import ntplib import os import ta API_KEY = '' API_SECRET = '' client = Client(API_KEY, API_SECRET) # Set the endpoint and parameters for the request url = "https://fapi.binance.com/fapi/v2/account" recv_window = 10000 # update the recv_window value params = { "timestamp": int(time.time() * 1000), "recvWindow": recv_window } # Define a function to get the server time and calculate the time difference def get_server_time(): # Create a new client without API keys to avoid rate limiting client = Client("", "") server_time = client.time()["serverTime"] local_time = int(time.time() * 1000) time_difference = server_time - local_time return time_difference time_difference = get_server_time() # Adjust the timestamp to synchronize with the Binance server time params = { "timestamp": int(time.time() * 1000) + time_difference, "recvWindow": recv_window } # Sign the message using the Client’s secret key message = "&".join([f"{k}={v}" for k, v in params.items()]) signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest() params['signature'] = signature leverage = 100 # Send the request using the requests library response = requests.get(url, params=params, headers={'X-MBX-APIKEY': API_KEY}) account_info = response.json() # 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) STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = 'SELL' POSITION_SIDE_LONG = 'BUY' quantity = 1 symbol = 'BTC/USDT' order_type = 'market' leverage = 100 max_trade_quantity_percentage = 1 binance_futures = ccxt.binance({ 'apiKey': API_KEY, 'secret': API_SECRET, 'enableRateLimit': True, # enable rate limitation 'options': { 'defaultType': 'future', 'adjustForTimeDifference': True }, 'future': { 'sideEffectType': 'MARGIN_BUY', # MARGIN_BUY, AUTO_REPAY, etc… } }) # Load the market symbols params = { "timestamp": int(time.time() * 1000) + time_difference, "recvWindow": recv_window } try: markets = binance_futures.load_markets() except ccxt.BaseError as e: print(f'Error fetching markets: {e}') markets = [] if symbol in markets: print(f"{symbol} found in the market") else: print(f"{symbol} not found in the market") 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' } 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 df = get_klines(symbol, '1m', 44640) def signal_generator(df): open = df.Open.iloc[-1] close = df.Close.iloc[-1] previous
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.