火幣網API文檔——WebSocket API簡介


WebSocket API簡介

WebSocket協議是基於TCP的一種新的網絡協議。它實現了客戶端與服務器之間在單個 tcp 連接上的全雙工通信,由服務器主動發送信息給客戶端,減少了頻繁的身份驗證等不必要的開銷。其最大優點有兩個:

  • 兩方請求的 header 數據很小,大概只有2 Bytes。

  • 服務器不再是被動的接到客戶端的請求后才返回數據,而是有了新數據后主動推送給客戶端。

以上 WebSocket 協議帶來的優點使得其十分適用於數字貨幣行情和交易這種實時性強的接口。

 

WebSocket  API 行情 代碼示例

from websocket import create_connection
import gzip
import time

if __name__ == '__main__':
    while(1):
        try:
            ws = create_connection("wss://api.huobipro.com/ws")
            break
        except:
            print('connect ws error,retry...')
            time.sleep(5)

    # 訂閱 KLine 數據
    tradeStr="""{"sub": "market.ethusdt.kline.1min","id": "id10"}"""

    # 請求 KLine 數據
    # tradeStr="""{"req": "market.ethusdt.kline.1min","id": "id10", "from": 1513391453, "to": 1513392453}"""

    #訂閱 Market Depth 數據
    # tradeStr="""{"sub": "market.ethusdt.depth.step5", "id": "id10"}"""

    #請求 Market Depth 數據
    # tradeStr="""{"req": "market.ethusdt.depth.step5", "id": "id10"}"""

    #訂閱 Trade Detail 數據
    # tradeStr="""{"sub": "market.ethusdt.trade.detail", "id": "id10"}"""

    #請求 Trade Detail 數據
    # tradeStr="""{"req": "market.ethusdt.trade.detail", "id": "id10"}"""

    #請求 Market Detail 數據
    # tradeStr="""{"req": "market.ethusdt.detail", "id": "id12"}"""

    ws.send(tradeStr)
    while(1):
        compressData=ws.recv()
        result=gzip.decompress(compressData).decode('utf-8')
        if result[:7] == '{"ping"':
            ts=result[8:21]
            pong='{"pong":'+ts+'}'
            ws.send(pong)
            ws.send(tradeStr)
        else:
            print(result)
View Code

注:運行前需先安裝websocket_client-0.44.0-py2.py3-none-any.whl    猛戳我下載    下載后pip install websocket_client-0.44.0-py2.py3-none-any.whl

 

 

 

    


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM