(okex量化)python打通api最简单的一个程序(inflate(data)函数是官方提供转码的,必须使用否则乱码解决不了!!)

import websocket
import sys
import zlib


def on_open(self):
    #subscribe okcoin.com spot ticker
    self.send(
        '{"channel":"ok_sub_futureusd_btc_depth_quarter","event":"addChannel"}'
    )
    print("数据连接成功")


#okex专用转码函数(如果不转码,会乱码无法解决)
def inflate(data):
    decompress = zlib.decompressobj(-zlib.MAX_WBITS  # see above
                                    )
    inflated = decompress.decompress(data)
    inflated += decompress.flush()
    return inflated


def on_message(self, evt):
    #这里必须用官方提供的inflate函数转码,否则是乱码!
    data = inflate(evt)
    print(data)


def on_error(self, evt):
    print(evt)


def on_close(self, evt):
    print('DISCONNECT')


if __name__ == "__main__":
    url = "wss://real.okex.com:10441/websocket?compress=true"  #if okcoin.cn  change url wss://real.okcoin.cn:10440/websocket/okcoinapi

    websocket.enableTrace(False)
    if len(sys.argv) < 2:
        host = url
    else:
        host = sys.argv[1]
    ws = websocket.WebSocketApp(
        host, on_message=on_message, on_error=on_error, on_close=on_close)
    ws.on_open = on_open
    ws.run_forever()

 

你可能感兴趣的:(okex量化交易,python语言)