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 from binance.helpers import round_step_size import pandas as pd import requests import json import numpy as np import pytz import datetime as dt import ccxt import asyncio
Get the current time and timestamp
now = dt.datetime.now() date = now.strftime(“%m/%d/%Y %H:%M:%S”) print(date)
timestamp = int(time.time() * 1000)
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 binance_futures = ccxt.binance({ ‘apiKey’: ‘’, ‘secret’: ‘’, ‘enableRateLimit’: True, # enable rate limitation ‘options’: { ‘defaultType’: ‘future’, ‘adjustForTimeDifference’: True } })
binance_futures = ccxt.binance({ ‘apiKey’: API_KEY, ‘secret’: API_SECRET, ‘enableRateLimit’: True, # enable rate limitation ‘options’: { ‘defaultType’: ‘future’, ‘adjustForTimeDifference’: True } })
markets = binance_futures.load_markets() futures_symbols = [symbol for symbol in markets if symbol.endswith(‘USDT’)]
Get server time and time difference
async def get_server_time(exchange): server_time = await exchange.fetch_time() return server_time
async def get_time_difference(): server_time = await get_server_time(binance_futures) local_time = int(time.time() * 1000) time_difference = local_time - server_time return time_difference
async def get_klines(symbol, interval, lookback): url = “https://fapi.binance.com/fapi/v1/klines” start_time = (dt.datetime.now() - dt.timedelta(minutes=lookback)) end_time = dt.datetime.now() 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’, 44640)
- Assistant
The error message suggests that the coroutine
get_klines()was never awaited. To fix this, you need to add theawaitkeyword before the call toget_klines()on line 134:df = await get_klines(symbol, ‘1m’, 44640)This should resolve the RuntimeWarning and AttributeError issues.
- User
I did it , terminal returned them : "await" allowed only within async function
- Assistant
The error message suggests that the call to
await get_klines()needs to be made within anasyncfunction. When working with coroutines andasyncfunctions, the code that calls them needs to be wrapped in a coroutine function that uses theawaitkeyword appropriately.In your case, you can define a
main()function and decorate it with theasynckeyword to make it a coroutine function. Then, move the code that callsget_klines()inside this function. Here's an example:async def main(): # define an async function while True: df = await 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}") await order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage) time.sleep(0.1) # you can also use asyncio.sleep() here asyncio.run(main()) # run the async function using asyncioThis should allow you to use
awaitwith your coroutine functions within the function.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.