trading-system

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Trading System - Complete API Reference

交易系统 - 完整API参考

Unified trading system with auto-logging to SQLite, bot management, and performance analytics.

具备自动日志(存储至SQLite)、交易机器人管理和绩效分析功能的统一交易系统。

Chat Commands

聊天指令

Portfolio

投资组合

/trading portfolio                          # View all positions
/trading portfolio poly                     # Positions on Polymarket
/trading portfolio --value                  # Include current values
/trading portfolio                          # 查看所有持仓
/trading portfolio poly                     # Polymarket平台持仓
/trading portfolio --value                  # 包含当前市值

Performance

绩效统计

/trading stats                              # Overall statistics
/trading stats --period 30d                 # Last 30 days
/trading daily-pnl                          # Daily P&L breakdown
/trading weekly-pnl                         # Weekly P&L
/trading monthly-pnl                        # Monthly P&L
/trading stats                              # 整体统计数据
/trading stats --period 30d                 # 最近30天数据
/trading daily-pnl                          # 每日盈亏明细
/trading weekly-pnl                         # 每周盈亏
/trading monthly-pnl                        # 每月盈亏

Trade History

交易历史

/trading history                            # Recent trades
/trading history --limit 50                 # Last 50 trades
/trading history --platform poly            # Polymarket only
/trading export                             # Export to CSV
/trading export --format json               # Export as JSON
/trading history                            # 近期交易记录
/trading history --limit 50                 # 最近50笔交易
/trading history --platform poly            # 仅Polymarket平台交易
/trading export                             # 导出为CSV格式
/trading export --format json               # 导出为JSON格式

Bot Management

机器人管理

/bot list                                   # List all bots
/bot register <name> <strategy>             # Register new bot
/bot start <name>                           # Start bot
/bot stop <name>                            # Stop bot
/bot status <name>                          # Bot status
/bot delete <name>                          # Delete bot
/bot list                                   # 列出所有机器人
/bot register <name> <strategy>             # 注册新机器人
/bot start <name>                           # 启动机器人
/bot stop <name>                            # 停止机器人
/bot status <name>                          # 查看机器人状态
/bot delete <name>                          # 删除机器人

Bot Strategies

机器人策略

/bot strategies                             # List available strategies
/bot create mean-reversion --config {...}   # Create with config
/bot create momentum --lookback 14          # Momentum strategy
/bot create arbitrage --min-spread 1        # Arbitrage strategy

/bot strategies                             # 列出可用策略
/bot create mean-reversion --config {...}   # 使用配置创建均值回归策略
/bot create momentum --lookback 14          # 创建动量策略(回溯周期14)
/bot create arbitrage --min-spread 1        # 创建套利策略(最小价差1)

TypeScript API Reference

TypeScript API参考

Create Trading System

创建交易系统

typescript
import { createTradingSystem } from 'clodds/trading';

const trading = createTradingSystem({
  // Execution service
  execution: executionService,

  // Auto-logging
  autoLog: true,
  logPath: './trades.db',

  // Bot configuration
  bots: {
    enabled: true,
    maxConcurrent: 5,
  },
});
typescript
import { createTradingSystem } from 'clodds/trading';

const trading = createTradingSystem({
  // 执行服务
  execution: executionService,

  // 自动日志
  autoLog: true,
  logPath: './trades.db',

  // 机器人配置
  bots: {
    "enabled": true,
    "maxConcurrent": 5,
  },
});

Portfolio

投资组合

typescript
// Get portfolio
const portfolio = await trading.getPortfolio();

console.log(`Total value: $${portfolio.totalValue.toLocaleString()}`);
console.log(`Unrealized P&L: $${portfolio.unrealizedPnl.toLocaleString()}`);

for (const position of portfolio.positions) {
  console.log(`[${position.platform}] ${position.market}`);
  console.log(`  Side: ${position.side}`);
  console.log(`  Size: ${position.size}`);
  console.log(`  Avg price: ${position.avgPrice}`);
  console.log(`  Current: ${position.currentPrice}`);
  console.log(`  P&L: $${position.unrealizedPnl.toFixed(2)}`);
}
typescript
// 获取投资组合
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)}`);
}

Statistics

统计数据

typescript
// Get trading statistics
const stats = await trading.getStats({ period: '30d' });

console.log(`Total trades: ${stats.totalTrades}`);
console.log(`Win rate: ${(stats.winRate * 100).toFixed(1)}%`);
console.log(`Profit factor: ${stats.profitFactor.toFixed(2)}`);
console.log(`Total P&L: $${stats.totalPnl.toLocaleString()}`);
console.log(`Avg trade: $${stats.avgTrade.toFixed(2)}`);
console.log(`Largest win: $${stats.largestWin.toFixed(2)}`);
console.log(`Largest loss: $${stats.largestLoss.toFixed(2)}`);
console.log(`Sharpe ratio: ${stats.sharpeRatio.toFixed(2)}`);
console.log(`Max drawdown: ${(stats.maxDrawdown * 100).toFixed(1)}%`);
typescript
// 获取交易统计数据
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)}%`);

