Pharos

XMX API 参考文档

本目录包含 XMX 量化交易机器人所有 API 方法的详细文档。

📚 文档分类

1. 市场行情

获取市场数据和行情信息的方法。

方法描述文档链接
GetTicker()获取行情数据(最新价、买卖价等)查看文档
GetDepth()获取盘口深度数据(买卖委托单)查看文档
GetTrades()获取最新成交记录查看文档
GetRecords()获取K线数据(OHLCV)查看文档
GetCurrenciesPrecision()获取所有交易对的精度信息查看文档

2. 账户信息

查询账户资产和余额的方法。

方法描述文档链接
GetAccount()获取账户资产信息(余额、冻结等)查看文档

3. 交易

下单、查询订单和撤单的方法。

方法描述文档链接
Buy(price, amount)下买单(做多)查看文档
Sell(price, amount)下卖单(做空)查看文档
GetOrder(order_id)查询指定订单详情查看文档
GetOrders()查询所有订单(含历史订单)查看文档
GetHistoryOrders()查询历史订单查看文档
GetPendingOrders()查询未完成订单(挂单)查看文档
CancelOrder(order_id)撤销指定订单查看文档
CancelAllOrders()撤销所有订单查看文档

4. 合约交易

期货/永续合约专用的方法。

方法描述文档链接
GetPosition()获取合约持仓信息查看文档
SetContractType(symbol)设置合约类型(合约代码)查看文档
GetContractType()获取当前合约类型查看文档
SetDirection(direction)设置开平仓方向查看文档
SetMarginLevel(level)设置杠杆倍数查看文档
GetMarginLevel()获取当前杠杆倍数查看文档
SetPositionMode(mode)设置保证金模式(全仓/逐仓)查看文档
SetDualMode(dualSide)设置持仓模式(单向/双向)查看文档
GetFundings()获取合约资金费率信息查看文档

5. 交易所设置

配置交易所、币对等的方法。

方法描述文档链接
GetName()获取交易所名称查看文档
GetCurrency()获取当前交易对查看文档
SetCurrency(symbol)设置交易对查看文档

6. 扩展 API

底层接口调用和特殊功能。

方法描述文档链接
IO(api, method, params)调用交易所底层 REST API查看文档

🚀 快速开始

基础工作流程

python
# 1. 获取行情
ticker = exchange.GetTicker()
Log("当前价格:", ticker["Last"])

# 2. 查询账户
account = exchange.GetAccount()
Log("可用余额:", account["Balance"])

# 3. 下单交易
order_id = exchange.Buy(ticker["Last"] * 0.99, 0.01)

# 4. 查询订单
order = exchange.GetOrder(order_id)
Log("订单状态:", order["Status"])

# 5. 撤销订单(如果需要)
if order["Status"] == 0:  # 未成交
    exchange.CancelOrder(order_id)

合约交易工作流程

python
# 1. 设置合约和杠杆
exchange.SetContractType("swap")  # 永续合约
exchange.SetMarginLevel(5)        # 5倍杠杆

# 2. 双向持仓模式 - 开仓做多
exchange.SetDirection("buy")      # 开多(也可用"long")
order_id = exchange.Buy(-1, 10)   # 市价开10张

# 3. 查询持仓
positions = exchange.GetPosition()
for pos in positions:
    if pos["Type"] == 0:  # 多头持仓
        Log("持仓量:", pos["Amount"])
        Log("未实现盈亏:", pos["Profit"])
        Log("爆仓价:", pos.get("LiquidationPrice", "N/A"))
        Log("杠杆:", pos.get("Leverage", "全仓"))

# 4. 双向持仓模式 - 平仓
exchange.SetDirection("closebuy") # 平多(也可用"close_long")
exchange.Sell(-1, 10)             # 市价平10张

# 注意:单向持仓模式下,不需要 SetDirection
# 系统会根据持仓方向和下单方向自动判断开仓/平仓

📖 常用代码片段

1. 获取实时价格并计算差价

python
ticker = exchange.GetTicker()
spread = ticker["Sell"] - ticker["Buy"]
spread_percent = (spread / ticker["Last"]) * 100
Log(f"买卖价差: {spread} ({spread_percent:.2f}%)")

2. 网格交易下单

python
price = exchange.GetTicker()["Last"]
grid_count = 5
grid_size = 0.01  # 1%

