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

MEXC API Python下单语法错误求助:完成ETH→BTC→USDT交易

问题解决与代码完善

一、语法错误修复

你遇到的位置参数位于关键字参数之后错误,是因为Python函数调用时不能在参数中添加类型标注(options: any),且字典键未加引号。正确写法如下:

错误写法:

spot.new_order(symbol= 'ETHUSDT', side= 'BUY', order_type= 'LIMIT_MAKER', options: any={price: str(ask1), quantity: str(size)})

正确写法:

spot.new_order(symbol='ETHUSDT', side='BUY', order_type='LIMIT_MAKER', options={"price": str(ask1), "quantity": str(size)})

二、完整交易流程代码

以下是修复错误并完善后的代码,实现「买入ETH→转卖为BTC→卖出BTC兑换USDT」的完整流程,包含订单成交等待、错误处理和状态管理:

import json
import os
import time
from mexc_sdk import Spot

# 初始化API客户端
spot = Spot(api_key="mx0apikeyXDkeyA", api_secret="10secret5c2b2apisecret06507b44a847bb")

# 初始化状态文件
def init_files():
    if not os.path.exists("profit"):
        with open("profit", "w") as f:
            f.write("0.0")
    if not os.path.exists("step"):
        with open("step", "w") as f:
            f.write("0")
    if not os.path.exists("COAX"):
        with open("COAX", "w") as f:
            f.write("0")
    if not os.path.exists("db"):
        os.makedirs("db")

init_files()

# 读取状态
def read_file(file_path, default):
    try:
        with open(file_path, "r") as f:
            return f.read().strip()
    except Exception:
        return default

# 写入状态
def write_file(file_path, content):
    with open(file_path, "w") as f:
        f.write(str(content))

# 等待订单成交
def wait_order_fill(symbol):
    while True:
        open_orders = spot.open_orders(symbol=symbol)
        if not open_orders:
            break
        print(f"等待{symbol}订单成交...")
        time.sleep(1)

while True:
    # 读取状态
    profit = float(read_file("profit", "0.0"))
    step = int(read_file("step", "0"))
    coax = int(read_file("COAX", "0"))

    # 获取市场深度数据
    eth_usdt_depth = spot.depth(symbol="ETHUSDT")
    eth_btc_depth = spot.depth(symbol="ETHBTC")
    btc_usdt_depth = spot.depth(symbol="BTCUSDT")

    # 计算套利空间(覆盖手续费阈值设为0.001)
    eth_usdt_bid = float(eth_usdt_depth["bids"][0][0])  # ETHUSDT买一价
    eth_btc_ask = float(eth_btc_depth["asks"][0][0])   # ETHBTC卖一价
    btc_usdt_bid = float(btc_usdt_depth["bids"][0][0]) # BTCUSDT买一价

    # 用1 USDT模拟套利收益
    eth_amount = 1 / eth_usdt_bid
    btc_amount = eth_amount * eth_btc_ask
    final_usdt = btc_amount * btc_usdt_bid
    arbitrage_profit = final_usdt - 1

    if arbitrage_profit > 0.001:
        print(f"发现套利机会,收益:{arbitrage_profit:.6f} USDT")
        profit += arbitrage_profit
        write_file("profit", profit)

        # 步骤1:买入ETH
        if step == 0:
            try:
                spot.new_order(
                    symbol='ETHUSDT',
                    side='BUY',
                    order_type='LIMIT_MAKER',
                    options={"price": str(eth_usdt_bid), "quantity": str(eth_amount)}
                )
                wait_order_fill("ETHUSDT")
                write_file("step", 1)
                print("ETH买入完成")
            except Exception as e:
                print(f"ETH买入失败:{e}")
                continue

        # 步骤2:ETH转BTC
        if step == 1:
            try:
                spot.new_order(
                    symbol='ETHBTC',
                    side='SELL',
                    order_type='LIMIT_MAKER',
                    options={"price": str(eth_btc_ask), "quantity": str(eth_amount)}
                )
                wait_order_fill("ETHBTC")
                write_file("step", 2)
                print("ETH转BTC完成")
            except Exception as e:
                print(f"ETH转BTC失败:{e}")
                continue

        # 步骤3:卖出BTC换USDT
        if step == 2:
            try:
                spot.new_order(
                    symbol='BTCUSDT',
                    side='SELL',
                    order_type='LIMIT_MAKER',
                    options={"price": str(btc_usdt_bid), "quantity": str(btc_amount)}
                )
                wait_order_fill("BTCUSDT")
                write_file("step", 0)
                print("BTC卖出完成,套利流程结束")
            except Exception as e:
                print(f"BTC卖出失败:{e}")
                continue

    # 记录市场数据
    bidprice = btc_usdt_depth['bids'][0][0]
    bidsize = btc_usdt_depth['bids'][0][1]
    askprice = btc_usdt_depth['asks'][0][0]
    asksize = btc_usdt_depth['asks'][0][1]

    json_d = {
        0: {
            "bid": str(bidprice),
            "bid_size": str(bidsize),
            "ask": str(askprice),
            "ask_size": str(asksize),
            "bid_price": str(bidprice),
            "ask_price": str(askprice)
        }
    }
    js = json.dumps(json_d, indent=4)

    with open(f"db/ledger-{coax}.json", "w+") as f:
        f.write(js)

    # 更新状态
    write_file("COAX", coax + 1)
    print(f"当前累计收益:{profit:.6f} USDT,轮次:{coax}")
    time.sleep(2)

三、关键技术要点

  • 参数规范:MEXC SDK的new_order方法中,options是字典参数,无需类型标注,且字典键必须用字符串引号包裹。
  • 订单等待逻辑:必须等待上一笔订单完全成交后再执行下一步,避免因余额不足导致下单失败,通过open_orders接口判断订单状态。
  • 手续费考虑:设置收益阈值时需覆盖MEXC maker手续费(约0.1%),避免无意义的交易亏损。
  • 错误处理:添加异常捕获,防止单次API调用失败导致程序崩溃。
  • 状态持久化:用文件记录交易步骤,程序重启后可从中断处继续执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 12:25:40