kalshi-trading

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Kalshi Trading

Kalshi交易

Trade on Kalshi, a CFTC-regulated prediction market exchange. This skill enables you to query markets, analyze probabilities, manage positions, and execute trades.
Kalshi(一家受CFTC监管的预测市场交易所)进行交易。该技能可让你查询市场、分析概率、管理持仓并执行交易。

Types

类型

typescript
interface Market {
  ticker: string;
  title: string;
  status: string;
  yes_bid?: number;
  yes_ask?: number;
  volume?: number;
  close_time?: string;
}

interface Orderbook {
  yes: [number, number][]; // [price_cents, quantity]
  no: [number, number][];
}

interface Balance {
  balance: number; // cents
  payout: number;  // pending settlement
}

interface Position {
  ticker: string;
  position: number; // positive = YES, negative = NO
  market_exposure: number;
}

interface Order {
  order_id: string;
  ticker: string;
  side: "yes" | "no";
  action: "buy" | "sell";
  count: number;
  status: string;
}
typescript
interface Market {
  ticker: string;
  title: string;
  status: string;
  yes_bid?: number;
  yes_ask?: number;
  volume?: number;
  close_time?: string;
}

interface Orderbook {
  yes: [number, number][]; // [price_cents, quantity]
  no: [number, number][];
}

interface Balance {
  balance: number; // cents
  payout: number;  // pending settlement
}

interface Position {
  ticker: string;
  position: number; // positive = YES, negative = NO
  market_exposure: number;
}

interface Order {
  order_id: string;
  ticker: string;
  side: "yes" | "no";
  action: "buy" | "sell";
  count: number;
  status: string;
}

Quick Start

快速开始

typescript
import * as crypto from "crypto";

const API_BASE = "https://api.elections.kalshi.com/trade-api/v2";

// See AUTHENTICATION.md for full setup
function getAuthHeaders(
  apiKey: string,
  privateKeyPem: string,
  method: string,
  path: string
): Record<string, string> {
  const timestamp = Date.now().toString();
  const message = `${timestamp}${method}${path}`;

  const sign = crypto.createSign("RSA-SHA256");
  sign.update(message);
  const signature = sign.sign(privateKeyPem, "base64");

  return {
    "KALSHI-ACCESS-KEY": apiKey,
    "KALSHI-ACCESS-SIGNATURE": signature,
    "KALSHI-ACCESS-TIMESTAMP": timestamp,
    "Content-Type": "application/json",
  };
}
typescript
import * as crypto from "crypto";

const API_BASE = "https://api.elections.kalshi.com/trade-api/v2";

// See AUTHENTICATION.md for full setup
function getAuthHeaders(
  apiKey: string,
  privateKeyPem: string,
  method: string,
  path: string
): Record<string, string> {
  const timestamp = Date.now().toString();
  const message = `${timestamp}${method}${path}`;

  const sign = crypto.createSign("RSA-SHA256");
  sign.update(message);
  const signature = sign.sign(privateKeyPem, "base64");

  return {
    "KALSHI-ACCESS-KEY": apiKey,
    "KALSHI-ACCESS-SIGNATURE": signature,
    "KALSHI-ACCESS-TIMESTAMP": timestamp,
    "Content-Type": "application/json",
  };
}

Common Operations

常见操作

Search Markets

搜索市场

typescript
async function searchMarkets(query: string, limit = 10): Promise<Market[]> {
  const url = new URL(`${API_BASE}/markets`);
  url.searchParams.set("status", "open");
  url.searchParams.set("limit", String(limit));

  const response = await fetch(url.toString());
  const data = await response.json();

  // Filter by query in title
  return data.markets.filter((m: Market) =>
    m.title.toLowerCase().includes(query.toLowerCase())
  );
}
typescript
async function searchMarkets(query: string, limit = 10): Promise<Market[]> {
  const url = new URL(`${API_BASE}/markets`);
  url.searchParams.set("status", "open");
  url.searchParams.set("limit", String(limit));

  const response = await fetch(url.toString());
  const data = await response.json();

  // Filter by query in title
  return data.markets.filter((m: Market) =>
    m.title.toLowerCase().includes(query.toLowerCase())
  );
}

Get Market Details

获取市场详情

typescript
async function getMarket(ticker: string): Promise<Market> {
  const response = await fetch(`${API_BASE}/markets/${ticker}`);
  const data = await response.json();
  return data.market;
}
typescript
async function getMarket(ticker: string): Promise<Market> {
  const response = await fetch(`${API_BASE}/markets/${ticker}`);
  const data = await response.json();
  return data.market;
}

Get Orderbook

获取订单簿

