从API提取数据

时间:2019-12-09 13:42:05

标签: json python-3.x websocket python-asyncio subscription

我已经在这个问题上停留了一段时间,希望能对您有所帮助。我正在尝试使用2个订阅从API拉动比特币和以太坊的价格。同时,我还将向网络套接字发送一条授权消息,以登录到我的帐户。

我遇到的问题是订阅代码没有按我期望的那样过滤掉last_price。

如果我删除登录/授权消息,则它会过滤输出的罚款(尽管我需要为其他用途进行授权),并且它只会给出一次输出,而不是像订阅一样的连续价格流。

我的代码是:

import asyncio
import json

import websocket


btc = None
eth = None

async def call_api2(msg1, msg2, msg4):
    async with websockets.connect('wss://testapp.deribit.com/ws/api/v2') as websocket:
        await websocket.send(msg1)
        btc_ticker = await websocket.recv()
        btc_ticker_load = json.loads(btc_ticker)
        #print(btc_ticker_load)
        btc_ticker = await websocket.recv()
        btc_ticker_load = json.loads(btc_ticker)
        global btc
        btc = btc_ticker_load["params"]["data"]["last_price"]
        print(btc)


        await websocket.send(msg4)
        eth_ticker = await websocket.recv()
        eth_ticker_load = json.loads(eth_ticker)
        #print(eth_ticker_load)
        eth_ticker = await websocket.recv()
        eth_ticker_load = json.loads(eth_ticker)
        global eth
        eth = eth_ticker_load["params"]["data"]["last_price"]
        print(eth, 'this is eth')
        print(btc-eth, 'this is the delta')

        await websocket.send(msg2)
        while websocket.open:
            authenticate = await websocket.recv()
            # do something with the notifications...
            authenticate_load = json.loads(authenticate)
            print(authenticate_load)


loop = asyncio.get_event_loop()
try:
  asyncio.ensure_future(call_api2( json.dumps(msg1), json.dumps(msg2), json.dumps(msg4) ))   
  loop.run_forever()
except KeyboardInterrupt:
  pass
finally:
  print('closing loop')
  loop.close()

我的输出不仅仅过滤btc和eth价格,而是整个输出如下:

{'jsonrpc': '2.0', 'method': 'subscription', 'params': {'channel': 'ticker.ETH-PERPETUAL.raw', 'data': {'timestamp': 1575898571330, 'stats': {'volume': 47214.31236, 'low': 148.5, 'high': 151.9}, 'state': 'open', 'settlement_price': 148.89, 'open_interest': 165337623, 'min_price': 147.26, 'max_price': 153.27, 'mark_price': 150.26, 'last_price': 150.25, 'instrument_name': 'ETH-PERPETUAL', 'index_price': 150.29, 'funding_8h': 0.0, 'current_funding': 0.0, 'best_bid_price': 150.25, 'best_bid_amount': 39114.0, 'best_ask_price': 150.3, 'best_ask_amount': 9398.0}}}

0 个答案:

没有答案