历史记录 history

这是一个用于跟踪、同步和分析交易历史的服务,支持从Polymarket和Kalshi等平台获取详细的交易数据,并提供性能分析。

量化策略 0 次安装 0 次浏览 更新于 3/5/2026

历史记录 描述: “交易历史跟踪、同步和性能分析” 表情符号: “📊” 网关: 环境变量: 任何: - POLY_API_KEY - KALSHI_API_KEY

交易历史 - 完整API参考

从Polymarket和Kalshi获取、同步和分析交易历史,提供详细的性能指标。


聊天命令

获取 & 同步

/历史记录 获取                             # 从API获取所有交易
/历史记录 获取 poly                         # 仅限Polymarket
/历史记录 获取 --from 2024-01-01            # 从特定日期开始
/历史记录 同步                               # 同步到本地数据库

查看历史

/历史记录 列表                               # 最近交易
/历史记录 列表 --limit 50                    # 最后50笔交易
/历史记录 列表 --platform poly               # 仅限Polymarket
/历史记录 列表 --market <id>                 # 特定市场

统计

/历史记录 统计                              # 总体统计
/历史记录 统计 --period 30d                 # 最后30天
/历史记录 统计 --platform kalshi            # 平台特定

盈亏分析

/历史记录 每日盈亏                          # 每日盈亏
/历史记录 每周盈亏                         # 每周盈亏
/历史记录 每月盈亏                        # 每月盈亏
/历史记录 按市场                          # 按市场类别盈亏

导出

/历史记录 导出                             # 导出到CSV
/历史记录 导出 --format json               # 导出为JSON
/历史记录 导出 --from 2024-01-01           # 日期范围

过滤

/历史记录 过滤 --side buy                  # 仅限买入
/历史记录 过滤 --pnl positive              # 仅限盈利
/历史记录 过滤 --pnl negative              # 仅限亏损
/历史记录 过滤 --min-size 100              # 最小$100交易

TypeScript API参考

创建历史服务

import { createTradeHistoryService } from 'clodds/history';

const history = createTradeHistoryService({
  polymarket: {
    apiKey: process.env.POLY_API_KEY,
    address: process.env.POLY_ADDRESS,
  },
  kalshi: {
    apiKey: process.env.KALSHI_API_KEY,
  },

  // 本地存储
  dbPath: './trade-history.db',
});

从API获取交易

// 从交易所API获取所有交易
const trades = await history.fetchTrades({
  platforms: ['polymarket', 'kalshi'],
  from: '2024-01-01',
});

console.log(`获取了 ${trades.length} 笔交易`);

// 从特定平台获取
const polyTrades = await history.fetchTrades({
  platforms: ['polymarket'],
  limit: 100,
});

同步到数据库

// 将获取的交易同步到本地数据库
await history.syncToDatabase();

console.log('交易已同步到数据库');

获取交易

// 从本地存储获取交易
const trades = await history.getTrades({
  platform: 'polymarket',
  from: '2024-01-01',
  to: '2024-12-31',
  limit: 100,
});

for (const trade of trades) {
  console.log(`${trade.timestamp}: ${trade.side} ${trade.market}`);
  console.log(`  大小: $${trade.size}`);
  console.log(`  价格: ${trade.price}`);
  console.log(`  盈亏: $${trade.pnl?.toFixed(2) || '开放'}`);
}

统计

// 获取全面统计
const stats = await history.getStats({
  period: '30d',
  platform: 'polymarket',
});

console.log(`=== 交易统计 (30天) ===`);
console.log(`总交易数: ${stats.totalTrades}`);
console.log(`盈利交易: ${stats.winningTrades}`);
console.log(`亏损交易: ${stats.losingTrades}`);
console.log(`胜率: ${(stats.winRate * 100).toFixed(1)}%`);
console.log(`
盈亏:`);
console.log(`  总计: $${stats.totalPnl.toLocaleString()}`);
console.log(`  总利润: $${stats.grossProfit.toLocaleString()}`);
console.log(`  总亏损: $${stats.grossLoss.toLocaleString()}`);
console.log(`  利润因子: ${stats.profitFactor.toFixed(2)}`);
console.log(`
交易大小:`);
console.log(`  平均: $${stats.avgTradeSize.toFixed(2)}`);
console.log(`  最大盈利: $${stats.largestWin.toFixed(2)}`);
console.log(`  最大亏损: $${stats.largestLoss.toFixed(2)}`);
console.log(`
风险指标:`);
console.log(`  夏普比率: ${stats.sharpeRatio.toFixed(2)}`);
console.log(`  最大回撤: ${(stats.maxDrawdown * 100).toFixed(1)}%`);

每日盈亏

// 获取每日盈亏分解
const dailyPnl = await history.getDailyPnL({
  days: 30,
  platform: 'polymarket',
});

console.log('=== 每日盈亏 ===');
for (const day of dailyPnl) {
  const sign = day.pnl >= 0 ? '+' : '';
  const bar = day.pnl >= 0
    ? '█'.repeat(Math.min(Math.floor(day.pnl / 10), 20))
    : '▓'.repeat(Math.min(Math.floor(Math.abs(day.pnl) / 10), 20));

  console.log(`${day.date} | ${sign}$${day.pnl.toFixed(2).padStart(8)} | ${bar}`);
}

按市场表现

// 按市场类别获取表现分解
const byMarket = await history.getPerformanceByMarket({
  period: '30d',
});

console.log('=== 按市场类别表现 ===');
for (const [category, data] of Object.entries(byMarket)) {
  console.log(`
${category}:`);
  console.log(`  交易数: ${data.trades}`);
  console.log(`  胜率: ${(data.winRate * 100).toFixed(1)}%`);
  console.log(`  盈亏: $${data.pnl.toLocaleString()}`);
  console.log(`  平均交易: $${data.avgTrade.toFixed(2)}`);
}

导出

// 导出到CSV
await history.exportCsv({
  path: './trades.csv',
  from: '2024-01-01',
  to: '2024-12-31',
  columns: ['timestamp', 'platform', 'market', 'side', 'size', 'price', 'pnl'],
});

// 导出为JSON
const json = await history.exportJson({
  from: '2024-01-01',
});

数据库模式

CREATE TABLE trades (
  id TEXT PRIMARY KEY,
  platform TEXT NOT NULL,
  market_id TEXT NOT NULL,
  market_question TEXT,
  side TEXT NOT NULL,  -- '买入'或'卖出'
  outcome TEXT,        -- '是'或'否'
  size REAL NOT NULL,
  price REAL NOT NULL,
  fee REAL DEFAULT 0,
  pnl REAL,
  timestamp INTEGER NOT NULL,
  created_at INTEGER DEFAULT (strftime('%s', 'now'))
);

CREATE INDEX idx_trades_platform ON trades(platform);
CREATE INDEX idx_trades_timestamp ON trades(timestamp);
CREATE INDEX idx_trades_market ON trades(market_id);

最佳实践

  1. 定期同步 - 保持本地数据库最新
  2. 导出备份 - 定期导出为CSV
  3. 每周审查 - 分析性能模式
  4. 按类别跟踪 - 识别强/弱领域
  5. 监控回撤 - 设置最大回撤警报