You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python websocket-client传递token连接Indodax Websocket API

问题根因

你的报错来自三个核心问题:

  1. 订阅请求格式不符合接口要求,你直接将订阅频道字符串序列化后发送,接口要求的是固定结构的JSON对象,不是纯字符串。
  2. 代码存在语法错误,on_open函数末尾有多余的无效字符x,会导致运行异常。
  3. 握手阶段的Origin头使用了http协议,和wss请求的安全协议不匹配。

修复步骤

  • 调整订阅请求的结构,按照接口要求构造包含方法、参数的JSON对象,不要直接序列化频道字符串。
  • 修正代码中的语法错误,删除多余的无效字符。
  • 手动指定正确的Origin头,改为https协议前缀。

修正后代码

import websocket
import json
import _thread


def on_message(ws, message):
    print(message)

def on_error(ws, error):
    print(error)

def on_close(ws, close_status_code, close_msg):
    print("### closed ###")

def on_open(ws):
    subscribeEvent(ws, "btcidr.trade")
    print("thread terminating...")
    _thread.start_new_thread(send_heartbeat, ())

def send_heartbeat(*args):
    # 实际使用时按文档要求定时发送心跳包即可
    pass

def subscribeEvent(ws, channel, auth_key=''):
    try:
        # 构造符合要求的订阅请求体
        sub_data = {
            "method": "subscribe",
            "params": {
                "channel": channel
            }
        }
        ws.send(json.dumps(sub_data))
    except Exception as e:
        print(e)

if __name__ == "__main__":
    websocket.enableTrace(True)
    token='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwiaW5mbyI6eyJuYW1lIjoiUHVibGljIn19.VJAHTrrfwxceSITpuPBl75LVM5bgojKGiUTOwCZxw-k'
    # 补充正确的Origin头和token头
    headers = [
        f"extension-token:{token}",
        "Origin: https://ws.indodax.com"
    ]
    while True:
        ws = websocket.WebSocketApp("wss://ws.indodax.com/ws/",
                                  on_open=on_open,
                                  on_message=on_message,
                                  on_error=on_error,
                                  on_close=on_close,
                                  header=headers)
        ws.run_forever()

额外说明

你之前的token传递格式本身是符合要求的,不需要调整,报错的核心原因是订阅消息结构错误和Origin头协议不匹配。

内容的提问来源于stack exchange,提问作者Himanshu Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 01:15:04