feat: Introduce Polymarket API client, paper trading module, and essential utilities for market data and trading.

This commit is contained in:
2569718930@qq.com
2026-02-05 22:29:52 +08:00
parent 2c76c835c0
commit 81b3736ea1
9 changed files with 374 additions and 185 deletions
-94
View File
@@ -183,38 +183,6 @@ class PolymarketClient:
return None
def get_buy_prices(self, yes_token_id: str, no_token_id: str) -> Optional[Dict]:
"""
获取买入价格 (Buy Yes 和 Buy No)
Args:
yes_token_id: Yes token ID
no_token_id: No token ID
Returns:
dict: {"buy_yes": float, "buy_no": float} 或 None
"""
try:
# Buy Yes = Yes token 的最佳卖单 (asks)
yes_book = self.get_orderbook(yes_token_id)
buy_yes = None
if yes_book and isinstance(yes_book, dict) and yes_book.get("asks"):
buy_yes = float(yes_book["asks"][0].get("price", 0))
# Buy No = No token 的最佳卖单 (asks)
no_book = self.get_orderbook(no_token_id)
buy_no = None
if no_book and isinstance(no_book, dict) and no_book.get("asks"):
buy_no = float(no_book["asks"][0].get("price", 0))
if buy_yes is not None and buy_no is not None:
return {"buy_yes": buy_yes, "buy_no": buy_no}
except Exception as e:
logger.debug(f"获取买入价格失败: {e}")
return None
def get_multiple_prices(self, token_requests: List[Dict]) -> Dict[str, float]:
"""
批量获取多个 token 的价格 (使用 Polymarket 批量接口)
@@ -249,68 +217,6 @@ class PolymarketClient:
logger.debug(f"批量获取盘口价格失败: {e}")
return {}
try:
url = f"{self.base_url}/prices"
# 这里的价格接口通常返回最佳买入/卖出价
# 构造请求体:Polymarket 期望的格式
payload = []
for req in token_requests:
payload.append(
{
"token_id": req["token_id"],
"side": "buy"
if req["side"] == "ask"
else "sell", # 映射:我们要买,所以查盘口的 sell side (ask)
}
)
# 分批处理,每批 50 个,避免请求过大
all_prices = {}
for i in range(0, len(payload), 50):
batch = payload[i : i + 50]
response = self.session.post(url, json=batch, timeout=20)
if response.status_code == 200:
results = response.json()
# 结果通常是一个字典 {token_id: price}
if isinstance(results, dict):
all_prices.update(results)
return all_prices
except Exception as e:
logger.debug(f"批量获取价格失败: {e}")
return {}
def get_trades(self, market_id: str = None, limit: int = 100) -> Optional[Dict]:
"""
获取成交历史 (使用 CLOB 专业接口 + Builder Key)
"""
try:
url = f"{self.base_url}/trades"
params = {"limit": limit}
if market_id:
params["market"] = market_id
# 关键:带上你的 Builder Key
headers = {}
if self.api_key:
headers["x-api-key"] = self.api_key
response = self.session.get(
url, params=params, headers=headers, timeout=self.timeout
)
if response.status_code == 200:
return response.json()
elif response.status_code == 401:
logger.debug(
f"CLOB Trades 依然返回 401 (权限受限): {market_id[:20]}..."
)
else:
logger.debug(f"CLOB Trades 接口返回状态码: {response.status_code}")
except Exception as e:
logger.debug(f"获取成交历史失败: {e}")
return None
def get_midpoint(self, token_id: str) -> Optional[float]:
"""
Get midpoint price for a token
+156
View File
@@ -0,0 +1,156 @@
import json
import os
import time
from datetime import datetime, timedelta
from loguru import logger
class PaperTrader:
"""
模拟交易系统 (Paper Trading System)
"""
def __init__(self, storage_path="data/paper_positions.json", total_capital=1000.0):
self.storage_path = storage_path
self.initial_capital = total_capital
data = self._load_data()
self.positions = data.get("positions", {})
self.history = data.get("history", []) # 历史结项记录
self.trades = data.get("trades", []) # 原始买入/卖出记录
self.balance = data.get("balance", total_capital)
logger.info(f"模拟交易系统初始化。累计成交: {len(self.history)} 笔, 买入记录: {len(self.trades)}")
def _load_data(self):
if os.path.exists(self.storage_path):
try:
with open(self.storage_path, "r", encoding="utf-8") as f:
return json.load(f)
except:
return {"positions": {}, "history": [], "trades": [], "balance": self.initial_capital}
return {"positions": {}, "history": [], "trades": [], "balance": self.initial_capital}
def _save_data(self):
with open(self.storage_path, "w", encoding="utf-8") as f:
json.dump(
{
"positions": self.positions,
"history": self.history,
"trades": self.trades,
"balance": round(self.balance, 2),
},
f,
ensure_ascii=False,
indent=2,
)
def open_position(self, market_id: str, city: str, option: str, price: int, side: str, amount_usd: float = 5.0):
"""
开仓进入模拟仓位
"""
# 价格以美分计,转换为 0-1 比例
price_decimal = price / 100.0
# 检查余额
if self.balance < amount_usd:
logger.warning(f"余额不足,无法开仓 (余额: ${self.balance:.2f})")
return False
# 计算持仓份额
shares = amount_usd / price_decimal if price_decimal > 0 else 0
position_id = f"{market_id}_{side}"
# 如果已经有相同方向的仓位,可以选择加仓或忽略(这里简单起见,不重复开仓)
if position_id in self.positions:
return False
new_pos = {
"market_id": market_id,
"city": city,
"option": option,
"side": side,
"entry_price": price,
"shares": shares,
"cost_usd": amount_usd,
"current_price": price,
"pnl_usd": 0.0,
"pnl_pct": 0.0,
"status": "OPEN",
"opened_at": (datetime.utcnow() + timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S")
}
self.positions[position_id] = new_pos
self.balance -= amount_usd
# 记录交易流水
self.trades.append({
"type": "BUY",
"city": city,
"option": option,
"side": side,
"price": price,
"amount": amount_usd,
"time": new_pos["opened_at"]
})
self._save_data()
logger.success(f"【模拟开仓】{city} | {option} | {side} | 价格: {price}¢ | 投入: ${amount_usd}")
return True
def update_pnl(self, current_prices: dict):
updated_report = []
finished_ids = []
for pid, pos in self.positions.items():
if pos["status"] != "OPEN":
continue
m_id = pos["market_id"]
if m_id in current_prices:
curr_price = current_prices[m_id].get("price", 50)
if pos["side"] == "NO":
curr_price = 100 - curr_price
# 更新当前价值
value = pos["shares"] * (curr_price / 100.0)
pnl = value - pos["cost_usd"]
pnl_pct = (pnl / pos["cost_usd"]) * 100 if pos["cost_usd"] > 0 else 0
pos["current_price"] = curr_price
pos["pnl_usd"] = round(pnl, 2)
pos["pnl_pct"] = round(pnl_pct, 2)
# --- 自动结项检测:如果价格变为 0 或 100 (Polymarket 已结算) ---
if curr_price >= 99.5 or curr_price <= 0.5:
pos["status"] = "CLOSED"
pos["closed_at"] = (
datetime.utcnow() + timedelta(hours=8)
).strftime("%Y-%m-%d %H:%M:%S")
self.balance += value # 资金回笼
self.history.append(pos)
finished_ids.append(pid)
logger.success(
f"【模拟结项】{pos['city']} | {pos['option']} | 最终价格: {curr_price}¢ | 获利: ${pnl:+.2f}"
)
else:
updated_report.append(pos)
# 从活跃仓位中移除已结项的
for pid in finished_ids:
# 在流水中添加卖出(结项)记录
pos = self.positions[pid]
self.trades.append({
"type": "SELL",
"city": pos["city"],
"option": pos["option"],
"side": pos["side"],
"price": pos["current_price"],
"amount": round(pos["shares"] * (pos["current_price"] / 100.0), 2),
"time": pos.get("closed_at")
})
del self.positions[pid]
self._save_data()
return updated_report
+3 -3
View File
@@ -1,7 +1,7 @@
import sys
from loguru import logger
def setup_logger():
def setup_logger(level="DEBUG"):
"""
Configure loguru logger
"""
@@ -11,7 +11,7 @@ def setup_logger():
logger.add(
sys.stderr,
format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <level>{message}</level>",
level="DEBUG"
level=level
)
# 文件输出
@@ -19,7 +19,7 @@ def setup_logger():
"data/logs/trading_system.log",
rotation="10 MB",
retention="10 days",
level="DEBUG",
level=level,
encoding="utf-8",
compression="zip"
)
+2 -1
View File
@@ -132,7 +132,8 @@ class TelegramNotifier:
items_text = ""
for a in alerts:
type_icon = "" if a["type"] == "price" else "🐋"
items_text += f"{type_icon} <b>{a['market']}</b>: {a['msg']}\n"
buy_tag = " [🛒 模拟仓已买入]" if a.get("bought") else ""
items_text += f"{type_icon} <b>{a['market']}</b>: {a['msg']}{buy_tag}\n"
text = (
f"🔔 <b>城市监控报告 #{self._escape_html(city)}</b>\n\n"