Daily P&L

每日盈亏

typescript
// Get daily P&L
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} trades)`);
}
typescript
// 获取每日盈亏
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} 笔交易)`);
}

Export Trades

导出交易记录

typescript
// Export to CSV
await trading.exportTrades({
  format: 'csv',
  path: './trades.csv',
  from: '2024-01-01',
  to: '2024-12-31',
});

// Export to JSON
const trades = await trading.exportTrades({
  format: 'json',
  from: '2024-01-01',
});
typescript
// 导出为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',
});

Bot Management

机器人管理

typescript
// List bots
const bots = trading.bots.list();

// Register a bot
await trading.bots.register({
  name: 'my-arb-bot',
  strategy: 'arbitrage',
  config: {
    minSpread: 1,
    maxPositionSize: 500,
    platforms: ['polymarket', 'kalshi'],
  },
});

// Start bot
await trading.bots.start('my-arb-bot');

// Get status
const status = trading.bots.getStatus('my-arb-bot');
console.log(`Running: ${status.isRunning}`);
console.log(`Trades today: ${status.tradesToday}`);
console.log(`P&L today: $${status.pnlToday}`);

// Stop bot
await trading.bots.stop('my-arb-bot');

// Delete bot
await trading.bots.delete('my-arb-bot');
typescript
// 列出机器人
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');

Built-in Strategies

内置策略

typescript
// Mean Reversion
await trading.bots.register({
  name: 'mean-rev',
  strategy: 'mean-reversion',
  config: {
    lookbackPeriod: 20,
    deviationThreshold: 2,
    positionSize: 100,
  },
});

// Momentum
await trading.bots.register({
  name: 'momentum',
  strategy: 'momentum',
  config: {
    lookbackPeriod: 14,
    entryThreshold: 0.6,
    exitThreshold: 0.4,
    positionSize: 100,
  },
});

// Arbitrage
await trading.bots.register({
  name: 'arb',
  strategy: 'arbitrage',
  config: {
    minSpread: 1,
    minLiquidity: 500,
    maxPositionSize: 1000,
  },
});
typescript
// 均值回归策略
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,
  },
});

Custom Strategy

自定义策略

typescript
// Register custom strategy
trading.bots.registerStrategy('my-strategy', {
  init: async (ctx) => {
    // Initialize state
  },

  evaluate: async (ctx) => {
    // Return signals
    return [
      {
        platform: 'polymarket',
        marketId: 'market-123',
        action: 'buy',
        side: 'YES',
        size: 100,
        reason: 'Signal triggered',
      },
    ];
  },

  onTrade: (trade) => {
    console.log(`Trade executed: ${trade.orderId}`);
  },

  cleanup: async () => {
    // Cleanup
  },
});

typescript
// 注册自定义策略
trading.bots.registerStrategy('my-strategy', {
  "init": async (ctx) => {
    // 初始化状态
  },

  "evaluate": async (ctx) => {
    // 返回交易信号
    return [
      {
        "platform": 'polymarket',
        "marketId": 'market-123',
        "action": 'buy',
        "side": 'YES',
        "size": 100,
        "reason": 'Signal triggered',
      },
    ];
  },

  "onTrade": (trade) => {
    console.log(`交易已执行: ${trade.orderId}`);
  },

  "cleanup": async () => {
    // 清理资源
  },
});

Auto-Logging

自动日志

All trades are automatically logged to SQLite:
sql
-- trades table
SELECT * FROM trades
WHERE platform = 'polymarket'
ORDER BY timestamp DESC
LIMIT 10;

-- Get win rate
SELECT
  COUNT(CASE WHEN pnl > 0 THEN 1 END) * 100.0 / COUNT(*) as win_rate
FROM trades;

所有交易都会自动记录至SQLite数据库:
sql
-- 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;

Best Practices

最佳实践

  1. Start with paper trading - Use dry-run mode first
  2. Set position limits - Prevent overexposure
  3. Monitor bots regularly - Don't set and forget
  4. Review performance weekly - Adjust strategies
  5. Export data regularly - Backup your trade history
  1. 先进行模拟交易 - 首先使用试运行模式
  2. 设置持仓限额 - 避免过度暴露风险
  3. 定期监控机器人 - 不要设置后就不管
  4. 每周复盘绩效 - 调整策略
  5. 定期导出数据 - 备份交易历史