统一交易系统,包含自动记录日志、机器人管理和性能分析。
聊天命令
投资组合
/trading portfolio # 查看所有头寸
/trading portfolio poly # Polymarket上的头寸
/trading portfolio --value # 包含当前价值
性能
/trading stats # 总体统计
/trading stats --period 30d # 最后30天
/trading daily-pnl # 每日盈亏分析
/trading weekly-pnl # 每周盈亏
/trading monthly-pnl # 每月盈亏
交易历史
/trading history # 最近的交易
/trading history --limit 50 # 最后50笔交易
/trading history --platform poly # 仅限Polymarket
/trading export # 导出到CSV
/trading export --format json # 导出为JSON
机器人管理
/bot list # 列出所有机器人
/bot register <name> <strategy> # 注册新机器人
/bot start <name> # 启动机器人
/bot stop <name> # 停止机器人
/bot status <name> # 机器人状态
/bot delete <name> # 删除机器人
机器人策略
/bot strategies # 列出可用策略
/bot create mean-reversion --config {...} # 创建并配置
/bot create momentum --lookback 14 # 动量策略
/bot create arbitrage --min-spread 1 # 套利策略
TypeScript API参考
创建交易系统
import { createTradingSystem } from 'clodds/trading';
const trading = createTradingSystem({
// 执行服务
execution: executionService,
// 自动记录日志
autoLog: true,
logPath: './trades.db',
// 机器人配置
bots: {
enabled: true,
maxConcurrent: 5,
},
});
投资组合
// 获取投资组合
const portfolio = await trading.getPortfolio();
console.log(`总价值: $${portfolio.totalValue.toLocaleString()}`);
console.log(`未实现盈亏: $${portfolio.unrealizedPnl.toLocaleString()}`);
for (const position of portfolio.positions) {
console.log(`[${position.platform}] ${position.market}`);
console.log(` 方向: ${position.side}`);
console.log(` 大小: ${position.size}`);
console.log(` 平均价格: ${position.avgPrice}`);
console.log(` 当前价格: ${position.currentPrice}`);
console.log(` 盈亏: $${position.unrealizedPnl.toFixed(2)}`);
}
统计数据
// 获取交易统计数据
const stats = await trading.getStats({ period: '30d' });
console.log(`总交易次数: ${stats.totalTrades}`);
console.log(`胜率: ${(stats.winRate * 100).toFixed(1)}%`);
console.log(`利润因子: ${stats.profitFactor.toFixed(2)}`);
console.log(`总盈亏: $${stats.totalPnl.toLocaleString()}`);
console.log(`平均交易: $${stats.avgTrade.toFixed(2)}`);
console.log(`最大盈利: $${stats.largestWin.toFixed(2)}`);
console.log(`最大亏损: $${stats.largestLoss.toFixed(2)}`);
console.log(`夏普比率: ${stats.sharpeRatio.toFixed(2)}`);
console.log(`最大回撤: ${(stats.maxDrawdown * 100).toFixed(1)}%`);
每日盈亏
// 获取每日盈亏
const dailyPnl = await trading.getDailyPnL({ days: 30 });
for (const day of dailyPnl) {
const sign = day.pnl >= 0 ? '+' : '';
console.log(`${day.date}: ${sign}$${day.pnl.toFixed(2)} (${day.trades} 交易)`);
}
导出交易
// 导出到CSV
await trading.exportTrades({
format: 'csv',
path: './trades.csv',
from: '2024-01-01',
to: '2024-12-31',
});
// 导出为JSON
const trades = await trading.exportTrades({
format: 'json',
from: '2024-01-01',
});
机器人管理
// 列出机器人
const bots = trading.bots.list();
// 注册机器人
await trading.bots.register({
name: 'my-arb-bot',
strategy: 'arbitrage',
config: {
minSpread: 1,
maxPositionSize: 500,
platforms: ['polymarket', 'kalshi'],
},
});
// 启动机器人
await trading.bots.start('my-arb-bot');
// 获取状态
const status = trading.bots.getStatus('my-arb-bot');
console.log(`运行中: ${status.isRunning}`);
console.log(`今日交易: ${status.tradesToday}`);
console.log(`今日盈亏: $${status.pnlToday}`);
// 停止机器人
await trading.bots.stop('my-arb-bot');
// 删除机器人
await trading.bots.delete('my-arb-bot');
内置策略
// 均值回归
await trading.bots.register({
name: 'mean-rev',
strategy: 'mean-reversion',
config: {
lookbackPeriod: 20,
deviationThreshold: 2,
positionSize: 100,
},
});
// 动量
await trading.bots.register({
name: 'momentum',
strategy: 'momentum',
config: {
lookbackPeriod: 14,
entryThreshold: 0.6,
exitThreshold: 0.4,
positionSize: 100,
},
});
// 套利
await trading.bots.register({
name: 'arb',
strategy: 'arbitrage',
config: {
minSpread: 1,
minLiquidity: 500,
maxPositionSize: 1000,
},
});
自定义策略
// 注册自定义策略
trading.bots.registerStrategy('my-strategy', {
init: async (ctx) => {
// 初始化状态
},
evaluate: async (ctx) => {
// 返回信号
return [
{
platform: 'polymarket',
marketId: 'market-123',
action: 'buy',
side: 'YES',
size: 100,
reason: '信号触发',
},
];
},
onTrade: (trade) => {
console.log(`交易执行: ${trade.orderId}`);
},
cleanup: async () => {
// 清理
},
});
自动记录日志
所有交易自动记录到SQLite:
-- trades表
SELECT * FROM trades
WHERE platform = 'polymarket'
ORDER BY timestamp DESC
LIMIT 10;
-- 获取胜率
SELECT
COUNT(CASE WHEN pnl > 0 THEN 1 END) * 100.0 / COUNT(*) as win_rate
FROM trades;
最佳实践
- 先从纸面交易开始 - 首先使用试运行模式
- 设置头寸限制 - 防止过度暴露
- 定期监控机器人 - 不要设置后就不管
- 每周审查性能 - 调整策略
- 定期导出数据 - 备份你的交易历史