見出し画像

[FTX][pybotters]websocket使ってみた

pybottersの使用例的なもの自分用備忘録

参考にしたソースコード​

# 参考にした関数
def _init(self) -> None:

# 見た場所 channel == の辺り
def _onmessage(self, msg: Any, ws: ClientWebSocketResponse) -> None:

完全に理解するには↓見ないとダメそう

orderbookGrouped で勝手にグルーピングしてくれるのはありがたい

使用例: 5秒毎にティッカーと板情報をcsvに保存するコード

exsamle.py

import time
import pybotters
import asyncio
import pandas as pd


async def main(symbol):
   async with pybotters.Client(base_url='https://ftx.com/api/') as client:
       store = pybotters.FTXDataStore()
       await client.ws_connect(
           'wss://ftx.com/ws/',
           send_json=[
               {'op': 'subscribe', 'channel': 'ticker', 'market': symbol},
               {'op': 'subscribe', 'channel': 'markets'},
               {'op': 'subscribe', 'channel': 'trades', 'market': symbol},
               {'op': 'subscribe', 'channel': 'orderbook', 'market': symbol},
               {'op': 'subscribe', 'channel': 'orderbookGrouped', 'market': symbol, 'grouping': 100},
               {'op': 'subscribe', 'channel': 'orders'},
               {'op': 'subscribe', 'channel': 'fills'},
           ],
           hdlr_json=store.onmessage,)

       while True:
           start = time.time()
           await store.ticker.wait()
           await store.orderbook.wait()
           ticker = store.ticker.find()
           orderbook = store.orderbook.find()
           df_ticker = await data_to_df(ticker)
           df_orderbook = await data_to_df(orderbook)
           # df_ticker.to_csv('ticker.csv')
           # df_orderbook.to_csv('orderbook.csv')
           await df_to_csv(df_ticker, 'ticker')
           await df_to_csv(df_orderbook, 'orderbook')
           print(df_ticker)
           await asyncio.sleep(5)
           end = time.time()
           elpsed_time = end - start
           print(elpsed_time)


async def data_to_df(data):
   await asyncio.sleep(0.0001)
   return pd.DataFrame(data)


async def df_to_csv(df, name):
   await asyncio.sleep(0.0001)
   return df.to_csv(name + '.csv')


# 非同期メイン関数を実行(Ctrl+Cで終了)
if __name__ == '__main__':
   try:
       asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())  # need windowsOS python3.8
       asyncio.run(main('BTC-PERP'))
   except KeyboardInterrupt:
       pass

この記事が気に入ったらサポートをしてみませんか?