一、核心交易功能
一、核心交易功能
1.1 交易指令执行
▶️ publish(cmd)
功能: 向交易引擎发送并执行单个交易指令
参数:
cmd: 交易指令对象,符合ExecutionCommand结构
返回值:
- Result结构: 包含
Ok或Err字段的字典 - 成功时:
{"Ok": execution_result}- 指令执行结果 - 失败时:
{"Err": error_info}- 包含错误信息
示例:
# ✅ 正确的使用方式 - 查询USDT余额
cmd = {
"account_id": 0,
"method": "UsdtBalance",
"sync": True
}
result = trader.publish(cmd)
if "Ok" in result:
balance_data = result["Ok"]
print(f"USDT余额查询成功: {balance_data}")
# 提取具体余额信息
if isinstance(balance_data, dict) and "balance" in balance_data:
print(f"可用余额: {balance_data['balance']}")
else:
error = result.get("Err", "未知错误")
print(f"余额查询失败: {error}")
# 下单指令示例 - 带完整错误处理
place_order_cmd = {
"account_id": 0,
"method": "PlaceOrder",
"order": {
"symbol": "BTC_USDT",
"order_type": "Limit",
"side": "Buy",
"price": 50000.0,
"amount": 0.01,
"time_in_force": "GTC",
"cid": "client_order_123"
},
"params": {
"is_dual_side": False,
"market_order_mode": "Normal"
},
"sync": True
}
result = trader.publish(place_order_cmd)
if "Ok" in result:
order_result = result["Ok"]
print(f"下单成功: {order_result}")
# 提取订单ID
if isinstance(order_result, dict):
order_id = order_result.get("order_id")
client_order_id = order_result.get("client_order_id")
print(f"订单ID: {order_id}, 客户端ID: {client_order_id}")
else:
error = result.get("Err")
print(f"下单失败: {error}")
# 根据错误类型进行处理
if "insufficient balance" in str(error).lower():
print("余额不足,请检查账户余额")
elif "invalid symbol" in str(error).lower():
print("交易对不存在,请检查symbol参数")
# 另一个查询示例
balance_cmd = {"account_id": 0, "method": "UsdtBalance", "sync": True}
result = trader.publish(balance_cmd)
if "Ok" in result:
balance_data = result["Ok"]
print(f"USDT余额查询成功: {balance_data}")
else:
error = result.get("Err", "未知错误")
print(f"USDT余额查询失败: {error}")
▶️ batch_publish(cmds)
功能: 批量执行多个交易指令
参数:
cmds: 交易指令对象列表
返回值:
- Result结构列表: 每个元素都包含
Ok或Err字段的字典 - 成功时: 每个结果为
{"Ok": execution_result} - 失败时: 每个结果为
{"Err": error_info}
示例:
# ✅ 正确的使用方式 - 批量执行多个交易指令
cmds = [
{
"account_id": 0,
"method": "UsdtBalance",
"sync": True
},
{
"account_id": 0,
"method": "BalanceByCoin",
"asset": "BTC",
"sync": True
}
]
results = trader.batch_publish(cmds)
# 处理批量结果
for i, result in enumerate(results):
if "Ok" in result:
data = result["Ok"]
print(f"指令{i+1}执行成功: {data}")
else:
error = result.get("Err", "未知错误")
print(f"指令{i+1}执行失败: {error}")
# 统计执行结果
success_count = 0
failed_count = 0
cmd_names = ["USDT余额查询", "BTC余额查询"]
for i, result in enumerate(results):
cmd_name = cmd_names[i] if i < len(cmd_names) else f"指令{i+1}"
if "Ok" in result:
success_count += 1
data = result["Ok"]
print(f"✅ {cmd_name} 执行成功: {data}")
else:
failed_count += 1
error = result.get("Err", "未知错误")
print(f"❌ {cmd_name} 执行失败: {error}")
print(f"\n总计: 成功 {success_count} 个, 失败 {failed_count} 个")
1.2 唯一标识符生成
🆔 create_cid(exchange)
功能: 创建唯一的客户端标识符
参数:
exchange: 交易所对象,用于生成对应交易所的CID格式
返回值:
- Result结构: 包含
Ok或Err字段的字典 - 成功时:
{"Ok": "unique_cid_string"}- 唯一的标识符字符串 - 失败时:
{"Err": error_info}- 包含错误信息
用途:
- 用于标识和跟踪交易订单
- 在高频交易中避免重复订单
- 关联策略生成的订单与回报信息
- 作为交易请求的唯一引用
示例:
# 创建唯一的客户端标识符
from exchange import Exchange # 假设有交易所模块
# 需要提供exchange对象
exchange = Exchange.BINANCE # 或其他交易所
result = trader.create_cid(exchange)
if "Ok" in result:
cid = result["Ok"]
print(f"生成的订单ID: {cid}")
# 在下单时使用生成的CID
place_order_cmd = {
"account_id": 0,
"method": "PlaceOrder",
"order": {
"symbol": "BTC_USDT",
"order_type": "Limit",
"side": "Buy",
"price": 50000.0,
"amount": 0.01,
"cid": cid # 使用生成的CID
},
"sync": True
}
else:
error = result.get("Err", "未知错误")
print(f"生成订单ID失败: {error}")
1.3 进程管理
⛔ graceful_shutdown()
功能: 优雅退出交易进程,发送 SIGINT 信号(等效于 Ctrl+C)来安全停止程序
参数: 无
返回值: 无
用途:
- 在需要安全退出交易程序时使用
- 通过发送 kill -2 信号来优雅停止当前进程
- 允许程序有序地清理资源和保存状态
- 适用于程序自动退出、异常处理或远程控制停止
示例:
# 在满足特定条件时优雅退出程序
if should_shutdown:
trader.log("准备优雅退出程序", "INFO")
trader.graceful_shutdown()
# 在异常处理中使用
try:
# 执行交易逻辑
pass
except CriticalError as e:
trader.log(f"遇到严重错误,程序将退出: {e}", "ERROR", color="red")
trader.graceful_shutdown()
# 定时退出示例
import time
start_time = time.time()
while True:
# 交易逻辑...
if time.time() - start_time > 24 * 3600: # 24小时后退出
trader.log("程序运行24小时,准备退出", "INFO")
trader.graceful_shutdown()
break
注意事项:
- 此方法会立即发送退出信号,程序会在短时间内停止
- 确保在调用此方法前已完成重要数据的保存
- 建议在调用前使用日志记录退出原因