for i in range(grid_count):
    buy_price = price * (1 - grid_size * (i + 1))
    sell_price = price * (1 + grid_size * (i + 1))
    
    exchange.Buy(buy_price, 0.01)
    exchange.Sell(sell_price, 0.01)

3. 合约开仓和止损

python
# 开仓
exchange.SetDirection("buy")
entry_price = exchange.GetTicker()["Last"]
exchange.Buy(-1, 100)  # 市价开100张多单

# 设置止损价
stop_loss_price = entry_price * 0.95  # 5%止损

# 监控并止损
while True:
    ticker = exchange.GetTicker()
    if ticker["Last"] <= stop_loss_price:
        exchange.SetDirection("closebuy")
        exchange.Sell(-1, 100)
        Log("止损平仓")
        break
    Sleep(1000)

4. 查询并撤销所有未成交订单

python
# 方法1:使用 GetPendingOrders
pending = exchange.GetPendingOrders()
for order in pending:
    exchange.CancelOrder(order["Id"])
    Log(f"已撤销订单: {order['Id']}")

# 方法2:使用 CancelAllOrders
canceled_count = exchange.CancelAllOrders()
Log(f"已撤销 {canceled_count} 个订单")

5. 单向持仓 vs 双向持仓模式

python
# --- 双向持仓模式(需要 SetDirection)---
exchange.SetContractType("swap")

# 开多仓
exchange.SetDirection("buy")        # 或 "long"
exchange.Buy(-1, 10)

# 开空仓(可以同时持有多空仓位)
exchange.SetDirection("sell")       # 或 "short"
exchange.Sell(-1, 10)

# 平多仓
exchange.SetDirection("closebuy")   # 或 "close_long"
exchange.Sell(-1, 10)

# 平空仓
exchange.SetDirection("closesell")  # 或 "close_short"
exchange.Buy(-1, 10)

# --- 单向持仓模式(可选 SetDirection)---
# 单向模式下,系统自动判断开仓/平仓
# 买入正数开多,卖出负数自动平多
# 卖出正数开空,买入负数自动平空

# 开多仓
exchange.Buy(-1, 10)    # 正数开多

# 平多仓(当前有多仓时)
exchange.Sell(-1, 10)   # 自动平多

# 开空仓
exchange.Sell(-1, 10)   # 正数开空

# 平空仓(当前有空仓时)
exchange.Buy(-1, 10)    # 自动平空

5. 监控持仓盈亏和爆仓风险

python
exchange.SetContractType("swap")

while True:
    positions = exchange.GetPosition()
    total_profit = 0
    
    for pos in positions:
        total_profit += pos["Profit"]
        pos_type = "" if pos["Type"] == 0 else ""
        
        # 基本信息
        Log(f"类型: {pos_type}, 数量: {pos['Amount']}, 盈亏: {pos['Profit']}")
        
        # 爆仓价风险检查
        if pos.get("LiquidationPrice") and pos["LiquidationPrice"] > 0:
            current_price = exchange.GetTicker()["Last"]
            
            if pos["Type"] == 0:  # 多头
                distance_percent = ((current_price - pos["LiquidationPrice"]) / current_price) * 100
            else:  # 空头
                distance_percent = ((pos["LiquidationPrice"] - current_price) / current_price) * 100
            
            Log(f"爆仓价: {pos['LiquidationPrice']}, 距离: {distance_percent:.2f}%")
            
            # 风险预警
            if distance_percent < 5:
                Log("⚠️ 警告:距离爆仓价小于5%!")
            elif distance_percent < 10:
                Log("⚡ 注意:距离爆仓价小于10%")
        
        # 杠杆和保证金信息
        if pos.get("Leverage"):
            leverage = pos["Leverage"] if pos["Leverage"] > 0 else "全仓"
            Log(f"杠杆: {leverage}, 保证金: {pos.get('InitialMargin', 0)}")
    
    Log(f"总盈亏: {total_profit}")
    Sleep(5000)

⚠️ 重要提示

  1. API 限流: 所有交易所都有 API 调用频率限制,请合理使用 Sleep() 避免超限
  2. 精度问题: 下单前请使用 GetCurrenciesPrecision() 获取精度要求
  3. 错误处理: 务必检查返回值,API 失败时会返回 null 或空对象
  4. 合约交易风险: 使用杠杆前请充分了解风险,建议从低倍数开始
  5. 测试先行: 新策略建议先在模拟盘测试,确认无误后再上实盘