N001 Websocket 的连接方法

Fcoin交易所为例子, websocket 订阅的代码写法

  1. 建立websocket的实例.
  2. 连接成功
  3. 每次发送订阅信息得到返回 json数据
  4. 处理数据...
  • websocket 连接的代码
import websocket
import json
import datetime
import time

ws = websocket.WebSocket()
ws.connect("wss://ws.fcoin.com/api/v2/ws")
ws.recv()
s = "ticker.ftusdt"
req = {
    'cmd': 'req',
    'args': [s],
    'id': '1'
}

while True:
    ws.send(json.dumps(req))
    r = json.loads(ws.recv())
    print(datetime.datetime.fromtimestamp(time.time())
                  .strftime("%Y%m%d %H%M%S"), '\t',  r['data']['ticker'])
    print()
    time.sleep(1)
  • 运行结果

20180713 090217 [0.242509, 16.67, 0.242506, 98.44, 0.242509, 1672.78,]
20180713 090218 [0.242476, 15.0, 0.242476, 519.8, 0.242509, 31.83, ...]
20180713 090220 [0.242472, 5.0, 0.242468, 10.0, 0.242508, 15.15, ...]
20180713 090221 [0.242476, 15.0, 0.24245, 2638.7, 0.242476, 151.88, ...]
20180713 090222 [0.242488, 5.91, 0.242476, 151.88, 0.242488, 667.09, ...]
20180713 090223 [0.242476, 16.67, 0.242476, 35.21, 0.242488, 667.09,..]

你可能感兴趣的:(N001 Websocket 的连接方法)