typescript
async function getOrderbook(ticker: string): Promise<Orderbook> {
  const response = await fetch(`${API_BASE}/markets/${ticker}/orderbook`);
  const data = await response.json();
  return data.orderbook;
}
typescript
async function getOrderbook(ticker: string): Promise<Orderbook> {
  const response = await fetch(`${API_BASE}/markets/${ticker}/orderbook`);
  const data = await response.json();
  return data.orderbook;
}

Check Balance (Authenticated)

查看账户余额(需认证)

typescript
async function getBalance(
  apiKey: string,
  privateKeyPem: string
): Promise<Balance> {
  const path = "/portfolio/balance";
  const headers = getAuthHeaders(apiKey, privateKeyPem, "GET", path);

  const response = await fetch(`${API_BASE}${path}`, { headers });
  return response.json();
}
typescript
async function getBalance(
  apiKey: string,
  privateKeyPem: string
): Promise<Balance> {
  const path = "/portfolio/balance";
  const headers = getAuthHeaders(apiKey, privateKeyPem, "GET", path);

  const response = await fetch(`${API_BASE}${path}`, { headers });
  return response.json();
}

Get Positions (Authenticated)

获取持仓(需认证)

typescript
async function getPositions(
  apiKey: string,
  privateKeyPem: string
): Promise<Position[]> {
  const path = "/portfolio/positions";
  const headers = getAuthHeaders(apiKey, privateKeyPem, "GET", path);

  const response = await fetch(`${API_BASE}${path}`, { headers });
  const data = await response.json();
  return data.market_positions;
}
typescript
async function getPositions(
  apiKey: string,
  privateKeyPem: string
): Promise<Position[]> {
  const path = "/portfolio/positions";
  const headers = getAuthHeaders(apiKey, privateKeyPem, "GET", path);

  const response = await fetch(`${API_BASE}${path}`, { headers });
  const data = await response.json();
  return data.market_positions;
}

Place Order (Authenticated)

下单(需认证)

typescript
async function placeOrder(
  apiKey: string,
  privateKeyPem: string,
  ticker: string,
  side: "yes" | "no",
  action: "buy" | "sell",
  count: number,
  price: number // In cents (1-99)
): Promise<Order> {
  const path = "/portfolio/orders";
  const headers = getAuthHeaders(apiKey, privateKeyPem, "POST", path);

  const body = {
    ticker,
    side,
    action,
    count,
    type: "limit",
    ...(side === "yes" ? { yes_price: price } : { no_price: price }),
  };

  const response = await fetch(`${API_BASE}${path}`, {
    method: "POST",
    headers,
    body: JSON.stringify(body),
  });
  const data = await response.json();
  return data.order;
}
typescript
async function placeOrder(
  apiKey: string,
  privateKeyPem: string,
  ticker: string,
  side: "yes" | "no",
  action: "buy" | "sell",
  count: number,
  price: number // In cents (1-99)
): Promise<Order> {
  const path = "/portfolio/orders";
  const headers = getAuthHeaders(apiKey, privateKeyPem, "POST", path);

  const body = {
    ticker,
    side,
    action,
    count,
    type: "limit",
    ...(side === "yes" ? { yes_price: price } : { no_price: price }),
  };

  const response = await fetch(`${API_BASE}${path}`, {
    method: "POST",
    headers,
    body: JSON.stringify(body),
  });
  const data = await response.json();
  return data.order;
}

Key Concepts

核心概念

  • Markets: Event contracts with Yes/No outcomes (e.g., "Will X happen by Y date?")
  • Prices: Quoted in cents (1-99), representing probability percentage
  • Positions: Your holdings in Yes or No contracts
  • Settlement: Markets resolve to $1.00 (Yes wins) or $0.00 (No wins)
  • 市场:具有Yes/No结果的事件合约(例如:“X是否会在Y日期前发生?”)
  • 价格:以美分报价(1-99),代表概率百分比
  • 持仓:你持有的Yes或No合约数量
  • 结算:市场最终会结算为1.00美元(Yes获胜)或0.00美元(No获胜)

Additional Resources

额外资源

  • AUTHENTICATION.md - Detailed API key setup
  • API_REFERENCE.md - Full endpoint documentation
  • scripts/kalshi-client.ts - Ready-to-use TypeScript client
  • AUTHENTICATION.md - 详细的API密钥设置指南
  • API_REFERENCE.md - 完整的端点文档
  • scripts/kalshi-client.ts - 即用型TypeScript客户端

Tips

提示

  1. Start with market research: Use
    searchMarkets()
    to explore opportunities
  2. Check liquidity: Review orderbook depth before placing large orders
  3. Use limit orders: Avoid market orders to control execution price
  4. Monitor positions: Regularly check your positions and P&L
  1. 从市场调研开始:使用
    searchMarkets()
    探索机会
  2. 检查流动性:下单前查看订单簿深度
  3. 使用限价订单:避免市价订单,以控制执行价格
  4. 监控持仓:定期检查你的持仓和盈亏情况