The problem of asynchrony is crazy.

Author: lzhqlj, Created: 2023-03-15 10:43:20, Updated:

import pandas as pd from binance.client import AsyncClient from datetime import datetime, timedelta imported aiohttp import json def utc_to_local ((utc_dt):# Converted to Beijing time local_tz = datetime.timezone ((datetime.timedelta ((hours=8)) # East 8th district time difference Local_dt = utc_dt.replace ((tzinfo=datetime.timezone.utc).astimezone ((local_tz)) is a local_tz that is used to replace the local_tz. return local_dt

Asynchronous initialization of the Binance client

async def init_client(): client = await AsyncClient.create(api_key=api_key, api_secret=api_secret)

return client

Asynchronous acquisition of K-line data

async def get_klines(client, symbol, start_time, end_time, interval): klines = await client.futures_klines(symbol=symbol, interval=interval, startTime=start_time.timestamp()*1000, endTime=end_time.timestamp()*1000) df = pd.DataFrame(klines, columns=[‘timestamp’, ‘open’, ‘high’, ‘low’, ‘close’, ‘volume’, ‘close_time’, ‘quote_asset_volume’, ‘number_of_trades’, ‘taker_buy_base_asset_volume’, ‘taker_buy_quote_asset_volume’, ‘ignore’]) df[‘timestamp’] = pd.to_datetime(df[‘timestamp’], unit=‘ms’) df[‘close_time’] = pd.to_datetime(df[‘close_time’], unit=‘ms’) df.set_index(‘timestamp’, inplace=True) df.drop(columns=[‘close_time’, ‘ignore’], inplace=True) df = df.astype(‘float’) return df

Asynchronous shutdown of the Binance client

async def close_client(client): await client.close_connection()

Asynchronous execution of the main function

Async def main (: client = await init_client (()) # Acquire all pairs of USDT perpetual contracts Exchange_info = await client.Futures_exchange_info is the name of the client. symbols = [symbol_info [symbol] for symbol_info in exchange_info [symbols] if symbol_info [contractType] == PERPETUAL and symbol_info [quoteAsset] == USDT] # Create an empty dataframe df = pd.DataFrame ((columns=[Symbol array, Open array, High array, Low array, Close array, Change array, Volume array]) df.set_index ((Symbol array, in place=True)

# 将所有交易对添加到 DataFrame 中
for symbol in symbols:
    df.loc[symbol] = [None] * len(df.columns)
# 遍历所有交易对
for symbol in symbols:
    # 设置起止时间
    start_time = datetime.utcnow() - timedelta(minutes=16)#开始时间为16分钟前
    end_time = datetime.utcnow()
    try:
   # 获取M15k线
        current_klines = await get_klines(client, symbol, end_time - timedelta(minutes=15), end_time, '15m')
    except Exception as e:
        Log(f"An error occurred: {e}")
        current_klines = []
    # 将数据存入 DataFrame
   # 更新对应的行
    df.loc[symbol, 'Open'] = current_klines['open'].iloc[-1]
    df.loc[symbol, 'High'] = current_klines['high'].iloc[-1]
    df.loc[symbol, 'Low'] = current_klines['low'].iloc[-1]
    df.loc[symbol, 'Close'] = current_klines['close'].iloc[-1]
    df.loc[symbol, 'Change'] = current_change
    df.loc[symbol, 'Volume'] = current_klines['volume'].iloc[-1]

# 关闭客户端
Log(df)
await close_client(client)

Running asynchronous

if name == ‘main’: import asyncio asyncio.run(main())

The aim is to obtain data on the fall of all contract currencies against the M15.

Log ((df) after one error; i.e. after one update of all symbols, data such as price, etc. error: Trackback (most recent call last): File , line 1246, ininit_ctxFile , line 147, in TypeError: Object of type coroutine is not JSON serializable sys:1: RuntimeWarning: coroutine ChatGpt also failed to fix it, so we asked for help.


More

Not ifIt can be collected through multiple threads, and put the data collected by each thread into a public object; then judge whether all threads end up in the same file.

lzhqljDo you always mention a keyword or two in your dream about the aggregation function?

lzhqljDo you always mention a keyword or two in your dream about the aggregation function?

The grassI haven't used this library, but it's best to debug it step by step. It's also not very good to directly pair hundreds of transactions simultaneously. It's easier to record yourself with an aggregated market interface.

The grass/fapi/v1/ticker/price There are