交易历史追踪分析Skill history

这个技能是一个用于量化交易的工具,专门用于获取、同步和分析来自Polymarket和Kalshi平台的交易历史数据。它提供全面的API接口、本地数据库存储、以及详细的性能统计分析,包括每日P&L、市场类别分析、统计指标等,帮助用户评估交易策略效果。关键词:交易历史、量化分析、API集成、性能评估、数据同步、回测支持、统计分析、量化金融。

回测系统 0 次安装 0 次浏览 更新于 3/9/2026

name: 历史 description: “交易历史追踪、同步和性能分析” emoji: “📊” gates: envs: anyOf: - POLY_API_KEY - KALSHI_API_KEY

交易历史 - 完整API参考

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


聊天命令

获取与同步

/history fetch                              # 从API获取所有交易
/history fetch poly                         # 仅获取Polymarket
/history fetch --from 2024-01-01            # 从特定日期开始
/history sync                               # 同步到本地数据库

查看历史

/history list                               # 最近交易
/history list --limit 50                    # 最后50笔交易
/history list --platform poly               # 仅Polymarket
/history list --market <id>                 # 特定市场

统计

/history stats                              # 整体统计
/history stats --period 30d                 # 最近30天
/history stats --platform kalshi            # 平台特定

P&L分析

/history daily-pnl                          # 每日P&L
/history weekly-pnl                         # 每周P&L
/history monthly-pnl                        # 每月P&L
/history by-market                          # 按市场类别P&L

导出

/history export                             # 导出到CSV
/history export --format json               # 导出为JSON
/history export --from 2024-01-01           # 日期范围

过滤

/history filter --side buy                  # 仅买入
/history filter --pnl positive              # 仅盈利交易
/history filter --pnl negative              # 仅亏损交易
/history filter --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(`  P&L: $${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(`
P&L:`);
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)}%`);

每日P&L

// 获取每日P&L细分
const dailyPnl = await history.getDailyPnL({
  days: 30,
  platform: 'polymarket',
});

console.log('=== 每日P&L ===');
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(`  P&L: $${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,  -- 'buy' 或 'sell'
  outcome TEXT,        -- 'YES' 或 'NO'
  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. 监控回撤 - 设置最大回撤警报