이 문제는 미친 짓입니다.

저자:, 창작: 2023-03-15 10:43:20, 업데이트:

pandas as pd를 가져오기 from binance.client import 아시크 클라이언트 from datetime, import datetime, timedelta 로 가져옵니다 aiohttp를 가져오세요 json를 가져오기 def utc_to_local ((utc_dt):# 베이징 시간으로 변환 local_tz = datetime.timezone ((datetime.timedelta ((hours=8)) # 동부 8구역 시간차 local_dt = utc_dt.replace ((tzinfo=datetime.timezone.utc).astimezone ((local_tz) 로 로컬_디트. return local_dt

비동기 초기화 Binance 클라이언트

async def init_client ((): 클라이언트 = 대기 AsyncClient.create ((api_key=api_key, api_secret=api_secret)

return client

K 라인 데이터를 비동기적으로 가져옵니다.

async def get_klines ((클라이언트, 기호, 시작_시간, 종료_시간, 간격): klines = wait 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[시간표] = pd.to_datetime(df[시간표], 단위=ms) df[close_time] = pd.to_datetime ((df[close_time], 단위=ms) df.set_index (시간표) inplace=True df.drop(columns=[close_time, ignore], inplace=True) df = df.astype ((float) 반환 df

비동시 종료 Binance 클라이언트

async def close_client ((클라이언트): 클라이언트를 기다립니다.close_connection (()

오시크로 실행되는 메인 함수

async def main (((): 클라이언트 = init_client를 기다립니다 # 모든 USDT 영구 계약 거래 쌍을 획득 exchange_info = await client.futures_exchange_info (예: 클라이언트를 기다린다) symbols = [symbol_info[symbol] for symbol_info in exchange_info[symbols] if symbol_info[contractType] == PERPETUAL and symbol_info[quoteAsset] == USDT] # 빈 데이터프레임을 생성합니다 df = pd.DataFrame ((columns=[Symbol, Open, High, Low, Close, Change, Volume]) df.set_index (Symbol, inplace=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)

비동기 프로그램을 실행합니다.

만약이름 == ‘주요: 아시니오asyncio.run(주))

M15에 대한 모든 계약 화폐의 부진 데이터를 얻기 위한 것입니다.

Log ((df) 한 번 후에 오류가 발생한다; 즉, 모든 기호의 가격과 같은 데이터를 한 번 업데이트 한 후에 오류가 발생한다:Traceback (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 main was never awaited RuntimeWarning: Enable tracemalloc to get the object allocation traceback 파일 , line 147, in TypeError: Object of type coroutine is not JSON serializable sys:1: RuntimeWarning: coroutine main was never awaited 런타임워닝: 트레이스몰록을 활성화하여 객체 할당 트레이스백을 얻을 수 있습니다 ChatGpt도 해결하지 못했고, 대장에게 도움을 요청했습니다.


더 많은

만약여러 개의 스레드를 통해 수집할 수 있고, 각각의 스레드에서 수집된 데이터를 하나의 공용 객체에 넣고, 모든 스레드가 끝나는지 판단합니다.

그리고 이 모든 것은, 이 모든 것은, 이 모든 것은, 이 모든 것은, 이 모든 것은, 이 모든 것은, 이 모든 것은, 이 모든 것은, 이 모든 것은, 이 모든 것은, 이 모든 것은, 이 모든 것은, 이 모든 것은, 이 모든 것은.

그리고 이 모든 것은, 이 모든 것은, 이 모든 것은, 이 모든 것은, 이 모든 것은, 이 모든 것은, 이 모든 것은, 이 모든 것은, 이 모든 것은, 이 모든 것은, 이 모든 것은, 이 모든 것은, 이 모든 것은, 이 모든 것은.

초목이 라이브러리를 사용하지 않았지만 단계별로 디뷰하는 것이 좋습니다. 또한 직접 동시에 수백 개의 거래가 잘되지 않습니다.

초목/fapi/v1/ticker/price 바이안 문서가 있습니다