用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/alsk1992/CloddsBot --skill portfolio-sync命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
正在显示 SKILL.md
基于 SOC 职业分类
| name | portfolio-sync |
| description | Sync portfolio positions from Polymarket, Kalshi, and Manifold |
| emoji | 📁 |
Real methods to fetch and sync positions from each prediction market platform.
Polymarket positions are held as ERC-1155 tokens on Polygon. Query on-chain balances.
import os
import requests
WALLET = os.getenv("POLY_FUNDER_ADDRESS")
CTF_CONTRACT = "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045" # Conditional Token Framework
def get_polymarket_positions(token_ids: list[str]) -> dict:
"""
Get balances for specific token IDs
Args:
token_ids: List of token IDs to check (from market data)
Returns:
Dict of token_id -> balance in shares
"""
positions = {}
for token_id in token_ids:
token_int = int(token_id)
# ERC-1155 balanceOf call
data = f"0x00fdd58e000000000000000000000000{WALLET[2:].lower()}{token_int:064x}"
r = requests.post("https://polygon-rpc.com/", json={
"jsonrpc": "2.0",
"method": "eth_call",
"params": [{"to": CTF_CONTRACT, "data": data}, "latest"],
"id": 1
})
result = r.json().get("result", "0x0")
balance = int(result, 16) / 1e6 # Raw to shares
if balance > 0:
positions[token_id] = balance
return positions
# Example: Check positions for BTC 15-min market
btc_tokens = [
"21742633143463906290569050155826241533067272736897614950488156847949938836455", # YES
"48331043336612883890938759509493159234755048973500640148014422747788308965745" # NO
]
positions = get_polymarket_positions(btc_tokens)
for token_id, balance in positions.items():
print(f"Token {token_id[:20]}...: {balance} shares")
def get_all_polymarket_positions(wallet: str):
"""Get all positions for a wallet via Gamma API"""
url = f"https://gamma-api.polymarket.com/positions?user={wallet.lower()}"
r = requests.get(url)
if r.status_code != 200:
return []
positions = r.json()
result = []
for p in positions:
result.append({
"market_id": p.get("conditionId"),
"market_question": p.get("title", "Unknown"),
"token_id": p.get("tokenId"),
"outcome": p.get("outcome"),
"size": float(p.get("size", 0)),
"avg_price": float(p.get("avgPrice", 0)),
"current_price": float(p.get("currentPrice", 0)),
"pnl": float(p.get("pnl", 0)),
"value": float(p.get("value", 0))
})
return result
positions = get_all_polymarket_positions(WALLET)
for p in positions:
print(f"{p['market_question'][:]}")
()
()
def get_usdc_balance(wallet: str) -> float:
"""Get USDC balance on Polygon"""
USDC = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174" # USDC on Polygon
# ERC-20 balanceOf
data = f"0x70a08231000000000000000000000000{wallet[2:].lower()}"
r = requests.post("https://polygon-rpc.com/", json={
"jsonrpc": "2.0",
"method": "eth_call",
"params": [{"to": USDC, "data": data}, "latest"],
"id": 1
})
result = r.json().get("result", "0x0")
balance = int(result, 16) / 1e6 # USDC has 6 decimals
return balance
usdc = get_usdc_balance(WALLET)
print(f"USDC Balance: ${usdc:.2f}")
import requests
import time
BASE_URL = "https://trading-api.kalshi.com/trade-api/v2"
class KalshiSync:
def __init__(self, email: str, password: str):
self.email = email
self.password = password
self.token = None
self.token_expiry = 0
def _auth(self):
if time.time() > self.token_expiry - 60:
r = requests.post(f"{BASE_URL}/login", json={
"email": self.email,
"password": self.password
})
r.raise_for_status()
self.token = r.json()["token"]
self.token_expiry = time.time() + 29 * 60
def _headers(self):
self._auth()
return {"Authorization": f"Bearer {self.token}"}
def get_positions(self):
"""Get all Kalshi positions"""
r = requests.get(f"/portfolio/positions", headers=._headers())
r.raise_for_status()
positions = []
p r.json().get(, []):
market = requests.get(
,
headers=._headers()
).json().get(, {})
positions.append({
: p[],
: market.get(, p[]),
: p.get(, ) > ,
: (p.get(, )),
: p.get(, ) / ,
: market.get(, ) / ,
: (p.get(, )) * market.get(, ) / ,
: p.get(, ) /
})
positions
():
r = requests.get(, headers=._headers())
r.raise_for_status()
data = r.json()
{
: data.get(, ) / ,
: data.get(, ) /
}
sync = KalshiSync(os.getenv(), os.getenv())
positions = sync.get_positions()
p positions:
()
()
balance = sync.get_balance()
()
()
import requests
API_URL = "https://api.manifold.markets/v0"
API_KEY = os.getenv("MANIFOLD_API_KEY")
def get_manifold_positions():
"""Get all Manifold positions"""
headers = {"Authorization": f"Key {API_KEY}"}
# Get user profile
r = requests.get(f"{API_URL}/me", headers=headers)
r.raise_for_status()
user = r.json()
user_id = user["id"]
balance = user.get("balance", 0)
# Get all bets
r = requests.get(f"{API_URL}/bets", headers=headers, params={"userId": user_id, "limit": 1000})
bets = r.json()
# Aggregate positions by market
markets = {}
for bet in bets:
if bet.get("isSold") or bet.get("isCancelled"):
continue
mid = bet["contractId"]
if mid not in markets:
markets[mid] = {
"yes_shares": 0,
"no_shares": 0,
"invested": 0,
"question": bet.get("contractQuestion", "Unknown")
}
if bet["outcome"] == "YES":
markets[mid][] += bet.get(, )
:
markets[mid][] += bet.get(, )
markets[mid][] += bet[]
positions = []
mid, data markets.items():
data[] == data[] == :
r = requests.get()
r.status_code == :
market = r.json()
prob = market.get(, )
yes_value = data[] * prob
no_value = data[] * ( - prob)
total_value = yes_value + no_value
pnl = total_value - data[]
positions.append({
: mid,
: data[],
: data[],
: data[],
: data[],
: total_value,
: prob,
: pnl,
: market.get(, )
})
positions, balance
positions, balance = get_manifold_positions()
()
p positions:
()
()
()
#!/usr/bin/env python3
"""
Sync portfolio from all prediction markets
"""
import os
from dataclasses import dataclass
from typing import List
@dataclass
class Position:
platform: str
market_id: str
market_question: str
side: str
size: float
avg_price: float
current_price: float
value: float
pnl: float
pnl_pct: float
def sync_all_portfolios() -> List[Position]:
"""Sync positions from all platforms"""
all_positions = []
# Polymarket
if os.getenv("POLY_FUNDER_ADDRESS"):
poly_positions = get_all_polymarket_positions(os.getenv("POLY_FUNDER_ADDRESS"))
for p in poly_positions:
avg = p["avg_price"] or 0.01
pnl_pct = ((p["current_price"] - avg) / avg * 100) if avg > 0 else 0
all_positions.append(Position(
platform="polymarket",
market_id=p["market_id"],
market_question=p["market_question"],
side=p["outcome"],
size=p["size"],
avg_price=avg,
current_price=p[],
value=p[],
pnl=p[],
pnl_pct=pnl_pct
))
os.getenv():
kalshi = KalshiSync(os.getenv(), os.getenv())
kalshi_positions = kalshi.get_positions()
p kalshi_positions:
avg = p[]
pnl_pct = ((p[] - avg) / avg * ) avg >
all_positions.append(Position(
platform=,
market_id=p[],
market_question=p[],
side=p[],
size=p[],
avg_price=avg,
current_price=p[],
value=p[],
pnl=p[],
pnl_pct=pnl_pct
))
os.getenv():
mani_positions, _ = get_manifold_positions()
p mani_positions:
invested = p[]
pnl_pct = (p[] / invested * ) invested >
p[] > :
all_positions.append(Position(
platform=,
market_id=p[],
market_question=p[],
side=,
size=p[],
avg_price=,
current_price=p[],
value=p[] * p[],
pnl=p[] / ,
pnl_pct=pnl_pct
))
p[] > :
all_positions.append(Position(
platform=,
market_id=p[],
market_question=p[],
side=,
size=p[],
avg_price=,
current_price= - p[],
value=p[] * ( - p[]),
pnl=p[] / ,
pnl_pct=pnl_pct
))
all_positions
positions = sync_all_portfolios()
total_value = (p.value p positions)
total_pnl = (p.pnl p positions)
()
()
()
()
()
()
platform [, , ]:
plat_positions = [p p positions p.platform == platform]
plat_positions:
plat_value = (p.value p plat_positions)
plat_pnl = (p.pnl p plat_positions)
()
p plat_positions:
()
()
()
#!/usr/bin/env python3
"""
Run every hour to sync positions to database
"""
import sqlite3
from datetime import datetime
def sync_to_db():
"""Sync all positions to SQLite"""
conn = sqlite3.connect("~/.clodds/clodds.db")
positions = sync_all_portfolios()
for p in positions:
conn.execute("""
INSERT OR REPLACE INTO positions
(platform, market_id, market_question, side, size, avg_price, current_price, value, pnl, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (
p.platform, p.market_id, p.market_question, p.side,
p.size, p.avg_price, p.current_price, p.value, p.pnl,
datetime.now().isoformat()
))
conn.commit()
conn.close()
print(f"Synced {len(positions)} positions at {datetime.now()}")
if __name__ == "__main__":
sync_to_db()
Add to crontab:
# Sync every hour
0 * * * * cd /path/to/clodds && python3 -c "from skills.portfolio_sync import sync_to_db; sync_to_db()"